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的结果进行回答,而没有依据自身的知识。

相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby8 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩8 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
swipe9 小时前
Neo4j + Graph RAG 医疗知识图谱工程实践:患者教育问答真正需要的是“关系可追溯”
后端·langchain·llm
Front思9 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
CC大煊10 小时前
一个Javaer的AI转型笔记(1):入坑LangChain,我的第一个hello world
笔记·langchain
ZC跨境爬虫11 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。12 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星12 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒13 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端