Sub topic 5
Sending your first chat completion
This chapter covers the chat completion request and the response it returns. It uses the raw HTTP form first, then the Python client. It assumes you can run Python with pip, read JSON, and have a local server such as Ollama running with the llama3.2 model downloaded. It also assumes you have already pointed the client at your server's base URL. Streaming, sampling and error handling get their own chapters, so this one stays on the basic request and reply.
What a chat completion is
A chat completion is a single request in which you send a list of messages and the server returns the next message in the conversation. The server holds no memory between calls. Every request must carry all the context the model needs.
The endpoint is POST /v1/chat/completions. With Ollama on its default port, the full URL is http://localhost:11434/v1/chat/completions. The request body is JSON with two required fields:
model: the name of the model the server should use.messages: a list of objects, each with aroleand acontent.
Everything else is optional, and the server applies its own defaults for any field you leave out.
The raw HTTP request
Start with curl, so you can see exactly what travels over the wire.
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "llama3.2", "messages": [{"role": "user", "content": "Say hello in one sentence."}]}'The Content-Type header tells the server the body is JSON. No Authorization header is sent here because Ollama does not check keys. Some servers do require one, which the base URL and key chapter covers.
The server replies with JSON shaped like this. Exact values will differ, and some servers add extra fields.
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1764249247,
"model": "llama3.2",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! It's nice to meet you."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 31,
"completion_tokens": 10,
"total_tokens": 41
}
}Reading the response
| Field | Meaning |
|---|---|
| `id` | An identifier for this completion. Useful in logs. |
| `object` | The type of the object. For this endpoint it is `chat.completion`. |
| `created` | A Unix timestamp in seconds. |
| `model` | The model that produced the reply. Some servers echo the name you sent, others report an internal name. |
| `choices` | A list of candidate replies. Normally it holds one item. |
| `choices[0].message` | The assistant's reply, with `role` and `content`. |
| `choices[0].finish_reason` | Why generation stopped. |
| `usage` | Token counts for the prompt and the reply. |
A token is a chunk of text, often a word or part of a word. Models read and write tokens, not characters. The usage block tells you how much of the model's context window you consumed. The context window is the maximum number of tokens the model can handle in one request, prompt and reply together.
Finish reasons
The finish_reason tells you whether you got a complete answer.
| Value | Meaning |
|---|---|
| `stop` | The model finished naturally, or hit a stop sequence. |
| `length` | Generation reached the `max_tokens` limit or the context limit. The reply is probably cut off. |
| `tool_calls` | The model asked to call a tool. A later chapter covers this. |
Check for length whenever you cap output. A truncated answer looks like a valid answer unless you test for it.
The same call in Python
The OpenAI Python package is a thin wrapper around this HTTP call. Install it with pip install openai. Then send a request with a system message and a user message.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a context window is."},
],
temperature=0.2,
max_tokens=200,
)
print(response.choices[0].message.content)Walk through what happens:
OpenAI(...)builds a client. Thebase_urlends in/v1, and the client appends/chat/completionsto it. Theapi_keyis a placeholder, since the client refuses to start without a value.create(...)serializes your arguments to JSON and sends the POST request.- The client parses the JSON reply into a typed object. You reach fields with attribute access, such as
response.choices[0].message.content, instead of dictionary keys.
The call blocks until the whole reply has been generated. On a laptop with a small model, that can take several seconds. The first request after the server starts is often slower, because the server loads the model into memory.
Inspecting the whole response
Printing only the content hides useful details. This version also reports the finish reason and token usage, and warns when the reply was cut off.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Name three uses of a local LLM."}],
max_tokens=60,
)
choice = response.choices[0]
print(choice.message.content)
print("finish_reason:", choice.finish_reason)
if response.usage:
print("prompt tokens:", response.usage.prompt_tokens)
print("reply tokens:", response.usage.completion_tokens)
if choice.finish_reason == "length":
print("Warning: the reply was truncated. Raise max_tokens.")The if response.usage: guard matters. The usage field is optional in the client's types, and a server may leave it out.
You can also dump the full response as a dictionary with response.model_dump(). That is the quickest way to see any extra, server-specific fields.
How the server uses your messages
The server does not feed the list of messages to the model as separate objects. It flattens them into one block of text using a chat template. A chat template is a model-specific format that wraps each message in special marker tokens, so the model can tell which role said what. The server normally picks the right template for the model, so you do not write it yourself.
This has two consequences:
- Different models can react differently to the same
messages. Some models treat the system message weakly, and a few older ones have no system role at all. - Every call re-sends and re-processes the full history. A long conversation costs more time per call, and it can eventually exceed the context window.
The next chapter covers roles and conversation history in detail. For now, remember that one request equals one complete prompt.
Choosing a model name
The model value must match a name the server knows. On Ollama, the names are those shown by ollama list, such as llama3.2 or llama3.2:3b. A bare name like llama3.2 resolves to the latest tag.
If the name does not match, a typical Ollama server returns HTTP 404 with a message that the model was not found. Other servers behave differently. Some ignore the model field when they serve only one model, and some return a 400 error. If you are unsure, list the models first, as shown in the previous chapter, and copy the ID exactly.
Common mistakes
- Missing
/v1in the base URL. The client then calls/chat/completionson the server root, and you get a 404. - Wrong port. Ollama uses 11434. LM Studio,
llama-serverand vLLM use different defaults, so check your server's startup output. - Using the wrong response path. The reply is at
response.choices[0].message.content, notresponse.messageorresponse.text. - Ignoring
finish_reason. A reply that stopped because oflengthis incomplete. - Sending the model name of a hosted service. Names such as
gpt-4omean nothing to a local server. - Assuming the first call is representative. Time the second call, after the model is loaded.
Putting it together
The following script wraps the pattern into a small function. It sends one question, checks the finish reason, and returns the text.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
def ask(question: str, model: str = "llama3.2", max_tokens: int = 150) -> str:
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "Answer in at most two sentences."},
{"role": "user", "content": question},
],
max_tokens=max_tokens,
)
choice = response.choices[0]
text = choice.message.content or ""
if choice.finish_reason == "length":
text += " [truncated]"
return text
if __name__ == "__main__":
print(ask("Why run a language model locally?"))The or "" handles the case where `content can happen when a model returns a tool call instead of text.
Exercises
Exercise
Your reply ends in the middle of a sentence, and finish_reason is length. Name two possible causes and one fix.
Show answer
The max_tokens value you set was too low, or the prompt plus reply reached the model's context window. Raise max_tokens if it was the cause, or shorten the prompt or history if the context limit was reached. Some servers also let you raise the context size in their own settings.
Exercise
A call to a local server returns a 404 error. The server is running and the model is downloaded. What do you check first?
Show answer
Check the base URL. It must include the /v1 path, for example http://localhost:11434/v1. Then check that the model string matches the name the server lists exactly, including any tag.
Exercise
Write the expression that returns the assistant's text from a response object named response, and explain why the [0] is there.
Show answer
response.choices[0].message.content. The choices field is a list of candidate replies, so [0] selects the first one. Normal requests return exactly one choice.