use super::run::AgentRun;
use crate::{errors::AgentError, run_result::RunResult};
use merry_core::{
ErrorInfo, PendingToolCall, ToolCallArguments, ToolCallBatchId, ToolCallId, ToolName,
};
use merry_runtime::ToolExecutionOutcome;
use std::{collections::BTreeMap, fmt};
use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolInvocationContent {
kind: ToolInvocationContentKind,
value: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToolInvocationContentKind {
Text,
Json,
}
impl ToolInvocationContent {
#[must_use]
pub fn text(content: impl Into<String>) -> Self {
Self {
kind: ToolInvocationContentKind::Text,
value: content.into(),
}
}
pub fn json(content: impl Into<String>) -> Result<Self, ToolInvocationContentError> {
let content = content.into();
let _: serde_json::Value = serde_json::from_str(&content)
.map_err(|source| ToolInvocationContentError::InvalidJson { source })?;
Ok(Self {
kind: ToolInvocationContentKind::Json,
value: content,
})
}
}
#[derive(Debug, Error)]
pub enum ToolInvocationContentError {
#[error("tool invocation JSON content is invalid: {source}")]
InvalidJson {
#[source]
source: serde_json::Error,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToolInvocationResult {
Succeeded {
call_id: ToolCallId,
content: ToolInvocationContent,
},
Failed {
call_id: ToolCallId,
content: ToolInvocationContent,
diagnostic: ErrorInfo,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToolInvocationSubmission {
Accepted,
RejectedAndRecorded,
}
impl ToolInvocationResult {
#[must_use]
pub fn succeeded(call_id: ToolCallId, content: ToolInvocationContent) -> Self {
Self::Succeeded { call_id, content }
}
#[must_use]
pub fn failed(
call_id: ToolCallId,
content: ToolInvocationContent,
diagnostic: ErrorInfo,
) -> Self {
Self::Failed {
call_id,
content,
diagnostic,
}
}
#[must_use]
pub fn call_id(&self) -> &ToolCallId {
match self {
Self::Succeeded { call_id, .. } | Self::Failed { call_id, .. } => call_id,
}
}
pub(crate) fn into_runtime(self) -> (ToolCallId, ToolExecutionOutcome) {
match self {
Self::Succeeded { call_id, content } => (call_id, content.into_success_outcome()),
Self::Failed {
call_id,
content,
diagnostic,
} => (call_id, content.into_failure_outcome(diagnostic)),
}
}
}
impl ToolInvocationContent {
fn into_success_outcome(self) -> ToolExecutionOutcome {
match self.kind {
ToolInvocationContentKind::Text => ToolExecutionOutcome::succeeded_text(self.value),
ToolInvocationContentKind::Json => ToolExecutionOutcome::succeeded_json(self.value),
}
}
fn into_failure_outcome(self, diagnostic: ErrorInfo) -> ToolExecutionOutcome {
match self.kind {
ToolInvocationContentKind::Text => {
ToolExecutionOutcome::failed_text(self.value, diagnostic)
}
ToolInvocationContentKind::Json => {
ToolExecutionOutcome::failed_json(self.value, diagnostic)
}
}
}
}
pub(crate) fn order_tool_invocation_results(
invocations: &[ToolInvocation],
results: Vec<ToolInvocationResult>,
) -> Result<Vec<(ToolCallId, ToolExecutionOutcome)>, AgentError> {
let expected_call_ids = invocations
.iter()
.map(|invocation| invocation.id().clone())
.collect::<Vec<_>>();
let mut received_call_ids = Vec::with_capacity(results.len());
let mut results_by_call_id = BTreeMap::new();
for result in results {
let call_id = result.call_id().clone();
received_call_ids.push(call_id.clone());
if results_by_call_id.insert(call_id, result).is_some() {
return Err(AgentError::ToolInvocationBatchMismatch {
expected_call_ids,
received_call_ids,
});
}
}
let mut expected_set = expected_call_ids.clone();
expected_set.sort();
let mut received_set = results_by_call_id.keys().cloned().collect::<Vec<_>>();
received_set.sort();
if expected_set != received_set || expected_call_ids.len() != received_call_ids.len() {
return Err(AgentError::ToolInvocationBatchMismatch {
expected_call_ids,
received_call_ids,
});
}
let mut ordered_results = Vec::with_capacity(invocations.len());
for invocation in invocations {
let Some(result) = results_by_call_id.remove(invocation.id()) else {
return Err(AgentError::ToolInvocationBatchMismatch {
expected_call_ids,
received_call_ids,
});
};
ordered_results.push(result.into_runtime());
}
Ok(ordered_results)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolInvocation {
call: PendingToolCall,
}
impl ToolInvocation {
pub(crate) fn new(call: PendingToolCall) -> Self {
Self { call }
}
#[must_use]
pub fn id(&self) -> &ToolCallId {
self.call.id()
}
#[must_use]
pub fn name(&self) -> &ToolName {
self.call.name()
}
#[must_use]
pub fn arguments(&self) -> &ToolCallArguments {
self.call.arguments()
}
}
pub struct ToolInvocationBatch<'a> {
invocations: Vec<ToolInvocation>,
batch_id: ToolCallBatchId,
run: &'a mut AgentRun,
resolved: bool,
}
impl<'a> ToolInvocationBatch<'a> {
pub(crate) fn from_batch(
run: &'a mut AgentRun,
batch_id: ToolCallBatchId,
calls: Vec<PendingToolCall>,
) -> Option<Self> {
if calls.is_empty() {
return None;
}
Some(Self {
invocations: calls.into_iter().map(ToolInvocation::new).collect(),
batch_id,
run,
resolved: false,
})
}
#[must_use]
pub fn invocations(&self) -> &[ToolInvocation] {
&self.invocations
}
#[must_use]
pub fn len(&self) -> usize {
self.invocations.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.invocations.is_empty()
}
pub async fn submit(
&mut self,
results: Vec<ToolInvocationResult>,
) -> Result<ToolInvocationSubmission, AgentError> {
if self.resolved {
return Err(AgentError::ToolInvocationBatchResolved);
}
let result = self
.run
.submit_tool_invocation_results(&self.batch_id, &self.invocations, results)
.await;
if result.is_ok() {
self.resolved = true;
}
result
}
pub async fn cancel(mut self) -> Result<RunResult, AgentError> {
if self.resolved {
return Err(AgentError::ToolInvocationBatchResolved);
}
self.resolved = true;
self.run.cancel().await
}
}
impl fmt::Debug for ToolInvocationBatch<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolInvocationBatch")
.field("invocations", &self.invocations)
.finish()
}
}
impl PartialEq for ToolInvocationBatch<'_> {
fn eq(&self, other: &Self) -> bool {
self.invocations == other.invocations
}
}
impl Eq for ToolInvocationBatch<'_> {}
impl Drop for ToolInvocationBatch<'_> {
fn drop(&mut self) {
if !self.resolved {
self.run.request_cancel();
}
}
}