POC 1 - Terminal Calculator Agent
Lessons 1.5 to 1.7 and 1.10A ReAct agent with one calculate tool, in the terminal: keep asking questions until you type quit. It is pure assembly - the safe calculator (1.6), the robust loop (1.10), the "say so when no tool helps" line (1.10), and a small input loop. Every answer below came from the calculator - including 4783 * 2917, which the model got wrong every time without a tool in Lesson 1.4.
"""POC 1 - Terminal Calculator Agent: Lessons 1.5 to 1.7 and 1.10 in one file."""
import ast
import operator
import re
import ollama
MODEL = "llama3.1"
# --- The tool (Lesson 1.6's safe calculator: arithmetic only, no eval) ---
OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.USub: operator.neg,
}
def calculate(expression):
def evaluate(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in OPERATORS:
return OPERATORS[type(node.op)](evaluate(node.left), evaluate(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in OPERATORS:
return OPERATORS[type(node.op)](evaluate(node.operand))
raise ValueError("only numbers and + - * / are allowed")
result = evaluate(ast.parse(expression, mode="eval").body)
return str(int(result) if result == int(result) else result)
TOOLS = {"calculate": calculate}
SYSTEM_PROMPT = """You solve problems step by step using this format:
Thought: what you're thinking
Action: tool_name(argument)
Observation: (this will be filled in for you)
... repeat Thought/Action/Observation as needed ...
Final Answer: your final answer to the user
Available tools:
- calculate(expression): evaluates an arithmetic expression such as 47 * 89
Only output ONE Thought/Action pair at a time, then stop and wait for the Observation.
If the question needs no tool, or the tool cannot help, answer straight away with a Final Answer that says so."""
ACTION = re.compile(r"Action:\s*(\w+)\((.*?)\)")
# --- The loop (Lesson 1.10's run_agent_safe) ---
def run_agent_safe(user_question, max_steps=5, max_retries_per_step=2):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_question},
]
for step in range(max_steps):
text = None
for retry in range(max_retries_per_step):
response = ollama.chat(model=MODEL, messages=messages, options={"temperature": 0})
candidate = response["message"]["content"]
if "Final Answer:" in candidate or ACTION.search(candidate):
text = candidate
break
messages.append({"role": "user", "content": "That wasn't in the right format. Use Thought/Action or Final Answer."})
if text is None:
return "Agent failed to produce a valid step after retries."
messages.append({"role": "assistant", "content": text})
if "Final Answer:" in text:
return text.split("Final Answer:")[-1].strip()
match = ACTION.search(text)
tool_name, arg = match.group(1), match.group(2).strip("\"' ")
if tool_name not in TOOLS:
observation = f"error: '{tool_name}' is not a valid tool. Available tools: {list(TOOLS)}"
else:
try:
observation = TOOLS[tool_name](arg)
except Exception as e:
observation = f"error running {tool_name}: {e}"
messages.append({"role": "user", "content": f"Observation: {observation}"})
return "Max steps reached without a final answer."
# --- The terminal ---
if __name__ == "__main__":
print("Calculator Agent - type 'quit' to exit")
while True:
q = input("\nYou: ")
if q.strip().lower() == "quit":
break
print("Agent:", run_agent_safe(q))Calculator Agent - type 'quit' to exit
You: What is 47 * 89?
Agent: The final answer is 4183. calculate("47 * 89")
You: What is 1000 / 25?
Agent: The result of 1000 divided by 25 is 40. calculate("1000 / 25")
You: What is 4783 * 2917?
Agent: The product of 4783 and 2917 is 13952011. calculate("4783 * 2917")
You: What is 15% of 2400?
Agent: The answer is 360. calculate("2400 * 0.15")
You: What is the capital of France?
Agent: Paris no tool needed
You: quit