当前位置: 首页 > news >正文

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

在 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'}

相关文章:

  • 【models】Transformer 之 各种 Attention 原理和实现
  • LLM KV Cache压缩技术解析:Multi-Head Key-Value共享方案
  • openharmony—release—4.1开发环境搭建(踩坑记录)
  • 软考 系统架构设计师系列知识点 —— 设计模式之抽象工厂模式
  • WPS复制粘贴错误 ,文件未找到 mathpage.wll
  • Android学习22 -- perfetto
  • 【自动驾驶 机器人】速度规划 |梯形/S型速度曲线
  • python中的字符串
  • 嵌入式面试笔试那点事2:2025.4.13
  • Vue事件修饰符课堂练习
  • golang-context详解
  • MySQL varchar 最大长度
  • 【苹果cms 2】资源站动漫采集爬取
  • C#容器源码分析 --- List<T>
  • AI技术实战:从零搭建图像分类系统全流程详解
  • SaaS、Paas、IaaS、MaaS、BaaS五大云计算服务模式
  • 【前端网络请求】XHR封装,支持文件上传、进度监控、混合字段传输
  • 基于SpringBoot的瑜伽馆管理系统【附源码】
  • Java 基础数据类型与运算符深度剖析
  • Python、C++中的查找
  • 百年传承,再启新程,参天中国迎来2.0时代
  • 排除燃气爆炸、人为放火可能,辽宁辽阳火灾事故起火原因正在调查
  • 新开发银行如何开启第二个“金色十年”?
  • 习近平在上海考察时强调,加快建成具有全球影响力的科技创新高地
  • 言短意长|政府食堂、停车场开放的示范效应
  • 专访|首夺天元头衔创生涯历史,王星昊打算一步一步慢慢来