> For the complete documentation index, see [llms.txt](https://genos-docs.gitbook.io/default/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://genos-docs.gitbook.io/default/v1.7.8/advanced-tutorials/guides/api/workflow.md).

# 워크플로우 API 사용

### 인증키 입력

```python
import requests
import re
import json

workflow_id = 251
bearer_token = 'GenOS에서 발급한 인증키'
genos_url = 'GenOS 주소'

url = f"{genos_url}/api/gateway/workflow/{workflow_id}"
headers = dict(Authorization=f"Bearer {bearer_token}")

res = requests.get(f"{url}/healthcheck", headers=headers)
print(res.json())
```

* 인증키 입력 후 API 호출 가능 여부확인을 위해 healthcheck 호출 진행하였습니다.
* 정상 출력은 아래와 같습니다.

```
{'status': 'ok'}
```

### 인증키(bearer\_token) 생성 참고

* 에이전트 > 워크플로우 > 워크플로우 상세> 인증 키 탭에서 **인증 키 생성 버튼**을 클릭합니다.

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

* 인증 키 생성
  * **허용 IP:** 키가 작동 가능한 IP를 입력 후 + 버튼을 클릭하여 추가합니다.
  * **만료 일자:** 인증 키의 유효 기간 종료일시를 선택합니다.
  * **분당 사용 한도:** 해당 키를 통한 분당 사용 한도를 입력합니다.
  * **사용자:** 사용자를 선택합니다.
  * **메모:** 사용 목적, 제약 조건 등 해당 키에 대한 메모를 입력합니다.

<figure><img src="/files/5bofTzIoCvbeWVze7x45" alt=""><figcaption></figcaption></figure>

### 워크플로우 API 호출

```python
body = {
    'question': '1 + 1은?'
}

res = requests.post(f'{url}/run/v2', json=body, headers=headers)
print(res.json())
```

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

```
{
    'code': 0,
    'errMsg': 'success',
    'data': {
        'question': '1 + 1은?',
        'text': '1과 1을 더하면 2가 됩니다.',
        'sourceDocuments': [...], // Optional
        'chatId': '131a7da2-1ebf-41ec-bafe-6aed3be5f08c',
        'chatMessageId': '212571bd-43d1-4dd0-b81d-0bcd4c0a050b',
        'sessionId': '131a7da2-1ebf-41ec-bafe-6aed3be5f08c',
    }
}
```

### 스트리밍 요청

* 토큰별로 응답을 받고 싶을 경우 아래와 같이 `stream=True`를 body와 옵션에 추가합니다.
* 토큰별 응답은 `token:` 으로 시작하며, 최종 결과는 `result:` 로 시작합니다.

```python
body = {
    'question': '3 + 3은?',
    "stream": True
}
res = requests.post(f'{url}/run/v2', json=body, headers=headers, stream=True)

result = None
for line in res.iter_lines():
    if line:
        data = line.decode('utf-8')
        if token := re.search(r'^token: (.*)$', data, flags=re.DOTALL):
            print(token.group(1), end='', flush=True)
        elif result := re.search(r'^result: (.*)$', data, flags=re.DOTALL):
            result = json.loads(result.group(1))

print('='*20)
print('최종 출력:')
print(result)
```

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

```
3 + 3 은 6 입니다.
====================
최종 출력:
{
    'question': '3 + 3은?',
    'text': '3 + 3 은 6 입니다.',
    'sourceDocuments': [...], // Optional
    'chatId': '7db9f59b-b67e-454a-bf9e-e1b3f2e00ac6',
    'chatMessageId': '9aa04675-8422-4e53-bca3-c1135e3c6949',
    'sessionId': '7db9f59b-b67e-454a-bf9e-e1b3f2e00ac6'
}
```

## 부가 기능

### 멀티턴 대화

* 멀티턴 대화 (히스토리 기반 응답)를 활성화하려면 요청 시 uuid4를 포함합니다.

```python
session_id = '02f4bbfb-5624-436f-9144-2e2dfda7253d'

body['chatId'] = session_id
headers['x-genos-session-id'] = session_id
```

* `session_id`는 워크플로우 API를 호출한 뒤, 이어서 진행할 수 있습니다. ([참고](#워크플로우-api-호출))

```python
body = {
    'question': '1 + 1은?'
}
res = requests.post(f'{url}/run/v2', json=body, headers=headers)
session_id = res.json()['data']['sessionId']

next_body = {
    'question': '영어로 다시 대답해줘.',
    'chatId': session_id
}
headers['x-genos-session-id'] = session_id
```

### Trace Id

* Trace Id를 활성화하려면 요청 시 uuid4를 포함합니다. Trace Id와 관련된 내용은 [멀티 턴 대화 API 호출 문서](https://genos-docs.gitbook.io/default/v1.7.8/advanced-tutorials/guides/api/pages/N0AfNiCFCCiNGAcBWuO7#멀티-턴-대화)에서 확인할 수 있습니다.
* 같은 Trace ID를 가진 요청은 GenOS의 `이용 로그` 페이지에서 묶여서 표시됩니다.

```python
headers['x-genos-trace-id'] = 'b35aec2c-d390-4ce2-9cb1-f7658be37d74'
```

### 사용자 정보

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

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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://genos-docs.gitbook.io/default/v1.7.8/advanced-tutorials/guides/api/workflow.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
