How to build an AI Agent

banner

I'll use MiniGen, a minimalist framework for building agents with the OpenAI API. We'll start with a small assistant, give it a Python tool, and watch the messages move.

I want to keep the task simple: converting Celsius to Fahrenheit. We already know how to check the answer, so we can focus on how an agent works. If you're comfortable with Python functions and dictionaries, you have enough to follow along.

The illustrations use scripted model responses and local calculations; the Python examples were checked with mocked responses rather than live API calls.

Start with the loop

Imagine asking our assistant, “What's 25°C in Fahrenheit?” It could write an answer immediately. With a conversion tool available, it can instead ask our program to do the calculation, read the result, and then answer.

That back-and-forth is the idea I want you to notice. The model chooses an action, our application runs it, and the result becomes part of the next model request. We keep going until the model answers or our application stops execution.

The pieces have familiar names. Instructions describe the job. Tools are functions the assistant can request. An observation is a returned result, such as 77°F. Conversation state keeps the messages together. A stopping rule tells our program when to finish.

Try the comparison task below. It needs two conversions, so you can watch the loop repeat before the final answer.

One visible agent loop

Application-controlled execution · scripted model decisions · local arithmetic

Agent feedback loop. A request enters the loopContext0 results receivedModelRead contextPython toolWaiting for a callObservationWaiting for a resultAnswerWaitingAgent feedback loop. A request enters the loopContext0 results receivedModelRead contextPython toolWaiting for a callObservationWaiting for a resultAnswerWaiting
Hover, focus, or tap a station to inspect it.
A request enters the loop

Convert 25°C. The application adds the request to conversation context.

Stage 1 of 6

Research such as ReAct explores alternating actions with observations. For our purposes, the useful idea is simple: let the model see what happened before asking it what to do next. MiniGen uses function calling for this exchange; we're watching messages and actions, not the model's private reasoning.1

Set up MiniGen

I'll use Python 3.12 or newer. Let's create a virtual environment and install MiniGen.2

Create the environment:

python -m venv .venv

Activate it with source .venv/bin/activate on macOS/Linux, or .venv\Scripts\Activate.ps1 in Windows PowerShell. Then install:

python -m pip install "git+https://github.com/devdezzies/minigen.git@281c8bd19703851594df8bb0c6b5395cf0ffb99d"

Set your API key and choose an available model that supports Chat Completions and function calling. Replace the placeholders before running these commands.

On macOS/Linux:

export OPENAI_API_KEY="your-api-key"
export DEFAULT_MODEL="your-function-calling-model"

In PowerShell:

$env:OPENAI_API_KEY="your-api-key"
$env:DEFAULT_MODEL="your-function-calling-model"

Keep your API key out of your Python files. Set these variables before running the examples: MiniGen reads the environment but doesn't automatically load a .env file.

Let's first ask a question without adding a tool. Save this as assistant.py and run it with python assistant.py:

import os
from minigen import Agent
 
assistant = Agent(
    name="Temperature tutor",
    model=os.environ["DEFAULT_MODEL"],
    api_key=os.environ["OPENAI_API_KEY"],
    system_prompt="Explain temperature scales clearly and briefly.",
)
print(assistant.chat("What is the difference between Celsius and Fahrenheit?"))

The system prompt describes how I want the assistant to respond. chat() sends the question and returns its answer. MiniGen creates an AgentSession to hold the conversation, so later calls can use earlier messages.3

We've now connected a model to our program. Next, I'll give it something concrete to do.

Give it a Python tool

The conversion is ordinary Python: multiply by 9/5, then add 32. The interesting part is making that function available to the model.

MiniGen's @tool decorator describes the function's arguments and registers it for execution. Passing it in tools lets the model request it by name.4

Save this complete example as converter.py. It uses the same environment variables as before:

import math
import os
from minigen import Agent, tool
 
@tool(description="Convert Celsius to Fahrenheit", strict=False)
def celsius_to_fahrenheit(celsius: float) -> float:
    if isinstance(celsius, bool) or not isinstance(celsius, (int, float)):
        raise ValueError("celsius must be a number")
    result = celsius * 9 / 5 + 32
    if not math.isfinite(celsius) or celsius < -273.15 or not math.isfinite(result):
        raise ValueError("temperature must be finite and at or above absolute zero")
    return round(result, 6)
 
# Compatibility helper: make schema types plain strings.
parameters = celsius_to_fahrenheit.tool_spec["function"]["parameters"]
for property_schema in parameters["properties"].values():
    if isinstance(property_schema["type"], tuple):
        property_schema["type"] = property_schema["type"][0]
 
converter = Agent(
    name="Converter",
    model=os.environ["DEFAULT_MODEL"],
    api_key=os.environ["OPENAI_API_KEY"],
    system_prompt="Use the conversion tool for temperatures. Explain results briefly.",
    tools=[celsius_to_fahrenheit],
)
print(converter.chat("Convert 25 degrees Celsius to Fahrenheit."))

There's one compatibility helper to keep when copying this example: it fixes the decorator's argument types. We also use strict=False because its generated schema needs additional fields for strict mode. The source note explains both details.4

Run python converter.py. When the model requests the conversion, Python calculates 77°F, and the model receives that result before answering. Its wording can vary; the arithmetic stays the same.

The function also checks its input. A tool description tells the model what to send, but I still want Python to reject invalid values. A schema is the description of those arguments: here, an object with a required numeric celsius field.5

Step through the walkthrough to see the arguments, execution, and returned message. Then try a direct answer and a failing tool call.

Follow one tool call

Scripted model responses · conversion computed locally · no API calls

Agent tool-call loop. Current stage: User request. User request enters conversation history; the model can call Python, read its observation, then answer.User request25°C → °FHistory2 messagesLanguage modelChoose an actionPython toolcelsius → °FObservationWaiting for resultFinal answerWaiting for modelAgent tool-call loop. Current stage: User request. User request enters conversation history; the model can call Python, read its observation, then answer.User request25°C → °FHistory2 messagesLanguage modelChoose an actionPython toolcelsius → °FObservationWaiting for resultFinal answerWaiting for model
Request / toolModel / decisionObservation / result
Hover, focus, or tap a module to inspect it.
User request

The user request joins the system instructions in conversation history.

Step 1 of 5
Inspect message transcript
[
  {
    "role": "system",
    "content": "Use the conversion tool for temperatures. Explain results briefly."
  },
  {
    "role": "user",
    "content": "Convert 25°C to Fahrenheit."
  }
]

Adding a tool doesn't train a new model. We're giving an existing model an action it can request. Toolformer studies learning tool use through training; MiniGen handles the runtime exchange instead.6

Watch the conversation grow

Our converter needs to know which result belongs to which request. MiniGen keeps that relationship in its messages:

  1. We send the user's question.
  2. The model returns an assistant message requesting a tool.
  3. Python returns a tool message with the matching tool_call_id.
  4. The model reads the updated conversation and answers.7

That call ID matters when several tools are requested. It's the link between an action and its result, so the model can tell what each returned value means.

Ask about 30°C afterward, and the new turn joins the same history. Use the cards below to inspect both conversions and their matching IDs.

Every turn leaves a message

In-process session context · not persistent storage · scripted conversation

1 messagesession.messages
Hover, focus, or tap a card to inspect its role and content.
Only the system instruction remains

Clear session retains the system message. These cards are current-session context; no persistent store is implemented.

Message 1 of 9
Inspect accumulated messages
[
  {
    "role": "system",
    "content": "Use the conversion tool for temperatures. Explain results briefly."
  }
]

This is conversation history held in the running process. It isn't persistent memory saved across restarts. Earlier messages remain available during the session, and a growing history means more context to send on later requests.

When I want a fresh conversation, I can call converter.clear_session(). MiniGen retains the system instruction while removing the other messages. The illustration's “Clear session” control shows that same idea.7

Choose a workflow when you need one

I'd start with the single converter we've built. For larger tasks, it helps to decide which parts should follow a fixed order and which parts need a choice.

A workflow follows steps we define in code. An agent can let the model choose its next action. Anthropic's guide uses this distinction when discussing the extra time and complexity that more elaborate systems introduce.8

Switch between the three patterns below and inspect what each stage receives.

Choose how the work flows

Local simulation · scripted outputs and routing · no model calls

chain workflow. Current stage: Step 1 · outline. Three fixed prompts share one agent's conversation history.OutlineTopic → outlineDraftOutline → draftEditDraft → explanationFinal outputWaitingchain workflow. Current stage: Step 1 · outline. Three fixed prompts share one agent's conversation history.OutlineTopic → outlineDraftOutline → draftEditDraft → explanationFinal outputWaiting
Request / toolModel / decisionObservation / result
Hover, focus, or tap a module to inspect it.
Step 1 · outline

Insert the outline into the next prompt's {input}.

Stage 1 of 4
Inspect context and outputIncoming context · current template + accumulated agent history
Outline this topic: Explain how a temperature-conversion agent works.
Output
Model → tool call → execution → observation → answer.

Chain: follow a fixed sequence

Suppose I want an outline, then a draft, then an edit. A Chain passes each output into the next prompt's {input}. It reuses one agent, keeping its conversation history too.9

Add this after the first example in assistant.py:

from minigen import Chain
 
chain = Chain(agent=assistant)
chain.add_step("Outline this topic: {input}")
chain.add_step("Expand this outline into a short explanation: {input}")
chain.add_step("Edit this explanation for clarity: {input}")
print(chain.run("How a temperature-conversion agent works"))

We choose the order. That makes intermediate results easy to inspect, though an error in the outline can still affect the draft.

Network: choose the next worker

A network lets us route a request to a worker, such as an Engineer or Writer. We can choose the route in Python or ask another model to select it. The explorer uses a scripted branch so both paths are easy to follow.10

Here's the context detail I'd keep in mind: workers receive the latest network message, while the built-in model router receives the broader history. If a worker needs the original user's constraints, we must carry them into that latest message.11

Parallel: do independent work together

Two workers can examine the same input independently, then pass their collected outputs to a synthesizer. MiniGen's Parallel primitive supports this pattern.12

Their waiting time can overlap, but two workers and a synthesizer still make multiple model calls. I'd use this for independent perspectives, not for a step that needs another worker's unfinished answer.

Know when to stop

Before adding more tools, I'd check the converter with answers we can verify: 0°C gives 32°F, 25°C gives 77°F, and −40°C gives −40°F. Then I'd try invalid input and inspect whether the right function ran.

The question is whether the task was completed correctly. AgentBench evaluates agents in interactive environments with that broader goal in mind; a convincing final paragraph alone doesn't tell us whether the actions succeeded.13

We also need a limit. MiniGen's network max_rounds counts worker iterations, but doesn't bound tool calls inside a worker. One worker can keep requesting actions. The application budget below checks each proposed call before allowing Python to execute it.11

The application decides when to stop

Illustrative tool-call budget wrapper · not provided by MiniGen's max_rounds

Tool-call budget
Network worker iterations 1Tool calls used 0 / 3
Application execution budget. The model proposes call 1ModelProposes call 1Budget gate3 calls leftPython toolNot executedObservationNo result yetApplication execution budget. The model proposes call 1ModelProposes call 1Budget gate3 calls leftPython toolNot executedObservationNo result yet
Hover, focus, or tap a station to inspect it.
The model proposes call 1

Scripted request: celsius_to_fahrenheit(25). It has not executed yet.

Stage 1 of 9

If a tool raises an error, MiniGen stops that loop with an exception. I'd handle it in application code and tell the user what failed. Retrying a calculation is different from retrying an action that places an order.

Finally, I wouldn't treat retrieved text as instructions for our application. A page or document can contain directions intended to redirect the model, a risk studied as indirect prompt injection. Restrict tool permissions and check sensitive actions in code.14

We now have a small agent we can follow from request to result. I'd build on this by adding one useful tool at a time, checking its inputs and outputs, and keeping each extra workflow easy to explain.

For more code to explore, head to MiniGen on GitHub. There's also a DeepWiki overview. The implementation notes below link to the code used for these examples.

Footnotes

  1. Shunyu Yao et al., “ReAct: Synergizing Reasoning and Acting in Language Models”, ICLR 2023, arXiv v3. Sections 2–4 and Appendix E.1: interleaved actions/observations and task-specific failure analysis. ↩

  2. devdezzies, MiniGen source snapshot, reviewed 2026: package metadata and router f-strings. Metadata declares Python ≥3.11; router syntax motivates the tutorial's ≥3.12 requirement. ↩

  3. devdezzies, MiniGen agent.py, reviewed 2026. Agent.__init__, chat, and clear_session; environment defaults, client creation, and session lifecycle. ↩

  4. devdezzies, MiniGen tool.py, reviewed 2026. tool and get_tool_func. The decorator produces tuple-valued schema types; the example normalizes them locally. Its schema is incomplete for strict mode, so the example uses strict=False. The global registry is keyed by function name; duplicate names overwrite registrations. ↩ ↩2

  5. OpenAI, “Function calling”, accessed October 4, 2026. Tool-calling flow, Chat Completions examples, and strict-mode schema requirements. This article uses MiniGen's Chat Completions interface. ↩

  6. Timo Schick et al., “Toolformer: Language Models Can Teach Themselves to Use Tools”, NeurIPS 2023. Section 2: sampling, executing, filtering API calls, and fine-tuning; Section 7: limitations. ↩

  7. devdezzies, MiniGen context.py, reviewed 2026. AgentSession.run and parse_run: message ordering and recursive tool calls. For inspection, use agent.session.messages; get_messages() and clear() reference a nonexistent memory attribute. Use agent.clear_session() to retain system messages. Structured output returns the SDK completion wrapper rather than the parsed payload; these examples use plain text. ↩ ↩2

  8. Erik Schluntz and Barry Zhang, “Building effective agents”, Anthropic, 2024. Sections “What are agents?”, “When (and when not) to use agents”, and workflow patterns; engineering guidance, not a MiniGen benchmark. ↩

  9. devdezzies, MiniGen chain.py, reviewed 2026. Chain.add_step and run; template interpolation and reuse of one agent session. ↩

  10. devdezzies, MiniGen router.py, reviewed 2026. create_llm_router: broader network history, registered routes, parsed-decision extraction from the SDK wrapper, and FINISH mapping to None. ↩

  11. devdezzies, MiniGen network.py and state.py, reviewed 2026. run, worker context, max_rounds, and returned NetworkState; read state.result for the final result. A worker receives the latest network message after its session is cleared, retaining system instructions. Reaching the round cap reports the limit even if routing finishes on that iteration. ↩ ↩2

  12. devdezzies, MiniGen parallel execution, _run_parallel_node, and primitive exports, reviewed 2026. Thread-pool execution, ordered aggregation, and Parallel import location. ↩

  13. Xiao Liu et al., “AgentBench: Evaluating LLMs as Agents”, ICLR 2024; arXiv v3, 2025. Sections 2–4: eight interactive environments, evaluation, and agent failure analysis. ↩

  14. Kai Greshake et al., “Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection”, 2023, arXiv v2. Sections 3–5: attack delivery, demonstrations, limitations, and mitigation discussion. ↩