# Backend-Controlled API Flow

Source: https://docs.openwebui.com/reference/api-flow

---

# Backend-Controlled, UI-Compatible API Flow

> **warning**
>
> This tutorial is a community contribution and is not supported by the Open WebUI team. It serves only as a demonstration on how to customize Open WebUI for your specific use case. Want to contribute? Check out the [contributing tutorial](/tutorials/contributing-tutorial).

This tutorial demonstrates how to implement server-side orchestration of Open WebUI conversations while ensuring that assistant replies appear properly in the frontend UI. This approach requires zero frontend involvement and allows complete backend control over the chat flow. This tutorial has been verified to work with Open WebUI version v0.6.15. Future versions may introduce changes in behavior or API structure.

## Prerequisites

Before following this tutorial, ensure you have:

- A running Open WebUI instance
- Valid API authentication token
- Access to the Open WebUI backend APIs
- Basic understanding of REST APIs and JSON
- Command-line tools: `curl`, `jq` (optional for JSON parsing)

## Overview

This tutorial describes a comprehensive 6-step process that enables server-side orchestration of Open WebUI conversations while ensuring that assistant replies appear properly in the frontend UI.

> **Looking for tool calling specifically?**
>
> If your goal is to have the model use tools (built-in tools, workspace tools, MCP servers or a machine) and have Open WebUI execute them server-side, see [Server-Side Tool Calling (API)](/reference/server-side-tool-calling). It builds on the chat structures documented here and adds the fields that switch tool execution on.

### Process Flow

The essential steps are:

1. **Create a new chat with user and assistant messages**: Initialize the conversation with the user's input and an empty assistant placeholder
2. **Trigger the assistant completion**: Generate the actual AI response (with optional knowledge integration)
3. **Wait for response completion**: Monitor the assistant response until fully generated
4. **Fetch and process the final chat**: Retrieve and parse the completed conversation

This enables server-side orchestration while still making replies show up in the frontend UI exactly as if they were generated through normal user interaction.

## Important Concepts

### Message IDs Are Caller-Generated

All message IDs (`user-msg-id`, `assistant-msg-id`) must be **generated by the caller** as valid UUIDs **before** making API calls. Open WebUI does not assign message IDs for you. Use any UUID v4 generator to create them.

Example (bash):

```
USER_MSG_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")
ASSISTANT_MSG_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")
```

### The `childrenIds` Field

The Open WebUI frontend renders messages as a **tree structure**. Each message must include a `childrenIds` array that lists the IDs of its direct child messages. Without this field, the frontend cannot walk the message tree and **messages will not render**, even if they exist in the database.

- A **user message** must list its assistant reply IDs in `childrenIds`
- An **assistant message** typically has `childrenIds: []` (empty) unless there are follow-up messages

### The `currentId` Field

The `history` object must use `currentId` (**camelCase**, not `current_id`). This tells the frontend which message is at the end of the active conversation thread.

## Implementation Guide

### Pre-creating the Assistant Message (Optional)

For an existing `chat_id`, `POST /api/chat/completions` inserts the assistant placeholder itself when you pass the assistant message's `id`, and links it under the user message you send as `user_message` (Step 2), so pre-creating it is no longer required. If you do pre-create it, always send `user_message`: the backend overwrites the stored placeholder's `parentId` with that message's `id`, or with null when `user_message` is missing.

A pre-created assistant message goes into `chat.history.messages[<assistantId>]`, the indexed message history the frontend uses to render the tree.

**Expected structure of the assistant message:**

```
{
  "id": "<uuid>",
  "role": "assistant",
  "content": "",
  "parentId": "<user-msg-id>",
  "childrenIds": [],
  "model": "gpt-5.6-sol",
  "modelName": "gpt-5.6-sol",
  "modelIdx": 0,
  "done": false,
  "timestamp": 1720000001
}
```

If you do pre-create it, use this structure.

## Step-by-Step Implementation

### Step 1: Create Chat with User and Assistant Messages

This creates the chat with **both** the user message and an empty assistant placeholder in a single request. The response returns a `chatId` (in the `id` field) that will be used in subsequent requests.

> **tip**
>
> You can combine chat creation and the assistant placeholder into this single step. The key is to include both the user message and an empty assistant message in the initial payload, with proper `parentId`, `childrenIds`, and `currentId` fields.

```
USER_MSG_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")
ASSISTANT_MSG_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")
TIMESTAMP=$(date +%s)

curl -X POST https://<host>/api/v1/chats/new \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "chat": {
      "title": "New Chat",
      "models": ["gpt-5.6-sol"],
      "messages": [
        {
          "id": "'"$USER_MSG_ID"'",
          "role": "user",
          "content": "Hi, what is the capital of France?",
          "timestamp": '"$TIMESTAMP"',
          "models": ["gpt-5.6-sol"],
          "childrenIds": ["'"$ASSISTANT_MSG_ID"'"]
        },
        {
          "id": "'"$ASSISTANT_MSG_ID"'",
          "role": "assistant",
          "content": "",
          "parentId": "'"$USER_MSG_ID"'",
          "childrenIds": [],
          "model": "gpt-5.6-sol",
          "modelName": "gpt-5.6-sol",
          "modelIdx": 0,
          "done": false,
          "timestamp": '"$((TIMESTAMP + 1))"'
        }
      ],
      "history": {
        "currentId": "'"$ASSISTANT_MSG_ID"'",
        "messages": {
          "'"$USER_MSG_ID"'": {
            "id": "'"$USER_MSG_ID"'",
            "role": "user",
            "content": "Hi, what is the capital of France?",
            "timestamp": '"$TIMESTAMP"',
            "models": ["gpt-5.6-sol"],
            "childrenIds": ["'"$ASSISTANT_MSG_ID"'"]
          },
          "'"$ASSISTANT_MSG_ID"'": {
            "id": "'"$ASSISTANT_MSG_ID"'",
            "role": "assistant",
            "content": "",
            "parentId": "'"$USER_MSG_ID"'",
            "childrenIds": [],
            "model": "gpt-5.6-sol",
            "modelName": "gpt-5.6-sol",
            "modelIdx": 0,
            "done": false,
            "timestamp": '"$((TIMESTAMP + 1))"'
          }
        }
      }
    }
  }'
```

**Save the `id` field from the response.** This is your `chatId` for all subsequent steps.

> **note**
>
> The `messages[]` array at the top level is a flat list for older clients. It is read only when `history.messages{}` is missing, and responses never include it. The `history.messages{}` object is the authoritative structure. It is a dictionary keyed by message ID, and the frontend uses it to build the conversation tree via `parentId` and `childrenIds`.

### Step 2: Trigger Assistant Completion

Generate the actual AI response using the completion endpoint. Use the `chatId` from Step 1:

```
curl -X POST https://<host>/api/chat/completions \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": "<chatId>",
    "id": "'"$ASSISTANT_MSG_ID"'",
    "user_message": {
      "id": "'"$USER_MSG_ID"'",
      "role": "user",
      "content": "Hi, what is the capital of France?",
      "parentId": null,
      "childrenIds": ["'"$ASSISTANT_MSG_ID"'"],
      "timestamp": '"$TIMESTAMP"',
      "models": ["gpt-5.6-sol"]
    },
    "messages": [
      {
        "role": "user",
        "content": "Hi, what is the capital of France?"
      }
    ],
    "model": "gpt-5.6-sol",
    "stream": true,
    "background_tasks": {
      "title_generation": true,
      "tags_generation": false,
      "follow_up_generation": false
    },
    "features": {
      "code_interpreter": false,
      "web_search": false,
      "image_generation": false,
      "memory": false
    },
    "variables": {
      "{{USER_NAME}}": "",
      "{{USER_LANGUAGE}}": "en-US",
      "{{CURRENT_DATETIME}}": "2025-07-14T12:00:00Z",
      "{{CURRENT_TIMEZONE}}": "Europe"
    },
    "session_id": "<session-uuid>"
  }'
```

> **note**
>
> The `session_id` should be a unique UUID that you generate for this session. It helps maintain conversation context and is also used for WebSocket event routing if the frontend is open.

> **Include user_message**
>
> `user_message` carries the user message this completion answers, the same object you stored in Step 1. The backend saves the assistant message with its `parentId` set to that message's `id`, which keeps the user message in the thread. Sent without it, the assistant message is saved with no parent, and after a page reload the chat shows only the assistant reply.

#### Step 2.1: Trigger Assistant Completion with Knowledge Integration (RAG)

For advanced use cases involving knowledge bases, include knowledge files in the completion request:

```
curl -X POST https://<host>/api/chat/completions \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": "<chatId>",
    "id": "'"$ASSISTANT_MSG_ID"'",
    "user_message": {
      "id": "'"$USER_MSG_ID"'",
      "role": "user",
      "content": "Hi, what is the capital of France?",
      "parentId": null,
      "childrenIds": ["'"$ASSISTANT_MSG_ID"'"],
      "timestamp": '"$TIMESTAMP"',
      "models": ["gpt-5.6-sol"]
    },
    "messages": [
      {
        "role": "user",
        "content": "Hi, what is the capital of France?"
      }
    ],
    "model": "gpt-5.6-sol",
    "stream": true,
    "files": [
      {
        "id": "knowledge-collection-id",
        "type": "collection",
        "status": "processed"
      }
    ],
    "background_tasks": {
      "title_generation": true,
      "tags_generation": false,
      "follow_up_generation": false
    },
    "features": {
      "code_interpreter": false,
      "web_search": false,
      "image_generation": false,
      "memory": false
    },
    "variables": {
      "{{USER_NAME}}": "",
      "{{USER_LANGUAGE}}": "en-US",
      "{{CURRENT_DATETIME}}": "2025-07-14T12:00:00Z",
      "{{CURRENT_TIMEZONE}}": "Europe"
    },
    "session_id": "<session-uuid>"
  }'
```

### Step 3: Wait for Assistant Response Completion

Assistant responses can be handled in two ways depending on your implementation needs:

#### Option A: Stream Processing

Streaming over the HTTP response only happens when the request carries no `session_id` (or no `chat_id`). With both present, as in Step 2, the completion runs as a background task and the response body is `{"status": true, "task_ids": [...], "chat_id": "..."}`, returned immediately; the output goes out as Socket.IO `events` to the `user:<id>` room (every socket signed in as that user), not to the `session_id`. To stream over HTTP, omit `session_id`; to track a background task, poll `GET /api/tasks/chat/{chat_id}` or the chat itself (Option B). The message types on that channel are listed in [Real-time events](#real-time-events).

#### Option B: Polling Approach

For implementations that cannot handle streaming, poll the chat endpoint until the response is ready. Use a retry mechanism with exponential backoff:

```

# Poll every few seconds until assistant content is populated
while true; do
  response=$(curl -s -X GET https://<host>/api/v1/chats/<chatId> \
    -H "Authorization: Bearer <token>")

# Check if assistant message has content (response is ready)
  assistant_content=$(echo "$response" | jq -r ".chat.history.messages[\"$ASSISTANT_MSG_ID\"].content // empty")
  if [ -n "$assistant_content" ]; then
    echo "Assistant response is ready!"
    echo "$assistant_content"
    break
  fi

  echo "Waiting for assistant response..."
  sleep 2
done
```

### Step 4: Fetch Final Chat

Retrieve the completed conversation:

```
curl -X GET https://<host>/api/v1/chats/<chatId> \
  -H "Authorization: Bearer <token>"
```

## Additional API Endpoints

### Fetch Knowledge Collection

Retrieve knowledge base information for RAG integration:

```
curl -X GET https://<host>/api/v1/knowledge/<knowledge-id> \
  -H "Authorization: Bearer <token>"
```

### Fetch Model Information

Get details about a specific model:

```
curl -X GET https://<host>/api/v1/models/model?id=<model-name> \
  -H "Authorization: Bearer <token>"
```

### Send Additional Messages to an Existing Chat

For multi-turn conversations, add the new user message and assistant placeholder to the existing chat, each with the correct `parentId`:

```
NEW_USER_MSG_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")
NEW_ASSISTANT_MSG_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")

# First: update the chat to add the new user + assistant placeholder
# childrenIds is recomputed from parentId, so the previous assistant message need not be resent
curl -X POST https://<host>/api/v1/chats/<chatId> \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "chat": {
      "history": {
        "currentId": "'"$NEW_ASSISTANT_MSG_ID"'",
        "messages": {
          "'"$NEW_USER_MSG_ID"'": {
            "id": "'"$NEW_USER_MSG_ID"'",
            "role": "user",
            "content": "Can you tell me more about Paris?",
            "parentId": "'"$ASSISTANT_MSG_ID"'",
            "childrenIds": ["'"$NEW_ASSISTANT_MSG_ID"'"],
            "timestamp": '"$(date +%s)"',
            "models": ["gpt-5.6-sol"]
          },
          "'"$NEW_ASSISTANT_MSG_ID"'": {
            "id": "'"$NEW_ASSISTANT_MSG_ID"'",
            "role": "assistant",
            "content": "",
            "parentId": "'"$NEW_USER_MSG_ID"'",
            "childrenIds": [],
            "model": "gpt-5.6-sol",
            "modelName": "gpt-5.6-sol",
            "modelIdx": 0,
            "done": false,
            "timestamp": '"$(($(date +%s) + 1))"'
          }
        }
      }
    }
  }'

# Then: trigger completion for the new assistant message (same as Step 2)
curl -X POST https://<host>/api/chat/completions \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": "<chatId>",
    "id": "'"$NEW_ASSISTANT_MSG_ID"'",
    "user_message": {
      "id": "'"$NEW_USER_MSG_ID"'",
      "role": "user",
      "content": "Can you tell me more about Paris?",
      "parentId": "'"$ASSISTANT_MSG_ID"'",
      "childrenIds": ["'"$NEW_ASSISTANT_MSG_ID"'"],
      "models": ["gpt-5.6-sol"]
    },
    "messages": [
      { "role": "user", "content": "Hi, what is the capital of France?" },
      { "role": "assistant", "content": "The capital of France is Paris." },
      { "role": "user", "content": "Can you tell me more about Paris?" }
    ],
    "model": "gpt-5.6-sol",
    "stream": true,
    "session_id": "<session-uuid>"
  }'
```

> **note**
>
> When updating an existing chat via `POST /api/v1/chats/<chatId>`, the payload is **merged** with the existing chat data. You only need to include the fields you are changing. For `history.messages`, the merge is per message, not per field: messages you omit are preserved, but a message you include replaces the stored one wholesale, so send full message objects. `childrenIds` is recomputed from each message's `parentId`, so you need not set it on the parent.

## Real-time events

This list is for Open WebUI v0.13.4. Since v0.13.4, updates for notes, presence, comments, the inbox and access changes arrive as typed messages on the `events` channel. A client that listened for `events:note` or `note:presence` as channel names receives nothing and must listen on `events` and read `data.type` instead.

### Connecting

- Connect a Socket.IO client to the root of your Open WebUI host with the path `/ws/socket.io`, and pass `{"token": "<token>"}` as the `auth` object.
- The token must be the session token returned by sign-in. The socket decodes it as a JWT, so an API key (`sk-...`) is not accepted. Only users with the `user` or `admin` role are accepted.
- With a valid token, the socket joins the room `user:<user id>`, which receives every event sent to that user, from any of their sessions.
- After connecting, emit `user-join` with `{"auth": {"token": "<token>"}}`. It returns `{"id", "name"}` and joins the `channel:<channel id>` room for each channel the user belongs to, if the user can use channels.
- Every 30 seconds the server checks the token of each socket and disconnects any socket whose token is no longer valid.

### Rooms you join on request

| Emit | Payload | Room joined | Condition |
| --- | --- | --- | --- |
| events:chat | {"chat_id": "<id>", "data": {"type": "join"}} | chat:<chat id> | Read access to a saved chat. The acknowledgement is true or false. Send {"type": "leave"} to leave |
| note:join | {"note_id": "<id>", "auth": {"token": "<token>"}} | note:<note id> | Notes are enabled, the user has the notes feature, and owns or can read the note. Emit note:leave with {"note_id": "<id>"} to leave |
| comments:join | {"resource_type": "<type>", "resource_id": "<id>", "subscription_id": "<name>"} | One comments room for that resource | Comments are enabled and the user can read the resource. resource_type is model, knowledge, prompt, skill, tool, note or chat. The acknowledgement is {"ok": true} or {"error": "..."}. A socket can hold up to 10 subscriptions. Emit comments:leave with the same subscription_id to leave |

### Messages on the `events` channel

Every message on `events` has the form `{"data": {"type": "<type>", "data": {...}}}`. Chat messages also carry `chat_id` and `message_id` at the top level.

| type | Sent to | data |
| --- | --- | --- |
| Chat output types such as chat:completion, status, source, files, chat:message:error | user:<id> | The event the model or a tool emitted. See Events for the types |
| Copies of chat output, chat:messages and chat:active for saved chats | chat:<id>, except the socket that started the request | The top level also carries "shared": true and the user_id of the person who sent the message |
| chat:presence | chat:<id> | {"users": [{"id", "name"}]}, the people with the chat open |
| typing | chat:<id>, except the sender | {"typing": true or false}. The top level carries user with id and name. Send it yourself with events:chat and {"chat_id": "<id>", "data": {"type": "typing", "data": {"typing": true}}}, which needs write access and a joined room |
| chat:access | Each socket that has someone else's chat open, when access to it is checked again | {}. Fetch the chat again. If access was removed, the socket has already left the room |
| chat:list | user:<id> | Sometimes {"chat_id", "last_read_at", "folder_unread_counts"}, sometimes nothing. Refresh the chat list |
| chat:reload | user:<id> | Nothing. Fetch the chat again |
| note:updated | note:<id> | The note. After an edit in the editor, {"id", "page", "updated_at"} with only the saved page |
| note:presence | note:<id> | {"note_id", "users": [...]}. Each user has id and name, plus page_id, document_id, cursor, cursor_position and updated_at when known |
| comments:changed | The comments room | {"resource_type", "resource_id"}, with no comment text. Fetch GET /api/v1/comments/?resource_type=<type>&resource_id=<id> again |
| comments:unavailable | The one socket that lost access | {"resource_type", "resource_id"}. The socket has already left the room |
| notifications:changed | user:<id> | Nothing. Fetch GET /api/v1/notifications/inbox again |
| access:updated | Each socket of users whose groups changed, or every socket when an admin saves the default user permissions | Nothing. After a group change the server disconnects those sockets right after this message, so reconnect and fetch permissions again |
| machines:changed | user:<id> | Nothing. Fetch machines, models and tools again |
| calendar:alert | user:<id> | {"event_id", "title", "description", "start_at", "minutes_until", "calendar_id", "location"} for a calendar reminder |
| channel:app | user:<id> | {"app_id", "app_name", "channel_id", "message_id", "parent_id", "reply": {"type": "error", "content"}} when an app could not reply in a channel |
| encryption:available | channel:<id> | {"channel", "session"} when a private chat in that channel starts, with session set to null when it ends. Its packets use the separate encryption:event channel |

### Other channels

- `events:channel` carries channel messages to the `channel:<id>` room in the form `{"channel_id", "message_id", "data": {"type", "data"}}`. Types include `message`, `message:update`, `message:reply`, `message:delete`, `message:reaction:add`, `message:reaction:remove` and `typing`. `channel:created` and `channel:mute` go to `user:<id>`.
- `automation:result` goes to `user:<id>` when an automation run finishes, with `automation_id`, `name`, `chat_id` and `status`.
- Collaborative note editing uses `ydoc:document:*` and `ydoc:awareness:update`, which carry Yjs updates for the editor.

## Response Processing

### Parsing Assistant Responses

Assistant responses may be wrapped in markdown code blocks. Here's how to clean them:

```

# Example raw response from assistant
raw_response='```json
{
  "result": "The capital of France is Paris.",
  "confidence": 0.99
}
```'

# Clean the response (remove markdown wrappers)
cleaned_response=$(echo "$raw_response" | sed 's/^```json//' | sed 's/```$//' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')

echo "$cleaned_response" | jq '.'
```

This cleaning process handles:

- Removal of ````json` prefix
- Removal of ```` suffix
- Trimming whitespace
- JSON validation

## API Reference

### DTO Structures

#### Chat DTO (Complete Structure)

```
{
  "id": "chat-uuid-12345",
  "title": "New Chat",
  "models": ["gpt-5.6-sol"],
  "files": [],
  "tags": [],
  "params": {
    "temperature": 0.7,
    "max_tokens": 1000
  },
  "timestamp": 1720000000,
  "messages": [
    {
      "id": "user-msg-id",
      "role": "user",
      "content": "Hi, what is the capital of France?",
      "timestamp": 1720000000,
      "models": ["gpt-5.6-sol"],
      "childrenIds": ["assistant-msg-id"]
    },
    {
      "id": "assistant-msg-id",
      "role": "assistant",
      "content": "",
      "parentId": "user-msg-id",
      "childrenIds": [],
      "model": "gpt-5.6-sol",
      "modelName": "gpt-5.6-sol",
      "modelIdx": 0,
      "done": false,
      "timestamp": 1720000001
    }
  ],
  "history": {
    "currentId": "assistant-msg-id",
    "messages": {
      "user-msg-id": {
        "id": "user-msg-id",
        "role": "user",
        "content": "Hi, what is the capital of France?",
        "timestamp": 1720000000,
        "models": ["gpt-5.6-sol"],
        "childrenIds": ["assistant-msg-id"]
      },
      "assistant-msg-id": {
        "id": "assistant-msg-id",
        "role": "assistant",
        "content": "",
        "parentId": "user-msg-id",
        "childrenIds": [],
        "model": "gpt-5.6-sol",
        "modelName": "gpt-5.6-sol",
        "modelIdx": 0,
        "done": false,
        "timestamp": 1720000001
      }
    }
  },
  "currentId": "assistant-msg-id"
}
```

#### ChatCompletionsRequest DTO

```
{
  "chat_id": "chat-uuid-12345",
  "id": "assistant-msg-id",
  "user_message": {
    "id": "user-msg-id",
    "role": "user",
    "content": "Hi, what is the capital of France?",
    "parentId": null,
    "childrenIds": ["assistant-msg-id"],
    "timestamp": 1720000000,
    "models": ["gpt-5.6-sol"]
  },
  "messages": [
    {
      "role": "user",
      "content": "Hi, what is the capital of France?"
    }
  ],
  "model": "gpt-5.6-sol",
  "stream": true,
  "background_tasks": {
    "title_generation": true,
    "tags_generation": false,
    "follow_up_generation": false
  },
  "features": {
    "code_interpreter": false,
    "web_search": false,
    "image_generation": false,
    "memory": false
  },
  "variables": {
    "{{USER_NAME}}": "",
    "{{USER_LANGUAGE}}": "en-US",
    "{{CURRENT_DATETIME}}": "2025-07-14T12:00:00Z",
    "{{CURRENT_TIMEZONE}}": "Europe"
  },
  "session_id": "session-uuid-67890",
  "filter_ids": [],
  "files": [
    {
      "id": "knowledge-collection-id",
      "type": "collection",
      "status": "processed"
    }
  ]
}
```

#### ChatCompletionMessage DTO

```
{
  "role": "user",
  "content": "Hi, what is the capital of France?"
}
```

#### History DTO

```
{
  "currentId": "assistant-msg-id",
  "messages": {
    "user-msg-id": {
      "id": "user-msg-id",
      "role": "user",
      "content": "Hi, what is the capital of France?",
      "timestamp": 1720000000,
      "models": ["gpt-5.6-sol"],
      "childrenIds": ["assistant-msg-id"]
    },
    "assistant-msg-id": {
      "id": "assistant-msg-id",
      "role": "assistant",
      "content": "The capital of France is Paris.",
      "parentId": "user-msg-id",
      "childrenIds": [],
      "model": "gpt-5.6-sol",
      "modelName": "gpt-5.6-sol",
      "modelIdx": 0,
      "timestamp": 1720000001
    }
  }
}
```

#### Message DTO (Complete Structure)

**User message:**

```
{
  "id": "user-msg-id",
  "role": "user",
  "content": "Hi, what is the capital of France?",
  "timestamp": 1720000000,
  "models": ["gpt-5.6-sol"],
  "childrenIds": ["assistant-msg-id"]
}
```

**Assistant message:**

```
{
  "id": "assistant-msg-id",
  "role": "assistant",
  "content": "The capital of France is Paris.",
  "parentId": "user-msg-id",
  "childrenIds": [],
  "model": "gpt-5.6-sol",
  "modelName": "gpt-5.6-sol",
  "modelIdx": 0,
  "done": true,
  "timestamp": 1720000001
}
```

### Response Examples

#### Create Chat Response

```
{
  "id": "chat-uuid-12345",
  "user_id": "user-uuid",
  "title": "New Chat",
  "chat": {
    "title": "New Chat",
    "models": ["gpt-5.6-sol"],
    "messages": [
      {
        "id": "user-msg-id",
        "role": "user",
        "content": "Hi, what is the capital of France?",
        "timestamp": 1720000000,
        "models": ["gpt-5.6-sol"],
        "childrenIds": ["assistant-msg-id"]
      },
      {
        "id": "assistant-msg-id",
        "role": "assistant",
        "content": "",
        "parentId": "user-msg-id",
        "childrenIds": [],
        "model": "gpt-5.6-sol",
        "modelName": "gpt-5.6-sol",
        "modelIdx": 0,
        "done": false,
        "timestamp": 1720000001
      }
    ],
    "history": {
      "currentId": "assistant-msg-id",
      "messages": {
        "user-msg-id": {
          "id": "user-msg-id",
          "role": "user",
          "content": "Hi, what is the capital of France?",
          "timestamp": 1720000000,
          "models": ["gpt-5.6-sol"],
          "childrenIds": ["assistant-msg-id"]
        },
        "assistant-msg-id": {
          "id": "assistant-msg-id",
          "role": "assistant",
          "content": "",
          "parentId": "user-msg-id",
          "childrenIds": [],
          "model": "gpt-5.6-sol",
          "modelName": "gpt-5.6-sol",
          "modelIdx": 0,
          "done": false,
          "timestamp": 1720000001
        }
      }
    },
    "currentId": "assistant-msg-id"
  },
  "updated_at": 1720000000,
  "created_at": 1720000000
}
```

#### Final Chat Response (After Completion)

```
{
  "id": "chat-uuid-12345",
  "title": "Capital of France Discussion",
  "chat": {
    "models": ["gpt-5.6-sol"],
    "history": {
      "currentId": "assistant-msg-id",
      "messages": {
        "user-msg-id": {
          "id": "user-msg-id",
          "role": "user",
          "content": "Hi, what is the capital of France?",
          "timestamp": 1720000000,
          "models": ["gpt-5.6-sol"],
          "childrenIds": ["assistant-msg-id"]
        },
        "assistant-msg-id": {
          "id": "assistant-msg-id",
          "role": "assistant",
          "content": "The capital of France is Paris. Paris is not only the capital but also the most populous city in France, known for its iconic landmarks such as the Eiffel Tower, the Louvre Museum, and Notre-Dame Cathedral.",
          "parentId": "user-msg-id",
          "childrenIds": [],
          "model": "gpt-5.6-sol",
          "modelName": "gpt-5.6-sol",
          "modelIdx": 0,
          "done": true,
          "timestamp": 1720000001
        }
      }
    },
    "currentId": "assistant-msg-id"
  }
}
```

#### OWUIKnowledge DTO (Knowledge Collection)

```
{
  "id": "knowledge-collection-id",
  "type": "collection",
  "status": "processed",
  "name": "Geography Knowledge Base",
  "description": "Contains information about world geography and capitals",
  "created_at": 1720000000,
  "updated_at": 1720000001
}
```

#### Model Information Response

```
{
  "id": "gpt-5.6-sol",
  "name": "GPT-5.6 Sol",
  "model": "gpt-5.6-sol",
  "base_model_id": "gpt-5.6-sol",
  "meta": {
    "description": "OpenAI's frontier model for complex professional work",
    "capabilities": ["text", "vision", "function_calling"],
    "context_length": 128000,
    "max_output_tokens": 4096
  },
  "params": {
    "temperature": 0.7,
    "top_p": 1.0,
    "frequency_penalty": 0.0,
    "presence_penalty": 0.0
  },
  "created_at": 1720000000,
  "updated_at": 1720000001
}
```

### Field Reference Guide

#### Required vs Optional Fields

**Chat Creation - Required Fields:**

- `title`: Chat title (string)
- `models`: Array of model names (string[])
- `messages`: Initial message array
- `history`: Message tree with `currentId` and `messages` map

**Chat Creation - Optional Fields:**

- `files`: Knowledge files for RAG (defaults to empty array)
- `tags`: Chat tags (defaults to empty array)
- `params`: Model parameters (defaults to empty object)

**Message Structure - User Message:**

- **Required:** `id`, `role`, `content`, `timestamp`, `models`, `childrenIds`
- **Optional:** `parentId` (for threading; omit for the first message in a chat)

**Message Structure - Assistant Message:**

- **Required:** `id`, `role`, `content`, `parentId`, `childrenIds`, `model`, `modelName`, `modelIdx`, `timestamp`
- **Optional:** `done` (boolean, defaults to false), additional metadata fields

**ChatCompletionsRequest - Required Fields:**

- `chat_id`: Target chat ID
- `id`: Assistant message ID
- `messages`: Array of ChatCompletionMessage
- `model`: Model identifier

**ChatCompletionsRequest - Optional Fields:**

- `session_id`: Session identifier (caller-generated). Together with `chat_id` it runs the completion as a background task that returns `task_ids`; omit it to stream over HTTP.
- `stream`: Enable streaming (defaults to false)
- `background_tasks`: Control automatic tasks
- `features`: Enable/disable features
- `variables`: Template variables
- `filter_ids`: Pipeline filters
- `files`: Knowledge bases for RAG

#### Field Constraints

**Timestamps:**

- Format: Unix timestamp in **seconds** (not milliseconds) for message timestamps in `history.messages`
- The top-level chat `timestamp` field uses milliseconds
- Example: `1720000000` (July 3, 2024)

**UUIDs:**

- All ID fields (`id`, `parentId`, `session_id`) should use valid UUID v4 format
- Example: `550e8400-e29b-41d4-a716-446655440000`
- IDs are **generated by the caller**, not assigned by the server

**Model Names:**

- Must match available models in your Open WebUI instance
- Common examples: `gpt-5.6-sol`, `gpt-5.6-luna`, `claude-sonnet-5`

**Session IDs:**

- Can be any unique string identifier
- Recommendation: Use UUID format for consistency

**Knowledge File Status:**

- Valid values: `"processed"`, `"processing"`, `"error"`
- Only use `"processed"` files for completions

## Important Notes

- This workflow is compatible with Open WebUI + backend orchestration scenarios
- **Critical: Use `currentId` (camelCase)** in the history object, not `current_id` (snake_case)
- **Critical: Include `childrenIds`** on every message. The frontend uses this to build the message tree
- No frontend code changes are required for this approach
- The `stream: true` parameter allows for real-time response streaming if needed
- `outlet()` filters run inline during `/api/chat/completions`, on both the streaming and non-streaming paths, controlled by [`ENABLE_API_OUTLET_FILTERS`](/reference/env-configuration#enable_api_outlet_filters) (default `True`). Neither a `chat_id` nor a message `id` is required in the request body; with neither present, the conversation is reconstructed from the `messages` you sent plus the assistant reply, and a message ID is generated for it. Inline execution does not rewrite the HTTP response body, so the filtered payload never comes back to an API caller over HTTP. The separate `/api/chat/completed` endpoint is deprecated and kept for backward compatibility, and it remains the way to have the filtered payload returned to you. See [Filter Behavior with API Requests](/features/extensibility/plugin/functions/filter#filter-behavior-with-api-requests) for the full picture
- Background tasks like title generation can be controlled via the `background_tasks` object
- Session IDs help maintain conversation context across requests
- **Knowledge Integration:** Use the `files` array to include knowledge bases for RAG capabilities
- **Response Parsing:** Handle JSON responses that may be wrapped in markdown code blocks
- **Error Handling:** Implement proper retry mechanisms for network timeouts and server errors

## Common Pitfalls

| Symptom | Cause | Fix |
| --- | --- | --- |
| Chat created but messages don't appear in UI | Missing childrenIds on messages | Add childrenIds array linking parent → child messages |
| Chat shows "How can I help you today?" | Using current_id instead of currentId | Use camelCase currentId in the history object |
| Completion works but response only appears as notification | Assistant message not in chat history before triggering completion | Pass the assistant message's id and user_message in the completion request (Step 2), or include the assistant placeholder in Step 1 |
| Messages exist in DB but frontend shows empty chat | Missing parentId or broken tree linkage | Ensure every message has correct parentId and parent's childrenIds includes the child |
| User message disappears after a page reload once the completion ran | user_message missing from the /api/chat/completions request, so the assistant message is saved with no parent | Send user_message with the user message's id in the completion request (Step 2) |

## Summary

Use the Open WebUI backend APIs to:

1. **Start a chat with messages**: Create the conversation with user input and an empty assistant placeholder (including proper `childrenIds` and `currentId`)
2. **Trigger a reply**: Generate the AI response (with optional knowledge integration)
3. **Monitor completion**: Wait for the assistant response using streaming or polling
4. **Fetch the final chat**: Retrieve and parse the completed conversation

**Enhanced Capabilities:**

- **RAG Integration**: Include knowledge bases for context-aware responses
- **Asynchronous Processing**: Handle long-running AI operations with streaming or polling
- **Response Parsing**: Clean and validate JSON responses from the assistant
- **Session Management**: Maintain conversation context across requests

This enables backend-controlled workflows that still appear properly in the Web UI frontend chat interface, providing seamless integration between programmatic control and user experience.

The key advantage of this approach is that it maintains full compatibility with the Open WebUI frontend while allowing complete backend orchestration of the conversation flow, including advanced features like knowledge integration and asynchronous response handling.

## Testing

You can test your implementation by following the step-by-step CURL examples provided above. Make sure to replace placeholder values with your actual:

- Host URL
- Authentication token
- Chat IDs (from the create chat response)
- Message IDs (UUIDs you generate)
- Model names (matching your configured models)

> **tip**
>
> Start with a simple user message and gradually add complexity like knowledge integration and advanced features once the basic flow is working.
