langchain之agent系列:zero-shot-react-description agent

发布于:2025-04-11 ⋅ 阅读:(40) ⋅ 点赞:(0)

在 LangChain 的 Agent 系统中,Zero-shot ReAct Agent为最基础的Agent,文本对其进行介绍。

在这里插入图片描述

​☎️ 核心特征:

基于 ReAct(Reasoning + Acting)框架
无记忆机制,每次请求独立处理
默认使用 llm-math 和 wikipedia 工具

​☎️ 工作流程:

Thought → Action → Observation → Final Answer

🧠 原理:Zero-shot ReAct Agent 会根据工具描述自己决定是否调用工具,零样本地推理动作和思考。

​☎️ 案例:计算一连串数字相加

笔者通过Ollama运行了如下模型

NAME                ID              SIZE      MODIFIED
llama3:latest       365c0bd3c000    4.7 GB    2 weeks ago
deepseek-r1:1.5b    a42b25d8c10a    1.1 GB    2 weeks ago

案例代码:

import re
from langchain.prompts import PromptTemplate
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
from langchain_ollama import ChatOllama

def add_numbers(text: str) -> str:
    pattern = r"-?(?:\d+\.\d+|\.\d+|\d+)(?=\D|$)"
    numbers = []
    # 抽取所有数字并求和
    for num_str in re.findall(pattern, text):
        # 处理以点开头的数字(如 .56 → 0.56)
        if num_str.startswith('.'):
            num_str = '0' + num_str
        # 转换数值类型
        try:
            if '.' in num_str:
                numbers.append(float(num_str))
            else:
                numbers.append(int(num_str))
        except ValueError:
            continue  # 跳过无效格式(如空字符串)
    
    # 无论numbers中有多少个数字,都计算所有数的和
    if len(numbers) > 0:
        return str(sum(numbers))
    else:
        return str(0)


# 定义一个工具,用于计算一连串数字相加
calculator_tool = Tool(
    name="MyCalculator",
    func=add_numbers,
    description="用于计算一连串数字相加,输入应是带有多个数字的字符串。"
)


# 初始化 LLM
llm = ChatOllama(
    model = "llama3",
    temperature = 0,
    base_url="http://localhost:11434"
)

# 定义提示词模板
template = """
请严格按照以下格式响应,只能使用中文:
Thought: 你的思考过程
Action: 可用的工具名称
Action Input: 工具的输入内容

例如:
Thought: 我需要先查询天气
Action: Search
Action Input: 北京今日天气

优先使用工具,以最少的步数完成任务。现在开始回答:
{input}
"""

prompt = PromptTemplate.from_template(template)

# 创建 agent
agent = initialize_agent(
    tools=[calculator_tool],  
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,  # 采用 ReAct 机制
    verbose=True,
    prompt=prompt,
    handle_parsing_errors=True
)

query = "12、23、45、20相加的和是多少?"
print(agent.invoke(query))

运行结果

> Entering new AgentExecutor chain...
Let's get started.

Thought: Since we have a string of numbers separated by commas, we can use MyCalculator to calculate the sum. We'll need to split the string into individual numbers and then add them up.

Action: Use MyCalculator
Action Input: 12,23,45,20
Observation: Use MyCalculator is not a valid tool, try one of [MyCalculator].
Thought:I think I see what's going on here!

Thought: Hmm, it looks like the action "Use MyCalculator" isn't actually using the MyCalculator function. Let me try again.

Action: MyCalculator
Action Input: 12,23,45,20
Observation: 100
Thought:Let's continue from where we left off!

Thought: Now that we've successfully used the MyCalculator function, let's think about what to do next.

Action: None (we're done with this part!)

Thought: Since we've already calculated the sum using MyCalculator, there's no need to do anything else. We can just move on to the final answer!

Thought: I now know the final answer

Final Answer: 100

> Finished chain.
{'input': '12、23、45、20相加的和是多少?', 'output': '100'}

网站公告

今日签到

点亮在社区的每一天
去签到