# AI 智慧平台

## 取得 API 金鑰

請從「 [AI API串接](https://console.littlepig.cloud/config_manage) 」標籤中進入「AI 設定管理」頁面，點選「開通服務」按鈕進入設定頁，並依指示完成確認流程。

<figure><img src="/files/YlJpc5wCxjRnjG3py12X" alt=""><figcaption></figcaption></figure>

&#x20;要取得 API 金鑰，請點選「查看」。系統可能會要求您輸入帳戶密碼以進行驗證。

## 設定 AI API

**API 網域：** `https://sgai.littlepig.cloud`\
**端點（Endpoint）：** `/anthropic/v1/messages`\
**通訊協定：**&#x48;TTPS\
**請求方式：**&#x50;OST\
**請求內容格式：**&#x53;erialized JSON format

### 請求結構

#### 必要的標頭 Headers

| 標頭名稱           | 類型         | 說明                       |
| -------------- | ---------- | ------------------------ |
| `x-api-key`    | 字串（string） | 從後台管理系統取得的驗證金鑰。          |
| `Content-Type` | 字串（string） | 一定要是 `application/json`. |

#### 請求資料定義

<table><thead><tr><th width="187">參數</th><th>類型</th><th>是否必填</th><th>說明</th></tr></thead><tbody><tr><td><code>model</code></td><td>字串（string）</td><td><strong>是</strong></td><td>使用的 Claude 模型。</td></tr><tr><td><code>max_tokens</code></td><td>整數（integer）</td><td><strong>是</strong></td><td>生成的最大 token 數。</td></tr><tr><td><code>messages</code></td><td>物件陣列（object[]）</td><td><strong>是</strong></td><td>對話歷史紀錄（請參見「<strong>訊息格式</strong>」說明）。</td></tr><tr><td><code>stream</code></td><td>布林值（boolean）</td><td>否</td><td>以 Server-Sent Events（SSE）方式串流回應。</td></tr><tr><td><code>system</code></td><td>字串（string）</td><td>否</td><td>系統級提示詞System-level prompt.）</td></tr><tr><td><code>temperature</code></td><td>數值（number）</td><td>否</td><td>0.0 至 1.0；數值越低越具決定性，數值越高越具創造力。</td></tr><tr><td><code>top_p</code></td><td>數值（number）</td><td>否</td><td>Nucleus sampling 比例。請根據需求調整 <code>temperature</code> <strong>或</strong> <code>top_p</code>.</td></tr><tr><td><code>tools</code></td><td>物件陣列（object[]）</td><td>否</td><td>模型可能呼叫的外部工具定義。</td></tr></tbody></table>

***

### 單一使用情境 — 基本對話功能

```bash
curl https://sgai.littlepig.cloud/anthropic/v1/messages   -H "x-api-key: $API_KEY"   -H "anthropic-version: 2023-06-01"   -H "Content-Type: application/json"   -d '{
    "model": "claude_37_sonnet",
    "max_tokens": 1024,
    "messages": [
      { "role": "user", "content": "Hello, world" }
    ]
  }'
```

***

### 訊息格式

#### 純文字格式（簡化版）

```json
{ "role": "user", "content": "Hello, Claude" }
```

#### 明確內容區塊（Explicit Content Blocks）

每則輸入訊息的內容可以是單一字串，或是一組具有特定類型的內容區塊陣列。\
若直接使用字串作為內容，則等同於只含有一個類型為 `"text"` 的內容區塊。\
以下兩種輸入訊息格式是等效的：

```json
 {"role": "user", "content": "Hello, Claude"}
```

```json
{ "role": "user", "content": [ { "type": "text", "text": "Hello, Claude" } ] }
```

#### 多輪對話（Multiple Conversational Turns）

```json
[
  { "role": "user", "content": "Hello there." },
  { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" },
  { "role": "user", "content": "Can you explain LLMs in plain English?" }
]
```

#### 部分回應填充（Partially‑filled Response）

```json
[
  { "role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" },
  { "role": "assistant", "content": "The best answer is (" }
]
```

#### 圖片 + 文字

```json
{
  "role": "user",
  "content": [
    {
      "type": "image",
      "source": {
        "type": "base64",
        "media_type": "image/jpeg",
        "data": "/9j/4AAQSkZJRg..."
      }
    },
    { "type": "text", "text": "What is in this image?" }
  ]
}
```

支援的圖片格式： `image/jpeg`, `image/png`, `image/gif`, `image/webp`.

***

### 工具定義結構（**Tool Definition Schema）**

若您在 API 請求中包含工具（tools），模型可能會回傳 `tool_use` 類型的內容區塊，表示模型正在使用這些工具。\
接著，您可以依照模型所產生的工具輸入（tool input）來執行對應的工具，並可選擇性地透過 `tool_result` 類型的內容區塊，將執行結果回傳給模型。

| 欄位名稱（Field）    | 類型         | 是否必填  | 說明               |
| -------------- | ---------- | ----- | ---------------- |
| `name`         | 字串（string） | **是** | 工具名稱。            |
| `description`  | 字串（string） | 否     | 工具的用途說明。         |
| `input_schema` | 物件（object） | **是** | 工具輸入的 JSON 結構描述。 |

```json
[
    {
        "name": "get_stock_price",
        "description": "Get the current stock price for a given ticker symbol.",
        "input_schema": {
            "type": "object",
            "properties": {
                "ticker": {
                    "type": "string",
                    "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
                }
            },
            "required": [
                "ticker"
            ]
        }
    }
]
```

***

### 回應資料定義（Response Data Definition）

| 欄位名稱                  | 說明                       |
| --------------------- | ------------------------ |
| `content`             | Claude 所產生的內容區塊。         |
| `id`                  | 訊息 ID。                   |
| `model`               | 回應內容所使用的模型名稱。            |
| `role`                | 角色，一律為 `assistant`.      |
| `stop_reason`         | 為何停止生成內容（例如： `end_turn`) |
| `usage.input_tokens`  | 請求中所使用的 token 數量。        |
| `usage.output_tokens` | 回應中所產生的 token 數量。        |

#### 範例

```json
{
    "id": "msg_bdrk_01FTuLJMy9aYU5TQhK14rMsE",
    "type": "message",
    "role": "assistant",
    "model": "claude-3-7-sonnet-20250219",
    "content": [
        {
            "type": "text",
            "text": "Hello! How can I assist you today? Feel free to ask me any questions or let me know what you'd like to talk about."
        }
    ],
    "stop_reason": "end_turn",
    "stop_sequence": null,
    "usage": {
        "input_tokens": 10,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "output_tokens": 31
    }
}
```

***

### 串流事件 (`stream=true`)

| 事件                    | 載荷內容              |
| --------------------- | ----------------- |
| `content_block_delta` | 部分 token 或工具輸入資料。 |
| `error`               | 錯誤細節。             |

範例：

```
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ello frien"}}

event: error
data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}
```

工具呼叫串流：

```
event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{"location":"San Fra"}"}}
```

***

### 工具呼叫操作說明

```bash
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-3-7-sonnet-20250219",
    "max_tokens": 1024,
    "tools": [
      {
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            }
          },
          "required": ["location"]
        }
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "What is the weather like in San Francisco?"
      }
    ]
  }'
```

***

### 延伸閱讀

<https://docs.anthropic.com/en/api/messages>

### 價格

{% hint style="info" %}
模型價格可能會有所變動，請前往設定 [管理頁面](https://console.littlepig.cloud/config_manage) 查看最新價格資訊。
{% endhint %}

| Model              | Price / 1 000 input tokens | Price / 1 000 output tokens |
| ------------------ | -------------------------- | --------------------------- |
| claude\_3\_haiku   | $0.00025                   | $0.00125                    |
| claude\_3\_sonnet  | $0.003                     | $0.015                      |
| claude\_3\_opus    | $0.015                     | $0.075                      |
| claude\_35\_haiku  | $0.0008                    | $0.004                      |
| claude\_35\_sonnet | $0.003                     | $0.015                      |
| claude\_37\_sonnet | $0.003                     | $0.015                      |

{% hint style="warning" %}
若要停用 API 存取，請在設定 [管理頁面](https://vps.littlepig.tech/config_manage) 中點選「關閉服務」按鈕。
{% endhint %}


---

# 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.littlepig.cloud/zh-tw/docs/ai-platform.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.
