Langchain-React范式调用API —— 自定义工具

因为Langchain的代码也不是很复杂,因此 直接看代码会更好的学习。 一些说明,我已经放到了注释当中。

请各位看官享用。

代码样例

python 复制代码
from langchain.agents import initialize_agent
from langchain.llms import OpenAI
from langchain.tools import BaseTool

# 下面是继承 langchain的工具类来自定义工具
# 天气查询工具 ,无论查询什么都返回雷暴天气
class WeatherTool(BaseTool):
    name = "Weather"
    description = "用于查询天气情况"

    def _run(self, query: str) -> str:
        return "雷暴天气"
# 计算工具,暂且写死返回3
class CustomCalculatorTool(BaseTool):
    name = "Calculator"
    description = "计算机用于准确的进行数值计算"

    def _run(self, query: str) -> str:
        # 我这里强制等于 3 来测试工具使用情况
        return "3"


# 因为没有钱买GPT4,我就使用阿里开源的Qwen模型,部署openai的api服务。
llm = OpenAI(temperature=0,
             openai_api_base="http://192.168.101.30:8081/v1",
             openai_api_key="EMPTY",
             model_name="Qwen-7B-Chat")
tools = [WeatherTool(), CustomCalculatorTool()]

agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)

agent.run("今天天气怎么样")

agent.run("使用计算器工具计算 1+9=?")

运行结果:

bash 复制代码
> Entering new AgentExecutor chain...
我应该使用weather API来查询天气情况。
Action: Weather
Action Input: 今天天气怎么样
Observation:
Observation: 雷暴天气
Thought:I now know the final answer.
Final Answer: 今天是雷暴天气,记得带上雨伞。

> Finished chain.


> Entering new AgentExecutor chain...
我需要使用计算器工具来进行数值计算
Action: Calculator
Action Input: 1+9
Observation:
Observation: 3
Thought:I now know the final answer.
Final Answer: 1+9=3

> Finished chain.

我们会发现,模型成功的运行使用了API的结果进行回答,而没有依据自身的知识。

相关推荐
前端 贾公子5 小时前
第 5 章:Codex 从可运行程序到可交付工具
java·前端·数据库
小易老师AI实战5 小时前
LangChain Deep Agents:新一代增强型通用智能体框架
langchain·大模型开发·deepagents·ai 智能体·agent 开发
用户360055579005 小时前
Kestrel_VLLM - 26 · 发射空档三步曲:事件计时 → nsys → 判别实验
前端
echome8885 小时前
JavaScript async/await 错误处理:别让 Promise 静默失败
开发语言·前端·javascript·promise
PedroQue996 小时前
v0.2.0 架构升级:class + reactive 重塑状态管理
前端·uni-app
鶴哥只手遮天6 小时前
Angular 22 源码级深度解析-第 02 章 编译链路总览:从模板字符串到 `ɵɵ` 指令
前端·开源·angular.js
尘世中一位迷途小书童6 小时前
别再堆万字 Prompt:用 Agent Skills 给团队写一个「前端 Review」Skill
前端·ai编程·cursor
aixingpan6 小时前
aixingpan.cn API开发文档:api_docs_bichart_common2接口指南
前端·php
super_Omni6 小时前
text/PDF/Word → 解析成纯文本 → 分词 → 词表匹配 → 加权打分 → 低于阈值
前端·chrome
阶进遐6 小时前
浏览器工具自制指南·对话导出(3):消息池设计
前端