> ## Documentation Index
> Fetch the complete documentation index at: https://docs-platform.crewai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Conversational Flow Chat API

> CrewAI AMP에서 배포된 채팅 엔드포인트로 멀티 턴 conversational Flow를 실행하세요

## 개요

배포된 conversational Flow는 자동화 URL에 채팅 세션 API를 노출합니다. 단일 `/kickoff` 실행 대신 세션을 만들고, 사용자 메시지를 턴으로 보내며, 선택적으로 토큰과 런타임 이벤트를 스트리밍하고, 턴에 사람 피드백이 필요할 때 HITL 일시중지를 재개합니다.

<Note>
  Conversational Flow 채팅은 **experimental**입니다. 엔드포인트는 배포된 Flow가 [`GET /inspect`](#채팅-기능-확인)에서 `conversational: true`와 `handle_turn: true`를 모두 보고할 때만 사용할 수 있습니다.
</Note>

Flow 자체 구현(`conversational = True`, `handle_turn`, 라우터, 트레이싱)은 오픈소스 [Conversational Flows](https://docs.crewai.com/en/guides/flows/conversational-flows) 가이드를 참고하세요.

## 사전 요구 사항

1. conversational 턴(`handle_turn`)을 구현한 Flow 자동화를 배포합니다.
2. 자동화 **Status** 탭에서 bearer 토큰을 복사합니다(`/kickoff`와 동일한 토큰).
3. 아래 `/inspect`로 채팅이 활성화되어 있는지 확인합니다.

모든 요청은 다음을 사용합니다:

```bash theme={null}
Authorization: Bearer YOUR_FLOW_TOKEN
```

이 가이드의 기본 URL 예시는 `https://your-flow-url.crewai.com`입니다.

## 채팅 기능 확인

```bash theme={null}
curl -X GET \
  -H "Authorization: Bearer YOUR_FLOW_TOKEN" \
  https://your-flow-url.crewai.com/inspect
```

`flow.chat`를 확인하세요:

```json theme={null}
{
  "flow": {
    "chat": {
      "conversational": true,
      "handle_turn": true,
      "transports": ["webhook"],
      "experimental": true
    }
  }
}
```

둘 중 하나라도 false이면 채팅 엔드포인트는 `"Conversational flow chat is not available"`와 함께 `404`를 반환합니다.

## 엔드투엔드 채팅 루프

<Steps>
  <Step title="세션 시작">
    채팅 세션을 만듭니다. 선택적으로 세션 수명 동안 completed-turn 웹훅과 이벤트 웹훅을 등록합니다.

    ```bash theme={null}
    curl -X POST \
      -H "Authorization: Bearer YOUR_FLOW_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "completedTurnWebhookUrl": "https://your-server.com/webhooks/completed-turn",
        "webhooks": {
          "url": "https://your-server.com/webhooks/events",
          "events": ["*"],
          "realtime": false,
          "authentication": {
            "strategy": "bearer",
            "token": "my-secret-token"
          }
        }
      }' \
      https://your-flow-url.crewai.com/chat/start
    ```

    응답:

    ```json theme={null}
    { "session_id": "11111111-2222-3333-4444-555555555555" }
    ```

    웹훅이 필요 없으면 빈 body(`{}` 또는 body 없음)도 유효합니다.
  </Step>

  <Step title="사용자 메시지 보내기">
    세션에 턴을 큐에 넣습니다:

    ```bash theme={null}
    curl -X POST \
      -H "Authorization: Bearer YOUR_FLOW_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "message": "Where is my order?",
        "stream": true
      }' \
      https://your-flow-url.crewai.com/chat/11111111-2222-3333-4444-555555555555/message
    ```

    응답:

    ```json theme={null}
    {
      "session_id": "11111111-2222-3333-4444-555555555555",
      "kickoff_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
      "status": "queued"
    }
    ```

    | 필드               | 설명                                                                                               |
    | ---------------- | ------------------------------------------------------------------------------------------------ |
    | `message`        | 필수. 이 턴의 현재 사용자 메시지.                                                                             |
    | `stream`         | 기본값 `true`. `true`이면 WebSocket/SSE 클라이언트용 토큰/이벤트 프레임이 게시됩니다.                                     |
    | `messageHistory` | 선택적 fallback 트랜스크립트(`[{ "role", "content" }, ...]`). 서버 측 세션 기록이 권위 있으며, 저장된 기록이 비어 있을 때만 사용됩니다. |

    `messageHistory`에서 허용되는 role: `user`, `assistant`, `system`, `tool`.
  </Step>

  <Step title="턴 완료 대기">
    반환된 `kickoff_id`로 턴을 폴링합니다(일반 Flow kickoff와 동일한 status API):

    ```bash theme={null}
    curl -X GET \
      -H "Authorization: Bearer YOUR_FLOW_TOKEN" \
      https://your-flow-url.crewai.com/status/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
    ```

    세션당 활성 턴은 하나만 가능합니다. `active_kickoff_id`가 설정된 상태에서 두 번째 `/message`는 `409`를 반환합니다:

    ```json theme={null}
    {
      "detail": {
        "code": "session_busy",
        "kickoff_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
      }
    }
    ```

    다음 메시지를 보내기 전에 history에서 `active_kickoff_id: null`이 되거나 턴이 종료/일시중지 상태가 될 때까지 기다립니다.
  </Step>

  <Step title="세션 history 읽기">
    ```bash theme={null}
    curl -X GET \
      -H "Authorization: Bearer YOUR_FLOW_TOKEN" \
      https://your-flow-url.crewai.com/chat/11111111-2222-3333-4444-555555555555/history
    ```

    ```json theme={null}
    {
      "session_id": "11111111-2222-3333-4444-555555555555",
      "messages": [
        { "role": "user", "content": "Where is my order?" },
        { "role": "assistant", "content": "Your order is on the way." }
      ],
      "active_kickoff_id": null
    }
    ```
  </Step>
</Steps>

## 턴 스트리밍

스트리밍은 선택 사항입니다. UI가 턴 실행 중 토큰이나 런타임 이벤트가 필요할 때 사용합니다. 프레임은 항상 라이프사이클 타입(`turn_started`, `turn_completed`, `turn_failed`, `token`, `error`)을 포함합니다. 추가 `event` 프레임은 `events` 쿼리 파라미터(`*` 또는 쉼표로 구분된 목록)로 필터링할 수 있습니다.

### 옵션 A: HTTP 메시지 + SSE attach

1. `"stream": true`로 `POST /chat/{session_id}/message`를 호출합니다.
2. 활성 턴에 attach합니다:

```bash theme={null}
curl -N \
  -H "Authorization: Bearer YOUR_FLOW_TOKEN" \
  "https://your-flow-url.crewai.com/chat/11111111-2222-3333-4444-555555555555/stream/events?events=*&last_event_id=0-0"
```

SSE는 `text/event-stream` JSON 프레임(`data: {...}`)과 keepalive 코멘트를 반환합니다. 스트림은 `turn_completed` 또는 `turn_failed`에서 종료됩니다.

활성 턴이 없으면 이 엔드포인트는 `409`(`No active chat turn`)를 반환합니다.

### 옵션 B: WebSocket (attach 또는 전송)

```text theme={null}
wss://your-flow-url.crewai.com/chat/{session_id}/stream?token=YOUR_FLOW_TOKEN&events=*&last_event_id=0-0
```

인증: bearer 토큰을 `token` 쿼리 파라미터로 전달하거나, 클라이언트가 WebSocket 헤더를 지원하면 `Authorization: Bearer ...` 헤더를 사용합니다.

동작:

* **이미 활성 턴이 실행 중** — 소켓이 attach되고 먼저 `data.status: "attached"`인 `turn_started`를 보낸 뒤, terminal 타입까지 프레임을 스트리밍합니다.
* **활성 턴 없음** — JSON 메시지로 턴을 큐에 넣은 뒤 스트림을 소비합니다:

```json theme={null}
{
  "message": "Where is my order?",
  "messageHistory": [],
  "events": "*",
  "lastEventId": "0-0"
}
```

서버는 `turn_started`(`status: "queued"`)로 응답한 뒤 해당 `kickoff_id`의 스트림 프레임을 보냅니다.

연결이 끊긴 뒤에는 `last_event_id` / `lastEventId`로 재개하세요.

### 스트림 프레임 예시

```json theme={null}
{
  "type": "turn_started",
  "kickoff_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
  "session_id": "11111111-2222-3333-4444-555555555555",
  "data": { "status": "queued" }
}
```

```json theme={null}
{
  "type": "token",
  "kickoff_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
  "session_id": "11111111-2222-3333-4444-555555555555",
  "data": { "content": "Your order" }
}
```

```json theme={null}
{
  "type": "turn_completed",
  "kickoff_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
  "session_id": "11111111-2222-3333-4444-555555555555",
  "data": {}
}
```

## 채팅 세션 내 HITL

턴이 사람 피드백을 위해 일시중지되면(`status` / 상태 `PAUSED`), 일반 Flow와 동일한 resume 엔드포인트로 재개합니다:

```bash theme={null}
curl -X POST \
  -H "Authorization: Bearer YOUR_FLOW_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "flow_id": "FLOW_OR_SESSION_ID",
    "feedback": "approved"
  }' \
  https://your-flow-url.crewai.com/resume_feedback
```

응답의 resume `kickoff_id`를 폴링한 뒤, `/history`에서 `active_kickoff_id: null`이 될 때까지 기다렸다가 다음 채팅 메시지를 보내세요.

플랫폼 검토 UX는 [HITL 워크플로](/platform/ko/guides/human-in-the-loop)와 [Flow HITL 관리](/platform/ko/features/flow-hitl-management)를 참고하세요.

## API 레퍼런스

| 메서드    | Path                               | 용도                                 |
| ------ | ---------------------------------- | ---------------------------------- |
| `GET`  | `/inspect`                         | conversational 채팅 활성화 여부 확인        |
| `POST` | `/chat/start`                      | 채팅 세션 생성                           |
| `POST` | `/chat/{session_id}/message`       | 사용자 턴 큐잉                           |
| `GET`  | `/chat/{session_id}/history`       | 메시지 및 활성 턴 id 조회                   |
| `GET`  | `/chat/{session_id}/stream/events` | 활성 턴 SSE 스트림                       |
| `WS`   | `/chat/{session_id}/stream`        | WebSocket 스트림 (attach 또는 전송 + 스트림) |
| `GET`  | `/status/{kickoff_id}`             | 턴(또는 resume) 실행 상태 폴링              |
| `POST` | `/resume_feedback`                 | 일시중지된 HITL 턴 재개                    |

### 일반적인 오류

| Status | 상황                                                     |
| ------ | ------------------------------------------------------ |
| `400`  | 빈 `message`                                            |
| `404`  | 이 배포에서 채팅이 비활성화되었거나 알 수 없는 `session_id`                |
| `409`  | 세션에 이미 활성 턴이 있음(`session_busy`), 또는 활성 턴 없이 SSE attach |
| `422`  | `session_id`가 유효한 UUID가 아님                             |
| `503`  | 채팅 세션 또는 스트림 스토리지를 사용할 수 없음                            |

## 관련 문서

<CardGroup cols={2}>
  <Card title="Conversational Flows" href="https://docs.crewai.com/en/guides/flows/conversational-flows" icon="comments">
    `handle_turn`, 라우터, 트레이싱으로 멀티 턴 Flow를 구축하세요.
  </Card>

  <Card title="Kickoff Crew / Flow" href="/platform/ko/guides/kickoff-crew" icon="flag-checkered">
    배포 URL에서 단일 실행 kickoff 및 상태 폴링.
  </Card>

  <Card title="Webhook Streaming" href="/platform/ko/features/webhook-streaming" icon="webhook">
    이벤트 웹훅 페이로드 형식과 인증 옵션.
  </Card>

  <Card title="Flow HITL 관리" href="/platform/ko/features/flow-hitl-management" icon="users-gear">
    일시중지된 Flow 단계에 대한 이메일 우선 인간 검토.
  </Card>
</CardGroup>
