feat: add first valid response timing and related metrics

- Introduced `first_valid_response_ms` and `ttfr_ms` to track the timing of the first valid response in LLM calls.
- Updated relevant interfaces and components to display and utilize the new metrics, including CallDetails, CallTable, and LatencyChart.
- Enhanced the database schema to accommodate the new timing fields.
- Implemented logic in the service layer to record the first valid response during model interactions.
This commit is contained in:
leookun committed 2026-08-28 22:56:39 +08:00
1 parent 5a0bc2e0e9
commit 5cc2401ce2
20 files changed
+461 -52

No files matched your search

+53
View File
@@ -34,3 +34,56 @@ pub enum ModelEvent {
Usage(Usage),
Done(FinishReason),
}
/// Returns whether an event represents the first valid upstream response.
/// Transport markers, replay metadata, usage, completion, and provider heartbeats
/// are intentionally excluded; empty text/reasoning/tool deltas are valid events.
pub fn is_valid_response_event(event: &ModelEvent) -> bool {
matches!(
event,
ModelEvent::TextDelta(_)
| ModelEvent::ThinkingStart
| ModelEvent::ThinkingDelta(_)
| ModelEvent::ThinkingEnd
| ModelEvent::ToolCallStart { .. }
| ModelEvent::ToolCallArgumentsDelta { .. }
| ModelEvent::ToolCallEnd { .. }
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn response_markers_include_empty_content_but_exclude_transport_events() {
assert!(is_valid_response_event(&ModelEvent::TextDelta(
String::new()
)));
assert!(is_valid_response_event(&ModelEvent::ThinkingDelta(
String::new()
)));
assert!(is_valid_response_event(
&ModelEvent::ToolCallArgumentsDelta {
index: 0,
delta: String::new(),
}
));
assert!(is_valid_response_event(&ModelEvent::ThinkingStart));
assert!(is_valid_response_event(&ModelEvent::ToolCallStart {
index: 0,
call_id: "call".into(),
name: "tool".into(),
}));
assert!(!is_valid_response_event(&ModelEvent::Start {
model_call_id: "call".into(),
}));
assert!(!is_valid_response_event(&ModelEvent::TextStart));
assert!(!is_valid_response_event(&ModelEvent::Usage(
Usage::default()
)));
assert!(!is_valid_response_event(&ModelEvent::Done(
FinishReason::Stop
)));
}
}
+73 -2
View File
@@ -14,7 +14,7 @@ use crate::{
Result,
};
use super::{FinishReason, ModelEvent};
use super::{is_valid_response_event, FinishReason, ModelEvent};
pub(crate) fn recorded_headers(
config: &crate::config::ProviderConfig,
@@ -56,6 +56,7 @@ struct AttemptState {
next_chunk: AtomicI64,
chunks: ChunkBuffer,
first_text_recorded: AtomicBool,
first_valid_response_recorded: AtomicBool,
}
impl AttemptState {
@@ -66,6 +67,7 @@ impl AttemptState {
next_chunk: AtomicI64::new(0),
chunks: ChunkBuffer::default(),
first_text_recorded: AtomicBool::new(false),
first_valid_response_recorded: AtomicBool::new(false),
}
}
}
@@ -176,8 +178,29 @@ impl CallRecorder {
}
pub async fn event(&self, event: &ModelEvent) -> Result<()> {
let attempt = self.inner.attempt.lock().await;
if is_valid_response_event(event)
&& attempt
.first_valid_response_recorded
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
if let Err(error) = self
.inner
.store
.record_llm_first_valid_response(&attempt.call_id, elapsed_ms(attempt.started))
.await
{
attempt
.first_valid_response_recorded
.store(false, Ordering::Release);
return Err(error);
}
}
drop(attempt);
match event {
ModelEvent::TextDelta(_) => {
ModelEvent::TextDelta(delta) if !delta.trim().is_empty() => {
let attempt = self.inner.attempt.lock().await;
if attempt
.first_text_recorded
@@ -470,6 +493,54 @@ mod tests {
assert_eq!(count, 1);
}
#[tokio::test]
async fn first_valid_response_includes_empty_text_and_reasoning_events() {
let store = Store::connect("sqlite::memory:").await.unwrap();
let recorder = test_recorder(&store, "first-valid-response-call", false).await;
recorder
.event(&ModelEvent::Start {
model_call_id: "call".into(),
})
.await
.unwrap();
recorder.event(&ModelEvent::TextStart).await.unwrap();
recorder
.event(&ModelEvent::TextDelta(String::new()))
.await
.unwrap();
let call = store
.llm_call("first-valid-response-call")
.await
.unwrap()
.unwrap();
assert!(call.ttfr_ms.is_some());
assert!(call.ttft_ms.is_none());
recorder
.event(&ModelEvent::TextDelta("text".into()))
.await
.unwrap();
let call = store
.llm_call("first-valid-response-call")
.await
.unwrap()
.unwrap();
assert!(call.ttft_ms.is_some());
recorder
.event(&ModelEvent::ThinkingDelta("reasoning".into()))
.await
.unwrap();
let call = store
.llm_call("first-valid-response-call")
.await
.unwrap()
.unwrap();
assert!(call.first_valid_response_at_ms.is_some());
}
#[tokio::test]
async fn retry_finishes_the_old_call_and_records_the_new_request() {
let store = Store::connect("sqlite::memory:").await.unwrap();