use async_trait::async_trait;
use serde_json::Value;
use std::sync::Arc;
use troupekit_core::http::{HttpError, HttpErrorKind};
use troupekit_core::ids::RunId;
use troupekit_core::tool::{HostedTool, ToolSpec};
#[derive(Debug, Clone, Default)]
pub struct ToolContext {
pub run_id: Option<RunId>,
pub idempotency_key: Option<String>,
}
impl ToolContext {
pub fn for_call(run_id: RunId, step: u64, index: usize) -> ToolContext {
ToolContext {
run_id: Some(run_id),
idempotency_key: Some(format!("{run_id}:{step}:{index}")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolOutput {
pub content: String,
pub is_error: bool,
}
impl ToolOutput {
pub fn text(content: impl Into<String>) -> Self {
Self {
content: content.into(),
is_error: false,
}
}
pub fn error(content: impl Into<String>) -> Self {
Self {
content: content.into(),
is_error: true,
}
}
pub fn from_result(result: Result<ToolOutput, ToolError>) -> Self {
result.unwrap_or_else(|e| Self::error(e.to_string()))
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ToolError {
#[error("invalid arguments: {0}")]
InvalidArgs(String),
#[error("unknown tool: {0}")]
UnknownTool(String),
#[error("duplicate tool: {0}")]
DuplicateTool(String),
#[error("invalid tool spec: {0}")]
InvalidSpec(String),
#[error("config: {0}")]
Config(String),
#[error("blocked: {0}")]
Blocked(String),
#[error("http: {0}")]
Http(String),
#[error("decode: {0}")]
Decode(String),
#[error("failed: {0}")]
Failed(String),
}
impl From<HttpError> for ToolError {
fn from(e: HttpError) -> Self {
match e.kind {
HttpErrorKind::Invalid => ToolError::InvalidArgs(e.message),
HttpErrorKind::Blocked => ToolError::Blocked(e.message),
_ => ToolError::Http(e.message),
}
}
}
#[async_trait]
pub trait Tool: Send + Sync {
fn spec(&self) -> &ToolSpec;
async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError>;
}
struct Hosted {
inner: Arc<dyn Tool>,
spec: ToolSpec,
}
#[async_trait]
impl Tool for Hosted {
fn spec(&self) -> &ToolSpec {
&self.spec
}
async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
self.inner.call(args, ctx).await
}
}
pub fn hosted(inner: Arc<dyn Tool>, kind: HostedTool) -> Arc<dyn Tool> {
assert_eq!(
inner.spec().name,
kind.name(),
"a hosted stand-in carries the hosted tool's name"
);
let spec = ToolSpec {
hosted: Some(kind),
..inner.spec().clone()
};
Arc::new(Hosted { inner, spec })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn for_call_builds_stable_keys() {
let run = RunId::new();
let a = ToolContext::for_call(run, 3, 1);
assert_eq!(a.run_id, Some(run));
assert_eq!(a.idempotency_key, Some(format!("{run}:3:1")));
assert_eq!(
ToolContext::for_call(run, 3, 1).idempotency_key,
a.idempotency_key
);
assert_ne!(
ToolContext::for_call(run, 4, 1).idempotency_key,
a.idempotency_key
);
assert_eq!(ToolContext::default().idempotency_key, None);
}
}