CookbookStream in Python

Stream in Python

Two versions: with the openai client library pointed at Syntic, and with plain requests when you want no extra dependency or need full control of the events.

# pip install openai
import os
import sys
 
from openai import OpenAI
 
client = OpenAI(base_url="https://app.syntic.ai/v1", api_key=os.environ["SYNTIC_API_KEY"])
 
stream = client.chat.completions.create(
    model="Amara S1.2",
    stream=True,
    messages=[{"role": "user", "content": "Explain how a bicycle derailleur works in 5 sentences."}],
)
 
usage = None
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        sys.stdout.write(chunk.choices[0].delta.content)
        sys.stdout.flush()
    if getattr(chunk, "usage", None):
        usage = chunk.usage
print()
print("usage:", usage)

Notes

  • Check the status code before reading events. Errors such as 401, 402 and 429 arrive as a normal JSON body.
  • A stream that ends without data: [DONE], or with an event carrying error, is incomplete. Retry it or tell the user.
  • usage arrives on a chunk near the end. Keep the last one you see.
  • Set a read timeout long enough for slow replies; five minutes is a safe ceiling for long answers.
Was this page helpful?