OpenAI ChatGPT-4开发笔记2024-03:Chat之Tool和Tool_Call(含前function call)

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和parameters

import json
import openai

#step 1: Define 2 functions: self-defined function and text completions
def get_weather(location, unit="fahrenheit"):
    if "beijing" in location.lower():
        return json.dumps({"location": location, "temperature": "11", "unit": "celsius"})
    elif "tokyo" in location.lower():
        return json.dumps({"location": location, "temperature": "33", "unit": "celsius"})
    else:
        return json.dumps({"location": location, "temperature": "22", "unit": "celsius"})

def chat_completions(parameter_message):
    
    response = openai.chat.completions.create(
        model    = "gpt-3.5-turbo-1106",
        messages = parameter_message,
        tools    = ai_function,
        tool_choice="auto",  # auto is default, but we'll be explicit
    )

    return response.choices[0].message

#step 2: Define parameters for text completion, and functions for transferring to Tools

ai_prompt = [{"role"   : "user",
              "content": "What's the weather in tokyo?"}]

ai_function = [
    {
        "type"    : "function",
        "function": {
            "name": "get_weather",
            "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"],
            },
        },
    }
]

第二步,第一轮chat completions

先做一个chat completions, 再由chat completion决定是否要调用function。

# step 3: first round call text completions, to get the response_message/tool_calls
first_response = chat_completions(ai_prompt)
tool_calls = first_response.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.

第三步,第一轮chat completions的结果加入prompt,再把function参数加入prompt,然后一起喂给chatgpt

    if tool_calls:
        available_functions = {
            "get_weather": get_weather,
        }  # only one function in this example, but you can have multiple
        ai_prompt.append(first_response)  # step 4: extend conversation with assistant's reply
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_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"),
            )
            ai_prompt.append(
                {
                    "tool_call_id": tool_call.id,
                    "role": "tool",
                    "name": function_name,
                    "content": function_response,
                }
            )  # step 5: extend conversation with function response
        print("\nfinal msg1 --> ", ai_prompt)
        second_response = chat_completions(ai_prompt)  # get a new response from the model where it can see the function response
        print("\n second_response --> ", second_response)  

得出结果:

ChatCompletionMessage(
	content='The weather in Tokyo is 33°C. Enjoy the sunny day!', 
	role='assistant', 
	function_call=None, 
	tool_calls=None)

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

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

考公还是互联网?

来源 花了 10 小时检索,汇总的有效信息 V2EX,牛客,Google,Bing,广东省人事考试网,国家公务员局,B站,小红书,知乎,掘金,Github,公务员…

Rollup-plugin-bundle-analyzer VS Rollup-plugin-visualizer

分析和可视化Rollup打包后的文件的插件 Rollup-plugin-bundle-analyzerRollup-plugin-visualizer Rollup-plugin-bundle-analyzer和Rollup-plugin-visualizer都是用于分析和可视化Rollup打包后的文件的插件,但它们在功能和使用方式上存在一些差异。 Rollup-plugi…

低成本高回报:如何利用免版素材库提升设计品质?

免版素材库起源于互联网的发展,是指一种包含大量图片、图标、字体等创意资源的网站或平台,这些资源多为设计师和相关行业人士创作,并免费提供给用户使用。免版素材库的资源通常遵循一定的授权协议,如CC0(Creative Comm…

Python pip 常用指令

前言 Python的pip是一个强大的包管理工具,它可以帮助我们安装、升级和管理Python的第三方库。以下是一些常用的pip指令。 1. 安装第三方库 使用pip安装Python库非常简单,只需要使用pip install命令,后面跟上库的名字即可。 # 安装virtuale…

【leetcode 447. 回旋镖的数量】审慎思考与推倒重来

447. 回旋镖的数量 题目描述 给定平面上 **n **对 互不相同 的点 points ,其中 points[i] [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。 返回平…

加速科技ST2500 数模混合信号测试设备累计装机量突破500台!

国产数字机,测试中国芯!新年伊始,国产半导体测试设备领军企业加速科技迎来了振奋人心的一刻,ST2500 数模混合信号测试设备累计装机量突破500台!加速科技凭借其持续的创新能力、完善的解决方案能力、专业热忱的本地化服…

企业级快速开发平台可以用在什么行业?优点多吗?

应用专业的企业级快速开发平台可以带来什么效果?目前,低代码技术平台在很多领域都获得了广泛应用和推广,在实现高效率办公、流程化办公和数字化发展中扮演了非常重要的角色,具有举足轻重的作用。针对这个话题,现在将给…

外汇天眼:台北妇女轻信假投资诈骗话术,小赚1万却惨赔1500万

当今社会物价急速上涨,许多民众为了避免资产因通膨缩水,纷纷开始寻找各种能增加收入的渠道,因此投资理财日渐受到重视。 然而,诈骗集团也注意到这趋势,并且推出虚假的投资平台或方案,以各种话术行骗。 不久…

【css】快速实现鼠标悬浮变色效果

<div class"nav-item"><div class"ic-img"></div><div>切换</div> </div>.nav-item {width: 100rem;height: 45rem;line-height: 45rem;display: flex;text-align: center;justify-content: center;align-items: cent…

用python提取word中的所有图片

使用word中提取的方式图片会丢失清晰度&#xff0c;使用python写一个脚本&#xff0c;程序运行将弹出对话框选择一个word文件&#xff0c;然后在弹出一个对话框选择一个文件夹保存word中的文件。将该word中的所有图片都保存成png格式&#xff0c;并命名成image_i的样式。 程序…

go image.DecodeConfig 和image.Decode 不能同时使用吗

问题场景&#xff1a;在同时使用go image.DecodeConfig 和image.Decode获取图片信息时&#xff0c;报错提示&#xff1a; 无法读取图像配置 image: unknown format package mainimport ("fmt""github.com/golang/freetype""image""image/d…

软件压测工具有哪些功能和特点

目前市场上有许多成熟的压测工具&#xff0c;开发人员可以根据自己的项目特点和需求选择合适的工具进行压力测试。本文将介绍软件压测工具的功能和特点&#xff1a; 一、软件压测工具定义 软件压测工具是一种专门设计用于模拟大量用户并发访问系统的工具。通过模拟真实场景中的…

1876_电感的特性小结

Grey 全部学习内容汇总&#xff1a; GitHub - GreyZhang/g_hardware_basic: You should learn some hardware design knowledge in case hardware engineer would ask you to prove your software is right when their hardware design is wrong! 1876_电感的特性小结 主要是…

服务器运维工具推荐——站长、运维必看!

服务器运维是确保服务器系统稳定运行并保持高效性的重要工作。为了提高运维工作的效率&#xff0c;使用一些优秀的服务器运维工具是非常必要的。使用了解多款运维工具后&#xff0c;总结了几款还不错的工具&#xff1a; 1、Zabbix &#x1f4d2;简介&#xff1a;Zabbix是一款开…

分析一个项目(微信小程序篇)二

目录 首页&#xff1a; 发现&#xff1a; 购物车&#xff1a; 我的&#xff1a; 分析一个项目讲究的是如何进行对项目的解析分解&#xff0c;进一步了解项目的整体结构&#xff0c;熟悉项目的结构&#xff0c;能够知道每个组件所处在哪个位置&#xff0c;发挥什么作用。 接…

U盘、硬盘无法打开,修复RAW磁盘或分区,硬盘变成raw格式如何恢复,数据恢复

本文持续更新&#xff0c;针对遇到的数据丢失问题进行详细记录 磁盘变成RAW的可能原因 突然断电或关机文件系统丢失或损坏病毒或恶意软件感染坏扇区磁盘损坏 以下解决方案针对非病毒损坏 通过Windows自带的工具进行恢复&#xff08;CHKDSK命令&#xff09; 1.连接硬盘 2.…

自动化测试框架搭建(流程详解)

说起自动化测试&#xff0c;我想大家都会有个疑问&#xff0c;要不要做自动化测试&#xff1f; 自动化测试给我们带来的收益是否会超出在建设时所投入的成本&#xff0c;这个嘛别说是我&#xff0c;即便是高手也很难回答&#xff0c;自动化测试的初衷是美好的&#xff0c;而测试…

用PreMaint引领先进的预测性维护

在设备维护领域&#xff0c;预测性维护成为一项利用先进技术和巧妙工具的数据驱动战略。这一战略通过条件监控和数据分析&#xff0c;以主动维护的方式识别潜在的设备缺陷&#xff0c;避免问题升级。高效使用PreMaint预测性维护工具可不仅节省时间和成本&#xff0c;更显著提升…

信息时代的品牌危机与应对之道:迅腾文化的价值“从心所欲不逾矩”

在瞬息万变的信息时代&#xff0c;企业品牌面临着时代的危机与挑战。在这个时代&#xff0c;自诩能穿透未来迷雾的先知已然无法满足企业的需求&#xff0c;而居安思危、行死而生的“惶者”才是企业所需要的。迅腾文化正是这样的存在&#xff0c;积极倾听企业&#xff0c;融汇未…

Linux第22步_安装CH340驱动和串口终端软件MobaXterm

开发板输出信息通常是采用串口&#xff0c;而计算机通常是USB接口&#xff0c;为了让他们之间能够交换数据&#xff0c;我们通常采用USB转串口的转换器来实现。目前市场上的串口转换器大多是采用CH340芯片来实现的&#xff0c;因此我们需要在计算中安装一个CH340驱动程序&#…
最新文章