Build a Minimal AI Agent from Scratch: A Step-by-Step Beginner’s Guide

    Learn how to build a minimal AI agent using a language model, a tool definition, a function registry, and a bounded execution loop. This provider-neutral guide walks through a mock weather tool, tool-call handling, testing, and the safety and operational controls needed before expanding the agent. All model API examples are pseudocode that must be adapted to your chosen service.

    For beginners, “AI agent” can sound like something that requires complex frameworks, memory systems, multi-agent collaboration, and vector databases. A minimal working agent is much simpler.

    Its core consists of four parts:

    • A language model makes decisions.
    • Tool descriptions tell the model what capabilities are available.
    • An executor invokes the actual tools.
    • A loop connects decision-making, execution, and the next decision.

    This guide uses provider-neutral pseudocode rather than a specific model service or third-party framework. The goal is to understand a minimal agent architecture. To implement it with a particular model API, adapt the request and response fields using the relevant API documentation.

    1. What Does a Minimal AI Agent Look Like?

    A minimal agent is a loop with tool-calling capabilities, not a large software platform.

    When a user submits a question, the program sends the question and a list of available tools to the model. The model decides whether a tool is needed. If it requests one, the program executes the tool and returns the result to the model. The model then uses that result to produce an answer or request another tool call.

    This process may require one tool call or several. For a minimal implementation, a maximum step count provides a basic limit on execution.

    Rather than starting with an all-purpose assistant, build a small weather-query example. A weather tool has a clear input and an easily checked output, making it useful for learning the mechanism. Once the loop works, you can replace the tool with an order lookup, document lookup, calculation, or database query.

    2. Prerequisites: Understand Three Concepts

    Before writing the loop, distinguish these three concepts.

    Tool: An executable function. For example, a weather function accepts a city name and returns weather information.

    Tool description: A structured explanation of what the function does and which arguments it requires. The model does not execute your code directly; it reads this description and decides whether to request a call.

    Tool result: The output your program returns to the model after executing the function. The model needs this result to continue answering the user.

    You will need:

    • An environment that can run Python.
    • Access credentials for a language model service.
    • A basic understanding of reading and writing JSON.

    API field names differ between services, but the general pattern is the same: send a message history and tool definitions, receive a model response, and determine whether it contains ordinary text or a tool-call request.

    The examples below are pseudocode. They illustrate the structure, not the exact interface of any particular provider.

    3. Step 1: Describe a Tool the Model Can Understand

    A tool definition usually includes a name, a description, and an input schema.

    Use a short, explicit name. The description should explain when to use the tool, what input it accepts, and what it returns. The input schema should specify parameter types and required fields.

    Vague descriptions can cause incorrect tool selection or missing arguments. “Get weather” is less useful than “Get the current weather for a specified city.”

    Here is an illustrative definition:

    1. tools = [
    2. {
    3. "name": "get_weather",
    4. "description": "Get the current weather for a specified city",
    5. "input_schema": {
    6. "type": "object",
    7. "properties": {
    8. "city": {
    9. "type": "string",
    10. "description": "City name, such as Beijing or Shanghai"
    11. }
    12. },
    13. "required": ["city"]
    14. }
    15. }
    16. ]

    This definition does not execute anything. It tells the model that a capability called get_weather exists and requires a city argument.

    Clear tool descriptions give the model a better basis for deciding which tool to request and what arguments to supply.

    4. Step 2: Create an Executable Tool Registry

    The model requests a tool call; your program executes it.

    To connect those two responsibilities, implement the function and create a mapping from its name to the callable. Start with fixed weather data so that an external service does not complicate the first exercise.

    1. def get_weather(city: str) -> dict:
    2. # Mock data; replace with an HTTP request or internal service call later.
    3. return {
    4. "city": city,
    5. "weather": "Sunny",
    6. "temperature": "25°C"
    7. }
    8. TOOL_REGISTRY = {
    9. "get_weather": get_weather
    10. }

    The registry makes the design extensible. Adding an order lookup or tax calculation means adding a function and its tool description rather than rewriting the main loop.

    More importantly, it establishes a fundamental separation: the model decides what to request, while the program controls execution.

    5. Step 3: Ask the Model Whether It Needs a Tool

    Send the user’s message and the available tool definitions to the model client.

    Message formats, tool fields, and response structures vary by service. The following is only pseudocode:

    1. # Generic model client pseudocode; adapt using your provider's documentation.
    2. client = LLMClient(api_key=API_KEY)
    3. messages = [
    4. {"role": "user", "content": "What is the weather in Beijing right now?"}
    5. ]
    6. response = client.create(
    7. messages=messages,
    8. tools=tools
    9. )

    At this point, the model may return either:

    • A direct text response.
    • A request to call a tool, including its name and arguments.

    During initial development, print the raw response and inspect its structure. Avoid hiding the response behind multiple abstraction layers before you understand which fields your provider returns.

    6. Step 4: Execute the Tool and Return Its Result

    When the model requests a tool call, your program needs to:

    1. Extract the tool name and arguments.
    2. Check that the tool and arguments are valid.
    3. Execute the registered function.
    4. Append the tool-call request and tool result to the message history.
    5. Call the model again.

    The basic message flow looks like this:

    1. import json
    2. if response.type == "tool_call":
    3. tool_name = response.tool_name
    4. tool_args = response.arguments
    5. tool_result = TOOL_REGISTRY[tool_name](**tool_args)
    6. messages.append({"role": "assistant", "content": response.raw})
    7. messages.append({
    8. "role": "tool",
    9. "tool_name": tool_name,
    10. "content": json.dumps(tool_result, ensure_ascii=False)
    11. })
    12. final_response = client.create(messages=messages, tools=tools)

    This snippet illustrates execution and result forwarding; it does not implement the validation checks described above. Adapt the message structure and response parsing to your provider’s requirements.

    Do not trust arguments simply because the model generated them. Before execution, check whether the city is a nonempty string and whether its value is within any allowed constraints.

    If execution fails, return a readable error result to the model rather than exposing an unhandled exception to the user. The model can then explain the failure in context.

    7. Step 5: Assemble the Minimal Agent Loop

    Put these steps inside a bounded loop to create a minimal agent. A maximum step count prevents the program from repeatedly requesting tools without reaching an answer.

    1. def run_agent(user_input: str, max_steps: int = 5):
    2. messages = [{"role": "user", "content": user_input}]
    3. for step in range(max_steps):
    4. response = client.create(messages=messages, tools=tools)
    5. if response.type == "tool_call":
    6. name = response.tool_name
    7. args = response.arguments
    8. if name not in TOOL_REGISTRY:
    9. return "Unknown tool. Check the tool registry."
    10. try:
    11. result = TOOL_REGISTRY[name](**args)
    12. except Exception as e:
    13. result = {"error": str(e)}
    14. messages.append({"role": "assistant", "content": response.raw})
    15. messages.append({
    16. "role": "tool",
    17. "tool_name": name,
    18. "content": json.dumps(result, ensure_ascii=False)
    19. })
    20. continue
    21. return response.text
    22. return "Maximum step count reached without a final answer."

    This short skeleton contains the essential agent decision loop. It checks tool names and catches execution errors, but argument validation still needs to be added before invoking a function.

    First understand the structure, then adapt the client calls and response handling to your model API. Do not rush to add memory, planning, or concurrent tool execution. Make one tool work reliably across one or a few calls before expanding the design.

    8. Step 6: Test the Agent and Troubleshoot Each Stage

    Test at least three categories of input:

    Test category Example input What to check
    A tool is clearly needed “What is the weather in Beijing?” Does the model request the weather tool with the correct city?
    No tool is needed “Hello, please explain what a loop is.” Does the model answer without calling the weather tool?
    Required information is missing “What is the weather?” How does the model handle the missing city?

    Check whether tool calls happen at appropriate times, whether arguments are correct, and whether the final answer reflects the returned tool data.

    Common problems include:

    • Vague tool descriptions: The model requests the wrong tool or uses it unnecessarily.
    • Missing required fields: The model omits necessary arguments.
    • No step limit: Repeated calls can continue without reaching a final answer.
    • No exception handling: A tool failure interrupts the program.
    • No raw-response inspection: Provider-specific parsing problems become difficult to diagnose.

    For troubleshooting, log each stage separately:

    1. User input.
    2. Model response.
    3. Tool execution.
    4. Result sent back to the model.
    5. Final answer.

    Following the data through these stages usually makes it easier to locate a failure.

    9. Step 7: Add Safety, Cost, and Operational Controls

    Once the minimal loop works, focus on engineering constraints rather than immediately adding more features.

    • Minimize permissions. Expose only the capabilities the agent needs.
    • Validate arguments. Check parameter types and allowed values before execution.
    • Control external calls. Configure timeouts, retries, and rate limits.
    • Keep useful logs. Record tool names, argument summaries, execution results, and elapsed time while redacting sensitive information.
    • Bound execution. Set limits on steps, total runtime, and cost.
    • Require approval for consequential actions. Tools that write data, delete records, or make payments need human confirmation or permission checks.

    The illustrative error handling above is useful for understanding the flow, but error details and logs must also be handled carefully so that sensitive information is not exposed.

    For deployment, cloud infrastructure categories such as function computing, object storage, logging, monitoring, and alerting can support operation and observability. These categories are available through cloud platforms, including Baidu AI Cloud; evaluate the relevant services and availability for your deployment environment.

    Regardless of the infrastructure, the division of responsibilities stays the same: the model makes decisions, the program enforces boundaries, tools execute operations, and logs provide traceability.

    10. Conclusion: Complete the Small Loop Before Expanding

    For beginners, the most practical starting point is not a complex framework. It is a minimal agent you can understand from end to end:

    1. Define a tool.
    2. Register its executable function.
    3. Call the model.
    4. Parse the tool request.
    5. Execute the tool and return its result.
    6. Continue until the model produces a final answer or reaches the step limit.

    Once this loop is clear, multi-tool routing, memory management, task planning, and evaluation become easier to understand.

    For your next exercise, replace the mock weather function with a tool that retrieves a local document summary. Keep the loop unchanged and observe how the model uses the new description to decide when to request the tool. That small change demonstrates the value of the architecture: capabilities can change while the core execution loop remains the same.