LLM大语言模型(十五):LangChain的Agent中使用自定义的ChatGLM,且底层调用的是remote的ChatGLM3-6B的HTTP服务

背景

本文搭建了一个完整的LangChain的Agent,调用本地启动的ChatGLM3-6B的HTTP server。

为后续的RAG做好了准备。

增加服务端role:observation

ChatGLM3的官方demo:openai_api_demo目录

api_server.py文件

class ChatMessage(BaseModel):# role: Literal["user", "assistant", "system", "function"]role: Literal["user", "assistant", "system", "function","observation"]content: str = Nonename: Optional[str] = Nonefunction_call: Optional[FunctionCallResponse] = None

修改role列表,增加了“observation”。

这是因为LangChain的Agent执行过程,是ReAct模式,在执行完tool调用后,会生成一个observation角色的消息。

在将LangChain的prompt转换为ChatGLM3的prompt时,也保留了observation角色,但是在服务启动时,接口允许的role却没有observation,会导致接口调用失败。

ChatGLM3-6B 本地HTTP服务启动

参考:

LLM大语言模型(一):ChatGLM3-6B本地部署_llm3 部署-CSDN博客

自定义LLM

自定义LLM内部访问的是HTTP server。

将LangChain Agent的prompt转换为ChatGLM3能识别的prompt。

prompt转换参考:LLM大语言模型(十三):ChatGLM3-6B兼容Langchain的Function Call的一步一步的详细转换过程记录_langchain+chatglm3-CSDN博客

import ast
import requests
import json
from typing import Any, List, Optional
from langchain.llms.base import LLM
from langchain_core.callbacks import CallbackManagerForLLMRun
from output_parse import getFirstMsg,parse_toolclass MyChatGLM(LLM):max_token: int = 8192# do_sample: bool = Falsedo_sample: bool = Truetemperature: float = 0.8top_p = 0.8tokenizer: object = Nonemodel: object = Nonehistory: List = []has_search: bool = Falsemodel_name: str = "chatglm3-6b"url: str = "http://localhost:8000/v1/chat/completions"tools: List = []# def __init__(self):#     super().__init__()@propertydef _llm_type(self) -> str:return "MyChatGLM"def _tool_history(self, prompt: str):ans = []tool_prompts = prompt.split("You have access to the following tools:\n\n")[1].split("\n\nUse a json blob")[0].split("\n")tools_json = []for tool_desc in tool_prompts:name = tool_desc.split(":")[0]description = tool_desc.split(", args:")[0].split(":")[1].strip()parameters_str = tool_desc.split("args:")[1].strip()parameters_dict = ast.literal_eval(parameters_str)params_cleaned = {}for param, details in parameters_dict.items():params_cleaned[param] = {'description': details['description'], 'type': details['type']}tools_json.append({"name": name,"description": description,"parameters": params_cleaned})ans.append({"role": "system","content": "Answer the following questions as best as you can. You have access to the following tools:","tools": tools_json})dialog_parts = prompt.split("Human: ")for part in dialog_parts[1:]:if "\nAI: " in part:user_input, ai_response = part.split("\nAI: ")ai_response = ai_response.split("\n")[0]else:user_input = partai_response = Noneans.append({"role": "user", "content": user_input.strip()})if ai_response:ans.append({"role": "assistant", "content": ai_response.strip()})query = dialog_parts[-1].split("\n")[0]return ans, querydef _extract_observation(self, prompt: str):return_json = prompt.split("Observation: ")[-1].split("\nThought:")[0]self.history.append({"role": "observation","content": return_json})returndef _extract_tool(self):if len(self.history[-1]["metadata"]) > 0:metadata = self.history[-1]["metadata"]content = self.history[-1]["content"]lines = content.split('\n')for line in lines:if 'tool_call(' in line and ')' in line and self.has_search is False:# 获取括号内的字符串params_str = line.split('tool_call(')[-1].split(')')[0]# 解析参数对params_pairs = [param.split("=") for param in params_str.split(",") if "=" in param]params = {pair[0].strip(): pair[1].strip().strip("'\"") for pair in params_pairs}action_json = {"action": metadata,"action_input": params}self.has_search = Trueprint("*****Action*****")print(action_json)print("*****Answer*****")return f"""
Action: 
```
{json.dumps(action_json, ensure_ascii=False)}
```"""final_answer_json = {"action": "Final Answer","action_input": self.history[-1]["content"]}self.has_search = Falsereturn f"""
Action: 
```
{json.dumps(final_answer_json, ensure_ascii=False)}
```"""def _call(self, prompt: str, history: List = [], stop: Optional[List[str]] = ["<|user|>"]):if not self.has_search:self.history, query = self._tool_history(prompt)if self.history[0]:self.tools = self.history[0]["tools"]else:self._extract_observation(prompt)query = ""print(self.history)data = {}data["model"] = self.model_namedata["messages"] = self.historydata["temperature"] = self.temperaturedata["max_tokens"] = self.max_tokendata["tools"] = self.toolsresp = self.doRequest(data)msg = {}respjson = json.loads(resp)if respjson["choices"]:if respjson["choices"][0]["finish_reason"] == 'function_call':msg["metadata"] = respjson["choices"][0]["message"]["function_call"]["name"]else:msg["metadata"] = ''msg["role"] = "assistant"msg["content"] = respjson["choices"][0]["message"]["content"]self.history.append(msg)print(self.history)response = self._extract_tool()history.append((prompt, response))return responsedef doRequest(self,payload:dict) -> str:# 请求头headers = {"content-type":"application/json"}# json形式,参数用jsonres = requests.post(self.url,json=payload,headers=headers)return res.text

定义tool

使用LangChain中Tool的方式:继承BaseTool

Tool实现方式对prompt的影响,参考:LLM大语言模型(十四):LangChain中Tool的不同定义方式,对prompt的影响-CSDN博客

class WeatherInput(BaseModel):location: str = Field(description="the location need to check the weather")class Weather(BaseTool):name = "weather"description = "Use for searching weather at a specific location"args_schema: Type[BaseModel] = WeatherInputdef __init__(self):super().__init__()def _run(self, location: str) -> dict[str, Any]:weather = {"temperature": "20度","description": "温度适中",}return weather

LangChain Agent调用

设置Agent使用了2个tool:Calculator() Weather(),看是否能正确调用。

    # Get the prompt to use - you can modify this!prompt = hub.pull("hwchase17/structured-chat-agent")prompt.pretty_print()tools = [Calculator(),Weather()]# Choose the LLM that will drive the agent# Only certain models support this# Choose the LLM to usellm = MyChatGLM()# Construct the agentagent = create_structured_chat_agent(llm, tools, prompt)# Create an agent executor by passing in the agent and toolsagent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)ans = agent_executor.invoke({"input": "北京天气怎么样?"})print(ans)

调用结果:

> Entering new AgentExecutor chain...
[{'role': 'system', 'content': 'Answer the following questions as best as you can. You have access to the following tools:', 'tools': [{'name': 'Calculator', 'description': 'Useful for when you need to calculate math problems', 'parameters': {'calculation': {'description': 'calculation to perform', 'type': 'string'}}}, {'name': 'weather', 'description': 'Use for searching weather at a specific location', 'parameters': {'location': {'description': 'the location need to check the weather', 'type': 'string'}}}]}, {'role': 'user', 'content': '北京天气怎么样?\n\n\n (reminder to respond in a JSON blob no matter what)'}]
[{'role': 'system', 'content': 'Answer the following questions as best as you can. You have access to the following tools:', 'tools': [{'name': 'Calculator', 'description': 'Useful for when you need to calculate math problems', 'parameters': {'calculation': {'description': 'calculation to perform', 'type': 'string'}}}, {'name': 'weather', 'description': 'Use for searching weather at a specific location', 'parameters': {'location': {'description': 'the location need to check the weather', 'type': 'string'}}}]}, {'role': 'user', 'content': '北京天气怎么样?\n\n\n (reminder to respond in a JSON blob no matter what)'}, {'metadata': 'weather', 'role': 'assistant', 'content': "weather\n ```python\ntool_call(location='北京')\n```"}]
*****Action*****
{'action': 'weather', 'action_input': {'location': '北京'}}
*****Answer*****

Action:
```
{"action": "weather", "action_input": {"location": "北京"}}
```{'temperature': '20度', 'description': '温度适中'}

[{'role': 'system', 'content': 'Answer the following questions as best as you can. You have access to the following tools:', 'tools': [{'name': 'Calculator', 'description': 'Useful for when you need to calculate math problems', 'parameters': {'calculation': {'description': 'calculation to perform', 'type': 'string'}}}, {'name': 'weather', 'description': 'Use for searching weather at a specific location', 'parameters': {'location': {'description': 'the location need to check the weather', 'type': 'string'}}}]}, {'role': 'user', 'content': '北京天气怎么样?\n\n\n (reminder to respond in a JSON blob no matter what)'}, {'metadata': 'weather', 'role': 'assistant', 'content': "weather\n ```python\ntool_call(location='北京')\n```"}, {'role': 'observation', 'content': "{'temperature': '20度', 'description': '温度适中'}"}]
[{'role': 'system', 'content': 'Answer the following questions as best as you can. You have access to the following tools:', 'tools': [{'name': 'Calculator', 'description': 'Useful for when you need to calculate math problems', 'parameters': {'calculation': {'description': 'calculation to perform', 'type': 'string'}}}, {'name': 'weather', 'description': 'Use for searching weather at a specific location', 'parameters': {'location': {'description': 'the location need to check the weather', 'type': 'string'}}}]}, {'role': 'user', 'content': '北京天气怎么样?\n\n\n (reminder to respond in a JSON blob no matter what)'}, {'metadata': 'weather', 'role': 'assistant', 'content': "weather\n ```python\ntool_call(location='北京')\n```"}, {'role': 'observation', 'content': "{'temperature': '20度', 'description': '温度适中'}"}, {'metadata': '', 'role': 'assistant', 'content': '根据最新的气象数据 
,北京的天气情况如下:温度为20度,天气状况适中。'}]

Action:
```
{"action": "Final Answer", "action_input": "根据最新的气象数据,北京的天气情况如下:温度为20度,天气状况适中。"}
```

> Finished chain.
{'input': '北京天气怎么样?', 'output': '根据最新的气象数据,北京的天气情况如下:温度为20度,天气状况适中。'}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/9318.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity 性能优化之GPU Instancing(五)

提示&#xff1a;仅供参考&#xff0c;有误之处&#xff0c;麻烦大佬指出&#xff0c;不胜感激&#xff01; 文章目录 前言一、GPU Instancing使用方法二、使用GPU Instancing的条件三、GPU Instancing弊端四、注意五、检查是否成功总结 前言 GPU Instancing也是一种Draw call…

AppImage 创建快捷方式

AppImage是什么&#xff1f; AppImage 是一个可下载的 Linux 文件&#xff0c;它内部包含一个应用程序和应用程序所需的一切&#xff08;库、图标、字体等&#xff09;。 官网 https://appimage.org/ 如何运行 AppImage 很简单&#xff0c;下载一个 AppImage&#xff0c;给…

PowerShell ⇒ Excel 批量创建Excel

New-Object -ComObject Excel.Application&#xff1a;创建Excel对象[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null 用来显式释放 Excel COM 对象的资源&#xff0c;以确保在脚本执行完成后&#xff0c;释放 Excel 进程和相关资源&#xff0…

揭秘:让代码更优雅的七大面向对象设计秘诀

软件项目中&#xff0c;需求是不断变化的&#xff0c;需求也是项目中最难把控的&#xff0c;需求的变更也是无法避免的。我们写的软件程序&#xff0c;如何能实现拥抱变化&#xff0c;使我们的软件达到可维护和可复用&#xff0c;这是一代代软件工程师不断追寻的真理。 导致一个…

接口数据脱敏实现方案

背景 敏感信息如手机号、身份证、邮箱等信息需要脱敏后展示给前台&#xff0c;如果需要查看&#xff0c;则需要申请权限&#xff0c;查询时需要记录操作日志。 方案 通过JsonSerializer和注解&#xff0c;在json序列化的时候做脱敏操作 此处使用redis存储了加密后的key和明…

认养小游戏功能介绍

认养小游戏通常模拟了真实的农业生产过程&#xff0c;让玩家能够在线上体验种植、养殖的乐趣。以下是一些常见的认养小游戏功能介绍&#xff1a; 选择认养的农产品&#xff1a;首先&#xff0c;玩家可以从游戏中提供的多种农产品中选择自己想要认养的种类&#xff0c;如蔬菜、…

【Java一些注解知识】

RequestMapping RequestMapping是Spring框架中的一个注解&#xff0c;用于将HTTP请求映射到特定的处理方法上。通过使用RequestMapping注解&#xff0c;我们可以指定处理方法应该处理的URL路径和HTTP请求方法。 下面是一个简单的示例&#xff1a; 假设我们有一个UserControl…

[wp]第一届 “帕鲁杯“ --应急响应

1.前言&#xff1a; 第一次做这么大规模的应急响应靶场&#xff0c;收获许多 2.拓补图&#xff1a; 3.资产清单 4.解题 1. 签到[堡垒机的flag标签的值] [BrYeaVj54009rDIZzu4O] 2. 提交攻击者第一次登录时间 2024/04/11/14:21:18 3. 提交攻击者源IP 192.168.1.4 4. 提交…

网络隔离状态下,如何可以安全高效地进行研发文件外发?

研发部门的数据传输通常需要保证数据的安全性、完整性和保密性&#xff0c;尤其是当涉及到公司的核心技术、产品设计、源代码等重要信息时。研发文件外发&#xff0c;即研发资料的外部传输&#xff0c;通常涉及到公司的核心技术和商业机密&#xff0c;因此需要采取严格的安全措…

LayaAir引擎全面支持淘宝小游戏、小程序、小部件的发布

在最新的3.1版本和2.13版本中&#xff0c;LayaAir引擎已经全面支持了淘宝小游戏、小程序和小部件的开发和发布。这一重大更新&#xff0c;标志着LayaAir引擎与电商巨头阿里巴巴旗下的淘宝平台形成生态合作&#xff0c;在为广大开发者提供更加强大、高效的跨平台开发工具和解决方…

c++11 标准模板(STL)本地化库 - 平面类别(std::money_get) - 从输入字符序列中解析并构造货币值

本地化库 本地环境设施包含字符分类和字符串校对、数值、货币及日期/时间格式化和分析&#xff0c;以及消息取得的国际化支持。本地环境设置控制流 I/O 、正则表达式库和 C 标准库的其他组件的行为。 平面类别 从输入字符序列中解析并构造货币值 std::money_get template<…

Unity-NGUI爆错以后-导致不能多次点击,UI假卡死问题解决方法

太久没用&#xff0c;忘了&#xff0c;NGUI好像易出错&#xff0c;就再次点击不了 导致打开了UI关闭不了&#xff0c;每次都要重启就比较烦&#xff08;说的就是那种美术团队&#xff0c;一个 UI 打开几十层&#xff09; 就好比【左上角&#xff0c;箭头】点第二次是退出不了了…

【Mac】Hype 4 Pro for Mac(HTML5动画制作软件)v4.1.17安装激活教程

软件介绍 Hype 4 Pro是一款专业的HTML5动画和交互式内容制作软件&#xff0c;适用于Mac平台。它的主要特点和功能包括&#xff1a; 1.HTML5动画制作&#xff1a; Hype 4 Pro提供了直观的界面和丰富的工具&#xff0c;帮助用户轻松创建各种复杂的HTML5动画效果&#xff0c;包括…

每天五分钟计算机视觉:使用极大值抑制来寻找最优的目标检测对象

本文重点 在目标检测领域,当模型预测出多个候选框(bounding boxes)时,我们需要一种方法来确定哪些候选框最有可能表示真实的目标。由于模型的不完美性和图像中目标的重叠性,往往会有多个候选框对应于同一个目标。此时,极大值抑制(Non-Maximum Suppression,NMS)技术就…

Isaac Sim 6 仅使用isaacsim中自带的工具进行语义分割、实例分割(学习笔记5.09)

一.概要 建立场景&#xff0c;给场景内的物体赋予语义&#xff0c;使用Replicator进行分割操作&#xff0c;从而获得带标签信息的mask掩码图&#xff0c;可作为数据集、验证集等训练使用。 二.具体操作步骤 场景部分 1.搭建一个基础场景 这里建议在搭建的时候就按类别分好类…

变配电工程 变配电室智能监控系统 门禁 视频 环境 机器人

一、方案背景 要真正了解无人值守配电房的运行模式&#xff0c;我们必须对“无人值守”这一概念有准确的理解。它并不意味着完全没有工作人员管理&#xff0c;而是通过技术设备和人机协作来确保配电房的正常运行。 利用变配电室智能监控系统&#xff0c;可以实时获得配电室各…

44.乐理基础-音符的组合方式-附点

内容参考于&#xff1a; 三分钟音乐社 首先如下图&#xff0c;是之前的音符&#xff0c;但是它不全&#xff0c;比如想要一个三拍的音符改怎样表示&#xff1f; 在简谱中三拍&#xff0c;在以四分音符为一拍的情况下&#xff0c;在后面加两根横线就可以了&#xff0c;称为附点…

基于Unity为Vision Pro 构建游戏的4个关键

为Vision Pro开发游戏时需要考虑的四个关键概念:输入的自然性、物理尺寸的真实匹配、交互空间的充足性以及Unity组件的有效利用。 AVP交互小游戏(Capsule Critters)作者分享了使用Unity构建的几个核心关键: Bounded - 游戏定义:Bounded(有限)是Unity的术语,指的是游戏作…

利用“AnaTraf“网络流量分析仪轻松诊断和优化网络

网络性能监测和诊断(NPMD)是网络管理和优化的重要环节,准确快速地定位和排除网络故障对于保障业务正常运转至关重要。作为一款专业的网络流量分析设备,AnaTraf网络流量分析仪凭借其强大的流量分析和故障诊断功能,为网络管理者提供了一个高效的网络优化解决方案。 全面掌握网络…

【Ubuntu18.04+melodic】抓取环境设置

UR5_gripper_camera_gazebo&#xff08;无moveit&#xff09; 视频讲解 B站-我要一米八了-抓取不止&#xff01;Ubuntu 18.04下UR5机械臂搭建Gazebo环境&#xff5c;开源分享 运行步骤 1.创建工作空间 catkin_make2.激活环境变量 source devel/setup.bash3.1 rviz下查看模…