anda_engine 0.18.3

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
//! Live prompt-cache checks for `tools_call` across providers.
//!
//! Run one provider at a time with its API key set, for example:
//! - `ANTHROPIC_API_KEY=… cargo test -p anda_engine --test tools_call_live anthropic_ -- --ignored --nocapture`
//! - `OPENAI_API_KEY=… cargo test -p anda_engine --test tools_call_live openai_ -- --ignored --nocapture`
//! - `GEMINI_API_KEY=… cargo test -p anda_engine --test tools_call_live gemini_ -- --ignored --nocapture`
//! - `DEEPSEEK_API_KEY=… cargo test -p anda_engine --test tools_call_live deepseek_ -- --ignored --nocapture`

use anda_core::{
    AgentContext, AgentOutput, BoxError, BoxPinFut, CompletionRequest, FunctionDefinition, Json,
    ModelEffort, Tool, ToolCall, ToolOutput,
};
use anda_engine::{
    context::{BaseCtx, TOOLS_CALL_NAME, TOOLS_SELECT_NAME, ToolsCallArgs},
    engine::EngineBuilder,
    model::{CompletionFeaturesDyn, Model, anthropic, gemini, openai},
};
use serde::Deserialize;
use serde_json::json;
use std::sync::{Arc, Mutex};

const CACHE_SUFFIX_TOKENS: u64 = 512;

#[derive(Debug, Clone)]
struct Round {
    tools: Vec<String>,
    tool_additions: Vec<String>,
    input_tokens: u64,
    cached_tokens: u64,
    tool_calls: Vec<ToolCall>,
}

struct Recorder {
    inner: Arc<dyn CompletionFeaturesDyn>,
    rounds: Arc<Mutex<Vec<Round>>>,
}

impl CompletionFeaturesDyn for Recorder {
    fn model_name(&self) -> String {
        self.inner.model_name()
    }

    fn supports_tool_additions(&self, effort: Option<ModelEffort>) -> bool {
        self.inner.supports_tool_additions(effort)
    }

    fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
        let inner = self.inner.clone();
        let rounds = self.rounds.clone();
        Box::pin(async move {
            let tools: Vec<String> = req.tools.iter().map(|t| t.name.clone()).collect();
            let tool_additions = req.tool_additions.clone();
            let output = inner.completion(req).await?;
            rounds.lock().unwrap().push(Round {
                tools,
                tool_additions,
                input_tokens: output.usage.input_tokens,
                cached_tokens: output.usage.cached_tokens,
                tool_calls: output.tool_calls.clone(),
            });
            Ok(output)
        })
    }
}

#[derive(Deserialize)]
struct TicketArgs {
    code: String,
    priority: u32,
}

struct SecretTicketTool {
    name: &'static str,
    token: String,
}

impl Tool<BaseCtx> for SecretTicketTool {
    type Args = TicketArgs;
    type Output = Json;

    fn name(&self) -> String {
        self.name.to_string()
    }

    fn description(&self) -> String {
        format!(
            "Returns the secret token for {} after validating code and priority.",
            self.name
        )
    }

    fn definition(&self) -> FunctionDefinition {
        FunctionDefinition {
            name: self.name(),
            description: self.description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "code": {"type": "string"},
                    "priority": {"type": "integer"}
                },
                "required": ["code", "priority"],
                "additionalProperties": false
            }),
            strict: Some(true),
        }
    }

    async fn call(
        &self,
        _ctx: BaseCtx,
        args: Self::Args,
        _resources: Vec<anda_core::Resource>,
    ) -> Result<ToolOutput<Self::Output>, BoxError> {
        Ok(ToolOutput::new(json!({
            "token": self.token,
            "code": args.code,
            "priority": args.priority,
        })))
    }
}

async fn run_proxy_cache_flow(completer: Arc<dyn CompletionFeaturesDyn>) {
    let token_a = format!("ALPHA_{:016x}", rand::random::<u64>());
    let token_b = format!("BETA_{:016x}", rand::random::<u64>());
    let rounds = Arc::new(Mutex::new(Vec::new()));
    let recorder = Arc::new(Recorder {
        inner: completer,
        rounds: rounds.clone(),
    });

    let ctx = EngineBuilder::new()
        .with_model(Model::with_completer(recorder))
        .register_tool(Arc::new(SecretTicketTool {
            name: "alpha_ticket",
            token: token_a.clone(),
        }))
        .unwrap()
        .register_tool(Arc::new(SecretTicketTool {
            name: "beta_ticket",
            token: token_b.clone(),
        }))
        .unwrap()
        .mock_ctx();

    let records = (0..120)
        .map(|i| format!("record-{i}: {:032x}", rand::random::<u128>()))
        .collect::<Vec<_>>()
        .join("\n");
    let initial_tools = ctx
        .definitions(Some(&[
            TOOLS_SELECT_NAME.to_string(),
            TOOLS_CALL_NAME.to_string(),
        ]))
        .await;
    let initial_names: Vec<String> = initial_tools.iter().map(|t| t.name.clone()).collect();

    let mut runner = ctx
        .completion_iter(
            CompletionRequest {
                instructions: "Follow instructions exactly. Use tools_select to inspect schemas and tools_call to invoke discovered tools.".to_string(),
                prompt: format!(
                    "Keep these reference records. Do not call tools yet. Reply READY.\n{records}"
                ),
                tools: initial_tools,
                ..Default::default()
            },
            Vec::new(),
        )
        .unbound();

    let drive = async |runner: &mut anda_engine::context::CompletionRunner| {
        let mut content = String::new();
        while let Some(out) = runner.next().await.unwrap() {
            assert!(out.failed_reason.is_none(), "{:?}", out.failed_reason);
            content = out.content.clone();
            if runner.is_idle() {
                break;
            }
        }
        content
    };

    drive(&mut runner).await;
    for (ticket, code, priority, token) in [
        ("alpha_ticket", "A1", 1, token_a),
        ("beta_ticket", "B2", 2, token_b),
    ] {
        let start = rounds.lock().unwrap().len();
        runner.follow_up(format!(
            "Discover `{ticket}` with tools_select, invoke it via tools_call with code=\"{code}\" and priority={priority}, and reply with its token."
        ));
        let reply = drive(&mut runner).await;
        assert!(reply.contains(&token), "{ticket}: {reply:?}");

        let recorded = rounds.lock().unwrap();
        let calls = &recorded[start..];
        let selection = calls
            .iter()
            .position(|r| r.tool_calls.iter().any(|c| c.name == TOOLS_SELECT_NAME))
            .expect("the model must discover the ticket");
        assert!(
            calls[selection + 1..]
                .iter()
                .flat_map(|r| &r.tool_calls)
                .filter_map(ToolsCallArgs::from_tool_call)
                .any(|call| call.name == ticket
                    && call.arguments == json!({"code": code, "priority": priority})),
            "the model must use the proxy after discovery: {calls:?}"
        );
    }

    let rounds = rounds.lock().unwrap().clone();
    for (i, round) in rounds.iter().enumerate() {
        println!(
            "round {i}: input={} cached={} tools={:?} additions={:?} calls={:?}",
            round.input_tokens,
            round.cached_tokens,
            round.tools,
            round.tool_additions,
            round.tool_calls
        );
        assert_eq!(round.tools, initial_names, "req.tools must stay static");
        assert!(round.tool_additions.is_empty());
        assert!(
            round
                .tool_calls
                .iter()
                .all(|c| initial_names.contains(&c.name)),
            "an undeclared direct call bypassed the proxy: {:?}",
            round.tool_calls
        );
    }
    let last = rounds.last().expect("at least one round");
    let first = &rounds[0];
    assert!(
        last.cached_tokens + CACHE_SUFFIX_TOKENS >= first.input_tokens,
        "expected cached prefix hit: last cached {} vs first input {}",
        last.cached_tokens,
        first.input_tokens
    );
}

#[tokio::test]
#[ignore = "calls Anthropic API; set ANTHROPIC_API_KEY and run with --ignored"]
async fn anthropic_tools_call_preserves_prefix_cache() {
    let key = std::env::var("ANTHROPIC_API_KEY").expect("ANTHROPIC_API_KEY is required");
    let model_name =
        std::env::var("ANTHROPIC_MODEL").unwrap_or_else(|_| "claude-sonnet-4-5".into());
    let model = anthropic::Client::new(&key, None)
        .completion_model(&model_name)
        .with_stream(true);
    run_proxy_cache_flow(Arc::new(model)).await;
}

#[tokio::test]
#[ignore = "calls OpenAI Responses API; set OPENAI_API_KEY and run with --ignored"]
async fn openai_tools_call_preserves_prefix_cache() {
    let key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY is required");
    let model_name = std::env::var("OPENAI_MODEL").unwrap_or_else(|_| "gpt-5-mini".into());
    let model = openai::Client::new(&key, None).completion_model_v2(&model_name);
    run_proxy_cache_flow(Arc::new(model)).await;
}

#[tokio::test]
#[ignore = "calls Gemini API; set GEMINI_API_KEY and run with --ignored"]
async fn gemini_tools_call_preserves_prefix_cache() {
    let key = std::env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY is required");
    let model_name = std::env::var("GEMINI_MODEL").unwrap_or_default();
    let model = gemini::Client::new(&key, None).completion_model(&model_name);
    run_proxy_cache_flow(Arc::new(model)).await;
}

#[tokio::test]
#[ignore = "calls DeepSeek API; set DEEPSEEK_API_KEY and run with --ignored"]
async fn deepseek_tools_call_preserves_prefix_cache() {
    let key = std::env::var("DEEPSEEK_API_KEY").expect("DEEPSEEK_API_KEY is required");
    let model = anthropic::Client::new(&key, Some("https://api.deepseek.com/anthropic".into()))
        .completion_model("deepseek-flash")
        .with_stream(true)
        .with_effort(Some(ModelEffort::Medium))
        .with_max_output(4096);
    run_proxy_cache_flow(Arc::new(model)).await;
}