E2E Testing for Chat, Voice, Phone and Video AI Agents

Run Thousands of Test Scenarios against Your Agent and Catch Hallucinations, Bias, and Toxicity Before Users Do.

How to Build an AI Agent (and Test It Before Users Do)

Part of: AI Testing

Build an AI agent in 8 steps: pick one job, a model, tools, memory and guardrails, then test it on real conversations before launch. Code or no-code.

Published

Summarise with AI

To build an AI agent, give a language model one clear job, the tools it needs to act (APIs, search, a database), instructions, and a loop that lets it plan, call a tool, read the result and decide what to do next. Then test it on realistic conversations before launch, because agents fail in ways unit tests miss.

  • Pick one job with a measurable outcome (for example, "resolve password-reset tickets").
  • Choose a model and an agent framework or a no-code builder.
  • Define the tools as functions with clear names, inputs and outputs.
  • Write the instructions: role, allowed actions, when to ask a human.
  • Add memory: conversation state now, long-term storage only if the job needs it.
  • Add guardrails: step limits, spend limits, approval for risky actions.
  • Test with scripted and adversarial conversations, then fix and retest.
  • Deploy behind monitoring and review failed conversations weekly.

Steps 1 to 6 follow two public references: Anthropic's engineering post Building effective agents and the OpenAI Agents SDK documentation. Steps 7 and 8 cover the part most guides skip: proving the agent works before and after real users reach it.

What Is an AI Agent (and What Isn't)?

An AI agent is a language model that uses tools in a loop: it decides which action to take, runs it, reads the result and repeats until the job is done.

Anthropic draws the line between two kinds of systems. Workflows are "systems where LLMs and tools are orchestrated through predefined code paths". Agents are systems where "LLMs dynamically direct their own processes and tool usage". In practice, Anthropic says, agents "are typically just LLMs using tools based on environmental feedback in a loop."

That gives you three parts to build:

  • Model: the language model that reads the conversation and decides the next step.
  • Tools: functions the model can ask your code to run, such as an order lookup, a search or a database query.
  • Loop: the code that sends the conversation to the model, runs any tool it asks for, returns the result and stops when the model gives a final answer or hits a limit.

A chatbot that only answers questions from its training data or a fixed FAQ is not an agent. It can't check your order status or reset a password, because it has no tools and no loop. A fixed pipeline that always calls the same three APIs in the same order isn't an agent either; that's a workflow, and Anthropic recommends "finding the simplest solution possible, and only increasing complexity when needed." If a workflow does the job, ship the workflow.

For a feel of what agents do in production today, browse these real AI agent examples.

Step 1: Choose a Job an Agent Can Finish

A common way for an agent project to fail is a job that is too broad ("handle customer support") or has no clear finish line. Pick one job that ends in a state you can check.

Good first jobWhy it worksSuccess metric
Resolve password-reset ticketsTwo or three tools, a clear end state, easy hand-off ruleShare of tickets closed without a human
Answer "where is my order?"One lookup tool, the answer is checkable against the order systemCorrect status given, measured on a sample
Triage bug reports into the right queueRead-only input, a small set of labels, low cost of a wrong guessAgreement with human triage

Poor first jobs share the opposite traits:

  • No finish line: "be our sales team" or "manage my inbox" can't be scored, so you can't tell whether a change helped.
  • Irreversible actions with no review: issuing refunds, deleting records or sending contracts on the agent's word alone.
  • Missing data: if a person needs three internal systems the agent can't reach, the agent will guess.

Write the success metric down before you write any code. It becomes the pass condition for your test suite in Step 7.

Step 2: Pick a Model and a Framework (Code) or a Builder (No Code)

You need a model that supports tool use (also called function calling) and something to run the loop. There are three common ways to get the loop:

ApproachBest forTrade-off
Model API with your own loopLearning how agents work; small agents with a few tools; full controlYou write retries, limits, logging and memory yourself
Agent framework or SDKProduction agents in Python or TypeScript; multi-agent setups; tracing out of the boxMore concepts to learn; framework updates can change behavior
No-code builderTeams without developers; agents that mostly connect existing SaaS toolsLess control over the loop; harder to version and test outside the builder

The OpenAI Agents SDK is a good picture of what a framework gives you. Its docs describe agents as "LLMs equipped with instructions and tools", plus handoffs that "allow agents to delegate to other agents", guardrails that "enable validation of agent inputs and outputs", sessions as "a persistent memory layer", and built-in tracing. Our list of agent frameworks compared covers LangGraph, CrewAI, Google ADK and others side by side.

How to build an AI agent without code: a no-code builder gives you the same three parts in a visual editor. You choose a model from a list, connect tools through prebuilt integrations, write the instructions in a text box and test the agent in a chat preview. Rather than repeat a list here, compare AI agent builders by use case. Whichever you pick, check that it lets you export conversations or run the agent from an API, because you'll need both for testing.

Single agent or multi-agent? Start with one agent. Split into several agents only when one agent's instructions or tool list get too long to follow reliably, for example a router agent that hands billing questions to a billing agent and technical questions to a support agent. Each handoff is one more place for a conversation to go wrong, so read up on how multi-agent systems are structured before you add the second agent.

Which model? Pick a current model from a provider whose API supports tool use, then let your Step 7 test suite decide between candidates. A cheaper model that passes the same suite is the better choice for that job.

Step 3: Give the Agent Tools

A tool is a function you describe to the model with a name, a description and an input schema. The model never runs your code. When it wants a tool, it returns a structured request; your loop runs the function and sends the result back. Anthropic's tool use docs describe the round trip: the model responds with stop_reason: "tool_use" and one or more tool_use blocks, and your code "runs the operation and sends back a tool_result".

How to build an AI agent in Python: the complete agent below uses the Anthropic Python SDK. It defines one tool, runs the loop, prints every tool call and stops after five model calls at most.

# weather_agent.py
# pip install anthropic   (and set the ANTHROPIC_API_KEY environment variable)
import anthropic

client = anthropic.Anthropic()

tools = [{
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string", "description": "City name, e.g. Paris"}},
        "required": ["city"],
    },
}]

def get_weather(city):
    return f"Light rain, 14 degrees Celsius in {city}"  # replace with a real weather API call

system = "You answer weather questions. Call get_weather before answering; never guess the weather."
messages = [{"role": "user", "content": "Do I need an umbrella in Paris today?"}]

for step in range(5):  # guardrail: at most 5 model calls per question
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=16000,
        system=system, tools=tools, messages=messages,
    )
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason != "tool_use":
        break  # the model answered instead of asking for a tool
    results = []
    for block in response.content:
        if block.type == "tool_use":
            print(f"Tool call: {block.name}({block.input})")
            results.append({"type": "tool_result", "tool_use_id": block.id,
                            "content": get_weather(**block.input)})
    messages.append({"role": "user", "content": results})

print(next((b.text for b in response.content if b.type == "text"), ""))

Run it from a terminal:

python weather_agent.py

You should see a line such as Tool call: get_weather({'city': 'Paris'}) followed by the model's answer, which will mention the rain and suggest an umbrella. The wording of the answer changes from run to run; the tool call is what you check.

What each part does:

  • tools tells the model what it may ask for. The description is what the model reads to decide when to call it, so write it for the model, not for a colleague.
  • for step in range(5) is the loop and the step limit in one line. Without a limit, a confused agent can keep calling tools.
  • messages.append(...) keeps the whole exchange, including tool calls and results, so the model sees what already happened.
  • tool_use_id ties each result to the call that asked for it.

Tool design rules. Anthropic's advice is to "Test how the model uses your tools" and to "Poka-yoke your tools", that is, shape them so they are hard to misuse. In practice: give each tool one job, use parameter names a new hire would understand, return short results with only the fields the agent needs, and return a clear error message (not a stack trace) when the input is wrong so the model can correct itself.

MCP in one paragraph. The Model Context Protocol is "an open-source standard for connecting AI applications to external systems". Instead of writing a tool wrapper for every service, you connect your agent to an MCP server that already exposes that service's tools (files, a database, a ticketing system), and any MCP-compatible client can use the same server. Use MCP when a server for your system already exists or when several agents need the same tools; write plain function tools when the agent needs two or three calls to your own API.

Step 4: Write Instructions That Hold Up

The instructions (the system prompt) are the agent's job description. Vague instructions are a common cause of an agent that "works in the demo" and fails with real users. Cover four things: the role, what the agent may do, what it must never do, and when to hand off to a person.

Here is an example for the password-reset agent from Step 1:

You are the password-reset assistant for Acme's customer support.

Your job: help a signed-in customer reset their account password.

You may:
- Look up the customer's account with get_account (use the email they give you).
- Send a reset link with send_reset_link, once per conversation.

You must not:
- Change an email address, phone number or payment details.
- Reveal any account information other than "a reset link was sent".
- Promise refunds, credits or anything outside password resets.

Hand off to a human (call escalate_to_human) when:
- The customer can't access the email on the account.
- The account is locked for fraud or the lookup returns an error twice.
- The customer asks for a person.

Style: short, plain sentences. Confirm what you did at the end.

Habits that keep instructions reliable:

  • Name the tools in the rules. "Call send_reset_link once" is clearer than "help them reset".
  • Write the hand-off rule as conditions, not feelings. "When the lookup fails twice" can be tested; "when the customer seems upset" is hard to test.
  • Keep the prompt in version control next to the code, so every change can be tied to a test run.
  • Don't rely on the prompt for security. If the agent must never change a payment method, don't give it a tool that can.

Step 5: Add Memory and State

Models don't remember anything between API calls. Whatever the agent "remembers" is what your code sends back with each request. There are two layers:

  • Conversation state (short-term): the list of messages, tool calls and tool results for the current conversation. In the Python example it's the messages list. Every agent needs this.
  • Long-term memory: facts that should survive the conversation, such as a customer's preferences or the outcome of a previous ticket. Store these in a database and load only what the current task needs.

Frameworks package both layers. The OpenAI Agents SDK has sessions for conversation history, and Anthropic offers a memory tool that lets the model "store and retrieve information across conversations in files you control".

Add long-term memory only when the job needs it. Every stored fact is one more thing that can be stale, wrong or leaked to the wrong user, and one more thing to test. For long conversations, also plan for the context window: trim or summarize old turns rather than sending every message forever.

Step 6: Add Guardrails: Max Steps, Cost Caps and Human Approval

An agent chooses its own next step, so you need limits it can't talk its way around. Anthropic recommends "stopping conditions (such as a maximum number of iterations) to maintain control", and notes that agents "can then pause for human feedback at checkpoints or when encountering blockers."

GuardrailWhat it stopsHow to add it
Max stepsLoops that never endA loop counter (the range(5) above). In the OpenAI Agents SDK, max_turns raises MaxTurnsExceeded when a run goes over.
Spend limitOne runaway conversation using a large share of your budgetAdd up the token counts each API response reports and stop the run when it passes your cap
Human approvalIrreversible actions taken on a wrong guessBefore running a risky tool (refund, delete, send), pause and ask a person; return "declined" to the model if they say no
Input and output checksOff-topic requests, leaked personal data, policy breaksValidate the user's message before the agent runs and the answer before it's shown; the OpenAI Agents SDK calls these guardrails
Least-privilege toolsDamage from prompt injectionGive tools read-only access where possible and scope API keys to the job

Decide what happens when a limit trips. A good default is a polite hand-off: "I can't finish this one, so I've passed it to a colleague", plus a log entry you review in Step 8.

Step 7: Test the Agent Before Launch

Unit tests check that your tools return the right data. They can't tell you whether the agent calls the right tool, follows its rules under pressure or invents an answer when a lookup fails. For that you need conversation-level tests, and TestMu AI's Agent Testing lets you test chat and voice agents before launch with simulated users. Anthropic gives the same advice in general terms: "extensive testing in sandboxed environments, along with the appropriate guardrails."

A pre-launch test plan has four parts:

  • Scenario suite. Write the conversations the agent must handle, from the happy path ("I forgot my password") to edge cases ("I no longer have access to that email"). Each scenario has an expected outcome tied to your Step 1 metric: reset link sent, hand-off called, or a refusal.
  • Personas. Run each scenario as different users: impatient, confused, non-native speaker, someone who changes their mind halfway. An agent that passes with a polite tester can still fail with an upset one.
  • Hallucination and policy checks. Compare every factual claim with your source data and check every action against the rules in Step 4. Include adversarial cases: requests to ignore the instructions, requests for another customer's data, and tool results that contain instructions.
  • Regression after every change. Rerun the full suite whenever you change the prompt, the model, a tool or the framework version. A one-line prompt edit that fixes one scenario can break three others.

Agent Testing runs these suites across chat, WhatsApp, voice, phone, video and image agents. Simulated users act out personas with accents, background noise and edge cases drawn from your docs. Answers are compared with your knowledge base to flag invented facts, and each suite gets a Green, Yellow or Red verdict with the failing turns linked, so you can rerun it on every release.

Building a voice agent? Before you set up a full suite, you can score a voice agent with simulated calls using our free audit tool.

Note

Note: Treat a failed test as a new rule or a better tool, not a reason to add more words to the prompt. Fix the cause, rerun the whole suite and only then ship. Run your first agent test suite.

Step 8: Deploy and Monitor the Agent

Launch to a small share of traffic first, with a person watching, and widen the rollout only when the live results match your test results.

  • Log every step. Store the user's message, each tool call with its input and output, the final answer, token counts and which limit (if any) ended the run. Frameworks with tracing, such as the OpenAI Agents SDK, record much of this for you.
  • Track the Step 1 metric. Watch the task success rate alongside the hand-off rate and cost per conversation.
  • Review failed conversations weekly. Pull every conversation that hit a limit, got a thumbs-down or ended in a hand-off. Group them by cause: wrong tool, missing tool, unclear rule, bad data.
  • Turn each failure into a test. Add the conversation to your Step 7 suite so the same failure can't come back unnoticed.

Anthropic's closing advice fits this step: "Prioritize transparency by explicitly showing the agent's planning steps." Logs that show each decision make the weekly review a short job.

How Long Does It Take to Build an AI Agent?

The Python agent above takes minutes to run. A production agent takes as long as its tools, rules and test suite take to get right, so the honest answer depends on how many systems the job touches and how strict your pass bar is.

Conclusion

Building an AI agent comes down to a model, a few well-described tools, clear instructions and a loop with limits. The Python example in this guide has all four. What separates a demo from an agent you can put in front of customers is Steps 7 and 8: a scenario suite you rerun on every change, and a weekly look at the conversations that went wrong.

Next step: Before you ship, run your agent through simulated conversations with TestMu AI Agent Testing.

To run your first agent test, start free, or
for a full walkthrough of the product.

Was this helpful?

Authors

Salman Khan

Salman Khan

Author · 138 posts

Salman is a Test Automation Evangelist and Community Contributor at TestMu AI, with over 6 years of hands-on experience in software testing and automation. He has completed his Master of Technology in Computer Science and Engineering, demonstrating strong technical expertise in software development, testing, AI agents and LLMs. He is certified in KaneAI, Automation Testing, Selenium, Cypress, Playwright, and Appium, with deep experience in CI/CD pipelines, cross-browser testing, AI in testing, and mobile automation. Salman works closely with engineering teams to convert complex testing concepts into actionable, developer-first content. Salman has authored 120+ technical tutorials, guides, and documentation on test automation, web development, and related domains, making him a strong voice in the QA and testing community.

Sai Krishna

Sai Krishna

Reviewer

Sai Krishna is Director of Engineering at TestMu AI, where he leads agentic AI for quality engineering, building AI agents that autonomously drive mobile and conversational test automation. His current focus is Agent Testing and Model Context Protocol (MCP) support for mobile. He is a core contributor and member of the Appium open-source project and the creator of AppiumTestDistribution and appium-device-farm. With over 14 years of experience including more than 9 years at Thoughtworks as a Principal Consultant, he holds a BSc in Electronics and speaks regularly at TestMu and Appium Conf on Appium, mobile automation, and agentic AI in testing.

How to Build an AI Agent FAQs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests