Token 计数让您在向模型发送请求之前,就能确定请求将使用多少输入 Token。您可以用它来:
- 优化提示 ,使其符合上下文限制
- 在调用 API 之前估算费用
- 根据请求大小路由请求 (例如,将较短的提示发送给速度更快的模型)
- 处理图像和文件时避免用量超出预期 ,不再依赖基于字符数的估算
输入 Token 计数端点接受与 Responses API 相同的输入格式。传入文本、消息、图像、文件、工具或对话,API 即可返回模型将接收的准确 Token 数量。
计数包含用于表示请求结构的格式 Token,例如用于标识消息角色和边界的 Token。这些 Token 可能不会出现在您在本地进行 Token 化处理的文本或字段中。
tiktoken 等本地 Token 化工具适用于纯文本,但存在以下局限:
- 不支持图像和文件 ,使用
characters / 4 等方式估算并不准确
- 工具和模式 会增加难以在本地统计的 Token
- 模型特有的行为 (例如推理、缓存)可能改变 Token 化处理方式
Token 计数 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
图像消耗的 Token 数量取决于图像尺寸和细节级别。Token 计数 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 服务器等)会增加上下文中的 Token 数量。请将它们与您的输入一并统计:
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。Token 计数涵盖模型处理后的完整输入。
报告的输出 Token 用量包含模型生成的所有 Token,而不仅仅是响应中的可见文本。Responses API 通过 output_tokens 报告这一总数,Chat Completions API 则通过 completion_tokens 报告。
包括 GPT-5 模型在内的某些模型会生成用于格式化或分隔响应通道、工具调用及其他消息结构的 Token。这些格式 Token 不会出现在消息内容或 logprobs 中,也不一定会在用量中单独列出。因此,即使报告的 reasoning_tokens 值为 0,报告的输出或补全 Token 数量也可能高于可见 Token 数量或 logprobs 中包含的 Token 数量。
max_output_tokens 和 max_completion_tokens 参数限制的是模型生成的所有 Token 的总量,包括不可见的 Token。不可见 Token 的数量会因模型和响应结构而异,因此请勿假定报告用量与可见输出之间存在固定差值。当您需要特定数量的可见输出时,请在设置这些限制时预留余量。
有关完整的参数说明和响应结构,请参阅输入 Token 计数 API 参考。端点如下:
POST /v1/responses/input_tokens
响应包含 input_tokens(整数)和 object: "response.input_tokens"。