Single-goal agent loop structure
You’re designing a tiny “agent” that chugs along toward one clear goal, step by step, in Python.
On paper, that means: list out the steps in words, then turn each step into a Python operation.
A simple mental model:
- Start with a goal and an empty history.
- Look at the goal and the history.
- Decide what to do next.
- Call a tool (a helper function) to do that thing.
- Record what happened in the history.
- Check if you’re done; if not, go back to step 2.
Let’s write this as a small, runnable-style skeleton (no real APIs):
pythondef agent_loop(goal):
# 1. Initialize state
history = [] # will store steps like dicts or strings
step = 0
max_steps = 5
# 2. Loop until we succeed or hit limits
while step < max_steps:
step += 1
# 3. Decide what to do next based on goal + history
# For now, we hardcode a simple “plan”
if step == 1:
action = "search"
else:
action = "summarize"
# 4. Call a tool based on the action
if action == "search":
result = tool_search(goal)
elif action == "summarize":
result = tool_summarize(history)
else:
result = "unknown action"
# 5. Record the step into history
history.append({
"step": step,
"action": action,
"result": result,
})
# 6. Check for stopping condition
if goal_satisfied(goal, history):
break
# Return whatever final answer we think we have
final_answer = extract_answer(history)
return final_answer
On paper, your job is to sketch something like this:
- A single function
agent_loop(goal) - A loop (
whileorfor) that:- Chooses an
action - Calls a tool
- Logs result into
history - Checks if the goal is satisfied or if you hit a limit
- Chooses an
You don’t need real logic for planning yet; just fake it with if step == 1: ....
1 / 4