当前位置: 首页> 文旅> 文化 > 使用 openai 和 langchain 调用自定义工具完成提问需求

使用 openai 和 langchain 调用自定义工具完成提问需求

时间:2025/7/9 21:36:58来源:https://blog.csdn.net/fanghailiang2016/article/details/140854565 浏览次数:0次

我们提供了一个函数,接受传入运算的字符串,返回运算的结果。

现在的需求是,我们问 gpt 模型,由于模型计算能力并不好,他要调用计算函数,根据计算结果,回答我们的问题。


使用 openai 实现:

定义函数:

def calculator(expression):return eval(expression)
from openai import OpenAIclient = OpenAI()

把函数作为工具,声明给 openai

tools = [{"type": "function","function": {"name": "calculator","description": "运行加减乘除运算的表达式。","parameters": {"type": "object","properties": {"expression": {"type": "string","description": "需要运行的算术表达式"}}}}
}]

调用大模型,传入我们的问题并告知 openai 可使用的工具:

messages = [{"role": "user", "content": "计算 100*100/400*56 的值?"}]response = client.chat.completions.create(model="gpt-3.5-turbo",messages=messages,tools=tools
)response_message = response.choices[0].messagemessages.append(response_message)import json

根据 openai 的指示,包含调用什么工具和工具的传参是什么,我们按照这个调用工具(函数)

tool_calls = response_message.tool_callsif tool_calls:available_functions = {"calculator": calculator,}for tool_call in tool_calls:function_name = tool_call.function.nameif function_name == 'calculator':function_args = json.loads(tool_call.function.arguments)function_response = calculator(function_args.get('expression'))messages.append({"tool_call_id": tool_call.id,"role": "tool","name": function_name,"content": str(function_response),})

我们把消息的上下文,工具的返回结果等信息封装成一条消息,发给大模型,让大模型返回和我们的提问相匹配的回答的文案。

        second_response = client.chat.completions.create(model="gpt-3.5-turbo",messages=messages)print(second_response.choices[0].message.content)

好了,代码到此结束,以下截图是 openai 的返回:


使用 langchain 实现:

引包

from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools.base import BaseTool

把我们的功能函数声明为一个工具:

class Calculator(BaseTool):name = "Calculator"description = "运行加减乘除运算的表达式"def _run(self, query: str):"""Use the tool."""# 在这里实现您的自定义函数逻辑result = self.custom_function(query)return resultasync def _arun(self, query: str):"""Use the tool asynchronously."""raise NotImplementedError("This tool does not support async")def custom_function(self, expression: str):"""Your custom function logic goes here."""# 示例:将输入文本转换为大写return eval(expression)

把工具实例化后放进工具包中

# 创建工具实例
calculator = Calculator()tools = [calculator]

实例化模型创建智能体(agent)

chat_model = ChatOpenAI()# 初始化代理
agent = initialize_agent(tools, chat_model, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

调用智能体拿结果

response = agent.run("计算 10*10/2")print(response)

好了,代码到此结束,以下截图是 openai 的返回:

整个过程用了 reACt 的思想。




 MyPostMan: MyPostMan 是一款类似 PostMan 的接口请求软件,按照 项目(微服务)、目录来管理我们的接口,基于迭代来管理我们的接口文档,文档可以导出和通过 url 实时分享,按照迭代编写自动化测试用例,在不同环境中均可运行这些用例。

关键字:使用 openai 和 langchain 调用自定义工具完成提问需求

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: