Velamuvi AIAcademy

Lesson 24 of 39 · Control, Safety and Quality

Evaluations and Testing

Test agents like code with evaluate_agent: local checks, expected tool calls, custom evaluators, workflow evaluations, FoundryEvals and a CI gate.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why agents need evaluations as well as ordinary tests
  • Run an agent against test queries with evaluate_agent and LocalEvaluator
  • Check tool calls and their arguments with ExpectedToolCall
  • Write your own checks with @evaluator and fail a build with raise_for_status
  • Evaluate a workflow per agent, and know when to use FoundryEvals

Testing something that answers differently every time

A normal function returns the same result for the same input, so assert result == 35 works. A model words its answer differently on every run, and a prompt change that fixes one question can break three others. So instead of one exact answer, you check properties of the answer, on a fixed set of test questions, every time you change something.

The whole idea in plain Python:

Try it yourselfPython
# An evaluation in plain Python: fixed test queries, checks on each answer, a pass count.
def agent(query):
    return "A City E costs 35 EUR a day." if "cost" in query else "I can help with rentals."


def mentions_euros(query, answer):
    return "EUR" in answer


def stays_short(query, answer):
    return len(answer) < 60


checks = [mentions_euros, stays_short]
queries = ["How much does a City E cost?", "Can I rent a helmet?"]

passed = 0
for query in queries:
    answer = agent(query)
    failed = [check.__name__ for check in checks if not check(query, answer)]
    passed += not failed
    print(f"{query!r}: {'pass' if not failed else 'fail ' + str(failed)}")
print(f"{passed} of {len(queries)} passed")

Agent Framework gives you the same loop as evaluate_agent(), ready-made checks, and a way to plug in cloud evaluators.

Your first evaluation

A LocalEvaluator runs check functions on your computer, with no extra API calls. keyword_check() and tool_called_check() are two ready-made checks:

import asyncio

from agent_framework import Agent, LocalEvaluator, evaluate_agent, keyword_check, tool, tool_called_check
from agent_framework.openai import OpenAIChatClient


@tool
def refund(booking_id: str, amount_eur: float) -> str:
    """Refund money for a booking."""
    return f"Refunded {amount_eur:.0f} EUR for {booking_id}."


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        name="rental_desk",
        instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day. Use refund() for refunds.",
        tools=[refund],
    )
    checks = LocalEvaluator(
        keyword_check("EUR"),          # every answer must mention euros
        tool_called_check("refund"),   # and the refund tool must be called
    )
    results = await evaluate_agent(
        agent=agent,
        queries=["How much does a City E cost?", "Please refund 35 EUR for booking B-1042."],
        evaluators=checks,
    )

    report = results[0]                # one EvalResults per evaluator
    print(f"{report.provider}: {report.passed} of {report.total} passed")
    for item in report.items:
        print(f"{item.input_text} -> {item.status}")
        for score in item.scores:
            if not score.passed:
                print(f"    {score.name}: {score.sample['reason']}")


asyncio.run(main())
Output
Local: 1 of 2 passed
How much does a City E cost? -> fail
    tool_called: Expected tools not called: ['refund'] (called: [])
Please refund 35 EUR for booking B-1042. -> pass

evaluate_agent() returns a list with one EvalResults per evaluator. Each result has passed, failed, total and all_passed, and its items hold one result per query, with a score and a reason for every check. Here the price question failed, but not because the agent was wrong: a global tool_called_check("refund") doesn't fit a question that needs no tool. Checks that depend on the query belong with the query, as in the next section.

Expected tool calls

For agents with tools, the most useful question is often "did it call the right tool with the right arguments?" Give each query its own list of ExpectedToolCall objects and use two built-in checks: tool_calls_present (every expected tool was called) and tool_call_args_match (the arguments match; extra arguments are fine):

import asyncio

from agent_framework import (
    Agent,
    ExpectedToolCall,
    LocalEvaluator,
    evaluate_agent,
    tool,
    tool_call_args_match,
    tool_calls_present,
)
from agent_framework.openai import OpenAIChatClient


@tool
def refund(booking_id: str, amount_eur: float) -> str:
    """Refund money for a booking."""
    return f"Refunded {amount_eur:.0f} EUR for {booking_id}."


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        name="rental_desk",
        instructions="You are Velo's rental desk in Porto. Use refund() for refunds, once per booking.",
        tools=[refund],
    )
    results = await evaluate_agent(
        agent=agent,
        queries=[
            "Please refund 35 EUR for booking B-1042.",
            "Please refund 35 EUR for bookings B-1042 and B-2077.",
        ],
        expected_tool_calls=[
            [ExpectedToolCall("refund", {"booking_id": "B-1042", "amount_eur": 35})],
            [ExpectedToolCall("refund", {"booking_id": "B-1042"}), ExpectedToolCall("refund", {"booking_id": "B-2077"})],
        ],
        evaluators=LocalEvaluator(tool_calls_present, tool_call_args_match),
    )

    for item in results[0].items:
        print(f"{item.input_text} -> {item.status}")
        for score in item.scores:
            if not score.passed:
                print(f"    {score.name}: {score.sample['reason']}")


asyncio.run(main())
Output
Please refund 35 EUR for booking B-1042. -> pass
Please refund 35 EUR for bookings B-1042 and B-2077. -> fail
    tool_call_args_match: Tool call args match: 1/2
  refund: args match
  refund: args mismatch (actual: [{'booking_id': 'B-1042', 'amount_eur': 35.0}])

The second test found a real bug: the agent refunded only the first of two bookings. tool_calls_present passed, because refund was called, but tool_call_args_match caught the missing B-2077. That's why you usually want both.

Your own checks, and a CI gate

The @evaluator decorator turns a plain function into a check. Its parameter names choose what it receives: query, response, expected_output, conversation, tools, context or expected_tool_calls. Return True/False, a score from 0 to 1 (0.5 and above passes), or a dictionary with a score or passed key.

import asyncio
import re

from agent_framework import Agent, EvalNotPassedError, LocalEvaluator, evaluate_agent, evaluator
from agent_framework.openai import OpenAIChatClient


@evaluator
def no_card_numbers(response: str) -> bool:
    # The parameter names choose the data: query, response, expected_output, conversation, tools ...
    return not re.search(r"\b(?:\d[ -]?){13,19}\b", response)


@evaluator(name="same_price")
def same_price_as_expected(response: str, expected_output: str) -> bool:
    return expected_output in response


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        name="rental_desk",
        instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
    )
    results = await evaluate_agent(
        agent=agent,
        queries=["How much does a City E cost?", "What's the daily price of a City E?"],
        expected_output=["35 EUR", "30 EUR"],     # the second answer key is out of date
        evaluators=LocalEvaluator(no_card_numbers, same_price_as_expected),
    )

    try:
        results[0].raise_for_status()               # the line that fails your CI build
    except EvalNotPassedError as error:
        print("EvalNotPassedError:", error)


asyncio.run(main())
Output
EvalNotPassedError: Eval run Eval: rental_desk completed: 1 passed, 1 failed. Error: same_price: failed

expected_output gives each query a reference answer, one per query, for checks that compare against it. raise_for_status() raises EvalNotPassedError when any item failed. Put it at the end of a test and your CI build fails whenever the agent gets worse. Here the failure is in the test data, not the agent: the answer key still says 30 EUR. Failed evaluations are worth reading before you "fix" the agent.

Evaluating workflows

evaluate_workflow() runs a workflow on test queries and scores the final output and each agent in it. The per-agent results are in sub_results:

import asyncio

from agent_framework import Agent, LocalEvaluator, evaluate_workflow, keyword_check
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import SequentialBuilder


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    pricer = Agent(client=client, name="pricer", instructions="You find Velo's prices. A City E costs 35 EUR a day.")
    writer = Agent(client=client, name="writer", instructions="You turn facts into one friendly sentence.")
    workflow = SequentialBuilder(participants=[pricer, writer]).build()

    results = await evaluate_workflow(
        workflow=workflow,
        queries=["How much does a City E cost?"],
        evaluators=LocalEvaluator(keyword_check("EUR")),
    )
    report = results[0]
    print(f"whole workflow: {report.passed} of {report.total} passed")
    for name, sub in report.sub_results.items():
        print(f"  {name}: {sub.passed} of {sub.total} passed")


asyncio.run(main())
Output
whole workflow: 1 of 1 passed
  pricer: 1 of 1 passed
  writer: 1 of 1 passed

When the overall score drops, the per-agent breakdown shows which agent caused it. Pass workflow_result= instead of queries= to evaluate a run you already have.

Cloud evaluators: FoundryEvals

Some qualities need a judge, not a keyword: is the answer relevant, did the agent stick to its task, were the tool calls sensible? FoundryEvals sends your items to Microsoft Foundry, where a judge model scores them with built-in evaluators such as relevance, task_adherence and tool_call_accuracy, and the results appear in the Foundry portal.

from agent_framework.foundry import FoundryChatClient, FoundryEvals
from azure.identity.aio import DefaultAzureCredential

judge = FoundryChatClient(
    project_endpoint="https://velo.services.ai.azure.com/api/projects/velo",
    model="MODEL_NAME",                       # the model that acts as the judge
    credential=DefaultAzureCredential(),
)
foundry_evals = FoundryEvals(
    client=judge,
    evaluators=[FoundryEvals.RELEVANCE, FoundryEvals.TASK_ADHERENCE, FoundryEvals.TOOL_CALL_ACCURACY],
)
# Use it like LocalEvaluator: evaluate_agent(agent=agent, queries=queries, evaluators=foundry_evals)

This needs a Foundry project, so it only shows the setup. FoundryEvals follows the same Evaluator protocol as LocalEvaluator: a name and an async evaluate(items, eval_name=...) method that receives EvalItem objects and returns EvalResults. You can implement the protocol yourself to plug in any other scoring service.

Common mistakes

Practice exercise

Write the check behind tool_call_args_match: an expected call matches when some actual call has the same name and contains every expected argument.

Your solutionPython
def args_match(expected, actual_calls):
    """True if some actual call has the expected name and contains every expected argument."""
    # Look at each actual call: the name must be the same, and every expected
    # argument must have the same value in the call (extra arguments are fine).
    return False


calls = [{"name": "refund", "arguments": {"booking_id": "B-1042", "amount_eur": 35}}]
print(args_match({"name": "refund", "arguments": {"booking_id": "B-1042"}}, calls))
print(args_match({"name": "refund", "arguments": {"booking_id": "B-2077"}}, calls))
print(args_match({"name": "cancel", "arguments": {}}, calls))
print(args_match({"name": "refund", "arguments": {"booking_id": "B-1042", "amount_eur": 35}}, calls))
Knowledge check

An agent called refund for booking B-1042, but the customer asked about two bookings. Which check catches it?

Summary

  • Evaluations run an agent on fixed test queries and score each answer with checks, because model output changes from run to run.
  • evaluate_agent() with a LocalEvaluator runs fast, free checks such as keyword_check() and tool_called_check().
  • ExpectedToolCall with tool_calls_present and tool_call_args_match checks tools and their arguments per query.
  • @evaluator turns any function into a check; raise_for_status() raises EvalNotPassedError to fail a CI build.
  • evaluate_workflow() scores each agent of a workflow, and FoundryEvals adds judge-based evaluators from Microsoft Foundry.

Next: DevUI: Run and Debug Agents Locally.

Finished reading? Tick it off to track your progress.