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 = None
    name: Optional[str] = None
    function_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_tool


class MyChatGLM(LLM):
    max_token: int = 8192
    # do_sample: bool = False
    do_sample: bool = True
    temperature: float = 0.8
    top_p = 0.8
    tokenizer: object = None
    model: object = None
    history: List = []
    has_search: bool = False
    model_name: str = "chatglm3-6b"
    url: str = "http://localhost:8000/v1/chat/completions"
    tools: List = []

    # def __init__(self):
    #     super().__init__()

    @property
    def _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 = part
                    ai_response = None

                ans.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, query

    def _extract_observation(self, prompt: str):
        return_json = prompt.split("Observation: ")[-1].split("\nThought:")[0]
        self.history.append({
            "role": "observation",
            "content": return_json
        })
        return

    def _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 = True
                    print("*****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 = False
        return 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_name
        data["messages"] = self.history
        data["temperature"] = self.temperature
        data["max_tokens"] = self.max_token
        data["tools"] = self.tools
        resp = 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 response


    def doRequest(self,payload:dict) -> str:
        # 请求头
        headers = {"content-type":"application/json"}
        # json形式,参数用json
        res = 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] = WeatherInput

    def __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 use
    llm = MyChatGLM()

    # Construct the agent
    agent = create_structured_chat_agent(llm, tools, prompt)
    # Create an agent executor by passing in the agent and tools
    agent_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.mfbz.cn/a/609509.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode HOT 100刷题总结

文章目录 1 哈希1.1 1-1.两数之和&#x1f7e2;1.2 2-49.字母异位词分组&#x1f7e1;1.3 3-128.最长连续序列&#x1f7e1; 2 双指针2.1 4-283.移动零&#x1f7e2;2.2 6-15.三数之和&#x1f7e1;2.3 7-11.盛最多水的容器&#x1f7e1;2.4 8-42.接雨水&#x1f534; 3 滑动窗…

传输层协议——UDP协议

目录 一、传输层 二、再谈端口号 端口号的划分 知名端口号 pidof netstat命令 三、UDP协议 1、UDP协议格式 2、UDP协议特点 3、UDP协议的缓冲区 四、基于UDP的应用层协议 一、传输层 上一篇文章我们所讲到的HTTP协议和HTTPS协议&#xff0c;是属于应用层协议。我们…

【小笔记】问答系统可视化实现的三种方式

下面三种方式都是基于Python的哈&#xff0c;从简单到复杂。 方式一&#xff1a;命令行交互问答 优点&#xff1a;原始简单直接 方式二&#xff1a;使用Python可视化框架 优点&#xff1a;无需学习前端技术栈即可搭建一个web。 streamlit&#xff1a;⭐️⭐️⭐️⭐️gra…

【服务器优化】LVS负载均衡

LVS负载均衡 LVS简介 ​ LVS&#xff08;Linux Virtual Server&#xff09;即Linux虚拟服务器&#xff0c;是由章文嵩博士主导的开源负载均衡项目&#xff0c;目前LVS已经被集成到Linux内核模块中。该项目在Linux内核中实现了基于IP的数据请求负载均衡调度方案&#xff0c;终…

nginx的应用部署nginx

这里写目录标题 nginxnginx的优点什么是集群常见的集群什么是正向代理、反向代理、透明代理常见的代理技术正向代理反向代理透明代理 nginx部署 nginx nginx&#xff08;发音同enginex&#xff09;是一款轻量级的Web服务器/反向代理服务器及电子邮件&#xff08;IMAP/POP3&…

Java设计模式 _结构型模式_外观模式

一、外观模式 1、外观模式 外观模式&#xff08;Facade Pattern&#xff09;是一种结构型模式。主要特点为隐藏系统的复杂性&#xff0c;并向客户端提供了一个客户端可以访问系统的接口。这有助于降低系统的复杂性&#xff0c;提高可维护性。当客户端与多个子系统之间存在大量…

FPGA+海思ARM方案,可同时接收HDMI/VGA 两种信号,远程控制

FPGA海思ARM方案&#xff0c;可同时接收HDMI/VGA 两种信号&#xff0c;通过配置输出任一图像或者拼接后的图像 客户应用&#xff1a;无线远程控制 主要特性&#xff1a; 1.支持2K以下任意分辨率格式 2.支持H264压缩图像 3.支持WIFI/4G无线传输 4.支持自适应输入图像分辨率 …

如何编辑百度百科里面的资料

编辑百度百科资料是一个相对简单的过程&#xff0c;但同时也需要遵循一定的规则和流程。以下是百科优化网yajje整理的编辑百度百科资料的步骤和注意事项。 登录账户 首先&#xff0c;编辑百度百科需要一个百度账号。如果没有&#xff0c;你需要先注册一个。登录后&#xff0c;…

西奥机电CLRT-01:重塑碳酸饮料质检新纪元

西奥机电CLRT-01&#xff1a;重塑碳酸饮料质检新纪元 在追求品质生活的今天&#xff0c;碳酸饮料的品质检测成为了行业内外关注的焦点。西奥机电&#xff0c;作为行业创新的领跑者&#xff0c;携其最新研发的CLRT-01二氧化碳气容量测试仪&#xff0c;为碳酸饮料行业带来了革命性…

一文详解|影响成长的关键思考(二)

之前写过一篇《一文详解&#xff5c;影响成长的关键思考》&#xff0c;里面对自己工作前几年的心法进行了总结&#xff0c;并分享了出来。现在又工作了一段时间后&#xff0c;有了一些新的体会&#xff0c;想进一步分析一下&#xff0c;于是便有了此文。的确&#xff0c;思考也…

LeetCode63:不同路径Ⅱ

题目描述 一个机器人位于一个 m x n 网格的左上角 &#xff08;起始点在下图中标记为 “Start” &#xff09;。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角&#xff08;在下图中标记为 “Finish”&#xff09;。 现在考虑网格中有障碍物。那么从左上角…

【NPS】微软NPS配置802.1x,验证域账号,动态分配VLAN(NPS篇)

NPS简介 Network Policy Server&#xff08;NPS&#xff09;是微软Windows Server中的一个网络服务&#xff0c;它作为RADIUS服务器实现&#xff0c;用于集中管理网络接入请求。NPS处理对网络资源的认证、授权和审计请求&#xff0c;通常用于控制远程访问VPN和无线网络的接入。…

Python 数据库操作- sqlite3 模块

Python sqlite3 模块 1. 安装 SQLite3 可使用 sqlite3 模块与 Python 进行集成。sqlite3 模块是由 Gerhard Haring 编写的。它提供了一个与 PEP 249 描述的 DB-API 2.0 规范兼容的 SQL 接口。用户不需要单独安装该模块&#xff0c;因为 Python 2.5.x 以上版本默认自带了该模块…

(动画详解)LeetCode225.用队列实现栈

. - 力扣&#xff08;LeetCode&#xff09; 题目描述 解题思路 这道题的思路就是使用两个队列来实现 入栈就是入队列 出栈就是将非空队列的前n-1个元素移动到新的队列中去 再将最后一个元素弹出 动画详解 代码实现 #define _CRT_SECURE_NO_WARNINGS 1#include <stdio.…

打车遇到臭车的底层逻辑!修炼的法门居然又捡起来了!——早读(逆天打工人爬取热门微信文章解读)

冥冥之中自有天意 引言Python 代码第一篇 洞见 热搜上“打车遇到臭车”话题&#xff0c;戳到了650万成年人的尴尬第二篇 冯站长之家 三分钟新闻早餐结尾 生命不息 探索不止 在生命的旅程中 我不断探索不断发现 永不停歇 引言 记 ​一大突破 炁​机启动 ​没想到 ​去年9月份…

【NodeMCU实时天气时钟温湿度项目 3】连接SHT30传感器,获取并显示当前环境温湿度数据(I2C)

今天&#xff0c;我们开始第三个专题&#xff1a;连接SHT30温湿度传感器模块&#xff0c;获取当前环境实时温湿度数据&#xff0c;并显示在1.3寸TFT液晶显示屏上。 第一专题内容&#xff0c;请参考 【NodeMCU实时天气时钟温湿度项目 1】连接点亮SPI-TFT屏幕和UI布局设计…

【0day漏洞复现】中移铁通禹路由器信息泄露漏洞

0x01 阅读须知 “如棠安全的技术文章仅供参考&#xff0c;此文所提供的信息只为网络安全人员对自己所负责的网站、服务器等&#xff08;包括但不限于&#xff09;进行检测或维护参考&#xff0c;未经授权请勿利用文章中的技术资料对任何计算机系统进行入侵操作。利用此文所提供…

AJAX家政系统源码部署/售后更新/搭建/上线维护

基于FastAdmin和原生微信小程序开发的一款同城预约、上门服务、到店核销家政系统&#xff0c;用户端、服务端(高级授权)、门店端(高级授权)各端相互依赖又相互独立&#xff0c;支持选择项目、选择服务人员、选择门店多种下单方式&#xff0c;支持上门服务和到店核销两种服务方式…

收放卷控制系统详细算法介绍(全伺服系统)

收放卷控制系统涉及的内容非常多,这里我们介绍全伺服系统利用电子齿轮指令实现主从轴的比例随动速度控制,收放卷控制算法介绍常用链接如下 1、收放卷+排线控制 收放卷+排线控制系统框图-CSDN博客文章浏览阅读24次。1、收放卷前馈量计算FC收放卷前馈量计算FC(CODESYS ST源代…

基于51单片机的智能导盲手杖—超声波测距

基于51单片机的智能导盲手杖 &#xff08;仿真&#xff0b;程序原理图&#xff0b;PCB设计报告&#xff09; 功能介绍 具体功能&#xff1a; 1.显示前方障碍物距离。 2.实时测量距离&#xff0c;并通过蜂鸣器提醒距离过短&#xff0c;蜂鸣器蜂鸣发出预警。 3.可以通过按键调…
最新文章