1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
//! Billing for a deep worker's OWN reasoning-loop LLM calls.
//!
//! An in-process `operala.call` deep worker runs in
//! `greentic_dw_operala_invoker::DeepWorkerInvoker`, which is handed a raw
//! `greentic_llm::LlmProvider` and never goes through
//! `greentic_aw_runtime::AgentRuntime` — so none of its planning, execution,
//! reflection or reply-writing calls reached a `BillingMeter`. The invoker
//! exposes no usage of its own, and it does not need to: every one of those
//! calls goes through the provider it was handed, and a
//! `greentic_llm::ChatResponse` carries the provider-reported `usage`. So the
//! handler wraps the provider in [`MeteredLlmProvider`], which emits one event
//! per completed `chat` through the same sink `dw.agent` uses.
//!
//! What it cannot see: `chat_stream` (the invoker never calls it; passed
//! through unmetered) and a response whose backend reported no usage (the rig
//! backend always does — a `None` is skipped rather than recorded as zero, so
//! a zero in the ledger always means the provider said zero).
use std::sync::Arc;
use async_trait::async_trait;
use greentic_aw_runtime::billing::BillingMeter;
use greentic_aw_runtime::tenant::TenantContext;
use greentic_llm::{Capabilities, ChatRequest, ChatResponse, ChatStream, LlmError, LlmProvider};
use serde_json::Value;
/// An [`LlmProvider`] that bills every completed `chat` through `meter`.
pub(crate) struct MeteredLlmProvider {
inner: Arc<dyn LlmProvider>,
meter: Arc<dyn BillingMeter>,
tenant: TenantContext,
agent_id: String,
}
impl MeteredLlmProvider {
pub(crate) fn new(
inner: Arc<dyn LlmProvider>,
meter: Arc<dyn BillingMeter>,
tenant: TenantContext,
agent_id: String,
) -> Self {
Self {
inner,
meter,
tenant,
agent_id,
}
}
}
#[async_trait]
impl LlmProvider for MeteredLlmProvider {
fn capabilities(&self) -> Capabilities {
self.inner.capabilities()
}
fn provider_name(&self) -> &'static str {
self.inner.provider_name()
}
fn model(&self) -> &str {
self.inner.model()
}
async fn chat(&self, req: ChatRequest) -> Result<ChatResponse, LlmError> {
let response = self.inner.chat(req).await?;
if let Some(usage) = &response.usage {
// The CONFIGURED model id, exactly what `dw.agent` and graph turns
// report (`AgentConfig.llm.model`), so one worker's spend lands in
// one `model` bucket whichever path ran it. A provider often
// reports a dated id (`gpt-4o-mini-2024-07-18`) that would split
// the bucket and miss a price-table entry; it is used only when
// nothing is configured.
let configured = self.inner.model();
let model = if configured.trim().is_empty() {
usage.model.as_str()
} else {
configured
};
// `emit` is fire-and-forget by contract; an error is still only
// ever a warning — billing never fails a deep worker's step.
if let Err(error) = self
.meter
.emit(
&self.tenant,
usage.input_tokens,
usage.output_tokens,
&self.agent_id,
model,
)
.await
{
tracing::warn!(%error, agent_id = %self.agent_id, "deep-worker usage not recorded");
}
}
Ok(response)
}
async fn chat_stream(&self, req: ChatRequest) -> Result<ChatStream, LlmError> {
self.inner.chat_stream(req).await
}
}
/// The agent id a deep worker's usage is attributed to: the node's
/// `input.agent_id` (what greentic-dw-authoring stamps), else the dispatch
/// target, else the operation. Descriptive only — the unit, not the agent,
/// is what `project_id` groups by.
pub(crate) fn deep_worker_agent_id(input: &Value, target: &str, operation: &str) -> String {
let stamped = input
.get("agent_id")
.and_then(Value::as_str)
.map(str::trim)
.filter(|id| !id.is_empty());
stamped
.or_else(|| Some(target.trim()).filter(|t| !t.is_empty()))
.unwrap_or_else(|| operation.trim())
.to_string()
}
#[cfg(test)]
#[path = "metered_llm_tests.rs"]
mod tests;