claude-sonnet-5-5

最后更新:2026-11-14

POSThttps://www.sagelib.com/chat/completions

claude-sonnet-5-5 模型的聊天生成接口,OpenAI兼容,支持多轮上下文、流式输出、工具调用、结构化输出等。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Authorization string 鉴权令牌,格式为 Bearer ${AIGATEWAY_TOKEN}
*Content-Type string 默认值:application/json
可选值:application/json
内容类型,固定为 application/json

Body 参数

参数名称 描述
*model string 可选值:claude-sonnet-5-5
模型名称,须精确匹配
*messages array 可选值:user
对话消息列表,content 内容块支持 text 与 image_url;系统提示可写成 messages[0].role="system"
*max_tokens integer 可选值:1 ~ 128000
最大输出 token 数,思考与正文共享该上限
stream boolean 默认值:false
可选值:true、false
是否以 SSE 增量流式返回响应
tools array 可选值:Array of OpenAI-format tool definitions
工具定义列表,每项含 type 与 function(name / description / parameters)
tool_choice object 默认值:auto
可选值:auto、none
工具选择策略,控制模型如何选用已声明的工具
cache_control object 可选值:1h
缓存控制,自动在最后一个可缓存块打标记,最低可缓存前缀 512 token
metadata object 可选值:Contains user_id sub-field
请求元数据,user_id 为调用方终端用户标识
stop array 可选值:String or string array (up to 4 sequences)
自定义停止序列,命中后 finish_reason 为 stop
reasoning_effort string 默认值:high
可选值:low、medium、high、xhigh、max
推理强度,控制自适应思考的思考量
max_completion_tokens integer 可选值:1 ~ 128000
max_tokens 的回退值,未传 max_tokens 时生效
eca_context_management object 可选值:clear_thinking_20251015、thinking_turns、all
上下文管理配置,用于长对话中自动清理或压缩较早上下文
eca_fallbacks array 可选值:"default" or list of fallback models
服务端降级配置,请求被安全分类器拒绝时改用备选模型

请求示例

curl -v 'https://www.sagelib.com/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "messages": [
      {
        "role": "system",
        "content": "You are a senior technical expert"
      },
      {
        "role": "user",
        "content": "Explain consistency algorithms in distributed systems in detail, including Raft vs Paxos comparison, leader election, log replication, fault recovery, and CAP theorem trade-offs in practice; at least 800 words"
      }
    ],
    "max_tokens": 1000
  }'
import json
import requests

base_url = "https://www.sagelib.com"
api_key = "***"
url = f"https://www.sagelib.com/chat/completions"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
data = {
    "model": "claude-sonnet-5-5",
    "messages": [
        {
            "role": "system",
            "content": "You are a senior technical expert"
        },
        {
            "role": "user",
            "content": "Explain consistency algorithms in distributed systems in detail, including Raft vs Paxos comparison, leader election, log replication, fault recovery, and CAP theorem trade-offs in practice; at least 800 words"
        }
    ],
    "max_tokens": 1000
}
response = requests.post(url, headers=headers, json=data)
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/chat/completions";
        String jsonRequestBody = """
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "system",
                        "content": "You are a senior technical expert"
                    },
                    {
                        "role": "user",
                        "content": "Explain consistency algorithms in distributed systems in detail, including Raft vs Paxos comparison, leader election, log replication, fault recovery, and CAP theorem trade-offs in practice; at least 800 words"
                    }
                ],
                "max_tokens": 1000
            }
            """;
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).header("Authorization", "Bearer " + apiKey).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody)).build();
        try {
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) break;
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"
    jsonRequestBody := `
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "system",
                        "content": "You are a senior technical expert"
                    },
                    {
                        "role": "user",
                        "content": "Explain consistency algorithms in distributed systems in detail, including Raft vs Paxos comparison, leader election, log replication, fault recovery, and CAP theorem trade-offs in practice; at least 800 words"
                    }
                ],
                "max_tokens": 1000
            }
`
    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil { fmt.Println("Failed to create request:", err); return }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil { fmt.Println("Request failed:", err); return }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "messages": [
      {
        "role": "user",
        "content": "How is the weather in Beijing today? Please use a tool to query."
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "parameters": {}
        }
      }
    ]
  }'
import json
import requests

base_url = "https://www.sagelib.com"
api_key = "***"
url = f"https://www.sagelib.com/chat/completions"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
data = {
    "model": "claude-sonnet-5-5",
    "messages": [
        {
            "role": "user",
            "content": "How is the weather in Beijing today? Please use a tool to query."
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "parameters": {}
            }
        }
    ]
}
response = requests.post(url, headers=headers, json=data)
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/chat/completions";
        String jsonRequestBody = """
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query."
                    }
                ],
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "parameters": {}
                        }
                    }
                ]
            }
            """;
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).header("Authorization", "Bearer " + apiKey).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody)).build();
        try {
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) break;
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"
    jsonRequestBody := `
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query."
                    }
                ],
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "parameters": {}
                        }
                    }
                ]
            }
`
    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil { fmt.Println("Failed to create request:", err); return }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil { fmt.Println("Request failed:", err); return }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "messages": [
      {
        "role": "user",
        "content": "Carefully read the following technical document and summarize the core points, extract 3-5 key conclusions:\n\n# Survey of LLM Inference Optimization Techniques\n\n## 1. Inference Acceleration Techniques\nMain inference acceleration techniques include: KV cache optimization, speculative decoding, model quantization and distillation, etc. ...(technical document body, about 700 tokens)...\n\nBased on the above, summarize the core technical routes and future trends of large model inference optimization, extracting 3-5 key conclusions."
      }
    ],
    "max_tokens": 16384,
    "reasoning_effort": "max"
  }'
import json
import requests

base_url = "https://www.sagelib.com"
api_key = "***"
url = f"https://www.sagelib.com/chat/completions"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
data = {
    "model": "claude-sonnet-5-5",
    "messages": [
        {
            "role": "user",
            "content": "Carefully read the following technical document and summarize the core points, extract 3-5 key conclusions:\n\n# Survey of LLM Inference Optimization Techniques\n\n## 1. Inference Acceleration Techniques\nMain inference acceleration techniques include: KV cache optimization, speculative decoding, model quantization and distillation, etc. ...(technical document body, about 700 tokens)...\n\nBased on the above, summarize the core technical routes and future trends of large model inference optimization, extracting 3-5 key conclusions."
        }
    ],
    "max_tokens": 16384,
    "reasoning_effort": "max"
}
response = requests.post(url, headers=headers, json=data)
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/chat/completions";
        String jsonRequestBody = """
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "user",
                        "content": "Carefully read the following technical document and summarize the core points, extract 3-5 key conclusions:\n\n# Survey of LLM Inference Optimization Techniques\n\n## 1. Inference Acceleration Techniques\nMain inference acceleration techniques include: KV cache optimization, speculative decoding, model quantization and distillation, etc. ...(technical document body, about 700 tokens)...\n\nBased on the above, summarize the core technical routes and future trends of large model inference optimization, extracting 3-5 key conclusions."
                    }
                ],
                "max_tokens": 16384,
                "reasoning_effort": "max"
            }
            """;
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).header("Authorization", "Bearer " + apiKey).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody)).build();
        try {
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) break;
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"
    jsonRequestBody := `
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "user",
                        "content": "Carefully read the following technical document and summarize the core points, extract 3-5 key conclusions:\n\n# Survey of LLM Inference Optimization Techniques\n\n## 1. Inference Acceleration Techniques\nMain inference acceleration techniques include: KV cache optimization, speculative decoding, model quantization and distillation, etc. ...(technical document body, about 700 tokens)...\n\nBased on the above, summarize the core technical routes and future trends of large model inference optimization, extracting 3-5 key conclusions."
                    }
                ],
                "max_tokens": 16384,
                "reasoning_effort": "max"
            }
`
    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil { fmt.Println("Failed to create request:", err); return }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil { fmt.Println("Request failed:", err); return }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}

响应参数

Body 参数

参数名称 描述
id string 响应唯一标识,形如 chatcmpl-msg_xxx
object string 固定为 chat.completion(流式为 chat.completion.chunk)
created integer 创建时间戳(Unix 秒)
model string 实际使用的模型名称
choices array
service_tier string 服务层级
usage object
    prompt_tokens integer 输入 token 数(已含缓存命中量)
    completion_tokens integer 输出 token 数(已含思考 token)
    total_tokens integer 总 token 数,等于 prompt_tokens + completion_tokens
    completion_tokens_details object
        reasoning_tokens integer 思考 token 数(completion_tokens 的子集)
    prompt_tokens_details object
        cached_tokens integer 缓存命中量(prompt_tokens 的子集)
        cache_write_tokens integer 缓存写入量(prompt_tokens 的子集)
        eca_cache_creation_details object 缓存创建明细(未启用为空对象)
        eca_cleared_tokens_details object
            applied_edits array 上下文管理实际生效的编辑(未启用为空数组)
    service_tier string 服务层级
    inference_geo string 推理地理区域
POSThttps://www.sagelib.com/anthropic/v1/messages

claude-sonnet-5-5 模型的聊天生成接口,Anthropic直连,支持多轮上下文、流式输出、工具调用、结构化输出等。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Content-Type string 默认值:application/json
可选值:application/json
内容类型,固定为 application/json
*anthropic-version string 默认值:2023-06-01
可选值:2023-06-01
Anthropic API 版本号,固定为 2023-06-01
*X-Api-Key string 鉴权令牌,格式为 ${AIGATEWAY_TOKEN}

Body 参数

参数名称 描述
*model string 可选值:claude-sonnet-5-5
模型名称,须精确匹配
*messages array 可选值:role: user / assistant; content: string or content block array
对话消息列表,content 内容块支持 text / image / document / tool_use / tool_result;首条须为 user 角色
*max_tokens integer 可选值:1 ~ 128000
最大输出 token 数,思考与正文共享该上限
stream boolean 默认值:false
可选值:true、false
是否以 SSE 增量流式返回响应
system string 可选值:String or array of TextBlock
系统提示词,Anthropic 顶层参数(非 messages 数组内)
tools array 可选值:Array of Anthropic-format tool definitions
工具定义列表,每项含 name / description / input_schema
tool_choice object 可选值:type:auto、type:none
工具选择策略,控制模型如何选用已声明的工具
thinking object 可选值:type:adaptive、summarized、updates
思考配置,该模型强制开启思考,仅支持 enabled
output_config object 可选值:effort:low、medium、high、xhigh
输出配置,effort 控制推理强度,format 控制结构化 JSON 输出
cache_control object 可选值:1h
缓存控制,打在 system 块或 messages 内容块上,最低可缓存前缀 512 token
metadata object 可选值:Contains user_id sub-field
请求元数据,user_id 为调用方终端用户标识
stop_sequences array 可选值:String array
自定义停止序列,命中后 stop_reason 为 stop_sequence 并回带命中串
container object 可选值:custom
容器标识,用于跨请求复用容器(代码执行等场景)
service_tier string 默认值:auto
可选值:auto、standard_only
服务层级
inference_geo string 可选值:Region identifier such as us
指定本次推理处理的地理区域
user_profile_id string 可选值:String
代表组织外第三方发起请求时的用户档案 ID
workspace_id string 可选值:Such as wrkspc_xxx
指定本次请求使用的 Workspace ID
diagnostics object 可选值:previous_message_id
缓存诊断(未启用为 null,启用后含 cache_miss_reason)

请求示例

curl -v 'https://www.sagelib.com/anthropic/messages' \
  -H "x-api-key: ***" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "system": "You are an expert",
    "messages": [
      {
        "role": "user",
        "content": "Compare Raft and Paxos consistency algorithms; at least 800 words"
      }
    ],
    "max_tokens": 1000
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your API key

url = f"https://www.sagelib.com/anthropic/messages"

headers = {
    "x-api-key": api_key,
    "anthropic-version": "2023-06-01",
    "Content-Type": "application/json",
}

data = {
    "model": "claude-sonnet-5-5",
    "system": "You are an expert",
    "messages": [
        {
            "role": "user",
            "content": "Compare Raft and Paxos consistency algorithms; at least 800 words"
        }
    ],
    "max_tokens": 1000
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/anthropic/messages";

        String jsonRequestBody = """
            {
                "model": "claude-sonnet-5-5",
                "system": "You are an expert",
                "messages": [
                    {
                        "role": "user",
                        "content": "Compare Raft and Paxos consistency algorithms; at least 800 words"
                    }
                ],
                "max_tokens": 1000
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("x-api-key", apiKey).header("anthropic-version", "2023-06-01")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/anthropic/messages"

    jsonRequestBody := `
            {
                "model": "claude-sonnet-5-5",
                "system": "You are an expert",
                "messages": [
                    {
                        "role": "user",
                        "content": "Compare Raft and Paxos consistency algorithms; at least 800 words"
                    }
                ],
                "max_tokens": 1000
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("x-api-key", apiKey)
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/anthropic/messages' \
  -H "x-api-key: ***" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "messages": [
      {
        "role": "user",
        "content": "How is the weather in Beijing today? Please use a tool to query."
      }
    ],
    "max_tokens": 1024,
    "tools": [
      {
        "name": "get_weather",
        "description": "Get the weather of a specified city",
        "input_schema": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string"
            }
          }
        }
      }
    ]
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your API key

url = f"https://www.sagelib.com/anthropic/messages"

headers = {
    "x-api-key": api_key,
    "anthropic-version": "2023-06-01",
    "Content-Type": "application/json",
}

data = {
    "model": "claude-sonnet-5-5",
    "messages": [
        {
            "role": "user",
            "content": "How is the weather in Beijing today? Please use a tool to query."
        }
    ],
    "max_tokens": 1024,
    "tools": [
        {
            "name": "get_weather",
            "description": "Get the weather of a specified city",
            "input_schema": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string"
                    }
                }
            }
        }
    ]
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/anthropic/messages";

        String jsonRequestBody = """
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query."
                    }
                ],
                "max_tokens": 1024,
                "tools": [
                    {
                        "name": "get_weather",
                        "description": "Get the weather of a specified city",
                        "input_schema": {
                            "type": "object",
                            "properties": {
                                "city": {
                                    "type": "string"
                                }
                            }
                        }
                    }
                ]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("x-api-key", apiKey).header("anthropic-version", "2023-06-01")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/anthropic/messages"

    jsonRequestBody := `
            {
                "model": "claude-sonnet-5-5",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query."
                    }
                ],
                "max_tokens": 1024,
                "tools": [
                    {
                        "name": "get_weather",
                        "description": "Get the weather of a specified city",
                        "input_schema": {
                            "type": "object",
                            "properties": {
                                "city": {
                                    "type": "string"
                                }
                            }
                        }
                    }
                ]
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("x-api-key", apiKey)
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/anthropic/messages' \
  -H "x-api-key: ***" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 2048,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "image",
            "source": {
              "type": "url",
              "url": "${image_url}"
            }
          },
          {
            "type": "text",
            "text": "Carefully describe the main content of this image, including the subject, scene, composition, and color characteristics."
          }
        ]
      }
    ]
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your API key

url = f"https://www.sagelib.com/anthropic/messages"

headers = {
    "x-api-key": api_key,
    "anthropic-version": "2023-06-01",
    "Content-Type": "application/json",
}

data = {
    "model": "claude-sonnet-5-5",
    "max_tokens": 2048,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "${image_url}"
                    }
                },
                {
                    "type": "text",
                    "text": "Carefully describe the main content of this image, including the subject, scene, composition, and color characteristics."
                }
            ]
        }
    ]
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/anthropic/messages";

        String jsonRequestBody = """
            {
                "model": "claude-sonnet-5-5",
                "max_tokens": 2048,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "image",
                                "source": {
                                    "type": "url",
                                    "url": "${image_url}"
                                }
                            },
                            {
                                "type": "text",
                                "text": "Carefully describe the main content of this image, including the subject, scene, composition, and color characteristics."
                            }
                        ]
                    }
                ]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("x-api-key", apiKey).header("anthropic-version", "2023-06-01")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

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

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/anthropic/messages"

    jsonRequestBody := `
            {
                "model": "claude-sonnet-5-5",
                "max_tokens": 2048,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "image",
                                "source": {
                                    "type": "url",
                                    "url": "${image_url}"
                                }
                            },
                            {
                                "type": "text",
                                "text": "Carefully describe the main content of this image, including the subject, scene, composition, and color characteristics."
                            }
                        ]
                    }
                ]
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("x-api-key", apiKey)
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}

响应参数

Body 参数

参数名称 描述
id string 响应唯一标识,形如 msg_xxx
type string 固定为 message
role string 固定为 assistant
model string 实际使用的模型名称
content array 内容块数组
stop_reason string 停止原因:end_turn / stop_sequence / max_tokens / tool_use / refusal
stop_sequence string 命中的停止序列(未命中为 null)
stop_details object 停止详情(无则为 null)
container object 容器信息(未使用为 null)
context_management object
    applied_edits array 上下文管理实际生效的编辑(未启用为空数组)
diagnostics object 缓存诊断(未启用为 null,启用后含 cache_miss_reason)
input_transformations array 输入变换记录(无变换为空数组,每项含 text 等字段)
usage object
    input_tokens integer 输入 token 数(不含缓存,总输入 = input_tokens + cache_creation_input_tokens + cache_read_input_tokens)
    output_tokens integer 输出 token 数(已含思考 token)
    output_tokens_details object
        thinking_tokens integer 思考 token 数(output_tokens 的子集)
    cache_creation_input_tokens integer 缓存写入总量
    cache_creation object
        ephemeral_5m_input_tokens integer 5 分钟 TTL 桶写入量
        ephemeral_1h_input_tokens integer 1 小时 TTL 桶写入量
    cache_read_input_tokens integer 缓存命中量
    iterations array 每次尝试的用量记录(无降级时单条,type=message)
    service_tier string 服务层级
    inference_geo string 推理地理区域