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

相关文章

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v