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并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔

SQL中JOIN操作的条件使用总结与实践

《SQL中JOIN操作的条件使用总结与实践》在SQL查询中,JOIN操作是多表关联的核心工具,本文将从原理,场景和最佳实践三个方面总结JOIN条件的使用规则,希望可以帮助开发者精准控制查询逻辑... 目录一、ON与WHERE的本质区别二、场景化条件使用规则三、最佳实践建议1.优先使用ON条件2.WHERE用

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma