> ## 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

> 通过 squarecloud-api 的 client.ai.chat() 调用 Square Cloud AI Gateway：兼容 OpenAI 的聊天补全，不支持流式传输。

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

```python theme={"system"}
completion = client.ai.chat({
    "model": "cubic",
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is Square Cloud?"},
    ],
    "max_tokens": 512,
})

print(completion["choices"][0]["message"]["content"])
print(completion["usage"]["total_tokens"])
```

## 请求

`request` 是一个字典，会原样作为请求体发送，因此任何其他 OpenAI 参数都会被透传。它的类型为 `squarecloud.types.ChatRequest`。

| 字段                      | 说明                                                                                             |
| ----------------------- | ---------------------------------------------------------------------------------------------- |
| `model`                 | `cubic`。为兼容性而接受：没有其他模型                                                                         |
| `messages`              | `{ role, content?, tool_call_id?, tool_calls? }`，`role` 为 `system`、`user`、`assistant` 或 `tool` |
| `tools` / `tool_choice` | OpenAI 函数调用                                                                                    |
| `max_tokens`            | 回答的最大 token 数                                                                                  |
| `temperature`           | 采样温度                                                                                           |

响应采用 OpenAI 的格式：`id`、`object`、`created`、`model`、`choices`（`index`、`message`、`finish_reason`）和 `usage`。

## 不支持流式传输

`ai.chat()` 不进行流式传输：它返回完整的补全结果。`"stream": True` 会返回 400 `stream_not_supported`。

## 超时

网关为每个请求总共提供 **90 秒**，之后返回 503 `server_overloaded`。SDK 至少等待 120 秒才会超时，因此你会收到网关的响应。

## 错误

AI 错误使用 OpenAI 格式，因此其代码为**小写**。它们仍然会抛出 [`SquareCloudAPIError`](/zh/sdks/py/errors)，`code` 被设为 OpenAI 代码（没有代码时则为其 `type`）：

```python theme={"system"}
from squarecloud import SquareCloudAPIError

try:
    client.ai.chat({"messages": [{"role": "user", "content": "Hi"}]})
except SquareCloudAPIError as error:
    if error.code == "server_overloaded":
        ...  # safe to retry yourself
    else:
        raise
```

| 状态  | 代码                                                                                                      | 触发条件                   |
| --- | ------------------------------------------------------------------------------------------------------- | ---------------------- |
| 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)。
