Call an LLM From Python and See Why the API Forgets
The problem: every agent starts with one API call you need to understand
Before an agent can plan, use tools or remember anything, it has to talk to a language model. That part looks trivial: send some text, get some text back. But the shape of that exchange decides everything you will build in this course. If you misunderstand it, your agent will forget the user's name between two messages, lose track of tool results, or send far more text than it needs to.
The core surprise for most people is this: the chat completions API has no memory. Each request stands alone. The model does not remember the previous request, your session, or the person typing. Anything that looks like memory is your code sending the earlier messages again.
In this lesson you will set up a free local model, make your first call from Python, watch the API forget, and then fix it by keeping the conversation yourself. If you want the theory behind agents first, the LLM Fundamentals course on BlogLLM covers what an agent is; this course is about building one.
What you will build in this course
Across 15 lessons you will build a small trip helper agent in plain Python. It checks a (made-up) weather table, converts money with (made-up) exchange rates, searches a (made-up) hotel list, remembers the traveller's preferences, and later connects to tools over MCP. All data is fictional so you can run everything offline.
There is no agent framework. You will use:
- the official
openaiPython SDK, which speaks the chat completions format - any server that speaks that format: by default a local Ollama server, so it costs nothing
pydantic,numpyand themcpSDK in later lessons
The code in every lesson was run and tested with qwen2.5 (the 1.5B version) via Ollama on a CPU only machine. A model that small is a good stress test, because its mistakes show up clearly, and every failure it made is reported in the lessons. Larger and hosted models were not tested.
Set up a free local model with Ollama
Ollama runs open models on your own machine and exposes an endpoint that accepts the same requests as the OpenAI API. Its documentation lists support for chat completions, streaming, JSON mode, tools and embeddings on its /v1 endpoints.
Install Ollama from its website, then pull a small chat model and a small embedding model (you need the embedding model from lesson 8 on):
bashollama pull qwen2.5:1.5b ollama pull all-minilm
If the Ollama app is not already running in the background, start the server in a separate terminal with ollama serve. It listens on http://localhost:11434.
Now create a project folder with a virtual environment and the libraries for the whole course:
bashpython -m venv .venv source .venv/bin/activate pip install openai pydantic numpy mcp
On Windows, activate with .venv\Scripts\activate instead.
One config file for every lesson
Every lesson imports its client from one small file, so switching providers means changing environment variables, not code. Save this as llm.py in your project folder:
python# file: llm.py import os from openai import OpenAI # Defaults point at a local Ollama server. Override with environment variables # to use OpenAI or any other OpenAI-compatible provider. client = OpenAI( base_url=os.getenv("AGENT_BASE_URL", "http://localhost:11434/v1"), api_key=os.getenv("AGENT_API_KEY", "ollama"), # Ollama ignores the key ) MODEL = os.getenv("AGENT_MODEL", "qwen2.5:1.5b")
Three things are worth noticing:
base_urlis the only thing that makes this "Ollama" instead of "OpenAI". The SDK appends paths like/chat/completionsto it.- Ollama does not check the API key, but the SDK requires one, so any string works locally.
- The model name is just a string the server understands. On Ollama it is the name you pulled.
Switch to OpenAI or another provider
To use a hosted provider, set the three variables before running any lesson:
bashexport AGENT_BASE_URL="https://api.openai.com/v1" export AGENT_API_KEY="your-api-key" export AGENT_MODEL="a-model-your-provider-lists"
The code is written for any provider with an OpenAI compatible chat completions endpoint, but be clear about what was tested: every run in this course used a local Ollama server. OpenAI and other hosted providers were not tested, so treat them as untested and check each lesson's output yourself. Two cautions. First, check the provider's documentation for which models support tool calling on chat completions: OpenAI's function calling guide notes that some of its newest models require the Responses API for tool calling, so pick a model that the docs list for chat completions. Second, hosted models cost money per token, which you will learn to track in lesson 11.
Your first call
Save this as hello.py and run it with python hello.py:
python# file: hello.py from llm import client, MODEL response = client.chat.completions.create( model=MODEL, messages=[ {"role": "system", "content": "You are a friendly trip helper. Answer in one or two sentences."}, {"role": "user", "content": "What should I pack for a weekend in Lisbon in spring?"}, ], temperature=0.2, ) message = response.choices[0].message print("role:", message.role) print("text:", message.content) print("finish_reason:", response.choices[0].finish_reason) print("tokens in/out:", response.usage.prompt_tokens, response.usage.completion_tokens)
Here is what each part does:
messagesis a list of dictionaries. Each has aroleandcontent.- The
systemmessage sets standing instructions: who the model is and how it should answer. - The
usermessage is the actual question. temperature=0.2keeps answers fairly consistent between runs. Lower values make output more repeatable; they do not make it more correct.
The response is an object, not a string. The text lives at response.choices[0].message.content. The finish_reason tells you why the model stopped: stop means it finished naturally, length means it hit a token limit, and in lesson 3 you will see tool_calls, which means the model wants your code to run a function.
response.usage reports how many tokens went in and came out. Keep an eye on the input number: it grows with every message you send, and it is what you pay for on hosted APIs.
The three roles you will use all course
| Role | Who writes it | What it is for |
|---|---|---|
system | you, the developer | standing instructions and rules |
user | the person using your agent | requests and questions |
assistant | the model | its earlier replies, which you send back |
A fourth role, tool, appears in lesson 3. It carries the result of a function your code ran.
The model sees all of these as one long text with markers between turns. The roles are a convention the model was trained on, not a security boundary. You will come back to that in lesson 6 on safe tools.
Watch the API forget
Save this as forgets.py:
python# file: forgets.py from llm import client, MODEL def ask(messages): response = client.chat.completions.create(model=MODEL, messages=messages, temperature=0) return response.choices[0].message.content # Call 1: tell the model something. print(ask([{"role": "user", "content": "My name is Asha and I am flying to Kyoto next week."}])) # Call 2: a brand new request. The server keeps no memory of call 1. print(ask([{"role": "user", "content": "Where am I flying next week?"}]))
Two separate requests. The first tells the model the user's name and destination. The second asks about the destination.
When this was run with qwen2.5:1.5b, the second answer said it had no access to the user's flight information. That is the correct behaviour for a stateless API: the second request contains one message, and nothing in it mentions Kyoto. The server did not store the first request anywhere the model can see.
This is not a bug or a limit of small models. Large hosted models behave the same way on the chat completions endpoint. The model is a function from "the messages in this request" to "the next message". Nothing else goes in.
Fix it: keep the conversation yourself
Save this as remembers.py:
python# file: remembers.py from llm import client, MODEL messages = [{"role": "system", "content": "You are a friendly trip helper. Keep answers short."}] def chat(user_text): messages.append({"role": "user", "content": user_text}) response = client.chat.completions.create(model=MODEL, messages=messages, temperature=0) reply = response.choices[0].message.content messages.append({"role": "assistant", "content": reply}) # store the answer too return reply print(chat("My name is Asha and I am flying to Kyoto next week.")) print(chat("Where am I flying next week?")) print(f"\nThe history now holds {len(messages)} messages, sent in full on every call.")
The fix is one list. Every user message is appended. Every assistant reply is appended too. Each call sends the full list. Now the second question arrives together with the first exchange, so the model can answer "Kyoto". In the tested run it replied that the user is flying to Kyoto next week.
This list is the agent's working memory, and almost every lesson in this course is about managing it well:
- In lesson 2 the agent loop appends its own tool requests and the tool results to it.
- In lesson 7 you will trim and summarize it when it gets too long for the context window.
- In lesson 8 you will add a second, long-term memory that survives between separate conversations.
- In lesson 15 you will write it to a log file so you can replay a failed run.
sequenceDiagram autonumber participant C as Your Python code participant M as Chat completions API Note over C,M: forgets.py: two separate requests C->>M: [user] My name is Asha, flying to Kyoto M-->>C: Reply C->>M: [user] Where am I flying next week? M-->>C: No access to your flight information Note over C,M: remembers.py: you keep the list C->>M: [system, user] Asha, flying to Kyoto M-->>C: Reply, appended as assistant C->>M: [system, user, assistant, user] Where? M-->>C: Kyoto next week Note over C,M: The full list is sent on every call
Diagram: The API keeps no memory: only the list your code resends makes the second answer say Kyoto.
Animation: Call 2 alone has no idea about Kyoto. Send the whole messages list and the answer comes back.
Why statelessness is good news
It can feel like a limitation, but a stateless API gives you full control:
- You decide what the model sees. You can drop irrelevant turns, insert retrieved facts, or add a summary. Nothing hidden is carried along.
- Runs are reproducible. The same message list sent to the same model with temperature 0 tends to give the same or very similar output, which makes testing possible.
- Providers are swappable. Because your code holds the state, moving from Ollama to a hosted model is a change of
base_urland model name.
The cost is that you pay to resend the history every time. A long conversation means a long prompt on every call. That trade off is what lesson 7 is about.
Common mistakes at this stage
- Forgetting to append the assistant reply. The model then sees a user asking two questions in a row and never sees its own answer.
- Treating
contentas always present. When the model asks for a tool,contentcan be empty orNone. Lesson 2 handles this. - Hard coding the model name. Keep it in
llm.pyor an environment variable so you can test with a different model in one line. - Reading
responseas a dict. The SDK returns typed objects. Use attribute access such asresponse.choices[0].message.content.
What to try next
- Change the system message to "Answer only in French" and run
remembers.pyagain. The rule holds for every turn because the system message is resent every time. - Print
response.usage.prompt_tokensinsidechat()and watch it grow with each turn. - Delete the line that appends the assistant reply and see how the answers change.
- Point
AGENT_MODELat a different model you have pulled and compare the replies.
In the next lesson you will turn this single call into a loop that lets the model ask your code for information, which is the step that turns a chatbot into an agent.
Sources
Build the message list the API needs
The chat completions API forgets everything between calls, so your code must send the whole conversation every time.
Write build_messages(history, user_text, system=None) that returns a NEW list:
1. If system is given, the first message is {"role": "system", "content": system}. Skip it if history already starts with a system message.
2. Then every message in history, in order.
3. Last, {"role": "user", "content": user_text}.
Do not change the history list you were given: the caller keeps using it.
The worked solution unlocks after your first attempt.
Check what you learned
Answer all 3 questions. You need at least 2 right to pass.
1. Why did the second request in forgets.py not know the user's destination?
2. What do you change to point the course code at a hosted provider instead of Ollama?
3. What does finish_reason "length" mean?