Agent学习(一)初识Agent

一、什么是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实现中的很多参数还需要下一步继续研究。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rebegin_2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值