Messages API
Anthropic Claude 原生 Messages 接口,支持 Content Block 结构和工具使用。
POST /v1/messages
请求示例
- Curl
- Python
- TypeScript
- Java
- Go
- PHP
- Ruby
- C#
curl https://gw.opentoken.io/v1/messages \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPEN_TOKEN_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-sonnet-4-6",
"system": "你是一位资深 Python 编程导师。",
"messages": [
{"role": "user", "content": [{"type": "text", "text": "请解释 Python 装饰器的工作原理。"}]}
],
"max_tokens": 500,
"temperature": 0.7
}'
import os, requests
response = requests.post(
"https://gw.opentoken.io/v1/messages",
headers={
"Authorization": f"Bearer {os.environ['OPEN_TOKEN_KEY']}",
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
},
json={
"model": "claude-sonnet-4-6",
"system": "你是一位资深 Python 编程导师。",
"messages": [
{"role": "user", "content": [{"type": "text", "text": "请解释 Python 装饰器的工作原理。"}]}
],
"max_tokens": 500,
},
)
data = response.json()
print(data["content"][0]["text"])
const response = await fetch("https://gw.opentoken.io/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.OPEN_TOKEN_KEY}`,
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
},
body: JSON.stringify({
model: "claude-sonnet-4-6",
system: "你是一位资深 Python 编程导师。",
messages: [{ role: "user", content: [{ type: "text", text: "请解释 Python 装饰器的工作原理。" }] }],
max_tokens: 500,
}),
});
const data = await response.json();
console.log(data.content[0].text);
import java.net.http.*;
import java.net.URI;
import com.google.gson.*;
HttpClient client = HttpClient.newHttpClient();
String apiKey = System.getenv("OPEN_TOKEN_KEY");
JsonObject body = new JsonObject();
body.addProperty("model", "claude-sonnet-4-6");
body.addProperty("system", "你是一位资深 Python 编程导师。");
body.addProperty("max_tokens", 500);
JsonArray msgs = new JsonArray();
JsonObject msg = new JsonObject();
msg.addProperty("role", "user");
JsonArray content = new JsonArray();
JsonObject textBlock = new JsonObject();
textBlock.addProperty("type", "text");
textBlock.addProperty("text", "请解释 Python 装饰器的工作原理。");
content.add(textBlock);
msg.add("content", content);
msgs.add(msg);
body.add("messages", msgs);
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://gw.opentoken.io/v1/messages"))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.header("anthropic-version", "2023-06-01")
.POST(HttpRequest.BodyPublishers.ofString(body.toString()))
.build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
func main() {
apiKey := os.Getenv("OPEN_TOKEN_KEY")
body := map[string]interface{}{
"model": "claude-sonnet-4-6",
"system": "你是一位资深 Python 编程导师。",
"messages": []map[string]interface{}{
{"role": "user", "content": []map[string]string{
{"type": "text", "text": "请解释 Python 装饰器的工作原理。"},
}},
},
"max_tokens": 500,
}
jsonBody, _ := json.Marshal(body)
req, _ := http.NewRequest("POST", "https://gw.opentoken.io/v1/messages", bytes.NewBuffer(jsonBody))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("anthropic-version", "2023-06-01")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
<?php
$apiKey = getenv('OPEN_TOKEN_KEY');
$ch = curl_init('https://gw.opentoken.io/v1/messages');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
'anthropic-version: 2023-06-01',
],
CURLOPT_POSTFIELDS => json_encode([
'model' => 'claude-sonnet-4-6',
'system' => '你是一位资深 Python 编程导师。',
'messages' => [[
'role' => 'user',
'content' => [['type' => 'text', 'text' => '请解释 Python 装饰器的工作原理。']],
]],
'max_tokens' => 500,
]),
]);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
echo $data['content'][0]['text'];
require 'net/http'
require 'json'
api_key = ENV['OPEN_TOKEN_KEY']
uri = URI('https://gw.opentoken.io/v1/messages')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{api_key}",
'Content-Type' => 'application/json',
'anthropic-version' => '2023-06-01',
})
request.body = {
model: 'claude-sonnet-4-6',
system: '你是一位资深 Python 编程导师。',
messages: [{ role: 'user', content: [{ type: 'text', text: '请解释 Python 装饰器的工作原理。' }] }],
max_tokens: 500,
}.to_json
response = http.request(request)
data = JSON.parse(response.body)
puts data['content'][0]['text']
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("OPEN_TOKEN_KEY");
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
client.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");
var payload = new
{
model = "claude-sonnet-4-6",
system = "你是一位资深 Python 编程导师。",
messages = new[]
{
new
{
role = "user",
content = new[]
{
new { type = "text", text = "请解释 Python 装饰器的工作原理。" }
}
}
},
max_tokens = 500,
};
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://gw.opentoken.io/v1/messages", content);
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
请求参数
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
| model | string | 是 | 模型 ID |
| messages | array | 是 | 消息列表,Content Block 格式 |
| system | string / array | 否 | 系统提示词 |
| max_tokens | integer | 是 | 限制本次响应可生成的最大 token 数;实际输出长度可能因停止条件、上下文长度或模型限制而更短。 |
| temperature | number | 否 | 采样温度,用于控制生成过程中的随机性。较低的值通常会使输出更稳定、可预测;较高的值通常会增加输出的多样性。 |
| tools | array | 否 | 工具定义 |
| stream | boolean | 否 | 流式输出 |
多模态(图片 + 文本)
{
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "描述这张图片中的内容。"},
{"type": "image", "source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}}
]
}]
}
Content Block 结构
Claude 使用 Content Block 表示消息内容,支持文本、图片和工具结果:
{
"role": "user",
"content": [
{"type": "text", "text": "描述这张图片"},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}
}
]
}
Tool Use 示例
{
"model": "claude-sonnet-4-6",
"max_tokens": 500,
"tools": [{
"name": "get_weather",
"description": "获取指定城市的天气",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}],
"messages": [{"role": "user", "content": "北京今天天气如何?"}]
}
响应结构
{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"content": [
{"type": "text", "text": "装饰器是 Python 中的一种设计模式..."}
],
"model": "claude-sonnet-4-6",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 25,
"output_tokens": 120
}
}