OpenAI的Function calling 和 LangChain的Search Agent

OpenAI的Function calling

         openai最近发布的gpt-3.5-turbo-0613 和 gpt-4-0613版本模型增加了function calling的功能,该功能通过定义功能函数,gpt通过分析问题和函数功能描述来决定是否调用函数,并且生成函数对应的入参。函数调用的功能可以弥补gpt的一些缺点,比如实时信息的缺乏、特定领域能力,使得能够进一步利用gpt的逻辑推理能力,可以将问题进行分解处理,解决问题能力更加强大。

gpt的函数调用功能步骤如下:
    1.使用问句和函数定义调用gpt
         2.gpt选择是否调用函数,并输出参数
         3.解析参数 调用函数
         4.将函数返回作为追加信息再次调用gpt

下面是一个通过调用search api的例子

1.定义+描述函数

        下面代码介绍了一个搜索函数,可以通过GoogleSerperAPI实时搜索网络上的信息。

###定义functions,用于描述函数作用和参数介绍。
functions = [{"name": "get_info_from_web","description": "get more informations from internet use google search","parameters": {"type": "object","properties": {"query": {"type": "string","description": "all the questions or information you want search from internet",}},"required": ["query"],},}
]###函数定义
def get_info_from_web(query):search = GoogleSerperAPIWrapper(serper_api_key="xxxxx")return search.run(query)

2.调用gpt,决定是否调用函数以及函数参数

        当用户问句为"今天杭州天气怎么样?"时,gpt做出了进行调用get_info_from_web函数的决定,并且调用的参数为"query": "杭州天气"。

messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous. "})
messages.append({"role": "user", "content": "今天杭州天气怎么样?"})
chat_response = chat_completion_request(messages, functions=functions
)
assistant_message = chat_response.json()["choices"][0]["message"]
messages.append(assistant_message)
print(assistant_message)>>>
{'role': 'assistant','content': None,'function_call': {'name': 'get_info_from_web','arguments': '{\n  "query": "杭州天气"\n}'}
}

3.执行gpt的决定,获得回答问题的中间结果

        调用第2步中gpt输出的参数执行相应的函数,获得中间结果。

assistant_message = chat_response.json()["choices"][0]["message"]
if assistant_message.get("function_call"):if assistant_message["function_call"]["name"] == "get_info_from_web":query = json.loads(assistant_message["function_call"]["arguments"])["query"]results = get_info_from_web(query)else:results = f"Error: function {assistant_message['function_call']['name']} does not exist"
print(results)>>>
81°F

4.函数结果和原始问题再次询问gpt,获得最终结果

messages.append({"role": "function", "name": assistant_message["function_call"]["name"], "content": results})
second_response = openai.ChatCompletion.create(model= GPT_MODEL,messages=messages)
print(second_response["choices"][0]["message"]["content"])>>>
今天杭州的天气是81°F。

LangChain的Search Agent        

        在openai的function calling发布之前,LangChain的Agent就可以实现类似功能。Agent接口是LangChain中一个重要的模块,一些应用程序需要根据用户输入灵活地调用LLM和其他工具。Agent接口为此类应用程序提供了灵活性。Agent可以访问一套工具,并根据用户输入确定要使用哪些工具。Agent可以使用多个工具,并将一个工具的输出用作下一个工具的输入。

        以下是search agent的例子。定义GoogleSerperApi工具作为LLM可用的tool,帮助解决相关问题。

from langchain.utilities import GoogleSerperAPIWrapper
from langchain.llms.openai import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentTypellm = OpenAI(temperature=0)
search = GoogleSerperAPIWrapper(serper_api_key="xxxxxx")
tools = [Tool(name="Intermediate Answer",func=search.run,description="useful for when you need to ask with search",)
]self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True
)self_ask_with_search.run("今天杭州天气怎么样?"
)>>>
> Entering new AgentExecutor chain...Yes.
Follow up: 今天是几号?
Intermediate answer: Sunday, July 16, 2023
Follow up: 杭州今天的天气情况?
Intermediate answer: 88°F
So the final answer is: 88°F> Finished chain.
88°F

       agent功能通过设计prompt实现,search agent的prompt设计如下:

"""Question: Who lived longer, Muhammad Ali or Alan Turing?
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad AliQuestion: When was the founder of craigslist born?
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952Question: Who was the maternal grandfather of George Washington?
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph BallQuestion: Are both the directors of Jaws and Casino Royale from the same country?
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate answer: New Zealand.
So the final answer is: NoQuestion: {input}
Are followup questions needed here:{agent_scratchpad}"""

 可以从prompt看出,通过四个例子提出了解决问题的方式,即通过follow up + Intermediate answer 分解问题并解决子问题。follow up是gpt的输出,表示需要search tool搜索的问题, Intermediate answer 则为search tool的答案,循环多次之后得到最终答案。
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/6385.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Pytorch个人学习记录总结 07

目录 神经网络-非线性激活 神经网络-线形层及其他层介绍 神经网络-非线性激活 官方文档地址:torch.nn — PyTorch 2.0 documentation 常用的:Sigmoid、ReLU、LeakyReLU等。 作用:为模型引入非线性特征,这样才能在训练过程中…

Java面试题总结记录(3)—— Spring篇

1、什么是Spring? Spring 是个java企业级应用的开源开发框架。Spring主要用来开发Java应用,但是有些扩展是针对 构建J2EE平台的web应用。 Spring 框架目标是简化Java企业级应用开发,并通过 POJO为基础的编程 模型促进良好的编程习惯 2、你们项…

Socks5代理在爬虫与HTTP应用中的重要性

IP代理的类型及原理常见的IP代理类型有HTTP代理、Socks代理等,本文重点关注Socks5代理。Socks5代理是一种网络协议,可以实现传输层的数据转发,使客户端在不直接连接服务器的情况下与其进行通信。其原理在于接收客户端的请求,然后将…

数组和链表、栈和队列的区别

1.数组和链表的区别 数组和链表是两种不同的数据结构,它们在存储和访问数据上有很大的区别。 1. 存储方式: 数组是一种连续内存空间的数据结构,其元素在内存中是按顺序存储的,通过索引可以直接访问元素。链表是由若干个节点组成…

[k8s] command和args

k8s中的command和args可以覆盖docker镜像中的entrypoint和cmd。其中,k8s-command可以覆盖docker-entrypoint,k8s-args可以覆盖docker-cmd。参考Difference between Docker ENTRYPOINT and Kubernetes container spec COMMAND? 了解一下entrypoint的意义…

Spring 更简单的读取和存储对象

目录 1.存储 Bean 对象 1.1 前置⼯作:配置扫描路径 1.2 添加注解存储 Bean 对象 1.2.1 Controller(控制器存储) 1.2.2 Service(服务存储) 1.2.3 Repository(仓库存储) 1.2.4 Component&a…

Python学习 - Request库

学习和使用 引入 import requests基本语法 Request常用方法总结 responserequests.get(url,params,**kwargs) responserequests.post(url,params,**kwargs)参数含义url目标URL地址params请求发起携带的数据kwargs控制请求访问的参数,使用后可以加入到requests请…

C++---string

String C语言中的字符串和C中的string类标准库中的string类string类的常用接口string类对象的常见构造string类对象的容量操作string类对象的访问及遍历操作 C语言中的字符串和C中的string类 在C语言中,字符串是一个字符数组,它以空字符\0结尾&#xff…

【数据结构】朴素模式匹配 KMP算法

🎇【数据结构】朴素模式匹配 & KMP 算法🎇 🌈 自在飞花轻似梦,无边丝雨细如愁 🌈 🌟 正式开始学习数据结构啦~此专栏作为学习过程中的记录🌟 文章目录 🎇【数据结构】朴素模式匹配 & K…

【数据架构】Data Fabric 架构是实现数据管理和集成现代化的关键

D&A 领导者应该了解数据编织架构的关键支柱,以实现机器支持的数据集成。 在日益多样化、分布式和复杂的环境中,数据管理敏捷性已成为组织的任务关键优先事项。为了减少人为错误和总体成本,数据和分析 (D&A) 领导者需要超越传统的数据…

Java相关知识点

变量的生命周期:位于内层中的变量可以访问并修改外层变量的值 注意:子类中方法的访问权限 > 父类 ReultSet不是一个集合,而是在使用jdbc(java database connectivity) 返回的一个结果集 enty中提供有参构造时, 未提供空参构…

MyBatis操作数据库

1.MyBatis是什么? MyBatis 是⼀款优秀的持久层框架,它⽀持⾃定义 SQL、存储过程以及⾼级映射。MyBatis 去除了⼏乎所有的 JDBC 代码以及设置参数和获取结果集的⼯作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接⼝和 Java POJO&#xf…

【机器学习】吃瓜教程 | 西瓜书 + 南瓜书 (1)

文章目录 一、绪论1、什么是机器学习?2、基本术语3、假设空间4、归纳偏好5、发展历程 二、模型评估与选择A、一种训练集一种算法2.1 经验误差 与 过拟合2.2 评估方法a) 留出法b) 交叉验证法c) 自助法d) 调参与最终模型 2.3 性能度量a) 错误率与精度b) 查准率、查全率…

matlab dot()函数求矩阵内积,三维 ,多维 详解

matlab dot()函数求矩阵内积,三维 ,多维 详解 Cdot(A,b,X),这个参数X 只能取1,或者2。1 表示按列,2表示按行,如果没有参数。默认按列。 1)按列优先计算 Cdot(A,B)dot(A,B,1)[a1*b1a4*b4 ,a2*b2a5*b5 ,a…

视频拼接得AI三维生成方案-开端(一)

想使用二维得图像生成三维得空间图像,英伟达有完整得方案,开源,但是三维拼接不一样,只需要二维,并且要实时,如何生成是我每天都在思考得东西。 cnn 提取特征器和自编码 在训练细胞神经网络时,问…

linux shell比较命令

1 比较运算 num1-eq num2 等于 [ 3 -eq $mynum ] num1-ne num2 不等于 [ 3 -ne $mynum ] num1-lt num2 小于 [ 3 -lt $mynum ] num1-le num2 小于或等于 [ 3 -le $mynum ] num1-gt num2 大于 [ 3 -gt $mynum ] num1-ge num2 大于或等于 [ 3 -ge $mynum ]。 filename1-nt filen…

linux上面修改u盘的名称

首先df-h显示文件系统磁盘空间使用情况 df -hFilesystem Size Used Avail Use% Mounted on /dev/sda1 39G 24G 13G 66% / tmpfs 990M 4.5M 986M 1% /dev/shm /dev/sda2 77G 62G 12G 85% /broncho /dev/s…

C++ PCL点云圆柱结构提取/立杆结构提取

目录 一、算法实现二、结果展示适用于圆柱体提取、立杆提取。 一、算法实现 #include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #in

大数据分析案例-基于LightGBM算法构建乳腺癌分类预测模型

&#x1f935;‍♂️ 个人主页&#xff1a;艾派森的个人主页 ✍&#x1f3fb;作者简介&#xff1a;Python学习者 &#x1f40b; 希望大家多多支持&#xff0c;我们一起进步&#xff01;&#x1f604; 如果文章对你有帮助的话&#xff0c; 欢迎评论 &#x1f4ac;点赞&#x1f4…

jmeter软件测试实验(附源码以及配置)

jmeter介绍 JMeter是一个开源的性能测试工具&#xff0c;由Apache软件基金会开发和维护。它主要用于对Web应用程序、Web服务、数据库和其他类型的服务进行性能测试。JMeter最初是为测试Web应用程序而设计的&#xff0c;但现在已经扩展到支持更广泛的应用场景。 JMeter 可对服务…