use std::collections::HashSet;
use async_trait::async_trait;
use causa_kernel::{
ProcessorContext, ProcessorError, TextPayload, ToolBatch, ToolBatchProcessor, ToolCallId,
ToolOutput, ToolResultPayload, ToolResultStatus,
};
use crate::new_block_id;
#[derive(Debug, Default)]
pub struct DeduplicateProcessor;
#[async_trait]
impl ToolBatchProcessor for DeduplicateProcessor {
async fn process(
&self,
batch: &mut ToolBatch,
_ctx: &ProcessorContext<'_>,
) -> Result<(), ProcessorError> {
let duplicates = {
let mut identities = HashSet::new();
let mut duplicates = Vec::new();
for entry in batch.results().iter().chain(batch.calls()) {
let input = &entry.call().input;
if !identities.insert(ToolCallId::new(&input.tool_name, &input.arguments)) {
duplicates.push(entry.call().call_block_id);
}
}
duplicates
};
for call_id in duplicates {
let Some(offset) = batch
.calls()
.iter()
.position(|entry| entry.call().call_block_id == call_id)
else {
continue;
};
let index = batch.completed_len() + offset;
batch
.resolve_at(
index,
new_block_id(),
rejected_result(call_id, "duplicate tool call"),
)
.map_err(|error| ProcessorError::Failed(error.to_string()))?;
}
Ok(())
}
}
fn rejected_result(call_block_id: causa_kernel::BlockId, reason: &str) -> ToolResultPayload {
ToolResultPayload::new(
call_block_id,
ToolResultStatus::Rejected,
ToolOutput::new(serde_json::json!({"error": reason})),
)
.with_notes(vec![TextPayload::new(reason)])
}