LangChain入门教程 - 使用代理Agent

对于大模型,比如某些场景,需要数学计算,或者需要从某些网站获取参考资料,就必须使用专门的代理来完成任务。这里我们使用langchain提供的数学工具来实现一个最简单的例子,下一篇我们会讲如何自己实现代理。

首先创建一个对话模型,记得自己设置环境变量QIANFAN_AKQIANFAN_SK

python 复制代码
from langchain_community.chat_models import QianfanChatEndpoint

chatModel = QianfanChatEndpoint(
    model='ERNIE-Bot',
    endpoint='completions'
)

组装代理

我们使用lc库提供的数学包LLMMathChain组装数学代理,负责数学相关的计算工作。这里简单解释一下代理的工作原理,不完全正确,但大概原理是没跑的:大模型在收到问题后,和工具的描述匹配一下,决定使用哪些工具。然后把问题理解后生成合适的参数调用工具并返回结果。这里面是个大黑盒,怎么理解和拆分问题并匹配工具都是由大模型自己决定的,你只能通过提示词给出参考。对于百度的千帆,测试中发现对于数学问题用英文提问比较好,如果是中文理解就问有问题,没法正确调用工具。

python 复制代码
from langchain import LLMMathChain
from langchain.agents import AgentType, initialize_agent
from langchain.tools import BaseTool, Tool
from pydantic import BaseModel, Field

tools = []

class CalculatorInput(BaseModel):
    question: str = Field()
    
llm_math_chain = LLMMathChain(llm=chatModel, verbose=True)

tools.append(
    Tool.from_function(
        func=llm_math_chain.run,
        name='牛逼的计算器',
        description='用于回答数学问题',
        args_schema=CalculatorInput
    )
)


# ZERO_SHOT_REACT_DESCRIPTION代表根据工具的描述进行选择
agent = initialize_agent(
    tools, chatModel, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)

这里args_schema参数用于构造输入参数,CalculatorInut的写法参考pydantic的文档:pydantic · PyPI

提问

python 复制代码
# 使用英文便于大模型理解
agent.run(
    'What is the result of 5.85 raised to the 2.16 power?'
)

"""输出
> Entering new AgentExecutor chain...

This is a mathematical question that requires raising a number to a specific power.

Action: 牛逼的计算器
Action Input: Calculate 5.85 raised to the power of 2.16


> Entering new LLMMathChain chain...
Calculate 5.85 raised to the power of 2.16

```text
5.85**2.16
```
...numexpr.evaluate("5.85**2.16")...

Answer: 45.400085499141575
> Finished chain.

Observation: Answer: 45.400085499141575
Thought:I now know the result of 5.85 raised to the 2.16 power.

Final Answer: 5.85 raised to the 2.16 power is equal to 45.400085499141575.

> Finished chain.
"""

代理是如何执行的?

前面我们在构造tool时,func参数设置为llm_math_chain.run。那么这个函数支持哪些参数,被调用时传进来的参数又是什么样的呢?一种方法是找源码,那个比较费事,我们可以inspect库提供的方法查看信息,然后自己在run函数外面包一层,就能看到想要看的信息了。

使用inspect函数查看信息,我们可以看到run有哪些参数和参数的默认值。

python 复制代码
import inspect

sig = inspect.signature(llm_math_chain.run)

for name, para in sig.parameters.items():
    print(name, para.default)

'''输出
args <class 'inspect._empty'>
callbacks None
tags None
metadata None
kwargs <class 'inspect._empty'>
'''

我们在这里只关心第一个参数args,我们自己定义一个函数打印传了什么参数进来。

python 复制代码
from langchain import LLMMathChain
from langchain.tools import BaseTool, Tool
from pydantic import BaseModel, Field

tools = []

class CalculatorInput(BaseModel):
    question: str = Field()
    
llm_math_chain = LLMMathChain(llm=chatModel, verbose=True)

def my_math_func(*args):
    print('输入参数', args)
    return llm_math_chain.run(*args)

tools.append(
    Tool.from_function(
        func=my_math_func,
        name='牛逼的计算器',
        description='用于回答数学问题',
        args_schema=CalculatorInput
    )
)

'''
我们可以看到以下输出:

Action: 牛逼的计算器

Action Input: Calculate 5.85 raised to the 2.16 power.
输入参数 ('Calculate 5.85 raised to the 2.16 power.\n',)
'''
相关推荐
bst@微胖子1 小时前
Python高级语法之selenium
开发语言·python·selenium
Luis Li 的猫猫2 小时前
深度学习中的知识蒸馏
人工智能·经验分享·深度学习·学习·算法
查理零世2 小时前
【蓝桥杯集训·每日一题2025】 AcWing 6118. 蛋糕游戏 python
python·算法·蓝桥杯
魔尔助理顾问3 小时前
一个简洁高效的Flask用户管理示例
后端·python·flask
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
木觞清4 小时前
PyTorch与TensorFlow的对比:哪个框架更适合你的项目?
人工智能·pytorch·tensorflow
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
wyg_0311137 小时前
用deepseek学大模型04-模型可视化与数据可视化
人工智能·机器学习·信息可视化
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python
陈敬雷-充电了么-CEO兼CTO8 小时前
DeepSeek核心算法解析:如何打造比肩ChatGPT的国产大模型
人工智能·神经网络·自然语言处理·chatgpt·大模型·aigc·deepseek