点击上方卡片 关注我们
image
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 是多少。"})
image
有路过的大佬指点一二么?
2.【解决方案】用initialize_agent
llm就按照这篇文章配置任意一个LangChain连接国内大模型测试|智谱ai、讯飞星火、通义千问
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 次方是多少?")
image
就说清不清楚吧!
{'input': '3乘以6,加上 5 的 4 次方是多少?', 'output': '643'}
【官方文档】
- initialize_agent
image
- create_tool_calling_agent
如果本文对你有帮助,还请你 点赞 在看 转发 。
你的支持就是我创作的最大动力,🙏谢谢啦!🌟
-
私信我【 加群 】欢迎加入AI交流群~
-
私信我【 科学 】送1个月科学链接~
点击下方卡片 关注我们 技术前沿不迷路