[译][AI OpenAI-doc] 函数调用 Beta

简介: 类似于聊天完成 API,助手 API 支持函数调用。函数调用允许您描述函数给助手 API,并让它智能地返回需要调用的函数及其参数。

类似于聊天完成 API,助手 API 支持函数调用。函数调用允许您描述函数给助手 API,并让它智能地返回需要调用的函数及其参数。

快速入门

在这个示例中,我们将创建一个天气助手,并定义两个函数,get_current_temperature 和 get_rain_probability,作为助手可以调用的工具。根据用户的查询,如果使用我们在 2023 年 11 月 6 日或之后发布的最新模型,模型将调用并行函数调用。在我们使用并行函数调用的示例中,我们将询问助手今天旧金山的天气如何以及下雨的几率。我们还展示了如何通过流式输出助手的响应。

步骤 1:定义函数

在创建您的助手时,您首先会在助手的 tools 参数下定义这些函数。

from openai import OpenAI
client = OpenAI()

assistant = client.beta.assistants.create(
  instructions="You are a weather bot. Use the provided functions to answer questions.",
  model="gpt-4-turbo",
  tools=[
    {
   
      "type": "function",
      "function": {
   
        "name": "get_current_temperature",
        "description": "Get the current temperature for a specific location",
        "parameters": {
   
          "type": "object",
          "properties": {
   
            "location": {
   
              "type": "string",
              "description": "The city and state, e.g., San Francisco, CA"
            },
            "unit": {
   
              "type": "string",
              "enum": ["Celsius", "Fahrenheit"],
              "description": "The temperature unit to use. Infer this from the user's location."
            }
          },
          "required": ["location", "unit"]
        }
      }
    },
    {
   
      "type": "function",
      "function": {
   
        "name": "get_rain_probability",
        "description": "Get the probability of rain for a specific location",
        "parameters": {
   
          "type": "object",
          "properties": {
   
            "location": {
   
              "type": "string",
              "description": "The city and state, e.g., San Francisco, CA"
            }
          },
          "required": ["location"]
        }
      }
    }
  ]
)

步骤 2:创建线程并添加消息

当用户开始对话时,创建一个线程,并随着用户提问,向线程添加消息。

thread = client.beta.threads.create()
message = client.beta.threads.messages.create(
  thread_id=thread.id,
  role="user",
  content="What's the weather in San Francisco today and the likelihood it'll rain?",
)

第三步:发起运行

当您在包含触发一个或多个函数的用户消息的线程上发起运行时,该运行将进入待处理状态。在处理完成后,运行将进入需要行动的状态,您可以通过检查运行的状态来验证。这表明您需要运行工具并提交它们的输出到助手,以继续运行执行。在我们的案例中,我们将看到两个工具调用,这表明用户查询导致了并行函数调用。

请注意,运行会在创建后的十分钟后过期。请确保在 10 分钟标记之前提交您的工具输出。

您将在 required_action 中看到两个工具调用,这表明用户查询触发了并行函数调用。

{
   
  "id": "run_qJL1kI9xxWlfE0z1yfL0fGg9",
  ...
  "status": "requires_action",
  "required_action": {
   
    "submit_tool_outputs": {
   
      "tool_calls": [
        {
   
          "id": "call_FthC9qRpsL5kBpwwyw6c7j4k",
          "function": {
   
            "arguments": "{
   "location": "San Francisco, CA"}",
            "name": "get_rain_probability"
          },
          "type": "function"
        },
        {
   
          "id": "call_RpEDoB8O0FTL9JoKTuCVFOyR",
          "function": {
   
            "arguments": "{
   "location": "San Francisco, CA", "unit": "Fahrenheit"}",
            "name": "get_current_temperature"
          },
          "type": "function"
        }
      ]
    },
    ...
    "type": "submit_tool_outputs"
  }
}

如何发起运行并提交工具调用将取决于您是否使用了流式处理,虽然在这两种情况下,所有工具调用都需要同时提交。然后,您可以通过提交您调用的函数的工具输出来完成运行。将 required_action 对象中引用的每个 tool_call_id 传递,以将输出与每个函数调用匹配。

使用流式处理

对于流式处理的情况,我们创建一个 EventHandler 类来处理响应流中的事件,并使用 Python 和 Node SDK 中的 "submit tool outputs stream" 助手一次性提交所有工具输出。

from typing_extensions import override
from openai import AssistantEventHandler

class EventHandler(AssistantEventHandler):
    @override
    def on_event(self, event):
      # Retrieve events that are denoted with 'requires_action'
      # since these will have our tool_calls
      if event.event == 'thread.run.requires_action':
        run_id = event.data.id  # Retrieve the run ID from the event data
        self.handle_requires_action(event.data, run_id)

    def handle_requires_action(self, data, run_id):
      tool_outputs = []

      for tool in data.required_action.submit_tool_outputs.tool_calls:
        if tool.function.name == "get_current_temperature":
          tool_outputs.append({
   "tool_call_id": tool.id, "output": "57"})
        elif tool.function.name == "get_rain_probability":
          tool_outputs.append({
   "tool_call_id": tool.id, "output": "0.06"})

      # Submit all tool_outputs at the same time
      self.submit_tool_outputs(tool_outputs, run_id)

    def submit_tool_outputs(self, tool_outputs, run_id):
      # Use the submit_tool_outputs_stream helper
      with client.beta.threads.runs.submit_tool_outputs_stream(
        thread_id=self.current_run.thread_id,
        run_id=self.current_run.id,
        tool_outputs=tool_outputs,
        event_handler=EventHandler(),
      ) as stream:
        for text in stream.text_deltas:
          print(text, end="", flush=True)
        print()


with client.beta.threads.runs.stream(
  thread_id=thread.id,
  assistant_id=assistant.id,
  event_handler=EventHandler()
) as stream:
  stream.until_done()

不使用流式处理

运行是异步的,这意味着您会希望通过轮询运行对象的状态,直到达到终端状态为止。为方便起见,“创建和轮询”SDK 助手在创建运行后会自动轮询其完成。一旦运行完成,您可以列出助手添加到线程中的所有消息。最后,您将从 required_action 中检索所有的 tool_outputs,并一次性将它们提交给“提交工具输出并轮询”助手。

run = client.beta.threads.runs.create_and_poll(
  thread_id=thread.id,
  assistant_id=assistant.id,
)

if run.status == 'completed':
  messages = client.beta.threads.messages.list(
    thread_id=thread.id
  )
  print(messages)
else:
  print(run.status)

# Define the list to store tool outputs
tool_outputs = []

# Loop through each tool in the required action section
for tool in run.required_action.submit_tool_outputs.tool_calls:
  if tool.function.name == "get_current_temperature":
    tool_outputs.append({
   
      "tool_call_id": tool.id,
      "output": "57"
    })
  elif tool.function.name == "get_rain_probability":
    tool_outputs.append({
   
      "tool_call_id": tool.id,
      "output": "0.06"
    })

# Submit all tool outputs at once after collecting them in a list
if tool_outputs:
  try:
    run = client.beta.threads.runs.submit_tool_outputs_and_poll(
      thread_id=thread.id,
      run_id=run.id,
      tool_outputs=tool_outputs
    )
    print("Tool outputs submitted successfully.")
  except Exception as e:
    print("Failed to submit tool outputs:", e)
else:
  print("No tool outputs to submit.")

if run.status == 'completed':
  messages = client.beta.threads.messages.list(
    thread_id=thread.id
  )
  print(messages)
else:
  print(run.status)

相关文章
|
人工智能 测试技术 API
PaperBench:OpenAI开源AI智能体评测基准,8316节点精准考核复现能力
PaperBench是OpenAI推出的开源评测框架,通过8316个评分节点系统评估AI智能体复现学术论文的能力,涵盖理论理解、代码实现到实验执行全流程。
1197 30
PaperBench:OpenAI开源AI智能体评测基准,8316节点精准考核复现能力
|
人工智能 自然语言处理 安全
💻 Codex 来了:OpenAI 推出多任务软件工程 AI 代理,开发者工作方式将被重塑?
Codex 是 OpenAI 推出的一款云端智能开发代理,基于优化后的 Codex-1 模型,能够执行从代码编写、Bug 修复到 PR 提交的完整工程任务。通过 ChatGPT 的界面,用户可向 Codex 分配任务,它将在独立沙盒中运行并返回结果。Codex 支持多任务异步处理,遵循项目规范(AGENTS.md),并生成日志与测试报告以确保透明性。作为“AI 参与式开发”的里程碑,Codex 不仅提升效率,还可能重塑开发者角色,使他们从具体编码转向指导 AI 完成任务,推动软件工程进入意图驱动的新时代。
2728 16
|
人工智能 搜索推荐 开发者
GPT-4o测评准确率竟不到1%!BrowseComp:OpenAI开源AI代理评测新基准,1266道高难度网络检索问题
OpenAI最新开源的BrowseComp基准包含1266个高难度网络检索问题,覆盖影视、科技、艺术等九大领域,其最新Deep Research模型以51.5%准确率展现复杂信息整合能力,为AI代理的浏览能力评估建立新标准。
1311 4
GPT-4o测评准确率竟不到1%!BrowseComp:OpenAI开源AI代理评测新基准,1266道高难度网络检索问题
|
人工智能 自然语言处理 测试技术
自然语言生成代码一键搞定!Codex CLI:OpenAI开源终端AI编程助手,代码重构+测试全自动
Codex CLI是OpenAI推出的轻量级AI编程智能体,基于自然语言指令帮助开发者高效生成代码、执行文件操作和进行版本控制,支持代码生成、重构、测试及数据库迁移等功能。
4268 1
自然语言生成代码一键搞定!Codex CLI:OpenAI开源终端AI编程助手,代码重构+测试全自动
|
人工智能 数据可视化 JavaScript
NodeTool:AI 工作流可视化构建器,通过拖放节点设计复杂的工作流,集成 OpenAI 等多个平台
NodeTool 是一个开源的 AI 工作流可视化构建器,通过拖放节点的方式设计复杂的工作流,无需编码即可快速原型设计和测试。它支持本地 GPU 运行 AI 模型,并与 Hugging Face、OpenAI 等平台集成,提供模型访问能力。
1502 14
NodeTool:AI 工作流可视化构建器,通过拖放节点设计复杂的工作流,集成 OpenAI 等多个平台
|
人工智能 自然语言处理 并行计算
ASAL:Sakana AI 联合 OpenAI 推出自动探索人工生命的系统,通过计算机模拟生命进化的过程
ASAL 是由 Sakana AI 联合 OpenAI 等机构推出的自动化搜索人工生命系统,基于基础模型实现多种搜索机制,扩展了人工生命研究的边界。
907 1
ASAL:Sakana AI 联合 OpenAI 推出自动探索人工生命的系统,通过计算机模拟生命进化的过程
|
Web App开发 人工智能 JavaScript
Nanobrowser:开源版OpenAI Operator!AI自动操控浏览器,复杂网页任务一键搞定
Nanobrowser 是一款开源的 Chrome 扩展工具,基于多智能体系统实现复杂的网页任务自动化,支持多种大型语言模型,完全免费且注重隐私保护。
2730 1
|
人工智能 编解码 机器人
OpenAI又出王炸了!正式推出超强AI视频模型Sora
OpenAI正式推出AI视频生成模型Sora,可根据文本提示生成逼真视频,面向美国及其他市场ChatGPT付费用户开放。Sora Turbo支持生成长达20秒的视频及多种变体,具备模拟物理世界的新兴能力,可创建多镜头视频,提供Remix和Storyboard等创新功能。
537 4
OpenAI又出王炸了!正式推出超强AI视频模型Sora
|
人工智能 搜索推荐 机器人
用户破4亿、企业客户翻倍!OpenAI的GPT-5将推进全球AI战争进入白热化阶段!
用户破4亿、企业客户翻倍!OpenAI的GPT-5将推进全球AI战争进入白热化阶段!

热门文章

最新文章