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

AI Agent:我的第一个Agent项目

今天实现了我的第一个Agent项目,是实现乘法,加法和幂次运算。下面是具体的代码:

from langchain.tools import BaseTool
from langchain.agents import initialize_agent
from langchain.agents import AgentType
import os
from langchain.chat_models import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from langchain.agents import AgentExecutor, create_react_agent
import operator # 导入 operator 模块以便进行安全的数学运算评估# 指向本地 API 地址
llm = ChatOpenAI(model="xxx",  # 模型名称(根据本地配置)openai_api_base="yyy",  # Ollama 默认地址openai_api_key="zzz"
)class Multiply(BaseTool):name: "str" = "乘法"description: "str" = "只做乘法运算,输入格式为'数字1,数字2'"def _run(self, input: str) -> str:try:num1_str, num2_str = input.split(',')num1 = float(num1_str.strip())num2 = float(num2_str.strip())result = num1 * num2return str(result) # 返回计算结果的字符串形式except Exception as e:return f"乘法运算失败,请检查输入格式。错误:{e}"def _arun(self, query: str):raise NotImplementedError("This tool does not support async")class Add(BaseTool):name: "str" = "加法"description: "str" = "只做加法运算,输入格式为'数字1,数字2'"def _run(self, input: str) -> str:try:num1_str, num2_str = input.split(',')num1 = float(num1_str.strip())num2 = float(num2_str.strip())result = num1 + num2return str(result) # 返回计算结果的字符串形式except Exception as e:return f"加法运算失败,请检查输入格式。错误:{e}"def _arun(self, query: str):raise NotImplementedError("This tool does not support async")class Exponentiate(BaseTool):name: "str" = "幂运算"description: "str" = "只做幂运算,输入格式为'底数,指数'"def _run(self, input: str) -> str:try:base_str, exp_str = input.split(',')base = float(base_str.strip())exponent = float(exp_str.strip())result = base ** exponentreturn str(result) # 返回计算结果的字符串形式except Exception as e:return f"幂运算失败,请检查输入格式。错误:{e}"def _arun(self, query: str):raise NotImplementedError("This tool does not support async")prompt_template = PromptTemplate.from_template("""
Answer the following questions as best you can. You have access to the following tools:{tools}Use the following format:Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input questionBegin!Question: {input}
Thought:{agent_scratchpad}
""")tools = [Multiply(),Add(),Exponentiate()]# # agent = initialize_agent(tools, agent=AgentType.DEFAULT)
# agent = initialize_agent(tools, 
#                          llm, 
#                          verbose=True)
agent = create_react_agent(llm, tools, prompt_template)
agent_executor = AgentExecutor(agent=agent,tools=tools,verbose=True,handle_parsing_errors=True # 加上这一行
)
agent_executor.invoke({"input": "3乘以6,加上 5 的 4 次方是多少?"})
# agent("3乘以6,加上 5 的 4 次方是多少?")

运行结果如下所示:

Parsing LLM output produced both a final answer and a parse-able action:: <think> 好,我现在要解决这个问题:“3乘以6,加上5的4次方是多少?”首先,我需要仔细分析题目,确保自己理解正确。题目中的运算顺序可能会影响结果,所以得一步步来。 首先,题目分成两部分:3乘以6,然后加上5的4次方。不过,可能需要确认是否有括号或者其他结构。原题是“3乘以6,加上5的4次方”,这里的逗号可能表示分步计算,也就是先算3×6,再算5的4次方,最后把两者相加。不过也有可能存在不同的理解,比如是否是3乘以(6+5的4次方),但根据中文的表达习惯,这里的逗号可能分隔了两个独立的运算,然后相加。不过需要仔细分析。 首先,先计算3乘以6。这应该是3×6=18。然后,计算5的4次方,也就是5^4。5的四次方是5×5×5×5,等于625。然后,把这两个结果相加,即18+625=643。所以答案应该是643。 不过,我需要确认是否运算顺序正确。比如,是否存在优先级的问题。比如,是否应该先算5的4次方,再进行其他运算。根据数学中的运算顺序,指数运算优先级高于乘法和加法,所以5^4应该先算,然后3×6,最后相加。所以步骤是对的。 现在,用工具来执行这些步骤。首先,使用乘法工具计算3×6,输入“3,6”,得到18。然后,使用幂运算工具计算5的4次方,输入“5,4”,得到625。接着,使用加法工具将18和625相加,输入“18,625”,得到643。这样整个过程就完成了。 不过,有没有可能题目中的“加上5的4次方”指的是3×(6+5^4)?这种情况下结果会不同。但根据题目的中文表达,“3乘以6,加上5的4次方”更可能的是分开的两个部分,即3×6 + 5^4。如果题目想表达的是3×(6+5^4),应该会有不同的标点或者结构,比如“3乘以(6加上5的4次方)”。所以,我认为原来的分步计算是正确的。 所以,最终的答案应该是643。 </think> Thought: 首先,我需要计算3乘以6的结果,然后计算5的4次方,最后将两者相加。 Action: 乘法 Action Input: 3,6 Observation: 18 Thought: 接下来计算5的4次方。 Action: 幂运算

...

Final Answer: 643

{'input': '3乘以6,加上 5 的 4 次方是多少?', 'output': '643'}

感兴趣的读者可以使用这段代码在本地测试一下,需要根据使用的模型去更新代码中的第12-14行。

http://www.xdnf.cn/news/1095013.html

相关文章:

  • 树莓派免密登录(vs code/cursor)
  • 一天两道力扣(3)
  • 【计算机组成原理——知识点总结】-(总线与输入输出设备)-学习笔记总结-复习用
  • AI大模型:(二)4.2 文生图训练实践-真人写实生成
  • Linux的`if test`和`if [ ]中括号`的取反语法比较 笔记250709
  • kbmMemTable Pro 7.82 Delphi 11 源代码
  • 【牛客刷题】小欧的选数乘积
  • 【 MySQL】一点点相关的记录
  • Wireshark抓包实验之TCP连接
  • C++最小生成树算法详解
  • 【图像处理基石】图像超分辨率有哪些研究进展值得关注?
  • 【具身智能】本地实时语音识别kaldi在正点原子RK3588上部署
  • 图像匹配方向最新论文--CoMatch: Covisibility-Aware Transformer for Subpixel Matching
  • 自动化Trae Apollo参数解释的批量获取
  • LeetCode热题100—— 152. 乘积最大子数组
  • 7.神经网络基础
  • SpringBoot集成文件 - 大文件的上传(异步,分片,断点续传和秒传)
  • huggingface 笔记: Trainer
  • Airtest 的 Poco 框架中,offspring()
  • 使用Python求解最优化问题:从理论到实践的全方位指南
  • 2025年上半年软件设计师考后分享
  • LLM中 最后一个词语的表征(隐藏状态)通常会融合前面所有词语的信息吗?
  • 跨服务sqlplus连接oracle数据库
  • Flink-1.19.0源码详解6-JobGraph生成-后篇
  • 【Java】【字节面试】字符串中 出现次数最多的字符和 对应次数
  • pytorch chunk 切块
  • 两种方式清除已经保存的git账号密码
  • 11.7 ChatGPT奖励模型完全解读:RLHF核心技术深度剖析与Hugging Face实战
  • MyBatisPlus-03-扩展功能
  • 学习日记-spring-day44-7.9