|
| 1 | +//! ARCP v1.1 §9.6 — `cost.budget` capability + `BUDGET_EXHAUSTED`. |
| 2 | +//! |
| 3 | +//! Hosts a `web-research` agent that charges $0.30 per iteration. The |
| 4 | +//! client submits with a `cost.budget: ["USD:1.00"]` lease, so the |
| 5 | +//! fourth iteration's pre-call charge fails with `BUDGET_EXHAUSTED` |
| 6 | +//! and the runtime emits a terminal `job.failed`. Along the way the |
| 7 | +//! runtime emits `cost.search` (the agent's cost report) and |
| 8 | +//! `cost.budget.remaining` (the running counter) metric events. |
| 9 | +//! |
| 10 | +//! Run with: |
| 11 | +//! `cargo run --example cost_budget` |
| 12 | +
|
| 13 | +#![allow(clippy::similar_names, clippy::expect_used, clippy::print_stdout)] |
| 14 | + |
| 15 | +use std::sync::Arc; |
| 16 | +use std::time::Duration; |
| 17 | + |
| 18 | +use arcp::auth::BearerAuthenticator; |
| 19 | +use arcp::envelope::Envelope; |
| 20 | +use arcp::error::ARCPError; |
| 21 | +use arcp::messages::{ |
| 22 | + AuthScheme, Capabilities, ClientIdentity, CostBudget, CostBudgetAmount, Credentials, |
| 23 | + MessageType, SessionOpenPayload, ToolInvokePayload, |
| 24 | +}; |
| 25 | +use arcp::runtime::context::ToolContext; |
| 26 | +use arcp::runtime::tools::{ToolHandler, ToolRegistryBuilder}; |
| 27 | +use arcp::runtime::ARCPRuntime; |
| 28 | +use arcp::transport::{paired, Transport}; |
| 29 | +use async_trait::async_trait; |
| 30 | + |
| 31 | +struct WebResearchTool; |
| 32 | + |
| 33 | +#[async_trait] |
| 34 | +impl ToolHandler for WebResearchTool { |
| 35 | + fn name(&self) -> &'static str { |
| 36 | + "web-research" |
| 37 | + } |
| 38 | + |
| 39 | + async fn invoke( |
| 40 | + &self, |
| 41 | + arguments: serde_json::Value, |
| 42 | + ctx: ToolContext, |
| 43 | + ) -> Result<serde_json::Value, ARCPError> { |
| 44 | + let iterations = arguments |
| 45 | + .get("iterations") |
| 46 | + .and_then(serde_json::Value::as_u64) |
| 47 | + .unwrap_or(8); |
| 48 | + let per = arguments |
| 49 | + .get("perCallUSD") |
| 50 | + .and_then(serde_json::Value::as_f64) |
| 51 | + .unwrap_or(0.3); |
| 52 | + for i in 1..=iterations { |
| 53 | + println!( |
| 54 | + "[agent] iteration {i}: charging {per:.2} USD (remaining={})", |
| 55 | + ctx.budget().remaining("USD").unwrap_or(f64::INFINITY) |
| 56 | + ); |
| 57 | + ctx.charge("cost.search", per, "USD").await?; |
| 58 | + } |
| 59 | + Ok(serde_json::json!({"iterations": iterations})) |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +#[tokio::main] |
| 64 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 65 | + let runtime = ARCPRuntime::builder() |
| 66 | + .with_authenticator(Box::new( |
| 67 | + BearerAuthenticator::new().with_token("demo-token", "demo"), |
| 68 | + )) |
| 69 | + .with_tools( |
| 70 | + ToolRegistryBuilder::new() |
| 71 | + .with(Arc::new(WebResearchTool)) |
| 72 | + .build(), |
| 73 | + ) |
| 74 | + .build() |
| 75 | + .await?; |
| 76 | + |
| 77 | + let (server_t, client_t) = paired(); |
| 78 | + let _h = runtime.serve_connection(server_t); |
| 79 | + |
| 80 | + let mut open = Envelope::new(MessageType::SessionOpen(SessionOpenPayload { |
| 81 | + auth: Credentials { |
| 82 | + scheme: AuthScheme::Bearer, |
| 83 | + token: Some("demo-token".into()), |
| 84 | + }, |
| 85 | + client: ClientIdentity { |
| 86 | + kind: "cost-budget-demo".into(), |
| 87 | + version: env!("CARGO_PKG_VERSION").into(), |
| 88 | + fingerprint: None, |
| 89 | + principal: None, |
| 90 | + }, |
| 91 | + capabilities: Capabilities::default(), |
| 92 | + })); |
| 93 | + open.id = arcp::ids::MessageId::new(); |
| 94 | + client_t.send(open).await?; |
| 95 | + let accepted = client_t.recv().await?.ok_or("no session.accepted")?; |
| 96 | + let MessageType::SessionAccepted(payload) = accepted.payload else { |
| 97 | + return Err("expected session.accepted".into()); |
| 98 | + }; |
| 99 | + let session_id = payload.session_id; |
| 100 | + println!("connected; session_id={session_id}"); |
| 101 | + |
| 102 | + let mut invoke = Envelope::new(MessageType::ToolInvoke(ToolInvokePayload { |
| 103 | + tool: "web-research".into(), |
| 104 | + arguments: serde_json::json!({"iterations": 8, "perCallUSD": 0.3}), |
| 105 | + cost_budget: Some(CostBudget { |
| 106 | + amounts: vec![CostBudgetAmount { |
| 107 | + currency: "USD".into(), |
| 108 | + amount: 1.0, |
| 109 | + }], |
| 110 | + }), |
| 111 | + })); |
| 112 | + invoke.session_id = Some(session_id); |
| 113 | + client_t.send(invoke).await?; |
| 114 | + |
| 115 | + let deadline = std::time::Instant::now() + Duration::from_secs(5); |
| 116 | + while std::time::Instant::now() < deadline { |
| 117 | + let env = tokio::time::timeout(Duration::from_millis(500), client_t.recv()) |
| 118 | + .await?? |
| 119 | + .ok_or("transport closed")?; |
| 120 | + match env.payload { |
| 121 | + MessageType::JobAccepted(p) => println!("job_id={}", p.job_id), |
| 122 | + MessageType::Metric(m) => { |
| 123 | + println!("metric[{}]={:.2} {}", m.name, m.value, m.unit); |
| 124 | + } |
| 125 | + MessageType::JobFailed(p) => { |
| 126 | + println!( |
| 127 | + "job.failed code={} retryable={:?} message={:?}", |
| 128 | + p.code, p.retryable, p.message |
| 129 | + ); |
| 130 | + break; |
| 131 | + } |
| 132 | + MessageType::JobCompleted(p) => { |
| 133 | + println!("job.completed value={:?}", p.value); |
| 134 | + break; |
| 135 | + } |
| 136 | + _ => {} |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + Ok(()) |
| 141 | +} |
0 commit comments