当前位置: 首页 > news >正文

function call使用基础

以请求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 函数的实现来真正地获取天气信息。
 

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 手把手教你手写单例,六种实现方式一网打尽!
  • 【MySQL进阶之路】oracle 9i的经典测试雇员信息表案例——多表查询
  • WPF Mvvm
  • MySQL集群+Keepalived实现高可用部署
  • Hooks 「 useImperativeHandle 」子组件向父组件暴露方法
  • Dockerfile常用指令详解
  • 在NVIDIA jetson中使用jetson-ffmpeg调用硬件编解码加速处理
  • TCP的连接建立及报文段首部格式
  • ESP32-IDF 在 Ubuntu 下的配置
  • 【xilinx】Vivado 成功运行Ubuntu需要哪些 文件?
  • 微软RDL远程代码执行超高危漏洞(CVE-2024-38077)漏洞检测排查方式
  • JavaSE基础(12)——文件、递归、IO流
  • 未知单播泛洪原因
  • 日志审计Graylog 使用教程-kafka收取消息
  • 【数据结构】一篇讲清楚什么是堆? 带图食用超详细~
  • $translatePartialLoader加载失败及解决方式
  • 【Leetcode】104. 二叉树的最大深度
  • JavaScript服务器推送技术之 WebSocket
  • jquery cookie
  • js操作时间(持续更新)
  • JS数组方法汇总
  • React中的“虫洞”——Context
  • Spring Cloud Feign的两种使用姿势
  • 阿里云前端周刊 - 第 26 期
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 实习面试笔记
  • 使用common-codec进行md5加密
  • 微信小程序设置上一页数据
  • 怎样选择前端框架
  • MPAndroidChart 教程:Y轴 YAxis
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • # centos7下FFmpeg环境部署记录
  • ######## golang各章节终篇索引 ########
  • ###C语言程序设计-----C语言学习(3)#
  • #include
  • (delphi11最新学习资料) Object Pascal 学习笔记---第5章第5节(delphi中的指针)
  • (function(){})()的分步解析
  • (Python第六天)文件处理
  • (每日持续更新)jdk api之StringBufferInputStream基础、应用、实战
  • (十二)python网络爬虫(理论+实战)——实战:使用BeautfulSoup解析baidu热搜新闻数据
  • (十七)Flask之大型项目目录结构示例【二扣蓝图】
  • (太强大了) - Linux 性能监控、测试、优化工具
  • (转载)CentOS查看系统信息|CentOS查看命令
  • .net core webapi 部署iis_一键部署VS插件:让.NET开发者更幸福
  • .NET Core 控制台程序读 appsettings.json 、注依赖、配日志、设 IOptions
  • .NET Framework与.NET Framework SDK有什么不同?
  • .NET gRPC 和RESTful简单对比
  • .NET 材料检测系统崩溃分析
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
  • .NET项目中存在多个web.config文件时的加载顺序
  • // an array of int
  • @AutoConfigurationPackage的使用
  • @PreAuthorize注解
  • @四年级家长,这条香港优才计划+华侨生联考捷径,一定要看!
  • [ vulhub漏洞复现篇 ] JBOSS AS 5.x/6.x反序列化远程代码执行漏洞CVE-2017-12149