How to Stream an AI API Response in Python

Level: Intermediate
Time to read: 15 minutes
Track: Python for AI

Priya already has a Python script that sends a fee-reminder prompt and waits for the full reply, as in Your First AI Program in Python. On a slow day that wait feels long: the terminal sits blank, then a whole paragraph appears at once. Streaming changes that. The API sends the message a few characters at a time, and your script can print each piece as it arrives.

This lesson shows how to call the same OpenAI-compatible chat-completions endpoint with "stream": true, using the requests library. You will read AI_API_KEY from an environment variable, parse the server-sent events the API returns, and join choices[0].delta.content into the finished text. We will not hardcode a key, and we will not let the model invent the rupee amount.

Key takeaways

  • Add "stream": true to the request JSON so the API sends tokens as they are generated.
  • Each event is a line starting with data:. The stream ends with data: [DONE].
  • The next piece of text is usually at choices[0].delta.content, not message.content.
  • Call requests.post(..., stream=True) and decode each line as UTF-8 so a rupee sign stays readable.
  • Keep AI_API_KEY in the environment, and put official names and amounts into the prompt from your own data.

What streaming changes

A normal chat call, like the first Python lesson, waits until the model has finished, then returns one JSON object. The text you want is at choices[0].message.content.

A streaming call is still a POST to {base url}/v1/chat/completions, with the same model and messages. You add one field:

{
  "model": "gpt-4o-mini",
  "messages": [
    {
      "role": "system",
      "content": "You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts."
    },
    {
      "role": "user",
      "content": "Write a 2-sentence reminder that Ananya Sharma has a balance of ₹1,200 for November tuition."
    }
  ],
  "max_tokens": 200,
  "stream": true
}

The response is no longer one JSON object. It is a stream of server-sent events (SSE). Each event is a line that starts with data:, usually followed by a blank line. Most lines hold a small JSON object. The last event is the token [DONE]:

data: {"choices":[{"delta":{"content":"Dear par"},"index":0}]}
data: {"choices":[{"delta":{"content":"ent, Ana"},"index":0}]}
data: [DONE]

The next fragment of the reminder is in choices[0].delta.content. Early chunks may have a role and no text; later chunks carry the words. Join the content strings in order to get the same finished message you would have received without streaming.

Keep the API key in the environment

The request is still authorized with a header:

Authorization: Bearer YOUR_KEY_HERE

The key belongs in the environment, never in the Python file, just as in the first Python lesson.

import os
def api_key_from_env(name='AI_API_KEY', env=None):
    source = os.environ if env is None else env
    key = source.get(name)
    if not key:
        raise RuntimeError(
            f'Missing API key. Set the {name} environment variable. '
            'Do not hardcode the key in Python files.'
        )
    return key

Export it in the shell before you run the script, and point the base URL at a local mock while you practise:

export AI_API_KEY="paste-the-key-here"
export AI_API_BASE="http://127.0.0.1:8000"
python stream_reminder.py

You can also read the model name from the environment, with a sensible default:

base_url = os.environ.get('AI_API_BASE') or 'https://api.openai.com'
model = os.environ.get('AI_MODEL') or 'gpt-4o-mini'

Parse the stream with requests

Two details matter in the HTTP client. You must pass stream=True to requests.post, or the library will wait for the whole body before you can read a line. And you should decode each line as UTF-8 yourself, so a rupee sign is not garbled if the server omits a charset.

import json
import requests
def build_chat_request(model, messages, max_tokens=200, stream=True):
    body = {
        'model': model,
        'messages': messages,
        'stream': stream,
    }
    if max_tokens is not None:
        body['max_tokens'] = max_tokens
    return body
def reminder_messages(student, balance, month):
    formatted = f'{balance:,}'
    return [
        {
            'role': 'system',
            'content': 'You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts or dates.',
        },
        {
            'role': 'user',
            'content': f'Write a 2-sentence reminder that {student} has a balance of ₹{formatted} for {month} tuition.',
        },
    ]
def iter_sse_data(response):
    for raw_line in response.iter_lines():
        if not raw_line:
            continue
        line = raw_line.decode('utf-8')
        if not line.startswith('data:'):
            continue
        data = line[5:].strip()
        if data == '[DONE]':
            break
        yield data
def delta_content(chunk):
    choices = chunk.get('choices') or []
    if not choices:
        return None
    delta = choices[0].get('delta') or {}
    text = delta.get('content')
    if isinstance(text, str) and text:
        return text
    return None
def stream_chat_completions(base_url, api_key, payload, timeout=30):
    url = base_url.rstrip('/') + '/v1/chat/completions'
    with requests.post(
        url,
        headers={
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + api_key,
            'Accept': 'text/event-stream',
        },
        json=payload,
        stream=True,
        timeout=timeout,
    ) as response:
        if response.status_code < 200 or response.status_code >= 300:
            try:
                decoded = response.json()
                message = decoded.get('error', {}).get('message') or ('HTTP ' + str(response.status_code))
            except ValueError:
                message = 'HTTP ' + str(response.status_code)
            raise RuntimeError('API error: ' + message)
        got_text = False
        for data in iter_sse_data(response):
            try:
                chunk = json.loads(data)
            except json.JSONDecodeError:
                raise RuntimeError('The API did not return valid JSON in the stream.')
            if isinstance(chunk, dict) and chunk.get('error'):
                err = chunk['error']
                message = err.get('message') if isinstance(err, dict) else str(err)
                raise RuntimeError('API error: ' + message)
            text = delta_content(chunk)
            if text:
                got_text = True
                yield text
        if not got_text:
            raise RuntimeError('The API stream had no message content.')

Error handling still comes in layers. A timeout or DNS failure is raised by requests before you have any events. A 401 or 500 may arrive as ordinary JSON, not as SSE, which is why the status code is checked first. A stream that ends without a single delta.content string should be treated as a failure, so you do not show a parent a blank note.

Put it together for a fee reminder

api_key = api_key_from_env()
base_url = os.environ.get('AI_API_BASE') or 'https://api.openai.com'
payload = build_chat_request(
    os.environ.get('AI_MODEL') or 'gpt-4o-mini',
    reminder_messages('Ananya Sharma', 1200, 'November'),
)
parts = []
try:
    for piece in stream_chat_completions(base_url, api_key, payload):
        print(piece, end='', flush=True)
        parts.append(piece)
    print()
except RuntimeError as exc:
    print('Could not write the reminder just now. Please try again or send it by hand.')
    raise SystemExit(1) from exc
full = ''.join(parts)

The rupee figure is formatted in Python with f'{balance:,}', then placed in the prompt — 1200 becomes ₹1,200. print(..., end='', flush=True) writes each fragment at once, without waiting for a newline, so Priya sees the reminder grow in the terminal. The joined string full is what you would store, email, or escape for a web page.

Try this

First run the script without setting AI_API_KEY. You should get the missing-key error, not a network request. Then set a fake key and point AI_API_BASE at a local mock, or at a real compatible endpoint if you already have an account. Change the input so the balance is ₹2,450 and the student is Rahul Iyer. Confirm that the pieces print one after another, and that the joined reply mentions ₹2,450 and does not invent a different amount.

How this was tested

On Python 3.13 with the requests library, the request builder produced valid JSON with "stream": true, and an empty AI_API_KEY raised the missing-key error. The streaming call was then pointed at a local mock of POST /v1/chat/completions: a matching Bearer token returned HTTP 200 and several SSE chunks that joined to a ₹1,200 reminder; a wrong token returned HTTP 401 and the function raised API error: Invalid API key. No paid API was called here, so run one live call against your own provider before you rely on it.

What you learned

  • A streaming chat call is a POST of JSON to /v1/chat/completions with "stream": true.
  • The API sends SSE lines. Each text fragment is usually at choices[0].delta.content, and the stream ends with [DONE].
  • requests.post(..., stream=True) lets you read those lines as they arrive. Decode them as UTF-8.
  • The API key still belongs in an environment variable, never in the source file.
  • Official amounts and names go into the prompt from your own data. Join the chunks if you need the finished message.

Quick quiz

  1. 1. Which request field tells the API to send tokens as they are generated?

    • A) "stream": true
    • B) "max_tokens": 1
    • C) "stream": false
    Show answer

    A. max_tokens only caps the length. "stream": false (or omitting the field) waits for the full message.

  2. 2. In a stream chunk, where is the next piece of text usually found?

    • A) choices[0].message.content
    • B) choices[0].delta.content
    • C) error.message
    Show answer

    B. A non-streaming response uses message.content. Each streaming event uses a delta. Join the content strings in order to rebuild the full reply.

  3. 3. Why pass stream=True to requests.post?

    • A) So requests waits until [DONE] before returning anything
    • B) So you can read SSE lines as they arrive, instead of waiting for the full body
    • C) So the API key is hidden from the server log
    Show answer

    B. Without stream=True, requests buffers the whole response. That cancels the benefit of a streaming API.

  4. 4. Where should AI_API_KEY live?

    • A) In a string at the top of stream_reminder.py
    • B) In the process environment, read with os.environ
    • C) Printed at the start of the stream, so you can confirm it was sent
    Show answer

    B. A key in the file can leak through backups or git history. Never print it, including while you debug a stream.

Related lessons