# Felo Search API

接入帶有查詢分析、網頁資源和引用的 AI 對話搜尋。

[錯誤、限流與重試](https://openapi.felo.ai/zh-TW/docs/guides/errors-and-limits.md)

本頁說明既有的 `/v2` Felo APIs，使用 **Felo 帳戶權益與 Pro 點數規則**。是否扣除點數取決於 [操作](https://openapi.felo.ai/zh-TW/docs/faq/billing-and-credits.md#依-v2-能力區分的點數規則)。若要使用平台餘額呼叫，請選擇支援的 [Felo OpenAPI 端點](https://openapi.felo.ai/zh-TW/docs/api-reference/openapi/overview.md)；請求與回應格式可能不同。


Chat API 可讓你將 AI 驅動的對話式搜尋整合到你的應用程式中。送出自然語言查詢，並接收由即時網頁搜尋結果產生的智慧答案。

## 與 AI 代理人一起使用

當你希望 Agent 使用 Search 與所有其他可用的 Felo Skill 時，請安裝完整的 `felo-ai` 套件。安裝程式會動態探索每個包含 `SKILL.md` 的套件目錄，因此會納入未來的 Skills，而不是固定子集。請將它們安裝到你的 Agent 原生目錄：Codex 使用 `~/.codex/skills`，Claude Code 使用 `~/.claude/skills`，OpenClaw 使用 `~/.agents/skills`，而 Hermes Agent 使用 `~/.hermes/skills`。請參閱 [手動 AI Agent 設定指南](https://openapi.felo.ai/zh-TW/docs/felo-skills.md)，取得各平台的安全連結、API 金鑰與驗證步驟。


## 概覽

Chat API 會執行下列操作：
1. 分析並最佳化你的查詢
2. 在網頁上搜尋相關資訊
3. 對搜尋結果進行排序與篩選
4. 根據來源產生完整的 AI 答案
5. 回傳答案以及來源引用

**使用情境：**
- 對話式 AI 助理
- 研究與資訊擷取工具
- 具備網頁知識的客服聊天機器人
- 教育應用程式
- 內容創作工具

## 驗證

所有對 Chat API 的請求都需要使用 API Key 進行驗證。請在 `Authorization` 標頭中加入你的 API Key：

```
Authorization: Bearer YOUR_API_KEY
```

請參閱 [驗證指南](https://openapi.felo.ai/zh-TW/docs/authentication.md) 以取得關於如何取得與使用 API Key 的詳細資訊。

## 端點

```
POST https://openapi.felo.ai/v2/chat
```

## 請求

### 標頭

| 標頭 | 必填 | 說明 |
|--------|----------|-------------|
| `Authorization` | 是 | 你的 API Key，格式為：`Bearer YOUR_API_KEY` |
| `Content-Type` | 是 | 必須為 `application/json` |

### 主體參數

| 參數 | 類型 | 必填 | 說明 | 限制 |
|-----------|------|----------|-------------|-------------|
| `query` | string | 是 | 使用者的問題或搜尋查詢 | 1-2000 個字元 |
| `accept_language` | string | 否 | 偏好的答案語言，例如 `en`、`ja`、`zh-TW` | 語言標記，最多 64 個字元 |

當你的應用程式需要特定的答案語言時，請設定 `accept_language`。服務會在傳送給答案生成器的查詢中加入明確的語言指示。若未提供，上游服務會自行選擇語言。沒有固定的預設答案語言。英文查詢也可能收到中文答案。例如：`{"query":"What is AI?","accept_language":"en"}`。此偏好只會套用到生成的答案；來源標題與摘錄仍保留原始語言。

### 範例請求

```json
{
  "query": "What are the latest developments in quantum computing?"
}
```

## 回應

### 成功回應（200 OK）

當請求成功時，API 會回傳下列結構的 JSON 回應：

```json
{
  "status": 200,
  "code": "OK",
  "request_id": "req_example",
  "message": null,
  "data": {
    "id": "HabCj883yHLSXc8mWqu4Eq",
    "message_id": "18ea8517-5559-4f48-a355-1f8a79e73b71",
    "answer": "Recent developments in quantum computing include...",
    "query_analysis": {
      "queries": [
        "quantum computing latest developments 2025",
        "quantum computing breakthroughs"
      ]
    },
    "resources": [
      {
        "link": "https://example.com/quantum-news",
        "title": "Latest Quantum Computing Breakthroughs",
        "snippet": "Scientists have achieved a major milestone..."
      },
      {
        "link": "https://example.com/quantum-research",
        "title": "Quantum Computing Research 2025",
        "snippet": "New quantum algorithms show promise..."
      }
    ]
  }
}
```

### 回應欄位

| 欄位 | 類型 | 說明 |
|-------|------|-------------|
| `status` | integer | 數字型 HTTP 風格狀態，成功時為 `200` |
| `code` | string | 成功時為 `OK`；失敗時為可機器讀取的錯誤代碼 |
| `request_id` | string | 供支援與追蹤使用的請求識別碼 |
| `message` | string \| null | 額外訊息（成功請求時為 null） |
| `data` | object | 成功請求的回應資料 |
| `data.id` | string | 此聊天工作階段的唯一識別碼 |
| `data.message_id` | string | 此特定訊息的唯一識別碼 |
| `data.answer` | string | 針對查詢所產生的 AI 答案 |
| `data.query_analysis` | object | 使用者查詢的分析 |
| `data.query_analysis.queries` | string[] | 根據使用者輸入最佳化而來的搜尋查詢 |
| `data.resources` | array | 用於生成答案的網頁來源清單 |
| `data.resources[].link` | string | 來源網址 |
| `data.resources[].title` | string | 來源頁面標題 |
| `data.resources[].snippet` | string | 來源中的相關摘錄 |

### 錯誤回應

發生錯誤時，API 會回傳包含錯誤詳細資訊的 JSON 回應：

```json
{
  "status": 401,
  "code": "INVALID_API_KEY",
  "message": "The provided API Key is invalid or has been revoked",
  "request_id": "req_abc123xyz789"
}
```

### 錯誤回應欄位

| 欄位 | 類型 | 說明 |
|-------|------|-------------|
| `status` | integer | 數字型錯誤狀態，例如無效 API Key 時為 `401` |
| `code` | string | 識別錯誤類型的錯誤代碼 |
| `message` | string | 人類可讀的錯誤描述 |
| `request_id` | string | 此請求的唯一識別碼（有助於支援） |

## 錯誤代碼

| 代碼 | HTTP 狀態 | 說明 | 解決方式 |
|------|-------------|-------------|----------|
| `INVALID_API_KEY` | 401 | API Key 無效、格式錯誤或已撤銷 | 確認你的 API Key 正確且有效 |
| `MISSING_AUTHORIZATION` | 401 | 缺少 Authorization 標頭 | 在請求中加入 Authorization 標頭 |
| `MALFORMED_AUTHORIZATION` | 401 | Authorization 標頭格式不正確 | 使用格式：`Authorization: Bearer YOUR_API_KEY` |
| `MISSING_PARAMETER` | 400 | 缺少必要參數 | 確保請求主體中包含 `query` 參數 |
| `INVALID_PARAMETER` | 400 | 參數值無效 | 檢查 `query` 是否為非空字串（1-2000 個字元） |
| `QUERY_TOO_LONG` | 400 | 查詢超過最大長度 | 將查詢縮短至 2000 個字元以內 |
| `RATE_LIMITED` | 429 | 短時間內請求過多 | 降低請求頻率或聯絡支援 |
| `CHAT_FAILED` | 502 | 內部服務錯誤 | 重試請求；若問題持續，請聯絡支援 |
| `SERVICE_UNAVAILABLE` | 503 | 服務暫時無法使用 | 等待後重試；請查看狀態頁面以取得更新 |

## 範例

### cURL

```bash
curl -X POST https://openapi.felo.ai/v2/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What are the benefits of renewable energy?"
  }'
```

**回應：**

```json
{
  "status": 200,
  "code": "OK",
  "request_id": "req_example",
  "message": null,
  "data": {
    "id": "HabCj883yHLSXc8mWqu4Eq",
    "message_id": "18ea8517-5559-4f48-a355-1f8a79e73b71",
    "answer": "Renewable energy offers numerous benefits including reduced greenhouse gas emissions, decreased air pollution, energy independence, job creation, and long-term cost savings. Solar, wind, and hydroelectric power are sustainable alternatives to fossil fuels that help combat climate change while providing reliable electricity.",
    "query_analysis": {
      "queries": [
        "renewable energy benefits",
        "advantages of renewable energy sources"
      ]
    },
    "resources": [
      {
        "link": "https://example.com/renewable-benefits",
        "title": "Top Benefits of Renewable Energy",
        "snippet": "Renewable energy sources provide clean, sustainable power..."
      }
    ]
  }
}
```

### Python

```python
import requests
import os

# Get API key from environment variable
api_key = os.environ.get('FELO_API_KEY')

url = 'https://openapi.felo.ai/v2/chat'
headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}
data = {
    'query': 'What are the benefits of renewable energy?'
}

try:
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()  # Raise exception for HTTP errors

    result = response.json()

    if result['status'] == 200 and result['code'] == 'OK':
        print('Answer:', result['data']['answer'])
        print('\nSources:')
        for resource in result['data']['resources']:
            print(f"- {resource['title']}: {resource['link']}")
    else:
        print(f"Error: {result['code']} - {result['message']}")

except requests.exceptions.RequestException as e:
    print(f'Request failed: {e}')
```

### JavaScript（Node.js）

```javascript
const fetch = require('node-fetch');

const apiKey = process.env.FELO_API_KEY;
const url = 'https://openapi.felo.ai/v2/chat';

const headers = {
  'Authorization': `Bearer ${apiKey}`,
  'Content-Type': 'application/json'
};

const body = JSON.stringify({
  query: 'What are the benefits of renewable energy?'
});

fetch(url, { method: 'POST', headers, body })
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    if (data.status === 200 && data.code === 'OK') {
      console.log('Answer:', data.data.answer);
      console.log('\nSources:');
      data.data.resources.forEach(resource => {
        console.log(`- ${resource.title}: ${resource.link}`);
      });
    } else {
      console.error(`Error: ${data.code} - ${data.message}`);
    }
  })
  .catch(error => {
    console.error('Request failed:', error);
  });
```

### JavaScript（瀏覽器 / Fetch API）

```javascript
const apiKey = 'YOUR_API_KEY'; // In production, get this from your backend

fetch('https://openapi.felo.ai/v2/chat', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    query: 'What are the benefits of renewable energy?'
  })
})
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    if (data.status === 200 && data.code === 'OK') {
      console.log('Answer:', data.data.answer);

      // Display sources
      const sourcesList = data.data.resources.map(resource =>
        `<li><a href="${resource.link}">${resource.title}</a></li>`
      ).join('');

      document.getElementById('answer').innerHTML = data.data.answer;
      document.getElementById('sources').innerHTML = sourcesList;
    } else {
      console.error(`Error: ${data.code} - ${data.message}`);
    }
  })
  .catch(error => {
    console.error('Request failed:', error);
  });
```

### Go

```go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

type ChatRequest struct {
    Query string `json:"query"`
}

type ChatResponse struct {
    Status  int `json:"status"`
    Message string `json:"message,omitempty"`
    Data    struct {
        ID            string `json:"id"`
        MessageID     string `json:"message_id"`
        Answer        string `json:"answer"`
        QueryAnalysis struct {
            Queries []string `json:"queries"`
        } `json:"query_analysis"`
        Resources []struct {
            Link    string `json:"link"`
            Title   string `json:"title"`
            Snippet string `json:"snippet"`
        } `json:"resources"`
    } `json:"data,omitempty"`
    Code      string `json:"code,omitempty"`
    RequestID string `json:"request_id,omitempty"`
}

func main() {
    apiKey := os.Getenv("FELO_API_KEY")
    url := "https://openapi.felo.ai/v2/chat"

    requestBody := ChatRequest{
        Query: "What are the benefits of renewable energy?",
    }

    jsonData, err := json.Marshal(requestBody)
    if err != nil {
        fmt.Printf("Error marshaling request: %v\n", err)
        return
    }

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        fmt.Printf("Error creating request: %v\n", err)
        return
    }

    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error making request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response: %v\n", err)
        return
    }

    var chatResp ChatResponse
    err = json.Unmarshal(body, &chatResp)
    if err != nil {
        fmt.Printf("Error unmarshaling response: %v\n", err)
        return
    }

    if chatResp.Status == 200 && chatResp.Code == "OK" {
        fmt.Println("Answer:", chatResp.Data.Answer)
        fmt.Println("\nSources:")
        for _, resource := range chatResp.Data.Resources {
            fmt.Printf("- %s: %s\n", resource.Title, resource.Link)
        }
    } else {
        fmt.Printf("Error: %s - %s\n", chatResp.Code, chatResp.Message)
    }
}
```

## 速率限制

具有效的付費 Felo 訂閱（包含企業訂閱）的使用者，對所有 `/v2/chat` 速率限制皆享有豁免，無論是 API Key 或 OAuth 驗證皆然。豁免回應不會包含 `X-RateLimit-*` 標頭。

沒有付費訂閱的使用者會受到三個維度的速率限制。若無法驗證訂閱狀態，這些限制仍會套用：

- **每個 API Key** — 限制在 1 分鐘視窗內使用單一 API Key 發出的請求數。
- **每位使用者（每分鐘）** — 限制在 1 分鐘視窗內，某位使用者擁有的所有 API Key 的請求總數。
- **每位使用者（每小時）** — 限制在 1 小時視窗內，某位使用者擁有的所有 API Key 的請求總數。

任一維度超過限制都會觸發 `429 Too Many Requests` 回應。

> 精確的數值限制可能會隨時間變動。**請一律從下方回應標頭讀取**，不要從文件快照推斷。

**回應標頭（受速率限制的回應，包括 429）：**

| 標頭 | 意義 |
|---|---|
| `X-RateLimit-Limit` | 目前生效中最嚴格維度的限制 |
| `X-RateLimit-Remaining` | 三個維度中的最低剩餘配額 |
| `X-RateLimit-Reset` | 目前視窗重設的 Unix 時間戳（秒） |

**在 429 時，另外還有：**

| 標頭 | 意義 |
|---|---|
| `Retry-After` | 建議的重試延遲（秒） |

**429 範例主體**（`message` 會反映請求當下已設定的目前限制）：

```json
{
  "status": 429,
  "code": "RATE_LIMITED",
  "message": "Too many requests. Limit: <N>/min per API key, <M>/min per user, <H>/hour per user.",
  "request_id": "..."
}
```

**建議的用戶端行為：**

1. 在成功回應中，若有提供 `X-RateLimit-Remaining`，請讀取它；當它接近 `0` 時，提前退避。
2. 在 429 時，請至少等待 `Retry-After` 指定的秒數（或直到 `X-RateLimit-Reset`）再重試。
3. 不要硬編碼限制值——它們可能在不變更 API 合約的情況下調整。

如果你需要更高的速率限制，請聯絡 support@felo.ai。

## 最佳實務

### 1. 優雅處理錯誤

請務必檢查回應狀態並適當處理錯誤：

```python
if result['status'] == 200 and result['code'] == 'OK':
    # Process successful response
    answer = result['data']['answer']
else:
    # Handle error
    error_code = result['code']
    error_message = result['message']
    # Log error, show user-friendly message, etc.
```

### 2. 實作重試邏輯

對於暫時性錯誤（5xx 狀態碼），請實作指數退避：

```python
import time

max_retries = 3
retry_delay = 1  # seconds

for attempt in range(max_retries):
    response = requests.post(url, headers=headers, json=data)

    if response.status_code < 500:
        break  # Success or client error, don't retry

    if attempt < max_retries - 1:
        time.sleep(retry_delay * (2 ** attempt))  # Exponential backoff
```

### 3. 快取回應

對於相同的查詢，建議快取回應，以減少 API 呼叫並提升回應速度。

### 4. 驗證輸入

在送出至 API 前先驗證使用者輸入：
- 確認查詢不為空
- 檢查查詢長度（1-2000 個字元）
- 清理輸入以防止注入攻擊

### 5. 監控用量

追蹤你的 API 用量，以維持在速率限制內並優化成本：
- 記錄請求數與回應時間
- 監控錯誤率
- 針對異常模式設定警示

## 支援

需要 Chat API 的協助嗎？

- 閱讀 [快速入門指南](https://openapi.felo.ai/zh-TW/docs/getting-started.md)
- 檢查 [驗證文件](https://openapi.felo.ai/zh-TW/docs/authentication.md)
- 使用你的 request ID 聯絡 support@felo.ai

## 變更紀錄

### v2.0.0（目前）
- Chat API 初始版本
- 支援自然語言查詢
- 即時網頁搜尋整合
- 帶有來源引用的 AI 生成答案
