openai funciton calling使用

2024-05-05 21:04
文章标签 使用 openai calling funciton

本文主要是介绍openai funciton calling使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在 API 调用中,您可以描述函数,并让模型智能地选择输出包含调用一个或多个函数的参数的 JSON 对象。Chat Completions API不会调用该函数;相反,模型会生成 JSON,您可以使用它来调用代码中的函数。

本指南重点介绍使用聊天完成 API 进行函数调用,有关助手 API 中函数调用的详细信息,请参阅助手工具页面Assistants Tools page。

function calling的基本步骤

顺序如下:

  1. 使用用户查询和函数参数 functions parameter.中定义的一组函数来调用模型。

  2. 模型可以选择调用一个或多个函数;如果是这样,内容将是一个符合您的自定义架构的字符串化 JSON 对象(注意:模型可能会产生幻觉参数)。

  3. 在代码中将字符串解析为 JSON,并使用提供的参数(如果存在)调用函数。

  4. 通过将函数响应作为新消息附加来再次调用模型,并让模型将结果汇总返回给用户。

Supported models支持模型

并非所有模型版本都使用函数调用数据进行训练。以下模型支持函数调用: gpt-4-turbogpt-4-turbo-2024-04-09gpt-4-turbo-previewgpt-4-0125-previewgpt-4-1106-preview 、 < b5>、 gpt-4-0613gpt-3.5-turbogpt-3.5-turbo-0125gpt-3.5-turbo-1106gpt-3.5-turbo-0613

此外,以下模型支持并行函数调用: gpt-4-turbogpt-4-turbo-2024-04-09gpt-4-turbo-previewgpt-4-0125-previewgpt-4-1106-previewgpt-3.5-turbo-1106

Function calling behavior函数调用行为

tool_choice 的默认行为是 tool_choice: "auto" 。这让模型决定是否调用函数,如果调用,则调用哪些函数。

我们提供三种方法来根据您的用例自定义默认行为:

  1. 要强制模型始终调用一个或多个函数,可以设置 tool_choice: “required”。然后模型将选择要调用的函数。

  2. 要强制模型仅调用一个特定函数,可以设置 tool_choice: {“type”: “function”, “function”: {“name”: “my_function”}}。

  3. 要禁用函数调用并强制模型仅生成面向用户的消息,您可以设置 tool_choice: “none”。

Parallel function calling并行函数调用

并行函数调用是模型同时执行多个函数调用的能力,允许并行解决这些函数调用的效果和结果。如果函数需要很长时间,这尤其有用,并且可以减少 API 的往返次数。例如,模型可能会调用函数来同时获取 3 个不同位置的天气,这将导致在 tool_calls 数组中产生一条包含 3 个函数调用的消息,每个函数调用都有一个 id。要响应这些函数调用,请向对话中添加 3 条新消息,每条消息都包含一个函数调用的结果,并使用 tool_call_id 引用 tool_calls 中的 id。

在此示例中,我们定义了一个函数 get_current_weather 。模型多次调用该函数,并将函数响应发送回模型后,我们让它决定下一步。它回复了一条面向用户的消息,告诉用户旧金山、东京和巴黎的气温。根据查询,它可能会选择再次调用函数。

from openai import OpenAI
import jsonclient = 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 "tokyo" in location.lower():return json.dumps({"location": "Tokyo", "temperature": "10", "unit": unit})elif "san francisco" in location.lower():return json.dumps({"location": "San Francisco", "temperature": "72", "unit": unit})elif "paris" in location.lower():return json.dumps({"location": "Paris", "temperature": "22", "unit": unit})else:return json.dumps({"location": location, "temperature": "unknown"})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, 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-0125",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# 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 = client.chat.completions.create(model="gpt-3.5-turbo-0125",messages=messages,)  # get a new response from the model where it can see the function responsereturn second_responseprint(run_conversation())

out

daichang\.vscode\extensions\ms-python.debugpy-2024.6.0-win32-x64\bundled\libs\debugpy\adapter/../..\debugpy\launcher' '4336' '--' 'E:\OneDrive\aidev\openaidev\02FunctionCalling\get_weather.py'ChatCompletion(id='chatcmpl-9LTUxLZ36t55gdseSRMHYX8zfKv8N', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='The current weather in San Francisco is 72°F, in Tokyo it is 10°C, and in Paris it is 22°C.', role='assistant', function_call=None, tool_calls=None))], created=1714905307, model='gpt-3.5-turbo-0125', object='chat.completion', system_fingerprint='fp_a450710239', usage=CompletionUsage(completion_tokens=28, prompt_tokens=147, total_tokens=175))

这篇关于openai funciton calling使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/962677

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1