use std::time::Duration;
use futures_util::StreamExt;
use super::{AgentLoop, AgentLoopError};
use crate::llm::{ChatRequest, ChatResponse, ChatStreamEvent, InferenceError, StreamAssembly};
const INFERENCE_MAX_ATTEMPTS: u8 = 3;
const INFERENCE_RETRY_DELAYS: [Duration; 2] =
[Duration::from_millis(100), Duration::from_millis(200)];
const _: () = assert!(INFERENCE_MAX_ATTEMPTS as usize == INFERENCE_RETRY_DELAYS.len() + 1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResponseExposure {
Unexposed,
Exposed,
}
impl AgentLoop {
pub(super) async fn chat_turn(
&self,
request: &ChatRequest,
turn_id: &str,
) -> Result<ChatResponse, AgentLoopError> {
let Some(sink) = self.sink.clone() else {
let mut attempt = 1;
loop {
match self.llm.chat(request).await {
Ok(response) => return Ok(response),
Err(error) if error.is_retryable() && attempt < INFERENCE_MAX_ATTEMPTS => {
self.wait_before_inference_retry(attempt, &error).await;
attempt += 1;
}
Err(error) => {
if error.is_retryable() {
self.warn_inference_retry_exhausted(attempt, &error);
}
return Err(AgentLoopError::Llm(error));
}
}
}
};
let mut attempt = 1;
loop {
let mut stream = match self.llm.chat_stream(request).await {
Ok(stream) => stream,
Err(error) if error.is_retryable() && attempt < INFERENCE_MAX_ATTEMPTS => {
self.wait_before_inference_retry(attempt, &error).await;
attempt += 1;
continue;
}
Err(error) => {
if error.is_retryable() {
self.warn_inference_retry_exhausted(attempt, &error);
}
return Err(AgentLoopError::Llm(error));
}
};
let mut assembly = StreamAssembly::new();
let mut exposure = ResponseExposure::Unexposed;
let mut retry_error = None;
while let Some(event) = stream.next().await {
let event = match event {
Ok(event) => event,
Err(error)
if error.is_retryable()
&& exposure == ResponseExposure::Unexposed
&& attempt < INFERENCE_MAX_ATTEMPTS =>
{
retry_error = Some(error);
break;
}
Err(error) => {
if error.is_retryable() && exposure == ResponseExposure::Unexposed {
self.warn_inference_retry_exhausted(attempt, &error);
}
return Err(AgentLoopError::Llm(error));
}
};
if let ChatStreamEvent::Delta(chunk) = &event
&& !chunk.is_empty()
{
exposure = ResponseExposure::Exposed;
sink.agent_message(
self.agent_name(),
self.agent_id_str(),
turn_id,
chunk,
false,
)
.await;
}
assembly.push(event);
}
if let Some(error) = retry_error {
self.wait_before_inference_retry(attempt, &error).await;
attempt += 1;
continue;
}
if exposure == ResponseExposure::Exposed {
sink.agent_message(self.agent_name(), self.agent_id_str(), turn_id, "", true)
.await;
}
return Ok(assembly.into_response(String::new(), request.model.clone()));
}
}
async fn wait_before_inference_retry(&self, failed_attempt: u8, error: &InferenceError) {
let delay = INFERENCE_RETRY_DELAYS[usize::from(failed_attempt - 1)];
tracing::warn!(
attempt = failed_attempt,
max_attempts = INFERENCE_MAX_ATTEMPTS,
provider = self.llm.name(),
error_class = inference_error_class(error),
delay_ms = delay.as_millis(),
"retryable inference attempt failed; retrying"
);
tokio::time::sleep(delay).await;
}
fn warn_inference_retry_exhausted(&self, attempt: u8, error: &InferenceError) {
tracing::warn!(
attempt,
max_attempts = INFERENCE_MAX_ATTEMPTS,
provider = self.llm.name(),
error_class = inference_error_class(error),
"retryable inference attempts exhausted"
);
}
}
fn inference_error_class(error: &InferenceError) -> &'static str {
match error {
InferenceError::Transport(_) => "transport",
InferenceError::Api { .. } => "api",
InferenceError::Deserialise { .. } => "deserialise",
InferenceError::MissingCredential { .. } => "missing_credential",
InferenceError::NoAdapterRegistered { .. } => "no_adapter_registered",
InferenceError::Provider(_) => "provider",
InferenceError::Unsupported(_) => "unsupported",
InferenceError::MissingConfig(_) => "missing_config",
}
}