# How Open WebUI Reaches Your LLM: Messages, Endpoints and Streaming

> Trace a chat request from Open WebUI to a model API. Run a local TypeScript exercise, inspect messages and streamed events, and diagnose the boundary that failed.

- Drafted by AI, signed off by: [Muhammed Shakir](https://www.linkedin.com/in/muhammed-shakir-gen-ai-trainings-and-consulting): Creator, Projekts.ai | Enterprise AI Builder & Architect | Helping Businesses Build AI-Agent-Driven Operations | Agentic AI, RAG & AI-Native Systems | Forward Deployed Engineer | Corporate Trainer
- Published: 2026-10-30
- Last updated: 2026-10-30
- Topic: AI fundamentals for developers
- Written for: developers and architects
- Web page: https://workshopps.com/blog/open-webui-chat-endpoint-streaming
- Related Course Offering: [LangChain & LangGraph — Build Stateful AI Agents, from Chatbot to Multi-Agent Workflow](https://workshopps.com/courses/langchain-and-langgraph)

**At a glance:** Open WebUI sends a conversation to your chat endpoint, which combines application instructions with messages and calls a model API. The endpoint returns a complete answer or streamed events for the interface to display. Verify discovery, request handling and streaming separately; a listed model does not prove a working conversation.

## The short answer

Open WebUI sends a conversation to your chat endpoint, which combines application instructions with messages and calls a model API. The endpoint returns a complete answer or a stream of response events, and Open WebUI displays the content as it arrives. To understand the application, inspect those boundaries separately: a visible model name does not prove that a chat request or its stream works.

---

## Follow one message through the application

Suppose a learner asks, “Explain a context window in two sentences.” There are three responsibilities to follow:

| Part | Responsibility in this example | What to inspect |
| --- | --- | --- |
| Open WebUI | Collect the question and conversation; render the answer | Selected model and request messages |
| Your chat endpoint | Validate the request, add application instructions and call the model | Ordered messages, upstream status and response type |
| Model API | Generate a response from the supplied input | Returned content, stream termination and errors |

![Open WebUI sends messages to an application endpoint, which adds instructions and calls a model API; response events return through the endpoint to the chat interface.](https://infomover-public-content.s3.ap-south-1.amazonaws.com/prod/workshopps/open-webui-chat-endpoint-streaming/chat-flow.svg "Keep the request and return paths visible: discovery, generation and streaming are separate things to verify.")

For a compatible provider connection, the useful routes are `GET /v1/models` for discovery and `POST /v1/chat/completions` for chat. Our exercise also supplies `GET /health` to check whether the process is reachable. Open WebUI's own API has a different route, `/api/chat/completions`; do not substitute that for the application endpoint you are building. The [Open WebUI provider guide](https://docs.openwebui.com/getting-started/quick-start/connect-a-provider/starting-with-openai-compatible/) describes the connection contract, while its [API reference](https://docs.openwebui.com/reference/api-endpoints/) describes calls to Open WebUI itself.

The `/v1` prefix here identifies an HTTP interface. It does not mean that your application must use a particular model provider.

---

## Read the request before choosing a framework

A minimal request looks like this:

```json
{
  "model": "contract-demo",
  "messages": [
    { "role": "user", "content": "Explain a context window in two sentences." }
  ],
  "stream": true
}
```

The `model` identifies the backend capability the client selected. In this exercise the endpoint advertises exactly one ID and rejects another. The `messages` array carries an ordered conversation; earlier user and assistant messages provide history when you include them. The `stream` flag selects incremental events instead of one complete response.

Keep stable application instructions separate from the learner's text. Our endpoint adds a system message, retains user and assistant turns in their original order, and discards client-supplied system or developer instructions. That is a deliberate policy for this small exercise. An application that supports configurable assistant personas would need a different, explicit policy.

Message roles organise input; they do not make a model enforce access control. Authorisation and permission to execute an action belong in application code. Likewise, the endpoint below has no conversation store: if you leave an earlier turn out of the next request, this endpoint does not restore it for you.

LangChain can later compose instructions, model calls and output handling inside this boundary. Start by making the boundary observable; introducing composition should not change what the chat client expects.

---

## Run a local contract exercise

Use Node.js 22 or later and a shell with `npm`. Create an empty directory, run the following, then save the TypeScript below as `server.ts`:

```bash
npm init -y
npm install --save-dev tsx typescript @types/node
```

The default mode returns a fixed reply. It exercises discovery, request validation and response framing without downloading a model or using credentials. It does not generate an answer with an LLM. The optional upstream mode, shown afterwards, makes the model API call.

This is a TypeScript transport exercise. Session 1 of the [LangChain and LangGraph workshop](/courses/langchain-and-langgraph) builds the corresponding endpoint with Python and FastAPI as the foundation of its Learning Companion assistant.

```typescript
import { createServer, type ServerResponse } from 'node:http';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';

type Message = { role: string; content: string };
class HttpError extends Error {
  constructor(public status: number, message: string) { super(message); }
}
const upstream = process.env.UPSTREAM_CHAT_URL;
const model = process.env.CHAT_MODEL ?? 'contract-demo';
if (upstream && !process.env.CHAT_MODEL) {
  throw new Error('Set CHAT_MODEL to an installed upstream model ID');
}
const instruction: Message = {
  role: 'system',
  content: 'You are a learning companion. Explain clearly and briefly.'
};
function json(res: ServerResponse, status: number, value: unknown) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(value));
}

createServer(async (req, res) => {
  const cancelled = new AbortController();
  res.on('close', () => cancelled.abort());
  try {
    const path = req.url?.split('?')[0];
    if (req.method === 'GET' && path === '/health') {
      return json(res, 200, { mode: upstream ? 'relay' : 'canned' });
    }
    if (req.method === 'GET' && path === '/v1/models') {
      return json(res, 200, { object: 'list', data: [
        { id: model, object: 'model', created: 0, owned_by: 'local-lab' }
      ] });
    }
    if (req.method !== 'POST' || path !== '/v1/chat/completions') {
      throw new HttpError(404, 'Unknown route');
    }
    let size = 0;
    const chunks: Buffer[] = [];
    for await (const chunk of req) {
      const bytes = Buffer.from(chunk);
      size += bytes.length;
      if (size <= 32768) chunks.push(bytes);
    }
    if (size > 32768) throw new HttpError(413, 'Use a smaller transcript');
    const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
    if (!body || body.model !== model || !Array.isArray(body.messages)
        || (body.stream !== undefined && typeof body.stream !== 'boolean')) {
      throw new HttpError(400, 'Check model, messages and stream');
    }
    const valid = body.messages.every((m: Message) => m
      && ['system', 'developer', 'user', 'assistant'].includes(m.role)
      && typeof m.content === 'string');
    if (!valid || !body.messages.some((m: Message) => m.role === 'user')) {
      throw new HttpError(400, 'This lab accepts text chat messages only');
    }
    const messages = [instruction, ...body.messages.filter(
      (m: Message) => m.role === 'user' || m.role === 'assistant'
    )];
    const stream = body.stream === true;
    console.log({ mode: upstream ? 'relay' : 'canned',
      roles: messages.map(m => m.role), stream });

    if (upstream) {
      const response = await fetch(upstream, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ model, messages, stream }),
        signal: AbortSignal.any([cancelled.signal, AbortSignal.timeout(30000)])
      });
      if (!response.ok || !response.body) {
        throw new HttpError(502, `Upstream failed: HTTP ${response.status}`);
      }
      const expected = stream ? 'text/event-stream' : 'application/json';
      if (!response.headers.get('content-type')?.includes(expected)) {
        await response.body.cancel();
        throw new HttpError(502, 'Unexpected upstream response type');
      }
      res.writeHead(200, { 'Content-Type': expected, 'Cache-Control': 'no-cache' });
      await pipeline(Readable.fromWeb(response.body), res);
      return;
    }

    const id = `chatcmpl-${randomUUID()}`;
    const created = Math.floor(Date.now() / 1000);
    const parts = ['Transport is connected. ',
      'This is a canned reply, not a model answer.'];
    if (!stream) {
      return json(res, 200, { id, object: 'chat.completion', created, model,
        choices: [{ index: 0, message: { role: 'assistant',
          content: parts.join('') }, finish_reason: 'stop' }] });
    }
    res.writeHead(200, {
      'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'
    });
    const event = (delta: object, finish_reason: string | null = null) => {
      res.write(`data: ${JSON.stringify({ id, created, model,
        object: 'chat.completion.chunk',
        choices: [{ index: 0, delta, finish_reason }] })}\n\n`);
    };
    event({ role: 'assistant' });
    for (const content of parts) {
      await delay(150, undefined, { signal: cancelled.signal });
      event({ content });
    }
    event({}, 'stop');
    res.end('data: [DONE]\n\n');
  } catch (error) {
    if (res.destroyed) return;
    if (res.headersSent) { res.destroy(); return; }
    const status = error instanceof HttpError ? error.status
      : error instanceof SyntaxError ? 400 : 502;
    json(res, status, { error: { message: error instanceof Error
      ? error.message : 'Request failed' } });
  }
}).listen(Number(process.env.LAB_PORT ?? 8787), '127.0.0.1', () => {
  console.log(`Chat lab ready; mode=${upstream ? 'relay' : 'canned'}`);
});
```

Start it with `npx tsx server.ts`. In another terminal, check each boundary:

```bash
curl -sS http://127.0.0.1:8787/health
curl -sS http://127.0.0.1:8787/v1/models
curl -N http://127.0.0.1:8787/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{"model":"contract-demo","messages":[{"role":"user","content":"Explain a context window."}],"stream":true}'
```

Expect `mode: canned`, one advertised model, then several `data:` events ending with `data: [DONE]`. Repeat the last request with `"stream":false`: the response should be one JSON object, with the fixed text under `choices[0].message.content`. An unknown model should return HTTP 400.

The console reports roles and response mode rather than copying the conversation into a log. Both user and assistant turns are retained, but their number and size still need a deliberate policy in a real application.

---

## Connect the interface, then add a model

For this loopback exercise, use an existing Open WebUI installation whose backend runs directly on the same host as `server.ts`. If you need an installation, follow the [Open WebUI quick start](https://docs.openwebui.com/getting-started/quick-start/) and select its host installation option.

1. In the admin connection settings, add an OpenAI-compatible connection with base URL `http://127.0.0.1:8787/v1`.
2. This lab does not authenticate requests. Leave the API key empty, or use a dummy value if the interface requires one. Never enter a real provider key into this lab.
3. Verify discovery, save the connection and select `contract-demo`. Use a plain text chat without tools, files, retrieval or other optional capabilities.
4. Send a question. The expected answer is the canned reply. A second question should produce the same reply; that is intentional.

Open WebUI's documented connection verification calls the model list. A successful verification therefore establishes less than a successful streamed conversation. Check the actual chat separately.

If Open WebUI runs in Docker, its `127.0.0.1` addresses the container. This host-only lab is not reachable there just by changing a URL: the listener must also be reachable across that network boundary. Keep this exercise on one host, or arrange a private container network and appropriate listener and authentication before extending it. The [provider connection guide](https://docs.openwebui.com/getting-started/quick-start/connect-a-provider/starting-with-openai-compatible/) covers host-address configuration.

To replace the canned reply, you can use an already running local Ollama server with a downloaded, text-chat-capable model. Its [compatibility documentation](https://docs.ollama.com/api/openai-compatibility) covers the local chat endpoint and streaming support. Stop the lab and restart it with the exact model ID installed on your machine:

```bash
CHAT_MODEL='your-installed-model-id' \
UPSTREAM_CHAT_URL='http://127.0.0.1:11434/v1/chat/completions' \
npx tsx server.ts
```

Replace the placeholder with your installed ID; it is not a model to download. Update the curl request's `model` field, refresh model discovery in Open WebUI and select that ID. The request now carries the application instruction and ordered history to Ollama. Only this mode calls a model API.

The relay forwards the response body using a stream pipeline, which handles backpressure instead of reading the entire answer first. Its 30-second deadline covers the whole upstream response, including the streamed body. A long answer from a slow local model is therefore cut off mid-stream. For slower models, raise the millisecond value in `AbortSignal.timeout(30000)`, for example to `120000` for two minutes, and choose a limit that fits your workload. The relay also cancels the upstream call when the client connection closes.

An HTTP or content-type error becomes a 502 before response headers are sent; a failure after streaming begins closes the connection. A production client must recognise an incomplete stream rather than present partial text as a completed answer.

---

## Understand what is being streamed

Server-sent events, or SSE, frame a response as text events separated by a blank line. Here each `data:` field contains a JSON chunk, and content chunks carry text in `choices[0].delta.content`. [MDN's SSE guide](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) explains the framing; [Ollama's compatibility implementation](https://github.com/ollama/ollama/blob/main/middleware/openai.go) shows its finish chunk and `[DONE]` marker.

A chunk may declare the assistant role, carry text or signal completion. It need not carry text every time. A network read can also split one event or combine several, so a client must assemble complete events before parsing their JSON. Do not equate a network chunk, an SSE event and a model token.

The demo deliberately sends two text fragments with a short delay. It proves that incremental events can travel through the interface; it measures neither model speed nor answer quality. In relay mode, events come from the upstream model server rather than the demo timer.

---

## What this means for you

Debug the first boundary that fails:

| Symptom | First check | What success would establish |
| --- | --- | --- |
| Health request cannot connect | Process, address and network boundary | The endpoint is reachable |
| No selectable model | `/v1/models` and the configured base URL | Discovery returns the expected ID |
| Chat returns 400 | Requested ID, message types and stream flag | The request matches this endpoint's input contract |
| Relay returns 502 | Upstream address, installed model and response type | The model server accepts and answers the call |
| Full response works; streaming fails | Content type, blank-line framing and intervening buffering | Incremental events reach the client correctly |
| Answer is fluent but wrong | Instructions, supplied evidence and evaluation examples | Transport success is followed by useful answer evaluation |

For an architect, the boundary also gives you a stable place to apply authentication, per-user access checks, request limits, timeouts and operational measurements. The sample binds to loopback and accepts only short text transcripts. It deliberately omits authentication, persistent memory, tools, images, usage reporting and generation controls beyond `stream`. Extra generation parameters are ignored. Do not expose it as a shared gateway or treat it as a complete provider implementation.

Do not add this extra endpoint when all you need is ordinary chat against an existing compatible model server: connecting Open WebUI directly may be enough. Add application logic when you need to own behaviour such as instruction policy, retrieval or controlled tools, and keep that logic behind an interface you can test.

---

## Questions developers ask

### Does a listed model mean the model server is healthy?

No. This lab advertises its configured ID without probing the upstream. Discovery, an actual model call and a completed stream are separate checks. In canned mode there is no upstream model at all.

### Why does the demo ignore my question?

Its fixed reply isolates the HTTP contract from model behaviour. Switch to the local model relay only after discovery and both response modes work. Then assess whether the supplied instructions and history produce an appropriate answer.

### Does this endpoint remember a conversation?

It uses the messages supplied with each request. It stores nothing between calls. Test with a second request that includes an earlier user turn and assistant reply, then compare it with a request that omits them.

### Where do LangChain and LangGraph enter the picture?

Once this flow is clear, you can compose model work inside the endpoint and later introduce explicit workflow state where the application needs it. Session 1 of the LangChain and LangGraph workshop establishes the Open WebUI contract in Python; later sessions extend the same assistant with composition, retrieval, tools and state.

[Enquire about the LangChain and LangGraph workshop](/courses/langchain-and-langgraph) to build that flow through guided, connected exercises.
