Stop Waiting for the Full AI Response: Stream Tokens in Python A developer demonstrates how to stream tokens from OpenAI-compatible APIs in Python, showing that adding stream=True to a chat completion request returns chunks that can be printed as they arrive, improving perceived responsiveness. The pattern was tested with an OpenAI-compatible endpoint through APIHubRelay. Most AI applications wait for the model to generate the complete answer before showing anything to the user. For short answers, that may be acceptable. For longer responses, it can make the application feel slow—even when the model is already generating tokens. Streaming solves this by displaying each part of the response as soon as it arrives. A standard OpenAI-compatible request may look like this: python import os from openai import OpenAI client = OpenAI api key=os.environ "AI API KEY" , base url=os.environ "AI BASE URL" , response = client.chat.completions.create model=os.environ "AI MODEL" , messages= { "role": "user", "content": "Explain API gateways in three sentences.", } , print response.choices 0 .message.content This works, but nothing is printed until the complete response has arrived. Enable streaming by adding stream=True : stream = client.chat.completions.create model=os.environ "AI MODEL" , messages= { "role": "user", "content": "Explain API gateways in three sentences.", } , stream=True, The request now returns a sequence of chunks instead of one completed response. Loop through those chunks and print the available content: for chunk in stream: content = chunk.choices 0 .delta.content if content: print content, end="", flush=True print The user can now see the answer while it is being generated. python import os from openai import OpenAI client = OpenAI api key=os.environ "AI API KEY" , base url=os.environ "AI BASE URL" , stream = client.chat.completions.create model=os.environ "AI MODEL" , messages= { "role": "user", "content": "Explain API gateways in three sentences.", } , stream=True, for chunk in stream: content = chunk.choices 0 .delta.content if content: print content, end="", flush=True print Keeping the API key, base URL, and model name in environment variables also makes it easier to change providers without rewriting the application logic. Streaming is especially helpful for: Remember that model capabilities and streaming formats can vary between providers. Verify support for your selected model and handle empty chunks, connection failures, and interrupted streams before using this pattern in production. I tested this pattern with an OpenAI-compatible endpoint through APIHubRelay https://apihubrelay.com/ . What should the next example cover: streaming in Node.js, error handling, or automatic retries?