use async_trait::async_trait;
use futures_util::future::BoxFuture;
use serde_json::{json, Value};
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use troupekit_core::error::ProviderError;
use troupekit_core::event::Usage;
use troupekit_core::message::{Message, Role};
use troupekit_core::tool::ToolSpec;
use troupekit_providers::{CompletionRequest, CompletionResponse, Delta, Model, StopReason};
use troupekit_tools::{Tool, ToolContext, ToolError, ToolOutput};
pub fn text_reply(text: &str, input_tokens: u64) -> Result<CompletionResponse, ProviderError> {
Ok(CompletionResponse {
message: Message::text(Role::Assistant, text),
usage: Usage {
input_tokens,
output_tokens: 5,
cost_usd_micros: 0,
},
stop: StopReason::EndTurn,
})
}
type CallFn =
dyn Fn(Value, ToolContext) -> BoxFuture<'static, Result<ToolOutput, ToolError>> + Send + Sync;
pub struct FnTool {
spec: ToolSpec,
call: Box<CallFn>,
}
impl FnTool {
#[expect(
clippy::new_ret_no_self,
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"
)]
pub fn new<F, Fut>(name: &str, f: F) -> Arc<dyn Tool>
where
F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
{
assert!(troupekit_tools::valid_tool_name(name), "test tool name");
Arc::new(FnTool {
spec: ToolSpec {
name: name.to_string(),
description: format!("test tool {name}"),
schema: json!({"type": "object"}),
hosted: None,
},
call: Box::new(move |args, ctx| Box::pin(f(args, ctx))),
})
}
}
#[async_trait]
impl Tool for FnTool {
fn spec(&self) -> &ToolSpec {
&self.spec
}
async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
(self.call)(args, ctx.clone()).await
}
}
type ReplyFn =
dyn Fn(&CompletionRequest) -> Result<CompletionResponse, ProviderError> + Send + Sync;
pub struct FnModel {
id: String,
reply: Box<ReplyFn>,
calls: AtomicUsize,
}
impl FnModel {
pub fn new(
id: &str,
reply: impl Fn(&CompletionRequest) -> Result<CompletionResponse, ProviderError>
+ Send
+ Sync
+ 'static,
) -> Self {
Self {
id: id.to_string(),
reply: Box::new(reply),
calls: AtomicUsize::new(0),
}
}
pub fn calls(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
}
#[async_trait]
impl Model for FnModel {
fn id(&self) -> &str {
&self.id
}
async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
self.calls.fetch_add(1, Ordering::SeqCst);
(self.reply)(req)
}
async fn stream(
&self,
req: &CompletionRequest,
on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
) -> Result<CompletionResponse, ProviderError> {
let reply = self.complete(req).await?;
let text = reply.message.text_content();
if !text.is_empty() {
on_delta(&Delta::TextDelta { text });
}
Ok(reply)
}
}