トークン数をカウントすると、リクエストをモデルに送信する前に、そのリクエストで使われる入力トークン数を確認できます。次のような用途に役立ちます。
- コンテキストの上限に収まるようにプロンプトを最適化
- API を呼び出す前にコストを見積もり
- サイズに応じてリクエストを振り分け (例:短いプロンプトを高速なモデルに送信)
- 文字数に基づく推定に頼らず、画像やファイルでの想定外のトークン消費を回避
入力トークン数カウントエンドポイントは、Responses API と同じ入力形式に対応しています。テキスト、メッセージ、画像、ファイル、ツール、会話を渡すと、API はモデルが受け取る正確なトークン数を返します。
カウントには、メッセージのロールや境界など、リクエストの構造を表すための書式トークンも含まれます。これらのトークンは、ローカルでトークン化するテキストやフィールドには現れない場合があります。
tiktoken などのローカルトークナイザーはプレーンテキストに使えますが、次のような制限があります。
- 画像やファイル には非対応で、
characters / 4 のような推定方法では不正確
- ツールやスキーマ によって追加されるトークンは、ローカルでのカウントが困難
- モデル固有の動作 (推論やキャッシュなど)によってトークン化が変わることがあります
トークン数カウント API は、これらすべてに対応しています。responses.create に送信するものと同じペイロードを使えば、正確なトークン数を取得できます。その結果を、メッセージの検証やコスト見積もりのフローに組み込めます。
1
2
3
4
5
6
7
8
9
10import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.inputTokens.count({
model: "gpt-6-astra",
input: "Tell me a joke.",
});
console.log(response.input_tokens);
1
2
3
4
5
6
7
8from openai import OpenAI
client = OpenAI()
response = client.responses.input_tokens.count(
model="gpt-6-astra", input="Tell me a joke."
)
print(response.input_tokens)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{
Model: openai.String("gpt-6-astra"),
Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("Tell me a joke.")},
})
if err != nil {
panic(err)
}
fmt.Println(count.InputTokens)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.inputtokens.InputTokenCountParams;
var count =
client
.responses()
.inputTokens()
.count(
InputTokenCountParams.builder()
.model("gpt-6-astra")
.input("Tell me a joke.")
.build());
System.out.println(count.inputTokens());
1
2
3
4
5
6
7
8
9
10require "openai"
client = OpenAI::Client.new
count = client.responses.input_tokens.count(
model: "gpt-6-astra",
input: "Tell me a joke."
)
puts(count.input_tokens)
1
2
3
4
5
6
7curl https://api.openai.com/v1/responses/input_tokens \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"input": "Tell me a joke."
}'
1
2
3
4
5openai responses:input-tokens count \
--model gpt-6-astra \
--input "Tell me a joke." \
--raw-output \
--transform input_tokens
1
2
3
4
5
6
7
8
9
10
11
12
13
14import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.inputTokens.count({
model: "gpt-6-astra",
input: [
{ role: "user", content: "What is 2 + 2?" },
{ role: "assistant", content: "2 + 2 equals 4." },
{ role: "user", content: "What about 3 + 3?" },
],
});
console.log(response.input_tokens);
1
2
3
4
5
6
7
8
9
10
11
12
13from openai import OpenAI
client = OpenAI()
response = client.responses.input_tokens.count(
model="gpt-6-astra",
input=[
{"role": "user", "content": "What is 2 + 2?"},
{"role": "assistant", "content": "2 + 2 equals 4."},
{"role": "user", "content": "What about 3 + 3?"},
],
)
print(response.input_tokens)
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
26package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
input := []responses.ResponseInputItemUnionParam{
responses.ResponseInputItemParamOfMessage("What is 2 + 2?", responses.EasyInputMessageRoleUser),
responses.ResponseInputItemParamOfMessage("2 + 2 equals 4.", responses.EasyInputMessageRoleAssistant),
responses.ResponseInputItemParamOfMessage("What about 3 + 3?", responses.EasyInputMessageRoleUser),
}
count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{
Model: openai.String("gpt-6-astra"),
Input: responses.InputTokenCountParamsInputUnion{OfResponseInputItemArray: input},
})
if err != nil {
panic(err)
}
fmt.Println(count.InputTokens)
}
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
34import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseInputItem;
import com.openai.models.responses.inputtokens.InputTokenCountParams;
import java.util.List;
var count =
client
.responses()
.inputTokens()
.count(
InputTokenCountParams.builder()
.model("gpt-6-astra")
.inputOfResponseInputItems(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("What is 2 + 2?")
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.ASSISTANT)
.content("2 + 2 equals 4.")
.build()),
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("What about 3 + 3?")
.build())))
.build());
System.out.println(count.inputTokens());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24require "openai"
client = OpenAI::Client.new
conversation = [
{
role: :user,
content: "What is 2 + 2?"
},
{
role: :assistant,
content: "2 + 2 equals 4."
},
{
role: :user,
content: "What about 3 + 3?"
}
]
count = client.responses.input_tokens.count(
model: "gpt-6-astra",
input: conversation
)
puts(count.input_tokens)
1
2
3
4
5
6
7
8
9
10
11curl https://api.openai.com/v1/responses/input_tokens \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"input": [
{"role": "user", "content": "What is 2 + 2?"},
{"role": "assistant", "content": "2 + 2 equals 4."},
{"role": "user", "content": "What about 3 + 3?"}
]
}'
1
2
3
4
5
6
7
8
9
10
11
12openai responses:input-tokens count \
--raw-output \
--transform input_tokens <<'YAML'
model: gpt-6-astra
input:
- role: user
content: What is 2 + 2?
- role: assistant
content: 2 + 2 equals 4.
- role: user
content: What about 3 + 3?
YAML
1
2
3
4
5
6
7
8
9
10
11import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.inputTokens.count({
model: "gpt-6-astra",
instructions: "You are a helpful assistant that explains concepts simply.",
input: "Explain quantum computing in one sentence.",
});
console.log(response.input_tokens);
1
2
3
4
5
6
7
8
9
10from openai import OpenAI
client = OpenAI()
response = client.responses.input_tokens.count(
model="gpt-6-astra",
instructions="You are a helpful assistant that explains concepts simply.",
input="Explain quantum computing in one sentence.",
)
print(response.input_tokens)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{
Model: openai.String("gpt-6-astra"),
Instructions: openai.String("You are a helpful assistant that explains concepts simply."),
Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("Explain quantum computing in one sentence.")},
})
if err != nil {
panic(err)
}
fmt.Println(count.InputTokens)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.inputtokens.InputTokenCountParams;
var count =
client
.responses()
.inputTokens()
.count(
InputTokenCountParams.builder()
.model("gpt-6-astra")
.input("Explain quantum computing in one sentence.")
.instructions("You are a helpful assistant that explains concepts simply.")
.build());
System.out.println(count.inputTokens());
1
2
3
4
5
6
7
8
9
10
11require "openai"
client = OpenAI::Client.new
count = client.responses.input_tokens.count(
model: "gpt-6-astra",
instructions: "You are a helpful assistant that explains concepts simply.",
input: "Explain quantum computing in one sentence."
)
puts(count.input_tokens)
1
2
3
4
5
6
7
8curl https://api.openai.com/v1/responses/input_tokens \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"instructions": "You are a helpful assistant that explains concepts simply.",
"input": "Explain quantum computing in one sentence."
}'
1
2
3
4
5
6
7openai responses:input-tokens count \
--raw-output \
--transform input_tokens <<'YAML'
model: gpt-6-astra
instructions: You are a helpful assistant that explains concepts simply.
input: Explain quantum computing in one sentence.
YAML
画像は、サイズと詳細度に応じてトークンを消費します。トークン数カウント API は正確な数を返すため、推測する必要はありません。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.inputTokens.count({
model: "gpt-6-astra",
input: [
{
role: "user",
content: [
{
type: "input_image",
image_url: "https://example.com/chart.png",
detail: "auto",
},
{ type: "input_text", text: "Summarize this chart." },
],
},
],
});
console.log(response.input_tokens);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21from openai import OpenAI
client = OpenAI()
# Use file_id from uploaded file, or image_url for a URL
response = client.responses.input_tokens.count(
model="gpt-6-astra",
input=[
{
"role": "user",
"content": [
{
"type": "input_image",
"image_url": "https://example.com/chart.png",
},
{"type": "input_text", "text": "Summarize this chart."},
],
}
],
)
print(response.input_tokens)
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
30package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
input := []responses.ResponseInputItemUnionParam{
responses.ResponseInputItemParamOfMessage(
responses.ResponseInputMessageContentListParam{
{OfInputImage: &responses.ResponseInputImageParam{ImageURL: openai.String("https://example.com/chart.png"), Detail: responses.ResponseInputImageDetailAuto}},
{OfInputText: &responses.ResponseInputTextParam{Text: "Summarize this chart."}},
},
responses.EasyInputMessageRoleUser,
),
}
count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{
Model: openai.String("gpt-6-astra"),
Input: responses.InputTokenCountParamsInputUnion{OfResponseInputItemArray: input},
})
if err != nil {
panic(err)
}
fmt.Println(count.InputTokens)
}
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
30import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
import com.openai.models.responses.inputtokens.InputTokenCountParams;
import java.util.List;
var count =
client
.responses()
.inputTokens()
.count(
InputTokenCountParams.builder()
.model("gpt-6-astra")
.inputOfResponseInputItems(
List.of(
ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addContent(
ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.imageUrl(
"https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg")
.build())
.addInputTextContent("Summarize this chart.")
.build())))
.build());
System.out.println(count.inputTokens());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25require "openai"
client = OpenAI::Client.new
count = client.responses.input_tokens.count(
model: "gpt-6-astra",
input: [
{
role: :user,
content: [
{
type: :input_image,
image_url: "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg",
detail: :auto
},
{
type: :input_text,
text: "Summarize this chart."
}
]
}
]
)
puts(count.input_tokens)
1
2
3
4
5
6
7
8
9
10
11
12
13curl https://api.openai.com/v1/responses/input_tokens \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"input": [{
"role": "user",
"content": [
{"type": "input_image", "image_url": "https://example.com/chart.png"},
{"type": "input_text", "text": "Summarize this chart."}
]
}]
}'
1
2
3
4
5
6
7
8
9
10
11
12openai responses:input-tokens count \
--raw-output \
--transform input_tokens <<'YAML'
model: gpt-6-astra
input:
- role: user
content:
- type: input_image
image_url: https://example.com/chart.png
- type: input_text
text: Summarize this chart.
YAML
file_id(Files API から取得)、または image_url(URL または base64 データ URL)を使用できます。詳しくは、画像と視覚認識をご覧ください。
ツール定義(関数スキーマや MCP サーバーなど)は、コンテキストにトークンを追加します。入力と合わせてカウントしてください。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.inputTokens.count({
model: "gpt-6-astra",
tools: [
{
type: "function",
name: "get_weather",
description: "Get the current weather in a location",
strict: true,
parameters: {
type: "object",
properties: { location: { type: "string" } },
required: ["location"],
additionalProperties: false,
},
},
],
input: "What is the weather in San Francisco?",
});
console.log(response.input_tokens);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21from openai import OpenAI
client = OpenAI()
response = client.responses.input_tokens.count(
model="gpt-6-astra",
tools=[
{
"type": "function",
"name": "get_weather",
"description": "Get the current weather in a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
}
],
input="What is the weather in San Francisco?",
)
print(response.input_tokens)
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
32package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
parameters := map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]any{"type": "string"},
},
"required": []string{"location"},
"additionalProperties": false,
}
tool := responses.ToolParamOfFunction("get_weather", parameters, true)
tool.OfFunction.Description = openai.String("Get the current weather in a location")
count, err := client.Responses.InputTokens.Count(context.Background(), responses.InputTokenCountParams{
Model: openai.String("gpt-6-astra"),
Input: responses.InputTokenCountParamsInputUnion{OfString: openai.String("What is the weather in San Francisco?")},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
fmt.Println(count.InputTokens)
}
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
37import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.inputtokens.InputTokenCountParams;
import java.util.List;
import java.util.Map;
var count =
client
.responses()
.inputTokens()
.count(
InputTokenCountParams.builder()
.model("gpt-6-astra")
.input("What is the weather in San Francisco?")
.addTool(
FunctionTool.builder()
.name("get_weather")
.description("Get the current weather in a location")
.strict(true)
.parameters(
FunctionTool.Parameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties",
JsonValue.from(
Map.of("location", Map.of("type", "string"))))
.putAdditionalProperty(
"required", JsonValue.from(List.of("location")))
.putAdditionalProperty(
"additionalProperties", JsonValue.from(false))
.build())
.build())
.build());
System.out.println(count.inputTokens());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24require "openai"
client = OpenAI::Client.new
count = client.responses.input_tokens.count(
model: "gpt-6-astra",
input: "What is the weather in San Francisco?",
tools: [
{
type: :function,
name: "get_weather",
description: "Get the current weather in a location",
strict: true,
parameters: {
type: "object",
properties: { location: { type: "string" } },
required: ["location"],
additionalProperties: false
}
}
]
)
puts(count.input_tokens)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17curl https://api.openai.com/v1/responses/input_tokens \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Get the current weather in a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"]
}
}],
"input": "What is the weather in San Francisco?"
}'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17openai responses:input-tokens count \
--raw-output \
--transform input_tokens <<'YAML'
model: gpt-6-astra
tools:
- type: function
name: get_weather
description: Get the current weather in a location
parameters:
type: object
properties:
location:
type: string
required:
- location
input: What is the weather in San Francisco?
YAML
ファイル入力(現在は PDF)に対応しています。responses.create と同様に、file_id、file_url、または file_data を渡してください。トークン数には、モデル向けに処理された入力全体が反映されます。
報告される出力トークン使用量には、レスポンスに表示されるテキストだけでなく、モデルが生成したすべてのトークンが含まれます。Responses API はこの合計を output_tokens として、Chat Completions API は completion_tokens として報告します。
GPT-5 モデルを含む一部のモデルは、レスポンスのチャネル、ツール呼び出し、その他のメッセージ構造の書式設定や区切りに使うトークンを生成します。これらの書式トークンは、メッセージの内容や logprobs には現れず、使用量の内訳に別項目として示されるとも限りません。そのため、報告される reasoning_tokens の値が 0 であっても、報告される出力トークン数や完了トークン数は、表示されるトークン数や logprobs に含まれるトークン数より多くなる場合があります。
max_output_tokens と max_completion_tokens パラメーターは、表示されないトークンも含め、モデルが生成するすべてのトークンの数を制限します。表示されないトークンの数はモデルやレスポンスの構造によって異なるため、報告される使用量と表示される出力との差が一定だとは考えないでください。表示される出力を一定量確保したい場合は、これらの上限に余裕を持たせてください。
すべてのパラメーターとレスポンスの構造については、入力トークン数カウント API リファレンスを参照してください。エンドポイントは次のとおりです:
POST /v1/responses/input_tokens
レスポンスには、input_tokens(整数)と object: "response.input_tokens" が含まれます。