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的答案,循环多次之后得到最终答案。
相关文章:
OpenAI的Function calling 和 LangChain的Search Agent
OpenAI的Function calling openai最近发布的gpt-3.5-turbo-0613 和 gpt-4-0613版本模型增加了function calling的功能,该功能通过定义功能函数,gpt通过分析问题和函数功能描述来决定是否调用函数,并且生成函数对应的入参。函数调用的功能可以…...
【mysql数据库】MySQL7在Centos7的环境安装
说明: 安装与卸载中,用户全部切换成为root,⼀旦安装,普通用户就能使用。初期练习,mysql不进行用户管理,全部使⽤root进⾏,尽快适应mysql语句,后⾯学了用户管理,在考虑新…...
基于vue+element 分页的封装
目录标题 项目场景:认识分页1.current-page2.page-sizes3.page-size4.layout5.total6.size-change7.current-change 封装分页:创建paging:进行封装 页面中使用:引入效果 项目场景: 分页也是我们在实际应用当中非常常见…...
面试题模拟
C# 装箱和拆箱是什么? 装箱是指用堆空间来存放值类型数据 拆箱是指将存放在堆空间的值类型数据转换到栈空间 值和引用类型在变量赋值时的区别是什么? 值类型的数据赋值的时候是指向同一块内存区域,当前一个改变的时候后一个也会跟着改变。 引…...
Linux6.13 Docker LNMP项目搭建
文章目录 计算机系统5G云计算第四章 LINUX Docker LNMP项目搭建一、项目环境1.环境描述2.容器ip地址规划3.任务需求 二、部署过程1.部署构建 nginx 镜像2.部署构建 mysql 镜像3.部署构建 php 镜像4.验证测试 计算机系统 5G云计算 第四章 LINUX Docker LNMP项目搭建 一、项目…...
数据包协议栈处理
看了两个不错的帖子,记录一下。 4.2 TCP Segmentation Offload(TSO)_Remy的学习记录-CSDN博客_tcp-segmentation-offload Linux内核参数之rp_filter - 萝卜1992 - 博客园...
html刷新图片
文章目录 前言网页整体刷新改变图像的url 备注 前言 海思3516的一个开发板,不断的采集图像编码为jpeg,保存为同一个文件。打算用网页实现查看视频的效果,需要前端能够自动刷新。 目前找到了两个方法,一个是网页的不断刷新&#…...
PHP反序列化漏洞之魔术方法
一、魔术方法 PHP魔术方法(Magic Methods)是一组特殊的方法,它们在特定的情况下会被自动调用,用于实现对象的特殊行为或提供额外功能。这些方法的名称都以双下划线开头和结尾,例如: __construct()、__toString()等。 …...
2023年的深度学习入门指南(20) - LLaMA 2模型解析
2023年的深度学习入门指南(20) - LLaMA 2模型解析 上一节我们把LLaMA 2的生成过程以及封装的过程的代码简单介绍了下。还差LLaMA 2的模型部分没有介绍。这一节我们就来介绍下LLaMA 2的模型部分。 这一部分需要一些深度神经网络的基础知识,不懂的话不用着急…...
智能安全配电装置应用场景有哪些?
安科瑞 华楠 一、应用背景 电力作为一种清洁能源,给人们带来了舒适、便捷的电气化生活。与此同时,由于使用不当,维护不及时等原因引发的漏电触电和电气火灾事故,也给人们的生命和财产带来了巨大的威胁和损失。 为了防止低压配电…...
Rust vs Go:常用语法对比(四)
题图来自 Go vs. Rust performance comparison: The basics 61. Get current date 获取当前时间 package mainimport ( "fmt" "time")func main() { d : time.Now() fmt.Println("Now is", d) // The Playground has a special sandbox, so you …...
c++ 派生类 文本查询程序再探
Query_base类和Query类 //这是一个抽象基类,具体的查询类型从中派生,所有成员都是private的 class Query_base {friend class Query;protected:using line_no TextQuery::line_no;//用于level函数virtual ~Query_base() default;private://eval返回与…...
17. 电话号码的字母组合
题目描述 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 示例 1: 输入:digits "23" …...
Redis 基础知识和核心概念解析:理解 Redis 的键值操作和过期策略
🌷🍁 博主 libin9iOak带您 Go to New World.✨🍁 🦄 个人主页——libin9iOak的博客🎐 🐳 《面试题大全》 文章图文并茂🦕生动形象🦖简单易学!欢迎大家来踩踩~ἳ…...
Jenkins中sh函数的用法
在Jenkins的Pipeline中,sh函数的用法 用法一 单个命令字符串包括使用,示例如下: sh echo "Hello, Jenkins!"用法二 多个命令字符串包括命令列表使用,示例如下: sh echo "Step 1" echo "…...
Android 之 Canvas API 详解 (Part 3) Matrix 和 drawBitmapMesh
本节引言: 在Canvas的API文档中,我们看到这样一个方法:drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) 这个Matrix可是有大文章的,前面我们在学Paint的API中的ColorFilter中曾讲过ColorMatrix 颜色矩阵,一个4…...
基于Ubuntu 22.04 编译chip-tool工具
前言 编译过程有点曲折,做下记录,过程中,有参考别人写的博客,也看github 官方介绍,终于跑通了~ 环境说明: 首先需要稳定的梯子,可以访问“外网”ubuntu 环境,最终成功实验在Ubunt…...
opencv-17 脸部打码及解码
使用掩模和按位运算方式实现的对脸部打码、解码实例 代码如下: import cv2 import numpy as np #读取原始载体图像 lenacv2.imread("lena.png",0) #读取原始载体图像的 shape 值 r,clena.shape masknp.zeros((r,c),dtypenp.uint8) mask[220:400,250:350…...
JVM分享
JVM分享 官网:https://docs.oracle.com/javase/specs/jvms/se8/html/index.html Java代码的执行流程 我们编写完之后的java文件如果要运行,java文件会编译成class文件,在jvm中运行时ClassLoader会加载class文件,加载进来之后&a…...
Apache Dubbo CVE-2021-36162 挖掘过程
01 漏洞背景 发现该漏洞的起因是在分析 CVE-2021-30181 的脚本注入补丁的时候,意外发现了几个已被修复的 yaml 反序列化漏洞,还以为是未公开的Nday,查询后发现其实对应的是 CVE-2021-30180 漏洞的修复代码。通过查看补丁可以知道,…...
用快马AI十分钟搭建班级宠物园应用下载页,快速验证教育产品原型
最近在帮小学老师朋友设计一个班级宠物园应用,想快速验证这个教育产品的可行性。传统开发流程太耗时,于是尝试用InsCode(快马)平台的AI生成功能,十分钟就搭出了可交互的下载页原型。分享下具体实现思路: 需求拆解与框架搭建 先明确…...
Dunst未来发展方向:探索轻量级通知守护进程的创新路线图
Dunst未来发展方向:探索轻量级通知守护进程的创新路线图 【免费下载链接】dunst Lightweight and customizable notification daemon 项目地址: https://gitcode.com/gh_mirrors/du/dunst Dunst作为一款轻量级且高度可定制的通知守护进程,始终致力…...
MKVToolNix Batch Tool 全功能指南:从批量处理到生态协作
MKVToolNix Batch Tool 全功能指南:从批量处理到生态协作 【免费下载链接】mkvtoolnix-batch-tool Batch video and subtitle processing program with the ability to add, remove, or extract subtitles from all video files in a directory and its sub-directo…...
开发实战:asp.net core + ef core 实现动态可扩展的分页方案
统一请求参数先定义一个公共的 QueryParameters 解决这个问题:public class QueryParameters{private const int MaxPageSize 100;private int _pageSize 10;public int PageNumber { get; set; } 1;// 限制最大值,防止前端传一个很大数值把数据库搞崩…...
Ubuntu下MPI安装全攻略:从gcc到mpif90的完整配置流程
Ubuntu下MPI并行计算环境搭建实战指南 从零开始构建高性能计算基础环境 在科学计算和工程仿真领域,并行计算已经成为突破单机性能瓶颈的关键技术。作为最流行的消息传递接口标准,MPI(Message Passing Interface)让研究人员能够在集…...
VibeVoice保姆级教程:从部署到实战,打造你的专属语音助手
VibeVoice保姆级教程:从部署到实战,打造你的专属语音助手 1. 引言:为什么选择VibeVoice? 想象一下,你正在开发一个需要语音交互的应用,或者想为视频内容添加专业配音,又或者需要为视障用户提供…...
星图平台快速部署Qwen3-VL:30B:Ubuntu20.04环境配置全攻略
星图平台快速部署Qwen3-VL:30B:Ubuntu20.04环境配置全攻略 想在Ubuntu系统上快速部署强大的多模态AI模型?本文手把手教你从零开始配置星图GPU平台环境,30分钟搞定Qwen3-VL:30B部署! 1. 开篇:为什么选择这个部署方案 最…...
根据DNI、角度、光伏板参数等计算24小时光伏功率输出并用matlab编写MPPT追踪算法研究(Matlab代码实现)
💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 ⛳️座右铭&a…...
qmc-decoder:QMC加密音乐格式转换工具的全方位应用指南
qmc-decoder:QMC加密音乐格式转换工具的全方位应用指南 【免费下载链接】qmc-decoder Fastest & best convert qmc 2 mp3 | flac tools 项目地址: https://gitcode.com/gh_mirrors/qm/qmc-decoder 一、问题引入:当音乐文件被"锁住"…...
OneAPI开源大模型网关部署:支持国产数据库(达梦/人大金仓)存储用户与渠道数据
OneAPI开源大模型网关部署:支持国产数据库(达梦/人大金仓)存储用户与渠道数据 1. 引言:为什么你需要一个统一的大模型网关? 如果你正在使用或者计划使用大模型,大概率会遇到这样的烦恼:每个厂…...
