Skip to main content

adk_eval/personas/
simulator.rs

1//! User simulator that generates persona-driven messages.
2
3use std::sync::Arc;
4
5use adk_core::model::{Llm, LlmRequest};
6use adk_core::types::Content;
7use futures::StreamExt;
8
9use super::profile::PersonaProfile;
10use crate::error::{EvalError, Result};
11
12/// Drives multi-turn evaluation conversations by generating user messages
13/// according to a [`PersonaProfile`].
14///
15/// The simulator uses a configurable LLM to produce messages that reflect
16/// the persona's behavioral traits, pursue the persona's goals, and respect
17/// the persona's constraints.
18///
19/// # Example
20///
21/// ```rust,ignore
22/// use adk_eval::personas::{UserSimulator, PersonaProfile, PersonaTraits, Verbosity, ExpertiseLevel};
23/// use std::sync::Arc;
24///
25/// let persona = PersonaProfile {
26///     name: "impatient-dev".to_string(),
27///     description: "A senior developer who wants quick answers".to_string(),
28///     traits: PersonaTraits {
29///         communication_style: "direct and terse".to_string(),
30///         verbosity: Verbosity::Terse,
31///         expertise_level: ExpertiseLevel::Expert,
32///     },
33///     goals: vec!["Get a working code example".to_string()],
34///     constraints: vec!["Never ask for basic explanations".to_string()],
35/// };
36///
37/// let simulator = UserSimulator::new(llm, persona);
38/// let message = simulator.generate_message(&[]).await?;
39/// ```
40pub struct UserSimulator {
41    /// The LLM used to generate persona-driven messages.
42    llm: Arc<dyn Llm>,
43    /// The persona definition driving message generation.
44    persona: PersonaProfile,
45}
46
47impl UserSimulator {
48    /// Create a new simulator with the given LLM and persona.
49    pub fn new(llm: Arc<dyn Llm>, persona: PersonaProfile) -> Self {
50        Self { llm, persona }
51    }
52
53    /// Returns a reference to the persona profile.
54    pub fn persona(&self) -> &PersonaProfile {
55        &self.persona
56    }
57
58    /// Generate the next user message given conversation history.
59    ///
60    /// Builds a system prompt from the persona definition and sends
61    /// the conversation history to the configured LLM to produce a
62    /// message that reflects the persona's traits, goals, and constraints.
63    pub async fn generate_message(&self, history: &[Content]) -> Result<Content> {
64        let system_prompt = self.build_system_prompt();
65
66        let mut contents = Vec::with_capacity(history.len() + 1);
67
68        // Add the system instruction as the first message
69        contents.push(Content::new("user").with_text(&system_prompt));
70        contents
71            .push(Content::new("model").with_text("Understood. I will role-play as this persona."));
72
73        // Add conversation history
74        contents.extend_from_slice(history);
75
76        // If history is empty, prompt the LLM to start the conversation
77        if history.is_empty() {
78            contents.push(
79                Content::new("user")
80                    .with_text("Start the conversation as this persona. Send your first message."),
81            );
82        } else {
83            contents.push(
84                Content::new("user").with_text(
85                    "Continue the conversation as this persona. Send your next message.",
86                ),
87            );
88        }
89
90        let request = LlmRequest::new(self.llm.name(), contents);
91
92        let mut stream = self
93            .llm
94            .generate_content(request, false)
95            .await
96            .map_err(|e| EvalError::ExecutionError(format!("LLM generation failed: {e}")))?;
97
98        // Collect the full response from the stream
99        let mut response_text = String::new();
100        while let Some(result) = stream.next().await {
101            let response =
102                result.map_err(|e| EvalError::ExecutionError(format!("LLM stream error: {e}")))?;
103            if let Some(content) = &response.content {
104                for part in &content.parts {
105                    if let Some(text) = part.text() {
106                        response_text.push_str(text);
107                    }
108                }
109            }
110        }
111
112        if response_text.is_empty() {
113            return Err(EvalError::ExecutionError(
114                "LLM returned empty response for persona message".to_string(),
115            ));
116        }
117
118        Ok(Content::new("user").with_text(response_text))
119    }
120
121    /// Build a system prompt that instructs the LLM to role-play as the persona.
122    fn build_system_prompt(&self) -> String {
123        let persona = &self.persona;
124        let traits = &persona.traits;
125
126        let mut prompt = format!(
127            "You are role-playing as a user persona named \"{}\".\n\
128             Description: {}\n\n\
129             Communication style: {}\n\
130             Verbosity: {:?}\n\
131             Expertise level: {:?}\n",
132            persona.name,
133            persona.description,
134            traits.communication_style,
135            traits.verbosity,
136            traits.expertise_level,
137        );
138
139        if !persona.goals.is_empty() {
140            prompt.push_str("\nGoals (pursue these during the conversation):\n");
141            for goal in &persona.goals {
142                prompt.push_str(&format!("- {goal}\n"));
143            }
144        }
145
146        if !persona.constraints.is_empty() {
147            prompt.push_str("\nConstraints (always respect these):\n");
148            for constraint in &persona.constraints {
149                prompt.push_str(&format!("- {constraint}\n"));
150            }
151        }
152
153        prompt.push_str(
154            "\nRespond ONLY with the persona's message. \
155             Do not include any meta-commentary, labels, or prefixes. \
156             Stay in character at all times.",
157        );
158
159        prompt
160    }
161}