第8章(2)——项目二:Claude与显示思考——引用资料
第8章2——项目二Claude与显示思考——引用资料8.8 metadata显示思考的工具和资料8.8.1 metadata显示思考——使用工具8.8.2 项目二Claude与显示思考——引用资料8.8 metadata显示思考的工具和资料gr.Chatbot组件支持参数metadata因此可以原生支持显示中间思考过程呈现使用工具和资料引用情况这非常适合为LLM Agent和CoTChain-of-Thought, 思维链演示创建UI。本节先通过一个简单示例展示如何呈现使用工具然后通过一个项目展示如何使用gr.Chatbot构建显示思考中的资料引用。8.8.1 metadata显示思考——使用工具仔细的读者会发现gr.ChatMessage类似于openai风格的消息格式它有一个指向聊天消息内容的“content”键但也包括一个“metadata”键其值是字典gr.MetadataDict。如果字典包含“title”键标题显示在思考过程之上且生成的消息将呈现为中间思考过程。其用法如代码8-13所示代码8-13importgradioasgrdefgenerate_response(message,history):history.append(gr.ChatMessage(roleuser,contentinput message: message))history.append(gr.ChatMessage(roleassistant,contentThe weather API says it is 20 degrees Celcius in San Francisco.,metadata{title: Used tool Weather API,id:222,parent_id:111}))return,historywithgr.Blocks()asdemo:chatbotgr.Chatbot(value[{role:user,content:What is the weather in San Francisco?},{role:assistant,content:I need to use the weather API tool,metadata:{title: Thinking,id:111}}])msggr.Textbox()msg.submit(generate_response,[msg,chatbot],[msg,chatbot])demo.launch()示例模拟代理使用天气API工具的思考过程。用户输入消息后系统会生成两条记录一条是用户的输入另一条是助手调用工具后的回复。chatbot的初始值可理解为代理思考后的执行步骤再次提交时开始调用天气API工具生成新回复新回复消息根据parent_id附加到父类metadata消息中并通过gr.Chatbot组件展示所有对话历史运行界面如图8-10所示图8-10本例可以看出在Gradio的底层gr.Blocks中能够使用gr.Chatbot从头开始构建聊天机器人的用户界面从而能够完全控制界面效果。注意history定义时可添加多条消息但append追加时只能一条一条的添加否则报错“TypeError: list.append() takes exactly one argument (2 given)”。8.8.2 项目二Claude与显示思考——引用资料Gradio的聊天机器人可以显示来自大语言模型响应的引用Citation非常适合展示来源文档和参考资料。下面展示如何使用Anthropic Claude API构建支持引用功能的聊天机器人它既能显示响应也能显示引用资料。首先设置ANTHROPIC_API_KEY并导入库如代码8-14所示代码8-14importgradioasgrimportanthropicimportbase64fromtypingimportList,Dict,Any DEFAULT_DOCThe grass is pink and soil is green. The sky is red while the sun is blue.然后定义读取文件函数、存储用户输入消息函数、格式化历史消息函数、更新变量函数和机器人响应处理函数。这里只展示核心的机器人响应处理函数bot_response其他函数请参考线上资源。代码如下所示defbot_response(history:list,enable_citations:bool,doc_type:str,text_content:str,pdf_file:str,api_key:str)-List[Dict[str,Any]]:try:ifnotapi_key:history.append({role:assistant,content:Please provide your Anthropic API key to continue.})returnhistory clientAnthropic(api_keyapi_key)messagesformat_message_history(history,enable_citations,doc_type,text_content,pdf_fileifpdf_fileelseNone)responseclient.messages.create(modelclaude-sonnet-4-6,max_tokens1024,messagesmessages)main_responsecitations[]# Process each content block, append to main response and citationsforblockinresponse.content:ifblock.typetext:main_responseblock.textifenable_citationsandhasattr(block,citations)andblock.citations:forcitationinblock.citations:ifcitation.cited_textnotincitations:citations.append(citation.cited_text)history.append({role:assistant,content:main_response})# Add citations if any were found and citations are enabledifenable_citationsandcitations:history.append({role:assistant,content:\n.join([f•{cite}forciteincitations]),metadata:{title: Citations}})returnhistory最后创建Gradio界面withgr.Blocks(fill_heightTrue)asdemo:gr.Markdown(# Chat with Anthropic Claudes Citations)withgr.Row(scale1):withgr.Column(scale4):chatbotgr.Chatbot(show_labelFalse,scale1)msggr.Textbox(placeholderEnter your message here...,show_labelFalse,containerFalse)withgr.Column(scale1):api_keygr.Textbox(typepassword,labelAnthropic API Key,placeholderEnter your API key,interactiveTrue,infoYour API key will not be stored)enable_citationsgr.Checkbox(labelEnable Citations,valueTrue,infoToggle citation functionality)doc_type_radiogr.Radio(choices[plain_text,pdf,combined],valueplain_text,labelDocument Type,infoChoose the type of document(s) to reference)text_inputgr.Textbox(labelDocument Content,placeholderfEnter your document text here.\nDefault text will be picked if citations are enabled and you dont provide the documents. Default document is --{DEFAULT_DOC},lines10,infoEnter the text you want to reference)pdf_inputgr.File(labelUpload PDF,file_countmultiple,file_types[.pdf],typefilepath,visibleFalse)cleargr.ClearButton([msg,chatbot,text_input,pdf_input])# Update input visibility based on settingsenable_citations.change(update_document_inputs,inputs[enable_citations,doc_type_radio],outputs[doc_type_radio,text_input,pdf_input])doc_type_radio.change(update_document_inputs,inputs[enable_citations,doc_type_radio],outputs[doc_type_radio,text_input,pdf_input])# Handle message submissionmsg.submit(user_message,[msg,chatbot,enable_citations,doc_type_radio,text_input,pdf_input,api_key],[msg,chatbot],queueFalse).then(bot_response,[chatbot,enable_citations,doc_type_radio,text_input,pdf_input,api_key],chatbot)if__name____main__:demo.launch(themeocean,debugTrue)本例实现了一个基于Anthropic Claude API的交互式聊天机器人界面并可选择性地提供文本、多个PDF文档或二者混合作为上下文同时支持模型生成内容的引用溯源。其核心功能主要有函数bot_response及构建GUI下面分别讲述。首先看一下核心函数bot_response。它实现了一个基于Anthropic Claude模型的交互式聊天机器人发送消息并提取回复内容和引用信息(1)API认证与响应调用format_message_history函数将历史消息、引用文本或PDF文档转化为Claude模型能接受的格式通过用户提供的API密钥初始化Anthropic客户端然后调用指定模型Claude Sonnet 4生成响应。(2)解析响应内容分离主回复和引用信息当enable_citations选项开启并且回复中有属性’citations’时将首次出现的引用信息添加到引用列表。(3)返回聊天历史将主回复和可能的引用列表追加到聊天历史通过键metadata将更新后的聊天历史用作界面显示此外还支持引用功能的启用/禁用控制。然后使用Gradio库构建一个功能完整的图形用户界面GUI。用于与Anthropic Claude模型进行交互并支持文档引用功能。以下是详细解析(1)界面布局与核心组件使用gr.Blocks创建界面设置fill_heightTrue使界面占满浏览器高度同时设置标题。然后创建多个核心组件例如gr.Chatbot、gr.Checkbox、gr.Radio、gr.File及gr.ClearButton等。(2)交互逻辑①调整组件的可见性。enable_citations.change和doc_type_radio.change事件监听器调用update_document_inputs函数该函数根据用户是否启用引用以及选择的文档类型纯文本、PDF或组合动态控制界面上文本输入框和PDF上传组件的显示与隐藏。②消息处理流程。首先当用户在消息输入框按下回车时调用user_message函数将用户输入的消息添加到聊天历史中并清空输入框然后通过then()链式调用bot_response函数将完整的聊天历史包括新用户消息、引用设置、文本及文档内容、API密钥传递给它以生成机器人的回复并更新聊天机器人组件显示的内容。(3)应用启动if判断确保当脚本直接运行时会启动Gradio应用采用ocean主题并开启调试模式debugTrue。在安装包anthropic后启动执行以下操作①在页面输入ANTHROPIC_API_KEY不过为安全起见建议在本地运行程序并设置②在选择引用文档类型时选择“combined”上传总数不超过100页的PDF文档。也可上传其它格式文档只要编码为utf-8即可③输入文档内容和要求比如要求总结论文内容输入“Please provide a brief summary of the papers.”回车后运行界面如图8-11所示图8-11引用功能与Gradio聊天机器人的元数据功能metadata配合得特别好通过创建可折叠部分既保持聊天界面的简洁又能轻松访问来源文档从而创建更透明和可信的交互体验。Hugging Face线上完整代码请参阅ysharma/anthropic-citations-with-gradio-metadata-key️链接8-5。经过版本更迭后可能出现运行错误读者可参考本书线上修正后的代码。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2570346.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!