# API 연동하기

RunYour AI API를 서비스에 연동하는 방법을 안내합니다. OpenAI SDK를 사용하는 방법과 REST API를 직접 호출하는 방법, 두 가지 중 편한 방식을 선택하세요.

***

### OpenAI SDK로 연동하기 (권장)

기존에 OpenAI SDK를 사용 중이라면 **Base URL과 API 키 두 가지만 변경**하면 됩니다.

#### 1단계. SDK 설치하기

{% tabs %}
{% tab title="Python" %}

```bash
pip install openai
```

{% endtab %}

{% tab title="JavaScript" %}

```bash
npm install openai
```

{% endtab %}
{% endtabs %}

#### 2단계. 클라이언트 설정하기

{% tabs %}
{% tab title="Python" %}

```python
from openai import OpenAI

client = OpenAI(
    api_key="runyour-v1-YOUR_API_KEY",   # ← RunYour AI API 키
    base_url="https://api.runyour.ai/v1"  # ← Base URL 변경
)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.RUNYOUR_API_KEY,       // ← 환경 변수로 관리
  baseURL: "https://api.runyour.ai/v1",      // ← Base URL 변경
});
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
기존 OpenAI 코드에서 `api_key`와 `base_url`(또는 `baseURL`) 두 줄만 교체하면 됩니다. 나머지 코드는 그대로 사용할 수 있습니다.
{% endhint %}

#### 3단계. 첫 번째 API 호출 테스트하기

{% tabs %}
{% tab title="Python" %}

```python
completion = client.chat.completions.create(
    model="openai/gpt-5.2",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "안녕하세요!"}
    ],
    temperature=0.7,
    max_tokens=300
)

print(completion.choices[0].message.content)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const completion = await client.chat.completions.create({
  model: "openai/gpt-5.2",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "안녕하세요!" }
  ],
  temperature: 0.7,
  max_tokens: 300,
});

console.log(completion.choices[0]?.message?.content);
```

{% endtab %}
{% endtabs %}

응답에서 AI의 답변은 `choices[0].message.content`에서 확인할 수 있습니다.

***

### REST API로 직접 연동하기

SDK 없이 `curl`, Postman, 또는 자체 HTTP 클라이언트로 직접 호출할 수도 있습니다.

#### 기본 호출 예시

```bash
curl https://api.runyour.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer runyour-v1-YOUR_API_KEY" \
  -d '{
    "model": "openai/gpt-5.2",
    "messages": [
      { "role": "user", "content": "안녕하세요!" }
    ],
    "temperature": 0.7,
    "max_tokens": 300
  }'
```

#### 주요 엔드포인트

<table><thead><tr><th width="124.140625">메서드</th><th>엔드포인트</th><th>설명</th></tr></thead><tbody><tr><td><code>POST</code></td><td><code>https://api.runyour.ai/v1/chat/completions</code></td><td>AI 응답 생성 (주요 엔드포인트)</td></tr><tr><td><code>POST</code></td><td><code>https://api.runyour.ai/v1/responses</code></td><td>OpenAI Responses API 형식 호출</td></tr><tr><td><code>GET</code></td><td><code>https://api.runyour.ai/v1/models</code></td><td>사용 가능한 모델 목록 조회</td></tr></tbody></table>

#### 요청 시 사용할 수 있는 주요 파라미터

{% tabs %}
{% tab title="Chat Completions API" %}

<table><thead><tr><th width="159.578125">파라미터</th><th width="79.96875">필수</th><th>설명</th></tr></thead><tbody><tr><td><code>model</code></td><td>✅</td><td>호출할 모델 ID. <code>provider/model</code> 형식 (예: <code>openai/gpt-5.2</code>)</td></tr><tr><td><code>messages</code></td><td>✅</td><td>대화 메시지 배열. <code>role</code>(<code>system</code>·<code>user</code>·<code>assistant</code>)과 <code>content</code>로 구성</td></tr><tr><td><code>temperature</code></td><td></td><td>응답의 창의성 조절. <code>0</code>(결정적) ~ <code>2</code>(창의적), 기본값 <code>1.0</code></td></tr><tr><td><code>max_tokens</code></td><td></td><td>생성할 최대 토큰 수. 미설정 시 모델 기본값 적용</td></tr><tr><td><code>stream</code></td><td></td><td><code>true</code>로 설정하면 스트리밍 응답 활성화. 기본값 <code>false</code></td></tr><tr><td><code>response_format</code></td><td></td><td>응답 형식 지정. <code>{ "type": "text" }</code> 또는 <code>{ "type": "json_object" }</code></td></tr><tr><td><code>enable_web_search</code></td><td></td><td><code>true</code>로 설정하면 실시간 웹 검색 결과를 반영한 답변 생성 (지원 모델에 한함)</td></tr><tr><td><code>reasoning_config</code></td><td></td><td>OpenAI 추론 모델 전용. <code>effort</code>(<code>none</code>·<code>low</code>·<code>medium</code>·<code>high</code>·<code>xhigh</code>), <code>summary</code>(<code>auto</code>·<code>none</code>·<code>concise</code>·<code>detailed</code>)</td></tr></tbody></table>
{% endtab %}

{% tab title="Responses API" %}

<table><thead><tr><th width="160.38671875">파라미터</th><th width="79.640625">필수</th><th>설명</th></tr></thead><tbody><tr><td><code>model</code></td><td>✅</td><td>호출할 모델 ID. <code>provider/model</code> 형식 (예: <code>openai/gpt-5</code>)</td></tr><tr><td><code>input</code></td><td>✅</td><td>사용자 입력. 문자열 또는 메시지 배열(<code>role</code> + <code>content</code>)로 구성</td></tr><tr><td><code>instructions</code></td><td></td><td>시스템 레벨 지시사항. Chat Completions의 <code>system</code> 메시지에 해당</td></tr><tr><td><code>max_output_tokens</code></td><td></td><td>생성할 최대 토큰 수. 미설정 시 모델 기본값 적용</td></tr><tr><td><code>temperature</code></td><td></td><td>응답의 창의성 조절. <code>0</code>(결정적) ~ <code>2</code>(창의적)</td></tr><tr><td><code>stream</code></td><td></td><td><code>true</code>로 설정하면 스트리밍 응답 활성화. <strong>OpenAI 모델에서만 지원</strong></td></tr><tr><td><code>reasoning</code></td><td></td><td>추론 모델 전용. <code>{ "effort": "low" | "medium" | "high" }</code></td></tr><tr><td><code>response_format</code></td><td></td><td>응답 형식 지정. <code>json_object</code> 또는 <code>json_schema</code></td></tr><tr><td><code>tools</code></td><td></td><td>함수 도구 정의 배열</td></tr><tr><td><code>tool_choice</code></td><td></td><td>도구 선택 전략. <code>none</code>·<code>auto</code>·<code>required</code> 또는 특정 함수 지정</td></tr></tbody></table>
{% endtab %}
{% endtabs %}

#### 응답 예시

```json
{
  "id": "chatcmpl-2f3e0c18-...",
  "object": "chat.completion",
  "created": 1760000000,
  "model": "openai/gpt-5.2",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "안녕하세요! 무엇을 도와드릴까요?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 18,
    "total_tokens": 30
  }
}
```

AI의 답변은 `choices[0].message.content`에서 확인할 수 있으며, `usage`에서 이번 호출에 사용된 토큰 수를 확인할 수 있습니다.


---

# 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://runyourai.gitbook.io/userguide/api/guide/link.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.
