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 model
    messages = [{"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].message
    tool_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 function
    if tool_calls:
        # Step 3: call the function
        # Note: the JSON response may not always be valid; be sure to handle errors
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # only one function in this example, but you can have multiple
        messages.append(response_message)  # extend conversation with assistant's reply
        # Step 4: send the info for each function call and function response to the model
        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"),
            )
            messages.append(
                {
                    "tool_call_id": tool_call.id,
                    "role": "tool",
                    "name": function_name,
                    "content": function_response,
                }
            )  # extend conversation with function response
        second_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 response
        return 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.mfbz.cn/a/293858.html

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

相关文章

新耀莱要约收购接近尾声,此前共有4713万股接纳要约

新耀莱要约收购事件近期即将结束,引起了资本市场的广泛关注和讨论。作为曾经在汽车经销领域风光无限的企业,新耀莱如今面临衰退的结局,确实令人唏嘘。从财务数据的恶化到核心业务的萎靡,新耀莱的经营表现已无法令人乐观。而随着公司要约收购临近尾声,不少投资者都在担忧,新耀莱…

HTML5+CSS3小实例:文字涂抹动画

实例:文字涂抹动画 技术栈:HTML+CSS 效果: 源码: 【HTML】 <!DOCTYPE html> <html lang="zh-CN"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><me…

后端开发——JDBC的学习(三)

本篇继续对JDBC进行总结&#xff1a; ①通过Service层与Dao层实现转账的练习&#xff1b; ②重点&#xff1a;由于每次使用连接就手动创建连接&#xff0c;用完后就销毁&#xff0c;这样会导致资源浪费&#xff0c;因此引入连接池&#xff0c;练习连接池的使用&#xff1b; …

太阳能组件紫外预处理试验箱

太阳能组件紫外预处理试验箱波长范围&#xff1a;280-400nm用于太阳能光伏组件的温湿度及相类似紫外预处理环境的试验&#xff0c;主要用于太阳能组件材料评估诸如聚合物和保护层等材料抗紫外辐照能力&#xff0c;在预处理试验过程中能够快速、真实地再现阳光、雨、露等环境及对…

Etcd安装以及操作

Etcd介绍 etcd 是一个高度一致的分布式键值 (key-value) 存储&#xff0c;它提供了一种可靠的方式来存储需要由分布式系统或机器集群访问的数据。它可以优雅地处理网络分区期间的领导者选举&#xff0c;即使在 领导者节点中也可以容忍机器故障。 etcd 是用 Go 语言编写的&a…

Spring MVC响应结合RESTful风格开发,打造具有强大功能和良好体验的Web应用!

响应与Rest风格 1.11.1.1 环境准备步骤1:设置返回页面步骤2:启动程序测试 1.1.2 返回文本数据步骤1:设置返回文本内容步骤2:启动程序测试 1.1.3 响应JSON数据响应POJO对象响应POJO集合对象 知识点1&#xff1a;ResponseBody 2&#xff0c;Rest风格2.1 REST简介2.2 RESTful入门案…

Linux上搭建YApi

YApi是http接口管理和测试的重要工具&#xff0c;其作用相当于原来用的postman&#xff0c;但是比postman有更多的功能&#xff0c;本篇文章主要介绍如何在linux环境中快速的安装&#xff08;利用yum命令安装&#xff09;和部署YApi 一、nodejs 安装 1.1 下载nodejs包 yum i…

iPaaS与ETL:了解它们的主要区别

平均每个组织使用 130 多个应用程序&#xff0c;这一数字同比增长 30%。 随着公司试图充分利用其不断增长的应用程序生态系统&#xff0c;他们已经转向可以集成它们和/或其数据的工具。两个常用选项包括集成平台即服务 &#xff08;iPaaS&#xff09; 和提取、传输、加载 &…

pytorch08:学习率调整策略

目录 一、为什么要调整学习率&#xff1f;1.1 class _LRScheduler 二、pytorch的六种学习率调整策略2.1 StepLR2.2 MultiStepLR2.3 ExponentialLR2.4 CosineAnnealingLR2.5 ReduceLRonPlateau2.6 LambdaLR 三、学习率调整小结四、学习率初始化 一、为什么要调整学习率&#xff…

宝宝洗衣机哪个牌子质量好?好用的小型洗衣机推荐

当婴儿的到来&#xff0c;确实会给家庭带来许多变化&#xff0c;就好比如对于宝宝相关衣物的清洗需求。对于新生儿及婴幼儿的衣服&#xff0c;一般都要给予特殊的照顾与清洗&#xff0c;以保证不含细菌及过敏原。尤其是刚刚出生的婴儿&#xff0c;这时候宝宝们的皮肤很是幼嫩。…

JAVA基础学习笔记-day12-泛型

JAVA基础学习笔记-day12-泛型 1. 泛型概述1.1 泛型的引入 2. 使用泛型举例2.1 集合中使用泛型2.2 相关使用说明 3. 自定义泛型结构3.1 泛型的基础说明3.2 自定义泛型类或泛型接口3.2.1 说明3.2.2 注意 3.3 自定义泛型方法3.3.1 说明 4. 泛型在继承上的体现5. 通配符的使用5.1 通…

MySQL面试题汇总

常规&#xff1a; 1、数据库三大范式 1NF : 表中字段的数据不可再拆分。(原子性)2NF : 在满足第一范式的情况下&#xff0c;遵循唯一性&#xff0c;消除部分依赖。即&#xff0c;表中任意一个主键或任意一组联合主键&#xff0c;可以确定除该主键外的所有的非主键值。(一个表…

(适趣AI)Vue笔试题

&#x1f4d1;前言 本文主要是【Vue】——&#xff08;适趣AI&#xff09;Vue笔试题的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是听风与他&#x1f947; ☁️博客首页&#xff1a;CSDN主页听风与他 …

Android studio报错误提示 Some Kotlin libraries attached to this project 问题解决方案

前些天发现了一个蛮有意思的人工智能学习网站,8个字形容一下"通俗易懂&#xff0c;风趣幽默"&#xff0c;感觉非常有意思,忍不住分享一下给大家。 &#x1f449;点击跳转到教程 Android新建项目后&#xff0c;报以下错误 错误提示内容为&#xff1a; 这个项目附带的一…

pygame学习(二)——绘制线条、圆、矩形等图案

导语 pygame是一个跨平台Python库(pygame news)&#xff0c;专门用来开发游戏。pygame主要为开发、设计2D电子游戏而生&#xff0c;提供图像模块&#xff08;image&#xff09;、声音模块&#xff08;mixer&#xff09;、输入/输出&#xff08;鼠标、键盘、显示屏&#xff09;模…

Spring Boot 与 Spring 框架的区别

一、前言 Spring Boot 和 Spring 框架是由 Spring 项目提供的两个关键的技术栈&#xff0c;它们在 Java 开发中扮演着不同的角色。在阐述其区别之前&#xff0c;我们先大致了解下这两个框架 二、Spring 框架 1、背景 Spring 框架是一个全栈的企业应用开发框架&#xff0c;起…

营销的尽头是矩阵!如何通过小魔推短视频矩阵快速破圈?

“ 营销的尽头是矩阵&#xff01; 相信很多做互联网的朋友都听过这么一句话 在抖音上我们看到过大批的博主&#xff0c;都是通过矩阵的方式火遍全网&#xff0c;就比如张琦、小杨哥等等&#xff0c;矩阵的方式适用于大多数的实体品牌&#xff0c;以及个人IP 等&#xff0c…

DevOps(3)

目录 11.描述root账户&#xff1f; 12.如何在发出命令时打开命令提示符&#xff1f; 14.Linux系统下交换分区的典型大小是多少&#xff1f; 15.什么是符号链接&#xff1f; 11.描述root账户&#xff1f; root账户就像一个系统管理员账户&#xff0c;允许你完全控制系统。 …

目标跟踪算法中的卡尔曼滤波学习

在使用多目标跟踪算法时&#xff0c;接触到卡尔曼滤波&#xff0c;一直没时间总结下&#xff0c;现在来填坑。 1. 背景知识 在理解卡尔曼滤波前&#xff0c;有几个概念值得考虑下&#xff1a;时序序列模型&#xff0c;滤波&#xff0c;线性动态系统 1. 时间序列模型 时间序…

AspectJ入门(二)— 应用

AspectJ便于调试、测试和性能调整工作。定义的行为范围从简单的跟踪到分析&#xff0c;再到应用程序内部一致性到测试。AspectJ可以干净地模块化这类功能&#xff0c;从而可以在需要时轻松地启用和禁用这些功能。 1 基础 本节将继续介绍AspectJ到一些基础功能&#xff0c;为后…
最新文章