tencent cloud

DokumentasiLLM Service TokenHubAPI Integration GuideLanguage ModelAnthropic Message Protocol Field Descriptions

Anthropic Message Protocol Field Descriptions

Download
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-08-14 18:39:39
Diterjemahkan oleh AI

Using the Anthropic Messages API

Request Parameter Details

Basic Parameters

Parameter
Type
Required
Description
model
string
Yes
Name of the model to use, for example, deepseek-v4-flash.
messages
array
Yes
A list of conversation messages, arranged in chronological order and containing the full context. The platform does not manage sessions. For multi-turn conversations, the client must carry the complete history. For details, see Message Object Details.
system
string or array
No
System prompt. It is not within messages and is passed separately via the top-level system field. This is a key difference from the OpenAI Chat protocol.
max_tokens
integer
Yes
The maximum number of tokens that can be generated in a single model output. Different models have their own limits. Tokens consumed by the reasoning chain are counted toward this limit. Therefore, when thinking is enabled, this value must be greater than budget_tokens. When the limit is reached, stop_reason is "max_tokens".
stream
boolean
No
Whether to enable streaming responses (default: false). When true, responses are returned event by event in SSE format.
The system supports two forms:
// String
"system": "You are a friendly assistant."

// Content block array (which can carry cache_control)
"system": [
{ "type": "text", "text": "You are a friendly assistant." },
{ "type": "text", "text": "<Long Document>", "cache_control": { "type": "ephemeral" } }
]
Note:
Regarding max_tokens: This field is required in the Anthropic protocol. Some models may apply lenient fallback handling for missing or invalid max_tokens. However, always explicitly pass this field according to the protocol standard and do not rely on fallback behavior.

Generation Control Parameters

Parameter
Type
Scope
Description
temperature
float
[0, 1]
Sampling temperature. Note that the Anthropic range is [0, 1], which differs from OpenAI's [0, 2].
top_p
float
(0, 1]
Nucleus sampling. Generally, adjust only one of temperature or top_p.
top_k
integer
-
Samples only from the top K tokens with the highest probability. This is a parameter specific to Anthropic and is not present in the OpenAI Chat protocol.
stop_sequences
string[]
-
Custom stop sequences. Stops immediately when any sequence is matched, with stop_reason set to "stop_sequence". The matched sequence is written back to the stop_sequence field in the response.
Note:
Regarding thinking and temperature: When thinking is enabled, some models require temperature to be fixed at 1. Other models may tolerate temperature != 1. For thinking scenarios, use the default value or 1. Whether strict validation is enforced depends on the model. Regarding stop_sequences: Some models can reliably write back stop_reason=stop_sequence and the matched stop_sequence, while others do not guarantee write-back. Services that rely on precise stop semantics should validate against the target model.

Tool Call

Anthropic's tool definition structure differs from OpenAI's: fields are directly flattened, and the parameter field is named input_schema (OpenAI uses function.parameters).
{
"name": "get_weather",
"description": "Query the weather information for a specified city",
"input_schema": {
"type": "object",
"properties": {
"location": { "type": "string", "description": "City name" }
},
"required": ["location"]
}
}
Field
Type
Required
Description
name
string
Yes
Tool name.
description
string
No
Describes the tool's purpose, helping the model determine when to call it.
input_schema
object
Yes
Parameter definitions, which follow the JSON Schema format.
type
string
No
Leave it blank for regular tools. For built-in tools, enter the type name (for example, web_search_20250305).
max_uses
integer
No
Maximum number of calls per session for built-in tools.
cache_control
object
No
Cache flag at the tool definition level.
tool_choice(Anthropic uses an object format):
Anthropic tool_choice
Equivalent OpenAI
Description
{"type":"auto"}
"auto"
Default, the model decides on its own.
{"type":"any"}
"required"
Forces the model to call any available tool.
{"type":"none"}
"none"
Disables tool calls.
{"type":"tool","name":"x"}
{"type":"function","function":{"name":"x"}}
Forces the model to call a specified tool.
Optional subfield disable_parallel_tool_use (boolean): When set to true, it disables the parallel invocation of multiple tools within a single response.
Attention:
Combination restrictions with thinking: When thinking is enabled or entered by default, some models do not support forced tool calls (tool_choice:any and tool_choice:tool). Typically, only auto / none can be used together with thinking. If you need to force a tool call, explicitly pass thinking: {"type":"disabled"} first, and then use any or specify a tool. For specific differences among models, see Model Field Compatibility.

Chain of Thought (Extended Thinking)

Enable the extended thinking chain to allow the model to perform internal reasoning before generating the final response. This is suitable for tasks involving complex logic, mathematics, code, and similar challenges.
{
"thinking": {
"type": "enabled",
"budget_tokens": 8000
}
}
Field
Type
Required
Description
type
string
Yes
"enabled" for enabling / "disabled" for disabling / "adaptive" for adaptive mode.
budget_tokens
integer
Conditional
Recommended when enabled. This is the budget for chain-of-thought tokens (recommended range: 1024 to 32000). The value must be less than max_tokens.
display
string
No
The method for displaying the reasoning process (supported by some models).
Field requirements for different types: For enabled, include budget_tokens (and optionally display). For disabled, only type is required. For adaptive, include type (and optionally display), and the budget is adaptively allocated by the model.
Note:
Model Differences: Some reasoning models return a thinking block by default even when thinking is not passed. Other models may tolerate non-strict constraints such as missing budget_tokens, budget_tokens >= max_tokens, or temperature != 1. These are model/platform compatibility behaviors and should not be treated as a universal contract for all models. If you do not want thinking content returned, explicitly pass thinking: {"type":"disabled"}. Relationship with OpenAI-Compatible Parameters: Some vendor documentation uses fields like enable_thinking and reasoning_effort to describe thinking capabilities. In the Anthropic Messages protocol, the corresponding expressions are thinking.type, output_config.effort, and the thinking / redacted_thinking content blocks that are returned unchanged from the assistant in multi-turn history. Do not directly mix enable_thinking in the Messages request body.
Interleaved Thinking: Some models support interleaving thinking content during response generation. For models like Hunyuan, this feature is enabled via the request header Hunyuan-Beta. The platform forwards this header to the model service. This request header is an extended capability. Models that do not support it will ignore the header without reporting an error. To confirm whether it actually takes effect, refer to the capability documentation of the model you are using.

Output Configuration

output_config (object): Controls the output effort level and structured format.
{
"output_config": {
"effort": "high",
"format": {
"type": "json_schema",
"schema": { "type": "object", "properties": { "answer": { "type": "string" } } }
}
}
}
Field
Type
Description
effort
string
Output effort level: low / medium / high / xhigh / max.
format.type
string
Structured output type (such as json_schema).
format.schema
object
JSON Schema definition.
Note:
This field is an extended capability, and vendor support varies: output_config.effort is accepted by most models. For structured output with output_config.format.type=json_schema, only some models can reliably generate JSON according to the schema. Some models return a 200 status code but the JSON does not fully comply with the schema, while others return a 400. Do not treat json_schema as a universal capability for all models. Before using it, verify it against your target model.

Caching (Prompt Caching)

Use cache_control to tag cacheable content. After a cache hit, this significantly reduces the billing for input_tokens from repeated prompts. Three levels of tagging are supported:
Layer
Tag Location
Description
Tool level
tools[n].cache_control
Cache tool definition
System level
system[n].cache_control
Cache system content blocks
Message/content block level
messages[n].content[m].cache_control
Cache historical messages or content blocks
cache_control object structure:
{ "type": "ephemeral" } // Default 5-minute TTL
{ "type": "ephemeral", "ttl": "1h" } // 1-hour TTL
Cache hit details are returned via the cache_creation_input_tokens and cache_read_input_tokens fields in the response usage. If the model does not support caching, the related tokens are counted as 0.
Note:
Capability Description: Most models allow you to observe some cache tokens. However, details such as top-level cache_control, document block-level cache, ttl:"1h" specifics, and cache_creation.ephemeral_1h_input_tokens are generally incomplete. Interpret this as "partial support for Prompt Caching". Do not rely on complete Anthropic TTL / usage details.

Metadata and Service Levels

metadata (object): Request metadata. metadata.user_id (string) is the unique identifier for the end user, used for abuse detection and usage attribution.
service_tier (string): Service tier / TPM guarantee channel identifier. The actually matched tier is written back in the response.
Value
Description
auto
Automatic selection
standard
Standard tier
priority
Priority tier (higher guarantee)
batch
Batch tier

Request Header

Request header
Required
Description
x-api-key
Yes
API Key (Anthropic's official convention); the platform also supports Authorization: Bearer <key>.
anthropic-version
Yes
API version, fixed to 2023-06-01.
content-type
Yes
application/json
anthropic-beta
No
beta feature switch (such as prompt-caching and interleaved-thinking), which the platform transparently passes through to the model service as is.

Message Object Details

Each element in the messages array represents a message in the conversation.
role enumeration:
role
Description
Usage Location
user
Input from human users (including tool_result)
Odd-numbered conversation turns.
assistant
Historical responses from the model (may include text / thinking / tool_use)
Used in even-numbered conversation turns. For multi-turn conversations, historical context must be carried over.
Note:
Key Differences: The Anthropic protocol does not have a separate tool role. Tool execution results are expressed as a tool_result content block within a user message, and they immediately follow the corresponding tool_use from the assistant. This differs from the OpenAI Chat protocol, which has a separate tool role. The system is not within the messages array; it is passed via the top-level system field.
content format: It supports two forms: a string or an array of content blocks.
// String
{"role": "user", "content": "Hello"}

// Content block array
{
"role": "user",
"content": [
{ "type": "text", "text": "What is in this picture?" },
{ "type": "image", "source": { "type": "url", "url": "https://example.com/img.jpg" } }
]
}
content block type:
block type
Key Fields
Applicable role
Description
text
text,cache_control
user / assistant
Text Content
image
source
user
Figure
video
source
user
Video
document
source,title,context,citations,cache_control
user
Document Input and Citation
search_result
source,title,content,citations
user
Search result content block
tool_use
id,name,input
assistant
Model requests to invoke a tool
tool_result
tool_use_id,content
user
Tool execution result
thinking
thinking,signature
assistant
Reasoning chain content
redacted_thinking
data
assistant
Redacted reasoning chain
Note:
Capability Description: text, tool_use, the text tool_result, and thinking are generally available on models that support the corresponding capabilities. The image block requires a model that explicitly supports vision/multimodal capabilities; pure text models return a 400 error. Most models can receive document but do not return citations; search_result is generally not supported by current models.
Multimodal block:
Image block (type: "image"):
// Base64
{ "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "/9j/4AAQ..." } }

// URL
{ "type": "image", "source": { "type": "url", "url": "https://example.com/photo.jpg" } }
source Field
Type
Description
type
string
"base64" or "url".
media_type
string
Required when base64 is selected, for example, image/jpeg, image/png, image/gif, or image/webp.
data
string
Image data when base64 is selected.
url
string
Image address when url is selected.
detail
string
low / high / auto for image analysis detail.
Note:
Capability Description: When image understanding is required, use a model that explicitly supports vision/multimodal (VL) capabilities and verify this separately in the model's capability description. Pure text models return a 400 error for the image block.
Document block (type: "document"): source (supports text, base64, URL, and so on), title, context, citations, cache_control. Most models can receive document requests (returning 200), but their responses do not include citations. This makes them suitable for fallback processing as ordinary context, and you should not promise Anthropic's citation capability.
Search result block (type: "search_result"): It is used to provide external search results to the model as a content block with sources, typically used in conjunction with citations. Current models generally return a 400 error and do not support this content block.
Video block (type: "video"): Its structure is consistent with that of the image block, and the source additionally supports the fps (frames per second) field. Video understanding is an extended capability provided by various vendors and is not natively supported by Anthropic.
Tool-related block:
tool_use (assistant message) included when the model requests to invoke a tool:
{ "type": "tool_use", "id": "toolu_001", "name": "get_weather", "input": { "location": "Beijing" } }
Field
Type
Description
id
string
The unique ID for the tool call, which must be returned in the corresponding tool_result.
name
string
Name of the tool to be called.
input
object
Tool parameters (an object, not a JSON string, different from the arguments string in OpenAI).
tool_result (user message) :After a tool is executed, the result is placed into the user message as a tool_result block:
{ "type": "tool_result", "tool_use_id": "toolu_001", "content": "It is sunny in Beijing today, with a temperature of 25 degrees Celsius." }
Field
Type
Description
tool_use_id
string
Corresponds to tool_use.id.
content
string or array
The tool result, which can be plain text or an array of content blocks (supporting text+images).
is_error
boolean
Set to true when tool execution fails.
cache_control
object
Cache flag.
Attention:
Arrangement Requirement: All tool_result blocks generated within the same assistant turn must be placed in a single, immediately following user message. Image-type tool_result.content is supported only by some multimodal models.
Chain-of-thought related block:
thinking (assistant message):
{ "type": "thinking", "thinking": "Let me analyze step by step: outer loop n times, inner loop log n times...", "signature": "EqoBCkgIARgC..." }
Field
Type
Description
thinking
string
Text of the model reasoning process
signature
string
Integrity signature for reasoning blocks
Attention:
Multi-turn Return Requirement: In multi-turn conversations, the thinking block from the assistant's historical messages must be returned with the signature intact. Otherwise, the service returns 400 Invalid signature. The signature is an encrypted credential and must not be truncated or modified. This validation semantics primarily applies to the Claude series of models. For other models that carry the chain of thought using their own protocols, the return requirements should follow the corresponding model's documentation. Some models (such as deepseek-v4-flash and hy3) do not return a signature. In such cases, the field does not need to be returned in multi-turn conversations.
redacted_thinking (assistant message): Some thought content is encrypted for security reasons and is returned as { "type": "redacted_thinking", "data": "<encrypted data>" }, containing only the data field. In multi-turn conversations, all such blocks must be returned in their original order to maintain context continuity for subsequent writing. This content block primarily appears in the Claude series of models and is typically not returned by other models.

Response Parameter Details

Non-Streaming Response

{
"id": "msg_xxx",
"type": "message",
"role": "assistant",
"model": "<your-model-name>",
"content": [
{ "type": "thinking", "thinking": "...", "signature": "..." },
{ "type": "text", "text": "Reply content" },
{ "type": "tool_use", "id": "toolu_xxx", "name": "get_weather", "input": { "location": "Beijing" } }
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0
},
"service_tier": "standard"
}
Field
Type
Description
id
string
The unique identifier of the response (prefixed with msg_).
type
string
Fixed as "message".
role
string
Fixed as "assistant"
model
string
The name of the model actually used.
content
array
An array of content blocks, typically in the order of thinking → text → tool_use.
stop_reason
string
The reason for stopping. See the enumeration below.
stop_sequence
string or null
The matched stop sequence (when a stop_sequences is matched).
usage
object
Token consumption. See Token usage.
container
object
Information about the code execution container (id, expires_at). Returned only when the built-in code_execution tool is used.
service_tier
string
The service tier that was actually matched.
Note:
Request Trace ID: When troubleshooting logs, prioritize using the id from the response body. For streaming responses, prioritize using the data.message.id from the message_start event. The platform simultaneously forwards/generates the X-Request-Id / X-Tc-Requestid from the client request headers. However, the final valid model response ID is determined by the message id.

Streaming Response (SSE)

When stream: true, SSE is returned with the response headers Content-Type: text/event-stream, Cache-Control: no-cache, and Connection: keep-alive.
Standard Event Sequence:
message_start
→ content_block_start → content_block_delta (multiple times) → content_block_stop (Block 1)
→ content_block_start → content_block_delta (multiple times) → content_block_stop (Block 2)
...
→ message_delta → message_stop
Auxiliary events: ping (keep-alive heartbeat) and error (error). Each SSE frame has the format event: <type> + data: {json}.
Main Event Descriptions:
Event
Description
Key Fields
message_start
Indicates the start of a message and returns the initial message skeleton.
message (containing initial usage and input/cache)
content_block_start
The start of a content block
index and content_block (type is text/thinking/tool_use)
content_block_delta
Content increment
index and delta (see the table below)
content_block_stop
The end of a content block
index
message_delta
Message-level delta
delta.stop_reason and usage (final output_tokens)
message_stop
Message end
-
content_block_delta.delta type:
delta.type
Field
Meaning
text_delta
text
Text delta.
thinking_delta
thinking
Reasoning process delta.
signature_delta
signature
Integrity signature for reasoning blocks (delivered before the thinking block ends).
input_json_delta
partial_json
Tool parameter JSON fragments, which need to be accumulated and then parsed as a whole.
Note:
Streaming Error Handling: If an error occurs before the response headers are sent (HTTP 200), a standard JSON error body is returned or a failover retry is triggered. If an error occurs after the stream has started, an error event is delivered or the connection is closed directly. The client must detect this through connection exceptions. Capability Description: Basic SSE events are available on models that support the corresponding capabilities. citations_delta is generally not returned at present. The streaming tool parameter (input_json_delta) is available on some models only after thinking is explicitly disabled.

stop_reason Enumeration

Value
Description
Handling Recommendation
end_turn
Model ends normally.
Process as normal.
max_tokens
The max_tokens limit is reached, and the output is truncated.
Increase the max_tokens value or generate content in segments.
stop_sequence
A stop_sequences is matched
Check the matched stop_sequence field.
tool_use
Model requests to invoke a tool.
Execute the tool and return the result via tool_result to continue the conversation.
pause_turn
server tool long-turn pause
Echo the current content as is and continue the request to resume.
refusal
Model refuses to answer due to security reasons.
Check whether the input triggers the security policy.

Token usage

Field
Type
Description
input_tokens
integer
Net input tokens (excluding cache read/write operations)
output_tokens
integer
Output tokens (including thinking content)
cache_creation_input_tokens
integer
Number of tokens written to cache
cache_read_input_tokens
integer
Number of tokens read from cache hits (billing is significantly reduced)
cache_creation.ephemeral_5m_input_tokens
integer
5-minute TTL cache creation tokens (breakdown by TTL)
cache_creation.ephemeral_1h_input_tokens
integer
1-hour TTL cache creation tokens (breakdown by TTL)
server_tool_use.web_search_requests
integer
Number of built-in web_search calls
server_tool_use.web_fetch_requests
integer
Number of built-in web_fetch calls
service_tier
string
The service tier that was actually matched
Note:
Mutual Exclusion Rule for input_tokens: According to the Anthropic specification, input_tokens, cache_read_input_tokens, and cache_creation_input_tokens are mutually exclusive. The actual total input = the sum of these three. When calculating costs, add all three items. Do not rely solely on input_tokens. In streaming responses, the message_start event provides the initial input_tokens and cache tokens. The message_delta event provides the final output_tokens.

Typical Scenario Examples

Note:
All examples use the same request endpoint: POST /v1/messages. Include the anthropic-version and x-api-key headers. The ${BASE_URL} in the following examples is set to https://tokenhub-intl.tencentcloudmaas.com.

Example: Basic Conversation

cURL
Python
Node.js
Java
Go
curl -s -X POST "${BASE_URL}/v1/messages" \\
-H 'Content-Type: application/json' \\
-H 'anthropic-version: 2023-06-01' \\
-H "x-api-key: ${API_KEY}" \\
-d '{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Hello"}],
"max_tokens": 1024
}'
import requests

resp = requests.post(
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
headers={
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
json={
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Hello"}],
"max_tokens": 1024,
},
)
print(resp.json())
const resp = await fetch("https://tokenhub-intl.tencentcloudmaas.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
body: JSON.stringify({
model: "<your-model-name>",
"messages": [{"role": "user", "content": "Hello"}],
max_tokens: 1024,
}),
});
console.log(await resp.json());
import okhttp3.*;

public class BasicMessage {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Hello"}],
"max_tokens": 1024
}
""";

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/messages")
.header("Content-Type", "application/json")
.header("anthropic-version", "2023-06-01")
.header("x-api-key", "YOUR_API_KEY")
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"fmt"
"io"
"net/http"
"strings"
)

func main() {
body := `{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Hello"}],
"max_tokens": 1024
}`

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("x-api-key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}

Example: With system + Streaming

cURL
Python
Node.js
Java
Go
curl -s -N -X POST "${BASE_URL}/v1/messages" \\
-H 'Content-Type: application/json' \\
-H 'anthropic-version: 2023-06-01' \\
-H "x-api-key: ${API_KEY}" \\
-d '{
"model": "<your-model-name>",
"system": [{"type": "text", "text": "You are a friendly assistant."}],
"messages": [{"role": "user", "content": "What is 1+1?"}],
"max_tokens": 1024,
"stream": true
}'
import requests

resp = requests.post(
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
headers={
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
json={
"model": "<your-model-name>",
"system": [{"type": "text", "text": "You are a friendly assistant."}],
"messages": [{"role": "user", "content": "What is 1+1?"}],
"max_tokens": 1024,
"stream": True,
},
stream=True,
)
for line in resp.iter_lines(decode_unicode=True):
if line:
print(line)
const resp = await fetch("https://tokenhub-intl.tencentcloudmaas.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
body: JSON.stringify({
model: "<your-model-name>",
"system": [{"type": "text", "text": "You are a friendly assistant."}],
"messages": [{"role": "user", "content": "What is 1+1?"}],
max_tokens: 1024,
stream: true,
}),
});
const reader = resp.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
process.stdout.write(decoder.decode(value));
}
import okhttp3.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SystemStream {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "<your-model-name>",
"system": [{"type": "text", "text": "You are a friendly assistant."}],
"messages": [{"role": "user", "content": "What is 1+1?"}],
"max_tokens": 1024,
"stream": true
}
""";

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/messages")
.header("Content-Type", "application/json")
.header("anthropic-version", "2023-06-01")
.header("x-api-key", "YOUR_API_KEY")
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute();
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.body().byteStream()))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.isEmpty()) System.out.println(line);
}
}
}
}
package main

import (
"bufio"
"fmt"
"net/http"
"strings"
)

func main() {
body := `{
"model": "<your-model-name>",
"system": [{"type": "text", "text": "You are a friendly assistant."}],
"messages": [{"role": "user", "content": "What is 1+1?"}],
"max_tokens": 1024,
"stream": true
}`

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("x-api-key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
if line := scanner.Text(); line != "" {
fmt.Println(line)
}
}
}
The expected SSE event chain is: message_start → content_block_start → content_block_delta → content_block_stop → message_delta → message_stop.

Example: Multi-Turn Conversations

For multi-turn conversations, you must include the complete conversation history (the platform does not manage sessions).
{
"model": "<your-model-name>",
"messages": [
{"role": "user", "content": "How do I read a CSV file?"},
{"role": "assistant", "content": "Using pandas: pd.read_csv('file.csv')"},
{"role": "user", "content": "What should I do if the file is too large to fit in memory?"}
],
"max_tokens": 1024
}

Example: Multimodal (Image Understanding)

Understand images (URLs):
{
"model": "<your-model-name>",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Please describe the scene in the picture in detail"},
{ "type": "image", "source": { "type": "url", "url": "https://example.com/photo.jpg" } }
]
}],
"max_tokens": 1024
}
Base64 image:
{
"role": "user",
"content": [
{"type": "text", "text": "Recognize the text in the picture"},
{ "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "/9j/4AAQSkZJRgAB..." } }
]
}

Example: Tool Calling

cURL
Python
Node.js
Java
Go
curl -s -X POST "${BASE_URL}/v1/messages" \\
-H 'Content-Type: application/json' \\
-H 'anthropic-version: 2023-06-01' \\
-H "x-api-key: ${API_KEY}" \\
-d '{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What is the weather like in Beijing today?"}],
"max_tokens": 1024,
"tools": [{
"name": "get_weather",
"description": "Query the weather information for a specified city",
"input_schema": {
"type": "object",
"properties": { "location": { "type": "string", "description": "City name" } },
"required": ["location"]
}
}],
"tool_choice": { "type": "auto" }
}'
import requests

resp = requests.post(
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
headers={
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
json={
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What is the weather like in Beijing today?"}],
"max_tokens": 1024,
"tools": [
{
"name": "get_weather",
"description": "Query the weather information for a specified city",
"input_schema": {
"type": "object",
"properties": {"location": {"type": "string", "description": "City name"}},
"required": ["location"],
},
}
],
"tool_choice": {"type": "auto"},
},
)
print(resp.json())
const resp = await fetch("https://tokenhub-intl.tencentcloudmaas.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
body: JSON.stringify({
model: "<your-model-name>",
messages: [{role: "user", content: "What is the weather like in Beijing today?"}],
max_tokens: 1024,
tools: [
{
name: "get_weather",
description: "Query the weather information for a specified city",
input_schema: {
type: "object",
properties: { location: { type: "string", description: "City name" } },
required: ["location"],
},
},
],
tool_choice: { type: "auto" },
}),
});
console.log(await resp.json());
import okhttp3.*;

public class ToolUse {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What is the weather like in Beijing today?"}],
"max_tokens": 1024,
"tools": [{
"name": "get_weather",
"description": "Query the weather information for a specified city",
"input_schema": {
"type": "object",
"properties": { "location": { "type": "string", "description": "City name" } },
"required": ["location"]
}
}],
"tool_choice": { "type": "auto" }
}
""";

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/messages")
.header("Content-Type", "application/json")
.header("anthropic-version", "2023-06-01")
.header("x-api-key", "YOUR_API_KEY")
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"fmt"
"io"
"net/http"
"strings"
)

func main() {
body := `{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What is the weather like in Beijing today?"}],
"max_tokens": 1024,
"tools": [{
"name": "get_weather",
"description": "Query the weather information for a specified city",
"input_schema": {
"type": "object",
"properties": { "location": { "type": "string", "description": "City name" } },
"required": ["location"]
}
}],
"tool_choice": { "type": "auto" }
}`

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("x-api-key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
After the model returns a tool_use, the client executes the tool and returns the result as a tool_result (placed into the user message):
{
"model": "<your-model-name>",
"messages": [
{ "role": "user", "content": "What is the weather like in Beijing today?" },
{ "role": "assistant", "content": [
{ "type": "tool_use", "id": "toolu_001", "name": "get_weather", "input": { "location": "Beijing" } }
]},
{ "role": "user", "content": [
{ "type": "tool_result", "tool_use_id": "toolu_001", "content": "It is sunny in Beijing today, with a temperature of 25 degrees Celsius." }
]}
],
"max_tokens": 1024,
"tools": [{
"name": "get_weather", "description": "Query the weather",
"input_schema": { "type": "object", "properties": { "location": { "type": "string" } }, "required": ["location"] }
}]
}

Example: Chain of Thought

cURL
Python
Node.js
Java
Go
curl -s -X POST "${BASE_URL}/v1/messages" \\
-H 'Content-Type: application/json' \\
-H 'anthropic-version: 2023-06-01' \\
-H "x-api-key: ${API_KEY}" \\
-d '{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Please explain what recursion is"}],
"max_tokens": 4096,
"thinking": { "type": "enabled", "budget_tokens": 2048 }
}'
import requests

resp = requests.post(
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
headers={
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
json={
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Please explain what recursion is"}],
"max_tokens": 4096,
"thinking": {"type": "enabled", "budget_tokens": 2048},
},
)
print(resp.json())
const resp = await fetch("https://tokenhub-intl.tencentcloudmaas.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
body: JSON.stringify({
model: "<your-model-name>",
messages: [{ role: "user", content: "Please explain what recursion is" }],
max_tokens: 4096,
thinking: { type: "enabled", budget_tokens: 2048 },
}),
});
console.log(await resp.json());
import okhttp3.*;

public class Thinking {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Please explain what recursion is"}],
"max_tokens": 4096,
"thinking": { "type": "enabled", "budget_tokens": 2048 }
}
""";

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/messages")
.header("Content-Type", "application/json")
.header("anthropic-version", "2023-06-01")
.header("x-api-key", "YOUR_API_KEY")
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"fmt"
"io"
"net/http"
"strings"
)

func main() {
body := `{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "Please explain what recursion is"}],
"max_tokens": 4096,
"thinking": { "type": "enabled", "budget_tokens": 2048 }
}`

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("x-api-key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
The response content contains a thinking block (with a signature) and a text block. Note that max_tokens must be greater than budget_tokens.

Example: Multi-Turn Chain of Thought (With signature)

In multi-turn conversations, the thinking block from the previous assistant's turn, along with the signature, must be returned unchanged:
{
"model": "<your-model-name>",
"messages": [
{"role": "user", "content": "Analyze the complexity of this code."},
{ "role": "assistant", "content": [
{ "type": "thinking", "thinking": "outer loop n times, inner loop log n times...", "signature": "EqoBCkgIARgC..." },
{ "type": "text", "text": "O(n log n)" }
]},
{"role": "user", "content": "How can it be optimized to O(n)?"}
],
"max_tokens": 4096,
"thinking": { "type": "enabled", "budget_tokens": 5000 }
}
Attention:
Key Point: The signature must be retained and returned unchanged. Otherwise, the service returns 400 Invalid signature.

Example: Built-in Tools (web_search)

cURL
Python
Node.js
Java
Go
curl -s -X POST "${BASE_URL}/v1/messages" \\
-H 'Content-Type: application/json' \\
-H 'anthropic-version: 2023-06-01' \\
-H "x-api-key: ${API_KEY}" \\
-d '{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What new large models will be available in 2026?"}],
"max_tokens": 2048,
"tools": [{ "type": "web_search_20250305", "name": "web_search", "max_uses": 3 }]
}'
import requests

resp = requests.post(
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
headers={
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
json={
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What new large models will be available in 2026?"}],
"max_tokens": 2048,
"tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 3}],
},
)
print(resp.json())
const resp = await fetch("https://tokenhub-intl.tencentcloudmaas.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "YOUR_API_KEY",
},
body: JSON.stringify({
model: "<your-model-name>",
messages: [{ role: "user", content: "What new large models will be available in 2026?" }],
max_tokens: 2048,
tools: [{ type: "web_search_20250305", name: "web_search", max_uses: 3 }],
}),
});
console.log(await resp.json());
import okhttp3.*;

public class BuiltinTool {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What new large models will be available in 2026?"}],
"max_tokens": 2048,
"tools": [{ "type": "web_search_20250305", "name": "web_search", "max_uses": 3 }]
}
""";

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/messages")
.header("Content-Type", "application/json")
.header("anthropic-version", "2023-06-01")
.header("x-api-key", "YOUR_API_KEY")
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"fmt"
"io"
"net/http"
"strings"
)

func main() {
body := `{
"model": "<your-model-name>",
"messages": [{"role": "user", "content": "What new large models will be available in 2026?"}],
"max_tokens": 2048,
"tools": [{ "type": "web_search_20250305", "name": "web_search", "max_uses": 3 }]
}`

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/messages",
strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("anthropic-version", "2023-06-01")
req.Header.Set("x-api-key", "YOUR_API_KEY")

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Note:
Built-in tools specify the versioned type name via type and do not require input_schema. Support for built-in tools varies by model. For details, see Supported Protocols by Model.

Example: Prompt Caching

Apply the cache_control tag to long system documents or tool definitions. After a cache hit, this significantly reduces the billing for input_tokens:
{
"model": "<your-model-name>",
"system": [
{ "type": "text", "text": "You are a document Q&A assistant." },
{ "type": "text", "text": "<Long document content...>", "cache_control": { "type": "ephemeral", "ttl": "1h" } }
],
"messages": [{"role": "user", "content": "What does Chapter 3 of the document cover?"}],
"max_tokens": 1024
}
The cache_creation_input_tokens (first-time cache write) and cache_read_input_tokens (subsequent cache hit reads) can be seen in the response usage.

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan