Google just shipped a closed-loop improvement pipeline that turns your agent's session data into better prompts automatically. No hand-editing. No guessing what went wrong. The system evaluates sessions, generates ground truth, optimizes the prompt, and validates against a growing regression gate. In their demo, a policy Q&A agent went from ~60% useful responses to ~99% in one automated run.

Here is how it works and why it matters for production agent operations.

The Problem: Your Anti-Hallucination Guardrail Is Eating Your Tools

Google's demo uses a company policy Q&A agent built with the Agent Development Kit and Gemini 2.5 Flash. Two tools. One retrieves policy data. One returns the current date.

The V1 prompt looks reasonable:

You are a helpful company information assistant. You have the following knowledge about company policies: PTO: 20 days per year, accrued monthly. Up to 5 unused days roll over. Sick leave: 10 days per year, does not roll over. Remote work: Up to 3 days per week with manager approval. Benefits: The company offers competitive benefits. Answer questions using only the information above. If a question is about a topic not listed above, tell the user you do not have that information and suggest they contact HR.

The golden eval set passes. Three hand-written cases. Three passes. The agent looks solid.

Then they sent 100 synthetic employee questions through it.

35% came back with "I do not have that information, contact HR." The agent had a lookupcompanypolicy tool that covers PTO, sick leave, remote work, expenses, benefits, and holidays. It had the answers. It just would not use them.

The anti-hallucination instruction "only answer from what I told you" worked exactly as designed. The prompt listed PTO, sick leave, and remote work explicitly. It said nothing about dental coverage, 401k matching, holiday schedules, or expense details. For topics mentioned in the prompt, the model called the tool. For topics absent from the prompt, the model had no signal that the tool might help, so it obeyed the refusal instruction.

The agent had the capability. The prompt blocked it from trying.

This is a systemic failure mode. You write a tight prompt to prevent hallucinations. You inadvertently train the model to ignore its own tools when the topic is not explicitly named. The guardrail becomes a cage.

The Pipeline: Five Components in a Loop

Google's solution is not a new model. It is a measurement and optimization loop built on top of existing infrastructure.

BigQuery Agent Analytics Plugin

One line of code in the agent definition. Every session streams into BigQuery: user queries, agent responses, complete tool call trajectories with arguments and results, LLM request/response pairs, per-step latencies, token counts, and error states. No custom logging. No extra instrumentation.

BigQuery becomes the observability layer. Every interaction is queryable. Every failure is traceable.

CategoricalEvaluator

This uses LLM-as-a-judge to evaluate sessions at scale. For each session, it reads the user question, the agent response, and the tool calls. Then it classifies on two dimensions: response usefulness (meaningful, partial, unhelpful) and task grounding (was the answer derived from tool output or fabricated?).

The evaluator constructs an AI.GENERATE query inside BigQuery and runs the judge as a single SQL job. All sessions are scored server-side in one pass. The output is a quality report with category distributions, per-session verdicts with natural-language justifications, and sample questions for each verdict.

Sessions scored unhelpful or partial become candidates for extraction, ground truth generation, and prompt optimization.

CodeEvaluator

This runs deterministic checks on the same sessions: average latency, token usage per session, turn count, and tool error rate. Pure SQL aggregations on data already in BigQuery. No LLM needed.

Each metric is compared against a configurable budget. Latency under 10 seconds. Tokens under 50,000. Tool error rate under 0.1. Pass or fail. These numbers serve as the operational baseline and can gate every pull request.

Teacher Agent and Knowledge Distillation

The Prompt Optimizer needs input and expected output pairs. You have the inputs and the bad outputs. You need the ground truth.

A generic teacher agent generates correct, tool-grounded answers as training data for the production student agent. The teacher has no domain knowledge, no style guidelines, and no formatting rules. Its sole purpose is to produce factually correct ground truth.

The student is the production agent with the tuned prompt, personality, tone, and safety guardrails. The Optimizer figures out how to make the student produce answers of teacher quality while preserving its own style and constraints.

In production, the teacher would typically be a stronger model. Or you could use an AI-aided human-in-the-loop process where a domain expert reviews and corrects teacher outputs. The pipeline handles them the same way.

Vertex AI Prompt Optimizer and Prompt Registry

The Registry stores and versions prompts in the cloud. Each change creates a new version with a full audit trail.

The Optimizer operates in target-response mode. Given the current prompt, examples of incorrect and correct outputs, and the agent's tool signatures, it generates a new system instruction that closes the gap. Server-side job. Typically 2-4 minutes.

Regression Gate

Every candidate prompt must pass all golden eval cases before promotion. The golden set starts with hand-written cases and grows as new failures are discovered. In the demo, 12 failed cases were extracted and added to the original 3, creating a 15-case regression gate.

Changes never break what was already working. The gate grows with every cycle.

The Results: One Cycle, 12 Minutes, ~60% to ~99%

The demo ran at scale: 100 questions per batch, up to 3 cycles, auto-stopping at 95% quality. Total run time: ~12 minutes.

Before

  • Meaningful responses: 64%
  • Partial: 1%
  • Unhelpful: 35%
  • Not grounded in tool output: 9%

Operational baseline: 1,482 ms average latency, 811 tokens per session, 1 turn, zero tool errors.

After

  • Meaningful responses: 99%
  • Partial: 0%
  • Unhelpful: 1%
  • Operational metrics stayed within budget.

The Optimizer rewrote the prompt to remove the anti-hallucination cage. The new prompt told the agent to use the lookup tool for any company policy question and to defer to HR only when the tool returned no data. The model now had permission to discover answers through its own tools instead of being restricted to an explicit whitelist in the prompt.

Why This Matters for Production

This is not a research curiosity. It is a production pipeline with specific implications for how teams run agents.

Your Eval Set Is Too Small

Three hand-written cases passed. One hundred real questions exposed a 35% failure rate. Golden eval sets are necessary sanity checks, but they are not stress tests. You need synthetic or real traffic at scale to find the gaps your manual tests missed.

Anti-Hallucination Patterns Can Break Tools

The "only answer from what I told you" instruction is common. It prevents hallucinations by restricting the model to explicit prompt content. But it also prevents the model from using tools that contain information not explicitly named in the prompt. If you bake domain knowledge into the prompt and tell the model to stay inside it, you are training it to ignore its own retrieval capabilities.

The fix is not to remove guardrails. It is to move the guardrail from the prompt content to the tool contract. Tell the model to use the tool first, then judge whether the output is sufficient. Do not pre-judge sufficiency in the prompt.

Measurement Drives Improvement

The CategoricalEvaluator's two-dimensional scoring is the engine. Response usefulness tells you whether the user got what they needed. Task grounding tells you whether the agent used its tools or hallucinated. You need both. A helpful but ungrounded answer is a liability. A grounded but unhelpful answer is a missed tool call or a missing policy.

Automated Ground Truth Generation Scales

Manually writing correct answers for 35 unexpected failure categories is impractical. The teacher agent generates ground truth automatically. In production, you would validate teacher outputs with domain experts. But the pipeline removes the bottleneck of manual curation.

Regression Gates Prevent Backsliding

Without the regression gate, the Optimizer might fix the tool-calling problem while breaking the tone constraints or safety rules. The gate ensures every candidate prompt preserves all previously verified behaviors. The golden set grows with every discovered failure, so the gate gets stricter over time.

Operational Metrics Are First-Class Citizens

The CodeEvaluator checks latency, tokens, turns, and tool errors against budgets. Prompt optimization that improves accuracy while blowing the latency budget is not a win. The pipeline treats operational health as a constraint, not an afterthought.

The Architecture in Practice

Google wrapped the entire cycle in a single shell script. Setup takes a few minutes. One command runs the cycle.

In production, you would skip synthetic traffic generation and evaluate real user sessions already in BigQuery. The pipeline becomes: real sessions stream to BigQuery, the evaluator scores them overnight, failed cases feed the optimizer in a scheduled job, and candidate prompts are validated against the regression gate before deployment.

This turns prompt maintenance from a manual, reactive task into a measured, automated process. The agent's own data tells you what is broken. The system fixes it. The gate verifies it. The cycle repeats.

The Broader Implication

Prompt engineering has been a craft. You write, test, tweak, and hope. The Google pipeline turns it into an engineering discipline with measurement, automation, and verification.

The key shift is from prompt-as-static-artifact to prompt-as-versioned-system-component. Every change has a version, an audit trail, a quality score, and a regression test. The prompt is no longer a string you edit in a text editor. It is a managed asset with lifecycle, governance, and continuous improvement.

This is what production agent operations looks like at scale.


Suggested title: Your Agent Can Fix Its Own Prompt

Word count: ~1,480

Citations:

Fact-check notes:

  • The ~60% to ~99% improvement figure and 100 synthetic sessions per cycle come from the Google Cloud Community Medium post by Eva Khmelinskaya. The post includes detailed terminal output and quality reports from the demo run. These should be treated as vendor-published benchmark data from a controlled demo, not independent third-party verification.
  • The specific operational metrics (1,482 ms latency, 811 tokens) are from the same source.
  • The "12 minutes" total runtime is stated in the source post for the 100-question, 3-cycle configuration.
  • No independent replication of these specific numbers was found in third-party sources during research.