Mit der Tokenzählung ermittelst du, wie viele Eingabetoken eine Anfrage benötigt, bevor du sie an das Modell sendest. Damit kannst du:
- Prompts optimieren , damit sie die Kontextgrenzen einhalten
- Kosten abschätzen , bevor du API-Aufrufe ausführst
- Anfragen weiterleiten , je nach Umfang (zum Beispiel kürzere Prompts an schnellere Modelle)
- Überraschungen vermeiden , wenn du Bilder und Dateien verwendest, ohne auf Schätzungen anhand der Zeichenzahl angewiesen zu sein
Der Endpunkt zum Zählen von Eingabetoken akzeptiert dasselbe Eingabeformat wie die Responses API. Übergib Text, Nachrichten, Bilder, Dateien, Werkzeuge oder Unterhaltungen. Die API gibt die genaue Anzahl der Token zurück, die das Modell erhält.
Die Zählung umfasst auch Formatierungstoken, die die Struktur der Anfrage abbilden, etwa Nachrichtenrollen und Nachrichtengrenzen. Diese Token sind möglicherweise nicht in den Texten oder Feldern enthalten, die du lokal tokenisierst.
Lokale Tokenizer wie tiktoken funktionieren für reinen Text, haben aber Einschränkungen:
- Bilder und Dateien werden nicht unterstützt. Schätzungen wie
characters / 4 sind ungenau
- Tools und Schemas fügen Token hinzu, die sich lokal nur schwer zählen lassen
- Modellspezifisches Verhalten kann die Tokenisierung verändern (zum Beispiel Reasoning-Aufwand oder Caching)
Die API zur Tokenzählung berücksichtigt all diese Fälle. Verwende dieselbe Nutzlast, die du an responses.create senden würdest, um eine genaue Anzahl zu erhalten. Nutze das Ergebnis anschließend zur Validierung deiner Nachrichten oder zur Kostenschätzung.
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
Wie viele Token Bilder verbrauchen, hängt von ihrer Größe und Detailstufe ab. Die API zur Tokenzählung liefert die genaue Anzahl, ganz ohne Schätzungen.
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
Du kannst file_id (aus der Files API) oder image_url (eine URL oder eine Base64-Daten-URL) verwenden. Weitere Informationen findest du unter Bilder und Bildverständnis.
Tool-Definitionen (Funktionsschemas, MCP-Server usw.) fügen dem Kontext Token hinzu. Zähle sie zusammen mit deiner Eingabe:
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
Dateieingaben (derzeit PDFs) werden unterstützt. Übergib file_id, file_url oder file_data wie bei responses.create. Die Tokenanzahl entspricht der gesamten für das Modell aufbereiteten Eingabe.
Der gemeldete Verbrauch an Ausgabetoken umfasst alle vom Modell generierten Token, nicht nur den sichtbaren Text einer Antwort. Die Responses API meldet diese Gesamtzahl als output_tokens, die Chat Completions API als completion_tokens.
Einige Modelle, darunter GPT-5-Modelle, generieren Token, um Antwortkanäle, Tool-Aufrufe und andere Bestandteile der Nachrichtenstruktur zu formatieren oder voneinander abzugrenzen. Diese Formatierungstoken erscheinen weder im Nachrichteninhalt noch in logprobs und werden in den Verbrauchsangaben nicht unbedingt separat ausgewiesen. Daher kann die gemeldete Anzahl der Ausgabe- oder Completion-Token höher sein als die Anzahl der sichtbaren oder in logprobs enthaltenen Token, selbst wenn der gemeldete Wert für reasoning_tokens bei 0 liegt.
Die Parameter max_output_tokens und max_completion_tokens begrenzen die Gesamtzahl aller vom Modell generierten Token, einschließlich der nicht sichtbaren Token. Die Anzahl der nicht sichtbaren Token variiert je nach Modell und Antwortstruktur. Gehe deshalb nicht von einer festen Differenz zwischen dem gemeldeten Verbrauch und der sichtbaren Ausgabe aus. Plane bei diesen Grenzen einen Puffer ein, wenn du eine bestimmte Menge an sichtbarer Ausgabe benötigst.
Alle Parameter und die Antwortstruktur findest du in der API-Referenz zum Zählen von Eingabetoken. Der Endpunkt lautet:
POST /v1/responses/input_tokens
Die Antwort enthält input_tokens (Ganzzahl) und object: "response.input_tokens".