How AI Language Models Work · Building with Models
Agents: A Model in a Loop
An agent lets a model use tools. The model picks an action, the program runs it, the result goes back to the model, and the loop repeats until it answers.
agent.py
# An agent is a loop: the model picks an action, the program does it, and the result goes back in.
def multiply(a, b):
return a * b
def model(notes):
# A real agent asks a language model here. This stand-in makes the same kind of choice.
if not notes:
return "multiply", [23, 7]
return "answer", notes[-1]
notes = []
for turn in range(3):
action, data = model(notes)
print("turn", turn, ":", action, data)
if action == "answer":
break
result = multiply(data[0], data[1])
notes.append(result)
Step by step
- A tool: a normal function that multiplies two numbers.
- The "model". A real agent sends the question and its notes so far to a language model, which replies with the next action. This stand-in makes the same kind of choice with an if.
- notes holds what the agent has found out so far. It starts empty.
- Turn 0. The loop allows at most 3 turns, so a confused agent cannot run forever.
- Ask the model what to do, giving it the notes.
- No notes yet: the model has not worked anything out.
- So it asks for a tool: multiply 23 by 7.
- The model's reply is split into the action and its data.
- Log the decision.
- It is not "answer", so keep going.
- The program runs the tool the model asked for. The model never runs anything itself.
- 23 × 7 = 161.
- The tool's result: 161.
- Write the result into the notes, so the model sees it next turn. This is the "observe" step.
- Turn 1.
- Ask the model again, now with notes = [161].
- There are notes now.
- So it answers with the latest note: 161.
model() has finished, so its names are gone. The value it returned, 'answer', is stored in action. data changes from [23, 7] to 161.- It prints
turn 1 : answer 161. - The action is "answer".
- Done in two turns: decide, act, observe, then answer. Real agents run this same loop with a language model choosing among many tools: search, run code, read files, send email.