> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# AI

> 通过 Go SDK 的 c.AI.Chat 调用 Square Cloud AI Gateway：兼容 OpenAI 的聊天补全，不支持流式传输。

`c.AI.Chat(ctx, request)` 调用 [AI Gateway](/en/api-reference/ai-gateway)，这是一个**兼容 OpenAI** 的聊天补全 endpoint。它需要 `ai:chat` 作用域以及 Standard 或更高级别的套餐。

```go theme={"system"}
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/squarecloudofc/sdk-api-go/v3"
)

func main() {
	ctx := context.Background()
	c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

	completion, err := c.AI.Chat(ctx, squarecloud.ChatRequest{
		Model: "cubic",
		Messages: []squarecloud.ChatMessage{
			{Role: "system", Content: "You are a helpful assistant."},
			{Role: "user", Content: "What is Square Cloud?"},
		},
		MaxTokens: 512,
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(completion.Choices[0].Message.Content)
	fmt.Println(completion.Usage.TotalTokens)
}
```

## 请求

`squarecloud.ChatRequest` 的字段及其 JSON 名称：

| 字段                                              | 说明                                                                                                                                                                 |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Model`（`model`）                                | `cubic`。为兼容性而接受：没有其他模型。`""` 不会被发送                                                                                                                                  |
| `Messages`（`messages`）                          | `[]ChatMessage`，包含 `Role`、`Content`、`ToolCallID`（`tool_call_id`）和 `ToolCalls`（`tool_calls`）。`Role` 为 `system`、`user`、`assistant` 或 `tool`。`Content` 始终会被发送，包括 `""` |
| `Tools` / `ToolChoice`（`tools` / `tool_choice`） | OpenAI 函数调用：`Tools` 是 `[]json.RawMessage`，`ToolChoice` 可以是任何可 JSON 编码的值                                                                                            |
| `MaxTokens`（`max_tokens`）                       | 回答的最大 token 数。`0` 不会被发送                                                                                                                                            |
| `Temperature`（`temperature`）                    | 采样温度，类型为 `*float64`。`nil` 不会被发送                                                                                                                                    |

响应是一个采用 OpenAI 结构的 `ChatCompletion`：`ID`、`Object`、`Created`、`Model`、`Choices`（`Index`、`Message`、`FinishReason`）和 `Usage`（`PromptTokens`、`CompletionTokens`、`TotalTokens`）。

## 不支持流式传输

`AI.Chat` 不进行流式传输：它返回完整的补全结果。`ChatRequest` 没有 `stream` 字段；对于 `stream: true`，API 会返回 400 `stream_not_supported`。

## 超时

网关为每个请求总共提供 **90 秒**，之后返回 503 `server_overloaded`。在 `ctx` 没有截止时间的情况下，SDK 至少等待 2 分钟才会超时，因此你会收到网关的响应。

## 错误

AI 错误使用 OpenAI 格式，因此其代码为**小写**。它们仍然以 [`*APIError`](/zh/sdks/go/errors) 的形式返回，`Code` 被设为 OpenAI 代码（没有代码时则为其 `type`）：

```go theme={"system"}
_, err := c.AI.Chat(ctx, squarecloud.ChatRequest{
	Messages: []squarecloud.ChatMessage{{Role: "user", Content: "Hi"}},
})

var apiErr *squarecloud.APIError
if errors.As(err, &apiErr) && apiErr.Code == "server_overloaded" {
	// safe to retry yourself
}
```

| 状态  | 代码                                                                                                      | 触发条件                   |
| --- | ------------------------------------------------------------------------------------------------------- | ---------------------- |
| 400 | `stream_not_supported`                                                                                  | 发送了 `stream: true`     |
| 400 | `invalid_messages`, `invalid_tools`, `invalid_tool_choice`, `invalid_temperature`, `invalid_max_tokens` | 某个字段格式错误               |
| 400 | `context_length_exceeded`                                                                               | 对话超出了套餐的上下文窗口          |
| 401 | `access_denied`                                                                                         | 无效的 API 密钥             |
| 403 | `upgrade_required`                                                                                      | 该套餐无权访问 AI Gateway     |
| 429 | `rate_limit_exceeded`, `concurrent_limit_reached`                                                       | 请求过快，或已有请求正在进行中        |
| 429 | `daily_limit_reached`, `daily_request_limit_reached`, `daily_spend_limit_reached`                       | 每日额度已用完（UTC 00:00 重置）  |
| 503 | `server_overloaded`                                                                                     | 容量已满或已超过 90 秒期限：可以安全重试 |
| 503 | `daily_capacity_reached`                                                                                | 平台的每日容量已用完             |

SDK **从不重试** AI 错误：该请求是非幂等的 `POST`。套餐限制请参见 [AI Gateway 参考](/en/api-reference/ai-gateway)。
