跳至內容
English
Messages

建立訊息 ​

相容 Claude 的 Messages API,支援單次查詢與多輪對話。

POST /v1/messages

傳送包含文字內容的結構化訊息清單,模型便會產生對話中的下一則訊息。

  • 採用 Claude Messages API 請求格式
  • 支援單次查詢與無狀態多輪對話
  • 支援串流與非串流回應

圖像與文件分析請參閱檔案分析。

端點 ​

text
https://api.tokatlas.ai/v1/messages

身分驗證 ​

所有端點均需要 API 金鑰驗證。請在請求標頭中加入金鑰:

http
x-api-key: YOUR_API_KEY
anthropic-version: 2023-06-01
Content-Type: application/json

重要

請勿將真實 API 金鑰提交至程式碼儲存庫,或公開於用戶端程式碼中。

請求本文 ​

參數類型必填預設值說明
modelstring是-處理提示的模型
messagesarray是-對話的輸入訊息
max_tokensinteger是-停止前的生成 Token 數量上限
systemstring or array否-系統提示(不是訊息角色)
temperaturenumber否1.0輸出隨機程度,範圍 0–1
top_pnumber否-核心取樣參數,範圍 0–1
top_kinteger否-僅從機率最高的 K 個選項中取樣
streamboolean否false是否透過 SSE 傳回串流回應
stop_sequencesarray否-停止生成的自訂文字序列
metadataobject否-請求中繼資料(如 user_id)
toolsarray否-模型可使用的工具
tool_choiceobject否-模型使用工具的方式
thinkingobject否-延伸思考設定

model ​

以下為截至 2026-10-03 核對的官方現行型號。先依API 使用入門查詢帳戶可用模型,再將完整 ID 填入 model;官方已發布不代表您的 Tokatlas 帳戶已開通。

  • claude-opus-5-5 — Claude Opus 5.5
  • claude-sonnet-5-5 — Claude Sonnet 5.5
  • claude-fable-5-1 — Claude Fable 5.1
  • claude-haiku-4-5 — Claude Haiku 4.5

官方模型文件

新版本的思考模式與工具限制可能不同;先用純文字最小請求驗證,再加入 thinking 或強制工具選擇。

messages ​

輸入訊息。模型以 user 與 assistant 交替的輪次運作。建立新訊息時,請在 messages 中傳入先前的對話,模型便會產生下一則訊息。

每則訊息必須包含 role 和 content。連續相同角色的訊息會合併為單一輪次,每次請求最多可包含 100,000 則訊息。

欄位類型必填說明
rolestring是user or assistant
contentstring or array是訊息內容

注意

Messages API 的輸入不支援 "system" 角色。請使用最外層的 system 參數設定系統提示。

單則使用者訊息:

json
[{"role": "user", "content": "Hello, Claude"}]

多輪對話:

json
[
  {"role": "user", "content": "Hello there."},
  {"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
  {"role": "user", "content": "Can you explain LLMs in plain English?"}
]

預填助理回應(接續最後一輪助理訊息產生內容):

json
[
  {"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
  {"role": "assistant", "content": "The best answer is ("}
]

content 可以是字串或內容區塊陣列。字串是單一 "text" 區塊的簡寫:

json
{"role": "user", "content": "Hello, Claude"}
json
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}

max_tokens ​

停止生成前可產生的 Token 數量上限。模型可能在達到上限前停止,不同模型的上限也不同。最小值為 1。

system ​

用於設定角色、個性、目標與指令的系統提示。

字串格式:

json
{
  "system": "You are a professional Python programming tutor"
}

結構化格式:

json
{
  "system": [
    {
      "type": "text",
      "text": "You are a professional Python programming tutor"
    }
  ]
}

temperature ​

回應的隨機程度,範圍為 0–1,預設值為 1.0。

  • 較低數值(例如 0.2):回應更確定、偏向分析
  • 較高數值(例如 0.8):回應更有創意、多樣性更高

top_p ​

核心取樣參數,範圍為 0–1。建議只調整 temperature 或 top_p 其中一項。

top_k ​

每個後續 Token 僅從機率最高的 K 個選項中取樣,建議僅於進階情境使用。

stream ​

是否使用伺服器傳送事件(SSE)逐步傳回串流回應。

  • true:串流回應
  • false:一次傳回完整回應(預設)

stop_sequences ​

讓模型停止生成的自訂文字序列,最多 4 組。符合序列時,stop_reason 為 "stop_sequence",stop_sequence 則包含符合的值。

metadata ​

請求中繼資料物件,包含:

  • user_id:外部不透明使用者識別碼(UUID/雜湊值),請勿包含可識別個人的資訊。

tools ​

模型可用來完成任務的工具清單。

json
{
  "tools": [
    {
      "name": "get_weather",
      "description": "Get the current weather in a given location",
      "input_schema": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA"
          },
          "unit": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"]
          }
        },
        "required": ["location"]
      }
    }
  ]
}

tool_choice ​

控制模型使用工具的方式:

  • {"type": "auto"}:自動決定(預設)
  • {"type": "any"}:必須使用工具
  • {"type": "tool", "name": "tool_name"}:使用指定工具
  • {"type": "none"}:不使用工具

thinking ​

延伸思考設定。啟用後,回應可能會在最終答案之前包含 thinking 內容區塊。

回應 ​

下表描述協定回應物件。本文非串流範例若有 { "code": 200, "data": { ... } } 外層封裝,請先讀取 data;直接回傳協定物件的路由則讀取根物件。串流請按事件解析,不能將整段 SSE 當成單一 JSON。使用原生 SDK 前,須確認路由回傳 SDK 所需的直接協定格式。

欄位類型說明
idstring訊息唯一識別碼
typestring物件類型,固定為 message
rolestring固定為 assistant
contentarray模型產生的內容區塊
modelstring處理請求的模型
stop_reasonstring停止生成的原因
stop_sequencestring or null符合的停止序列(如有)
usageobjectToken 用量統計

content[] ​

內容區塊陣列,常見類型包括:

文字:

json
[{"type": "text", "text": "Hello! I'm Claude."}]

工具使用:

json
[
  {
    "type": "tool_use",
    "id": "toolu_01A09q90qw90lq917835lq9",
    "name": "get_weather",
    "input": {"location": "San Francisco, CA", "unit": "celsius"}
  }
]

stop_reason ​

值說明
end_turn自然完成
max_tokens已達 max_tokens 上限
stop_sequence符合停止序列
tool_use已呼叫工具

usage ​

欄位類型說明
input_tokensinteger輸入 Token 數量
output_tokensinteger輸出 Token 數量

使用範例 ​

基本對話 ​

json
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {"role": "user", "content": "Explain quantum computing basics"}
  ]
}

系統提示 ​

json
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "system": "You are a senior Python developer expert in code review.",
  "messages": [
    {"role": "user", "content": "How should I optimize this function?"}
  ]
}

多輪對話 ​

json
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {"role": "user", "content": "What is machine learning?"},
    {"role": "assistant", "content": "Machine learning is a branch of AI..."},
    {"role": "user", "content": "Can you give a practical example?"}
  ]
}

串流輸出 ​

json
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "stream": true,
  "messages": [
    {"role": "user", "content": "Write a short essay about AI"}
  ]
}

請求範例 ​

執行方式見多語言範例說明。先設定 API_KEY,並替換模型、檔案網址及 ID 占位值;四種方式會顯示相同請求的原始回應。

bash
curl --fail-with-body --silent --show-error --max-time 180 \
  --request POST \
  --url "https://api.tokatlas.ai/v1/messages" \
  --header "x-api-key: $API_KEY" \
  --header "anthropic-version: 2023-06-01" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Hello, world"
    }
  ]
}'
python
import os
import requests

headers = {
    'x-api-key': os.environ["API_KEY"],
    'anthropic-version': '2023-06-01',
    'Content-Type': 'application/json',
}
payload = {'model': 'claude-sonnet-4-6',
 'max_tokens': 1024,
 'messages': [{'role': 'user', 'content': 'Hello, world'}]}
response = requests.request(
    'POST', 'https://api.tokatlas.ai/v1/messages', headers=headers,
    json=payload,
    timeout=180,
)
response.raise_for_status()
print(response.text)
js
if (!process.env.API_KEY) throw new Error("Set API_KEY first.");
const response = await fetch("https://api.tokatlas.ai/v1/messages", {
  method: "POST",
  headers: {
    "x-api-key": process.env.API_KEY,
    "anthropic-version": "2023-06-01",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Hello, world"
    }
  ]
}),
  signal: AbortSignal.timeout(180_000),
});
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
console.log(await response.text());
java
import java.net.URI;
import java.net.http.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("API_KEY");
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("Set API_KEY first.");
        }
        String payload = String.join("\n",
            "{",
            "  \"model\": \"claude-sonnet-4-6\",",
            "  \"max_tokens\": 1024,",
            "  \"messages\": [",
            "    {",
            "      \"role\": \"user\",",
            "      \"content\": \"Hello, world\"",
            "    }",
            "  ]",
            "}"
        );
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30)).build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.tokatlas.ai/v1/messages"))
            .timeout(Duration.ofSeconds(180))
            .header("x-api-key", apiKey)
            .header("anthropic-version", "2023-06-01")
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString(payload))
            .build();
        HttpResponse<String> response = client.send(
            request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": "
                + response.body());
        }
        System.out.println(response.body());
    }
}
go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

func main() {
    url := "https://api.tokatlas.ai/v1/messages"

    payload := map[string]interface{}{
        "model":      "claude-sonnet-4-6",
        "max_tokens": 1024,
        "messages": []map[string]string{
            {
                "role":    "user",
                "content": "Hello, world",
            },
        },
    }

    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("x-api-key", os.Getenv("API_KEY"))
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

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

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

回應範例 ​

非串流 (stream: false) ​

json
{
  "code": 200,
  "data": {
    "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
    "type": "message",
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": "Hello! I'm Claude. Nice to meet you."
      }
    ],
    "model": "claude-sonnet-4-6",
    "stop_reason": "end_turn",
    "stop_sequence": null,
    "usage": {
      "input_tokens": 12,
      "output_tokens": 18
    }
  }
}

串流 (stream: true) ​

當 stream 為 true,API 會傳回 SSE 串流。事件遵循 Claude Messages 串流順序,並以 message_stop 結束。

text
event: message_start
data: {"type":"message_start","message":{"id":"msg_013Zva2CMHLNnXjNJJKqJ2EF","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-6","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":0}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"! I'm Claude."}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":18}}

event: message_stop
data: {"type":"message_stop"}

相關主題 ​