function call使用基础

server/2024/9/23 6:55:02/

以请求GPT4 api为例子进行展示,

当使用GPT-4这样的模型并通过API调用来实现功能调用(function call)时,你可以构建一个请求,其中包含特定的指令和参数以调用外部函数。下面是一个使用GPT-4 API实现功能调用的例子,假设你已经有了访问GPT-4 API的有效方式。
示例场景:
假设你需要构建一个简单的聊天机器人,它可以回答关于天气的问题。当用户询问某个城市的天气时,该机器人会调用一个外部函数来获取天气信息,并将结果返回给用户。
请求数据示例:
{
  "model": "gpt-4",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant that can call external functions. If the user asks about the weather, you should use the 'get_weather' function to retrieve the information."
    },
    {
      "role": "user",
      "content": "What's the weather like in New York today?"
    }
  ],
  "functions": [
    {
      "name": "get_weather",
      "description": "Get the weather in a specific city.",
      "parameters": {
        "type": "object",
        "properties": {
          "city": {
            "type": "string",
            "description": "The city name"
          }
        },
        "required": ["city"]
      }
    }
  ],
  "function_call": "auto"
}

解释:
1. 系统消息 (role: "system") - 定义了助手的角色以及何时调用哪个函数。
2. 用户消息 (role: "user") - 用户询问的问题。
3. 功能定义 (functions) - 定义了可被调用的函数及其参数。
4. 函数调用 (function_call: "auto") - 指示API自动选择合适的函数来响应用户的消息。
响应数据示例:
假设GPT-4选择了调用 get_weather 函数,那么它会返回一个类似下面的响应:
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652939,
  "model": "gpt-4",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "function_call": {
          "name": "get_weather",
          "arguments": "{\"city\": \"New York\"}"
        }
      },
      "finish_reason": "function_call"
    }
  ]
}

处理响应:
当你收到上述响应后,你需要调用 get_weather 函数并将结果传回给API。这通常需要编写一些额外的代码来处理这些交互。例如,在Python中,你可以这样做:
import openai

# 设置OpenAI API密钥
openai.api_key = "your-api-key"

def get_weather(city):
    # 假设这是一个真实的天气API调用
    return {"city": city, "temperature": "20°C", "forecast": "sunny"}

# 发送请求并处理响应
response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that can call external functions. If the user asks about the weather, you should use the 'get_weather' function to retrieve the information."},
        {"role": "user", "content": "What's the weather like in New York today?"}
    ],
    functions=[
        {
            "name": "get_weather",
            "description": "Get the weather in a specific city.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "The city name"
                    }
                },
                "required": ["city"]
            }
        }
    ],
    function_call="auto"
)

# 获取函数调用的结果
function_call = response.choices[0].message.function_call
function_name = function_call.name
function_args = json.loads(function_call.arguments)

# 调用函数并获取结果
result = get_weather(function_args.get("city"))

# 再次发送请求,这次是将函数调用的结果发送回去
response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that can call external functions. If the user asks about the weather, you should use the 'get_weather' function to retrieve the information."},
        {"role": "user", "content": "What's the weather like in New York today?"},
        {"role": "assistant", "content": None, "function_call": {"name": "get_weather", "arguments": "{\"city\": \"New York\"}"}},
        {"role": "function", "name": "get_weather", "content": json.dumps(result)}
    ]
)

# 输出最终的回复
print(response.choices[0].message.content)

请注意,上述示例代码中的 openai.ChatCompletion.create 方法调用是基于 OpenAI API 的,你需要安装 openai 库并设置你的API密钥。此外,你需要根据实际情况调整 get_weather 函数的实现来真正地获取天气信息。
 


http://www.ppmy.cn/server/104986.html

相关文章

判别分析1|距离分类器

判别分析简介 判别分析背景介绍 为了理解什么是判别分析,看下面两个例子: 例1: 银行为了对贷款进行管理,需要预测哪些类型的客户可能不会按时归还贷款(不可靠客户)。通过历史数据收集若干客户的个人信息&…

2024年架构设计师论文-“大数据处理架构及其应用”

论大数据lambda架构 大数据处理架构是专门用于处理和分析巨量复杂数据集的软件架构。它通常包括数据收集、存储、处理、分析和可视化等多个层面,旨在从海量、多样化的数据中提取有价值的信息。Lambda架构是大数据平台里最成熟、最稳定的架构,它是一种将批…

R 语言学习教程,从入门到精通,R 绘图饼图(22)

1、R 绘图 饼图 R 语言提供来大量的库来实现绘图功能。 饼图,或称饼状图,是一个划分为几个扇形的圆形统计图表,用于描述量、频率或百分比之间的相对关系。 R 语言使用 pie() 函数来实现饼图,语法格式如下: pie(x, la…

《第二十七章 性能优化 - 内存优化》

一、引言 在 Android 应用开发中,性能优化是至关重要的一环。良好的性能不仅能提升用户体验,还能减少应用崩溃的概率。其中,内存优化是性能优化的关键部分。在本章中,我们将重点探讨如何避免内存泄漏以及进行图片内存优化。 二、避…

TOMCAT-企业级WEB应用服务器

一 WEB技术 1.1 HTTP协议和B/S 结构 HTTP(HyperText Transfer Protocol)协议即超文本传输协议,是用于在万维网(WWW)上传输超文本内容的基础协议。 一、HTTP 协议的特点 1、简单快速 客户向服务器请求服务时&#…

ARM架构的BootLoader详解——对于Linux与Baremetal(裸机MCU)

BootLoader(引导加载器)是启动嵌入式系统时执行的第一个程序,位于固件中。它主要负责初始化系统硬件、加载操作系统,并将控制权转移到操作系统的启动过程。 关于Linux 引导加载程序的引入 嵌入式Linux系统从软件角度可以分为四…

探索Edge-TTS与WebSocket集成:打造实时语音交互系统

本文为实现 WebSocket 将文本转换为语音并返回 Base64 数据给 Vue 客户端【干货】 在本文中,我们将构建一个简单的系统,该系统能够接收文本输入,通过 Microsoft Edge 的文本到语音服务(Edge TTS)转换为语音&#xff0c…

element组件封装

1.上传组件 <!--文件上传组件--> <template><div class"upload-file"><el-uploadref"fileUpload"v-if"props.type default":action"baseURL other.adaptationUrl(props.uploadFileUrl)":before-upload"h…