# 对话生成（OpenAI协议）

## 1. 概述

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

{% hint style="success" %}
本 API 与 OpenAI 接口格式兼容。
{% endhint %}

**模型列表：**

* `claude-sonnet-4-20250514`
* `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`

## 2. 请求说明

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

  > `https://gateway.theturbo.ai/v1/chat/completions`

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

***

## 3. 请求参数

### 3.1 Header 参数

| 参数名称            | 类型     | 必填 | 说明                                         | 示例值                    |
| --------------- | ------ | -- | ------------------------------------------ | ---------------------- |
| `Content-Type`  | string | 是  | 设置请求头类型，必须为 `application/json`             | `application/json`     |
| `Accept`        | 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。详见[概述](#1-概述)列出的可用版本，如 `claude-haiku-4-5-20251001`。    | `claude-haiku-4-5-20251001`          |
| **messages**      | array   | 是  | 聊天消息列表，格式与 OpenAI 兼容。数组中的每个对象包含 `role`(角色) 与 `content`(内容)。      | `[{"role": "user","content": "你好"}]` |
| role              | string  | 否  | 消息角色，可选值：`system`、`user`、`assistant`。                            | `user`                               |
| content           | string  | 否  | 消息的具体内容。                                                         | `你好，请给我讲个笑话。`                        |
| temperature       | number  | 否  | 采样温度，取值 `0～2`。数值越大，输出越随机；数值越小，输出越集中和确定。                          | `0.7`                                |
| top\_p            | number  | 否  | 另一种调节采样分布的方式，取值 `0～1`。和 `temperature` 通常二选一设置。                   | `0.9`                                |
| stream            | boolean | 否  | 是否开启流式输出。设置为 `true` 时，返回类似 ChatGPT 的流式数据。                        | `false`                              |
| max\_tokens       | number  | 否  | 单次回复可生成的最大 token 数量，受模型上下文长度限制。                                  | `8192`                               |
| reasoning\_effort | string  | 否  | 用来控制模型在推理任务中投入多少“计算精力”。支持`low` `medium` `high` `none`。默认为`none`。 | `none`                               |

***

## 4. 请求示例

### 4.1 聊天对话

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

```http
POST /v1/chat/completions
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"messages": [
		{
			"role": "user",
			"content": "你好，给我科普一下量子力学吧"
		}
	]
}
```

{% endtab %}

{% tab title="Shell" %}

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

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"

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

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

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

	resp, err := client.Chat.Completions.New(
		context.Background(),
		openai.ChatCompletionNewParams{
			Model: "claude-haiku-4-5-20251001",
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.UserMessage("你好，给我科普一下量子力学吧"),
			},
		},
	)

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

	fmt.Println(resp.Choices[0].Message.Content)
}

```

{% 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.chat.completions.create(
        model="claude-haiku-4-5-20251001",
        messages=[
            {"role": "user", "content": "你好，给我科普一下量子力学吧"}
        ]
    )

    print(response.choices[0].message.content)

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

### 4.2 图片理解

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

<details>

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

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

</details>

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

```http
POST /v1/chat/completions
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"messages": [
		{
			"role": "user",
			"content": [
				{
					"type": "text",
					"text": "这张图片里有什么？"
				},
				{
					"type": "image_url",
					"image_url": {
						"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/chat/completions \
	-H "Content-Type: application/json" \
	-H "Accept: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"messages\": [{
		\"role\": \"user\",
		\"content\": [{
				\"type\": \"text\",
				\"text\": \"这张图片里有什么？\"
			},
			{
				\"type\": \"image_url\",
				\"image_url\": {
					\"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"
)

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.Chat.Completions.New(
		context.Background(),
		openai.ChatCompletionNewParams{
			Model: "claude-haiku-4-5-20251001",
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.UserMessage([]openai.ChatCompletionContentPartUnionParam{
					openai.TextContentPart("这张图片里有什么？"),
					openai.ImageContentPart(openai.ChatCompletionContentPartImageImageURLParam{
						URL: imageURL,
					}),
				}),
			},
		},
	)

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

	fmt.Println(resp.Choices[0].Message.Content)
}

```

{% 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.chat.completions.create(
        model="claude-haiku-4-5-20251001",
        messages=[{
            "role": "user",
            "content": [
                {"type": "text", "text": "这张图片里有什么？"},
                {"type": "image_url", "image_url": {"url": image_url}}
            ]
        }]
    )

    print(response.choices[0].message.content)

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

### 4.3 函数调用

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

```http
POST /v1/chat/completions
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "claude-haiku-4-5-20251001",
	"messages": [{
		"role": "user",
		"content": "What's the weather like in Boston today?"
	}],
	"tools": [{
		"type": "function",
		"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/chat/completions \
	-H "Content-Type: application/json" \
	-H "Accept: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"model\": \"claude-haiku-4-5-20251001\",
	\"messages\": [{
		\"role\": \"user\",
		\"content\": \"What's the weather like in Boston today?\"
	}],
	\"tools\": [{
		\"type\": \"function\",
		\"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"
	"encoding/json"
	"fmt"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
	"github.com/openai/openai-go/packages/param"
	"github.com/openai/openai-go/shared"
)

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

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

	tools := []openai.ChatCompletionToolParam{
		{
			Type: "function",
			Function: shared.FunctionDefinitionParam{
				Name:        "get_current_weather",
				Description: param.NewOpt("Get the current weather in a given location"),
				Parameters: shared.FunctionParameters{
					"type": "object",
					"properties": map[string]interface{}{
						"location": map[string]interface{}{
							"type":        "string",
							"description": "The city and state, e.g. San Francisco, CA",
						},
						"unit": map[string]interface{}{
							"type": "string",
							"enum": []string{"celsius", "fahrenheit"},
						},
					},
					"required": []string{"location"},
				},
			},
		},
	}

	resp, err := client.Chat.Completions.New(
		context.Background(),
		openai.ChatCompletionNewParams{
			Model: "claude-haiku-4-5-20251001",
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.UserMessage("What's the weather like in Boston today?"),
			},
			Tools: tools,
			ToolChoice: openai.ChatCompletionToolChoiceOptionUnionParam{
				OfAuto: param.NewOpt("auto"),
			},
		},
	)

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

	msg := resp.Choices[0].Message

	if msg.ToolCalls != nil && len(msg.ToolCalls) > 0 {
		for _, call := range msg.ToolCalls {
			fmt.Println("🔧 Function called:", call.Function.Name)
			fmt.Println("📥 Arguments JSON:", call.Function.Arguments)

			// 如果你想解析参数
			var args map[string]any
			_ = json.Unmarshal([]byte(call.Function.Arguments), &args)
			fmt.Println("📦 Parsed args:", args)
		}
	} else {
		fmt.Println("💬 Assistant reply:", msg.Content)
	}
}

```

{% 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",
        "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.chat.completions.create(
        model="claude-haiku-4-5-20251001",
        messages=[
            {"role": "user", "content": "What's the weather like in Boston today?"}
        ],
        tools=tools,
        tool_choice="auto"
    )

    msg = response.choices[0].message

    if msg.tool_calls:
        for call in msg.tool_calls:
            print(f"🔧 Function called: {call.function.name}")
            print(f"📥 Arguments JSON: {call.function.arguments}")

            args = json.loads(call.function.arguments)
            print(f"📦 Parsed args: {args}")
    else:
        print(f"💬 Assistant reply: {msg.content}")

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

## 5. 响应示例

```json
{
	"id": "chatcmpl-1234567890",
	"object": "chat.completion",
	"created": 1699999999,
	"model": "claude-haiku-4-5-20251001",
	"choices": [
		{
			"message": {
				"role": "assistant",
				"content": "量子力学是研究微观世界的物理学分支……"
			},
			"finish_reason": "stop"
		}
	],
	"usage": {
		"prompt_tokens": 10,
		"completion_tokens": 30,
		"total_tokens": 40
	}
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.console.zenlayer.com/test/compute/aig/chat-completion/anthropic-claude/anthropic-claude-chat-completion.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
