一、什么是Agent & 为什么要用Agent
Agent是当下LLM应用的一个热点,特点就是让LLM真正像一个人一样,可以用tools去帮助它完成一些任务。就好像我们如果计算729173*3136189,不会自己拿个笔拿个纸在那算,肯定打开手机的计算器一按,就出结果了。
对于传统的LLM,如果你给他一个任务,她就靠自己内部的知识以及一些推理来完成,无法借助外部tools。比如,你问它从天安门广场到故宫怎么走,它有可能凭借自己的训练数据回答出来。但是你要是问它,从你家到你的学校怎么走,这它就没办法回答了。
那怎么办呢?引入外部tools。
比如这个例子,就可以引入导航/地图tool,把LLM不会的/不擅长的交给它来完成。
二、Agent的简单实现(python)
Agent相关的最知名的就是langchain。主要步骤就以下四个:
1、导入相关包(langchain)
from langchain.agents import initialize_agent, Tool
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate
2、定义Tools(关键、核心)
def your_tool(arg):
...
return ...
tools = [
Tool(
name = "Your_Tool"
func = your_tool
description = "..."
)
]
3、设计Prompt
custom_prompt_template = """
You are a helpful assistant.
You have the following tools at your disposal:
1.Your_Tool: {description}
2...
Your Task: {input}
Thought:{agent_scratchpad}
"""
# 包装为 PromptTemplate 对象
prompt = PromptTemplate(
input_variables=["input", "agent_scratchpad"],
template=custom_prompt_template
)
4、创建Agent
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="xxx",
temperature=0.2,
max_tokens=2000,
api_key='xxx',
base_url="xxx"
)
agent = initialize_agent(
tools,
llm,
agent = "zero-shot-react-description", ## 零样本场景
verbose = True, ## 开启代理
handle_parsing_errors = "Check the output format to ensure compliance!"
)
5、调用Agent回答问题
agent.run({"input": "Please demonstrate the difference between C and Python", "agent_scratchpad": ""})
6、回答样式
> Entering new AgentExecutor chain...
(Thought):
Action:(use a tool)
Action Input:(the input of the tool)
Obeservation:(result returned by the tool)
Thought:(llm agent thinks about the current situation and plans for the next step.)
Action:....
...
Thought: ... I know the final Answer. ....
Finished chain.
三、总结
Agent相较于纯LLM最大的提升就是让LLM多了使用tool的功能,对于Agent实现中的很多参数还需要下一步继续研究。