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

1 篇文章 0 订阅
1 篇文章 0 订阅

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

请各位看官享用。

大语言模型的部署(glm3、qwen等)可以使用我的开源项目:https://github.com/shell-nlp/gpt_server

代码样例

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=?")

运行结果:

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

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一如年少模样丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值