Sub topic 3
Streaming Tokens as They Are Generated
This chapter assumes basic Python, HTTP, JSON, and a local model server with a downloaded model. Streaming lets your program display generated text while the server is still producing it.
Streaming a response
Set stream to true. The client then returns chunks instead of one completed response. Each chunk may contain a small text fragment, so check that content exists before printing it.
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=60.0,
)
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Explain local inference briefly."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()Errors, timeouts, and retries
A connection error usually means that the server is stopped or the base URL is wrong. A not-found error often means that the model name or path is wrong. Set a timeout because generation can take time, and use limited retries for temporary failures.
import openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=60.0,
max_retries=2,
)
try:
result = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Say hello."}],
)
print(result.choices[0].message.content)
except openai.APIConnectionError:
print("Cannot reach the local server.")
except openai.NotFoundError:
print("Check the model name and the /v1 path.")
except openai.APIStatusError as error:
print(f"Server error: {error.status_code}")Creating embeddings locally
An embedding is a vector of numbers representing text. Servers that support embeddings usually provide an embeddings endpoint and require a separate embedding model.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
result = client.embeddings.create(
model="nomic-embed-text",
input=["private local data", "offline processing"],
)
print(len(result.data), len(result.data[0].embedding))Structured output and tool calling
Structured output asks for a predictable format such as JSON. Tool calling asks the model to describe a function call. Local servers differ widely in their support, grammar controls, and response format. Test the exact model and server before depending on these features.
> Callout note > Compatibility means the request shape is similar. It does not guarantee identical features, tokenization, model behavior, or error messages.
Differences and troubleshooting
Check the server documentation for supported parameters. Common failures include:
- Wrong base URL or a missing /v1 path.
- A model that has not been downloaded.
- A model identifier that differs from the displayed name.
- Unsupported streaming, embeddings, tools, or response-format options.
- Context limits, memory shortages, or a request timeout.
Exercise
A request returns 404. What should you check first?
Show answer
Confirm the base URL includes the required /v1 path and that the model name matches one reported by the server.