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

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

请各位看官享用。

代码样例

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

猜你喜欢

转载自blog.csdn.net/q506610466/article/details/132500293