agent智能体
一.自定义工具
这段代码定义了一个提示词模板(Prompt Template),用于指导大模型在工具调用场景下的思考和输出格式。它的核心作用是规范大模型与工具交互的流程,确保对话逻辑可解析、可执行。
''''尽你所能用中文回答以下问题。如果能力不够你可以使用以下工具:\n\n''{tools}\n\nUse the following format:\n\n''Question: the input question you must answer\n''Thought: you should always think about what to do\n''Action: the action to take, should be one of [{tool_names}]\n''Action Input: the input to the action\n''Observation: the result of the action\n''... (this Thought/Action/Action Input/Observation can repeat N times)\n''Thought: I now know the final answer\n''Final Answer: the final answer to the original input question\n\n''Begin!\n\n''Question: {input}\n''Thought:{agent_scratchpad}''''1.第一部分:任务与工具说明
尽你所能用中文回答以下问题。如果能力不够你可以使用以下工具:
{tools}- 告知大模型核心任务:用中文回答问题。
 - 提示可借助工具:
{tools}是占位符,实际运行时会替换为可用工具的列表(例如前面定义的文本字数计算工具及其描述)。 
2.第二部分:格式规范(核心)
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question这部分强制规定了大模型的输出格式,确保工具调用过程可被程序解析:
Question:用户的原始问题(固定格式,用于明确任务)。Thought:大模型的思考过程(例如 “我需要计算这句话的字数,应该用文本字数计算工具”)。Action:要调用的工具名称(必须是{tool_names}中的一个,{tool_names}是占位符,实际会替换为可用工具的名称列表,例如["文本字数计算工具"])。Action Input:工具的输入参数(例如要计算字数的文本内容)。Observation:工具的返回结果(由程序自动填充,大模型无需手动输入)。- 循环逻辑:
...表示上述Thought-Action-Action Input-Observation流程可重复(例如复杂问题可能需要多次调用工具)。 - 最终结论:当大模型认为可以回答问题时,用 
Thought: I now know the final answer标记,并在Final Answer中给出最终结果。 
例如,在计算文本字数的场景中,大模型会按照模板输出:
Question: '我是一个非常聪明的人工智能助手',这句话的字数是多少?
Thought: 我需要计算这句话的字数,应该使用文本字数计算工具。
Action: 文本字数计算工具
Action Input: 我是一个非常聪明的人工智能助手3.第三部分:启动与动态参数
Begin!
Question: {input}
Thought:{agent_scratchpad}Begin!:表示对话流程开始。{input}:占位符,实际运行时替换为用户的具体问题(例如 “这句话的字数是多少?”)。{agent_scratchpad}:占位符,用于存储历史交互记录(例如之前的Thought-Action-Observation内容),确保大模型能基于上下文继续思考。
4.全部代码
from langchain import hub
from langchain.agents import create_structured_chat_agent, AgentExecutor
from langchain.memory import ConversationBufferMemory
from langchain.schema import HumanMessage
from langchain.tools import BaseTool
from langchain_openai import ChatOpenAImodel = ChatOpenAI(model="qwen-plus",openai_api_key="",openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",temperature=0)model.invoke([HumanMessage(content="'我是一个非常聪明的人工智能助手',这句话的字数是多少?")])
#AIMessage(content='我们来一步一步分析这句话的字数。\n\n原句是:  \n**“我是一个非常聪明的人工智能助手”**\n\n我们要计算的是**字数**,也就是这个句子中包含多少个汉字(或字符)。\n\n我们逐字来看:\n\n1. 我  \n2. 是  \n3. 一  \n4. 个  \n5. 非  \n6. 常  \n7. 聪  \n8. 明  \n9. 的  \n10. 人  \n11. 工  \n12. 智  \n13. 能  \n14. 助  \n15. 手\n\n现在我们数一下:从第1个“我”到最后一个“手”,一共是 **15** 个字。\n\n注意:这里不包含标点符号(比如引号),因为我们只看句子本身的内容。题目问的是“这句话的字数”,指的是中文字符的数量。\n\n所以,最终答案是:**15个字**。\n\n✅ 答案:**15**')class TextLengthTool(BaseTool):name = "文本字数计算工具"#工具名称description = "当你被要求计算文本的字数时,使用此工具"#工具描述def _run(self, text):return len(text)tools = [TextLengthTool()]
prompt = hub.pull("hwchase17/structured-chat-agent")
#初始化agent
agent = create_structured_chat_agent(llm=model,tools=tools,prompt=prompt
)
memory = ConversationBufferMemory(memory_key='chat_history',return_messages=True
)
#定义agent执行器
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, memory=memory, verbose=True, handle_parsing_errors=True#出现错误也不会停止推理,而是返回大模型让大模型判断
)
agent_executor.invoke({"input": "'我是一个非常聪明的人工智能助手',这句话的字数是多少?"})
agent_executor.invoke({"input": "请你充当我的数学老师,告诉我什么是勾股定理"})
#{'input': '请你充当我的数学老师,告诉我什么是勾股定理','chat_history': [HumanMessage(content="'我是一个非常聪明的人工智能助手',这句话的字数是多少?"),AIMessage(content='这句话的字数是15。'),HumanMessage(content='请你充当我的数学老师,告诉我什么是勾股定理'),AIMessage(content='勾股定理(又称毕达哥拉斯定理)是一个在直角三角形中成立的数学定理。它表明:在一个直角三角形中,斜边(即与直角相对的边)的平方等于另外两条直角边的平方和。用公式表示为:a² + b² = c²,其中 c 是斜边的长度,a 和 b 是两条直角边的长度。这个定理在几何学、物理学以及工程学中有广泛的应用。')],'output': '勾股定理(又称毕达哥拉斯定理)是一个在直角三角形中成立的数学定理。它表明:在一个直角三角形中,斜边(即与直角相对的边)的平方等于另外两条直角边的平方和。用公式表示为:a² + b² = c²,其中 c 是斜边的长度,a 和 b 是两条直角边的长度。这个定理在几何学、物理学以及工程学中有广泛的应用。'}''''尽你所能用中文回答以下问题。如果能力不够你可以使用以下工具:\n\n''{tools}\n\nUse the following format:\n\n''Question: the input question you must answer\n''Thought: you should always think about what to do\n''Action: the action to take, should be one of [{tool_names}]\n''Action Input: the input to the action\n''Observation: the result of the action\n''... (this Thought/Action/Action Input/Observation can repeat N times)\n''Thought: I now know the final answer\n''Final Answer: the final answer to the original input question\n\n''Begin!\n\n''Question: {input}\n''Thought:{agent_scratchpad}''''