Docs / Serverless

Streaming outputs

Generator handlers can yield partial outputs while the job is running: tokens from an LLM, frames from a renderer, or progress from a batch job. Clients read them from /stream/{jobId}.

Write a generator handler

handler.py
import apipods
from transformers import AutoTokenizer, TextIteratorStreamer
from threading import Thread

tokenizer, model = load_model()  # module level: runs once per worker


def handler(job):
    prompt = job["input"]["prompt"]
    streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
    inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
    Thread(target=model.generate, kwargs={**inputs, "streamer": streamer, "max_new_tokens": 512}).start()
    for text in streamer:
        yield {"text": text}


apipods.serverless.start({"handler": handler, "return_aggregate_stream": True})

Each yield becomes one chunk. With return_aggregate_stream set to True, the job's final output is the list of all chunks, so clients that only call /status still get the full result. Without it, output is null for generator handlers.

Read chunks by polling

GET /stream/{jobId} returns the chunks produced since your previous call, plus the job status. Keep calling it until the status is terminal.

cURL
curl https://run.apipods.com/v1/ep_llama70b/stream/job_3x9wq2mt \
  -H "Authorization: Bearer $APIPODS_API_KEY"
200 OK
{
  "status": "IN_PROGRESS",
  "stream": [
    {
      "output": {
        "text": "The lighthouse"
      }
    },
    {
      "output": {
        "text": " stood on"
      }
    }
  ]
}

Server-sent events

Send Accept: text/event-stream to keep the connection open and receive each chunk as it is produced. The stream ends with a done event carrying the final job status.

Terminal
$ curl -N https://run.apipods.com/v1/ep_llama70b/stream/job_3x9wq2mt \
  -H "Authorization: Bearer $APIPODS_API_KEY" \
  -H "Accept: text/event-stream"

event: chunk
data: {"output":{"text":"The lighthouse"}}

event: chunk
data: {"output":{"text":" stood on"}}

event: done
data: {"id":"job_3x9wq2mt","status":"COMPLETED"}

With the SDKs

import apipods

client = apipods.Client()
ep = client.endpoint("ep_llama70b")

job = ep.run({"prompt": "Describe a lighthouse in one paragraph."})
for chunk in job.stream():  # uses server-sent events, reconnects automatically
    print(chunk["text"], end="", flush=True)

Notes

  • Chunks are buffered for the job's result retention period, so a client that connects late still receives every chunk.
  • Each chunk can be up to 1 MB. Batch very small chunks (for example, a few tokens at a time) to reduce overhead.
  • For chat models, the vLLM worker's OpenAI-compatible route streams in the standard OpenAI format instead.