Sub topic 3
Handling Streamed Responses and Custom Ollama Models
Assume you have Ollama installed, its server running, and basic HTTP and JSON knowledge. A streamed response arrives as several newline-delimited JSON objects instead of one complete object. Each object contains a small part of the answer.
Handling streamed responses
The chat endpoint streams by default. Read each line, parse it as JSON, and append message.content. The final object has "done": true.
curl http://localhost:11434/api/chat -d '{
"model": "llama3.2",
"messages": [{"role": "user", "content": "What is quantization?"}]
}'Use "stream": false when your program needs one JSON response. Streaming improves perceived speed, but your client must handle partial output and connection errors.
OpenAI-compatible clients and embeddings
Ollama exposes an OpenAI-compatible endpoint at /v1. The key is required by the client library but is ignored by Ollama.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
result = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Give one clear writing tip."}],
)
print(result.choices[0].message.content)Embeddings convert text into numeric vectors. Applications use these vectors to compare meaning, often for search or retrieval. Ollama provides an embeddings endpoint for models that support embeddings.
Writing and running a Modelfile
A Modelfile describes a customized model. FROM selects the base model, PARAMETER changes generation behavior, and SYSTEM supplies a default instruction.
FROM llama3.2
PARAMETER temperature 0.3
PARAMETER num_ctx 4096
SYSTEM You answer in at most three sentences.Build and run it:
ollama create concise-assistant -f Modelfile
ollama run concise-assistantYou can also import compatible GGUF weights, a file format commonly used for quantized models:
ollama create my-model -f ModelfileSet the Modelfile's FROM line to the local GGUF path when importing your weights.
Server configuration and troubleshooting
Configure the server with environment variables. OLLAMA_HOST controls the listening address, OLLAMA_KEEP_ALIVE controls how long models remain loaded, and OLLAMA_MODELS changes the model storage directory.
OLLAMA_HOST=127.0.0.1:11434 OLLAMA_KEEP_ALIVE=10m ollama serve| Problem | Likely cause | First check |
|---|---|---|
| Out of memory | Model or context is too large | Use a smaller or more quantized model |
| Slow responses | CPU execution or model swapping | Run `ollama ps` and reduce `num_ctx` |
| Connection refused | Server is stopped or address differs | Check `curl http://localhost:11434/api/tags` |
Exercise
Why might a program set "stream": false?
Show answer
It receives one complete JSON response, which is simpler to parse when incremental output is unnecessary.