Sub topic 2
Sending Your First Chat Completion
Assume you know basic Python, JSON, and HTTP requests. You also need a local model server running with a model already downloaded. This example uses Ollama at its default address.
Sending a chat completion
A chat completion is a generated assistant message based on a list of messages. Configure the OpenAI Python client with your local server's URL instead of OpenAI's hosted URL.
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)The base_url points to the local server's OpenAI-compatible endpoint. The API key is a placeholder because many local servers do not authenticate requests, but the client requires a value. Replace llama3.2 with a model name that your server provides.
System, user, and assistant messages
A message has a role and content.
- A
systemmessage sets behavior and general instructions. - A
usermessage contains the current request. - An
assistantmessage records an earlier model response.
Include earlier assistant replies when continuing a conversation:
messages = [
{"role": "system", "content": "Answer in short paragraphs."},
{"role": "user", "content": "What is a context window?"},
{"role": "assistant", "content": "It is the amount of text a model can process at once."},
{"role": "user", "content": "Why does its size matter?"},
]The server does not remember history automatically between separate requests. Your application must send the relevant messages each time.
Controlling output
temperature controls randomness. Lower values usually produce more predictable text. Higher values allow more variation. max_tokens limits the generated response length; it does not limit the input messages.
Exercise
Which message role should contain the user's current question, and what does temperature control?
Show answer
The current question belongs in a user message. Temperature controls how varied or predictable the generated response is.