use std::sync::Arc;
use futures::future::BoxFuture;
use gadk_agent::{AgentError, ContextDelta, InvocationContext, Tool, pack_tool};
use gadk_model::LlmRequest;
use gadk_session::{Event, EventActions};
use crate::{
llm::{flow::Flow, processors::wrap_err, state::reveal},
workflow::route::go_quote,
};
pub(crate) fn tools_processor<'a>(
ctx: &'a InvocationContext,
_req: &'a mut LlmRequest,
f: &'a Flow,
) -> BoxFuture<'a, Result<Vec<Event>, AgentError>> {
Box::pin(async move {
let agent = ctx.agent();
let Some(state) = reveal(&*agent) else {
return Err(AgentError::other(format!(
"agent {} is not an LlmAgent",
agent.name()
)));
};
let mut tools: Vec<Arc<dyn Tool>> = state.tools();
let ro = ctx.as_readonly().clone();
for ts in &state.cfg.toolsets {
let ts_tools = ts.tools(&ro).await.map_err(|e| {
wrap_err(
format!(
"failed to extract tools from the tool set {}",
go_quote(ts.name())
),
e,
)
})?;
tools.extend(ts_tools);
}
*f.tools.write() = tools;
Ok(Vec::new())
})
}
pub(crate) async fn tool_preprocess(
ctx: &InvocationContext,
req: &mut LlmRequest,
tools: &[Arc<dyn Tool>],
) -> Result<(), AgentError> {
for t in tools {
let tool_ctx = ctx.clone().into_context().with_delta(ContextDelta {
function_call_id: Some(String::new()),
actions: Some(Arc::new(parking_lot::Mutex::new(EventActions::default()))),
tool_confirmation: Some(None),
..Default::default()
});
if t.declaration().is_some() {
pack_tool(req, t).map_err(|e| AgentError::Other(Box::new(e)))?;
}
t.process_request(&tool_ctx, req)
.await
.map_err(|e| AgentError::Other(Box::new(e)))?;
}
Ok(())
}
pub(crate) async fn toolset_preprocess(
ctx: &InvocationContext,
req: &mut LlmRequest,
) -> Result<(), AgentError> {
let agent = ctx.agent();
let Some(state) = reveal(&*agent) else {
return Ok(());
};
for ts in &state.cfg.toolsets {
let tool_ctx = ctx.clone().into_context().with_delta(ContextDelta {
function_call_id: Some(String::new()),
tool_confirmation: Some(None),
..Default::default()
});
ts.process_request(&tool_ctx, req).await.map_err(|e| {
wrap_err(
format!("process request by toolset {}", go_quote(ts.name())),
e,
)
})?;
}
Ok(())
}