Responses API は、Chat Completions を進化させた新しい API の基盤です。連携をよりシンプルにし、エージェント型アプリケーションの構築に役立つ強力な基本機能を提供します。
Chat Completions のサポートは継続しますが、新規プロジェクトにはすべて Responses を推奨します。
Responses API は、エージェントのように動作する強力なアプリケーションを構築するための統一インターフェースです。次の機能を備えています。
Responses API には、Chat Completions と比べて次のようなメリットがあります。
性能の向上 :GPT-5 などのリーズニングモデルを Responses で使用すると、Chat Completions よりもモデルの能力を引き出せます。社内評価では、同じプロンプトと設定で SWE-bench のスコアが 3% 向上しました。
エージェント動作を標準でサポート :Responses API はエージェントの実行ループとして機能し、モデルは 1 回の API リクエスト内で、web_search、image_generation、file_search、code_interpreter、リモート MCP サーバーなどの複数のツールや、独自のカスタム関数を呼び出せます。
コストの削減 :キャッシュの活用効率が向上することで、コストを削減できます。社内テストでは、Chat Completions と比べてキャッシュの活用効率が 40%~80% 向上しました。
ステートフルなコンテキスト :store: true を使用すると、ターン間で状態を維持し、推論とツールのコンテキストを引き継げます。
柔軟な入力 :input には文字列またはメッセージのリストを渡せます。システムレベルの指示には instructions を使用します。
暗号化された推論 :状態の保持を無効にしても、高度な推論を活用できます。
将来を見据えた設計 :今後登場するモデルへの対応を見据えて設計されています。
できること Chat Completions API Responses API テキスト生成 音声 近日公開 画像認識 構造化出力 Function Calling ウェブ検索 ファイル検索 コンピューターの使用 Code Interpreter MCP 画像生成 推論の要約
具体的なシナリオで、Responses API と Chat Completions API の違いを確認します。
どちらの API でも、OpenAI のモデルから簡単に出力を生成できます。Chat Completions の呼び出しでは、入力と結果に メッセージ の配列を使用します。
一方、Responses API では アイテム を使用します。アイテムは複数の型のユニオンであり、モデルが実行できるさまざまなアクションを表します。
message はアイテムの型の一つで、function_call や function_call_output も同様です。
Chat Completions のメッセージが多くの役割を一つのオブジェクトにまとめているのに対し、アイテムは役割ごとに分かれており、モデルのコンテキストの基本単位をより適切に表現します。
また、Chat Completions では、n パラメーターを使用して複数の出力を並列に生成し、choices として返すことができます。Responses ではこのパラメーターを廃止し、生成する出力を一つに限定しています。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 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) 1
2
3
4
5
6
7
8
9
10
11
12
13 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) 1
2
3
4
5
6
7
8
9
10 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) 1
2
3
4
5
6
7
8 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 API から返されるレスポンスでは、フィールドが少し異なります。
message の代わりに、固有の id を持つ、型付きの response オブジェクトが返されます。
Responses のレスポンスはデフォルトで保存されます。Chat Completions のレスポンスは、新しいアカウントではデフォルトで保存されます。
どちらの API でも、保存を無効にするには store: false を設定します。
これらの API から返されるオブジェクトには、わずかな違いがあります。
Chat Completions では、各要素に message を含む choices 配列が返されます。Responses では、output という名前のアイテム配列が返されます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 {
"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"
}
],
...
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 {
"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 のレスポンスは、新しいアカウントではデフォルトで保存されます。どちらの API でも、保存を無効にするには store: false を設定します。
Responses API ではツールの活用が改善されている ため、リーズニングモデル をより効果的に利用できます。GPT-5.4 以降、Chat Completions では reasoning_effort が none 以外の値の場合、ツール呼び出しはサポートされません。
構造化出力の API 形式が異なります。Responses では response_format の代わりに text.format を使用します。詳しくは、構造化出力 ガイドをご覧ください。
Function Calling の API 形式は、リクエスト内の関数設定と、レスポンスで返される関数呼び出しの両方で異なります。違いの詳細については、Function Calling ガイド をご覧ください。
Responses SDK には、Chat Completions SDK にはない output_text ヘルパーがあります。
Chat Completions では、会話の状態を手動で管理する必要があります。Responses API では、永続的な会話を扱う Conversations API を利用できます。また、previous_response_id を渡すことで、レスポンスを簡単につなげることもできます。
移行は、互いに関連する三つの変更として捉えてください。リクエストの送信先を /v1/responses に変更し、型付きの output 配列から出力を読み取り、アプリケーションでターン間の状態を引き継ぐ方法を選びます。
まず、生成エンドポイントを post /v1/chat/completions から post /v1/responses に変更します。
関数やマルチモーダル入力を使用していない場合、シンプルなメッセージ入力は両方の API で互換性があります。
1
2
3
4
5
6
7
8
9
10
11
12
13
14 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,
}); 1
2
3
4
5
6
7
8 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) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 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())
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 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())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 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()); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 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) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 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 Responses
Chat Completions
Chat Completions では、
messages 配列を作成し、
completion.choices[0].message.content からモデルのテキストを読み取ります。
1
2
3
4
5
6
7
8
9
10
11 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); 1
2
3
4
5
6
7
8
9
10
11
12 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) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 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)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14 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); 1
2
3
4
5
6
7
8
9
10
11
12
13
14 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); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 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) 1
2
3
4
5
6
7
8
9
10 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
Responses では、トップレベルで
instructions と
input を分けて指定し、
response.output_text から生成されたテキストを読み取れます。
1
2
3
4
5
6
7
8
9
10 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); 1
2
3
4
5
6
7
8 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) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 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())
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 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())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 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()); 1
2
3
4
5
6
7
8
9
10
11 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) 1
2
3
4
5
6
7
8 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!"
}'
Chat Completions は、入力と出力の両方に messages を使用します。Responses は、型付きアイテムの配列である input と output を使用します。message はアイテムの型の 1 つで、ほかにも reasoning、function_call、function_call_output などがあります。
Chat Completions の概念 Responses での対応 messages[]文字列または入力アイテムの配列として指定する input システムまたは開発者からの指示 トップレベルの instructions、または既存の会話履歴を保持する必要がある場合は互換性のあるメッセージアイテム ユーザーメッセージ role: "user" を持つ入力メッセージアイテムアシスタントメッセージ response.output 内の出力メッセージアイテム。状態を手動で管理する場合は、input に含めて再度渡します。ツールまたは関数の呼び出し function_call 型の出力アイテムツールまたは関数の結果 call_id で呼び出しと関連付けられた function_call_output 型の入力アイテムn による複数候補の生成Responses では利用できません。複数の出力候補が必要な場合は、リクエストを個別に送信します。
最終的なテキストだけが必要な場合は、SDK の output_text ヘルパーを使用します。処理フローで推論、ツール、またはマルチモーダル出力を使用する場合は、response.output を反復処理し、各アイテムをその type に応じて処理します。
アプリケーションで複数ターンの会話を扱う場合は、コンテキストの管理ロジックを更新します。Responses には、一般的な状態管理の方法が 3 つあります。
以前のレスポンスのコンテキストを OpenAI に管理させたい場合は、previous_response_id を使用します。previous_response_id は前のレスポンスのトップレベルの instructions を引き継がないため、共通の instructions をリクエストごとに再送信してください。
コンテキストを自分で管理したり削減したりする必要がある場合は、以前の output アイテムを次のリクエストに含めて再度渡します。
永続的な会話オブジェクトが必要な場合は、Conversations API を使用します。
Chat Completions Responses
Chat Completions
Chat Completions では、会話履歴を保存し、
蓄積した
messages 配列をリクエストごとに送信します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 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,
}); 1
2
3
4
5
6
7
8
9
10 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) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 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)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 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); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 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); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 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
Responses では、あるレスポンスの出力を、
別のレスポンスの入力として手動で渡せます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 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,
}); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 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,
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 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
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 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())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 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()); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 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 を使用して前のレスポンスを参照し、
レスポンスを連鎖させたりフォークしたりすることもできます。
1
2
3
4
5
6
7
8
9
10
11
12 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 ,
}); 1
2
3
4
5
6
7
8
9
10 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,
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 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())
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 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())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 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()); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 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)
previous_response_id を使用する場合でも、連鎖するレスポンスに含まれる過去のすべての入力トークンは、API の入力トークンとして課金されます。
Responses のレスポンスはデフォルトで保存されます。Chat Completions のレスポンスも、新しいアカウントではデフォルトで保存されます。どちらの API でも、保存を無効にするには store: false を設定します。
ゼロデータ保持(ZDR)が要件となっている組織などでは、コンプライアンスやデータ保持ポリシーにより、Responses API をステートフルに使用できない場合があります。こうしたケースに対応するため、OpenAI は暗号化された推論アイテムを提供しています。これにより、ワークフローをステートレスに保ちながら、推論アイテムの利点を活用できます。
状態の保持を無効にしながら推論を活用するには、次の手順に従います。
store フィールド に store: false を設定します。
返されたすべての推論アイテムを保持し、再送信します。レスポンスを作成すると、各アイテムにはデフォルトで encrypted_content が含まれます。
すると API は暗号化された推論トークンを返します。これらは通常の推論アイテムと同じように、後続のリクエストで再度渡せます。
ZDR を利用する組織には、OpenAI が store: false を自動的に強制適用します。リクエストに encrypted_content が含まれている場合、その内容はメモリ内で復号され、次のレスポンスの生成に使用された後、安全に破棄されます。新たな推論トークンはすべて直ちに暗号化されて返されるため、中間状態は永続化されません。
Chat Completions と Responses の関数の定義方法には、小さいながらも注意すべき違いが 2 つあります。
Chat Completions では、関数定義のタグは外部に配置されます。Responses では、内部に配置されます。
Chat Completions では、関数はデフォルトで非厳密モードです。Responses では、strict を省略すると厳密モードの適用を試みます。スキーマを厳密モードに適合させられない場合は、非厳密モードのベストエフォート型 Function Calling にフォールバックし、解決後のツールを strict: false とともに返します。Responses で非厳密モードの動作を明示的に維持するには、strict: false を設定します。
右側の Responses API の関数の例は、左側の Chat Completions の例と機能的に同等です。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 {
"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"
]
}
}
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 {
"type" : "function" ,
"name" : "get_weather" ,
"description" : "Determine weather in my location" ,
"parameters" : {
"type" : "object" ,
"properties" : {
"location" : {
"type" : "string"
}
},
"additionalProperties" : false ,
"required" : [
"location"
]
}
}
Responses では、ツール呼び出しとその出力はそれぞれ別の種類のアイテムで、call_id を使って関連付けられます。
Responses での Function Calling の仕組みについて詳しくは、Function Calling のドキュメント をご覧ください。
Responses API では、構造化出力の定義が response_format から text.format に移動しました。
Chat Completions Responses Chat Completions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 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" ,
}); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 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",
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 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)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 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); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 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); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 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) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 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 ,
},
},
},
}); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 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,
},
}
},
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 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())
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 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())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 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()); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 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) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 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
}
}
}
}'
Chat Completions のストリーミングでは、delta フィールドを含むチャンクが逐次返されます。Responses のストリーミングでは、型付きのサーバー送信イベントを使用します。各イベントの type に応じて処理を分岐し、UI やオーケストレーション層に必要なイベントを処理するよう、ストリームの受信処理を更新してください。
テキストのストリーミングでは、次のようなイベントを受信して処理します。
response.created
response.output_text.delta
response.completed
error
Function Calling のストリームでも、response.function_call_arguments.delta や response.function_call_arguments.done などのイベントが発生することがあります。Responses のストリーミングガイド とResponses のストリーミングイベントのリファレンス をご覧ください。
アプリケーションに OpenAI のネイティブツール が役立つユースケースがある場合は、ツール呼び出しを更新することで、OpenAI のツールをそのまま利用できます。
Chat Completions Responses
Chat Completions
Chat Completions では、OpenAI がホストするツールをネイティブに利用できないため、
ツール連携を自分で実装する必要があります。
GPT-6 Astra でツールを呼び出すには Responses API が必要なため、
この例では GPT-5.6 を使用しています。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 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" ,
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" ],
},
},
],
}); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 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",
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"],
},
}
],
) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 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",
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)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 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")
.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); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 require "openai"
client = OpenAI::Client.new
completion = client.chat.completions.create(
model: "gpt-5.6",
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) 1
2
3
4 curl https://api.example.com/search \
-G \
--data-urlencode "q=your+search+term" \
--data-urlencode "key=$SEARCH_API_KEY"
Responses
Responses では、モデルに使用させたいツールを指定できます。
1
2
3
4
5
6
7 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); 1
2
3
4
5
6
7 answer = client.responses.create(
model="gpt-6-astra",
input="Who is the current president of France?",
tools=[{"type": "web_search"}],
)
print(answer.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 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())
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 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())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14 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()); 1
2
3
4
5
6
7
8
9
10
11 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) 1
2
3
4
5
6
7
8 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"}]
}'
コードを Chat Completions から Responses に移行する際は、次のような問題に注意してください。
response.output_text や response.output ではなく、choices[0].message.content を読み取ってしまうこと
output のすべての要素をメッセージとして扱ってしまうこと。推論、ツール呼び出し、関数呼び出しは、それぞれ別の種類のアイテムです。
コンテキストを次のレスポンスに手動で引き継ぐ際に、推論、関数呼び出し、関数呼び出しの出力のアイテムを省いてしまうこと
対応する call_id を含めずに関数の結果を送信してしまうこと
Responses のリクエストで、text.format ではなく response_format を使用してしまうこと
Responses の型付きイベントに対応せずに、Chat Completions のストリーミングチャンク用ハンドラーを再利用してしまうこと
previous_response_id を使うと過去のコンテキストへの課金がなくなると思い込んでしまうこと。レスポンスチェーン内の過去の入力トークンは、引き続き入力トークンとして課金されます。
Chat Completions は引き続きサポートされるため、ユーザーフローを 1 つずつ移行できます。
OpenAI の最新機能や改善を活用できるよう、すべてのフローを段階的に Responses API へ移行することをおすすめします。
Assistants API ベータ版に対する開発者のフィードバックをもとに、Responses API に主要な改善を取り入れ、柔軟性、速度、使いやすさを向上させました。Responses API は、OpenAI でエージェントを構築するための今後の方向性を示すものです。
Assistants API は 2026 年 8 月 26 日に正式に提供を終了し、現在は利用できません。移行ガイド に従って、連携先を Responses API に更新してください。