1.create_tool_calling_agent
构建agent,这个方法是过时了吗?官方文档也没更新,官方示例也运行错误
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import ConfigurableField
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
@tool
def multiply(x: float, y: float) -> float:
"""将 'x' 乘以 'y'。"""
return x * y
@tool
def exponentiate(x: float, y: float) -> float:
"""将 'x' 乘以 'y' 的指数。"""
return x**y
@tool
def add(x: float, y: float) -> float:
"""将 'x' 和 'y' 相加。"""
return x + y
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个有用的助手"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
tools = [multiply, exponentiate, add]
# llm = ChatZhipuAI(
# model="glm-4",
# temperature=0.5,
# )
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "3 加上 5 的 2.743 次方是多少。还有 17.24 减去 918.1241 是多少。"})
llm就按照这篇文章配置任意一个
LangChain连接国内大模型测试|智谱ai、讯飞星火、通义千问
有路过的大佬指点一二么?
2.initialize_agent
from langchain.tools import BaseTool
from langchain.agents import initialize_agent
from langchain.agents import AgentType
import os
from langchain_community.chat_models import ChatZhipuAI
os.environ["ZHIPUAI_API_KEY"] = 'xxx'
llm = ChatZhipuAI(
model="glm-4",
temperature=0.5,
)
class Multiply(BaseTool):
name = "乘法"
description = "只做乘法运算"
def _run(self, input: str) -> str:
# Your logic here
return "乘法计算完毕"
def _arun(self, query: str):
raise NotImplementedError("This tool does not support async")
class Add(BaseTool):
name = "加法"
description = "只做加法运算"
def _run(self, input: str) -> str:
# Your logic here
return "加法计算完毕"
def _arun(self, query: str):
raise NotImplementedError("This tool does not support async")
class Exponentiate(BaseTool):
name = "幂运算"
description = "只做幂运算"
def _run(self, input: str) -> str:
# Your logic here
return "幂运算计算完毕"
def _arun(self, query: str):
raise NotImplementedError("This tool does not support async")
tools = [Multiply(),Add(),Exponentiate()]
# agent = initialize_agent(tools, agent=AgentType.DEFAULT)
agent = initialize_agent(tools,
llm,
verbose=True)
agent("3乘以6,加上 5 的 4 次方是多少?")
就说清不清楚吧!
{'input': '3乘以6,加上 5 的 4 次方是多少?', 'output': '643'}
【官方文档】
- initialize_agent
- create_tool_calling_agent