OpenAI ChatGPT-4开发笔记2024-03:Chat之Function Calling/Function/Tool/Tool_Choice

Updates on Function Calling were a major highlight at OpenAI DevDay.

In another world,原来的function call都不再正常工作了,必须全部重写。

function和function call全部由tool和tool_choice取代。2023年11月之前关于function call的代码都准备翘翘。

干嘛要整个tool出来取代function呢?原因有很多,不再赘述。作为程序员,我们真正关心的是:怎么改?

简单来说,就是整合chatgpt的能力和你个人的能力通过这个tools。怎么做呢?

第一步,定义你的function,最高指示是啥?

import json
from openai import OpenAI
client = OpenAI()# Example dummy function hard coded to return the same weather
# In production, this could be your backend API or an external API
def get_current_weather(location, unit="fahrenheit"):"""Get the current weather in a given location"""if "beijing" in location.lower():return json.dumps({"location": location, "temperature": "10", "unit": "celsius"})elif "tokyo" in location.lower():return json.dumps({"location": location, "temperature": "22", "unit": "celsius"})elif "shanghai" in location.lower():return json.dumps({"location": location, "temperature": "21", "unit": "celsius"})elif "san francisco" in location.lower():return json.dumps({"location": location, "temperature": "72", "unit": "fahrenheit"})else:return json.dumps({"location": location, "temperature": "22.22", "unit": "celsius"})

第二步,调用chatgpt模型

让chatgpt干活儿。问问chatgpt啥情况

def run_conversation():# Step 1: send the conversation and available functions to the modelmessages = [{"role": "user", "content": "What's the weather like in San Francisco, Tokyo, Beijing and Paris?"}]tools = [{"type": "function","function": {"name": "get_current_weather","description": "Get the current weather in a given location","parameters": {"type": "object","properties": {"location": {"type": "string","description": "The city and state, e.g. San Francisco, CA",},"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},},"required": ["location"],},},}]response = client.chat.completions.create(model="gpt-3.5-turbo-1106",messages=messages,tools = tools,tool_choice="auto",  # auto is default, but we'll be explicit)response_message = response.choices[0].messagetool_calls = response_message.tool_calls

tool_choice参数让chatgpt模型自行决断是否需要function介入。
response是返回的object,message里包含一个tool_calls array.

tool_calls array The tool calls generated by the model, such as function calls.
id string The ID of the tool call.
type string The type of the tool. Currently, only function is supported.
function object:  The function that the model called.name: string The name of the function to call.arguments: string The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.

第三步,chatgpt判断如果需要function介入,传回一个json对象。

    # Step 2: check if the model wanted to call a functionif tool_calls:# Step 3: call the function# Note: the JSON response may not always be valid; be sure to handle errorsavailable_functions = {"get_current_weather": get_current_weather,}  # only one function in this example, but you can have multiplemessages.append(response_message)  # extend conversation with assistant's reply# Step 4: send the info for each function call and function response to the modelfor tool_call in tool_calls:function_name = tool_call.function.namefunction_to_call = available_functions[function_name]function_args = json.loads(tool_call.function.arguments)function_response = function_to_call(location=function_args.get("location"),unit=function_args.get("unit"),)messages.append({"tool_call_id": tool_call.id,"role": "tool","name": function_name,"content": function_response,})  # extend conversation with function responsesecond_response = openai.chat.completions.create(model="gpt-3.5-turbo-1106",messages=messages,)  # get a new response from the model where it can see the function responsereturn second_response
print(run_conversation())    

我们把这个传回的json,叠加在message里面,再调用chatgpt模型。得出结果:

ChatCompletion(id='chatcmpl-8ciuEU38jFKJcjEbQH66ejGNnp0kO', 
choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(
content="Currently, the weather in San Francisco, California is 72°F (22°C) with a slight breeze. In Tokyo, Japan, the temperature is 22°C with partly cloudy skies. In Beijing, China, it's 10°C with overcast conditions. And in Paris, France, the temperature is 22.22°C with clear skies.", 
role='assistant', function_call=None, tool_calls=None))], 
created=1704239774, model='gpt-3.5-turbo-1106', object='chat.completion', system_fingerprint='fp_772e8125bb', usage=CompletionUsage(completion_tokens=71, prompt_tokens=229, total_tokens=300))

tool和tool_choice,取代了过去的function和function calling。
在这里插入图片描述

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

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

相关文章

【Java EE初阶八】多线程案例(计时器模型)

1. java标准库的计时器 1.1 关于计时器 计时器类似闹钟,有定时的功能,其主要是到时间就会执行某一操作,即可以指定时间,去执行某一逻辑(某一代码)。 1.2 计时器的简单介绍 在java标准库中,提供…

web前端之web前端

MENU web前端之原生实现分时函数、分时间段渲染页面,而不是等到所有操作都执行结束才渲染页面、提高用户体验web前端之原生实现树形目录结构、一维数组生成多维数组、无限级菜单目录 web前端之原生实现分时函数、分时间段渲染页面,而不是等到所有操作都执…

JS 文件导出,jszip多文件压缩导出

文章目录 JS 文件导出,jszip压缩导出1、单个文件导出2、压缩导出3、axios请求通过地址获取Blob源数据 JS 文件导出,jszip压缩导出 1、单个文件导出 let urlhttp://~.png // 可直接访问地址 // 当源数据为blob时 // url window.URL.createObjectURL(bl…

已经在datagrip或navicate等数据库管理工具连接上了mysql8.0,但是现在忘记了,怎么快速重置密码

直接在datagrip的查询终端中,执行这条sql,其中123456为你的新密码。 ALTER USER rootlocalhost IDENTIFIED BY 123456;

新手可理解的PyTorch线性层解析:神经网络的构建基石

目录 torch.nn子模块Linear Layers详解 nn.Identity Identity 类描述 Identity 类的功能和作用 Identity 类的参数 形状 示例代码 nn.Linear Linear 类描述 Linear 类的功能和作用 Linear 类的参数 形状 变量 示例代码 nn.Bilinear Bilinear 类的功能和作用 B…

国家信息安全水平等级考试NISP二级题目卷⑥(包含答案)

国家信息安全水平等级考试NISP二级题目卷(六) 国家信息安全水平等级考试NISP二级题目卷(六)需要报考咨询可以私信博主! 前言: 国家信息安全水平考试(NISP)二级,被称为校园版”CISP”,由中国信息…

用友U8 Cloud smartweb2.RPC.d XML外部实体注入漏洞

产品介绍 用友U8cloud是用友推出的新一代云ERP,主要聚焦成长型、创新型、集团型企业,提供企业级云ERP整体解决方案。它包含ERP的各项应用,包括iUAP、财务会计、iUFO cloud、供应链与质量管理、人力资源、生产制造、管理会计、资产管理&#…

基于gamma矫正的照片亮度调整(python和opencv实现)

import cv2 import numpy as npdef adjust_gamma(image, gamma1.0):invGamma 1.0 / gammatable np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8")return cv2.LUT(image, table)# 读取图像 original cv2.imread("tes…

影视仓最新配置接口2024tvbox源配置地址

影视仓是在TVBox开源代码基础上开发的优质版本,安装后需要配置接口才能正常使用。影视仓"内置版"是开发者做的资源内置化修改版本,不用自行设置接口,安装后即可使用。 影视仓的接口配置方法与TVBOX一样,区别在于影视仓…

Winform工具箱控件MenuStrip

MenuStrip是菜单栏 ComboBox是下拉框 TextBox是文本框 DataGridView是数据表 TextBox是文本框,大小可以调节,可以是单行,也可以是多行,通过右上角的小三角可以修改。 这个文本在编辑的时候可以在属性的Text中点击右边的小三角来换…

卷积神经网络|导入图片

在学习卷积神经网络时,我们通常使用的就是公开的数据集,这里,我们不使用公开数据集,直接导入自己的图片数据,下面,就简单写个程序实现批量图片的导入。 import osfrom PIL import Imageimport numpy as np…

【docker】使用 Dockerfile 构建镜像

一、什么是Dockerfile Dockerfile 是用于构建 Docker 镜像的文本文件。它包含了一系列的指令,用于描述如何构建镜像的步骤和配置。 通过编写 Dockerfile,您可以定义镜像的基础环境、安装软件包、复制文件、设置环境变量等操作。Dockerfile 提供了一种可…

Prometheus实战篇:Prometheus监控redis

准备环境 docker-compose安装redis docker-compose.yaml version: 3 services:redis:image:redis:5container_name: rediscommand: redis-server --requirepass 123456 --maxmemory 512mbrestart: alwaysvolumes:- /data/redis/data: /dataport:- "6379:6379"dock…

Python基础(十七、函数进阶用法)

文章目录 一、函数的回顾二、函数的进阶用法1.多个返回值示例,获取验证码及用户名示例,获取用户信息 2.多种参数1.位置参数2.关键字参数3.缺省参数4.不定长参数 3.匿名函数函数作为参数传递lambda匿名函数(一行代码) 总结练习题目: 之前学习了…

JAVA版随机抽人

主函数 public class Main {public static void main(String[] args) {//这里存入数据String[] data {"土一","李二","张三","李四","乔冠宇","王五"};MyJFrame frame new MyJFrame(data);} }界面类 import j…

leetcode 动态规划(斐波那契数列、 爬楼梯、使用最小花费爬楼梯)

509. 斐波那契数 斐波那契数,通常用 F(n) 表示,形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) 0,F(1) 1 F(n) F(n - 1) F(n - 2),其中 n …

【React系列】Portals、Fragment

本文来自#React系列教程:https://mp.weixin.qq.com/mp/appmsgalbum?__bizMzg5MDAzNzkwNA&actiongetalbum&album_id1566025152667107329) Portals 某些情况下,我们希望渲染的内容独立于父组件,甚至是独立于当前挂载到的DOM元素中&am…

GPU连通域分析方法

第1章连通域分析方法 连通域分析方法用于提取图像中相似属性的区域,并给出区域的面积,位置等特征信息。分为两种,基于游程(Runlength),和基于标记(Label)。 基于游程的方法,按照行对图像进行游…

3D Gaussian Splatting复现

最近3D Gaussian Splatting很火,网上有很多复现过程,大部分都是在Windows上的。Linux上配置环境会方便简单一点,这里记录一下我在Linux上复现的过程。 Windows下的环境配置和编译,建议看这个up主的视频配置,讲解的很细…

[算法与数据结构][python]:Python参数传递,“值传递”还是“引用传递“?

Python中的函数参数传递方式是“传对象引用”,可以理解为“值传递”和“引用传递”的混合体。 在Python中,所有的数据类型都是对象。如果函数参数是不可变对象(如整数、字符串、元组),那么传递的就是对象的值&#xf…