use super::TurnInterruption;
use crate::control::wait_for_stop;
use crate::{RunEvent, TurnRunOptions};
use causa_kernel::{
CallControl, ControlError, InvocationId, ModelGateway, ModelInvokeError, ModelInvokeErrorKind,
ModelOutput, ModelRequest, StreamDelta,
};
use futures_util::StreamExt;
pub(super) fn notify(options: &TurnRunOptions, event: RunEvent<'_>) {
if let Some(observer) = &options.observer {
observer(&event);
}
}
pub(super) fn control_cause(
error: ControlError,
invocation_id: Option<InvocationId>,
) -> TurnInterruption {
match error {
ControlError::Cancelled => TurnInterruption::Cancelled { invocation_id },
ControlError::TimedOut => TurnInterruption::DeadlineExceeded { invocation_id },
}
}
pub(super) fn stopped(
control: &CallControl,
invocation: Option<&InvocationId>,
) -> Option<TurnInterruption> {
control
.check()
.err()
.map(|e| control_cause(e, invocation.cloned()))
}
#[tracing::instrument(
name = "agent.round",
skip_all,
fields(
turn_id = %request.invocation_id.turn_id.0,
round_id = request.invocation_id.round_id.0,
model = %request.model.0,
usage.input = tracing::field::Empty,
usage.cache_read = tracing::field::Empty,
usage.cache_write = tracing::field::Empty,
usage.output = tracing::field::Empty,
)
)]
pub(super) async fn invoke(
gateway: &dyn ModelGateway,
request: &ModelRequest,
options: &TurnRunOptions,
control: &CallControl,
streaming: bool,
) -> Result<ModelOutput, TurnInterruption> {
let call_control = control.clone();
let call = async {
if !streaming {
return gateway.invoke(request, &call_control).await;
}
let mut stream = gateway.stream(request, &call_control).await?;
loop {
call_control.check().map_err(stream_control_error)?;
let Some(delta) = stream.next().await else {
break;
};
call_control.check().map_err(stream_control_error)?;
match delta {
StreamDelta::Done { final_output } => return Ok(final_output),
StreamDelta::Error { error } => {
return Err(error);
}
delta => notify(
options,
RunEvent::ModelDelta {
invocation_id: &request.invocation_id,
delta: &delta,
},
),
}
}
Err(ModelInvokeError::new(
ModelInvokeErrorKind::UnknownOutcome,
"model stream ended without Done",
))
};
let output = tokio::select! {
biased;
error = wait_for_stop(control) => return Err(control_cause(error, Some(request.invocation_id.clone()))),
result = call => result,
};
if let Some(cause) = stopped(control, Some(&request.invocation_id)) {
return Err(cause);
}
let output = output.map_err(|error| TurnInterruption::ModelCallFailed {
invocation_id: request.invocation_id.clone(),
error,
})?;
record_round_usage(&output);
Ok(output)
}
fn record_round_usage(output: &ModelOutput) {
if let Some(usage) = &output.usage {
let span = tracing::Span::current();
span.record("usage.input", usage.input_tokens);
span.record("usage.output", usage.output_tokens);
if let Some(cache_read) = usage.cache_read_tokens {
span.record("usage.cache_read", cache_read);
}
if let Some(cache_write) = usage.cache_write_tokens {
span.record("usage.cache_write", cache_write);
}
}
}
fn stream_control_error(error: ControlError) -> ModelInvokeError {
ModelInvokeError::new(
match error {
ControlError::Cancelled => ModelInvokeErrorKind::Cancelled,
ControlError::TimedOut => ModelInvokeErrorKind::TimedOut,
},
"execution control stopped stream",
)
}