Blog/Learn Agentic AI Development/The First Agent: Tools, Instructions and a Loop

Chapter 02 / 12 min read

The First Agent: Tools, Instructions and a Loop

The initial time, calculator and note-saving tools, the ReAct-style loop and its limitations.

The first agent: tools, instructions and a loop

Before creating the calculator project, we already had a small agent that used three Python functions. This first experiment is important because it shows the essential shape of an agent before introducing schemas, registries and execution records.

1. Define ordinary Python functions as tools

The first experiment used:

  • get_current_time to retrieve the current machine date/time.
  • calculate to evaluate a mathematical expression.
  • save_note to write a text file.

Here is the original style of implementation:

Code
import datetime

def get_current_time(
    format: str = "%Y-%m-%d %H:%M:%S"
) -> str:
    """Get the current live date and time on this machine."""
    now = datetime.datetime.now()
    return now.strftime(format)


def calculate(expression: str) -> str:
    """Evaluate a mathematical expression."""
    try:
        result = eval(
            expression,
            {"__builtins__": {}},
            {}
        )
        return str(result)
    except Exception as e:
        return f"Error evaluating expression: {e}"


def save_note(filename: str, content: str) -> str:
    """Save text or calculation results to a local text file."""
    try:
        with open(filename, "w", encoding="utf-8") as f:
            f.write(content)
        return f"File '{filename}' successfully written."
    except Exception as e:
        return f"Error writing file: {e}"

These are normal Python functions. The agent concept comes from the way the model is allowed to request them and the application handles those requests.

Important security note about eval

The original experiment used eval(expression, {"__builtins__": {}}, {}). Removing built-ins reduces some exposure, but it does not make arbitrary expression evaluation a generally safe production design. Never expose an unrestricted expression evaluator to untrusted users. For a real calculator, parse a deliberately limited grammar or use explicit arithmetic tools—the direction we later chose.

2. Map tool names to Python functions

The application needs a lookup table:

Code
TOOL_MAP = {
    "get_current_time": get_current_time,
    "calculate": calculate,
    "save_note": save_note,
}

A model can return the string "calculate". The registry lets Python find the actual function object associated with that name.

3. Keep a conversation history

The first agent sends a system message and a user task:

Code
messages = [
    {
        "role": "system",
        "content": (
            "You are a careful AI agent that solves problems "
            "step-by-step. "
            "Always retrieve the date/time and run calculations "
            "FIRST. "
            "Only call save_note AFTER receiving the other tool "
            "answers. "
            "The saved content must include the complete report."
        ),
    },
    {"role": "user", "content": task_description},
]

The system message defines the agent's operating rules. The user message contains the task. These are separate roles because they have different purposes.

4. The ReAct-style execution loop

The first version used a bounded loop:

Code
def run_agent(
    task_description: str,
    model_name: str = "llama3.2"
):
    messages = [
        {
            "role": "system",
            "content": "You are a careful AI agent. "
                       "Use tools in the required order."
        },
        {"role": "user", "content": task_description},
    ]

    max_turns = 5

    for turn in range(max_turns):
        response = ollama.chat(
            model=model_name,
            messages=messages,
            tools=[get_current_time, calculate, save_note],
        )

        messages.append(response.message)

        if not response.message.tool_calls:
            print(response.message.content)
            return

        for call in response.message.tool_calls:
            fn_name = call.function.name
            fn_args = call.function.arguments

            if fn_name in TOOL_MAP:
                result = TOOL_MAP[fn_name](**fn_args)
            else:
                result = f"Error: Tool '{fn_name}' not recognized."

            messages.append({
                "role": "tool",
                "name": fn_name,
                "content": str(result),
            })

The key sequence is:

  1. Send the current conversation and tool descriptions to the model.
  2. Preserve the assistant response in the message history.
  3. Check whether the response contains tool calls.
  4. If it does, find the Python function and execute it.
  5. Append the result as a tool message.
  6. Call the model again so it can use the observation.

The maximum number of turns prevents an accidental infinite loop. A model may request another tool after receiving a result; the application must have a stopping condition.

5. Why this experiment was not the final architecture

This prototype taught the basic interaction, but it had limitations:

  • Tool arguments were not yet validated by dedicated Pydantic models.
  • The registry and the model-facing tool definitions were not yet separated cleanly.
  • Error handling was simple.
  • It did not maintain typed task-step records or dependency metadata.
  • The eval-based calculator was not suitable as a hardened interface.

The next experiment kept the same central idea but narrowed the tools to addition, multiplication and division. That gave us a safer and more controlled engineering laboratory.