Skip to content
Learning Lab · 5 min read

Building AI Agents: Tool Calling, Memory, and Loop Patterns

AI agents are loops, not chatbots. Learn the core architecture pattern, how tool calling works, memory management strategies, and the code shape that actually handles failures in production.

AI Agent Architecture: Tool Calling and Memory Patterns

Most developers treat AI agents like chatbots with extra steps. Ask a question, get an answer, move on. The moment you need an agent to actually do something — fetch data, update a database, make a decision across multiple steps — that model breaks. This is where architecture matters, and where most implementations fail within the first two weeks of production.

An AI agent is a loop, not a model. The model is the decision engine. The loop is the operating system that decides what happens next.

The Core Agent Loop

Every functional agent follows this pattern:

1. User provides input/context
2. LLM decides what to do (including: do nothing)
3. If the LLM chose an action:
   - Execute the tool
   - Capture the result
   - Return result to LLM
4. Repeat until the LLM says "I'm done"
5. Return final response to user

The loop is the contract. The model is the decision-maker inside it. Confuse these, and you’ll waste weeks debugging prompts when the real problem is your loop logic.

I learned this at AlgoVesta the hard way. We built an agent to analyze market data and execute trades. The prompt was locked in at 40% accuracy — until we realized the loop was calling the same tool twice, feeding it stale results from the first call, then wondering why the agent made bad decisions. The model was fine. The plumbing was broken.

Tool Calling: The Contract Between LLM and Code

Tool calling is how the LLM tells your code what to execute. It’s not a prompt technique. It’s an API contract.

Most models support it natively now — Claude (via tool_use block), GPT-4o (via function_calling), Mistral (via tool_call). The names differ. The concept is identical: the model returns structured data that says “run this tool with these parameters.”

Here’s what a basic tool definition looks like:

{
  "name": "fetch_user_data",
  "description": "Retrieves user account info including balance and transaction history",
  "input_schema": {
    "type": "object",
    "properties": {
      "user_id": {
        "type": "string",
        "description": "The unique user identifier"
      },
      "include_history": {
        "type": "boolean",
        "description": "Include transaction history (default: false)"
      }
    },
    "required": ["user_id"]
  }
}

The description matters. A vague description like “get data” results in the model using the tool wrong. A specific description like “Retrieves user account info including balance and transaction history” gives the model context to decide whether it needs this tool at all.

Here’s a real scenario: we had an agent that was supposed to check user eligibility before making decisions. It kept calling the wrong tool because the description was generic. Changed “Validate customer eligibility based on account age, balance, and transaction patterns” and the error rate dropped from 18% to 3%.

The tool definition is half prompt engineering. Write it clearly.

Memory: Conversation or State

This is where most hobby projects diverge from production systems.

Conversation memory (the chat history you feed back to the model) works until it doesn’t. Token limits exist. Claude Sonnet 4 has 200k tokens, but feeding a 6-month conversation history into every API call wastes tokens and slows inference. After AlgoVesta hit ~3,000 agent interactions per month, we realized we were burning budget on context the model didn’t need.

Production agents need two memory layers:

Short-term memory: The current conversation or task. Keep it tight — only the last 5–10 messages, or the last 5 minutes of interaction, whichever is smaller.

Long-term memory: Facts the agent needs to remember but doesn’t need in every prompt. Store this separately — a database, a vector store, or a structured knowledge base — and retrieve it only when relevant.

Here’s the pattern:

1. User sends message
2. Query long-term memory for relevant facts
3. Add those facts to the system prompt
4. Add recent conversation history (last N messages)
5. Send to LLM
6. If the agent learned something important, store it
7. Proceed with tool calling

For a trading agent, we store prior decisions and their outcomes. When the agent is deciding whether to execute a trade, we retrieve the last 5 similar trades and their results — not the entire conversation history, just the signal.

This is a 10-line change from “naive memory” to “scalable memory.” Most developers never make it.

Failure Handling and Retry Logic

A tool call fails. The database was slow. The API returned a timeout. What does the agent do?

If your loop just crashes, you’ve built a toy. Production agents need fallback logic.

Minimal viable pattern:

for attempt in range(max_retries):
    try:
        result = execute_tool(tool_name, params)
        if result.success:
            return result
    except ToolExecutionError as e:
        if attempt == max_retries - 1:
            # Final attempt failed. Tell the LLM.
            agent_message = f"Tool '{tool_name}' failed: {e}. Choose another approach."
            # Feed this back to the agent, let it decide next step
        else:
            time.sleep(2 ** attempt)  # exponential backoff
            continue

The critical line: tell the LLM that the tool failed, and let it decide what to do. It might retry, choose a different tool, or report the error to the user. You don’t decide — the agent does.

Putting It Together: A Minimal Agent Implementation

Start here. This is the shape of a real agent:

def run_agent(user_input, system_prompt, tools):
    messages = [{"role": "user", "content": user_input}]
    max_iterations = 10
    iteration = 0
    
    while iteration < max_iterations:
        iteration += 1
        
        # Call LLM with current messages and available tools
        response = client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=1024,
            system=system_prompt,
            tools=tools,
            messages=messages
        )
        
        # Check if LLM is done
        if response.stop_reason == "end_turn":
            return extract_text_response(response)
        
        # Process tool calls
        if response.stop_reason == "tool_use":
            tool_results = []
            for block in response.content:
                if block.type == "tool_use":
                    result = execute_tool(block.name, block.input)
                    tool_results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": json.dumps(result)
                    })
            
            # Add LLM response and tool results to messages
            messages.append({"role": "assistant", "content": response.content})
            messages.append({"role": "user", "content": tool_results})
    
    return "Agent exceeded max iterations"

This runs on Claude Sonnet 4. It's not production-hardened — add timeouts, logging, error handling — but it's the actual shape. The loop is explicit. The tool calling is visible. Memory is just the messages list (short-term only, for now).

Start Simple, Then Optimize

Build this loop first. Get tool calling working. Make sure your tools are discoverable and your descriptions are precise. Once the agent can execute a task reliably, add memory management and failure handling.

Most developers try to build the "perfect" agent from day one. You can't. You have to know what breaks first.

Take the loop above. Add two or three real tools you actually need. Run it for a day. Where did it fail? That's where you add complexity next.

Batikan
· 5 min read
Share

Stay ahead of the AI curve

Weekly digest of the most impactful AI breakthroughs, tools, and strategies.

Related Articles

Cursor vs GitHub Copilot vs Claude Code: Which Wins for Production Work
Learning Lab

Cursor vs GitHub Copilot vs Claude Code: Which Wins for Production Work

Three AI coding assistants dominate production environments. This isn't a feature list. It's a breakdown of what each actually does, where it fails, and which to use for architecture, boilerplate, and debugging.

· 10 min read
Analyze Spreadsheets With Claude and GPT-4o
Learning Lab

Analyze Spreadsheets With Claude and GPT-4o

Claude and GPT-4o can analyze your spreadsheets and CSVs, but only if you structure the data correctly and ask with precision. Learn how to upload files, write analysis prompts, and avoid hallucination pitfalls.

· 2 min read
LLM Hallucinations: Why They Happen and 5 Ways to Stop Them
Learning Lab

LLM Hallucinations: Why They Happen and 5 Ways to Stop Them

Why do language models confidently invent facts? Because they predict tokens, not truth. Learn how grounding, constraint prompting, and temperature settings cut hallucination rates from 15%+ to under 5% in production systems.

· 5 min read
Freelancer AI Workflows That Actually Increase Billable Hours
Learning Lab

Freelancer AI Workflows That Actually Increase Billable Hours

AI can double your freelance output without replacing your judgment. Learn four production workflows that compress administrative tasks and recover 10+ billable hours per month.

· 6 min read
Stop Hallucinating: How RAG Actually Grounds LLMs
Learning Lab

Stop Hallucinating: How RAG Actually Grounds LLMs

RAG grounds LLMs with your actual data, eliminating hallucinations. This guide explains how RAG works in production, why basic setups fail, and the specific patterns that work — with code examples and trade-offs.

· 6 min read
Where Your Prompts Go: Data Handling in ChatGPT, Claude, and Gemini
Learning Lab

Where Your Prompts Go: Data Handling in ChatGPT, Claude, and Gemini

ChatGPT stores your data and uses it for training by default. Claude doesn't train on web conversations unless you opt in. Gemini links your chats to your entire Google account. Here's what each model does with your prompts and how to protect sensitive information.

· 4 min read

More from Prompt & Learn

Otter vs Fireflies vs tl;dv: Meeting Transcription Shootout
AI Tools Directory

Otter vs Fireflies vs tl;dv: Meeting Transcription Shootout

Three tools promise to transcribe your meetings and extract action items. Only one integrates cleanly with your workflow. Here's the real comparison: Otter vs Fireflies vs tl;dv — accuracy data, pricing breakdowns, and honest pros/cons for each.

· 4 min read
Gamma vs Beautiful.ai vs Tome: Slide Generation Tested
AI Tools Directory

Gamma vs Beautiful.ai vs Tome: Slide Generation Tested

I tested Gamma, Beautiful.ai, and Tome on production presentations. Gamma generates fastest but struggles with branding. Beautiful.ai delivers visual consistency and data handling. Tome offers flexibility and collaboration. Here's what actually works in practice — and when each tool wins.

· 11 min read
App Store Launches Spike in 2026. AI Tooling Is the Catalyst
AI News

App Store Launches Spike in 2026. AI Tooling Is the Catalyst

Appfigures reports a measurable surge in app launches in 2026, driven by AI development tools that compress timelines from weeks to days. A solo developer with Claude or Mistral can now ship what required a full engineering team in 2022.

· 3 min read
Julius AI vs ChatGPT vs Claude for Data Analysis
AI Tools Directory

Julius AI vs ChatGPT vs Claude for Data Analysis

Julius AI, ChatGPT Advanced Data Analysis, and Claude Artifacts all handle data tasks, but execution speed, pricing, and workflow differ significantly. Here's how to pick the right one for your use case.

· 4 min read
Perplexity vs Google AI vs Consensus: Which Wins for Academic Research
AI Tools Directory

Perplexity vs Google AI vs Consensus: Which Wins for Academic Research

Perplexity, Google AI, and Consensus each excel at different research tasks. Perplexity wins on recent topics with real-time synthesis. Consensus delivers unmatched citation precision for peer-reviewed work. Google Scholar provides historical depth. This breakdown shows exactly which tool to use for your next paper—and why.

· 10 min read
Google’s Travel Tools Cut Planning Time in Half. Here’s What Actually Works
AI Tools Directory

Google’s Travel Tools Cut Planning Time in Half. Here’s What Actually Works

Google released seven integrated travel tools this spring. Price tracking predicts optimal booking windows, restaurant availability pulls real-time data, and offline maps work without cell coverage. Here's which features earn trust and where to set expectations.

· 3 min read

Stay ahead of the AI curve

Weekly digest of the most impactful AI breakthroughs, tools, and strategies. No noise, only signal.

Follow Prompt Builder Prompt Builder