---
title: "Streaming"
description: "SSE streaming requests and the AI SDK chat transport."
canonical_url: "https://nuxt.mhaibaraai.cn/en/docs/api/stream"
---
# Streaming

> SSE streaming requests and the AI SDK chat transport.

## useApiStream

### Usage

`useApiStream` is the reactive shell around [`$api.stream()`](#apistream). It returns a lazy async generator: the request only starts once you begin iterating. Line buffering, multi-line `data:` concatenation, comment lines and `\r\n` handling are delegated to `eventsource-parser`; events that fail to parse are skipped silently — a heartbeat or handshake line should never break the whole stream.

```vue
<script setup lang="ts">
interface ChatChunk {
  content: string
  done: boolean
}

const text = ref('')
const { status, error, stream, abort } = useApiStream<ChatChunk>()

async function start() {
  text.value = ''

  for await (const chunk of stream('/chat', { method: 'POST', body: { message: 'Hello' } })) {
    text.value += chunk.content
  }
}
</script>

<template>
  <UButton :loading="status === 'streaming'" @click="start">Start</UButton>
  <UButton v-if="status === 'streaming'" @click="abort">Abort</UButton>
  <p>{{ text }}</p>
</template>
```

Starting a new stream aborts the previous one, and so does the component scope being disposed.

### How Accept and responseType are handled

> [!WARNING]
> 
> Both defaults were settled the hard way. Check your gateway's behaviour before changing them.

**Accept defaults to the wildcard — neither `application/json` nor `text/event-stream`.** ofetch automatically adds `Accept: application/json` whenever the body is JSON-serializable, which is simply the wrong claim for a request you intend to read as a stream: a backend negotiating on `Accept` may switch to its JSON renderer because of it. Sending `Accept: text/event-stream` instead gets the whole request rejected by those same backends (DRF, for instance) — verified against one that answers "cannot satisfy the Accept HTTP header" before any business logic runs. The wildcard avoids both. Gateways that need a specific value can pass one, and an explicit header always wins:

```ts
stream('/chat', { headers: { Accept: 'text/event-stream' } })
```

**`responseType: 'stream'` by default**: an event stream is read as a stream even when a gateway mislabels it as something other than `text/event-stream`. An `application/json` response (including HTTP 200 error envelopes like `{ code: 500 }`) is first restored to an object by the interceptor and then goes through business-code validation to surface the backend message, instead of turning into a stream that never yields anything.

A readable error is thrown when the response body is not a stream, so nothing spins silently.

### Errors and aborts

- Deliberate aborts (`abort()`, starting a new stream, scope disposal) are not errors: `status` becomes `'aborted'`, `error` stays `null` and iteration ends silently
- Any other error is written to `error`, sets `status` to `'error'`, calls `onError` and is then **re-thrown**, so a `try/catch` around `for await` can handle it
- Business errors (a `code` outside `successCodes`) are thrown by the interceptor before the stream starts, with the toast and the `movk:api:error` hook firing as usual

```ts
try {
  for await (const chunk of stream('/chat', { onError: e => console.error(e) })) {
    // ...
  }
}
catch (error) {
  // business error, HTTP error or broken stream
}
```

### $api.stream()

Outside components, or when reactive state is not needed, call `$api.stream()` directly:

```ts
const { $api } = useNuxtApp()

for await (const chunk of await $api.stream<ChatChunk>('/chat', { method: 'POST', body })) {
  console.log(chunk.content)
}
```

When the response is a stream the response interceptor short-circuits entirely — no unwrapping, no business-code check, no success toast — and `_data` is left untouched, so callers no longer need `unwrap` / `businessCheck`.

To plug into the AI SDK and `@nuxt/ui` Chat components, use [`createChatTransport`](https://nuxt.mhaibaraai.cn/en/docs/api/stream) instead.

### API

#### useApiStream()

##### Type Parameters

**T** (`unknown`): Type of a single chunk.

##### Returns

**status** (`Ref<ApiStreamStatus>`): 'idle' | 'streaming' | 'success' | 'error' | 'aborted'. Stays 'idle' until iteration starts.

**error** (`Ref<ApiError | Error | null>`): Error information; deliberate aborts are not written here.

**stream()** (`(url: string, options?: UseApiStreamOptions<T>) => AsyncGenerator<T>`): Starts the streaming request and yields chunks one by one.ParametersEndpoint name to use; defaults to defaultEndpoint.How to decode a single SSE event's data; return undefined to drop it. Defaults to a fault-tolerant JSON.parse.Failure callback; not triggered on deliberate aborts.Every other option is forwarded to ofetch: method, body, headers, query, responseType and so on.

**abort()** (`() => void`): Aborts the current stream and sets status to 'aborted'.

### Changelog

See commit history for [src/runtime/composables/streaming.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/composables/streaming.ts).

## createChatTransport

### Usage

`@nuxt/ui`'s `UChat*` components render AI SDK `UIMessage`s; all protocol parsing lives in the `ai` package and only understands the AI SDK's own UI Message Stream format. Internal gateways (MaxKB, Dify, FastGPT, in-house ones) each ship a different chunk shape, and `createChatTransport` fills exactly that gap: **your domain code writes one stateless `select`, everything else is inherited from the AI SDK's `HttpChatTransport`.**

> [!NOTE]
> 
> Install 
> 
> ai
> 
>  (an optional peer of 
> 
> @movk/nuxt
> 
> ) and 
> 
> @ai-sdk/vue
> 
> , then import from the 
> 
> @movk/nuxt/ai
> 
>  subpath — the main entry never pulls in the AI SDK.

```vue
<script setup lang="ts">
import { createChatTransport } from '@movk/nuxt/ai'
import { useChat } from '@ai-sdk/vue'

interface GatewayChunk {
  content: string
  node_id: string
  runtime_node_id: string
  node_is_end: boolean
  is_end: boolean
}

const transport = createChatTransport<GatewayChunk>({
  api: '/chat/completions',
  select: raw => ({
    id: raw.runtime_node_id,
    delta: raw.content,
    end: raw.node_is_end,
    finished: raw.is_end
  })
})

const { messages, status, error, sendMessage, stop } = useChat({ transport })
</script>
```

`createChatTransport` reads `$api` internally, so call it inside a setup scope.

### The select mapping

`select` is a pure function: given one backend chunk, it states which UI parts that chunk produces; return `undefined` to produce nothing. The lifecycle is handled by the transport — `start` is emitted once, text blocks are opened and closed per `id`, and every unclosed block plus `finish` is flushed when the stream ends, so a missing end signal or a broken connection never leaves the message stuck in streaming.

**id** (`string`): Text block id; deltas sharing an id are merged into one block. Omitted deltas go to the default block 'text-1'.

**delta** (`string`): Incremental text for this chunk; empty means no text-delta is emitted.

**end** (`boolean`): Closes that text block.

**data** (`{ type: string, value: unknown, transient?: boolean }`): An extra custom data part, emitted as data-${type}. With transient: true it only reaches useChat's onData callback and is never written to message history.

**finished** (`boolean`): Ends the whole stream; later chunks are ignored.

Workflow-style gateways often carry node information alongside the answer. Route it through a `data` part to drive progress without polluting the message history:

```ts
const transport = createChatTransport<GatewayChunk>({
  api: '/chat/completions',
  select: raw => ({
    id: raw.runtime_node_id,
    delta: raw.content,
    end: raw.node_is_end,
    finished: raw.is_end,
    data: { type: 'node', value: { nodeId: raw.node_id, nodeIsEnd: raw.node_is_end }, transient: true }
  })
})

const { messages } = useChat({
  transport,
  onData: (part) => {
    if (part.type === 'data-node') advanceStage(part.data)
  }
})
```

### Request orchestration

`api`, `headers`, `body`, `credentials`, `prepareSendMessagesRequest` and `prepareReconnectToStreamRequest` are the AI SDK `HttpChatTransport` options and behave identically. A private handshake (open a session first, then build the stream URL) belongs in `prepareSendMessagesRequest`, which may be async and may override `api`:

```ts
const transport = createChatTransport<GatewayChunk>({
  prepareSendMessagesRequest: async ({ messages }) => {
    const chatId = await $api<string>('/chat/open')

    return {
      api: `/chat_message/${chatId}`,
      body: { message: getTextFromMessage(messages.at(-1)!) }
    }
  },
  select
})
```

### Why the default fetch goes through $api

The injected default `fetch` is backed by `$api`, so endpoint baseURL, auth headers, business-code validation, error toasts and the `movk:api:*` hooks all apply. That is not only convenience: **some gateways return errors as HTTP 200 with a `{ code: 500 }` envelope**, which any `response.ok` check happily lets through before reading JSON as a stream and spinning forever. Through `$api` such a response throws at the business-code check and lands in `useChat`'s `onError`.

It also takes care of `Accept`: ofetch adds `Accept: application/json` whenever the body is JSON, which is the wrong claim for a stream, so the default is switched to the wildcard. An explicit `headers` entry always wins. See [`useApiStream`](https://nuxt.mhaibaraai.cn/en/docs/api/stream#how-accept-and-responsetype-are-handled) for the details.

Passing your own `fetch` overrides the default, `Accept` included.

### API

#### createChatTransport()

##### Type Parameters

**Raw** (`unknown`): Type of a single backend chunk.

**UI_MESSAGE** (`UIMessage`): Message type; defaults to the AI SDK UIMessage.

##### Parameters

**options** (`MovkChatTransportOptions<Raw, UI_MESSAGE>`) *required*: Pure mapping from a backend chunk to UI parts.Endpoint name to use; defaults to defaultEndpoint.How to decode a single SSE event's data; return undefined to drop it. Defaults to a fault-tolerant JSON.parse.api, headers, body, credentials, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest — same semantics as the AI SDK.

##### Returns

`ChatTransport<UI_MESSAGE>`, ready to hand to `useChat({ transport })`.

### Changelog

See commit history for [src/runtime/domains/ai/streaming.ts](https://github.com/mhaibaraai/movk-nuxt/commits/main/src/runtime/domains/ai/streaming.ts).


## Sitemap

See the full [sitemap](https://nuxt.mhaibaraai.cn/sitemap.md) for all pages.
