> 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-response.md).

# 兼容API (/responses)

## 1. 概述

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

{% hint style="success" %}
本 API 兼容 OpenAI 的 `/responses` 接口格式，方便使用 OpenAI SDK / Codex 的用户以统一的方式调用模型。平台会在网关侧自动将 Responses 请求格式转换为模型所需的格式。
{% endhint %}

{% hint style="warning" %}
本 API 在网关侧为无状态转换，不支持 `previous_response_id`，携带该参数时会返回 `400` 错误。多轮对话请将完整的历史上下文通过 `input` 传入。
{% endhint %}

{% hint style="warning" %}
本 API 为提高 Codex 用户访问性能，会默认开启 `cache_control` 产生缓存创建token。目前不支持关闭缓存，如果需要关闭缓存，请与我们联系。
{% 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/responses`

{% 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`     |
| `Authorization` | string | 是  | 身份验证所需的 API\_KEY，格式 `Bearer $YOUR_API_KEY` | `Bearer $YOUR_API_KEY` |

***

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

| 参数名称                  | 类型              | 必填 | 说明                                                                                                                                                    | 示例                             |
| --------------------- | --------------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| **model**             | string          | 是  | 要使用的模型 ID。详见[概述](#id-1.-gai-shu)列出的可用版本，如 `claude-haiku-4-5-20251001`。                                                                                | `claude-haiku-4-5-20251001`    |
| **input**             | string 或 array  | 是  | 传入 `/v1/responses` 请求的输入内容，可为纯文本字符串，也可为包含文本或图像的消息数组。                                                                                                  | `你好，请给我讲个笑话。`                  |
| instructions          | string          | 否  | 设置系统提示词的另一种方式，会作为 `system` 消息插入到上下文最前。                                                                                                                | `你是一位物理学老师。`                   |
| stream                | boolean         | 否  | 是否开启流式输出。设置为 `true` 时，以服务器发送事件（SSE）形式返回增量数据。                                                                                                          | `false`                        |
| temperature           | number          | 否  | 采样温度，取值 `0～2`。数值越大，输出越随机；数值越小，输出越集中和确定。仅在 4.6 及以下版本模型生效，且开启思考时不生效。                                                                                    | `0.7`                          |
| top\_p                | number          | 否  | 另一种调节采样分布的方式，取值 `0～1`。和 `temperature` 通常二选一设置，同时携带时仅 `temperature` 生效。仅在 4.6 及以下版本模型生效。                                                               | `0.9`                          |
| max\_output\_tokens   | integer         | 否  | 单次响应可生成的最大 token 数量，受模型上下文长度限制。                                                                                                                       | `1024`                         |
| reasoning             | object          | 否  | 推理配置，通过 `reasoning.effort` 控制模型在推理任务中投入多少“思考精力”，支持 `low`、`medium`、`high`、`xhigh`、`max`、`none`。`claude-sonnet-5` 默认开启思考，如需关闭，须显式携带 `"effort": "none"`。 | `{"effort": "medium"}`         |
| text                  | object          | 否  | 输出文本配置，包含 `format` 对象，用于约束输出格式。支持 `type` 为 `json_schema` 的结构化输出（不支持 `json_object`）。4.7版本及以上不支持该参数。                                                    | `{"format": {"type": "text"}}` |
| tools                 | array           | 否  | 模型可调用的工具列表，目前仅支持 `type` 为 `function` 的工具。详见[函数调用](#id-4.3-han-shu-diao-yong)。                                                                         | 见函数调用示例                        |
| tool\_choice          | string 或 object | 否  | 控制模型如何选择工具，支持 `auto`、`required`、`none`，或通过对象指定具体函数。                                                                                                   | `auto`                         |
| parallel\_tool\_calls | boolean         | 否  | 是否允许一次回复中并行调用多个工具。设为 `false` 时禁用并行工具调用。                                                                                                               | `true`                         |

***

## 4. 请求示例

### 4.1 基础对话

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

```http
POST /v1/responses
Content-Type: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"input": "你好，给我科普一下量子力学吧"
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/responses \
	-H "Content-Type: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"input\": \"你好，给我科普一下量子力学吧\"
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
	"github.com/openai/openai-go/responses"
)

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

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

	resp, err := client.Responses.New(
		context.Background(),
		responses.ResponseNewParams{
			Model: "claude-haiku-4-5-20251001",
			Input: responses.ResponseNewParamsInputUnion{
				OfString: openai.String("你好，给我科普一下量子力学吧"),
			},
		},
	)

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

	fmt.Println(resp.OutputText())
}

```

{% endtab %}

{% tab title="Python" %}

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

from openai import OpenAI

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

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

    response = client.responses.create(
        model="claude-haiku-4-5-20251001",
        input="你好，给我科普一下量子力学吧"
    )

    print(response.output_text)

if __name__ == "__main__":
    main()

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import OpenAI from "openai";

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

const response = await client.responses.create({
  model: "claude-haiku-4-5-20251001",
  input: "你好，给我科普一下量子力学吧",
});

console.log(response.output_text);
```

{% endtab %}

{% tab title="Java" %}

```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

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

        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl("https://gateway.theturbo.ai/v1")
                .build();

        ResponseCreateParams params = ResponseCreateParams.builder()
                .model("claude-haiku-4-5-20251001")
                .input("你好，给我科普一下量子力学吧")
                .build();

        Response response = client.responses().create(params);

        response.output().stream()
                .flatMap(item -> item.message().stream())
                .flatMap(message -> message.content().stream())
                .flatMap(content -> content.outputText().stream())
                .forEach(outputText -> System.out.println(outputText.text()));
    }
}
```

{% endtab %}
{% endtabs %}

### 4.2 图片理解

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

```http
POST /v1/responses
Content-Type: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"input": [
		{
			"role": "user",
			"content": [
				{
					"type": "input_text",
					"text": "这张图片里有什么？"
				},
				{
					"type": "input_image",
					"image_url": "data:image/jpeg;base64,${base64_image}"
				}
			]
		}
	]
}
```

{% endtab %}

{% tab title="Shell" %}

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

{% endtab %}

{% tab title="Go" %}

```go
package main

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

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
	"github.com/openai/openai-go/responses"
)

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

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

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

	base64Image := base64.StdEncoding.EncodeToString(imageBytes)
	imageURL := "data:image/jpeg;base64," + base64Image

	resp, err := client.Responses.New(
		context.Background(),
		responses.ResponseNewParams{
			Model: "claude-haiku-4-5-20251001",
			Input: responses.ResponseNewParamsInputUnion{
				OfInputItemList: responses.ResponseInputParam{
					responses.ResponseInputItemParamOfMessage(
						responses.ResponseInputMessageContentListParam{
							{
								OfInputText: &responses.ResponseInputTextParam{
									Text: "这张图片里有什么？",
								},
							},
							{
								OfInputImage: &responses.ResponseInputImageParam{
									ImageURL: openai.String(imageURL),
								},
							},
						},
						responses.EasyInputMessageRoleUser,
					),
				},
			},
		},
	)

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

	fmt.Println(resp.OutputText())
}

```

{% endtab %}

{% tab title="Python" %}

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

import base64
from openai import OpenAI

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

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

    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")
    image_url = f"data:image/jpeg;base64,{base64_image}"

    response = client.responses.create(
        model="claude-haiku-4-5-20251001",
        input=[{
            "role": "user",
            "content": [
                {"type": "input_text", "text": "这张图片里有什么？"},
                {"type": "input_image", "image_url": image_url}
            ]
        }]
    )

    print(response.output_text)

if __name__ == "__main__":
    main()

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import fs from "node:fs";
import OpenAI from "openai";

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

const imagePath = "Path/to/agi/image.jpeg";
const base64Image = fs.readFileSync(imagePath).toString("base64");
const imageUrl = `data:image/jpeg;base64,${base64Image}`;

const response = await client.responses.create({
  model: "claude-haiku-4-5-20251001",
  input: [
    {
      role: "user",
      content: [
        { type: "input_text", text: "这张图片里有什么？" },
        { type: "input_image", image_url: imageUrl, detail: "auto" },
      ],
    },
  ],
});

console.log(response.output_text);
```

{% endtab %}

{% tab title="Java" %}

```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
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";

        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl("https://gateway.theturbo.ai/v1")
                .build();

        byte[] imageBytes = Files.readAllBytes(Path.of("Path/to/agi/image.jpeg"));
        String imageUrl = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(imageBytes);

        ResponseInputImage inputImage = ResponseInputImage.builder()
                .detail(ResponseInputImage.Detail.AUTO)
                .imageUrl(imageUrl)
                .build();
        ResponseInputItem messageItem = ResponseInputItem.ofMessage(ResponseInputItem.Message.builder()
                .role(ResponseInputItem.Message.Role.USER)
                .addInputTextContent("这张图片里有什么？")
                .addContent(inputImage)
                .build());

        ResponseCreateParams params = ResponseCreateParams.builder()
                .model("claude-haiku-4-5-20251001")
                .inputOfResponse(List.of(messageItem))
                .build();

        Response response = client.responses().create(params);

        response.output().stream()
                .flatMap(item -> item.message().stream())
                .flatMap(message -> message.content().stream())
                .flatMap(content -> content.outputText().stream())
                .forEach(outputText -> System.out.println(outputText.text()));
    }
}
```

{% endtab %}
{% endtabs %}

### 4.3 函数调用

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

```http
POST /v1/responses
Content-Type: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"input": "What's the weather like in Boston today?",
	"tools": [{
		"type": "function",
		"name": "get_current_weather",
		"description": "Get the current weather in a given location",
		"parameters": {
			"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": "auto"
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/responses \
	-H "Content-Type: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"input\": \"What's the weather like in Boston today?\",
	\"tools\": [{
		\"type\": \"function\",
		\"name\": \"get_current_weather\",
		\"description\": \"Get the current weather in a given location\",
		\"parameters\": {
			\"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\": \"auto\"
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
	"github.com/openai/openai-go/responses"
)

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

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

	tools := []responses.ToolUnionParam{
		{
			OfFunction: &responses.FunctionToolParam{
				Name:        "get_current_weather",
				Description: openai.String("Get the current weather in a given location"),
				Parameters: map[string]any{
					"type": "object",
					"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"},
						},
					},
					"required": []string{"location"},
				},
				Strict: openai.Bool(false),
			},
		},
	}

	resp, err := client.Responses.New(
		context.Background(),
		responses.ResponseNewParams{
			Model: "claude-haiku-4-5-20251001",
			Input: responses.ResponseNewParamsInputUnion{
				OfString: openai.String("What's the weather like in Boston today?"),
			},
			Tools: tools,
		},
	)

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

	called := false
	for _, item := range resp.Output {
		if item.Type == "function_call" {
			called = true
			fmt.Println("🔧 Function called:", item.Name)
			fmt.Println("📥 Arguments JSON:", item.Arguments)
		}
	}

	if !called {
		fmt.Println("💬 Assistant reply:", resp.OutputText())
	}
}

```

{% endtab %}

{% tab title="Python" %}

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

import json
from openai import OpenAI

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

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

    tools = [{
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "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.responses.create(
        model="claude-haiku-4-5-20251001",
        input="What's the weather like in Boston today?",
        tools=tools,
        tool_choice="auto"
    )

    called = False
    for item in response.output:
        if item.type == "function_call":
            called = True
            print(f"🔧 Function called: {item.name}")
            print(f"📥 Arguments JSON: {item.arguments}")

            args = json.loads(item.arguments)
            print(f"📦 Parsed args: {args}")

    if not called:
        print(f"💬 Assistant reply: {response.output_text}")

if __name__ == "__main__":
    main()

```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import OpenAI from "openai";

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

const tools = [
  {
    type: "function",
    name: "get_current_weather",
    description: "Get the current weather in a given location",
    parameters: {
      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.responses.create({
  model: "claude-haiku-4-5-20251001",
  input: "What's the weather like in Boston today?",
  tools,
  tool_choice: "auto",
});

let called = false;
for (const item of response.output) {
  if (item.type === "function_call") {
    called = true;
    console.log("🔧 Function called:", item.name);
    console.log("📥 Arguments JSON:", item.arguments);

    const args = JSON.parse(item.arguments);
    console.log("📦 Parsed args:", args);
  }
}

if (!called) {
  console.log("💬 Assistant reply:", response.output_text);
}
```

{% endtab %}

{% tab title="Java" %}

```java
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseFunctionToolCall;
import java.util.List;
import java.util.Map;

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

        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl("https://gateway.theturbo.ai/v1")
                .build();

        FunctionTool weatherTool = FunctionTool.builder()
                .name("get_current_weather")
                .description("Get the current weather in a given location")
                .parameters(FunctionTool.Parameters.builder()
                        .putAdditionalProperty("type", JsonValue.from("object"))
                        .putAdditionalProperty("properties", JsonValue.from(Map.of(
                                "location", Map.of(
                                        "type", "string",
                                        "description", "The city and state, e.g. San Francisco, CA"),
                                "unit", Map.of(
                                        "type", "string",
                                        "enum", List.of("celsius", "fahrenheit")))))
                        .putAdditionalProperty("required", JsonValue.from(List.of("location")))
                        .build())
                .strict(false)
                .build();

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

        Response response = client.responses().create(params);

        boolean[] called = {false};
        response.output().forEach(item -> {
            if (item.isFunctionCall()) {
                called[0] = true;
                ResponseFunctionToolCall functionCall = item.asFunctionCall();
                System.out.println("🔧 Function called: " + functionCall.name());
                System.out.println("📥 Arguments JSON: " + functionCall.arguments());
            }
        });

        if (!called[0]) {
            System.out.print("💬 Assistant reply: ");
            response.output().stream()
                    .flatMap(item -> item.message().stream())
                    .flatMap(message -> message.content().stream())
                    .flatMap(content -> content.outputText().stream())
                    .forEach(outputText -> System.out.println(outputText.text()));
        }
    }
}
```

{% endtab %}
{% endtabs %}

## 5. 响应示例

```json
{
	"id": "resp_1234567890",
	"object": "response",
	"created_at": 1699999999,
	"status": "completed",
	"model": "claude-haiku-4-5-20251001",
	"output": [
		{
			"id": "msg_1234567890",
			"type": "message",
			"role": "assistant",
			"content": [
				{
					"type": "output_text",
					"text": "量子力学是研究微观世界的物理学分支……"
				}
			]
		}
	],
	"usage": {
		"input_tokens": 10,
		"output_tokens": 30,
		"total_tokens": 40
	}
}
```
