Day 2 of 960 minCipher Cadet
Day 2: Talking to the Model From Your Own Script
Taught by Mr Elite Updated
By the end of today you can
- Explain why a script gives you more control than the terminal chat
- Describe what a message and a role are in a conversation with a model
- Write and run assistant.py to get a reply from your local model
- Read the two most common errors and fix them
Warm-up
Answer from memory first, then tap to check. Recalling yesterday is what makes it stick.
What command starts a chat with a model in Ollama, and how do you leave the chat?
ollama run followed by the model name starts it, and /bye ends it.
Why can a language model sound confident and still be wrong?
It predicts likely next text, so it produces fluent answers whether or not they are true.
Yesterday you typed into a chat window and the model answered. That is fine for a first look, but you cannot build anything on it. You cannot add rules, you cannot feed it a file, and you cannot check what it was actually sent.
Today we move the conversation into a Python script that you wrote and can read. Once you can see exactly what goes in and what comes out, you can later control it, and later still, defend it. Everything runs on your own machine, talking only to your local model.
Why a script beats the terminal chat
The terminal chat is a finished product. Someone else decided how your words are packaged, what hidden settings are used and how the answer is shown. You just type.
A script puts you in charge of the packaging. You decide what text is sent, which model receives it and what happens to the reply. By Day 5 the script will read your notes, and by Day 7 it will use a tool. None of that is possible from the chat window.
Security starts here too. If you do not know exactly what your program sends to a model, you cannot reason about what could go wrong. A script makes the flow visible.
Messages and roles
A model does not see a chat the way you do. It receives a list of messages, and each message has a role and some content. The role says who is speaking.
- Message
- One piece of the conversation, made of a role and the text content.
- Role
- A label saying who wrote the message. Today we use user. Tomorrow we add system.
- user role
- Text from the person talking to the assistant, which is you right now.
- assistant role
- Text that the model wrote in reply.
- JSON
- A plain text format for structured data, using curly braces and quote marks. Our script sends and receives it.
Here is the shape of what we will send. It is a list with one message in it.
{"model": "llama3.2", "messages": [{"role": "user", "content": "What is a firewall?"}], "stream": false}Quick check
In the list of messages, which role label marks the text you typed?
The user role is the person asking. The assistant role is the model's own reply.
Watch me do it: build assistant.py
I will build the script from nothing. I use only parts of Python that come installed, so there is nothing extra to download. Follow each step and check what you see before moving on.
mkdir ai-assistant
cd ai-assistant
python --versionimport json
import urllib.request
import urllib.error
MODEL = "llama3.2"
URL = "http://localhost:11434/api/chat"
def ask(question):
payload = {
"model": MODEL,
"messages": [{"role": "user", "content": question}],
"stream": False,
}
data = json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
URL, data=data, headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(request, timeout=120) as response:
body = json.load(response)
return body["message"]["content"]
question = input("Ask something: ")
try:
print(ask(question))
except urllib.error.HTTPError as err:
print("The server answered with an error:", err.code)
print("Check the model name in MODEL. Run: ollama list")
except urllib.error.URLError:
print("Could not reach Ollama. Is it running?")Reading the script line by line
Now that it runs, let me explain it in the order it is written. Do not worry about memorising it. You just need to know where each job happens.
Quick check
Why do we set "stream": False in the payload?
With streaming off, the server sends one complete reply, which is much easier for a first script.
Your turn: change it and break it
There is no online lab today. The practice is on your own machine, and the best way to learn a script is to poke it. Make each change, run it, and note what happens.
Common errors and what they mean
Two errors will cover most of your trouble today. Both are caught by the except lines in the script, so the messages are friendly.
- Could not reach Ollama
- Nothing is listening on port 11434. Start the Ollama app or run ollama serve, then check the browser page again.
- Error 404
- Ollama is running but cannot find the model you named. Run ollama list and copy the NAME exactly, including any :latest.
- IndentationError
- The spaces at the start of a line are wrong. Re-paste the script and do not mix tabs and spaces.
- No such file
- Your terminal is in the wrong folder. Run cd ai-assistant first, then try again.
If it did not work
Saving the file as assistant.py.txt
Turn on file extensions in your file browser, or save again from VS Code and check the tab says assistant.py.
Using a model name from memory instead of ollama list
Always copy the NAME from ollama list. A small spelling difference gives a 404 error.
Running python assistant.py from the wrong folder
Use cd ai-assistant first. The terminal prompt usually shows the current folder.
Leaving curly quotes in pasted code
If Python complains about a strange character, retype the quote marks in VS Code so they are straight quotes.
Recap
- A script lets you see and control exactly what is sent to the model
- Ollama serves your local model at http://localhost:11434, so nothing leaves your machine
- A conversation is a list of messages, each with a role and content
- The reply text lives at body["message"]["content"] in the response
- Could not reach Ollama means start it; a 404 means fix the model name
- The model trusts whatever message history you give it, even invented history
Cheat sheet
ollama list- Shows installed models and their exact names
http://localhost:11434- Browser check that Ollama is running
python assistant.py- Runs your script (use py on some Windows setups)
role: user- A message written by the person asking
role: assistant- A message written by the model
"stream": False- Ask for the whole reply in one response
HTTPError 404- Model name not found
Before the next day
Mission: Run it and keep a record
Get assistant.py working on your own machine and prove it. Tomorrow we add a system prompt to this exact file, so you need a working copy and a note you can refer back to.
About 30 min
You are done when: A note containing your working assistant.py and one reply copied from the model.
Want more? Wrap the question and reply in a while True loop so you can ask many questions in one run, and let the user type quit to stop.
Quiz
4 questions. Your score is saved with your progress.
1. What is the main reason we moved from the terminal chat to a script?
Control and visibility are what let us add rules, files and tools later, and secure them.
2. Your script prints an error with code 404. What is the most likely cause?
A 404 means the server answered but could not find the thing you asked for, here the model. If Ollama were off you would get a connection error.
3. What does a role tell the model?
Roles label the speaker of each message, such as user for you and assistant for the model.
4. You add a fake assistant message to the history and the model goes along with it. What does that suggest?
The model has no way to verify the history it receives. That is why input control matters in security.
Finish the day
Mark the day complete to save your progress.
Next: Tomorrow we add a system prompt to assistant.py to give your assistant a role and rules, then see how a user message can push against them.
Your notes
Private to this device. Write what you want to remember from today.