Skip to main content

troupekit_graph/
testing.rs

1use async_trait::async_trait;
2use futures_util::future::BoxFuture;
3use serde_json::{json, Value};
4use std::future::Future;
5use std::sync::atomic::{AtomicUsize, Ordering};
6use std::sync::Arc;
7use troupekit_core::error::ProviderError;
8use troupekit_core::event::Usage;
9use troupekit_core::message::{Message, Role};
10use troupekit_core::tool::ToolSpec;
11use troupekit_providers::{CompletionRequest, CompletionResponse, Delta, Model, StopReason};
12use troupekit_tools::{Tool, ToolContext, ToolError, ToolOutput};
13
14/// Builds an assistant reply holding `text`, charged `input_tokens` input
15/// and 5 output tokens at the model's price, for `FnModel` closures.
16/// Returns the reply.
17pub fn text_reply(text: &str, input_tokens: u64) -> Result<CompletionResponse, ProviderError> {
18    Ok(CompletionResponse {
19        message: Message::text(Role::Assistant, text),
20        usage: Usage {
21            input_tokens,
22            output_tokens: 5,
23            cost_usd_micros: 0,
24        },
25        stop: StopReason::EndTurn,
26    })
27}
28
29type CallFn =
30    dyn Fn(Value, ToolContext) -> BoxFuture<'static, Result<ToolOutput, ToolError>> + Send + Sync;
31
32/// A `Tool` from an async closure over the arguments and context, for
33/// tests. Its schema accepts any object, so a tool node's reads always
34/// pass the registry check.
35pub struct FnTool {
36    spec: ToolSpec,
37    call: Box<CallFn>,
38}
39
40impl FnTool {
41    /// Builds tool `name` that answers every call with `f(args, ctx)`.
42    /// Returns it ready for `ToolRegistry::register`.
43    /// Panics on an invalid tool name, as tests pass literals.
44    #[expect(
45        clippy::new_ret_no_self,
46        reason = "public API since 0.2.0: renaming it or returning Self breaks the public API in a patch release; renamed or deprecated in 0.4"
47    )]
48    pub fn new<F, Fut>(name: &str, f: F) -> Arc<dyn Tool>
49    where
50        F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
51        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
52    {
53        assert!(troupekit_tools::valid_tool_name(name), "test tool name");
54        Arc::new(FnTool {
55            spec: ToolSpec {
56                name: name.to_string(),
57                description: format!("test tool {name}"),
58                schema: json!({"type": "object"}),
59                hosted: None,
60            },
61            call: Box::new(move |args, ctx| Box::pin(f(args, ctx))),
62        })
63    }
64}
65
66#[async_trait]
67impl Tool for FnTool {
68    fn spec(&self) -> &ToolSpec {
69        &self.spec
70    }
71
72    async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
73        (self.call)(args, ctx.clone()).await
74    }
75}
76
77type ReplyFn =
78    dyn Fn(&CompletionRequest) -> Result<CompletionResponse, ProviderError> + Send + Sync;
79
80/// A `Model` whose reply is a pure function of the request, for tests: a
81/// replayed call gets the same reply however often the model was called.
82/// `stream` sends the reply text as one delta; `calls` counts every call.
83pub struct FnModel {
84    id: String,
85    reply: Box<ReplyFn>,
86    calls: AtomicUsize,
87}
88
89impl FnModel {
90    /// Builds a model called `id` answering every request with `reply`.
91    /// The closure must not depend on call order.
92    /// Returns the model.
93    pub fn new(
94        id: &str,
95        reply: impl Fn(&CompletionRequest) -> Result<CompletionResponse, ProviderError>
96            + Send
97            + Sync
98            + 'static,
99    ) -> Self {
100        Self {
101            id: id.to_string(),
102            reply: Box::new(reply),
103            calls: AtomicUsize::new(0),
104        }
105    }
106
107    /// Returns how many times the model was called, streamed or not.
108    /// Crash and concurrency tests compare it across runners.
109    /// Counts failed replies too.
110    pub fn calls(&self) -> usize {
111        self.calls.load(Ordering::SeqCst)
112    }
113}
114
115#[async_trait]
116impl Model for FnModel {
117    fn id(&self) -> &str {
118        &self.id
119    }
120
121    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
122        self.calls.fetch_add(1, Ordering::SeqCst);
123        (self.reply)(req)
124    }
125
126    async fn stream(
127        &self,
128        req: &CompletionRequest,
129        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
130    ) -> Result<CompletionResponse, ProviderError> {
131        let reply = self.complete(req).await?;
132        let text = reply.message.text_content();
133        if !text.is_empty() {
134            on_delta(&Delta::TextDelta { text });
135        }
136        Ok(reply)
137    }
138}