> For the complete documentation index, see [llms.txt](https://docs.console.zenlayer.com/api-reference/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.console.zenlayer.com/api-reference/cn/ai/aig/chat-completion/anthropic-claude/anthropic-claude-message.md).

# 原生API (/messages)

## 1. 概述

Claude是Anthropic开发的大语言模型，具有强大的对话和写作能力。它能理解上下文、生成连贯文本、编写代码，并擅长逻辑推理和分析。注重安全性和道德准则，会明确表明自己是AI助手的身份。它支持多语言交流，能够处理复杂任务和长对话。

{% hint style="success" %}
本 API 符合 Anthropic Claude 接口格式规范，支持官方所有参数。
{% endhint %}

{% hint style="info" %}
本文档只列举了一部分参数，详细参数列表可参考[官方文档](https://platform.claude.com/docs/en/api/messages/create)。
{% endhint %}

**模型列表：**

* `claude-sonnet-4-5-20250929`
* `claude-haiku-4-5-20251001`
* `claude-opus-4-5-20251101`
* `claude-opus-4-6`
* `claude-sonnet-4-6`
* `claude-opus-4-7`
* `claude-opus-4-8`
* `claude-sonnet-5`
* `claude-fable-5`
* `claude-opus-5`
* `claude-opus-5-5`
* `claude-sonnet-5-5`
* `claude-haiku-5-5`

## 2. 请求说明

* **请求方法**:`POST`
* **请求地址**:

  > `https://gateway.theturbo.ai/v1/messages`

{% hint style="info" %}
平台为保障并发资源量，后端为多账号负载，如需提高缓存命中率，多轮对话模式可携带http请求头`X-Conversation-Id`加随机字符串请求，平台会优先路由到后端同一账号上。[参考文档](/api-reference/cn/ai/aig/gateway-features/cache-optimization.md)
{% endhint %}

***

## 3. 请求参数

### 3.1 Header 参数

| 参数名称           | 类型     | 必填 | 说明                                  | 示例值                |
| -------------- | ------ | -- | ----------------------------------- | ------------------ |
| `Content-Type` | string | 是  | 设置请求头类型，必须为 `application/json`      | `application/json` |
| `x-api-key`    | string | 是  | 身份验证所需的 API\_KEY，格式 `$YOUR_API_KEY` | `$YOUR_API_KEY`    |

***

### 3.2 Body 参数 (application/json)

| 参数名称                    | 类型      | 必填 | 说明                                                                                                                                              | 示例                                                                     |
| ----------------------- | ------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| **model**               | string  | 是  | 要使用的模型 ID。详见[概述](#id-1.-gai-shu)列出的可用版本，如 `claude-3-5-haiku-20241022`。                                                                          | `claude-haiku-4-5-20251001`                                            |
| **messages**            | array   | 是  | 聊天消息列表，格式与 Anthropic 兼容。数组中的每个对象包含 `role`(角色) 与 `content`(内容)。                                                                                  | `[{"role": "user","content": [{"type":"text","text":"你好，请给我讲个笑话。"}]}]` |
| message.role            | string  | 否  | 消息角色，可选值：`user`、`assistant`。                                                                                                                    | `user`                                                                 |
| message.content         | array   | 否  | s消息的具体内容。                                                                                                                                       | `[{"type":"text","text":"你好，请给我讲个笑话。"}]`                               |
| system                  | array   | 否  | system提示词。                                                                                                                                      | `[{"type":"text","text":"你是一个友善的人工智能助手"}]`                             |
| temperature             | number  | 否  | 采样温度，取值 `0～2`。数值越大，输出越随机；数值越小，输出越集中和确定。                                                                                                         | `0.7`                                                                  |
| top\_p                  | number  | 否  | 另一种调节采样分布的方式，取值 `0～1`。和 `temperature` 通常二选一设置。                                                                                                  | `0.9`                                                                  |
| stream                  | boolean | 否  | 是否开启流式输出。设置为 `true` 时，返回类似 ChatGPT 的流式数据。                                                                                                       | `false`                                                                |
| max\_tokens             | number  | 否  | 单次回复可生成的最大 token 数量，受模型上下文长度限制。                                                                                                                 | `8192`                                                                 |
| thinking                | struct  | 否  | 启用 Claude 扩展思考的配置。                                                                                                                              | `{"type":"adaptive"}`                                                  |
| thinking.type           | string  | 是  | thinking类型，支持配置`enabled`、`disabled`、`adaptive`。4.7版本及以上只支持`adaptive`、`disabled`，4.5版本及以下只支持`enabled`、`disabled`。`claude-sonnet-5`默认为`adaptive`。 | `adaptive`                                                             |
| thinking.budget\_tokens | number  | 否  | `type`配置为`enabled`时必须设置。用于确定 Claude 在内部推理过程中可以使用多少 token。更大的预算可以让 Claude 在处理复杂问题时进行更深入的分析，从而提升回答质量。该值必须大于等于`1024`，并且小于`max_tokens`。             | `1024`                                                                 |
| thinking.display        | string  | 否  | 当设置为`summarized`时，思考内容会正常返回。当设置为`omitted`时，思考内容会被隐藏，但会返回一个签名（signature），用于支持多轮对话的连续性。4.7版本及以上通常默认会被设置为`omitted`。                                | `omitted`                                                              |
| output\_config.effort   | string  | 否  | 用来控制模型在推理任务中投入多少“计算精力”。支持配置`low`、`medium`、`high`、`xhigh`、`max`。                                                                                 | `medium`                                                               |

***

### 3.3 支持工具列表

{% hint style="info" %}
anthropic-beta不为空的，代表需要携带http请求头anthropic-beta才能使用该工具，多个不同的beta头用逗号隔开，如`anthropic-beta: computer-use-2025-01-24,context-management-2025-06-27`。
{% endhint %}

| 工具名称                | 支持模型                                                                      | anthropic-beta                                      | 官方文档地址                                                                                               |
| ------------------- | ------------------------------------------------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `Bash tool`         | 所有模型                                                                      | -                                                   | [Bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool)                 |
| `Memory tool`       | Haiku系列/Opus系列/`claude-sonnet-4-6`                                        | -                                                   | [Memory tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool)             |
| `Text editor tool`  | 所有模型                                                                      | -                                                   | [Text editor tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool)   |
| `Tool search tool`  | Opus系列                                                                    | -                                                   | [Tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)   |
| `Computer use tool` | 所有模型                                                                      | `computer-use-2025-01-24`/`computer-use-2025-11-24` | [Computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) |
| `Compaction`        | `claude-sonnet-4-6`/`claude-opus-4-6`/`claude-opus-4-7`/`claude-opus-4-8` | `compact-2026-01-12`                                | [Compaction](https://platform.claude.com/docs/en/build-with-claude/compaction)                       |
| `Context editing`   | 所有模型                                                                      | `context-management-2025-06-27`                     | [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing)             |

***

## 4. 请求示例

### 4.1 基础对话

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/messages
Content-Type: application/json
x-api-key: $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"max_tokens": 4096,
	"system": [{
		"type": "text",
		"text": "你是一个友善的人工智能助手"
	}],
	"messages": [{
		"role": "user",
		"content": [{
			"type": "text",
			"text": "你好，给我科普一下量子力学吧"
		}]
	}]
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/messages \
	-H "Content-Type: application/json" \
	-H "x-api-key: $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"max_tokens\": 4096,
	\"system\": [{
		\"type\": \"text\",
		\"text\": \"你是一个友善的人工智能助手\"
	}],
	\"messages\": [{
		\"role\": \"user\",
		\"content\": [{
			\"type\": \"text\",
			\"text\": \"你好，给我科普一下量子力学吧\"
		}]
	}]
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/anthropics/anthropic-sdk-go/option"
)

func main() {
	apiKey := "sk-123456789012345678901234567890123456789012345678"

	client := anthropic.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL("https://gateway.theturbo.ai"),
	)

	resp, err := client.Messages.New(
		context.Background(),
		anthropic.MessageNewParams{
			Model:     "claude-haiku-4-5-20251001",
			MaxTokens: 4096,
			System: []anthropic.TextBlockParam{
				{
					Type: "text",
					Text: "你是一个友善的人工智能助手",
				},
			},
			Messages: []anthropic.MessageParam{
				anthropic.NewUserMessage(anthropic.NewTextBlock("你好，给我科普一下量子力学吧")),
			},
		},
	)

	if err != nil {
		fmt.Println("error:", err)
		return
	}

	for _, block := range resp.Content {
		if block.Type == "text" {
			fmt.Println("💬 Assistant reply:")
			fmt.Println(block.Text)
		}
	}

	fmt.Println("\n📊 Token usage:")
	fmt.Printf("  - Input tokens: %d\n", resp.Usage.InputTokens)
	fmt.Printf("  - Output tokens: %d\n", resp.Usage.OutputTokens)
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

from anthropic import Anthropic

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"

    client = Anthropic(
        api_key=api_key,
        base_url="https://gateway.theturbo.ai"
    )

    response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=4096,
        system=[{
            "type": "text",
            "text": "你是一个友善的人工智能助手"
        }],
        messages=[{
            "role": "user",
            "content": "你好，给我科普一下量子力学吧"
        }]
    )

    for block in response.content:
        if block.type == "text":
            print("💬 Assistant reply:")
            print(block.text)

    print("\n📊 Token usage:")
    print(f"  - Input tokens: {response.usage.input_tokens}")
    print(f"  - Output tokens: {response.usage.output_tokens}")

if __name__ == "__main__":
    main()

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: "sk-123456789012345678901234567890123456789012345678",
  baseURL: "https://gateway.theturbo.ai",
});

const response = await client.messages.create({
  model: "claude-haiku-4-5-20251001",
  max_tokens: 4096,
  system: [{ type: "text", text: "你是一个友善的人工智能助手" }],
  messages: [
    { role: "user", content: "你好，给我科普一下量子力学吧" },
  ],
});

for (const block of response.content) {
  if (block.type === "text") {
    console.log("💬 Assistant reply:");
    console.log(block.text);
  }
}

console.log("\n📊 Token usage:");
console.log(`  - Input tokens: ${response.usage.input_tokens}`);
console.log(`  - Output tokens: ${response.usage.output_tokens}`);
```

{% endtab %}

{% tab title="Java" %}

```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.TextBlockParam;
import java.util.List;

public final class Main {
    public static void main(String[] args) {
        String apiKey = "sk-123456789012345678901234567890123456789012345678";

        AnthropicClient client = AnthropicOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl("https://gateway.theturbo.ai")
                .build();

        MessageCreateParams params = MessageCreateParams.builder()
                .model("claude-haiku-4-5-20251001")
                .maxTokens(4096)
                .systemOfTextBlockParams(List.of(TextBlockParam.builder()
                        .text("你是一个友善的人工智能助手")
                        .build()))
                .addUserMessage("你好，给我科普一下量子力学吧")
                .build();

        Message message = client.messages().create(params);

        System.out.println("💬 Assistant reply:");
        message.content().stream()
                .flatMap(block -> block.text().stream())
                .forEach(textBlock -> System.out.println(textBlock.text()));

        System.out.println("\n📊 Token usage:");
        System.out.println("  - Input tokens: " + message.usage().inputTokens());
        System.out.println("  - Output tokens: " + message.usage().outputTokens());
    }
}
```

{% endtab %}
{% endtabs %}

### 4.2 图片理解

多模态图片理解功能，通过上传图片或图片URL提交图片给大模型。

<details>

<summary>支持的图片类型</summary>

`image/png` `image/jpeg` `image/webp` `image/gif`

</details>

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/messages
Content-Type: application/json
x-api-key: $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"max_tokens": 1024,
	"messages": [{
		"role": "user",
		"content": [
			{
				"type": "text",
				"text": "这张图片里有什么？"
			},
			{
				"type": "image",
				"source": {
					"type": "base64",
					"media_type": "image/jpeg",
					"data": "${base64_image}"
				}
			}
		]
	}]
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
base64_image=$(base64 -i "Path/to/agi/image.jpeg");
curl https://gateway.theturbo.ai/v1/messages \
	-H "Content-Type: application/json" \
	-H "x-api-key: $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"max_tokens\": 1024,
	\"messages\": [{
		\"role\": \"user\",
		\"content\": [{
				\"type\": \"text\",
				\"text\": \"这张图片里有什么？\"
			},
			{
				\"type\": \"image\",
				\"source\": {
					\"type\": \"base64\",
					\"media_type\": \"image/jpeg\",
					\"data\": \"${base64_image}\"
				}
			}
		]
	}]
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"os"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/anthropics/anthropic-sdk-go/option"
)

func main() {
	apiKey := "sk-123456789012345678901234567890123456789012345678"

	client := anthropic.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL("https://gateway.theturbo.ai"),
	)

	imagePath := "Path/to/agi/image.jpeg"
	imageBytes, err := os.ReadFile(imagePath)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	base64Image := base64.StdEncoding.EncodeToString(imageBytes)

	resp, err := client.Messages.New(
		context.Background(),
		anthropic.MessageNewParams{
			Model:     "claude-haiku-4-5-20251001",
			MaxTokens: 1024,
			Messages: []anthropic.MessageParam{
				anthropic.NewUserMessage(
					anthropic.NewTextBlock("这张图片里有什么？"),
					anthropic.NewImageBlockBase64("image/jpeg", base64Image),
				),
			},
		},
	)

	if err != nil {
		fmt.Println("error:", err)
		return
	}

	for _, block := range resp.Content {
		if block.Type == "text" {
			fmt.Println("💬 Assistant reply:")
			fmt.Println(block.Text)
		}
	}
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

import base64
from anthropic import Anthropic

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"

    client = Anthropic(
        api_key=api_key,
        base_url="https://gateway.theturbo.ai"
    )

    image_path = "Path/to/agi/image.jpeg"
    with open(image_path, "rb") as f:
        image_bytes = f.read()

    base64_image = base64.b64encode(image_bytes).decode("utf-8")

    response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=1024,
        messages=[{
            "role": "user",
            "content": [
                {"type": "text", "text": "这张图片里有什么？"},
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/jpeg",
                        "data": base64_image
                    }
                }
            ]
        }]
    )

    for block in response.content:
        if block.type == "text":
            print("💬 Assistant reply:")
            print(block.text)

if __name__ == "__main__":
    main()

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import fs from "node:fs";
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: "sk-123456789012345678901234567890123456789012345678",
  baseURL: "https://gateway.theturbo.ai",
});

const imagePath = "Path/to/agi/image.jpeg";
const base64Image = fs.readFileSync(imagePath).toString("base64");

const response = await client.messages.create({
  model: "claude-haiku-4-5-20251001",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        { type: "text", text: "这张图片里有什么？" },
        {
          type: "image",
          source: {
            type: "base64",
            media_type: "image/jpeg",
            data: base64Image,
          },
        },
      ],
    },
  ],
});

for (const block of response.content) {
  if (block.type === "text") {
    console.log("💬 Assistant reply:");
    console.log(block.text);
  }
}
```

{% endtab %}

{% tab title="Java" %}

```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Base64ImageSource;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.ImageBlockParam;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.TextBlockParam;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.List;

public final class Main {
    public static void main(String[] args) throws IOException {
        String apiKey = "sk-123456789012345678901234567890123456789012345678";

        AnthropicClient client = AnthropicOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl("https://gateway.theturbo.ai")
                .build();

        byte[] imageBytes = Files.readAllBytes(Path.of("Path/to/agi/image.jpeg"));
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        ContentBlockParam textParam = ContentBlockParam.ofText(TextBlockParam.builder()
                .text("这张图片里有什么？")
                .build());
        ContentBlockParam imageParam = ContentBlockParam.ofImage(ImageBlockParam.builder()
                .source(Base64ImageSource.builder()
                        .mediaType(Base64ImageSource.MediaType.IMAGE_JPEG)
                        .data(base64Image)
                        .build())
                .build());

        MessageCreateParams params = MessageCreateParams.builder()
                .model("claude-haiku-4-5-20251001")
                .maxTokens(1024)
                .addUserMessageOfBlockParams(List.of(textParam, imageParam))
                .build();

        Message message = client.messages().create(params);

        System.out.println("💬 Assistant reply:");
        message.content().stream()
                .flatMap(block -> block.text().stream())
                .forEach(textBlock -> System.out.println(textBlock.text()));
    }
}
```

{% endtab %}
{% endtabs %}

### 4.3 函数调用

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/messages
Content-Type: application/json
x-api-key: $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"max_tokens": 1024,
	"messages": [{
		"role": "user",
		"content": "What's the weather like in Boston today?"
	}],
	"tools": [{
		"name": "get_current_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"]
		}
	}]
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/messages \
	-H "Content-Type: application/json" \
	-H "x-api-key: $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"max_tokens\": 1024,
	\"messages\": [{
		\"role\": \"user\",
		\"content\": \"What's the weather like in Boston today?\"
	}],
	\"tools\": [{
		\"name\": \"get_current_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\"]
		}
	}]
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/anthropics/anthropic-sdk-go/option"
)

func main() {
	apiKey := "sk-123456789012345678901234567890123456789012345678"

	client := anthropic.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL("https://gateway.theturbo.ai"),
	)

	weatherTool := anthropic.ToolParam{
		Name:        "get_current_weather",
		Description: anthropic.String("Get the current weather in a given location"),
		InputSchema: anthropic.ToolInputSchemaParam{
			Properties: map[string]any{
				"location": map[string]any{
					"type":        "string",
					"description": "The city and state, e.g. San Francisco, CA",
				},
				"unit": map[string]any{
					"type": "string",
					"enum": []string{"celsius", "fahrenheit"},
				},
			},
		},
	}

	resp, err := client.Messages.New(
		context.Background(),
		anthropic.MessageNewParams{
			Model:     "claude-haiku-4-5-20251001",
			MaxTokens: 1024,
			Messages: []anthropic.MessageParam{
				anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in Boston today?")),
			},
			Tools: []anthropic.ToolUnionParam{
				{OfTool: &weatherTool},
			},
		},
	)

	if err != nil {
		fmt.Println("error:", err)
		return
	}

	for _, block := range resp.Content {
		switch block.Type {
		case "text":
			fmt.Println("💬 Assistant reply:", block.Text)
		case "tool_use":
			fmt.Println("🔧 Function called:", block.Name)
			fmt.Println("📥 Arguments JSON:", string(block.Input))
		}
	}
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

from anthropic import Anthropic

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"

    client = Anthropic(
        api_key=api_key,
        base_url="https://gateway.theturbo.ai"
    )

    tools = [{
        "name": "get_current_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"]
        }
    }]

    response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "What's the weather like in Boston today?"}
        ],
        tools=tools
    )

    for block in response.content:
        if block.type == "text":
            print(f"💬 Assistant reply: {block.text}")
        elif block.type == "tool_use":
            print(f"🔧 Function called: {block.name}")
            print(f"📥 Arguments JSON: {block.input}")

if __name__ == "__main__":
    main()

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: "sk-123456789012345678901234567890123456789012345678",
  baseURL: "https://gateway.theturbo.ai",
});

const tools = [
  {
    name: "get_current_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"],
    },
  },
];

const response = await client.messages.create({
  model: "claude-haiku-4-5-20251001",
  max_tokens: 1024,
  messages: [
    { role: "user", content: "What's the weather like in Boston today?" },
  ],
  tools,
});

for (const block of response.content) {
  if (block.type === "text") {
    console.log("💬 Assistant reply:", block.text);
  } else if (block.type === "tool_use") {
    console.log("🔧 Function called:", block.name);
    console.log("📥 Arguments JSON:", block.input);
  }
}
```

{% endtab %}

{% tab title="Java" %}

```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Tool;
import java.util.List;
import java.util.Map;

public final class Main {
    public static void main(String[] args) {
        String apiKey = "sk-123456789012345678901234567890123456789012345678";

        AnthropicClient client = AnthropicOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl("https://gateway.theturbo.ai")
                .build();

        Tool.InputSchema schema = Tool.InputSchema.builder()
                .properties(Tool.InputSchema.Properties.builder()
                        .putAdditionalProperty("location", JsonValue.from(Map.of(
                                "type", "string",
                                "description", "The city and state, e.g. San Francisco, CA")))
                        .putAdditionalProperty("unit", JsonValue.from(Map.of(
                                "type", "string",
                                "enum", List.of("celsius", "fahrenheit"))))
                        .build())
                .required(List.of("location"))
                .build();

        Tool weatherTool = Tool.builder()
                .name("get_current_weather")
                .description("Get the current weather in a given location")
                .inputSchema(schema)
                .build();

        MessageCreateParams params = MessageCreateParams.builder()
                .model("claude-haiku-4-5-20251001")
                .maxTokens(1024)
                .addUserMessage("What's the weather like in Boston today?")
                .addTool(weatherTool)
                .build();

        Message message = client.messages().create(params);

        message.content().forEach(block -> {
            if (block.isText()) {
                System.out.println("💬 Assistant reply: " + block.asText().text());
            } else if (block.isToolUse()) {
                System.out.println("🔧 Function called: " + block.asToolUse().name());
                System.out.println("📥 Arguments JSON: " + block.asToolUse()._input());
            }
        });
    }
}
```

{% endtab %}
{% endtabs %}

### 4.4 提示词缓存（Prompt Caching）

提示词缓存可以缓存请求中稳定不变的前缀内容（如工具定义、system 提示词、长文档等），从而降低重复请求的费用并加快响应速度。详细说明可参考[官方文档](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)。

{% hint style="info" %}
本平台仅支持\*\*显式缓存断点（Explicit cache breakpoints）\*\*的方式，即通过在 `tools`、`system`、`messages` 的具体内容块上添加 `cache_control` 字段来手动指定缓存位置。请勿在请求顶层设置 `cache_control`（自动缓存方式不受支持）。
{% endhint %}

{% hint style="info" %}
平台为保障并发资源量，后端为多账号负载，如需提高缓存命中率，多轮对话模式可携带http请求头`X-Conversation-Id`加随机字符串请求，平台会优先路由到后端同一账号上。[参考文档](/api-reference/cn/ai/aig/gateway-features/cache-optimization.md)
{% endhint %}

{% hint style="warning" %}
由于平台后端为多账号资源，缓存有效期越长越难保证命中同一后端账号（受账号配额等因素影响）。建议优先使用 5 分钟缓存（`ttl` 默认值），减少使用 1 小时缓存（`ttl: "1h"`）。
{% endhint %}

**`cache_control` 对象说明：**

| 参数名称   | 类型     | 必填 | 说明                      | 示例值         |
| ------ | ------ | -- | ----------------------- | ----------- |
| `type` | string | 是  | 缓存类型，目前仅支持 `ephemeral`  | `ephemeral` |
| `ttl`  | string | 否  | 缓存有效期，支持 `5m`（默认）与 `1h` | `1h`        |

```json
{ "type": "ephemeral" }              // 默认有效期 5 分钟
{ "type": "ephemeral", "ttl": "1h" } // 有效期 1 小时
```

{% hint style="info" %}
使用要点：

* 缓存前缀按 `tools` → `system` → `messages` 的顺序生成，缓存断点会缓存从开头到该断点（含）的全部内容。
* 每次请求最多设置 **4** 个缓存断点。
* `cache_control` 可添加在：`tools` 数组中的某个工具（通常放在最后一个工具上）、`system` 的文本块、`messages` 的内容块（`text`、`image`、`tool_result` 等）。
* 存在最小可缓存 token 数限制（随模型不同而变化），低于阈值时不会写入缓存，且不会报错。
* 可通过响应 `usage` 中的 `cache_creation_input_tokens`（写入缓存的 token 数）与 `cache_read_input_tokens`（命中缓存的 token 数）验证缓存是否生效。
  {% endhint %}

下面的示例在同一个请求中演示了三种位置的 `cache_control` 用法：工具（`tools`）、system 提示词（`system`）以及消息内容块（`messages`）。

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/messages
Content-Type: application/json
x-api-key: $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"max_tokens": 4096,
	"tools": [{
		"name": "get_weather",
		"description": "获取指定城市的天气",
		"input_schema": {
			"type": "object",
			"properties": {
				"location": {
					"type": "string",
					"description": "城市名称，例如：北京"
				}
			},
			"required": ["location"]
		},
		"cache_control": {
			"type": "ephemeral"
		}
	}],
	"system": [{
		"type": "text",
		"text": "你是一个友善的人工智能助手，请参考以下知识库回答用户问题：……（此处为需要被缓存的大段稳定上下文，长度需超过模型的最小可缓存 token 数）"
	}, {
		"type": "text",
		"text": "以上为知识库内容。",
		"cache_control": {
			"type": "ephemeral"
		}
	}],
	"messages": [{
		"role": "user",
		"content": [{
			"type": "text",
			"text": "你好，给我科普一下量子力学吧",
			"cache_control": {
				"type": "ephemeral"
			}
		}]
	}]
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/messages \
	-H "Content-Type: application/json" \
	-H "x-api-key: $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"max_tokens\": 4096,
	\"tools\": [{
		\"name\": \"get_weather\",
		\"description\": \"获取指定城市的天气\",
		\"input_schema\": {
			\"type\": \"object\",
			\"properties\": {
				\"location\": {
					\"type\": \"string\",
					\"description\": \"城市名称，例如：北京\"
				}
			},
			\"required\": [\"location\"]
		},
		\"cache_control\": { \"type\": \"ephemeral\" }
	}],
	\"system\": [{
		\"type\": \"text\",
		\"text\": \"你是一个友善的人工智能助手，请参考以下知识库回答用户问题：……（此处为需要被缓存的大段稳定上下文，长度需超过模型的最小可缓存 token 数）\"
	}, {
		\"type\": \"text\",
		\"text\": \"以上为知识库内容。\",
		\"cache_control\": { \"type\": \"ephemeral\" }
	}],
	\"messages\": [{
		\"role\": \"user\",
		\"content\": [{
			\"type\": \"text\",
			\"text\": \"你好，给我科普一下量子力学吧\",
			\"cache_control\": { \"type\": \"ephemeral\" }
		}]
	}]
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/anthropics/anthropic-sdk-go/option"
)

func main() {
	apiKey := "sk-123456789012345678901234567890123456789012345678"

	client := anthropic.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL("https://gateway.theturbo.ai"),
	)

	// 1) 在 tool 上添加 cache_control（缓存 tools 前缀）
	weatherTool := anthropic.ToolParam{
		Name:        "get_weather",
		Description: anthropic.String("获取指定城市的天气"),
		InputSchema: anthropic.ToolInputSchemaParam{
			Properties: map[string]any{
				"location": map[string]any{
					"type":        "string",
					"description": "城市名称，例如：北京",
				},
			},
		},
		CacheControl: anthropic.NewCacheControlEphemeralParam(),
	}

	// 2) 在 message 内容块上添加 cache_control
	userText := anthropic.NewTextBlock("你好，给我科普一下量子力学吧")
	userText.OfText.CacheControl = anthropic.NewCacheControlEphemeralParam()

	resp, err := client.Messages.New(
		context.Background(),
		anthropic.MessageNewParams{
			Model:     "claude-haiku-4-5-20251001",
			MaxTokens: 4096,
			Tools: []anthropic.ToolUnionParam{
				{OfTool: &weatherTool},
			},
			// 3) 在 system 文本块上添加 cache_control
			System: []anthropic.TextBlockParam{
				{
					Type: "text",
					Text: "你是一个友善的人工智能助手，请参考以下知识库回答用户问题：……（此处为需要被缓存的大段稳定上下文，长度需超过模型的最小可缓存 token 数）",
				},
				{
					Type:         "text",
					Text:         "以上为知识库内容。",
					CacheControl: anthropic.NewCacheControlEphemeralParam(),
				},
			},
			Messages: []anthropic.MessageParam{
				anthropic.NewUserMessage(userText),
			},
		},
	)

	if err != nil {
		fmt.Println("error:", err)
		return
	}

	for _, block := range resp.Content {
		if block.Type == "text" {
			fmt.Println("💬 Assistant reply:")
			fmt.Println(block.Text)
		}
	}

	// 缺失字段会被 SDK 解析为 0，无需额外判空
	fmt.Println("\n📊 Token usage:")
	fmt.Printf("  - Input tokens: %d\n", resp.Usage.InputTokens)
	fmt.Printf("  - Cache creation input tokens: %d\n", resp.Usage.CacheCreationInputTokens)
	fmt.Printf("  - Cache read input tokens: %d\n", resp.Usage.CacheReadInputTokens)
	fmt.Printf("  - Ephemeral 5m input tokens: %d\n", resp.Usage.CacheCreation.Ephemeral5mInputTokens)
	fmt.Printf("  - Ephemeral 1h input tokens: %d\n", resp.Usage.CacheCreation.Ephemeral1hInputTokens)
	fmt.Printf("  - Output tokens: %d\n", resp.Usage.OutputTokens)
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

from anthropic import Anthropic

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"

    client = Anthropic(
        api_key=api_key,
        base_url="https://gateway.theturbo.ai"
    )

    response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=4096,
        # 1) 在 tool 上添加 cache_control（缓存 tools 前缀）
        tools=[{
            "name": "get_weather",
            "description": "获取指定城市的天气",
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市名称，例如：北京"
                    }
                },
                "required": ["location"]
            },
            "cache_control": {"type": "ephemeral"}
        }],
        # 2) 在 system 文本块上添加 cache_control
        system=[
            {
                "type": "text",
                "text": "你是一个友善的人工智能助手，请参考以下知识库回答用户问题：……（此处为需要被缓存的大段稳定上下文，长度需超过模型的最小可缓存 token 数）"
            },
            {
                "type": "text",
                "text": "以上为知识库内容。",
                "cache_control": {"type": "ephemeral"}
            }
        ],
        # 3) 在 message 内容块上添加 cache_control
        messages=[{
            "role": "user",
            "content": [{
                "type": "text",
                "text": "你好，给我科普一下量子力学吧",
                "cache_control": {"type": "ephemeral"}
            }]
        }]
    )

    for block in response.content:
        if block.type == "text":
            print("💬 Assistant reply:")
            print(block.text)

    usage = response.usage
    cache_creation = usage.cache_creation  # 可能为 None

    # 缓存相关字段可能为空，统一按 0 处理
    print("\n📊 Token usage:")
    print(f"  - Input tokens: {usage.input_tokens}")
    print(f"  - Cache creation input tokens: {usage.cache_creation_input_tokens or 0}")
    print(f"  - Cache read input tokens: {usage.cache_read_input_tokens or 0}")
    print(f"  - Ephemeral 5m input tokens: {cache_creation.ephemeral_5m_input_tokens if cache_creation else 0}")
    print(f"  - Ephemeral 1h input tokens: {cache_creation.ephemeral_1h_input_tokens if cache_creation else 0}")
    print(f"  - Output tokens: {usage.output_tokens}")

if __name__ == "__main__":
    main()

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: "sk-123456789012345678901234567890123456789012345678",
  baseURL: "https://gateway.theturbo.ai",
});

const response = await client.messages.create({
  model: "claude-haiku-4-5-20251001",
  max_tokens: 4096,
  // 1) 在 tool 上添加 cache_control（缓存 tools 前缀）
  tools: [
    {
      name: "get_weather",
      description: "获取指定城市的天气",
      input_schema: {
        type: "object",
        properties: {
          location: { type: "string", description: "城市名称，例如：北京" },
        },
        required: ["location"],
      },
      cache_control: { type: "ephemeral" },
    },
  ],
  // 2) 在 system 文本块上添加 cache_control
  system: [
    {
      type: "text",
      text: "你是一个友善的人工智能助手，请参考以下知识库回答用户问题：……（此处为需要被缓存的大段稳定上下文，长度需超过模型的最小可缓存 token 数）",
    },
    {
      type: "text",
      text: "以上为知识库内容。",
      cache_control: { type: "ephemeral" },
    },
  ],
  // 3) 在 message 内容块上添加 cache_control
  messages: [
    {
      role: "user",
      content: [
        {
          type: "text",
          text: "你好，给我科普一下量子力学吧",
          cache_control: { type: "ephemeral" },
        },
      ],
    },
  ],
});

for (const block of response.content) {
  if (block.type === "text") {
    console.log("💬 Assistant reply:");
    console.log(block.text);
  }
}

// 缓存相关字段可能为空，统一按 0 处理
const usage = response.usage;
const cacheCreation = usage.cache_creation ?? {};

console.log("\n📊 Token usage:");
console.log(`  - Input tokens: ${usage.input_tokens}`);
console.log(`  - Cache creation input tokens: ${usage.cache_creation_input_tokens ?? 0}`);
console.log(`  - Cache read input tokens: ${usage.cache_read_input_tokens ?? 0}`);
console.log(`  - Ephemeral 5m input tokens: ${cacheCreation.ephemeral_5m_input_tokens ?? 0}`);
console.log(`  - Ephemeral 1h input tokens: ${cacheCreation.ephemeral_1h_input_tokens ?? 0}`);
console.log(`  - Output tokens: ${usage.output_tokens}`);
```

{% endtab %}

{% tab title="Java" %}

```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.CacheControlEphemeral;
import com.anthropic.models.messages.CacheCreation;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.TextBlockParam;
import com.anthropic.models.messages.Tool;
import java.util.List;
import java.util.Map;

public final class Main {
    public static void main(String[] args) {
        String apiKey = "sk-123456789012345678901234567890123456789012345678";

        AnthropicClient client = AnthropicOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl("https://gateway.theturbo.ai")
                .build();

        // 1) 在 tool 上添加 cache_control（缓存 tools 前缀）
        Tool.InputSchema schema = Tool.InputSchema.builder()
                .properties(Tool.InputSchema.Properties.builder()
                        .putAdditionalProperty("location", JsonValue.from(Map.of(
                                "type", "string",
                                "description", "城市名称，例如：北京")))
                        .build())
                .required(List.of("location"))
                .build();

        Tool weatherTool = Tool.builder()
                .name("get_weather")
                .description("获取指定城市的天气")
                .inputSchema(schema)
                .cacheControl(CacheControlEphemeral.builder().build())
                .build();

        MessageCreateParams params = MessageCreateParams.builder()
                .model("claude-haiku-4-5-20251001")
                .maxTokens(4096)
                .addTool(weatherTool)
                // 2) 在 system 文本块上添加 cache_control
                .systemOfTextBlockParams(List.of(
                        TextBlockParam.builder()
                                .text("你是一个友善的人工智能助手，请参考以下知识库回答用户问题：……（此处为需要被缓存的大段稳定上下文，长度需超过模型的最小可缓存 token 数）")
                                .build(),
                        TextBlockParam.builder()
                                .text("以上为知识库内容。")
                                .cacheControl(CacheControlEphemeral.builder().build())
                                .build()))
                // 3) 在 message 内容块上添加 cache_control
                .addUserMessageOfBlockParams(List.of(
                        ContentBlockParam.ofText(TextBlockParam.builder()
                                .text("你好，给我科普一下量子力学吧")
                                .cacheControl(CacheControlEphemeral.builder().build())
                                .build())))
                .build();

        Message message = client.messages().create(params);

        System.out.println("💬 Assistant reply:");
        message.content().stream()
                .flatMap(block -> block.text().stream())
                .forEach(textBlock -> System.out.println(textBlock.text()));

        // 缓存相关字段可能为空，统一按 0 处理
        CacheCreation cacheCreation = message.usage().cacheCreation().orElse(null);

        System.out.println("\n📊 Token usage:");
        System.out.println("  - Input tokens: " + message.usage().inputTokens());
        System.out.println("  - Cache creation input tokens: " + message.usage().cacheCreationInputTokens().orElse(0L));
        System.out.println("  - Cache read input tokens: " + message.usage().cacheReadInputTokens().orElse(0L));
        System.out.println("  - Ephemeral 5m input tokens: "
                + (cacheCreation != null ? cacheCreation.ephemeral5mInputTokens() : 0));
        System.out.println("  - Ephemeral 1h input tokens: "
                + (cacheCreation != null ? cacheCreation.ephemeral1hInputTokens() : 0));
        System.out.println("  - Output tokens: " + message.usage().outputTokens());
    }
}
```

{% endtab %}
{% endtabs %}

## 5. 响应示例

```json
{
	"model": "claude-haiku-4-5-20251001",
	"id": "msg_bdrk_01AZpXbu4crT5R6gsYJwk6KD",
	"type": "message",
	"role": "assistant",
	"content": [{
		"type": "text",
		"text": "量子力学是研究微观世界的物理学分支……"
	}],
	"stop_reason": "end_turn",
	"stop_sequence": null,
	"usage": {
		"input_tokens": 36,
		"cache_creation_input_tokens": 0,
		"cache_read_input_tokens": 0,
		"cache_creation": {
			"ephemeral_5m_input_tokens": 0,
			"ephemeral_1h_input_tokens": 0
		},
		"output_tokens": 366
	}
}
```
