# Felo Search API

query 분석, Web 리소스, citation을 포함한 AI 대화형 검색을 통합하세요.

[오류, 속도 제한 및 재시도](https://openapi.felo.ai/ko/docs/guides/errors-and-limits.md)

이 페이지는 기존 `/v2` Felo API를 문서화하며, **Felo 계정 자격과 Pro 크레딧 규칙**을 사용합니다. 크레딧 차감 여부는 [작업](https://openapi.felo.ai/ko/docs/faq/billing-and-credits.md#v2)에 따라 달라집니다. 플랫폼 잔액으로 호출하려면 지원되는 [Felo OpenAPI 엔드포인트](https://openapi.felo.ai/ko/docs/api-reference/openapi/overview.md)를 선택하세요. 요청 및 응답 형식은 다를 수 있습니다.


Chat API를 사용하면 애플리케이션에 AI 기반 대화형 검색을 통합할 수 있습니다. 자연어 쿼리를 보내면 실시간 웹 검색 결과를 바탕으로 생성된 지능형 답변을 받을 수 있습니다.

## AI 에이전트와 함께 사용

에이전트가 Search와 기타 모든 사용 가능한 Felo Skill을 사용하도록 하려면 완전한 `felo-ai` 패키지를 설치하세요. 설치 프로그램은 `SKILL.md`가 포함된 모든 패키지 디렉터리를 동적으로 탐지하므로, 고정된 일부가 아니라 향후 추가되는 Skill까지 포함합니다. 에이전트의 기본 디렉터리에 설치하세요: Codex는 `~/.codex/skills`, Claude Code는 `~/.claude/skills`, OpenClaw는 `~/.agents/skills`, Hermes Agent는 `~/.hermes/skills`를 사용합니다. 각 플랫폼별 안전한 링크, API 키, 검증 단계는 [수동 AI 에이전트 설정 가이드](https://openapi.felo.ai/ko/docs/felo-skills.md)를 참조하세요.


## 개요

Chat API는 다음 작업을 수행합니다:
1. 쿼리를 분석하고 최적화합니다
2. 웹에서 관련 정보를 검색합니다
3. 검색 결과를 순위화하고 필터링합니다
4. 소스를 바탕으로 포괄적인 AI 답변을 생성합니다
5. 출처 인용과 함께 답변을 반환합니다

**사용 사례:**
- 대화형 AI 비서
- 연구 및 정보 검색 도구
- 웹 지식을 사용하는 고객 지원 챗봇
- 교육용 애플리케이션
- 콘텐츠 제작 도구

## 인증

Chat API의 모든 요청에는 API Key를 사용한 인증이 필요합니다. API Key를 `Authorization` 헤더에 포함하세요:

```
Authorization: Bearer YOUR_API_KEY
```

API Key를 얻고 사용하는 방법은 [인증 가이드](https://openapi.felo.ai/ko/docs/authentication.md)를 참조하세요.

## 엔드포인트

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

## 요청

### 헤더

| 헤더 | 필수 | 설명 |
|--------|----------|-------------|
| `Authorization` | 예 | `Bearer YOUR_API_KEY` 형식의 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 | 소스 URL |
| `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 (Browser/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 구독(기업 구독 포함)이 있는 사용자는 API Key 및 OAuth 인증 모두에서 모든 `/v2/chat` 속도 제한이 면제됩니다. 면제 응답에는 `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/ko/docs/getting-started.md)를 검토하세요
- [인증 문서](https://openapi.felo.ai/ko/docs/authentication.md)를 확인하세요
- 요청 ID와 함께 support@felo.ai로 지원에 문의하세요

## 변경 내역

### v2.0.0 (현재)
- Chat API 최초 출시
- 자연어 쿼리 지원
- 실시간 웹 검색 통합
- 소스 인용이 포함된 AI 생성 답변
