langchain(6):代理Agent
llm使用从互联网上学习的各类背景知识,同时利用你提供的新信息来帮助你回答问题、推理内容、决定下一步操作等
# 使用llm作为agent的推理引擎,其连接到其他数据和计算资源
# 所以将temperature设置为0,希望结果尽可能好和精确,消除随机性
llm = ChatOpenAI(temperature=0, model=llm_model)
# 加载工具
tools = load_tools(["llm-math","wikipedia"], llm=llm)
# 初始化代理
agent= initialize_agent(
tools,
llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True,
verbose = True)
# 提问1,agent会自主选择使用什么工具
agent("What is the 25% of 300?")
# 提问2
question = "Tom M. Mitchell is an American computer scientist \
and the Founders University Professor at Carnegie Mellon University (CMU)\
what book did he write?"
result = agent(question)
# 查看agent的每一步过程
agent = create_python_agent(
llm,
tool=PythonREPLTool(),
verbose=True
)
customer_list = [["Harrison", "Chase"],
["Lang", "Chain"],
["Dolly", "Too"],
["Elle", "Elem"],
["Geoff","Fusion"],
["Trance","Former"],
["Jen","Ayai"]
]
import langchain
langchain.debug=True
agent.run(f"""Sort these customers by \
last name and then first name \
and print the output: {customer_list}""")
langchain.debug=False
# 创建自定义工具,将其用到你需要的地方
from langchain.agents import tool
from datetime import date
# 创建一个tool,其中可以添加注释,帮助agent决定什么时候用和注意事项
@tool
def time(text: str) -> str:
"""Returns todays date, use this for any \
questions related to knowing todays date. \
The input should always be an empty string, \
and this function will always return todays \
date - any date mathmatics should occur \
outside this function."""
return str(date.today())
# 创建agent,并将time的tool放入工具列表
agent= initialize_agent(
tools + [time],
llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True,
verbose = True)
# 运行agent
agent.run("whats the date today?")
浙公网安备 33010602011771号