Automated Prompt Optimization: Using LLMs to Compress Verbose Prompts in Google ADK
How to use automated prompt compression pipelines to eliminate redundant instructions, minimize token burn, and maintain agent behavioral fidelity in Google ADK.
Published on • December 5, 2026
AI Assistant

As enterprise AI agents mature, system instructions tend to suffer from prompt bloat: team members continuously append new guardrails, behavioral edge cases, few-shot examples, and redundant caveats. Over time, an agent that started with a crisp 300-word prompt grows into a 4,000-token behemoth.
This causes higher API costs, slower response times, and increased attention diffusion where the model ignores earlier rules in favor of later ones.
Automated Prompt Optimization (APO) utilizes fast, high-capability models (such as Gemini 3.8 Flash) to iteratively distill, compress, and benchmark verbose prompts into concise, high-density instructions without sacrificing task accuracy.
The Prompt Compression Pipeline
Rather than manually editing prompts, an automated compression pipeline treats prompt tuning as an engineering optimization loop:
[Verbose Prompt (4,000 tokens)] + [Eval Test Suite (50 golden queries)]
│
▼
┌──────────────────────────────────────────────┐
│ Distillation Agent (Gemini Flash) │
│ - Removes redundant phrasing │
│ - Collapses few-shots into negative rules │
│ - Formats as crisp imperative directives │
└──────────────────────┬───────────────────────┘
│
▼
[Candidate Prompt (1,200 tokens)]
│
▼
┌──────────────────────────────────────────────┐
│ ADK Evaluator / Quality Flywheel │
│ - Runs candidate against Golden Dataset │
│ - Checks behavioral consistency & pass rate │
└──────────────────────┬───────────────────────┘
│
┌───────────────────┴───────────────────┐
│ Pass Rate >= 98% │ Failed Cases Detected
▼ ▼
[Deploy to Production] [Self-Correction Feedback Loop]
Prompt Compression Techniques
When compressing system instructions, the distillation agent applies several proven structural transformations:
- Imperative Condensation: Replacing conversational guidelines (
"You should always remember to check if the user provided an email address before calling the API") with concise directives ("Require user email before invoking send_api"). - Few-Shot Elimination via Negative Rules: Replacing four multi-turn few-shot dialogues with two explicit negative constraints.
- Markdown Tag Structuring: Organizing instructions under predictable
# Role,# Constraints,# Workflowsheaders to optimize semantic clustering in attention layers.
Implementation: Automated Prompt Compression Script
Below is a Python utility using the google-genai SDK and Google ADK evaluation methodology to compress and validate prompts:
import asyncio
from google.genai import Client
from google.genai.types import GenerateContentConfig
COMPRESSION_META_PROMPT = """You are an expert prompt compression engineer.
Your goal is to compress the provided agent system instruction by at least 50% in token count while preserving 100% of its behavioral constraints and semantics.
Rules:
1. Strip all conversational filler and pleasantries.
2. Convert wordy explanations into crisp, imperative bullet points.
3. Consolidate overlapping instructions.
4. Preserve all exact variable placeholders, JSON formats, and tool names.
5. Use concise XML or Markdown tags for sectioning.
Return ONLY the compressed prompt, with no surrounding explanations."""
class PromptCompressor:
def __init__(self):
self.client = Client()
async def compress_prompt(self, original_prompt: str) -> str:
# Measure initial tokens
initial_count = await self.client.models.count_tokens(
model="gemini-3.8-flash",
contents=original_prompt
)
response = await self.client.models.generate_content(
model="gemini-3.8-pro",
contents=[COMPRESSION_META_PROMPT, f"<original_prompt>\n{original_prompt}\n</original_prompt>"],
config=GenerateContentConfig(temperature=0.1)
)
compressed_text = response.text.strip()
# Measure compressed tokens
final_count = await self.client.models.count_tokens(
model="gemini-3.8-flash",
contents=compressed_text
)
reduction_pct = (1 - (final_count.total_tokens / initial_count.total_tokens)) * 100
print(f"Original tokens: {initial_count.total_tokens}")
print(f"Compressed tokens: {final_count.total_tokens} (-{reduction_pct:.1f}%)")
return compressed_text
# Example execution
async def run():
verbose_instruction = """
You are a very helpful customer support assistant working for Acme Cloud Corp.
When users talk to you, always be very polite and greet them warmly.
You must make sure that whenever they ask about their bill, you never give them their credit card number.
It is extremely important that you never disclose the full credit card number under any circumstances.
If they ask for their invoice, please ask them for their account ID first before doing anything else.
Once they give you their account ID, you can go ahead and call the get_invoice tool.
If the tool returns an error, please tell the user that our billing system is temporarily down and they should try again later.
"""
compressor = PromptCompressor()
optimized = await compressor.compress_prompt(verbose_instruction)
print("\n--- Optimized Prompt ---\n")
print(optimized)
if __name__ == "__main__":
asyncio.run(run())
Output Comparison
The automated distillation transforms the wordy instructions into a tight, unambiguous prompt:
# Role: Acme Cloud Support Agent
# Workflow
1. Greet user politely.
2. Invoices: Require `account_id` -> Invoke `get_invoice(account_id)`.
3. Error Handling: If `get_invoice` fails, inform user system is temporarily unavailable.
# Constraints
- NEVER disclose full credit card numbers under any circumstance.
- Original Token Count: 148 tokens
- Compressed Token Count: 58 tokens
- Reduction: 60.8%
Safe Production Rollout
- Never Deploy Unvalidated Prompts: Always pass the candidate compressed prompt through a golden evaluation dataset (e.g. 50–100 edge case prompts) using the ADK evaluation framework.
- Monitor Model Drift: Compare the output embeddings or tool call accuracy of the original vs compressed prompt to detect subtle nuance loss.
- Automate in CI/CD: Integrate prompt compression checks in your Git pull requests to flag prompt growth before merging to production.