Skip to main content

adk_tool/
advisor.rs

1//! Advisor consultation: a tool an agent calls to ask a stronger or different model for advice
2//! mid-task.
3
4use std::collections::{HashMap, VecDeque};
5use std::sync::{Arc, Mutex};
6
7use adk_core::{
8    AdkError, Content, Effort, ErrorComponent, FinishReason, GenerateContentConfig, Llm,
9    LlmRequest, ModelCallScope, Part, Result, Tool, ToolContext, UsageMetadata,
10};
11use async_trait::async_trait;
12use futures::StreamExt;
13use futures::future::Either;
14use serde_json::{Value, json};
15
16/// The name an [`AdvisorTool`] is declared under unless configured otherwise.
17pub const DEFAULT_ADVISOR_TOOL_NAME: &str = "consult_advisor";
18
19/// How many consultations one run may make unless configured otherwise.
20pub const DEFAULT_MAX_CONSULTATIONS_PER_RUN: u32 = 3;
21
22/// How many characters of the agent's conversation the advisor sees unless configured
23/// otherwise, the most recent kept.
24pub const DEFAULT_ADVISOR_HISTORY_CHARS: usize = 24_000;
25
26/// The spend-ledger agent an advisor's calls are attributed to: `advisor:` and the name of
27/// the consulting agent, unless configured otherwise.
28pub const ADVISOR_SPEND_AGENT_PREFIX: &str = "advisor:";
29
30const DEFAULT_DESCRIPTION: &str = "Consult a stronger model for advice. Call it before you commit \
31to a hard or irreversible decision, when you are stuck or your last attempts failed, or before you \
32report a complex task as done. Ask one specific question and pass the facts the advisor needs in \
33`context`. The advisor sees the conversation so far but cannot call tools; you act on its advice. \
34Consultations per run are limited.";
35
36const DEFAULT_INSTRUCTION: &str = "You are an expert advisor consulted by another AI agent in the \
37middle of a task. The agent describes its question and context, and you see the conversation so \
38far. Give concise, concrete guidance the agent can act on now: the decision you recommend and why, \
39the next steps in order (naming the tools to call and with what arguments, when the conversation \
40shows them), and the risks or checks it should not skip. Say so plainly when the agent's plan is \
41wrong. You cannot call tools or see anything beyond what is shown here.";
42
43/// Runs whose consultation counts are kept; the oldest is forgotten past this.
44const TRACKED_RUNS: usize = 1_024;
45
46/// Longest rendering of one tool call or tool result in the advisor's transcript.
47const MAX_PART_CHARS: usize = 2_000;
48
49/// A tool that lets an agent consult another model for advice mid-task.
50///
51/// The provider-neutral counterpart of Google ADK's `ModelConsultTool` and of Claude's advisor
52/// tool. The agent calls it with a `question` and optional `context`; the tool sends them,
53/// with the most recent part of the agent's conversation, to the advisor model, which runs
54/// with no tools, and returns the advice as the tool's result.
55///
56/// | Guarantee | How |
57/// |-----------|-----|
58/// | Governed | The call goes through the agent's governed tool path like any tool: policy, approvals, audit and the kill switch apply before it runs |
59/// | Kill switch | A frozen run is refused before the advisor is called, and a freeze during the consultation ends it with `governance.frozen` |
60/// | Budgeted and ledgered | The advisor's model call runs under the run's [`ModelCallScope`]: one model call in the run budget, and a spend-ledger hold and commit under the advisor's provider |
61/// | Own attribution | The spend is attributed to `advisor:{agent}` ([`ADVISOR_SPEND_AGENT_PREFIX`]), or to [`AdvisorToolBuilder::spend_agent`]; org and vendor caps and the run budget cover it |
62/// | Per-run cap | At most [`DEFAULT_MAX_CONSULTATIONS_PER_RUN`] consultations per run, counted per root invocation; a call past it returns `limit_reached` without calling the advisor |
63///
64/// The result is a JSON object whose `status` is one of:
65///
66/// | `status` | Fields | When |
67/// |----------|--------|------|
68/// | `ok` | `advice`, `advisorModel`, `consultations`, `usage` | The advisor answered |
69/// | `limit_reached` | `message`, `consultations` | The run has used its consultations |
70/// | `error` | `error`, `message`, `advisorModel`, `consultations` | The advisor failed, refused or returned no advice; the consultation is not counted unless the advisor responded |
71/// | `invalid_request` | `message` | `question` is missing or empty |
72///
73/// A refusal by the run's budget or spend ledger, and the kill switch, fail the tool call
74/// with that error instead, as they fail any other call the run makes.
75///
76/// # Example
77///
78/// ```rust
79/// use std::sync::Arc;
80/// use adk_core::Tool;
81/// use adk_tool::AdvisorTool;
82/// # use adk_core::{Llm, LlmRequest, LlmResponseStream};
83/// # struct Advisor;
84/// # #[async_trait::async_trait]
85/// # impl Llm for Advisor {
86/// #     fn name(&self) -> &str { "claude-sonnet-5-5" }
87/// #     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
88/// #         unimplemented!()
89/// #     }
90/// # }
91///
92/// let advisor: Arc<dyn Llm> = Arc::new(Advisor);
93/// let tool = AdvisorTool::builder(advisor).max_consultations_per_run(2).max_output_tokens(2_048).build();
94/// assert_eq!(tool.name(), "consult_advisor");
95/// assert_eq!(tool.max_consultations_per_run(), 2);
96/// ```
97pub struct AdvisorTool {
98    model: Arc<dyn Llm>,
99    name: String,
100    description: String,
101    instruction: String,
102    max_per_run: u32,
103    max_output_tokens: Option<i32>,
104    effort: Option<Effort>,
105    history_chars: usize,
106    spend_agent: Option<String>,
107    runs: Mutex<RunCounts>,
108}
109
110impl std::fmt::Debug for AdvisorTool {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.debug_struct("AdvisorTool")
113            .field("name", &self.name)
114            .field("model", &self.model.name())
115            .field("max_per_run", &self.max_per_run)
116            .field("max_output_tokens", &self.max_output_tokens)
117            .field("history_chars", &self.history_chars)
118            .finish_non_exhaustive()
119    }
120}
121
122/// Consultations made per run, keyed by the run's root invocation id.
123#[derive(Default)]
124struct RunCounts {
125    used: HashMap<String, u32>,
126    order: VecDeque<String>,
127}
128
129/// Builds an [`AdvisorTool`].
130///
131/// # Example
132///
133/// ```rust
134/// use std::sync::Arc;
135/// use adk_core::{Effort, Tool};
136/// use adk_tool::AdvisorTool;
137/// # use adk_core::{Llm, LlmRequest, LlmResponseStream};
138/// # struct Advisor;
139/// # #[async_trait::async_trait]
140/// # impl Llm for Advisor {
141/// #     fn name(&self) -> &str { "claude-sonnet-5-5" }
142/// #     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
143/// #         unimplemented!()
144/// #     }
145/// # }
146///
147/// let tool = AdvisorTool::builder(Arc::new(Advisor))
148///     .name("ask_senior")
149///     .effort(Effort::High)
150///     .history_chars(0)
151///     .spend_agent("advisor:support")
152///     .build();
153/// assert_eq!(tool.name(), "ask_senior");
154/// ```
155pub struct AdvisorToolBuilder {
156    model: Arc<dyn Llm>,
157    name: String,
158    description: String,
159    instruction: String,
160    max_per_run: u32,
161    max_output_tokens: Option<i32>,
162    effort: Option<Effort>,
163    history_chars: usize,
164    spend_agent: Option<String>,
165}
166
167impl AdvisorToolBuilder {
168    /// Declares the tool under `name` instead of [`DEFAULT_ADVISOR_TOOL_NAME`].
169    pub fn name(mut self, name: impl Into<String>) -> Self {
170        self.name = name.into();
171        self
172    }
173
174    /// Replaces the description the agent's model reads, which says when to consult.
175    pub fn description(mut self, description: impl Into<String>) -> Self {
176        self.description = description.into();
177        self
178    }
179
180    /// Replaces the advisor's system instruction.
181    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
182        self.instruction = instruction.into();
183        self
184    }
185
186    /// Allows at most `max` consultations per run. `0` refuses every consultation.
187    pub fn max_consultations_per_run(mut self, max: u32) -> Self {
188        self.max_per_run = max;
189        self
190    }
191
192    /// Caps the advisor's output tokens per consultation.
193    pub fn max_output_tokens(mut self, max: i32) -> Self {
194        self.max_output_tokens = Some(max);
195        self
196    }
197
198    /// Sets the advisor's reasoning effort.
199    pub fn effort(mut self, effort: Effort) -> Self {
200        self.effort = Some(effort);
201        self
202    }
203
204    /// Shows the advisor at most `chars` characters of the agent's conversation, the most
205    /// recent kept; `0` sends only the question and context.
206    pub fn history_chars(mut self, chars: usize) -> Self {
207        self.history_chars = chars;
208        self
209    }
210
211    /// Attributes the advisor's spend to `agent` instead of `advisor:{agent name}`.
212    pub fn spend_agent(mut self, agent: impl Into<String>) -> Self {
213        self.spend_agent = Some(agent.into());
214        self
215    }
216
217    /// Builds the tool.
218    pub fn build(self) -> AdvisorTool {
219        AdvisorTool {
220            model: self.model,
221            name: self.name,
222            description: self.description,
223            instruction: self.instruction,
224            max_per_run: self.max_per_run,
225            max_output_tokens: self.max_output_tokens,
226            effort: self.effort,
227            history_chars: self.history_chars,
228            spend_agent: self.spend_agent,
229            runs: Mutex::new(RunCounts::default()),
230        }
231    }
232}
233
234impl AdvisorTool {
235    /// Starts a tool that consults `model`, with the defaults.
236    pub fn builder(model: Arc<dyn Llm>) -> AdvisorToolBuilder {
237        AdvisorToolBuilder {
238            model,
239            name: DEFAULT_ADVISOR_TOOL_NAME.to_string(),
240            description: DEFAULT_DESCRIPTION.to_string(),
241            instruction: DEFAULT_INSTRUCTION.to_string(),
242            max_per_run: DEFAULT_MAX_CONSULTATIONS_PER_RUN,
243            max_output_tokens: None,
244            effort: None,
245            history_chars: DEFAULT_ADVISOR_HISTORY_CHARS,
246            spend_agent: None,
247        }
248    }
249
250    /// A tool that consults `model`, with the defaults.
251    pub fn new(model: Arc<dyn Llm>) -> Self {
252        Self::builder(model).build()
253    }
254
255    /// The advisor model.
256    pub fn model(&self) -> &Arc<dyn Llm> {
257        &self.model
258    }
259
260    /// How many consultations one run may make.
261    pub fn max_consultations_per_run(&self) -> u32 {
262        self.max_per_run
263    }
264
265    /// How many consultations the run `root_invocation_id` has made.
266    pub fn consultations_used(&self, root_invocation_id: &str) -> u32 {
267        self.lock().used.get(root_invocation_id).copied().unwrap_or(0)
268    }
269
270    fn lock(&self) -> std::sync::MutexGuard<'_, RunCounts> {
271        self.runs.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
272    }
273
274    /// Takes one consultation of `run`'s allowance, returning how many are used with it, or
275    /// `None` when none is left.
276    fn reserve(&self, run: &str) -> Option<u32> {
277        let mut runs = self.lock();
278        let used = runs.used.get(run).copied().unwrap_or(0);
279        if used >= self.max_per_run {
280            return None;
281        }
282        if used == 0 {
283            runs.order.push_back(run.to_string());
284            while runs.order.len() > TRACKED_RUNS {
285                if let Some(oldest) = runs.order.pop_front() {
286                    runs.used.remove(&oldest);
287                }
288            }
289        }
290        runs.used.insert(run.to_string(), used + 1);
291        Some(used + 1)
292    }
293
294    /// Gives back a consultation that never reached the advisor.
295    fn release(&self, run: &str) {
296        let mut runs = self.lock();
297        if let Some(used) = runs.used.get_mut(run) {
298            *used = used.saturating_sub(1);
299        }
300    }
301
302    fn consultations(&self, used: u32) -> Value {
303        json!({
304            "used": used,
305            "max": self.max_per_run,
306            "remaining": self.max_per_run.saturating_sub(used),
307        })
308    }
309
310    /// The advisor's request: its instruction, then the question, the agent's context and
311    /// the recent conversation.
312    fn request(&self, ctx: &dyn ToolContext, question: &str, context: Option<&str>) -> LlmRequest {
313        let mut handover = format!(
314            "The agent `{agent}` asks for your advice.\n\nQuestion:\n{question}\n",
315            agent = ctx.agent_name()
316        );
317        if let Some(context) = context {
318            handover.push_str(&format!("\nContext from the agent:\n{context}\n"));
319        }
320        if self.history_chars > 0
321            && let Some(session) = ctx.session()
322        {
323            let transcript = transcript(
324                &session.conversation_history_for_agent(ctx.agent_name()),
325                self.history_chars,
326            );
327            if !transcript.is_empty() {
328                handover.push_str(&format!("\nThe conversation so far:\n{transcript}\n"));
329            }
330        }
331        let mut request = LlmRequest::new(
332            self.model.name(),
333            vec![
334                Content::new("system").with_text(self.instruction.clone()),
335                Content::new("user").with_text(handover),
336            ],
337        );
338        if self.max_output_tokens.is_some() || self.effort.is_some() {
339            request.config = Some(GenerateContentConfig {
340                max_output_tokens: self.max_output_tokens,
341                effort: self.effort,
342                ..Default::default()
343            });
344        }
345        request
346    }
347
348    /// Sends `request` to the advisor under `scope` and gathers its answer.
349    async fn consult(
350        &self,
351        scope: Option<ModelCallScope>,
352        request: LlmRequest,
353    ) -> Result<Consultation> {
354        let mut responses = match &scope {
355            Some(scope) => scope.generate(self.model.as_ref(), request, false).await?,
356            None => self.model.generate_content(request, false).await?,
357        };
358        let mut consultation = Consultation::default();
359        while let Some(response) = responses.next().await {
360            let response = response?;
361            if let Some(code) = &response.error_code {
362                return Err(AdkError::new(
363                    ErrorComponent::Model,
364                    adk_core::ErrorCategory::Internal,
365                    "tool.advisor.provider_error",
366                    format!(
367                        "{code}: {}",
368                        response
369                            .error_message
370                            .as_deref()
371                            .unwrap_or("the advisor's provider reported an error")
372                    ),
373                ));
374            }
375            let text: String = response
376                .content
377                .iter()
378                .flat_map(|content| content.parts.iter())
379                .filter_map(Part::text)
380                .collect();
381            if response.partial {
382                consultation.advice.push_str(&text);
383            } else if !text.is_empty() {
384                consultation.advice = text;
385            }
386            consultation.finish_reason = response.finish_reason.or(consultation.finish_reason);
387            consultation.usage = response.usage_metadata.or(consultation.usage.take());
388            consultation.model = response.model.or(consultation.model.take());
389            consultation.provider = response.provider.or(consultation.provider.take());
390        }
391        Ok(consultation)
392    }
393}
394
395/// What one consultation returned.
396#[derive(Default)]
397struct Consultation {
398    advice: String,
399    finish_reason: Option<FinishReason>,
400    usage: Option<UsageMetadata>,
401    model: Option<String>,
402    provider: Option<String>,
403}
404
405/// Renders `history` as a labelled transcript of at most about `max_chars` characters, the
406/// most recent contents kept whole and the oldest one kept shortened at its start.
407fn transcript(history: &[Content], max_chars: usize) -> String {
408    let mut kept: Vec<String> = Vec::new();
409    let mut total = 0usize;
410    for content in history.iter().rev() {
411        let rendered = render(content);
412        if rendered.is_empty() {
413            continue;
414        }
415        let length = rendered.chars().count();
416        if total + length > max_chars {
417            let room = max_chars.saturating_sub(total);
418            if room > 0 {
419                let tail: String = rendered.chars().skip(length - room).collect::<String>();
420                kept.push(format!("[earlier conversation omitted] …{tail}"));
421            } else {
422                kept.push("[earlier conversation omitted]".to_string());
423            }
424            break;
425        }
426        total += length;
427        kept.push(rendered);
428    }
429    kept.reverse();
430    kept.join("\n")
431}
432
433fn render(content: &Content) -> String {
434    let speaker = match content.role.as_str() {
435        "user" => "User",
436        "model" | "assistant" => "Agent",
437        "system" => return String::new(),
438        _ => "Tool",
439    };
440    let parts: Vec<String> = content
441        .parts
442        .iter()
443        .filter_map(|part| match part {
444            Part::Text { text } if !text.trim().is_empty() => Some(text.clone()),
445            Part::Text { .. } | Part::Thinking { .. } => None,
446            Part::FunctionCall { name, args, .. } => {
447                Some(format!("[called {name} with {}]", clip(&args.to_string())))
448            }
449            Part::FunctionResponse { function_response, .. } => Some(format!(
450                "[{} returned {}]",
451                function_response.name,
452                clip(&function_response.response.to_string())
453            )),
454            Part::InlineData { mime_type, .. } => Some(format!("[{mime_type} attachment]")),
455            Part::FileData { mime_type, file_uri, .. } => {
456                Some(format!("[{mime_type} file {file_uri}]"))
457            }
458            Part::ServerToolCall { .. } | Part::ServerToolResponse { .. } => {
459                Some("[provider tool activity]".to_string())
460            }
461            Part::EmbeddedResource { .. } => Some("[embedded resource]".to_string()),
462        })
463        .collect();
464    if parts.is_empty() {
465        return String::new();
466    }
467    format!("{speaker}: {}", parts.join("\n"))
468}
469
470fn clip(text: &str) -> String {
471    if text.chars().count() <= MAX_PART_CHARS {
472        return text.to_string();
473    }
474    let clipped: String = text.chars().take(MAX_PART_CHARS).collect();
475    format!("{clipped}… [truncated]")
476}
477
478fn usage_json(usage: Option<&UsageMetadata>) -> Value {
479    match usage {
480        Some(usage) => json!({
481            "inputTokens": usage.prompt_token_count,
482            "outputTokens": usage.candidates_token_count,
483            "thinkingTokens": usage.thinking_token_count,
484            "totalTokens": usage.total_token_count,
485            "costUsd": usage.cost,
486        }),
487        None => Value::Null,
488    }
489}
490
491#[async_trait]
492impl Tool for AdvisorTool {
493    fn name(&self) -> &str {
494        &self.name
495    }
496
497    fn description(&self) -> &str {
498        &self.description
499    }
500
501    fn parameters_schema(&self) -> Option<Value> {
502        Some(json!({
503            "type": "object",
504            "properties": {
505                "question": {
506                    "type": "string",
507                    "description": "What you need advice on: the decision, the problem, or the plan to check."
508                },
509                "context": {
510                    "type": "string",
511                    "description": "Facts the advisor needs that the conversation may not show: findings, constraints, the options you are weighing."
512                }
513            },
514            "required": ["question"]
515        }))
516    }
517
518    fn is_read_only(&self) -> bool {
519        true
520    }
521
522    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
523        let question = args.get("question").and_then(Value::as_str).map(str::trim).unwrap_or("");
524        if question.is_empty() {
525            return Ok(json!({
526                "status": "invalid_request",
527                "message": "Pass `question`: say what you need advice on.",
528            }));
529        }
530        let context =
531            args.get("context").and_then(Value::as_str).map(str::trim).filter(|c| !c.is_empty());
532        if let Some(config) = ctx.run_config() {
533            config.check_governance()?;
534        }
535
536        let run = ctx.orchestration_root_invocation_id().to_string();
537        let Some(used) = self.reserve(&run) else {
538            return Ok(json!({
539                "status": "limit_reached",
540                "message": "This run has used all its advisor consultations. Continue with what you know.",
541                "consultations": self.consultations(self.max_per_run),
542            }));
543        };
544
545        let request = self.request(ctx.as_ref(), question, context);
546        let spend_agent = self
547            .spend_agent
548            .clone()
549            .unwrap_or_else(|| format!("{ADVISOR_SPEND_AGENT_PREFIX}{}", ctx.agent_name()));
550        let scope =
551            ModelCallScope::for_tool(ctx.as_ref()).map(|scope| scope.with_agent(spend_agent));
552        let started = std::time::Instant::now();
553        let consultation = self.consult(scope, request);
554        let outcome = match ctx.run_config().filter(|config| !config.governance.is_empty()) {
555            // A freeze during the consultation ends it; dropping the call settles its hold.
556            Some(config) => match futures::future::select(
557                Box::pin(consultation),
558                Box::pin(config.governance_refused()),
559            )
560            .await
561            {
562                Either::Left((outcome, _)) => outcome,
563                Either::Right((frozen, _)) => Err(frozen),
564            },
565            None => consultation.await,
566        };
567        let advisor_model = self.model.name().to_string();
568
569        let consultation = match outcome {
570            Ok(consultation) => consultation,
571            Err(error) => {
572                self.release(&run);
573                if error.component != ErrorComponent::Model {
574                    // The run's budget, spend ledger or kill switch: not the advisor's failure.
575                    return Err(error);
576                }
577                tracing::warn!(
578                    advisor.model = %advisor_model,
579                    error.code = error.code,
580                    "advisor consultation failed"
581                );
582                return Ok(json!({
583                    "status": "error",
584                    "error": error.code,
585                    "message": "The advisor could not be reached. Continue with what you know.",
586                    "advisorModel": advisor_model,
587                    "consultations": self.consultations(used.saturating_sub(1)),
588                }));
589            }
590        };
591        let answered_by = consultation.model.clone().unwrap_or(advisor_model);
592        let refused = consultation.finish_reason == Some(FinishReason::Refusal);
593        if refused || consultation.advice.trim().is_empty() {
594            tracing::warn!(
595                advisor.model = %answered_by,
596                advisor.refused = refused,
597                "advisor returned no advice"
598            );
599            return Ok(json!({
600                "status": "error",
601                "error": if refused { "tool.advisor.refused" } else { "tool.advisor.empty" },
602                "message": if refused {
603                    "The advisor declined this question. Continue with what you know, or rephrase it."
604                } else {
605                    "The advisor returned no advice. Continue with what you know."
606                },
607                "advisorModel": answered_by,
608                "consultations": self.consultations(used),
609                "usage": usage_json(consultation.usage.as_ref()),
610            }));
611        }
612        tracing::info!(
613            advisor.model = %answered_by,
614            advisor.provider = consultation.provider.as_deref().unwrap_or(""),
615            advisor.consultation = used,
616            advisor.latency_ms = started.elapsed().as_millis() as u64,
617            "advisor consulted"
618        );
619        let mut advice = consultation.advice;
620        if consultation.finish_reason == Some(FinishReason::MaxTokens) {
621            advice.push_str("\n\n[The advice was cut off at the advisor's output limit.]");
622        }
623        Ok(json!({
624            "status": "ok",
625            "advice": advice,
626            "advisorModel": answered_by,
627            "consultations": self.consultations(used),
628            "usage": usage_json(consultation.usage.as_ref()),
629        }))
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636    use adk_core::{
637        BudgetTracker, CallbackContext, ErrorCategory, EventActions, GovernanceControl,
638        InMemorySpendLedger, LlmResponse, LlmResponseStream, MemoryEntry, ReadonlyContext,
639        RunBudget, RunConfig, SpendKey, SpendLedger, SpendPeriod,
640    };
641
642    /// Answers each call with the next scripted reply and records the requests.
643    struct Advisor {
644        name: &'static str,
645        replies: Mutex<VecDeque<Result<LlmResponse>>>,
646        requests: Mutex<Vec<LlmRequest>>,
647        freeze: Option<GovernanceControl>,
648    }
649
650    impl Advisor {
651        fn new(replies: impl IntoIterator<Item = Result<LlmResponse>>) -> Arc<Self> {
652            Arc::new(Self {
653                name: "claude-sonnet-5-5",
654                replies: Mutex::new(replies.into_iter().collect()),
655                requests: Mutex::new(Vec::new()),
656                freeze: None,
657            })
658        }
659
660        fn requests(&self) -> Vec<LlmRequest> {
661            self.requests.lock().unwrap().clone()
662        }
663    }
664
665    #[async_trait]
666    impl Llm for Advisor {
667        fn name(&self) -> &str {
668            self.name
669        }
670
671        async fn generate_content(&self, req: LlmRequest, _: bool) -> Result<LlmResponseStream> {
672            self.requests.lock().unwrap().push(req);
673            if let Some(control) = &self.freeze {
674                control.freeze("incident");
675                // Never answers: the freeze has to end the consultation.
676                return Ok(Box::pin(futures::stream::pending()));
677            }
678            let reply = self.replies.lock().unwrap().pop_front().expect("a scripted reply");
679            Ok(Box::pin(futures::stream::iter([reply])))
680        }
681    }
682
683    fn advice(text: &str, cost: f64) -> Result<LlmResponse> {
684        let mut response = LlmResponse::new(Content::new("model").with_text(text));
685        response.model = Some("claude-sonnet-5-5".to_string());
686        response.provider = Some("anthropic".to_string());
687        response.usage_metadata = Some(UsageMetadata {
688            prompt_token_count: 100,
689            candidates_token_count: 20,
690            total_token_count: 120,
691            cost: Some(cost),
692            ..Default::default()
693        });
694        Ok(response)
695    }
696
697    struct Ctx {
698        invocation: String,
699        content: Content,
700        config: Option<RunConfig>,
701        actions: Mutex<EventActions>,
702    }
703
704    impl Ctx {
705        fn new(invocation: &str, config: Option<RunConfig>) -> Arc<Self> {
706            Arc::new(Self {
707                invocation: invocation.to_string(),
708                content: Content::new("user").with_text("go"),
709                config,
710                actions: Mutex::new(EventActions::default()),
711            })
712        }
713    }
714
715    impl ReadonlyContext for Ctx {
716        fn invocation_id(&self) -> &str {
717            &self.invocation
718        }
719        fn agent_name(&self) -> &str {
720            "worker"
721        }
722        fn user_id(&self) -> &str {
723            "user"
724        }
725        fn app_name(&self) -> &str {
726            "acme"
727        }
728        fn session_id(&self) -> &str {
729            "session"
730        }
731        fn branch(&self) -> &str {
732            ""
733        }
734        fn user_content(&self) -> &Content {
735            &self.content
736        }
737    }
738
739    #[async_trait]
740    impl CallbackContext for Ctx {
741        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
742            None
743        }
744    }
745
746    #[async_trait]
747    impl ToolContext for Ctx {
748        fn function_call_id(&self) -> &str {
749            "call-1"
750        }
751        fn actions(&self) -> EventActions {
752            self.actions.lock().unwrap().clone()
753        }
754        fn set_actions(&self, actions: EventActions) {
755            *self.actions.lock().unwrap() = actions;
756        }
757        async fn search_memory(&self, _query: &str) -> Result<Vec<MemoryEntry>> {
758            Ok(Vec::new())
759        }
760        fn run_config(&self) -> Option<&RunConfig> {
761            self.config.as_ref()
762        }
763    }
764
765    fn metered() -> (RunConfig, Arc<InMemorySpendLedger>, Arc<BudgetTracker>) {
766        let ledger = Arc::new(InMemorySpendLedger::default());
767        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
768        let mut config = RunConfig::builder().spend_ledger(ledger.clone()).build();
769        config.budget_tracker = Some(tracker.clone());
770        (config, ledger, tracker)
771    }
772
773    #[tokio::test]
774    async fn a_consultation_returns_the_advice_and_is_metered_under_its_own_attribution() {
775        let (config, ledger, tracker) = metered();
776        let advisor = Advisor::new([advice("Release the order after the fraud check.", 0.003)]);
777        let tool = AdvisorTool::builder(advisor.clone()).max_output_tokens(1_024).build();
778
779        let result = tool
780            .execute(
781                Ctx::new("run-1", Some(config)),
782                json!({ "question": "Release order 42?", "context": "Fraud check passed." }),
783            )
784            .await
785            .unwrap();
786
787        assert_eq!(
788            result,
789            json!({
790                "status": "ok",
791                "advice": "Release the order after the fraud check.",
792                "advisorModel": "claude-sonnet-5-5",
793                "consultations": { "used": 1, "max": 3, "remaining": 2 },
794                "usage": {
795                    "inputTokens": 100,
796                    "outputTokens": 20,
797                    "thinkingTokens": null,
798                    "totalTokens": 120,
799                    "costUsd": 0.003,
800                },
801            })
802        );
803        let request = &advisor.requests()[0];
804        assert_eq!(request.model, "claude-sonnet-5-5");
805        assert!(request.tools.is_empty());
806        assert_eq!(request.contents[0].role, "system");
807        let handover = request.contents[1].parts[0].text().unwrap();
808        assert!(handover.contains("Release order 42?"), "{handover}");
809        assert!(handover.contains("Fraud check passed."), "{handover}");
810        assert_eq!(request.config.as_ref().unwrap().max_output_tokens, Some(1_024));
811
812        let advisor_key = SpendKey::org("acme").with_agent("advisor:worker");
813        assert_eq!(ledger.spent(&advisor_key, SpendPeriod::Day).await.unwrap(), 3_000);
814        let vendor_key = SpendKey::org("acme").with_vendor("anthropic");
815        assert_eq!(ledger.spent(&vendor_key, SpendPeriod::Day).await.unwrap(), 3_000);
816        assert_eq!(tracker.usage().model_calls, 1);
817        assert_eq!(tracker.usage().cost_micro_usd, 3_000);
818    }
819
820    #[tokio::test]
821    async fn the_per_run_cap_refuses_without_calling_the_advisor() {
822        let advisor = Advisor::new([advice("a", 0.0), advice("b", 0.0), advice("c", 0.0)]);
823        let tool = AdvisorTool::builder(advisor.clone()).max_consultations_per_run(2).build();
824        let ctx = Ctx::new("run-1", None);
825
826        for expected in ["a", "b"] {
827            let result = tool.execute(ctx.clone(), json!({ "question": "q" })).await.unwrap();
828            assert_eq!(result["advice"], expected);
829        }
830        let refused = tool.execute(ctx.clone(), json!({ "question": "q" })).await.unwrap();
831        assert_eq!(refused["status"], "limit_reached");
832        assert_eq!(refused["consultations"], json!({ "used": 2, "max": 2, "remaining": 0 }));
833        assert_eq!(advisor.requests().len(), 2);
834        assert_eq!(tool.consultations_used("run-1"), 2);
835
836        // Another run has its own allowance.
837        let result =
838            tool.execute(Ctx::new("run-2", None), json!({ "question": "q" })).await.unwrap();
839        assert_eq!(result["advice"], "c");
840    }
841
842    #[tokio::test]
843    async fn a_frozen_run_is_refused_before_the_advisor_is_called() {
844        let control = GovernanceControl::new();
845        let config = RunConfig::builder().governance(control.clone()).build();
846        control.freeze("incident");
847        let advisor = Advisor::new([advice("a", 0.0)]);
848        let tool = AdvisorTool::new(advisor.clone());
849
850        let refused =
851            tool.execute(Ctx::new("run-1", Some(config)), json!({ "question": "q" })).await;
852        assert_eq!(refused.unwrap_err().code, adk_core::GOVERNANCE_FROZEN_CODE);
853        assert!(advisor.requests().is_empty());
854        assert_eq!(tool.consultations_used("run-1"), 0);
855    }
856
857    #[tokio::test]
858    async fn a_freeze_during_the_consultation_ends_it() {
859        let control = GovernanceControl::new();
860        let config = RunConfig::builder().governance(control.clone()).build();
861        let advisor = Arc::new(Advisor {
862            name: "claude-sonnet-5-5",
863            replies: Mutex::new(VecDeque::new()),
864            requests: Mutex::new(Vec::new()),
865            freeze: Some(control),
866        });
867        let tool = AdvisorTool::new(advisor.clone());
868
869        let refused =
870            tool.execute(Ctx::new("run-1", Some(config)), json!({ "question": "q" })).await;
871        assert_eq!(refused.unwrap_err().code, adk_core::GOVERNANCE_FROZEN_CODE);
872        assert_eq!(advisor.requests().len(), 1);
873        assert_eq!(tool.consultations_used("run-1"), 0);
874    }
875
876    #[tokio::test]
877    async fn a_budget_refusal_fails_the_call_and_gives_the_consultation_back() {
878        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(0)));
879        let mut config = RunConfig::builder().build();
880        config.budget_tracker = Some(tracker);
881        let advisor = Advisor::new([advice("a", 0.0)]);
882        let tool = AdvisorTool::new(advisor.clone());
883
884        let refused =
885            tool.execute(Ctx::new("run-1", Some(config)), json!({ "question": "q" })).await;
886        assert_eq!(refused.unwrap_err().category, ErrorCategory::ResourceExhausted);
887        assert!(advisor.requests().is_empty());
888        assert_eq!(tool.consultations_used("run-1"), 0);
889    }
890
891    #[tokio::test]
892    async fn an_advisor_failure_is_reported_to_the_agent_and_not_counted() {
893        let overloaded = AdkError::new(
894            ErrorComponent::Model,
895            ErrorCategory::Unavailable,
896            "model.anthropic.api_error",
897            "overloaded",
898        );
899        let advisor = Advisor::new([Err(overloaded)]);
900        let tool = AdvisorTool::new(advisor);
901
902        let result =
903            tool.execute(Ctx::new("run-1", None), json!({ "question": "q" })).await.unwrap();
904        assert_eq!(result["status"], "error");
905        assert_eq!(result["error"], "model.anthropic.api_error");
906        assert_eq!(result["consultations"]["used"], 0);
907        assert_eq!(tool.consultations_used("run-1"), 0);
908    }
909
910    #[tokio::test]
911    async fn a_refusal_or_empty_answer_is_an_error_status() {
912        let refused = LlmResponse {
913            finish_reason: Some(FinishReason::Refusal),
914            turn_complete: true,
915            ..Default::default()
916        };
917        let advisor = Advisor::new([Ok(refused), advice("   ", 0.0)]);
918        let tool = AdvisorTool::new(advisor);
919        let ctx = Ctx::new("run-1", None);
920
921        let result = tool.execute(ctx.clone(), json!({ "question": "q" })).await.unwrap();
922        assert_eq!(result["error"], "tool.advisor.refused");
923        let result = tool.execute(ctx, json!({ "question": "q" })).await.unwrap();
924        assert_eq!(result["error"], "tool.advisor.empty");
925        assert_eq!(tool.consultations_used("run-1"), 2);
926    }
927
928    #[tokio::test]
929    async fn advice_cut_off_at_the_output_limit_says_so() {
930        let mut cut = advice("Batch the delete and", 0.0).unwrap();
931        cut.finish_reason = Some(FinishReason::MaxTokens);
932        let tool = AdvisorTool::new(Advisor::new([Ok(cut)]));
933        let result =
934            tool.execute(Ctx::new("run-1", None), json!({ "question": "q" })).await.unwrap();
935        assert_eq!(
936            result["advice"],
937            "Batch the delete and\n\n[The advice was cut off at the advisor's output limit.]"
938        );
939    }
940
941    #[tokio::test]
942    async fn an_empty_question_is_invalid_and_not_counted() {
943        let advisor = Advisor::new([]);
944        let tool = AdvisorTool::new(advisor.clone());
945        let result =
946            tool.execute(Ctx::new("run-1", None), json!({ "question": "  " })).await.unwrap();
947        assert_eq!(result["status"], "invalid_request");
948        assert!(advisor.requests().is_empty());
949    }
950
951    #[test]
952    fn the_transcript_keeps_the_most_recent_conversation() {
953        let history = vec![
954            Content::new("user").with_text("first question"),
955            Content {
956                role: "model".to_string(),
957                parts: vec![Part::FunctionCall {
958                    name: "lookup".to_string(),
959                    args: json!({ "id": 42 }),
960                    id: None,
961                    thought_signature: None,
962                }],
963            },
964            Content {
965                role: "function".to_string(),
966                parts: vec![Part::FunctionResponse {
967                    function_response: adk_core::FunctionResponseData::new(
968                        "lookup",
969                        json!({ "status": "held" }),
970                    ),
971                    id: None,
972                    annotations: None,
973                }],
974            },
975            Content::new("model").with_text("It is held."),
976        ];
977        assert_eq!(
978            transcript(&history, 10_000),
979            "User: first question\nAgent: [called lookup with {\"id\":42}]\n\
980             Tool: [lookup returned {\"status\":\"held\"}]\nAgent: It is held."
981        );
982        assert_eq!(transcript(&history, 18), "[earlier conversation omitted]\nAgent: It is held.");
983        let shortened = transcript(&history, 30);
984        assert!(shortened.starts_with("[earlier conversation omitted] …"), "{shortened}");
985        assert!(shortened.ends_with("\nAgent: It is held."), "{shortened}");
986    }
987}