# LLM 서빙 API 사용

### 인증키 확인

* GenOS에서 인증키 정보를 확인합니다.
  * LLM 서빙에 권한이 있는 사용자라면 인증키에서 api를 발급 및 확인 할 수 있습니다.
  * 다른사람이 서빙한 것의 주소만 공유받아 사용하는 것이라면 서빙 권한을 가진 사용자에게 인증키 발급을 요청해야 합니다.

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

### 인증키 입력 <a href="#auth-key-input" id="auth-key-input"></a>

```python
import requests
import re
import json
# import base64

serving_id = 43
bearer_token = '인증키입력'
genos_url = 'GenOS 주소'

endpoint = f"{genos_url}/api/gateway/rep/serving/{serving_id}"
headers = dict(Authorization=f"Bearer {bearer_token}")
```

* 인증키와 endpoint를 입력합니다.

```python
# endpoint의 모델이름을 확인합니다
response = requests.get(endpoint + '/v1/models', headers=headers, timeout=30)
model = response.json()['data'][0]['id']
print(model)
```

* endpoint에서 모델 정보를 가져옵니다.

### API 호출

* OpenAI 의 API 호출 형식과 동일합니다.
* role은 `system` / `assistant` / `user` 를 주로 사용합니다.
  * 경우에 따라 `developer` / `tool` / `function` 도 사용 가능합니다.

```python
payload = {
    'model': model,
    'messages': [
        {'role': 'system', 'content': '당신은 유용한 어시스턴트입니다.'},
        {'role': 'user', 'content': '안녕하세요, 잘 지내고 있나요?'}
    ]
}

response = requests.post(endpoint+'/v1/chat/completions', headers=headers, json=payload, timeout=30)
print(response.json()['choices'][0]['message']['content'])
```

* 예상되는 정상 출력은 아래와 같습니다.

### 스트리밍 요청

* 토큰별로 응답을 받고 싶을 경우 아래와 같이 `stream=True`를 body와 옵션에 추가합니다.

```python
response = requests.post(endpoint+'/v1/chat/completions', headers=headers, json=payload, stream=True)

for line in response.iter_lines():
    if line:
        data = line.decode('utf-8').removeprefix('data: ')
        if data == '[DONE]':
            break
        json_data = json.loads(data)
        choice = json_data.get('choices', [])[0]
        message = choice.get('delta', {}).get('content', '')
        print(message, end='', flush=True)
```

* 예상되는 정상 출력은 아래와 같습니다.

```
안녕하세요! 저는 잘 지내고 있습니다. 무엇이든 물어보세요!
```

* 한 청크의 응답은 아래와 같습니다.

```
{
    'id': 'chat-5a11ac760ced4c549b02b41ffac3b62b',
    'object': 'chat.completion.chunk',
    'created': 1737018387,
    'model': '/model/snapshots/9eb2daaa8597bf192a8b0e73f848f3a102794df5',
    'choices': [
        {
            'index': 0,
            'delta': {'content': ' 지내고'},
            'logprobs': None,
            'finish_reason': 'stop',
            'stop_reason': None
        }
    ]
}
```

## 부가 기능

### 사용자 정보

* GenOS의 사용자 정보를 `이용 로그` 에서 확인하려면 user\_id를 포함합니다.
* 해당 정보는 GenOS에 로그인 요청을 보내거나 JWT 토큰을 검증하여 얻을 수 있습니다.

```python
headers['x-genos-user-id'] = 653
```


---

# 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://genos-docs.gitbook.io/default/v1.8.5/advanced-tutorials/guides/api/llm.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.
