refactor: remove retry_count from ProviderConfig and enhance error handling in tool execution

- Removed the `retry_count` field from `ProviderConfig` as it is no longer needed.
- Introduced `argument_error` field in `ToolCall` to capture errors related to tool arguments.
- Updated various components to handle argument errors more gracefully, including in the `ToolDispatcher` and `ConversationOutput`.
- Enhanced tests to validate the new error handling and ensure proper functionality of tool calls.
This commit is contained in:
leokun committed 2026-09-01 10:14:53 +08:00
1 parent 29fde7d7c7
commit d83e14af9a
38 files changed
+1105 -444

No files matched your search

+203 -107
View File
@@ -14,8 +14,10 @@ use crate::{
};
use super::{
consume_model_cycle, CommitBarrier, CommitCause, MessagesCommitted, ModelCycleFailure,
RunCommand, RunEvent, RunFailure, RunOutcome, RunPort,
consume_model_cycle,
model_retry::{should_retry, MODEL_RETRY_DELAY},
CommitBarrier, CommitCause, MessagesCommitted, RunCommand, RunEvent, RunFailure, RunOutcome,
RunPort,
};
pub struct RunEngine {
@@ -208,119 +210,213 @@ impl RunEngine {
model: prepared.model.clone(),
history,
};
let invocation = crate::model::ModelInvocation {
call_id: format!("{}:{provider_call_index}", prepared.run_id),
run_id: prepared.run_id.to_string(),
conversation_id: prepared.conversation_id.to_string(),
provider_call_index,
request,
};
let cycle_cancellation = cancellation.child_token();
let cycle_events = client.events.clone();
let cycle = consume_model_cycle(
self.provider.stream(invocation, cycle_cancellation.clone()),
&cycle_events,
&cycle_cancellation,
);
tokio::pin!(cycle);
let mut retries = 0_u32;
let mut pending_insertions = Vec::new();
let cycle = loop {
tokio::select! {
biased;
command = client.commands.recv() => {
let interruption = match command {
Some(RunCommand::InsertMessages(insertion)) => {
pending_insertions.push(insertion);
continue;
let cycle = 'attempt: loop {
let call_id = if retries == 0 {
format!("{}:{provider_call_index}", prepared.run_id)
} else {
format!("{}:{provider_call_index}:retry-{retries}", prepared.run_id)
};
let invocation = crate::model::ModelInvocation {
call_id,
run_id: prepared.run_id.to_string(),
conversation_id: prepared.conversation_id.to_string(),
provider_call_index,
request: request.clone(),
};
let cycle_cancellation = cancellation.child_token();
let cycle_events = client.events.clone();
let cycle = consume_model_cycle(
self.provider.stream(invocation, cycle_cancellation.clone()),
&cycle_events,
&cycle_cancellation,
);
tokio::pin!(cycle);
let cycle = loop {
tokio::select! {
biased;
command = client.commands.recv() => {
let interruption = match command {
Some(RunCommand::InsertMessages(insertion)) => {
pending_insertions.push(insertion);
continue;
}
Some(RunCommand::BreakMessages(messages)) => messages,
Some(RunCommand::Cancel) => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
Some(RunCommand::ToolResult(_)) => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (
RunOutcome::Failed(RunFailure::Protocol(
"received a tool result while the model was running".into(),
)),
usage,
);
}
None => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (client_failure(), usage);
}
};
cycle_cancellation.cancel();
let interrupted = cycle.await;
match interrupted {
Ok(cycle) => {
if let Some(cycle_usage) = cycle.usage {
accumulate_usage(&mut usage, cycle_usage);
}
}
Err(failure) => {
if let Some(cycle_usage) = failure.usage {
accumulate_usage(&mut usage, cycle_usage);
}
}
}
Some(RunCommand::BreakMessages(messages)) => messages,
Some(RunCommand::Cancel) => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
Some(RunCommand::ToolResult(_)) => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (
RunOutcome::Failed(RunFailure::Protocol(
"received a tool result while the model was running".into(),
)),
usage,
);
}
None => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
if emit(client, RunEvent::CycleInterrupted).await.is_err() {
return (client_failure(), usage);
}
};
cycle_cancellation.cancel();
let interrupted = cycle.await;
match interrupted {
Ok(cycle) => {
if let Some(cycle_usage) = cycle.usage {
accumulate_usage(&mut usage, cycle_usage);
}
}
Err(failure) => {
if let Some(cycle_usage) = failure.usage {
accumulate_usage(&mut usage, cycle_usage);
}
}
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
std::mem::take(&mut pending_insertions),
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
vec![interruption],
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
continue 'model;
},
result = &mut cycle => break result,
}
};
match cycle {
Ok(cycle) => break 'attempt cycle,
Err(cycle_failure) => {
if let Some(cycle_usage) = cycle_failure.usage {
accumulate_usage(&mut usage, cycle_usage);
}
if emit(client, RunEvent::CycleInterrupted).await.is_err() {
if cancellation.is_cancelled() {
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
if !should_retry(&cycle_failure, retries) {
return (RunOutcome::Failed(cycle_failure.failure), usage);
}
retries += 1;
let message = failure_message(&cycle_failure.failure);
tracing::warn!(
provider_call_index,
retries,
max_retries = super::model_retry::MAX_MODEL_RETRIES,
delay_ms = MODEL_RETRY_DELAY.as_millis() as u64,
%message,
checkpoint_id = checkpoint.0,
"model attempt failed; retrying from current checkpoint"
);
if emit(
client,
RunEvent::ModelAttemptFailed {
attempt: retries,
message,
},
)
.await
.is_err()
{
return (client_failure(), usage);
}
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
std::mem::take(&mut pending_insertions),
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
vec![interruption],
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
continue 'model;
},
result = &mut cycle => break result,
}
};
let cycle = match cycle {
Ok(cycle) => cycle,
Err(ModelCycleFailure {
failure,
usage: cycle_usage,
..
}) => {
if let Some(cycle_usage) = cycle_usage {
accumulate_usage(&mut usage, cycle_usage);
let delay = tokio::time::sleep(MODEL_RETRY_DELAY);
tokio::pin!(delay);
loop {
tokio::select! {
biased;
command = client.commands.recv() => {
let interruption = match command {
Some(RunCommand::InsertMessages(insertion)) => {
pending_insertions.push(insertion);
continue;
}
Some(RunCommand::BreakMessages(messages)) => messages,
Some(RunCommand::Cancel) => {
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
Some(RunCommand::ToolResult(_)) => {
return (
RunOutcome::Failed(RunFailure::Protocol(
"received a tool result while waiting to retry the model".into(),
)),
usage,
);
}
None => return (client_failure(), usage),
};
if emit(client, RunEvent::CycleInterrupted).await.is_err() {
return (client_failure(), usage);
}
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
std::mem::take(&mut pending_insertions),
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
vec![interruption],
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
continue 'model;
}
_ = cancellation.cancelled() => {
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
_ = &mut delay => break,
}
}
}
if cancellation.is_cancelled() {
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
return (RunOutcome::Failed(failure), usage);
}
};
if let Some(cycle_usage) = cycle.usage {
+4
View File
@@ -104,6 +104,10 @@ pub enum RunEvent {
AutoCompactionStarted,
AutoCompactionCompleted,
CycleInterrupted,
ModelAttemptFailed {
attempt: u32,
message: String,
},
TextStart,
TextDelta(String),
TextEnd,
+1
View File
@@ -7,6 +7,7 @@ mod event;
mod handle;
mod messages;
mod model_cycle;
mod model_retry;
mod port;
mod tool_round;
+100 -15
View File
@@ -29,6 +29,7 @@ pub struct ModelCycleFailure {
pub partial_text: String,
pub partial_reasoning: String,
pub usage: Option<Usage>,
pub retryable: bool,
}
struct OpenTool {
@@ -186,6 +187,7 @@ pub async fn consume_model_cycle(
name: name.clone(),
arguments_text: String::new(),
arguments: serde_json::Value::Null,
argument_error: None,
},
ended: false,
});
@@ -218,13 +220,26 @@ pub async fn consume_model_cycle(
serde_json::from_str(&tool.call.arguments_text)
};
match arguments {
Ok(arguments) => {
Ok(arguments) if arguments.is_object() => {
tool.call.arguments = arguments;
tool.ended = true;
send(client, RunEvent::ToolCallEnd { index }).await
}
Err(_) => Err("provider ended a tool call with invalid JSON arguments"),
Ok(_) => {
tool.call.arguments = serde_json::json!({});
tool.call.argument_error = Some(format!(
"{} arguments must be a JSON object",
tool.call.name
));
}
Err(error) => {
tool.call.arguments = serde_json::json!({});
tool.call.argument_error = Some(format!(
"{} arguments are not valid JSON: {error}",
tool.call.name
));
}
}
tool.ended = true;
send(client, RunEvent::ToolCallEnd { index }).await
}
Some(_) => Err("provider emitted duplicate ToolCallEnd"),
None => Err("provider ended an unknown tool index"),
@@ -239,6 +254,13 @@ pub async fn consume_model_cycle(
ModelEvent::Usage(value) => {
if usage.replace(value).is_some() {
Err("provider emitted duplicate Usage")
} else if send(client, RunEvent::Usage(value)).await.is_err() {
return Err(failure(
RunFailure::Client("client event channel closed".into()),
text,
reasoning,
usage,
));
} else {
Ok(())
}
@@ -280,7 +302,7 @@ pub async fn consume_model_cycle(
.map(|tool| tool.call)
.collect::<Vec<_>>();
if finish_reason == FinishReason::Length {
return Err(failure(
return Err(terminal_failure(
RunFailure::Provider("model stopped before completing the response".into()),
text,
reasoning,
@@ -296,16 +318,6 @@ pub async fn consume_model_cycle(
usage,
));
}
if let Some(usage) = usage {
if send(client, RunEvent::Usage(usage)).await.is_err() {
return Err(failure(
RunFailure::Client("client event channel closed".into()),
text,
reasoning,
Some(usage),
));
}
}
let model_call_id = model_call_id.ok_or_else(|| {
failure(
RunFailure::Protocol("provider completed without Start".into()),
@@ -360,10 +372,83 @@ fn failure(
partial_reasoning: String,
usage: Option<Usage>,
) -> ModelCycleFailure {
let retryable = matches!(failure, RunFailure::Protocol(_) | RunFailure::Provider(_));
ModelCycleFailure {
failure,
partial_text,
partial_reasoning,
usage,
retryable,
}
}
fn terminal_failure(
failure: RunFailure,
partial_text: String,
partial_reasoning: String,
usage: Option<Usage>,
) -> ModelCycleFailure {
ModelCycleFailure {
failure,
partial_text,
partial_reasoning,
usage,
retryable: false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
model::Usage,
provider::{FinishReason, ModelEvent},
};
use tokio_stream::wrappers::ReceiverStream;
#[tokio::test]
async fn usage_is_forwarded_before_the_provider_call_finishes() {
let (provider_tx, provider_rx) = tokio::sync::mpsc::channel(4);
let stream = Box::pin(ReceiverStream::new(provider_rx));
let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(4);
let cancellation = CancellationToken::new();
let cycle_cancellation = cancellation.clone();
let cycle = tokio::spawn(async move {
consume_model_cycle(stream, &event_tx, &cycle_cancellation).await
});
let usage = Usage {
input_tokens: Some(100),
context_input_tokens: Some(100),
output_tokens: Some(20),
total_tokens: Some(120),
..Default::default()
};
provider_tx
.send(Ok(ModelEvent::Start {
model_call_id: "call".into(),
}))
.await
.unwrap();
provider_tx
.send(Ok(ModelEvent::Usage(usage)))
.await
.unwrap();
let event = tokio::time::timeout(std::time::Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap();
assert!(matches!(event, RunEvent::Usage(value) if value == usage));
assert!(!cycle.is_finished(), "usage must arrive before Done");
provider_tx
.send(Ok(ModelEvent::Done(FinishReason::Stop)))
.await
.unwrap();
drop(provider_tx);
let result = cycle.await.unwrap().unwrap();
assert_eq!(result.usage, Some(usage));
assert!(event_rx.try_recv().is_err(), "usage must be forwarded once");
}
}
+42
View File
@@ -0,0 +1,42 @@
//! Defines retry policy for one logical model call.
use std::time::Duration;
use super::ModelCycleFailure;
pub(super) const MAX_MODEL_RETRIES: u32 = 8;
pub(super) const MODEL_RETRY_DELAY: Duration = Duration::from_secs(5);
pub(super) fn should_retry(failure: &ModelCycleFailure, retries: u32) -> bool {
failure.retryable && retries < MAX_MODEL_RETRIES
}
#[cfg(test)]
mod tests {
use super::*;
use crate::run::{ModelCycleFailure, RunFailure};
fn failure(retryable: bool) -> ModelCycleFailure {
ModelCycleFailure {
failure: RunFailure::Provider("failed".into()),
partial_text: String::new(),
partial_reasoning: String::new(),
usage: None,
retryable,
}
}
#[test]
fn permits_eight_retries_after_the_initial_attempt() {
let retryable = failure(true);
for retries in 0..MAX_MODEL_RETRIES {
assert!(should_retry(&retryable, retries));
}
assert!(!should_retry(&retryable, MAX_MODEL_RETRIES));
}
#[test]
fn terminal_failures_never_retry() {
assert!(!should_retry(&failure(false), 0));
}
}