Inference

Streaming

Stream the answer first, then show an ad if Koah requests one.

Koah Free Inference supports incremental model output, so users can start reading before the full answer is ready. Use it for chat, writing assistants, and coding tools.

Start with the quickstart for your API key, model, and SDK setup.

Enable streaming

Set stream to true and read the output as it arrives. The SDK examples print the ad ID after the answer completes.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://inference.koah.ai/v1",
    api_key=os.environ["KOAH_INFERENCE_API_KEY"],
)

raw = client.chat.completions.with_raw_response.create(
    model="sail/DeepSeek-V4.1-Flash-1017-free",
    messages=[{"role": "user", "content": "Explain how solar panels work."}],
    stream=True,
)

finish_reason = None

with raw.parse() as stream:
    for chunk in stream:
        if not chunk.choices:
            continue
        choice = chunk.choices[0]
        print(choice.delta.content or "", end="", flush=True)
        if choice.finish_reason:
            finish_reason = choice.finish_reason

if finish_reason != "stop":
    raise RuntimeError("The answer did not finish completely.")
print("\nAd ID:", raw.headers.get("X-Koah-Ad-Id"))

--no-buffer lets cURL display incoming events immediately. --include shows the response headers, including the ad ID. The SDKs parse the events for you. Empty deltas and chunks without choices are not answer text.

Render the ad after the answer finishes

When Koah returns an ad ID, forward it separately from the text. We strongly recommend waiting until the full answer has arrived before calling displayAd, so the ad appears beside a finished response. Call it once for the returned ID, never per token.

Your server must send an explicit completion event. A successful HTTP status or a closed connection alone does not prove the answer is complete.

Use newline-delimited JSON between your server and browser, not raw provider events. Send {"type":"delta","text":"..."} for text and {"type":"complete"} only after verifying the provider's successful stop reason. This framing belongs to your app, not the Koah inference API.

For Chat Completions, wrap the stream and response returned by .withResponse() above in your server route instead of printing the chunks:

Server · JavaScript

function forwardStream(stream, response) {
  const encoder = new TextEncoder()
  const body = new ReadableStream({
    async start(controller) {
      const send = (event) => controller.enqueue(
        encoder.encode(JSON.stringify(event) + '\n'),
      )
      let finishReason = null
      try {
        for await (const chunk of stream) {
          const choice = chunk.choices[0]
          if (!choice) continue
          if (choice.delta.content) send({ type: 'delta', text: choice.delta.content })
          if (choice.finish_reason) finishReason = choice.finish_reason
        }
        if (finishReason !== 'stop') throw new Error('Incomplete answer.')
        send({ type: 'complete' })
        controller.close()
      } catch (error) {
        controller.error(error)
      } finally {
        stream.controller.abort()
      }
    },
    cancel() {
      stream.controller.abort()
    },
  })
  const headers = new Headers({ 'Content-Type': 'application/x-ndjson' })
  const adId = response.headers.get('X-Koah-Ad-Id')
  if (adId) headers.set('X-Koah-Ad-Id', adId)
  return new Response(body, { headers })
}

Return forwardStream(stream, response) from your route.

For Messages, require both message_stop and end_turn before sending complete. On a failure, error the stream and never send complete. An absent ad ID means no ad was requested.

Browser · JavaScript

async function renderStream(response, answerTarget, adTarget) {
  if (!response.ok || !response.body) throw new Error('Could not start the answer.')

  const adId = response.headers.get('X-Koah-Ad-Id')
  answerTarget.textContent = ''
  answerTarget.dataset.state = 'incomplete'
  let pending = ''
  let completed = false

  function readEvent(line) {
    if (!line.trim()) return
    if (completed) throw new Error('Unexpected event after completion.')
    const event = JSON.parse(line)
    if (event.type === 'delta' && typeof event.text === 'string') {
      answerTarget.textContent += event.text
    } else if (event.type === 'complete') {
      completed = true
    } else {
      throw new Error('Invalid or failed answer stream.')
    }
  }

  for await (const text of response.body.pipeThrough(new TextDecoderStream())) {
    pending += text
    let newline
    while ((newline = pending.indexOf('\n')) !== -1) {
      readEvent(pending.slice(0, newline))
      pending = pending.slice(newline + 1)
    }
  }
  if (pending.trim()) readEvent(pending)
  if (!completed) throw new Error('The answer did not finish completely.')
  answerTarget.dataset.state = 'complete'

  if (adId) {
    await window.koah.displayAd(adId, { target: adTarget })
  }
}

Handle a rejected renderStream call in your app's error UI. When answerTarget.dataset.state is incomplete, show an incomplete-answer label. A failed ad render leaves the state as complete and preserves the answer.

Keep the answer visible if ad rendering fails. If no ad ID is returned, stream the answer without calling the ad renderer. See the quickstart for SDK setup and the proposed rendering APIs.

Handle incomplete responses

A successful HTTP status does not guarantee a complete answer. Check how the model stopped: stop for the Chat Completions examples, or end_turn for the Messages example. A token limit or interrupted connection can leave partial output.

Keep partial text visible and mark it as incomplete. Complete or retry the answer before showing its ad. A retry starts a new generation; do not append it to the old answer or reuse the old response's ad ID. Cancel the server's model request when the user stops generation.

See request errors for recovery guidance, or Ads and Validation for display requirements.

Was this helpful?