OpenAI API 从 Chat Completions 迁移到 Responses

2026-11-09 16:21 更新

Responses API是在Chat Completions基础上演进的API基本接口,让集成更简单,并提供强大的智能体基础能力。

Chat Completions仍受支持;所有新项目建议采用Responses。

关于Responses API

Responses为功能强大的智能体应用提供统一接口,包括:

Responses的优势

相对于Chat Completions,Responses具有以下优势:

  • 更好的性能:官方说明,GPT-5等推理模型通过Responses使用时,模型表现优于Chat Completions;相同提示和配置下,内部SWE-bench评测提高3%。
  • 默认支持智能体循环:一次API请求内可调用多个工具,包括web_search、image_generation、file_search、code_interpreter、远程MCP和自定义函数。
  • 更低的成本:缓存利用率提高可降低费用;官方内部测试相较Chat Completions的缓存利用率改善40%—80%。
  • 有状态上下文:通过store: true维持多轮状态,保留推理及工具上下文。
  • 灵活输入:input可接收字符串或消息列表,instructions提供系统层指导。
  • 加密推理:无须保存状态也能使用高级推理。
  • 面向后续模型:为未来模型支持做好准备。

下表按官方HTML中的支持/不支持图标补全,Markdown原文的相应单元格为空。数值及“即将推出”均代表本页来源口径,不是对所有模型的能力承诺。

能力 Chat Completions API Responses API
文本生成 支持 支持
音频 支持 即将推出
视觉 支持 支持
结构化输出 支持 支持
函数调用 支持 支持
网页搜索 支持 支持
文件搜索 不支持 支持
计算机使用 不支持 支持
代码解释器 不支持 支持
MCP 不支持 支持
图像生成 不支持 支持
推理摘要 不支持 支持

示例

以下场景比较两种API。

Messages与Items

两种API均可让模型生成输出。Chat Completions的调用输入和结果以消息(Message)数组组织;Responses使用条目(Item)。Item是多个类型的联合,表示各种模型动作:message、function_call、function_call_output都是Item类型。Chat Completions把多个方面放进同一个消息对象,而Items将它们分开,更准确地表示模型上下文的基本单位。

Chat Completions还可以通过n参数返回多个并行生成结果,放入choices;Responses不提供该参数,只返回一次生成结果。

Chat Completions API

来源示例 1(python):

代码内提示词/文本译释:

  • Write a one-sentence bedtime story about a unicorn.:用一句话写一个独角兽睡前故事。

## [中文] 使用Chat Completions发送单条故事请求,读取choices中的消息文本;与Responses的Item输出结构对照。
from openai import OpenAI

client = OpenAI()

completion = client.chat.completions.create(
    model="gpt-6-astra",
    messages=[
        {
            "role": "user",
            "content": "Write a one-sentence bedtime story about a unicorn.",
        }
    ],
)

print(completion.choices[0].message.content)

来源示例 2(ruby):

代码内提示词/文本译释:

  • Write a one-sentence bedtime story about a unicorn.:用一句话写一个独角兽睡前故事。

## [中文] 使用Chat Completions发送单条故事请求,读取choices中的消息文本;与Responses的Item输出结构对照。
require "openai"

client = OpenAI::Client.new
completion = client.chat.completions.create(
  model: "gpt-6-astra",
  messages: [
    {
      role: :user,
      content: "Write a one-sentence bedtime story about a unicorn."
    }
  ]
)
puts(completion.choices.fetch(0).message.content)

Responses API

来源示例 3(python):

代码内提示词/文本译释:

  • Write a one-sentence bedtime story about a unicorn.:用一句话写一个独角兽睡前故事。

## [中文] 通过Responses发送故事输入并读取output_text;与Chat Completions的消息/choices结构对照。
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input="Write a one-sentence bedtime story about a unicorn.",
)

print(response.output_text)

来源示例 4(ruby):

代码内提示词/文本译释:

  • Write a one-sentence bedtime story about a unicorn.:用一句话写一个独角兽睡前故事。

## [中文] 通过Responses发送故事输入并读取output_text;与Chat Completions的消息/choices结构对照。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Write a one-sentence bedtime story about a unicorn."
)
puts(response.output_text)

Responses返回具有独立id和类型的response对象,而非message。Responses默认保存;新账户的Chat Completions也默认保存。两种API均可设置store: false关闭保存。

Chat Completions返回choices数组,每项包含message;Responses返回名为output的Item数组。

Chat Completions API

来源示例 5(json):

中文译释:这是带省略号的Chat Completions响应片段,不是完整有效JSON;文本位于choices中的message.content,不能照此直接解析。

代码内提示词/文本译释:

  • Under a blanket of starlight, a sleepy unicorn tiptoed through moonlit meadows, gathering dreams like dew to tuck beneath its silver mane until morning.:星光如毯,一只困倦的独角兽踮脚走过月下草地,像收集露珠一样收拢梦境,将它们藏入银色鬃毛,直到清晨。

{
    "id": "chatcmpl-C9EDpkjH60VPPIB86j2zIhiR8kWiC",
    "object": "chat.completion",
    "created": 1756315657,
    "model": "gpt-5.5",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "Under a blanket of starlight, a sleepy unicorn tiptoed through moonlit meadows, gathering dreams like dew to tuck beneath its silver mane until morning.",
          "refusal": null,
          "annotations": []
        },
        "finish_reason": "stop"
      }
    ],
    ...
}

Responses API

来源示例 6(json):

中文译释:这是带省略号的Responses响应片段,不是完整有效JSON;output同时包含reasoning与message条目,须按type处理。

代码内提示词/文本译释:

  • Under a quilt of moonlight, a drowsy unicorn wandered through quiet meadows, brushing blossoms with her glowing horn so they sighed soft lullabies that carried every dreamer gently to sleep.:月光如被,一只昏昏欲睡的独角兽漫步于安静草地,用发光的角轻拂花朵,花儿轻叹摇篮曲,将每位做梦的人温柔送入梦乡。

{
    "id": "resp_68af4030592c81938ec0a5fbab4a3e9f05438e46b5f69a3b",
    "object": "response",
    "created_at": 1756315696,
    "model": "gpt-5.5",
    "output": [
      {
        "id": "rs_68af4030baa48193b0b43b4c2a176a1a05438e46b5f69a3b",
        "type": "reasoning",
        "content": [],
        "summary": []
      },
      {
        "id": "msg_68af40337e58819392e935fb404414d005438e46b5f69a3b",
        "type": "message",
        "status": "completed",
        "content": [
          {
            "type": "output_text",
            "annotations": [],
            "logprobs": [],
            "text": "Under a quilt of moonlight, a drowsy unicorn wandered through quiet meadows, brushing blossoms with her glowing horn so they sighed soft lullabies that carried every dreamer gently to sleep."
          }
        ],
        "role": "assistant"
      }
    ],
    ...
}

其他差异

  • Responses默认保存;新账户的Chat Completions默认保存。用store: false关闭。
  • 推理模型在Responses中具有更丰富的工具使用体验。从GPT-5.4开始,Chat Completions在reasoning_effort不为none时不支持工具调用。
  • 结构化输出从response_format改用text.format,详见结构化输出指南。
  • 请求中的函数配置和响应中的函数调用结构均有变化,详见函数调用指南。
  • Responses SDK提供output_text辅助属性,Chat Completions SDK没有该属性。
  • Chat Completions需手工管理会话状态。Responses可使用Conversations API保存持久会话,或通过previous_response_id串联响应。

从Chat Completions迁移

将迁移分为三个相互关联的变化:向/v1/responses发请求,从带类型的output数组读取输出,以及选择应用如何在轮次间保留状态。

1. 更新生成端点

将生成请求从post /v1/chat/completions改为post /v1/responses。

不使用函数或多模态输入时,两种API的纯文本消息输入可兼容复用:

来源示例 7(javascript):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] 复用同一组纯文本system/user消息,分别传入Chat Completions的messages及Responses的input;此例不涉及工具或多模态。
const context = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "Hello!" },
];

const completion = await client.chat.completions.create({
  model: "gpt-6-astra",
  messages: context,
});

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: context,
});

来源示例 8(python):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] 复用同一组纯文本system/user消息,分别传入Chat Completions的messages及Responses的input;此例不涉及工具或多模态。
context = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"},
]

completion = client.chat.completions.create(model="gpt-6-astra", messages=context)

response = client.responses.create(model="gpt-6-astra", input=context)

来源示例 9(go):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] 复用同一组纯文本system/user消息,分别传入Chat Completions的messages及Responses的input;此例不涉及工具或多模态。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()

    completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
        Model: "gpt-6-astra",
        Messages: []openai.ChatCompletionMessageParamUnion{
            openai.SystemMessage("You are a helpful assistant."),
            openai.UserMessage("Hello!"),
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(completion.Choices[0].Message.Content)

    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
            responses.ResponseInputItemParamOfMessage("You are a helpful assistant.", responses.EasyInputMessageRoleSystem),
            responses.ResponseInputItemParamOfMessage("Hello!", responses.EasyInputMessageRoleUser),
        }},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例 10(java):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] 复用同一组纯文本system/user消息,分别传入Chat Completions的messages及Responses的input;此例不涉及工具或多模态。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;

var completion =
    client
        .chat()
        .completions()
        .create(
            ChatCompletionCreateParams.builder()
                .model("gpt-6-astra")
                .addSystemMessage("You are a helpful assistant.")
                .addUserMessage("Hello!")
                .build());
completion.choices().stream()
    .flatMap(choice -> choice.message().content().stream())
    .forEach(System.out::println);

var response =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .inputOfResponse(
                    List.of(
                        ResponseInputItem.ofEasyInputMessage(
                            EasyInputMessage.builder()
                                .role(EasyInputMessage.Role.SYSTEM)
                                .content("You are a helpful assistant.")
                                .build()),
                        ResponseInputItem.ofEasyInputMessage(
                            EasyInputMessage.builder()
                                .role(EasyInputMessage.Role.USER)
                                .content("Hello!")
                                .build())))
                .build());
response.output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例 11(csharp):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] 复用同一组纯文本system/user消息,分别传入Chat Completions的messages及Responses的input;此例不涉及工具或多模态。
using OpenAI.Chat;
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";

ChatClient chat = new(model, key);

ChatCompletion completion = await chat.CompleteChatAsync(
    [
        new SystemChatMessage("You are a helpful assistant."),
        new UserChatMessage("Hello!"),
    ]
);
Console.WriteLine(completion.Content[0].Text);

ResponsesClient responses = new(key);

ResponseResult response = await responses.CreateResponseAsync(
    model,
    [
        ResponseItem.CreateSystemMessageItem("You are a helpful assistant."),
        ResponseItem.CreateUserMessageItem("Hello!"),
    ]
);
Console.WriteLine(response.GetOutputText());

来源示例 12(ruby):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] 复用同一组纯文本system/user消息,分别传入Chat Completions的messages及Responses的input;此例不涉及工具或多模态。
require "openai"

client = OpenAI::Client.new
messages = [
  {
    role: :system,
    content: "You are a helpful assistant."
  },
  {
    role: :user,
    content: "Hello!"
  }
]

completion = client.chat.completions.create(
  model: "gpt-6-astra",
  messages: messages
)
puts(completion.choices.fetch(0).message.content)

response = client.responses.create(
  model: "gpt-6-astra",
  input: messages
)
puts(response.output_text)

来源示例 13(bash):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] 复用同一组纯文本system/user消息,分别传入Chat Completions的messages及Responses的input;此例不涉及工具或多模态。
INPUT='[
  { "role": "system", "content": "You are a helpful assistant." },
  { "role": "user", "content": "Hello!" }
]'

curl -s https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d "{
    \"model\": \"gpt-6-astra\",
    \"messages\": $INPUT
  }"

curl -s https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d "{
    \"model\": \"gpt-6-astra\",
    \"input\": $INPUT
  }"

Chat Completions

创建messages数组,从completion.choices[0].message.content读取模型文本。

来源示例 14(javascript):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Chat Completions文本生成:在messages中提供指导和用户内容,再从choices的消息中读取文本。
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const completion = await client.chat.completions.create({
  model: "gpt-6-astra",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Hello!" },
  ],
});
console.log(completion.choices[0].message.content);

来源示例 15(python):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] Chat Completions文本生成:在messages中提供指导和用户内容,再从choices的消息中读取文本。
from openai import OpenAI

client = OpenAI()

completion = client.chat.completions.create(
    model="gpt-6-astra",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"},
    ],
)
print(completion.choices[0].message.content)

来源示例 16(go):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Chat Completions文本生成:在messages中提供指导和用户内容,再从choices的消息中读取文本。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

func main() {
    client := openai.NewClient()

    completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
        Model: "gpt-6-astra",
        Messages: []openai.ChatCompletionMessageParamUnion{
            openai.SystemMessage("You are a helpful assistant."),
            openai.UserMessage("Hello!"),
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(completion.Choices[0].Message.Content)
}

来源示例 17(java):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Chat Completions文本生成:在messages中提供指导和用户内容,再从choices的消息中读取文本。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

ChatCompletionCreateParams params =
    ChatCompletionCreateParams.builder()
        .model("gpt-6-astra")
        .addSystemMessage("You are a helpful assistant.")
        .addUserMessage("Hello!")
        .build();

client.chat().completions().create(params).choices().stream()
    .flatMap(choice -> choice.message().content().stream())
    .forEach(System.out::println);

来源示例 18(csharp):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Chat Completions文本生成:在messages中提供指导和用户内容,再从choices的消息中读取文本。
using OpenAI.Chat;

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);

ChatCompletion completion = await client.CompleteChatAsync(
    [
        new SystemChatMessage("You are a helpful assistant."),
        new UserChatMessage("Hello!"),
    ]
);

Console.WriteLine(completion.Content[0].Text);

来源示例 19(ruby):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] Chat Completions文本生成:在messages中提供指导和用户内容,再从choices的消息中读取文本。
require "openai"

client = OpenAI::Client.new

completion = client.chat.completions.create(
  model: "gpt-6-astra",
  messages: [
    {
      role: :system,
      content: "You are a helpful assistant."
    },
    {
      role: :user,
      content: "Hello!"
    }
  ]
)

puts(completion.choices.fetch(0).message.content)

来源示例 20(bash):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] Chat Completions文本生成:在messages中提供指导和用户内容,再从choices的消息中读取文本。
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
      "model": "gpt-6-astra",
      "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"}
      ]
  }'

Responses

在顶层分别设置instructions和input,从response.output_text读取生成文本。

来源示例 21(javascript):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Responses文本生成:顶层instructions与input分开,输出通过SDK辅助属性或响应对象读取;HTTP示例返回原始响应。
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const response = await client.responses.create({
  model: "gpt-6-astra",
  instructions: "You are a helpful assistant.",
  input: "Hello!",
});

console.log(response.output_text);

来源示例 22(python):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] Responses文本生成:顶层instructions与input分开,输出通过SDK辅助属性或响应对象读取;HTTP示例返回原始响应。
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra", instructions="You are a helpful assistant.", input="Hello!"
)
print(response.output_text)

来源示例 23(go):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Responses文本生成:顶层instructions与input分开,输出通过SDK辅助属性或响应对象读取;HTTP示例返回原始响应。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()

    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:        "gpt-6-astra",
        Instructions: openai.String("You are a helpful assistant."),
        Input:        responses.ResponseNewParamsInputUnion{OfString: openai.String("Hello!")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例 24(java):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Responses文本生成:顶层instructions与input分开,输出通过SDK辅助属性或响应对象读取;HTTP示例返回原始响应。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Hello!")
        .instructions("You are a helpful assistant.")
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例 25(csharp):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

// [中文] Responses文本生成:顶层instructions与input分开,输出通过SDK辅助属性或响应对象读取;HTTP示例返回原始响应。
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

CreateResponseOptions options = new()
{
    Model = "gpt-6-astra",
    Instructions = "You are a helpful assistant.",
};
options.InputItems.Add(ResponseItem.CreateUserMessageItem("Hello!"));

ResponseResult response = await client.CreateResponseAsync(options);

Console.WriteLine(response.GetOutputText());

来源示例 26(ruby):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] Responses文本生成:顶层instructions与input分开,输出通过SDK辅助属性或响应对象读取;HTTP示例返回原始响应。
require "openai"

client = OpenAI::Client.new

response = client.responses.create(
  model: "gpt-6-astra",
  instructions: "You are a helpful assistant.",
  input: "Hello!"
)

puts(response.output_text)

来源示例 27(bash):

代码内提示词/文本译释:

  • You are a helpful assistant.:你是一位乐于助人的助手。
  • Hello!:你好!

## [中文] Responses文本生成:顶层instructions与input分开,输出通过SDK辅助属性或响应对象读取;HTTP示例返回原始响应。
curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
      "model": "gpt-6-astra",
      "instructions": "You are a helpful assistant.",
      "input": "Hello!"
  }'

2. 将Messages映射到Items

Chat Completions输入输出均使用messages;Responses使用带类型的input及output条目数组。message只是其中一种,其他类型还包括reasoning、function_call、function_call_output。

Chat Completions概念 Responses映射
messages[] input:字符串或输入Item数组。
系统或开发者指导 顶层instructions;需要保留既有对话记录时,也可使用兼容消息Item。
用户消息 带role: "user"的输入消息Item。
助手消息 response.output中的输出消息Item;手工管理状态时传回input。
工具或函数调用 function_call输出Item。
工具或函数结果 用call_id关联调用的function_call_output输入Item。
通过n生成多个结果 Responses不提供;需要多个候选时分别发请求。

只需要最终文本时使用SDK的output_text。涉及推理、工具或多模态输出时,遍历response.output,按各Item的type处理。

3. 更新多轮会话

多轮应用需要更新上下文逻辑,常用方案有三种:

  • 希望由OpenAI管理此前响应上下文时,使用previous_response_id。每次重新发送稳定的instructions,因为该ID不会继承前一响应的顶层指令。
  • 需要自己管理或裁剪上下文时,将以前的output条目传回下一请求。
  • 需要持久会话对象时,使用Conversations API。

Chat Completions:保存对话记录,每次发送累积的messages数组。

来源示例 28(javascript):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • You are a helpful assistant.:你是一位乐于助人的助手。
  • And its population?:它的人口有多少?

// [中文] Chat Completions多轮:自行保存第一轮助手消息及下一用户问题,再发送累积messages。
let messages = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "What is the capital of France?" },
];
const res1 = await client.chat.completions.create({
  model: "gpt-6-astra",
  messages,
});

messages = messages.concat([res1.choices[0].message]);
messages.push({ role: "user", content: "And its population?" });

const res2 = await client.chat.completions.create({
  model: "gpt-6-astra",
  messages,
});

来源示例 29(python):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • You are a helpful assistant.:你是一位乐于助人的助手。
  • And its population?:它的人口有多少?

## [中文] Chat Completions多轮:自行保存第一轮助手消息及下一用户问题,再发送累积messages。
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the capital of France?"},
]
res1 = client.chat.completions.create(model="gpt-6-astra", messages=messages)

messages += [res1.choices[0].message]
messages += [{"role": "user", "content": "And its population?"}]

res2 = client.chat.completions.create(model="gpt-6-astra", messages=messages)

来源示例 30(go):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • You are a helpful assistant.:你是一位乐于助人的助手。
  • And its population?:它的人口有多少?

// [中文] Chat Completions多轮:自行保存第一轮助手消息及下一用户问题,再发送累积messages。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

func main() {
    client := openai.NewClient()
    messages := []openai.ChatCompletionMessageParamUnion{
        openai.SystemMessage("You are a helpful assistant."),
        openai.UserMessage("What is the capital of France?"),
    }

    first, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})
    if err != nil {
        panic(err)
    }
    messages = append(messages, openai.AssistantMessage(first.Choices[0].Message.Content), openai.UserMessage("And its population?"))

    second, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{Model: "gpt-6-astra", Messages: messages})
    if err != nil {
        panic(err)
    }
    fmt.Println(second.Choices[0].Message.Content)
}

来源示例 31(java):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • You are a helpful assistant.:你是一位乐于助人的助手。
  • And its population?:它的人口有多少?

// [中文] Chat Completions多轮:自行保存第一轮助手消息及下一用户问题,再发送累积messages。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

var params =
    ChatCompletionCreateParams.builder()
        .model("gpt-6-astra")
        .addSystemMessage("You are a helpful assistant.")
        .addUserMessage("What is the capital of France?")
        .build();
var first = client.chat().completions().create(params);

var second =
    client
        .chat()
        .completions()
        .create(
            params.toBuilder()
                .addAssistantMessage(first.choices().get(0).message().content().orElseThrow())
                .addUserMessage("And its population?")
                .build());
second.choices().stream()
    .flatMap(choice -> choice.message().content().stream())
    .forEach(System.out::println);

来源示例 32(csharp):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • You are a helpful assistant.:你是一位乐于助人的助手。
  • And its population?:它的人口有多少?

// [中文] Chat Completions多轮:自行保存第一轮助手消息及下一用户问题,再发送累积messages。
using OpenAI.Chat;

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);

List<ChatMessage> messages =
[
    new SystemChatMessage("You are a helpful assistant."),
    new UserChatMessage("What is the capital of France?"),
];
ChatCompletion first = await client.CompleteChatAsync(messages);

messages.Add(new AssistantChatMessage(first));
messages.Add(new UserChatMessage("And its population?"));
ChatCompletion second = await client.CompleteChatAsync(messages);

Console.WriteLine(second.Content[0].Text);

来源示例 33(ruby):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • You are a helpful assistant.:你是一位乐于助人的助手。
  • And its population?:它的人口有多少?

## [中文] Chat Completions多轮:自行保存第一轮助手消息及下一用户问题,再发送累积messages。
require "openai"

client = OpenAI::Client.new
messages = [
  {
    role: :system,
    content: "You are a helpful assistant."
  },
  {
    role: :user,
    content: "What is the capital of France?"
  }
]

first = client.chat.completions.create(
  model: "gpt-6-astra",
  messages: messages
)
messages << {
  role: :assistant,
  content: first.choices.fetch(0).message.content
}
messages << {
  role: :user,
  content: "And its population?"
}

second = client.chat.completions.create(
  model: "gpt-6-astra",
  messages: messages
)

puts(second.choices.fetch(0).message.content)

Responses:手工将上一响应输出放进下一响应输入。

来源示例 34(javascript):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses多轮:将第一轮全部输出条目转换或追加到下一轮输入,再加入用户追问;保留推理和工具等条目类型。
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

let context = [{ role: "user", content: "What is the capital of France?" }];

const res1 = await client.responses.create({
  model: "gpt-6-astra",
  input: context,
});

// Append the first response’s output to context
context = context.concat(toResponseInputItems(res1.output));

// Add the next user message
context.push({ role: "user", content: "And its population?" });

const res2 = await client.responses.create({
  model: "gpt-6-astra",
  input: context,
});

来源示例 35(python):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

## [中文] Responses多轮:将第一轮全部输出条目转换或追加到下一轮输入,再加入用户追问;保留推理和工具等条目类型。
context = [{"role": "user", "content": "What is the capital of France?"}]
res1 = client.responses.create(
    model="gpt-6-astra",
    input=context,
)

## Append the first response's output to context
context += res1.output

## Add the next user message
context += [{"role": "user", "content": "And its population?"}]

res2 = client.responses.create(
    model="gpt-6-astra",
    input=context,
)

来源示例 36(go):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses多轮:将第一轮全部输出条目转换或追加到下一轮输入,再加入用户追问;保留推理和工具等条目类型。
package main

import (
    "context"
    "encoding/json"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()
    contextItems := responses.ResponseInputParam{
        responses.ResponseInputItemParamOfMessage("What is the capital of France?", responses.EasyInputMessageRoleUser),
    }
    first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},
    })
    if err != nil {
        panic(err)
    }
    contextItems = append(contextItems, outputAsInput(first.Output)...)
    contextItems = append(contextItems, responses.ResponseInputItemParamOfMessage("And its population?", responses.EasyInputMessageRoleUser))
    second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfInputItemList: contextItems},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(second.OutputText())
}

func outputAsInput(output []responses.ResponseOutputItemUnion) []responses.ResponseInputItemUnionParam {
    input := make([]responses.ResponseInputItemUnionParam, 0, len(output))
    for _, item := range output {
        var converted responses.ResponseInputItemUnion
        if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {
            panic(err)
        }
        input = append(input, converted.ToParam())
    }
    return input
}

来源示例 37(java):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses多轮:将第一轮全部输出条目转换或追加到下一轮输入,再加入用户追问;保留推理和工具等条目类型。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.ArrayList;

var history = new ArrayList<ResponseInputItem>();
history.add(
    ResponseInputItem.ofEasyInputMessage(
        EasyInputMessage.builder()
            .role(EasyInputMessage.Role.USER)
            .content("What is the capital of France?")
            .build()));

var first =
    client
        .responses()
        .create(
            ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build());
first.output().stream()
    .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))
    .forEach(history::add);
history.add(
    ResponseInputItem.ofEasyInputMessage(
        EasyInputMessage.builder()
            .role(EasyInputMessage.Role.USER)
            .content("And its population?")
            .build()));

client
    .responses()
    .create(ResponseCreateParams.builder().model("gpt-6-astra").inputOfResponse(history).build())
    .output()
    .stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例 38(csharp):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses多轮:将第一轮全部输出条目转换或追加到下一轮输入,再加入用户追问;保留推理和工具等条目类型。
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

List<ResponseItem> history =
[
    ResponseItem.CreateUserMessageItem("What is the capital of France?"),
];

ResponseResult first = await client.CreateResponseAsync("gpt-6-astra", history);
history.AddRange(first.OutputItems);
history.Add(ResponseItem.CreateUserMessageItem("And its population?"));

ResponseResult second = await client.CreateResponseAsync("gpt-6-astra", history);
Console.WriteLine(second.GetOutputText());

来源示例 39(ruby):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

## [中文] Responses多轮:将第一轮全部输出条目转换或追加到下一轮输入,再加入用户追问;保留推理和工具等条目类型。
require "openai"

client = OpenAI::Client.new
context = [
  {
    role: :user,
    content: "What is the capital of France?"
  }
]

first = client.responses.create(
  model: "gpt-6-astra",
  input: context
)
context.concat(first.output)
context << {
  role: :user,
  content: "And its population?"
}

second = client.responses.create(
  model: "gpt-6-astra",
  input: context
)

puts(second.output_text)

也可用previous_response_id引用此前响应,创建响应链或分支。

来源示例 40(javascript):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses响应链:第二轮传入previous_response_id引用第一轮;历史输入词元仍计费,顶层instructions需按正文重新发送。
const res1 = await client.responses.create({
  model: "gpt-6-astra",
  input: "What is the capital of France?",
  store: true,
});

const res2 = await client.responses.create({
  model: "gpt-6-astra",
  input: "And its population?",
  previous_response_id: res1.id,
  store: true,
});

来源示例 41(python):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

## [中文] Responses响应链:第二轮传入previous_response_id引用第一轮;历史输入词元仍计费,顶层instructions需按正文重新发送。
res1 = client.responses.create(
    model="gpt-6-astra", input="What is the capital of France?", store=True
)

res2 = client.responses.create(
    model="gpt-6-astra",
    input="And its population?",
    previous_response_id=res1.id,
    store=True,
)

来源示例 42(go):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses响应链:第二轮传入previous_response_id引用第一轮;历史输入词元仍计费,顶层instructions需按正文重新发送。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()

    first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Store: openai.Bool(true),
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is the capital of France?")},
    })
    if err != nil {
        panic(err)
    }

    second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:              "gpt-6-astra",
        Store:              openai.Bool(true),
        PreviousResponseID: openai.String(first.ID),
        Input:              responses.ResponseNewParamsInputUnion{OfString: openai.String("And its population?")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(second.OutputText())
}

来源示例 43(java):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses响应链:第二轮传入previous_response_id引用第一轮;历史输入词元仍计费,顶层instructions需按正文重新发送。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;

var first =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .input("What is the capital of France?")
                .store(true)
                .build());

var second =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .input("And its population?")
                .previousResponseId(first.id())
                .store(true)
                .build());
second.output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例 44(csharp):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

// [中文] Responses响应链:第二轮传入previous_response_id引用第一轮;历史输入词元仍计费,顶层instructions需按正文重新发送。
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

ResponseResult first = await client.CreateResponseAsync(
    "gpt-6-astra",
    "What is the capital of France?"
);
ResponseResult second = await client.CreateResponseAsync(
    "gpt-6-astra",
    "And its population?",
    previousResponseId: first.Id
);

Console.WriteLine(second.GetOutputText());

来源示例 45(ruby):

代码内提示词/文本译释:

  • What is the capital of France?:法国的首都是什么?
  • And its population?:它的人口有多少?

## [中文] Responses响应链:第二轮传入previous_response_id引用第一轮;历史输入词元仍计费,顶层instructions需按正文重新发送。
require "openai"

client = OpenAI::Client.new

first = client.responses.create(
  model: "gpt-6-astra",
  input: "What is the capital of France?",
  store: true
)

second = client.responses.create(
  model: "gpt-6-astra",
  previous_response_id: first.id,
  input: "And its population?",
  store: true
)

puts(second.output_text)

即便使用该ID,响应链中此前的全部输入词元仍按API输入词元计费。

4. 决定何时保存状态

Responses默认保存;新账户的Chat Completions也默认保存。两种API均可用store: false关闭。

某些组织受合规或数据保留政策约束,例如零数据保留(ZDR)组织,不能以有状态方式使用Responses。加密推理条目让这些工作流保持无状态,同时继续利用推理条目。

关闭状态保存并继续使用推理时:

  • 将store字段设为false。
  • 保留并回放每个返回的推理条目。按原文说明,创建响应时,每个推理条目默认包含encrypted_content。

API返回加密后的推理内容,之后可像普通推理条目一样传回。ZDR组织自动强制store: false。收到encrypted_content后,OpenAI在内存中解密,用于生成下一响应,然后安全丢弃;新产生的推理词元立即加密并返回,不持久化中间状态。

5. 更新函数定义和输出

函数定义存在两点区别:

  1. Chat Completions使用外层标签结构,Responses使用内部标签结构。
  2. Chat Completions函数默认非严格。Responses省略strict时会尝试严格模式;Schema无法兼容时,退回非严格、尽力执行的函数调用,返回解析后的工具并标明strict: false。若明确需要非严格行为,应主动设置strict: false。

以下两组定义功能等价。

Chat Completions API

来源示例 46(json):

中文译释:Chat Completions函数定义在function对象内嵌name、description、strict和parameters;get_weather描述意为“确定我所在位置的天气”。

{
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Determine weather in my location",
      "strict": true,
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string"
          }
        },
        "additionalProperties": false,
        "required": [
          "location"
        ]
      }
    }
}

Responses API

来源示例 47(json):

中文译释:Responses将函数名、描述和参数放在顶层,描述同样意为“确定我所在位置的天气”;strict省略后的尝试和回退规则见正文,不能仅按本片段认定必然严格。

{
    "type": "function",
    "name": "get_weather",
    "description": "Determine weather in my location",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "required": [
        "location"
      ]
    }
}

遵循函数调用最佳实践

Responses将工具调用和工具输出表示为两个不同Item类型,以call_id关联。细节见函数调用文档。

6. 更新结构化输出定义

结构化输出定义从response_format移至text.format。

Chat Completions

来源示例 48(javascript):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Chat Completions结构化输出:在response_format中声明person的JSON Schema,约束姓名、年龄及额外属性。
const completion = await openai.chat.completions.create({
  model: "gpt-6-astra",
  messages: [
    {
      role: "user",
      content: "Jane, 54 years old",
    },
  ],
  response_format: {
    type: "json_schema",
    json_schema: {
      name: "person",
      strict: true,
      schema: {
        type: "object",
        properties: {
          name: {
            type: "string",
            minLength: 1,
          },
          age: {
            type: "number",
            minimum: 0,
            maximum: 130,
          },
        },
        required: ["name", "age"],
        additionalProperties: false,
      },
    },
  },
  reasoning_effort: "medium",
});

来源示例 49(python):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

## [中文] Chat Completions结构化输出:在response_format中声明person的JSON Schema,约束姓名、年龄及额外属性。
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-6-astra",
    messages=[
        {
            "role": "user",
            "content": "Jane, 54 years old",
        }
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "minLength": 1},
                    "age": {"type": "number", "minimum": 0, "maximum": 130},
                },
                "required": ["name", "age"],
                "additionalProperties": False,
            },
        },
    },
    reasoning_effort="medium",
)

来源示例 50(go):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Chat Completions结构化输出:在response_format中声明person的JSON Schema,约束姓名、年龄及额外属性。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/shared"
)

func main() {
    client := openai.NewClient()
    schema := map[string]any{
        "type": "object",
        "properties": map[string]any{
            "name": map[string]any{"type": "string", "minLength": 1},
            "age":  map[string]any{"type": "number", "minimum": 0, "maximum": 130},
        },
        "required":             []string{"name", "age"},
        "additionalProperties": false,
    }

    completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
        Model:           "gpt-6-astra",
        ReasoningEffort: openai.ReasoningEffortMedium,
        Messages: []openai.ChatCompletionMessageParamUnion{
            openai.UserMessage("Jane, 54 years old"),
        },
        ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{
            OfJSONSchema: &shared.ResponseFormatJSONSchemaParam{JSONSchema: shared.ResponseFormatJSONSchemaJSONSchemaParam{
                Name: "person", Strict: openai.Bool(true), Schema: schema,
            }},
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(completion.Choices[0].Message.Content)
}

来源示例 51(java):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Chat Completions结构化输出:在response_format中声明person的JSON Schema,约束姓名、年龄及额外属性。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.ReasoningEffort;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.List;
import java.util.Map;

ChatCompletionCreateParams params =
    ChatCompletionCreateParams.builder()
        .model("gpt-6-astra")
        .reasoningEffort(ReasoningEffort.MEDIUM)
        .addUserMessage("Jane, 54 years old")
        .putAdditionalBodyProperty(
            "response_format",
            JsonValue.from(
                Map.of(
                    "type",
                    "json_schema",
                    "json_schema",
                    Map.of(
                        "name",
                        "person",
                        "strict",
                        true,
                        "schema",
                        Map.of(
                            "type",
                            "object",
                            "properties",
                            Map.of(
                                "name",
                                Map.of("type", "string", "minLength", 1),
                                "age",
                                Map.of("type", "number", "minimum", 0, "maximum", 130)),
                            "required",
                            List.of("name", "age"),
                            "additionalProperties",
                            false)))))
        .build();

client.chat().completions().create(params).choices().stream()
    .flatMap(choice -> choice.message().content().stream())
    .forEach(System.out::println);

来源示例 52(csharp):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Chat Completions结构化输出:在response_format中声明person的JSON Schema,约束姓名、年龄及额外属性。
using OpenAI.Chat;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);

BinaryData schema = BinaryData.FromString(
    """
    {
      "type": "object",
      "properties": {
        "name": { "type": "string", "minLength": 1 },
        "age": { "type": "number", "minimum": 0, "maximum": 130 }
      },
      "required": ["name", "age"],
      "additionalProperties": false
    }
    """
);
ChatCompletionOptions options = new()
{
    ReasoningEffortLevel = ChatReasoningEffortLevel.Medium,
    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
        "person",
        schema,
        jsonSchemaIsStrict: true
    ),
};

ChatCompletion completion = await client.CompleteChatAsync(
    [new UserChatMessage("Jane, 54 years old")],
    options
);

Console.WriteLine(completion.Content[0].Text);

来源示例 53(ruby):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

## [中文] Chat Completions结构化输出:在response_format中声明person的JSON Schema,约束姓名、年龄及额外属性。
require "openai"

client = OpenAI::Client.new
schema = {
  type: "object",
  properties: {
    name: {
      type: "string",
      minLength: 1
    },
    age: {
      type: "number",
      minimum: 0,
      maximum: 130
    }
  },
  required: ["name", "age"],
  additionalProperties: false
}

completion = client.chat.completions.create(
  model: "gpt-6-astra",
  reasoning_effort: :medium,
  messages: [
    {
      role: :user,
      content: "Jane, 54 years old"
    }
  ],
  response_format: {
    type: :json_schema,
    json_schema: {
      name: "person",
      strict: true,
      schema: schema
    }
  }
)

puts(completion.choices.fetch(0).message.content)

来源示例 54(bash):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

## [中文] Chat Completions结构化输出:在response_format中声明person的JSON Schema,约束姓名、年龄及额外属性。
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
  "model": "gpt-6-astra",
  "messages": [
    {
      "role": "user",
      "content": "Jane, 54 years old"
    }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1
          },
          "age": {
            "type": "number",
            "minimum": 0,
            "maximum": 130
          }
        },
        "required": [
          "name",
          "age"
        ],
        "additionalProperties": false
      }
    }
  },
  "reasoning_effort": "medium"
}'

Responses

来源示例 55(javascript):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Responses结构化输出:在text.format中声明相同person Schema,替代旧response_format位置。
const response = await openai.responses.create({
  model: "gpt-6-astra",
  input: "Jane, 54 years old",
  text: {
    format: {
      type: "json_schema",
      name: "person",
      strict: true,
      schema: {
        type: "object",
        properties: {
          name: {
            type: "string",
            minLength: 1,
          },
          age: {
            type: "number",
            minimum: 0,
            maximum: 130,
          },
        },
        required: ["name", "age"],
        additionalProperties: false,
      },
    },
  },
});

来源示例 56(python):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

## [中文] Responses结构化输出:在text.format中声明相同person Schema,替代旧response_format位置。
response = client.responses.create(
    model="gpt-6-astra",
    input="Jane, 54 years old",
    text={
        "format": {
            "type": "json_schema",
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "minLength": 1},
                    "age": {"type": "number", "minimum": 0, "maximum": 130},
                },
                "required": ["name", "age"],
                "additionalProperties": False,
            },
        }
    },
)

来源示例 57(go):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Responses结构化输出:在text.format中声明相同person Schema,替代旧response_format位置。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()
    schema := map[string]any{
        "type": "object",
        "properties": map[string]any{
            "name": map[string]any{"type": "string", "minLength": 1},
            "age":  map[string]any{"type": "number", "minimum": 0, "maximum": 130},
        },
        "required":             []string{"name", "age"},
        "additionalProperties": false,
    }

    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Jane, 54 years old")},
        Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{
            OfJSONSchema: &responses.ResponseFormatTextJSONSchemaConfigParam{Name: "person", Schema: schema, Strict: openai.Bool(true)},
        }},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例 58(java):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Responses结构化输出:在text.format中声明相同person Schema,替代旧response_format位置。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseFormatTextJsonSchemaConfig;
import com.openai.models.responses.ResponseTextConfig;
import java.util.List;
import java.util.Map;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Jane, 54 years old")
        .text(
            ResponseTextConfig.builder()
                .format(
                    ResponseFormatTextJsonSchemaConfig.builder()
                        .name("person")
                        .strict(true)
                        .schema(
                            ResponseFormatTextJsonSchemaConfig.Schema.builder()
                                .putAdditionalProperty("type", JsonValue.from("object"))
                                .putAdditionalProperty(
                                    "properties",
                                    JsonValue.from(
                                        Map.of(
                                            "name",
                                            Map.of("type", "string", "minLength", 1),
                                            "age",
                                            Map.of(
                                                "type", "number", "minimum", 0, "maximum",
                                                130))))
                                .putAdditionalProperty(
                                    "required", JsonValue.from(List.of("name", "age")))
                                .putAdditionalProperty(
                                    "additionalProperties", JsonValue.from(false))
                                .build())
                        .build())
                .build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例 59(csharp):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

// [中文] Responses结构化输出:在text.format中声明相同person Schema,替代旧response_format位置。
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

BinaryData schema = BinaryData.FromString(
    """
    {
      "type": "object",
      "properties": {
        "name": { "type": "string", "minLength": 1 },
        "age": { "type": "number", "minimum": 0, "maximum": 130 }
      },
      "required": ["name", "age"],
      "additionalProperties": false
    }
    """
);
CreateResponseOptions options = new()
{
    Model = "gpt-6-astra",
    TextOptions = new ResponseTextOptions
    {
        TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(
            "person",
            schema,
            jsonSchemaIsStrict: true
        ),
    },
};
options.InputItems.Add(
    ResponseItem.CreateUserMessageItem("Jane, 54 years old")
);

ResponseResult response = await client.CreateResponseAsync(options);

Console.WriteLine(response.GetOutputText());

来源示例 60(ruby):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

## [中文] Responses结构化输出:在text.format中声明相同person Schema,替代旧response_format位置。
require "openai"

client = OpenAI::Client.new
schema = {
  type: "object",
  properties: {
    name: {
      type: "string",
      minLength: 1
    },
    age: {
      type: "number",
      minimum: 0,
      maximum: 130
    }
  },
  required: ["name", "age"],
  additionalProperties: false
}

response = client.responses.create(
  model: "gpt-6-astra",
  input: "Jane, 54 years old",
  text: {
    format: {
      type: :json_schema,
      name: "person",
      strict: true,
      schema: schema
    }
  }
)

puts(response.output_text)

来源示例 61(bash):

代码内提示词/文本译释:

  • Jane, 54 years old:Jane,54岁。

## [中文] Responses结构化输出:在text.format中声明相同person Schema,替代旧response_format位置。
curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
  "model": "gpt-6-astra",
  "input": "Jane, 54 years old",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1
          },
          "age": {
            "type": "number",
            "minimum": 0,
            "maximum": 130
          }
        },
        "required": [
          "name",
          "age"
        ],
        "additionalProperties": false
      }
    }
  }
}'

7. 更新流式响应接收逻辑

Chat Completions返回含delta的增量数据块;Responses使用带类型的服务器发送事件。接收方应根据事件type分支,处理界面或编排层需要的事件。

文本流常见事件包括response.created、response.output_text.delta、response.completed和error。

函数调用流还可产生response.function_call_arguments.delta及response.function_call_arguments.done。详见流式Responses指南及事件参考。

8. 使用原生工具

应用适合使用OpenAI原生工具时,可将自己的工具调用更新为内置方案。

Chat Completions:不能原生使用OpenAI托管工具,需要自己集成。以下示例使用关闭推理的GPT-5.6 Terra;GPT-6 Astra与GPT-6.1 Sol要求通过Responses API调用工具。

来源示例 62(javascript):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?
  • Search the web for information:在网络上搜索信息。
  • You are a helpful assistant.:你是一位乐于助人的助手。

// [中文] Chat Completions自定义搜索对照:关闭GPT-5.6 Terra推理并声明web_search函数;来源未展示完整工具执行循环,不能当成原生托管网页搜索。
async function web_search(query) {
  const res = await fetch(`https://api.example.com/search?q=${query}`);
  const data = await res.json();
  return data.results;
}

const completion = await client.chat.completions.create({
  model: "gpt-5.6-terra",
  reasoning_effort: "none",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Who is the current president of France?" },
  ],
  functions: [
    {
      name: "web_search",
      description: "Search the web for information",
      parameters: {
        type: "object",
        properties: { query: { type: "string" } },
        required: ["query"],
      },
    },
  ],
});

来源示例 63(python):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?
  • Search the web for information:在网络上搜索信息。
  • You are a helpful assistant.:你是一位乐于助人的助手。

## [中文] Chat Completions自定义搜索对照:关闭GPT-5.6 Terra推理并声明web_search函数;来源未展示完整工具执行循环,不能当成原生托管网页搜索。
import requests


def web_search(query):
    r = requests.get(f"https://api.example.com/search?q={query}")
    return r.json().get("results", [])


completion = client.chat.completions.create(
    model="gpt-5.6-terra",
    reasoning_effort="none",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who is the current president of France?"},
    ],
    functions=[
        {
            "name": "web_search",
            "description": "Search the web for information",
            "parameters": {
                "type": "object",
                "properties": {"query": {"type": "string"}},
                "required": ["query"],
            },
        }
    ],
)

来源示例 64(go):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?
  • Search the web for information:在网络上搜索信息。
  • You are a helpful assistant.:你是一位乐于助人的助手。

// [中文] Chat Completions自定义搜索对照:关闭GPT-5.6 Terra推理并声明web_search函数;来源未展示完整工具执行循环,不能当成原生托管网页搜索。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/shared"
)

func main() {
    client := openai.NewClient()
    completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
        Model: "gpt-5.6-terra",
        Messages: []openai.ChatCompletionMessageParamUnion{
            openai.SystemMessage("You are a helpful assistant."),
            openai.UserMessage("Who is the current president of France?"),
        },
        Functions: []openai.ChatCompletionNewParamsFunction{{
            Name:        "web_search",
            Description: openai.String("Search the web for information"),
            Parameters: map[string]any{
                "type":       "object",
                "properties": map[string]any{"query": map[string]any{"type": "string"}},
                "required":   []string{"query"},
            },
        }},
        ReasoningEffort: shared.ReasoningEffortNone,
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(completion.Choices[0].Message)
}

来源示例 65(java):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?
  • Search the web for information:在网络上搜索信息。
  • You are a helpful assistant.:你是一位乐于助人的助手。

// [中文] Chat Completions自定义搜索对照:关闭GPT-5.6 Terra推理并声明web_search函数;来源未展示完整工具执行循环,不能当成原生托管网页搜索。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.FunctionParameters;
import com.openai.models.ReasoningEffort;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.List;
import java.util.Map;

ChatCompletionCreateParams params =
    ChatCompletionCreateParams.builder()
        .model("gpt-5.6-terra")
        .reasoningEffort(ReasoningEffort.NONE)
        .addSystemMessage("You are a helpful assistant.")
        .addUserMessage("Who is the current president of France?")
        .addFunction(
            ChatCompletionCreateParams.Function.builder()
                .name("web_search")
                .description("Search the web for information")
                .parameters(
                    FunctionParameters.builder()
                        .putAdditionalProperty("type", JsonValue.from("object"))
                        .putAdditionalProperty(
                            "properties",
                            JsonValue.from(Map.of("query", Map.of("type", "string"))))
                        .putAdditionalProperty("required", JsonValue.from(List.of("query")))
                        .build())
                .build())
        .build();

client.chat().completions().create(params).choices().stream()
    .map(choice -> choice.message())
    .forEach(System.out::println);

来源示例 66(ruby):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?
  • Search the web for information:在网络上搜索信息。
  • You are a helpful assistant.:你是一位乐于助人的助手。

## [中文] Chat Completions自定义搜索对照:关闭GPT-5.6 Terra推理并声明web_search函数;来源未展示完整工具执行循环,不能当成原生托管网页搜索。
require "openai"

client = OpenAI::Client.new

completion = client.chat.completions.create(
  model: "gpt-5.6-terra",
  reasoning_effort: :none,
  messages: [
    {
      role: :system,
      content: "You are a helpful assistant."
    },
    {
      role: :user,
      content: "Who is the current president of France?"
    }
  ],
  functions: [
    {
      name: "web_search",
      description: "Search the web for information",
      parameters: {
        type: "object",
        properties: { query: { type: "string" } },
        required: ["query"]
      }
    }
  ]
)

puts(completion.choices.fetch(0).message)

来源示例 67(bash):

## [中文] 向第三方占位搜索服务发送GET参数的curl片段,不是OpenAI工具调用;MD末尾多出续行反斜杠,与HTML不同,片段按来源保留且未执行。
curl https://api.example.com/search \
  -G \
  --data-urlencode "q=your+search+term" \
  --data-urlencode "key=$SEARCH_API_KEY"\

Responses:直接声明希望模型使用的工具。

来源示例 68(javascript):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?

// [中文] Responses声明内置web_search工具,由模型调用托管搜索并回答;示例问题是动态事实,不在本次翻译中实际查询或调用。
const answer = await client.responses.create({
  model: "gpt-6-astra",
  input: "Who is the current president of France?",
  tools: [{ type: "web_search" }],
});

console.log(answer.output_text);

来源示例 69(python):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?

## [中文] Responses声明内置web_search工具,由模型调用托管搜索并回答;示例问题是动态事实,不在本次翻译中实际查询或调用。
answer = client.responses.create(
    model="gpt-6-astra",
    input="Who is the current president of France?",
    tools=[{"type": "web_search"}],
)

print(answer.output_text)

来源示例 70(go):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?

// [中文] Responses声明内置web_search工具,由模型调用托管搜索并回答;示例问题是动态事实,不在本次翻译中实际查询或调用。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Who is the current president of France?")},
        Tools: []responses.ToolUnionParam{
            responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例 71(java):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?

// [中文] Responses声明内置web_search工具,由模型调用托管搜索并回答;示例问题是动态事实,不在本次翻译中实际查询或调用。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Who is the current president of France?")
        .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例 72(csharp):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?

// [中文] Responses声明内置web_search工具,由模型调用托管搜索并回答;示例问题是动态事实,不在本次翻译中实际查询或调用。
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);

CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(ResponseTool.CreateWebSearchTool());
options.InputItems.Add(
    ResponseItem.CreateUserMessageItem("Who is the current president of France?")
);

ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());

来源示例 73(ruby):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?

## [中文] Responses声明内置web_search工具,由模型调用托管搜索并回答;示例问题是动态事实,不在本次翻译中实际查询或调用。
require "openai"

client = OpenAI::Client.new

response = client.responses.create(
  model: "gpt-6-astra",
  input: "Who is the current president of France?",
  tools: [{ type: :web_search }]
)

puts(response.output_text)

来源示例 74(bash):

代码内提示词/文本译释:

  • Who is the current president of France?:法国现任总统是谁?

## [中文] Responses声明内置web_search工具,由模型调用托管搜索并回答;示例问题是动态事实,不在本次翻译中实际查询或调用。
curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "input": "Who is the current president of France?",
    "tools": [{"type": "web_search"}]
  }'

9. 检查常见迁移错误

  • 仍读取choices[0].message.content,没有改用response.output_text或response.output。
  • 将全部output条目都当作消息,忽略推理、工具及函数调用的独立类型。
  • 手工传递上下文时丢失推理、函数调用或函数结果条目。
  • 发送函数结果时缺少匹配的call_id。
  • Responses请求仍使用response_format,没有改用text.format。
  • 直接复用Chat Completions的数据块处理器,没有处理Responses的带类型事件。
  • 误以为previous_response_id可免除历史上下文费用;响应链中的此前输入词元仍计费。

渐进上线检查清单

Chat Completions仍受支持,因此可逐个用户流程迁移。

  • [ ] 先从文本生成流程开始。
  • [ ] 更新端点、请求体及输出处理。
  • [ ] 选择previous_response_id、手工Item回放或Conversations API。
  • [ ] 无状态或ZDR流程设置store: false;需要跨轮推理上下文时携带加密推理条目。
  • [ ] 迁移函数定义,检查函数结果含正确call_id。
  • [ ] 将结构化输出Schema从response_format移至text.format。
  • [ ] 更新流式接收逻辑,处理带类型事件。
  • [ ] 适合时用OpenAI托管工具替换自建编排。
  • [ ] 扩大Responses流量前,比较行为、延迟、词元用量及错误。

建议逐步迁移所有流程,以使用后续功能与改进。

Assistants API

根据Assistants API测试版反馈,Responses已吸收关键改进,更灵活、快速且易用,代表OpenAI智能体开发的后续方向。

Assistants API已于2026年8月26日正式停止服务,目前不可用。按迁移指南更新到Responses。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号