Skip to main content

adk_eval/
optimizer.rs

1//! Prompt optimization engine.
2//!
3//! Iteratively improves an agent's system instructions using an optimizer LLM
4//! and an evaluation set. Used by the `adk optimize` CLI command.
5//!
6//! # Overview
7//!
8//! The [`PromptOptimizer`] runs an optimization loop:
9//! 1. Evaluate the agent against the eval set to get a baseline score
10//! 2. If the score already meets the target threshold, report "no optimization needed"
11//! 3. Otherwise, ask the optimizer LLM to propose improved instructions
12//! 4. Apply the best improvement and re-evaluate
13//! 5. Repeat until max iterations or target threshold is reached
14//! 6. Write the best-performing instructions to the output file
15//!
16//! The optimizer rewrites an agent's instruction, so it needs the instruction and a way to
17//! build the agent from a candidate: an [`AgentCandidates`], usually an
18//! [`InstructionCandidates`] over the agent's builder. `Arc<dyn Agent>` exposes neither.
19//!
20//! # Example
21//!
22//! ```rust,ignore
23//! use adk_eval::optimizer::{InstructionCandidates, OptimizerConfig, PromptOptimizer};
24//! use std::sync::Arc;
25//!
26//! let candidates = InstructionCandidates::new("Answer questions", move |instruction| {
27//!     Ok(Arc::new(
28//!         LlmAgentBuilder::new("tutor").model(model.clone()).instruction(instruction).build()?,
29//!     ))
30//! });
31//! let optimizer = PromptOptimizer::new(optimizer_llm, evaluator, OptimizerConfig::default());
32//! let result = optimizer.optimize_candidates(&candidates, &eval_set).await?;
33//! println!("{} -> {}: {}", result.initial_score, result.final_score, result.best_instructions);
34//! ```
35
36use std::path::PathBuf;
37use std::sync::Arc;
38
39use futures::StreamExt;
40use tracing::{info, warn};
41
42use adk_core::types::Content;
43use adk_core::{Agent, Llm, LlmRequest};
44
45use crate::error::{EvalError, Result};
46use crate::evaluator::Evaluator;
47use crate::schema::EvalSet;
48
49/// Configuration for the prompt optimization loop.
50#[derive(Debug, Clone)]
51pub struct OptimizerConfig {
52    /// Maximum number of optimization iterations (default: 5).
53    pub max_iterations: u32,
54    /// Target evaluation score threshold (default: 0.9).
55    /// Optimization stops early if this score is reached.
56    pub target_threshold: f64,
57    /// Path to write the best-performing instructions.
58    pub output_path: PathBuf,
59}
60
61impl Default for OptimizerConfig {
62    fn default() -> Self {
63        Self {
64            max_iterations: 5,
65            target_threshold: 0.9,
66            output_path: PathBuf::from("optimized_instructions.txt"),
67        }
68    }
69}
70
71/// Result of a prompt optimization run.
72#[derive(Debug, Clone)]
73pub struct OptimizationResult {
74    /// Evaluation score before optimization.
75    pub initial_score: f64,
76    /// Best evaluation score achieved.
77    pub final_score: f64,
78    /// Number of iterations actually executed.
79    pub iterations_run: u32,
80    /// The best-performing system instructions.
81    pub best_instructions: String,
82}
83
84/// What the optimizer rewrites: the instruction under test and the agent to evaluate under
85/// a candidate instruction.
86///
87/// # Example
88///
89/// ```rust
90/// use std::sync::Arc;
91///
92/// use adk_core::Agent;
93/// use adk_eval::optimizer::AgentCandidates;
94///
95/// struct Fixed(Arc<dyn Agent>);
96///
97/// impl AgentCandidates for Fixed {
98///     fn instruction(&self) -> String {
99///         "Answer questions".to_string()
100///     }
101///
102///     fn build(&self, _instruction: &str) -> adk_core::Result<Arc<dyn Agent>> {
103///         Ok(self.0.clone())
104///     }
105/// }
106/// ```
107pub trait AgentCandidates: Send + Sync {
108    /// The instruction the optimizer starts from.
109    fn instruction(&self) -> String;
110
111    /// The agent to evaluate under `instruction`.
112    ///
113    /// # Errors
114    ///
115    /// Returns the agent's build error.
116    fn build(&self, instruction: &str) -> adk_core::Result<Arc<dyn Agent>>;
117}
118
119/// Builds the agent to evaluate under an instruction.
120type BuildAgent = dyn Fn(&str) -> adk_core::Result<Arc<dyn Agent>> + Send + Sync;
121
122/// [`AgentCandidates`] over a closure that builds the agent from an instruction.
123///
124/// # Example
125///
126/// ```rust
127/// use std::sync::Arc;
128///
129/// use adk_eval::optimizer::{AgentCandidates, InstructionCandidates};
130/// use adk_model::{ScriptedLlm, ScriptedResponse};
131///
132/// let candidates = InstructionCandidates::new("Answer questions", |instruction| {
133///     let reply = if instruction.contains("capital") { "Paris" } else { "Not sure" };
134///     let model = Arc::new(ScriptedLlm::new("agent", vec![ScriptedResponse::text(reply)]));
135///     # let _ = model;
136///     # Err::<Arc<dyn adk_core::Agent>, _>(adk_core::AdkError::config("built elsewhere"))
137///     // Ok(Arc::new(LlmAgentBuilder::new("tutor").model(model).instruction(instruction).build()?))
138/// });
139/// assert_eq!(candidates.instruction(), "Answer questions");
140/// ```
141pub struct InstructionCandidates {
142    instruction: String,
143    build: Box<BuildAgent>,
144}
145
146impl InstructionCandidates {
147    /// Candidates starting from `instruction`, each built by `build`.
148    pub fn new(
149        instruction: impl Into<String>,
150        build: impl Fn(&str) -> adk_core::Result<Arc<dyn Agent>> + Send + Sync + 'static,
151    ) -> Self {
152        Self { instruction: instruction.into(), build: Box::new(build) }
153    }
154}
155
156impl AgentCandidates for InstructionCandidates {
157    fn instruction(&self) -> String {
158        self.instruction.clone()
159    }
160
161    fn build(&self, instruction: &str) -> adk_core::Result<Arc<dyn Agent>> {
162        (self.build)(instruction)
163    }
164}
165
166impl std::fmt::Debug for InstructionCandidates {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        f.debug_struct("InstructionCandidates").field("instruction", &self.instruction).finish()
169    }
170}
171
172/// Iteratively improves an agent's system instructions using an optimizer LLM
173/// and an evaluation set.
174///
175/// The optimizer runs a loop of evaluate → propose improvements → apply best →
176/// repeat, logging progress via `tracing` at each iteration.
177pub struct PromptOptimizer {
178    optimizer_llm: Arc<dyn Llm>,
179    evaluator: Evaluator,
180    config: OptimizerConfig,
181}
182
183impl PromptOptimizer {
184    /// Create a new prompt optimizer.
185    ///
186    /// # Arguments
187    ///
188    /// * `optimizer_llm` - The LLM used to propose instruction improvements
189    ///   (separate from the agent's own LLM).
190    /// * `evaluator` - The evaluator used to score the agent against the eval set.
191    /// * `config` - Optimization configuration (max iterations, target threshold, output path).
192    pub fn new(optimizer_llm: Arc<dyn Llm>, evaluator: Evaluator, config: OptimizerConfig) -> Self {
193        Self { optimizer_llm, evaluator, config }
194    }
195
196    /// Evaluates `agent` against the eval set.
197    ///
198    /// An `Arc<dyn Agent>` carries neither its instruction nor a way to rebuild it, so this
199    /// method can only score the agent as given: when the baseline meets the threshold it
200    /// writes the agent's description to the output file and returns; otherwise it fails,
201    /// since it cannot rewrite the instruction. [`optimize_candidates`](Self::optimize_candidates)
202    /// is the optimization loop.
203    ///
204    /// # Errors
205    ///
206    /// Returns [`EvalError::ConfigError`] when the eval set has no cases or the baseline is
207    /// below the target threshold, or the evaluator's error.
208    pub async fn optimize(
209        &self,
210        agent: Arc<dyn Agent>,
211        eval_set: &EvalSet,
212    ) -> Result<OptimizationResult> {
213        let base_path = std::path::Path::new(".");
214        let cases = eval_set.get_all_cases(base_path)?;
215        if cases.is_empty() {
216            return Err(EvalError::ConfigError("eval set contains no cases".to_string()));
217        }
218        let initial_score = self.evaluate_agent(agent.clone(), eval_set).await?;
219        info!(iteration = 0, score = initial_score, "initial evaluation complete");
220        if initial_score < self.config.target_threshold {
221            return Err(EvalError::ConfigError(format!(
222                "the agent scored {initial_score:.2} against a target of {:.2}, and \
223                 PromptOptimizer::optimize cannot rewrite the instruction of an Arc<dyn Agent>. \
224                 Call optimize_candidates with InstructionCandidates::new(instruction, |candidate| \
225                 build the agent) so each proposal is evaluated",
226                self.config.target_threshold
227            )));
228        }
229        info!(
230            score = initial_score,
231            threshold = self.config.target_threshold,
232            "no optimization needed — initial score meets target threshold"
233        );
234        let instructions = agent.description().to_string();
235        self.write_output(&instructions)?;
236        Ok(OptimizationResult {
237            initial_score,
238            final_score: initial_score,
239            iterations_run: 0,
240            best_instructions: instructions,
241        })
242    }
243
244    /// Runs the optimization loop over `candidates`.
245    ///
246    /// Evaluates the agent built from the starting instruction, asks the optimizer LLM for
247    /// an improved instruction, evaluates the agent built from it, keeps the best, and
248    /// repeats until the target threshold is met or max iterations are exhausted. On
249    /// completion, writes the best-performing instruction to the configured output file.
250    ///
251    /// # Errors
252    ///
253    /// Returns [`EvalError::ConfigError`] when the eval set has no cases, the candidate's
254    /// build error, the evaluator's error, or [`EvalError::ExecutionError`] when the
255    /// optimizer LLM fails or answers nothing.
256    pub async fn optimize_candidates(
257        &self,
258        candidates: &dyn AgentCandidates,
259        eval_set: &EvalSet,
260    ) -> Result<OptimizationResult> {
261        let base_path = std::path::Path::new(".");
262        let cases = eval_set.get_all_cases(base_path)?;
263
264        if cases.is_empty() {
265            return Err(EvalError::ConfigError("eval set contains no cases".to_string()));
266        }
267
268        let mut current_instructions = candidates.instruction();
269        let agent = candidates.build(&current_instructions)?;
270
271        // Run initial evaluation
272        let initial_score = self.evaluate_agent(agent, eval_set).await?;
273        info!(iteration = 0, score = initial_score, "initial evaluation complete");
274
275        // Check if initial score already meets threshold
276        if initial_score >= self.config.target_threshold {
277            info!(
278                score = initial_score,
279                threshold = self.config.target_threshold,
280                "no optimization needed — initial score meets target threshold"
281            );
282
283            self.write_output(&current_instructions)?;
284
285            return Ok(OptimizationResult {
286                initial_score,
287                final_score: initial_score,
288                iterations_run: 0,
289                best_instructions: current_instructions,
290            });
291        }
292
293        let mut best_score = initial_score;
294        let mut best_instructions = current_instructions.clone();
295        let mut iterations_run = 0;
296
297        for iteration in 1..=self.config.max_iterations {
298            iterations_run = iteration;
299
300            // Propose improved instructions via optimizer LLM
301            let proposed = self.propose_improvements(&current_instructions, best_score).await?;
302
303            info!(
304                iteration,
305                current_score = best_score,
306                proposed_changes = %proposed,
307                "proposed instruction improvements"
308            );
309
310            // Evaluate the agent built from the proposed instructions
311            current_instructions = proposed;
312            let candidate = candidates.build(&current_instructions)?;
313            let score = self.evaluate_agent(candidate, eval_set).await?;
314
315            info!(iteration, score, previous_best = best_score, "evaluation complete");
316
317            if score > best_score {
318                best_score = score;
319                best_instructions = current_instructions.clone();
320            } else {
321                // Revert to best instructions if score didn't improve
322                warn!(
323                    iteration,
324                    score, best_score, "score did not improve, reverting to best instructions"
325                );
326                current_instructions = best_instructions.clone();
327            }
328
329            // Check if target threshold is met
330            if best_score >= self.config.target_threshold {
331                info!(
332                    iteration,
333                    score = best_score,
334                    threshold = self.config.target_threshold,
335                    "target threshold reached — stopping early"
336                );
337                break;
338            }
339        }
340
341        // Write best instructions to output file
342        self.write_output(&best_instructions)?;
343
344        info!(
345            initial_score,
346            final_score = best_score,
347            iterations_run,
348            output_path = %self.config.output_path.display(),
349            "optimization complete"
350        );
351
352        Ok(OptimizationResult {
353            initial_score,
354            final_score: best_score,
355            iterations_run,
356            best_instructions,
357        })
358    }
359
360    /// Evaluate the agent against the eval set and return an aggregate score.
361    async fn evaluate_agent(&self, agent: Arc<dyn Agent>, eval_set: &EvalSet) -> Result<f64> {
362        let base_path = std::path::Path::new(".");
363        let cases = eval_set.get_all_cases(base_path)?;
364
365        if cases.is_empty() {
366            return Ok(0.0);
367        }
368
369        let mut total_score = 0.0;
370        let mut case_count = 0u32;
371
372        for case in &cases {
373            let result = self.evaluator.evaluate_case(agent.clone(), case).await?;
374            // Compute average of all criterion scores for this case
375            let case_score = if result.scores.is_empty() {
376                if result.passed { 1.0 } else { 0.0 }
377            } else {
378                result.scores.values().sum::<f64>() / result.scores.len() as f64
379            };
380            total_score += case_score;
381            case_count += 1;
382        }
383
384        Ok(if case_count > 0 { total_score / f64::from(case_count) } else { 0.0 })
385    }
386
387    /// Ask the optimizer LLM to propose improved instructions.
388    async fn propose_improvements(
389        &self,
390        current_instructions: &str,
391        current_score: f64,
392    ) -> Result<String> {
393        let prompt = format!(
394            "You are a prompt optimization assistant. Your task is to improve the following \
395             system instructions for an AI agent.\n\n\
396             Current instructions:\n{current_instructions}\n\n\
397             Current evaluation score: {current_score:.2} (target: {target:.2})\n\n\
398             Please provide improved instructions that will help the agent perform better \
399             on its evaluation set. Return ONLY the improved instructions text, nothing else.",
400            target = self.config.target_threshold,
401        );
402
403        let request = LlmRequest::new(
404            self.optimizer_llm.name(),
405            vec![Content::new("user").with_text(prompt)],
406        );
407
408        let mut stream =
409            self.optimizer_llm.generate_content(request, false).await.map_err(|e| {
410                EvalError::ExecutionError(format!("optimizer LLM call failed: {e}"))
411            })?;
412
413        let mut result_text = String::new();
414        while let Some(response) = stream.next().await {
415            let response = response.map_err(|e| {
416                EvalError::ExecutionError(format!("optimizer LLM stream error: {e}"))
417            })?;
418            if let Some(content) = &response.content {
419                for part in &content.parts {
420                    if let Some(text) = part.text() {
421                        result_text.push_str(text);
422                    }
423                }
424            }
425        }
426
427        if result_text.is_empty() {
428            return Err(EvalError::ExecutionError(
429                "optimizer LLM returned empty response".to_string(),
430            ));
431        }
432
433        Ok(result_text)
434    }
435
436    /// Write the best instructions to the output file.
437    fn write_output(&self, instructions: &str) -> Result<()> {
438        std::fs::write(&self.config.output_path, instructions)?;
439        info!(
440            path = %self.config.output_path.display(),
441            "wrote optimized instructions to output file"
442        );
443        Ok(())
444    }
445}
446
447/// Run the core optimization loop with injectable evaluation and proposal functions.
448///
449/// This is the pure logic extracted for testability. Given a sequence of scores
450/// (one per iteration, plus the initial score), it runs the loop respecting
451/// `max_iterations` and `target_threshold`.
452///
453/// Returns `(iterations_run, best_score)`.
454pub fn run_optimization_loop(
455    scores: &[f64],
456    max_iterations: u32,
457    target_threshold: f64,
458) -> (u32, f64) {
459    if scores.is_empty() {
460        return (0, 0.0);
461    }
462
463    let initial_score = scores[0];
464
465    // Early exit if initial score meets threshold
466    if initial_score >= target_threshold {
467        return (0, initial_score);
468    }
469
470    let mut best_score = initial_score;
471    let mut iterations_run = 0u32;
472
473    for iteration in 1..=max_iterations {
474        iterations_run = iteration;
475
476        // Get the score for this iteration (cycle through available scores)
477        let score_idx = iteration as usize;
478        let score = if score_idx < scores.len() {
479            scores[score_idx]
480        } else {
481            // If we run out of scores, repeat the last one
482            scores[scores.len() - 1]
483        };
484
485        if score > best_score {
486            best_score = score;
487        }
488
489        // Check if target threshold is met
490        if best_score >= target_threshold {
491            break;
492        }
493    }
494
495    (iterations_run, best_score)
496}