LLM大语言模型(十四):LangChain中Tool的不同定义方式,对prompt的影响

背景

ChatGLM3-6B的函数调用功能,和LangChain的Tool调用,在prompt上并没有对齐。

参考:LLM大语言模型(十二):关于ChatGLM3-6B不兼容Langchain 的Function Call_error: valueerror: caught exception: unknown forma-CSDN博客

因此在LangChain的Agent中调用ChatGLM3-6B时,单独对prompt进行了转换。

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

今日发现,使用LangChain的不同方式定义的tool,之前的prompt转换失效了。

LangChain中不同Tool定义方式,生成的prompt不同

方式一:@tool

from langchain_core.tools import tool

@tool

def calculator(calculation:str)->str:

    "Useful for when you need to calculate math problems"

    calculation = calculation.replace("^", "**")

    if "sqrt" in calculation:

        calculation = calculation.replace("sqrt", "math.sqrt")

    elif "log" in calculation:

        calculation = calculation.replace("log", "math.log")

    return eval(calculation)

在Agent执行时生成的prompt如下,关注红色部分:

'System: Respond to the human as helpfully and accurately as possible. You have access to the following tools:\n\n

calculator: calculator(calculation: str) -> str - Useful for when you need to calculate math problems, args: {\'calculation\': {\'title\': \'Calculation\', \'type\': \'string\'}}\n\n

Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).\n\nValid "action" values: "Final Answer" or calculator\n\nProvide only ONE action per $JSON_BLOB, as shown:\n\n```\n{\n  "action": $TOOL_NAME,\n  "action_input": $INPUT\n}\n```\n\nFollow this format:\n\nQuestion: input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{\n  "action": "Final Answer",\n  "action_input": "Final response to human"\n}\n\nBegin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation\nHuman: 34 * 34\n\n\n (reminder to respond in a JSON blob no matter what)'


 

方式二:继承BaseTool

import os
import requests

from typing import Type, Any
from langchain.tools import BaseTool
from pydantic import BaseModel, Field

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

在Agent执行时生成的prompt如下,关注红色部分:

System: Respond to the human as helpfully and accurately as possible. You have access to the following tools:\n\n

Calculator: Useful for when you need to calculate math problems, args: {\'calculation\': {\'description\': \'calculation to perform\', \'title\': \'Calculation\', \'type\': \'string\'}}\n\n

Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).\n\nValid "action" values: "Final Answer" or Calculator\n\nProvide only ONE action per $JSON_BLOB, as shown:\n\n```\n{\n  "action": $TOOL_NAME,\n  "action_input": $INPUT\n}\n```\n\nFollow this format:\n\nQuestion: input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{\n  "action": "Final Answer",\n  "action_input": "Final response to human"\n}\n\nBegin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation\nHuman: 34 * 34\n\n\n (reminder to respond in a JSON blob no matter what)

因为生成的prompt不同了,所以之前的prompt转换也就失效了。

LangChain使用上的一个坑。

### LangChainAgent 的架构与工作原理 #### 1. **Agent 的核心概念** Agent 是一种基于大型语言模型 (LLM) 的推理机制,其主要功能是通过一系列工具和逻辑推导来解决复杂问题。它的设计目的是让 LLM 不仅能够生成自然语言响应,还能动态调用外部工具或 API 来增强自身的功能性[^2]。 #### 2. **Agent 的组成结构** LangChain 中的 Agent 主要由以下几个部分构成: - **Language Model (LLM)** 这是一个强大的预训练模型,负责理解输入并生成相应的输出。它是整个 Agent 推理过程的核心大脑[^3]。 - **Tools (工具集)** Tools 提供了一系列可以被 Agent 调用的功能模块,例如搜索引擎查询、数据库访问或其他自定义函数。这些工具扩展了 LLM 的能力范围[^1]。 - **Prompt Template (提示模板)** Prompt Template 定义了如何向 LLM 输入数据的形式化描述。它通常包含了上下文信息、可用工具列表以及用户的实际请求。 - **Memory (记忆存储)** Memory 组件允许 Agent 记录之前的交互历史,从而实现更连贯的对话体验。这对于多轮次的任务尤为重要。 #### 3. **Agent 的工作流程** 当用户提交一个问题给 Agent 后,以下是典型的处理步骤: 1. 用户提供初始指令; 2. 基于当前状态构建 prompt 并发送至 LLM; 3. LLM 返回下一步行动计划或者直接给出答案; 4. 如果返回的是行动计划,则执行相应 tool,并收集反馈结果; 5. 将新获得的信息重新注入到循环中继续迭代直至满足终止条件为止。 #### 4. **使用方法概述** 为了创建一个简单的 Agent 应用程序,在 Python 环境下可按照以下方式操作: ```python from langchain.agents import initialize_agent, Tool from langchain.llms import OpenAI from langchain.tools import DuckDuckGoSearchRun # 初始化基础组件 llm = OpenAI(temperature=0) search_tool = DuckDuckGoSearchRun() tools = [ Tool( name="Search", func=search_tool.run, description="Useful for when you need to search the web." ) ] agent_chain = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) result = agent_chain.run("What is the capital of France?") print(result) ``` 上述代码片段展示了如何快速搭建具备网络搜索能力的小型 Agent 实例。 #### 5. **示例分析** 假设我们希望开发一款能自动回答地理类常识问答的应用程序,那么就可以利用类似下面这样的配置文件来进行设置: ```yaml name: GeographyQA description: A simple geography question answering system. version: '0.1' toolkit: tools: - type: duckduckgo_search params: max_results: 3 model_config: model_name: gpt-3.5-turbo memory_type: conversation_buffer_memory max_iterations: 5 early_stopping_method: generate_until_stop ``` 此 YAML 文件明确了所使用的具体参数选项,便于后续维护调整。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hugo Lei

赏你了,我的一点心意

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值