1use crate::budget::{self, Limits};
2use crate::dsl::Call;
3use crate::error::AgentError;
4use crate::eval::{judge_request, judge_verdict, repair_message};
5use crate::io::{AgentIo, ModelHandle};
6use crate::persona::{open_trace, Persona, SavedTrace};
7use crate::schema::{parse_json, validate};
8use futures_util::future::join_all;
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use std::time::Instant;
12use troupekit_core::error::ProviderErrorKind;
13use troupekit_core::event::{Event, EventBody, PauseReason, Usage};
14use troupekit_core::ids::RunId;
15use troupekit_core::message::{ContentPart, Message, Role};
16use troupekit_core::store::{Checkpoint, CheckpointStore};
17use troupekit_providers::{CompletionRequest, CompletionResponse, Delta, FailedCall, StopReason};
18use troupekit_tools::{ToolContext, ToolOutput};
19use troupekit_trace::{content, trace, trace_span, Trace, TraceSpec};
20
21pub const RUN_FORMAT: u32 = 1;
25
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30#[serde(deny_unknown_fields)]
31pub struct PendingCall {
32 pub id: String,
33 pub name: String,
34 pub arguments: Value,
35}
36
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41#[serde(tag = "state", rename_all = "snake_case")]
42pub enum RunState {
43 CallModel,
44 CallTools {
45 calls: Vec<PendingCall>,
46 },
47 Check {
48 answer: String,
49 },
50 Repair {
51 errors: Vec<String>,
52 },
53 Done {
54 output: Value,
55 },
56 Failed {
57 error: String,
58 },
59 Paused {
60 reason: PauseReason,
61 resume: Box<RunState>,
62 },
63}
64
65impl RunState {
66 fn step_name(&self) -> &'static str {
67 match self {
68 RunState::CallModel => "call_model",
69 RunState::CallTools { .. } => "call_tools",
70 RunState::Check { .. } => "check",
71 RunState::Repair { .. } => "repair",
72 RunState::Done { .. } | RunState::Failed { .. } | RunState::Paused { .. } => {
73 unreachable!("only working states take steps")
74 }
75 }
76 }
77}
78
79#[derive(Debug, Clone, PartialEq)]
83pub enum StepOutcome {
84 Continue,
85 Retry {
86 error: String,
87 retry_after_ms: Option<u64>,
88 },
89 Paused(PauseReason),
90 Done(Value),
91 Failed(String),
92}
93
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95#[serde(deny_unknown_fields)]
96struct RunSpec {
97 persona: String,
98 model: String,
99 system: String,
100 tools: Vec<String>,
101 evals: Vec<Call>,
102 output: Option<Value>,
103 max_turns: u32,
104 max_tokens: u32,
105}
106
107#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111#[serde(deny_unknown_fields)]
112pub struct AgentRun {
113 format: u32,
114 run_id: RunId,
115 spec: RunSpec,
116 limits: Limits,
117 messages: Vec<Message>,
118 state: RunState,
119 model_calls: u32,
120 repaired: bool,
121 usage: Usage,
122 seq: u64,
123 steps: u64,
124 #[serde(default, skip_serializing_if = "is_zero")]
125 retries: u32,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 retry_at_ms: Option<i64>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 trace: Option<SavedTrace>,
130 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
131 host_failed: bool,
132}
133
134fn is_zero(n: &u32) -> bool {
138 *n == 0
139}
140
141impl AgentRun {
142 pub async fn new(
146 persona: &Persona,
147 input: Vec<Message>,
148 limits: Limits,
149 io: &dyn AgentIo,
150 ) -> Result<AgentRun, AgentError> {
151 let setup = |m: String| AgentError::Setup(format!("{}: {m}", persona.source));
152 if input.is_empty() {
153 return Err(setup("a run needs at least one input message".into()));
154 }
155 if persona.instructions.trim().is_empty() {
156 return Err(setup("instructions are not loaded".into()));
157 }
158 if let Some(t) = persona.tools.iter().find(|t| io.tools().get(t).is_none()) {
159 return Err(setup(format!("tool `{t}` is not registered")));
160 }
161 let mut models = vec![persona.model.clone()];
162 for e in &persona.evals {
163 if e.name == "judge" {
164 models.extend(e.args.get(2).and_then(Value::as_str).map(str::to_string));
165 } else if io.evals().get(&e.name).is_none() {
166 return Err(setup(format!("eval `{}` is not registered", e.name)));
167 }
168 }
169 for m in &models {
170 io.model(m).await.map_err(|e| setup(e.to_string()))?;
171 }
172 Ok(AgentRun {
173 format: RUN_FORMAT,
174 run_id: RunId::new(),
175 spec: RunSpec {
176 persona: persona.name.clone(),
177 model: persona.model.clone(),
178 system: persona.system_prompt(),
179 tools: persona.tools.clone(),
180 evals: persona.evals.clone(),
181 output: persona.output.clone(),
182 max_turns: persona.max_turns,
183 max_tokens: persona.max_tokens,
184 },
185 limits: limits.with_budget(&persona.budget),
186 messages: input,
187 state: RunState::CallModel,
188 model_calls: 0,
189 repaired: false,
190 usage: Usage::default(),
191 seq: 0,
192 steps: 0,
193 retries: 0,
194 retry_at_ms: None,
195 trace: None,
196 host_failed: false,
197 })
198 }
199
200 pub fn from_checkpoint(cp: &Checkpoint) -> Result<AgentRun, AgentError> {
204 let run: AgentRun = serde_json::from_value(cp.state.clone())
205 .map_err(|e| AgentError::Checkpoint(e.to_string()))?;
206 if run.format != RUN_FORMAT {
207 return Err(AgentError::Checkpoint(format!(
208 "run format {} is not {RUN_FORMAT}",
209 run.format
210 )));
211 }
212 if run.run_id != cp.run_id || run.steps != cp.step {
213 return Err(AgentError::Checkpoint(
214 "checkpoint header does not match its state".into(),
215 ));
216 }
217 if let Some(saved) = &run.trace {
218 saved.check_loaded().map_err(AgentError::Checkpoint)?;
219 }
220 Ok(run)
221 }
222
223 pub fn checkpoint(&self) -> Checkpoint {
227 Checkpoint {
228 run_id: self.run_id,
229 step: self.steps,
230 state: serde_json::to_value(self).expect("run state serializes"),
231 }
232 }
233
234 pub fn retries(&self) -> u32 {
238 self.retries
239 }
240
241 pub fn retry_at_ms(&self) -> Option<i64> {
246 self.retry_at_ms
247 }
248
249 pub fn set_retry_at_ms(&mut self, at_ms: Option<i64>) {
253 self.retry_at_ms = at_ms;
254 }
255
256 pub fn host_failed(&self) -> bool {
260 self.host_failed
261 }
262
263 pub fn run_id(&self) -> RunId {
267 self.run_id
268 }
269
270 pub fn state(&self) -> &RunState {
274 &self.state
275 }
276
277 pub fn messages(&self) -> &[Message] {
281 &self.messages
282 }
283
284 pub fn usage(&self) -> Usage {
288 self.usage
289 }
290
291 pub fn model_calls(&self) -> u32 {
295 self.model_calls
296 }
297
298 pub fn persona(&self) -> &str {
302 &self.spec.persona
303 }
304
305 pub fn tighten(&mut self, limits: &Limits) {
310 self.limits = self.limits.clone().stricter(limits);
311 }
312
313 pub fn resume(&mut self, limits: Limits) -> Result<(), AgentError> {
317 let RunState::Paused { resume, .. } = &self.state else {
318 return Err(AgentError::Setup("run is not paused".into()));
319 };
320 self.state = (**resume).clone();
321 self.limits = limits;
322 Ok(())
323 }
324
325 pub fn set_trace(&mut self, spec: TraceSpec) {
329 self.trace = Some(SavedTrace::from_spec(&spec));
330 assert_eq!(self.trace(), Some(spec));
331 }
332
333 pub fn trace(&self) -> Option<TraceSpec> {
336 self.trace
337 .as_ref()
338 .map(|saved| saved.spec().expect("trace spec checked when set or loaded"))
339 }
340
341 pub async fn step(&mut self, io: &dyn AgentIo) -> StepOutcome {
347 let working = !matches!(
348 self.state,
349 RunState::Done { .. } | RunState::Failed { .. } | RunState::Paused { .. }
350 );
351 let Some(spec) = self.trace().filter(|_| working) else {
352 return self.step_once(io).await;
353 };
354 if let Some(scope) = troupekit_trace::current() {
355 let content = scope.content() && spec.content();
356 let nested = scope.nest(spec.categories(), Some(content));
357 assert!(!nested.content() || scope.content());
358 return nested.in_scope(self.step_once(io)).await;
359 }
360 match open_trace(&spec, &self.spec.persona, self.run_id) {
361 Ok(tracer) => tracer.in_scope(self.step_once(io)).await,
362 Err(_) => self.step_once(io).await,
363 }
364 }
365
366 async fn step_once(&mut self, io: &dyn AgentIo) -> StepOutcome {
367 match &self.state {
368 RunState::Done { output } => return StepOutcome::Done(output.clone()),
369 RunState::Failed { error } => return StepOutcome::Failed(error.clone()),
370 RunState::Paused { reason, .. } => return StepOutcome::Paused(reason.clone()),
371 _ => {}
372 }
373 if self.seq == 0 {
374 self.emit(
375 io,
376 EventBody::RunStarted {
377 workflow: self.spec.persona.clone(),
378 },
379 );
380 }
381 self.steps += 1;
382 let name = self.state.step_name();
383 let mut span = trace_span!(
384 Trace::Agents,
385 "agent.step",
386 run = self.run_id.to_string(),
387 state = name,
388 persona = self.spec.persona.as_str(),
389 );
390 self.emit(
391 io,
392 EventBody::StepStarted {
393 step: name.into(),
394 persona: None,
395 },
396 );
397 let mut used = Usage::default();
398 let outcome = span
399 .instrument(async {
400 match self.state.clone() {
401 RunState::CallModel => self.call_model(io, &mut used).await,
402 RunState::CallTools { calls } => self.call_tools(io, &calls).await,
403 RunState::Check { answer } => self.check(io, &answer, &mut used).await,
404 RunState::Repair { errors } => {
405 self.messages.push(repair_message(&errors));
406 self.state = RunState::CallModel;
407 StepOutcome::Continue
408 }
409 RunState::Done { .. } | RunState::Failed { .. } | RunState::Paused { .. } => {
410 unreachable!("handled above")
411 }
412 }
413 })
414 .await;
415 if let StepOutcome::Failed(error) = &outcome {
416 span.fail("step failed");
417 span.record("error", content(error.as_str()));
418 }
419 self.emit(
420 io,
421 EventBody::StepFinished {
422 step: name.into(),
423 usage: used,
424 },
425 );
426 match &outcome {
427 StepOutcome::Paused(reason) => self.emit(
428 io,
429 EventBody::RunPaused {
430 reason: reason.clone(),
431 },
432 ),
433 StepOutcome::Done(_) => self.emit(io, EventBody::RunFinished { usage: self.usage }),
434 StepOutcome::Failed(error) => self.emit(
435 io,
436 EventBody::RunFailed {
437 error: error.clone(),
438 },
439 ),
440 StepOutcome::Retry { .. } => self.retries = self.retries.saturating_add(1),
441 StepOutcome::Continue => {}
442 }
443 outcome
444 }
445
446 fn emit(&mut self, io: &dyn AgentIo, body: EventBody) {
447 io.events().emit(Event {
448 run_id: self.run_id,
449 seq: self.seq,
450 at_ms: io.clock().now_ms(),
451 body,
452 });
453 self.seq += 1;
454 }
455
456 fn fail(&mut self, error: String) -> StepOutcome {
457 self.state = RunState::Failed {
458 error: error.clone(),
459 };
460 StepOutcome::Failed(error)
461 }
462
463 fn request(&self, io: &dyn AgentIo) -> CompletionRequest {
464 let tools = io
465 .tools()
466 .specs()
467 .into_iter()
468 .filter(|s| self.spec.tools.contains(&s.name))
469 .filter_map(|mut s| {
470 if let Some(h) = s.hosted {
471 let used: u64 = self.messages.iter().map(|m| m.hosted_calls(h.name())).sum();
472 let left = u64::from(h.max_uses()).saturating_sub(used);
473 if left == 0 {
474 return None;
475 }
476 s.hosted = Some(
477 h.with_max_uses(u32::try_from(left).expect("left is at most max_uses")),
478 );
479 }
480 Some(s)
481 })
482 .collect();
483 CompletionRequest {
484 model: None,
485 system: Some(self.spec.system.clone()),
486 messages: self.messages.clone(),
487 tools,
488 max_tokens: self.spec.max_tokens,
489 temperature: None,
490 output_schema: self.spec.output.clone(),
491 }
492 }
493
494 async fn call_model(&mut self, io: &dyn AgentIo, used: &mut Usage) -> StepOutcome {
495 let held = self.model_calls < self.spec.max_turns;
496 trace!(
497 Trace::Laws,
498 "law.check",
499 law = "step_keeps_model_calls_within_max_turns",
500 held = held,
501 model_calls = self.model_calls,
502 max_turns = self.spec.max_turns,
503 );
504 if !held {
505 return self.fail(format!("max_turns {} reached", self.spec.max_turns));
506 }
507 let handle = match io.model(&self.spec.model).await {
508 Ok(h) => h,
509 Err(e) => return self.fail(e.to_string()),
510 };
511 let req = self.request(io);
512 let reply = match self
513 .call(io, &handle, &req, true, used, RunState::CallModel)
514 .await
515 {
516 Ok(r) => r,
517 Err(outcome) => return outcome,
518 };
519 self.model_calls += 1;
520 let calls: Vec<PendingCall> = reply
521 .message
522 .tool_calls()
523 .map(|(id, name, arguments)| PendingCall {
524 id: id.into(),
525 name: name.into(),
526 arguments: arguments.clone(),
527 })
528 .collect();
529 let answer = reply.message.final_text();
530 let kept = reply
531 .message
532 .parts
533 .iter()
534 .any(|p| !matches!(p, ContentPart::Text { text } if text.trim().is_empty()));
535 if kept {
536 self.messages.push(reply.message);
537 }
538 self.state = if reply.stop == StopReason::PauseTurn {
539 RunState::CallModel
540 } else if calls.is_empty() {
541 RunState::Check { answer }
542 } else {
543 RunState::CallTools { calls }
544 };
545 StepOutcome::Continue
546 }
547
548 async fn call(
549 &mut self,
550 io: &dyn AgentIo,
551 handle: &ModelHandle,
552 req: &CompletionRequest,
553 stream: bool,
554 used: &mut Usage,
555 resume: RunState,
556 ) -> Result<CompletionResponse, StepOutcome> {
557 let estimate = budget::estimate_calls(req, &handle.price, handle.model.extra_calls(req));
558 let _reservation = match budget::admit(
559 &self.limits,
560 &handle.price,
561 self.usage.cost_usd_micros,
562 estimate,
563 io.ledger(),
564 )
565 .await
566 {
567 Err(e) => {
568 return Err(StepOutcome::Retry {
569 error: format!("usage ledger: {e}"),
570 retry_after_ms: None,
571 })
572 }
573 Ok(Err(layer)) => {
574 let reason = PauseReason::Budget {
575 limit: layer.into(),
576 };
577 self.state = RunState::Paused {
578 reason: reason.clone(),
579 resume: Box::new(resume),
580 };
581 return Err(StepOutcome::Paused(reason));
582 }
583 Ok(Ok(reservation)) => reservation,
584 };
585 let mut span = trace_span!(
586 Trace::Models,
587 "model.call",
588 model = handle.model.id(),
589 stream = stream,
590 messages = content(serde_json::to_string(&req.messages).expect("messages serialize")),
591 );
592 let started = span.is_enabled().then(Instant::now);
593 let mut first_delta: Option<Instant> = None;
594 let result = if stream {
595 let (sink, clock, run_id, seq) = (io.events(), io.clock(), self.run_id, &mut self.seq);
596 let first = &mut first_delta;
597 let timed = started.is_some();
598 let mut on_delta = |d: &Delta| {
599 if timed {
600 first.get_or_insert_with(Instant::now);
601 }
602 if let Delta::TextDelta { text } = d {
603 sink.emit(Event {
604 run_id,
605 seq: *seq,
606 at_ms: clock.now_ms(),
607 body: EventBody::TextDelta { text: text.clone() },
608 });
609 *seq += 1;
610 }
611 };
612 span.instrument(handle.model.stream_billed(req, &mut on_delta))
613 .await
614 } else {
615 span.instrument(handle.model.complete_billed(req)).await
616 };
617 if let (Some(started), Some(at)) = (started, first_delta) {
618 span.record(
619 "ttft_us",
620 at.saturating_duration_since(started).as_micros() as u64,
621 );
622 }
623 if let Err(FailedCall { error: e, .. }) = &result {
624 span.fail("model call failed");
625 span.record("retryable", e.is_retryable());
626 span.record("error", content(e.to_string()));
627 }
628 let mut reply = match result {
629 Ok(r) => r,
630 Err(FailedCall { error: e, usage }) => {
631 drop(span);
632 if usage != Usage::default() {
633 self.bill(io, priced(handle, usage), used).await?;
634 }
635 if e.is_retryable() {
636 return Err(StepOutcome::Retry {
637 error: e.to_string(),
638 retry_after_ms: e.retry_after_ms,
639 });
640 }
641 self.host_failed = e.kind == ProviderErrorKind::Host;
642 return Err(self.fail(e.to_string()));
643 }
644 };
645 reply.usage = priced_reply(handle, &reply);
646 if span.is_enabled() {
647 span.record("input_tokens", reply.usage.input_tokens);
648 span.record("output_tokens", reply.usage.output_tokens);
649 span.record("cost_usd_micros", reply.usage.cost_usd_micros);
650 span.record("stop", format!("{:?}", reply.stop));
651 span.record("reply", content(reply.message.text_content()));
652 }
653 drop(span);
654 self.bill(io, reply.usage, used).await?;
655 Ok(reply)
656 }
657
658 async fn bill(
662 &mut self,
663 io: &dyn AgentIo,
664 usage: Usage,
665 used: &mut Usage,
666 ) -> Result<(), StepOutcome> {
667 self.usage += usage;
668 *used += usage;
669 if let Err(e) = budget::record(&self.limits, io.ledger(), usage).await {
670 return Err(self.fail(format!("usage ledger: {e}")));
671 }
672 Ok(())
673 }
674
675 async fn call_tools(&mut self, io: &dyn AgentIo, calls: &[PendingCall]) -> StepOutcome {
676 assert!(!calls.is_empty(), "a tool step has at least one call");
677 for c in calls {
678 self.emit(
679 io,
680 EventBody::ToolCallStarted {
681 call_id: c.id.clone(),
682 name: c.name.clone(),
683 },
684 );
685 }
686 let (run_id, step) = (self.run_id, self.steps);
687 let allowed = &self.spec.tools;
688 let outputs = join_all(calls.iter().enumerate().map(|(i, c)| {
689 let ctx = ToolContext::for_call(run_id, step, i);
690 async move {
691 let mut span = trace_span!(
692 Trace::Tools,
693 "tool.call",
694 name = c.name.as_str(),
695 call_id = c.id.as_str(),
696 args = content(c.arguments.to_string()),
697 );
698 let out = if allowed.contains(&c.name) {
699 let call = io.tools().call(&c.name, c.arguments.clone(), &ctx);
700 ToolOutput::from_result(span.instrument(call).await)
701 } else {
702 ToolOutput::error(format!("tool `{}` is not allowed for this agent", c.name))
703 };
704 if span.is_enabled() {
705 span.record("is_error", out.is_error);
706 span.record("output", content(out.content.as_str()));
707 }
708 out
709 }
710 }))
711 .await;
712 assert_eq!(outputs.len(), calls.len());
713 let mut parts = Vec::with_capacity(calls.len());
714 for (c, out) in calls.iter().zip(outputs) {
715 self.emit(
716 io,
717 EventBody::ToolCallFinished {
718 call_id: c.id.clone(),
719 is_error: out.is_error,
720 },
721 );
722 parts.push(ContentPart::ToolResult {
723 call_id: c.id.clone(),
724 content: out.content,
725 is_error: out.is_error,
726 });
727 }
728 self.messages
729 .push(Message::new(Role::Tool, parts).expect("tool results form a valid tool message"));
730 self.state = RunState::CallModel;
731 StepOutcome::Continue
732 }
733
734 async fn check(&mut self, io: &dyn AgentIo, answer: &str, used: &mut Usage) -> StepOutcome {
735 let (output, mut errors) = match &self.spec.output {
736 None => (Value::String(answer.to_string()), Vec::new()),
737 Some(schema) => match parse_json(answer) {
738 Err(e) => (Value::Null, vec![e]),
739 Ok(v) => {
740 let errs = validate(schema, &v);
741 (v, errs)
742 }
743 },
744 };
745 if errors.is_empty() {
746 for call in self.spec.evals.clone() {
747 if call.name == "judge" {
748 match self.judge(io, &call, &output, answer, used).await {
749 Ok(None) => {}
750 Ok(Some(reason)) => errors.push(format!("judge: {reason}")),
751 Err(outcome) => return outcome,
752 }
753 continue;
754 }
755 let Some(f) = io.evals().get(&call.name) else {
756 return self.fail(format!("eval `{}` is not registered", call.name));
757 };
758 let mut span = trace_span!(Trace::Evals, "eval.run", name = call.name.as_str());
759 let passed = f(&output, &call.args);
760 span.record("passed", passed.is_ok());
761 if let Err(e) = passed {
762 errors.push(format!("{}: {e}", call.name));
763 }
764 }
765 }
766 if errors.is_empty() {
767 self.state = RunState::Done {
768 output: output.clone(),
769 };
770 return StepOutcome::Done(output);
771 }
772 if !self.repaired && self.model_calls < self.spec.max_turns {
773 self.repaired = true;
774 self.state = RunState::Repair { errors };
775 return StepOutcome::Continue;
776 }
777 self.fail(errors.join("; "))
778 }
779
780 async fn judge(
781 &mut self,
782 io: &dyn AgentIo,
783 call: &Call,
784 output: &Value,
785 answer: &str,
786 used: &mut Usage,
787 ) -> Result<Option<String>, StepOutcome> {
788 let criteria = call
789 .args
790 .first()
791 .and_then(Value::as_str)
792 .expect("judge criteria checked at persona load");
793 let min_score = call
794 .args
795 .get(1)
796 .and_then(Value::as_f64)
797 .expect("judge min_score checked at persona load");
798 let selector = call
799 .args
800 .get(2)
801 .and_then(Value::as_str)
802 .unwrap_or(self.spec.model.as_str())
803 .to_string();
804 let mut span = trace_span!(
805 Trace::Evals,
806 "eval.judge",
807 name = "judge",
808 selector = selector.as_str(),
809 );
810 let handle = match io.model(&selector).await {
811 Ok(h) => h,
812 Err(e) => {
813 span.fail(e.to_string());
814 return Err(self.fail(format!("judge: {e}")));
815 }
816 };
817 let req = judge_request(criteria, output);
818 let resume = RunState::Check {
819 answer: answer.to_string(),
820 };
821 let reply = match span
822 .instrument(self.call(io, &handle, &req, false, used, resume))
823 .await
824 {
825 Ok(reply) => reply,
826 Err(outcome) => {
827 span.fail("judge call did not complete");
828 return Err(outcome);
829 }
830 };
831 let text = reply.message.text_content();
832 let verdict = judge_verdict(&text, min_score);
833 if span.is_enabled() {
834 span.record("passed", verdict.is_ok());
835 if let Some(score) = parse_json(&text).ok().and_then(|v| v["score"].as_f64()) {
836 span.record("score", score);
837 }
838 }
839 Ok(verdict.err())
840 }
841}
842
843pub async fn drive(
847 run: &mut AgentRun,
848 io: &dyn AgentIo,
849 store: &dyn CheckpointStore,
850) -> Result<StepOutcome, AgentError> {
851 if store.latest(run.run_id).await?.is_none() {
852 store.save(run.checkpoint()).await?;
853 }
854 loop {
855 let outcome = run.step(io).await;
856 store.save(run.checkpoint()).await?;
857 if outcome != StepOutcome::Continue {
858 return Ok(outcome);
859 }
860 }
861}
862
863fn priced(handle: &ModelHandle, mut usage: Usage) -> Usage {
867 if repriced(handle) {
868 usage.cost_usd_micros = handle.price.cost_usd_micros(&usage);
869 }
870 usage
871}
872
873fn repriced(handle: &ModelHandle) -> bool {
877 let metered_elsewhere = handle
878 .model
879 .meter_price()
880 .is_some_and(|p| p != handle.price);
881 !handle.model.prices_replies() || metered_elsewhere
882}
883
884fn priced_reply(handle: &ModelHandle, reply: &CompletionResponse) -> Usage {
889 let mut usage = priced(handle, reply.usage);
890 if repriced(handle) {
891 usage.cost_usd_micros = usage
892 .cost_usd_micros
893 .max(handle.price.reply_cost_usd_micros(reply));
894 }
895 usage
896}