Telerik blogs

Building an AI agent is easier than ever. We connect a model, add a prompt and some tools, and soon we have an answer. But how do we know the agent made the right decisions?

I have seen answers that look complete and convincing, but which contain invented details or ignore a user’s request. This is called a hallucination, when the model presents invented information as fact. A polished answer can make those problems hard to spot, especially when we check each response by eye.

In this article, we will inspect an agent’s execution with Genkit. Then we will use the Developer UI to evaluate a sample plan: one evaluator checks its structure, and another judges its quality.

The Scenario: Our Family Travel Planner

In a previous article, we built a Family Travel Planner with Genkit. We used the Progress Nexus AI observability platform to see its tool calls and model requests.

Here, we’ll use a companion example based on the same travel-planning scenario. This time, we want to evaluate the plan itself. Does it include the required details? Do its activities and costs fit the family?

Our agent receives structured user requests:

  • Destination: Where the family wants to go (e.g., Ibiza)
  • Group Details: Number of adults and kids, including their exact ages.
  • Budget Preference: Categories like budget, moderate, comfortable or luxury.

To build the vacation plan, the agent has access to three Genkit tools:

  1. findFlights: Searches flights by destination and passenger count
  2. findHotels: Finds family-friendly hotels with amenities like kids’ pools
  3. findActivities: Discovers family-friendly attractions, filtered by the number of kids

The agent calls these tools, collects options and builds a structured travel plan with an estimated total cost.

Let’s make this work in a real project. To follow along, clone the companion repository from GitHub and install its dependencies:

git clone https://github.com/danywalls/genkit-agent-evaluations.git
cd genkit-agent-evaluations
npm install
cp .env.example .env

Open .env and add your Google AI Studio API key to GOOGLE_API_KEY.

Now let’s run the agent and see what its terminal output tells us.

Inspect the Agent’s Response

In our repository, we ask our planner for a five-day family trip to Ibiza for two adults and two young children (ages 6 and 7) on a moderate budget.

To run the agent from your terminal, execute:

npm run start

When we run the agent in the terminal, we get output like this. Your result can differ a little, such as the number of flights or the total cost, because the model is probabilistic:

==================================================
DESTINATION: Ibiza
DURATION:    5 days / 4 nights
SUMMARY:     An unforgettable family holiday in Ibiza designed for
parents and two young children (ages 6 and 7). Enjoy beautiful
family-friendly beaches, exciting boat trips, cultural exploration of
Dalt Vila, and relaxing resort amenities.

--- FLIGHTS ---
  1. Ryanair: 10:30 AM -> 12:15 PM (€74)
  2. Vueling: 07:15 AM -> 09:00 AM (€91)
  3. Iberia Express: 02:00 PM -> 03:45 PM (€128)

--- HOTEL ---
  Hotel Talamanca (4 stars) - €165
  Amenities: Beach access, Kids pool, Restaurant, Free WiFi

--- ACTIVITIES ---
  1. [water-sport] Catamaran Sunset Cruise (€45)
     Sail along the Ibizan coast, swim in crystal-clear coves, and watch the sunset from the water.
  2. [cultural] Dalt Vila Museum & Old Town (€12)
     Explore the charming Dalt Vila with its cobblestone streets and panoramic views.
  3. [family-fun] Cala Conta Family Beach Day (Free)
     Shallow, calm waters perfect for young children.
  4. [dining] San Juan Market & Paella (€25)
     Visit the hippy market followed by paella at a beachfront restaurant.

==================================================
TOTAL ESTIMATED COST: €1,356
==================================================

The response looks polite, detailed and well-structured. Everything seems fine. But how do we know it actually followed our rules?

Did it call the flight tool or invent prices? Did it pick a party beach instead of a calm one? If we change one sentence in the system prompt tomorrow, will it break an itinerary that worked today?

Reading terminal output alone leaves us guessing. Let’s inspect what Genkit recorded during this run.

Inspect the Execution with the Genkit Developer UI

Genkit comes with built-in tracing based on OpenTelemetry standards. A trace records the steps in a request. Each step is represented by a span, such as a flow, tool execution or model call.

To inspect how our agent operates, start the Genkit Developer UI:

npm run dev

This command starts the local Genkit development server. Open the dashboard at http://localhost:4000.

The Developer UI is more than a simple log viewer. In the left sidebar, it organizes your project into two main sections:

  • Runners: Lets you inspect and run individual components in isolation, including Flows, Tools, Models and Evaluators.
  • Observability: Provides views for Traces, Evaluations and Datasets.

At http://localhost:4000, click Traces and select the latest run for travelPlannerFlow. You should see the flow, model calls and any tool calls made during that run:


The Genkit Developer UI displays the full trace waterfall with green status badges for each tool and model call.

Let’s break down what the example trace below shows us:

  1. travelPlannerFlow (Root Span): This is the top-level boundary of our agent. It shows the total execution time (2.89s) and total token counts (757 input tokens, 705 output tokens).
  2. generate (First Model Call): Inside the flow, Genkit records the initial call to Gemini. The model inspects the prompt and decides which tools it needs to call.
  3. Tool Execution Spans (findFlights, findHotels, findActivities): The model triggers three tool calls in sequence. Each tool execution appears as its own span, recording duration (1-2ms) and exact arguments.
  4. generate (2) (Second Model Call): After the tools return their data, Gemini runs a second call. It takes the tool results and builds the final plan using our output schema.

Important: Your model and tool calls may differ.

You can click on any span in this tree to inspect its exact input payload, output payload, latency and system attributes.

Seeing every bar in green feels great. But is it enough?

Why a Green Trace Is Not Enough

Look closer at that trace in the Developer UI. Every span completed with a green checkmark. There are zero runtime errors.

Does that mean the vacation plan is good?

Not necessarily. The trace proves that findActivities ran without crashing. It does not verify whether the activities suit a 6-year-old child. It also cannot tell you if the total cost respected the family’s budget.

Here is the key distinction every agent developer needs to know:

  • Observability answers: “What happened during execution?” It tracks spans, latency, tool arguments and runtime errors.
  • Evaluation answers: “Did the output meet our quality requirements?” It tests whether the agent solved the user problem accurately and safely.

To judge the output itself, we need checks that measure the qualities we care about. Let’s define those checks and try them in the Developer UI.

Turn Expectations into Evaluation Criteria

Before writing code, we need to define what a good travel plan means. The Chrome AI Evals mental model gives us three useful terms:

  • A criterion describes what matters in the result.
  • A metric is the measurement or score for that criterion.
  • An evaluator is the code or model that produces the score.

For our Family Travel Planner, we divide expectations into two evaluators:

CriterionEvaluator TypeWhat We Check
Structure & completenessDeterministic ruleFlights, hotel, activities and estimated cost exist
Quality & fitLLM Judge (with rubric)Activities suit children’s ages, and price fits budget

Genkit provides first-class support for defining both types of evaluators.

We know what to measure. Let’s make this work in a real project. Evaluators need an agent that Genkit can observe, so let’s review how ours is built.

Define the Agent as a Genkit Flow

What problem does ai.defineFlow solve for us as developers? A standard function is not registered as a Genkit flow. When you wrap your logic in ai.defineFlow, Genkit automatically:

  1. Validates inputs and outputs against Zod schemas before and after execution.
  2. Creates an OpenTelemetry trace boundary for the entire request.
  3. Registers the flow in the Developer UI so you can run it interactively and evaluate it.

Open src/agent.ts in the repository. You do not need to change it. Here is how the flow is declared:

// src/agent.ts
export const travelPlannerFlow = ai.defineFlow(
  {
    name: 'travelPlannerFlow',
    inputSchema: TravelRequestSchema,
    outputSchema: TravelPlanSchema,
  },
  async (input) => {
    // Agent execution logic...
  }
);

The name property identifies this flow in the Developer UI. The inputSchema and outputSchema use Zod to enforce typed contracts. If someone calls the flow without a destination, Genkit rejects it before touching the model. The other fields have default values.

Inside the flow, we use ai.generate to prompt Gemini and provide our three tools:

// src/agent.ts (inside flow body)
const response = await ai.generate({
  model: modelName,
  prompt, // built from the request, see below
  tools: [findFlightsTool, findHotelsTool, findActivitiesTool],
  output: { schema: TravelPlanSchema },
});

return response.output;

The prompt is a template string built before this call. This is the core of it:

You are a local Ibizan family travel expert. Create a detailed travel plan
for a family visiting ${input.destination}.

Number of adults: ${input.numAdults}
Number of children: ${input.numKids} (ages: ${normalizedKidAges.join(', ')})
Total passengers: ${numPassengers}
Budget preference: ${input.budget}

Use the provided tools to find flights, hotels, and activities.
Then create a comprehensive travel plan.

IMPORTANT:
- Recommend activities appropriate for the children's ages.
- Provide realistic cost estimates in euros.
- Return the results in the exact JSON format requested.

Notice the tools array. Gemini inspects the user prompt, recognizes that it needs flight, hotel and activity data, and decides which tools to call.

Once the tools respond, output: { schema: TravelPlanSchema } instructs Gemini to assemble the final response into structured JSON matching our contract.

Our agent now returns a fixed, typed structure. That makes the first evaluator easy: check that the required data exists.

Build a Deterministic Evaluator for Structure

Open src/evals/evaluators.ts. In Genkit, an evaluator is an action registered using ai.defineEvaluator. Each evaluator receives a datapoint object containing:

  • testCaseId: A unique name for the test scenario
  • input: The original request sent to the agent
  • output: The response generated by the agent flow

Our first evaluator checks whether the generated plan satisfies basic structural requirements. We write this as five deterministic boolean checks:

// src/evals/evaluators.ts
const checks = [
  {
    name: 'Matches destination',
    passed: output.destination.toLowerCase() === input.destination.toLowerCase(),
  },
  { name: 'Includes flight options', passed: output.flights.length > 0 },
  { name: 'Includes hotel recommendation', passed: Boolean(output.hotel.name) },
  { name: 'Includes activities', passed: output.activities.length > 0 },
  { name: 'Includes estimated total cost', passed: Boolean(output.totalEstimatedCost) },
];

These checks run in pure TypeScript. They execute in less than a millisecond, cost zero tokens and don’t hallucinate. If the model forgets to include flights, the check fails immediately.

Now we wrap those checks inside ai.defineEvaluator:

// src/evals/evaluators.ts
export const planStructureEvaluator = ai.defineEvaluator(
  {
    name: 'planStructure',
    displayName: 'Plan Structure (Deterministic)',
    definition: 'Validates that flights, hotel, activities, and cost are present.',
  },
  async (datapoint) => {
    const input = datapoint.input as TravelRequest;
    const output = datapoint.output as TravelPlan;

    // Run the checks...
    const passedCount = checks.filter((c) => c.passed).length;
    const allPassed = passedCount === checks.length;

    return {
      testCaseId: datapoint.testCaseId,
      evaluation: {
        score: allPassed ? 1 : 0,
        status: allPassed ? 'PASS' : 'FAIL',
        details: { passed: `${passedCount}/${checks.length}`, checks },
      },
    };
  }
);

Notice the return shape:

  • score: 1 if all checks passed, 0 otherwise
  • status: A clean 'PASS' or 'FAIL' label
  • details: An object with individual check results for debugging

Our structure checks cover the skeleton of the plan. But they say nothing about its quality.

Build an LLM Judge Evaluator for Subjective Quality

Think of deterministic checks as strict TypeScript types: fast, free and exact. They can verify that activities exist. But can a TypeScript rule decide if a catamaran sunset cruise is safe for a 5-year-old child?

It cannot. Subjective quality needs judgment. Think of the LLM judge as a senior code reviewer. It is slower and costs tokens, but it understands context.

We build an LLM-as-a-judge evaluator in the same file.

First, we define a strict output schema using Zod:

// src/evals/evaluators.ts
const JudgeSchema = z.object({
  kidSuitability: z.object({
    score: z.number().int().min(0).max(2),
    reason: z.string(),
  }),
  budgetAlignment: z.object({
    score: z.number().int().min(0).max(2),
    reason: z.string(),
  }),
});

With JudgeSchema, the judge returns integer scores and short explanations instead of long markdown text.

Next, we define an explicit 0 to 2 rubric in the judge prompt. The prompt lives inside the evaluator, because it needs the input and output of each test case:

You are an expert travel evaluation judge. Evaluate this family vacation plan.

Input Request: ${JSON.stringify(input)}
Generated Plan: ${JSON.stringify(output)}

Rubric for kidSuitability (0 to 2):
- 0: Dangerous or inappropriate activities for the children's ages.
- 1: Acceptable but some activities lack kid amenities or fit.
- 2: Excellent shallow calm beaches, kid pools, and age-appropriate fun.

Rubric for budgetAlignment (0 to 2):
- 0: Obvious mismatch with the stated budget preference.
- 1: Acceptable estimate but missing cost transparency.
- 2: Thoughtful choices aligning with the stated budget preference.

The rubric is the most important part of an LLM judge. Without clear criteria, judges give inconsistent scores. With a 0 to 2 scale, the model has concrete guidelines for each score.

Finally, we wrap this judge in ai.defineEvaluator:

// src/evals/evaluators.ts
export const travelQualityJudgeEvaluator = ai.defineEvaluator(
  {
    name: 'travelQualityJudge',
    displayName: 'Travel Quality (LLM Judge)',
    definition: 'Uses an LLM judge to evaluate kid-friendliness and budget alignment.',
  },
  async (datapoint) => {
    const input = datapoint.input as TravelRequest;
    const output = datapoint.output as TravelPlan;

    const response = await ai.generate({
      model: modelName,
      prompt: `...the judge prompt above...`,
      output: { schema: JudgeSchema },
    });

    const result = response.output;
    if (!result) {
      throw new Error('The LLM judge did not return a structured result.');
    }

    const avgScore = (result.kidSuitability.score + result.budgetAlignment.score) / 4;

    return {
      testCaseId: datapoint.testCaseId,
      evaluation: { score: avgScore, details: result },
    };
  }
);

Run the Evaluators in the Developer UI

With the Genkit Developer UI running, both evaluators appear in the sidebar under Evaluators:


The Genkit Developer UI lists both the deterministic planStructure evaluator and the travelQualityJudge evaluator.

Select planStructure at http://localhost:4000/evaluators/planStructure. Replace the JSON in Input (JSON) with this sample request and plan.

This is browser input, so you do not need to create a file:

{
  "dataset": [
    {
      "testCaseId": "ibiza-family-moderate",
      "input": {
        "destination": "Ibiza",
        "numAdults": 2,
        "numKids": 2,
        "kidAges": [6, 7],
        "budget": "moderate"
      },
      "output": {
        "destination": "Ibiza",
        "duration": "5 days / 4 nights",
        "summary": "A family holiday with calm beaches and a kids pool.",
        "flights": [
          {
            "airline": "Ryanair",
            "departure": "10:30 AM",
            "arrival": "12:15 PM",
            "price": "€74",
            "stops": 0
          }
        ],
        "hotel": {
          "name": "Hotel Talamanca",
          "rating": 4,
          "pricePerNight": "€165",
          "amenities": ["Beach access", "Kids pool"]
        },
        "activities": [
          {
            "name": "Cala Conta Family Beach Day",
            "category": "family-fun",
            "costPerPerson": "Free",
            "duration": "Half day",
            "description": "Shallow, calm waters for young children."
          }
        ],
        "totalEstimatedCost": "€1,486"
      }
    }
  ],
  "evalRunId": "ibiza-manual-run"
}

Click Run. The output should show PASS with all five checks passing:


The planStructure runner returns PASS with 5/5 structure checks for the sample Ibiza datapoint.

Now select travelQualityJudge at http://localhost:4000/evaluators/travelQualityJudge. Paste the same JSON into Input (JSON) and click Run.

The judge makes a separate Gemini call, so this step uses tokens. The output includes a score and a reason for each criterion:


The LLM judge scores kid suitability and budget alignment, then explains each result.

The screenshot is one possible result. The judge uses a 0-to-2 scale for each criterion, and its scores and reasons can vary between runs. Its overall score combines both criteria on a 0-to-1 scale.

These runs evaluate the JSON we supplied. They do not generate a new plan or automatically test future prompt changes. A passing structure check also does not guarantee a safe or affordable trip, and an LLM judge can be wrong.

Recap

We learned how things happen behind the scene, with the trace like a trip log: it shows which stops the agent made. The evaluators are the checklist for the trip itself. One checks that the plan has the required pieces. The other judges its fit for the family and explains its reasoning.

We tested both evaluators with one sample in the Genkit Developer UI. Try changing the plan or the family request and compare the results. Remember that the judge’s answer is a model assessment, not verified travel advice.

But one more thing. We have tested our evaluators locally. But what happens when the agent reaches production and handles real requests?

In the next article, we will combine Genkit with the Progress Nexus AI observability platform and use Evaluation Tasks to evaluate historical and incoming traces.


About the Author

Dany Paredes

Dany Paredes is a Google Developer Expert on Angular and Progress Champion. He loves sharing content and writing articles about Angular, TypeScript and testing on his blog and on Twitter (@danywalls).

Related Posts

Comments

Comments are disabled in preview mode.