> ## 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)` は、**OpenAI 互換**のチャット補完 endpoint である [AI Gateway](/en/api-reference/ai-gateway) を呼び出します。`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` はボディとしてそのまま送信される dict なので、その他の OpenAI パラメーターもそのまま渡せます。型は `squarecloud.types.ChatRequest` です。

| フィールド                   | 説明                                                                                                 |
| ----------------------- | -------------------------------------------------------------------------------------------------- |
| `model`                 | `cubic`。互換性のために受け付けているだけで、他のモデルはありません                                                              |
| `messages`              | `{ role, content?, tool_call_id?, tool_calls? }`。`role` は `system`、`user`、`assistant`、`tool` のいずれか |
| `tools` / `tool_choice` | OpenAI の function calling                                                                          |
| `max_tokens`            | 回答の最大トークン数                                                                                         |
| `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`](/ja/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`                       | 1 日の予算を使い切った (00:00 UTC にリセット)     |
| 503   | `server_overloaded`                                                                                     | 容量が満杯、または 90 秒の期限を過ぎた: リトライしても安全です |
| 503   | `daily_capacity_reached`                                                                                | プラットフォームの 1 日の容量を使い切った             |

AI のエラーは SDK によって**リトライされることはありません**。リクエストが冪等でない `POST` であるためです。プランの制限については [AI Gateway リファレンス](/en/api-reference/ai-gateway)を参照してください。
