Skip to main content

gemini_adk_rs/
instruction.rs

1//! Instruction templating — inject state values into instruction strings.
2//!
3//! Replaces `{key}` placeholders with values from the state container.
4//! Supports optional `{key?}` syntax that resolves to empty string if missing.
5
6use regex::Regex;
7use std::sync::LazyLock;
8
9use crate::state::State;
10
11static PLACEHOLDER_RE: LazyLock<Regex> = LazyLock::new(|| {
12    Regex::new(r"\{([a-zA-Z_][a-zA-Z0-9_:]*)\??\}")
13        .expect("PLACEHOLDER_RE literal is a valid regex")
14});
15
16/// Replace `{key}` placeholders in `template` with values from `state`.
17///
18/// - `{key}` — required: if present in state, replaced with the string representation;
19///   if missing, left as-is (e.g., `{unknown}` stays `{unknown}`)
20/// - `{key?}` — optional: if present in state, replaced; if missing, replaced with `""`
21/// - Prefix keys are supported: `{app:flag}`, `{user:name}`, etc.
22pub fn inject_session_state(template: &str, state: &State) -> String {
23    PLACEHOLDER_RE
24        .replace_all(template, |caps: &regex::Captures| {
25            let full_match = &caps[0];
26            let key = &caps[1];
27            let optional = full_match.ends_with("?}");
28
29            match state.get_raw(key) {
30                Some(value) => value_to_string(&value),
31                None => {
32                    if optional {
33                        String::new()
34                    } else {
35                        full_match.to_string()
36                    }
37                }
38            }
39        })
40        .into_owned()
41}
42
43/// A dynamic instruction source — the ADK "instruction provider" pattern:
44/// instead of a string fixed at build time, the instruction is produced
45/// from live session state on every model request (persona switching,
46/// risk-driven guardrails, multi-tenant instructions without rebuilding
47/// the agent). Any `Fn(&State) -> String` closure is a provider.
48pub trait InstructionProvider: Send + Sync {
49    /// Produce the system instruction for the current request.
50    fn provide(&self, state: &State) -> String;
51}
52
53impl<F> InstructionProvider for F
54where
55    F: Fn(&State) -> String + Send + Sync,
56{
57    fn provide(&self, state: &State) -> String {
58        self(state)
59    }
60}
61
62impl<T: InstructionProvider + ?Sized> InstructionProvider for std::sync::Arc<T> {
63    fn provide(&self, state: &State) -> String {
64        (**self).provide(state)
65    }
66}
67
68/// A full template-engine instruction *(feature `templates`)* — minijinja
69/// (Jinja2 syntax: conditionals, loops, filters) over the session state,
70/// mirroring ADK's `use_jinja2` instructions. The whole state is exposed
71/// as `state` (subscript prefixed keys: `{{ state["session:turn_count"] }}`),
72/// and every key that is a bare identifier is also available at top level
73/// (`{{ name }}`). Falls back to the empty string for missing values under
74/// Jinja's default undefined semantics.
75///
76/// ```ignore
77/// let inst = TemplateInstruction::new(
78///     "You are a support agent.\n\
79///      {% if state[\"derived:risk\"] and state[\"derived:risk\"] > 0.8 %}\
80///      Escalate carefully and show extra empathy.{% endif %}",
81/// )?;
82/// LlmTextAgent::new("support", llm).instruction_provider(inst);
83/// ```
84#[cfg(feature = "templates")]
85pub struct TemplateInstruction {
86    source: String,
87}
88
89#[cfg(feature = "templates")]
90impl TemplateInstruction {
91    /// Compile-check the template now so errors surface at build time, not
92    /// on the first model request.
93    pub fn new(source: impl Into<String>) -> Result<Self, String> {
94        let source = source.into();
95        let env = minijinja::Environment::new();
96        env.template_from_str(&source)
97            .map_err(|e| format!("template error: {e}"))?;
98        Ok(Self { source })
99    }
100
101    fn context(state: &State) -> minijinja::Value {
102        let mut all = serde_json::Map::new();
103        let mut top = serde_json::Map::new();
104        for key in state.keys() {
105            if let Some(value) = state.get_raw(&key) {
106                let bare_identifier = !key.is_empty()
107                    && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
108                    && !key.starts_with(|c: char| c.is_ascii_digit());
109                if bare_identifier {
110                    top.insert(key.clone(), value.clone());
111                }
112                all.insert(key, value);
113            }
114        }
115        top.insert("state".into(), serde_json::Value::Object(all));
116        minijinja::Value::from(minijinja::value::Serde(serde_json::Value::Object(top)))
117    }
118}
119
120#[cfg(feature = "templates")]
121impl InstructionProvider for TemplateInstruction {
122    fn provide(&self, state: &State) -> String {
123        let env = minijinja::Environment::new();
124        env.render_str(&self.source, Self::context(state))
125            .unwrap_or_else(|e| format!("[template render error: {e}]"))
126    }
127}
128
129fn value_to_string(value: &serde_json::Value) -> String {
130    match value {
131        serde_json::Value::String(s) => s.clone(),
132        serde_json::Value::Null => String::new(),
133        other => other.to_string(),
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn placeholder_regex_literal_compiles() {
143        // Forces the `LazyLock`: a bad literal fails here, not at runtime.
144        LazyLock::force(&PLACEHOLDER_RE);
145    }
146
147    #[test]
148    fn closure_is_an_instruction_provider() {
149        let state = State::new();
150        let _ = state.set("persona", "pirate");
151        let provider = |s: &State| {
152            format!(
153                "Speak like a {}.",
154                s.get::<String>("persona").unwrap_or_default()
155            )
156        };
157        assert_eq!(
158            InstructionProvider::provide(&provider, &state),
159            "Speak like a pirate."
160        );
161    }
162
163    #[cfg(feature = "templates")]
164    #[test]
165    fn template_instruction_renders_conditionals_and_prefixed_keys() {
166        let state = State::new();
167        let _ = state.set("name", "Alice");
168        let _ = state.set("derived:risk", 0.9);
169        let inst = TemplateInstruction::new(
170            "Hello {{ name }}.{% if state[\"derived:risk\"] > 0.8 %} Escalate.{% endif %}",
171        )
172        .unwrap();
173        assert_eq!(inst.provide(&state), "Hello Alice. Escalate.");
174    }
175
176    #[cfg(feature = "templates")]
177    #[test]
178    fn template_instruction_rejects_bad_syntax_at_build() {
179        assert!(TemplateInstruction::new("{% if x %}unclosed").is_err());
180    }
181
182    #[test]
183    fn simple_substitution() {
184        let state = State::new();
185        let _ = state.set("name", "Alice");
186        let result = inject_session_state("Hello, {name}!", &state);
187        assert_eq!(result, "Hello, Alice!");
188    }
189
190    #[test]
191    fn optional_key_present() {
192        let state = State::new();
193        let _ = state.set("title", "Dr.");
194        let result = inject_session_state("Hello, {title?} Smith!", &state);
195        assert_eq!(result, "Hello, Dr. Smith!");
196    }
197
198    #[test]
199    fn optional_key_missing() {
200        let state = State::new();
201        let result = inject_session_state("Hello, {title?}Smith!", &state);
202        assert_eq!(result, "Hello, Smith!");
203    }
204
205    #[test]
206    fn missing_required_key_left_as_is() {
207        let state = State::new();
208        let result = inject_session_state("Hello, {unknown}!", &state);
209        assert_eq!(result, "Hello, {unknown}!");
210    }
211
212    #[test]
213    fn multiple_keys() {
214        let state = State::new();
215        let _ = state.set("first", "Alice");
216        let _ = state.set("last", "Smith");
217        let result = inject_session_state("{first} {last}", &state);
218        assert_eq!(result, "Alice Smith");
219    }
220
221    #[test]
222    fn prefix_key() {
223        let state = State::new();
224        let _ = state.app().set("flag", true);
225        let result = inject_session_state("Flag is {app:flag}", &state);
226        assert_eq!(result, "Flag is true");
227    }
228
229    #[test]
230    fn no_placeholders_passthrough() {
231        let state = State::new();
232        let template = "No placeholders here.";
233        assert_eq!(inject_session_state(template, &state), template);
234    }
235
236    #[test]
237    fn numeric_value() {
238        let state = State::new();
239        let _ = state.set("count", 42);
240        let result = inject_session_state("Count: {count}", &state);
241        assert_eq!(result, "Count: 42");
242    }
243
244    #[test]
245    fn empty_template() {
246        let state = State::new();
247        assert_eq!(inject_session_state("", &state), "");
248    }
249}