pub struct ModelCallScope { /* private fields */ }Expand description
Core traits and types.
Always available regardless of feature flags. Includes:
Agent- The fundamental trait for all agentsTool/Toolset- For extending agents with capabilitiesSession/State- For managing conversation contextEvent- For streaming agent responsesAdkError/Result- Unified error handling The budget and spend ledger that model calls made on behalf of a run count against.
Built from a run’s RunConfig with for_run, or assembled
explicitly for calls made outside any run. An empty scope meters nothing.
§Example
use std::sync::Arc;
use adk_core::{BudgetTracker, InMemorySpendLedger, ModelCallScope, RunBudget};
let scope = ModelCallScope::new()
.with_budget(Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(1.0))))
.with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme")
.with_agent("mcp-sampling");
assert_eq!(scope.spend_key("claude-haiku-4-5").unwrap().agent.as_deref(), Some("mcp-sampling"));Implementations§
Source§impl ModelCallScope
impl ModelCallScope
Sourcepub fn new() -> ModelCallScope
pub fn new() -> ModelCallScope
Creates a scope that meters nothing.
Sourcepub fn for_run(
config: &RunConfig,
org: &str,
agent_name: &str,
) -> ModelCallScope
pub fn for_run( config: &RunConfig, org: &str, agent_name: &str, ) -> ModelCallScope
Creates the scope for calls made on behalf of a run.
Uses the run’s budget_tracker, its
spend_ledger,
llm_spend_estimate and kill switches
(governance). Spend is attributed to
org (the runner passes its app name) and the AgentId the
agent named agent_name acts as
(ActingConfig::principal_for: the
configured principal, or urn:adk:agent:{org}/{agent_name}).
Sourcepub fn with_governance(self, control: GovernanceControl) -> ModelCallScope
pub fn with_governance(self, control: GovernanceControl) -> ModelCallScope
Refuses every call while control is frozen.
The scope checks its kill switches before each call it meters, so a call that makes several provider calls, such as a fallback chain, stops at the next one once a switch is frozen.
§Example
use adk_core::{GOVERNANCE_FROZEN_CODE, GovernanceControl, ModelCallScope};
let control = GovernanceControl::new();
let scope = ModelCallScope::new().with_governance(control.clone());
assert!(scope.check_governance().is_ok());
control.freeze("incident");
assert_eq!(scope.check_governance().unwrap_err().code, GOVERNANCE_FROZEN_CODE);Sourcepub fn check_governance(&self) -> Result<(), AdkError>
pub fn check_governance(&self) -> Result<(), AdkError>
Returns the error of the first frozen kill switch, if any.
§Errors
Returns the frozen control’s governance.frozen error
(GovernanceControl::check).
Sourcepub fn with_budget(self, tracker: Arc<BudgetTracker>) -> ModelCallScope
pub fn with_budget(self, tracker: Arc<BudgetTracker>) -> ModelCallScope
Counts calls against tracker.
Sourcepub fn with_spend_ledger(
self,
ledger: Arc<dyn SpendLedger>,
org: impl Into<String>,
) -> ModelCallScope
pub fn with_spend_ledger( self, ledger: Arc<dyn SpendLedger>, org: impl Into<String>, ) -> ModelCallScope
Reserves and commits call spend in ledger, attributed to org.
Sourcepub fn with_agent(self, agent: impl Into<String>) -> ModelCallScope
pub fn with_agent(self, agent: impl Into<String>) -> ModelCallScope
Attributes spend to agent. Has no effect without a spend ledger.
Sourcepub fn with_spend_estimate(self, estimate: LlmSpendEstimate) -> ModelCallScope
pub fn with_spend_estimate(self, estimate: LlmSpendEstimate) -> ModelCallScope
Sets the hold reserved before each call. Has no effect without a spend ledger.
Sourcepub fn budget(&self) -> Option<&Arc<BudgetTracker>>
pub fn budget(&self) -> Option<&Arc<BudgetTracker>>
The budget tracker calls count against.
Sourcepub fn is_unmetered(&self) -> bool
pub fn is_unmetered(&self) -> bool
Returns true when the scope has neither a budget nor a spend ledger.
Sourcepub fn spend_key(&self, model: &str) -> Option<SpendKey>
pub fn spend_key(&self, model: &str) -> Option<SpendKey>
The key a call to model reserves under, when the scope has a spend ledger.
Sourcepub fn vendor_spend_key(&self, vendor: &str) -> Option<SpendKey>
pub fn vendor_spend_key(&self, vendor: &str) -> Option<SpendKey>
The key a call billed by vendor reserves under, when the scope has a spend ledger.
§Example
use std::sync::Arc;
use adk_core::{InMemorySpendLedger, ModelCallScope};
let scope = ModelCallScope::new().with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme");
assert_eq!(scope.vendor_spend_key("muse").unwrap().vendor.as_deref(), Some("muse"));
assert!(ModelCallScope::new().vendor_spend_key("muse").is_none());Sourcepub fn for_tool(ctx: &dyn ToolContext) -> Option<ModelCallScope>
pub fn for_tool(ctx: &dyn ToolContext) -> Option<ModelCallScope>
The scope of the run a tool call belongs to, when the tool’s runtime exposes the
run’s RunConfig (ToolContext::run_config).
Spend is attributed to the context’s app and the agent making the call, as
for_run attributes it.
§Example
let scope = adk_core::ModelCallScope::for_tool(ctx.as_ref());Sourcepub fn within_tool<F>(
ctx: &dyn ToolContext,
future: F,
) -> impl Future<Output = <F as Future>::Output> + use<F>where
F: Future,
pub fn within_tool<F>(
ctx: &dyn ToolContext,
future: F,
) -> impl Future<Output = <F as Future>::Output> + use<F>where
F: Future,
Runs a tool call with the scope of the run it belongs to current
(for_tool), so the media and model calls the tool makes through
meter_usage and generate_metered count against the run. Without a run
configuration on ctx, future runs as is.
Agents call this around every tool execution.
§Example
let result = ModelCallScope::within_tool(ctx.as_ref(), tool.execute(ctx.clone(), args)).await;Sourcepub fn same_as(&self, other: &ModelCallScope) -> bool
pub fn same_as(&self, other: &ModelCallScope) -> bool
Returns true when both scopes count against the same budget and ledger.
Sourcepub fn current() -> Option<ModelCallScope>
pub fn current() -> Option<ModelCallScope>
The scope made current by an enclosing within, if any.
Sourcepub async fn within<F>(self, future: F) -> <F as Future>::Outputwhere
F: Future,
pub async fn within<F>(self, future: F) -> <F as Future>::Outputwhere
F: Future,
Runs future with this scope current, so generate_metered and MeteredLlm
inside it meter against this scope.
The scope does not follow work spawned onto other tasks.
Sourcepub async fn generate(
&self,
model: &dyn Llm,
request: LlmRequest,
stream: bool,
) -> Result<Pin<Box<dyn Stream<Item = Result<LlmResponse, AdkError>> + Send>>, AdkError>
pub async fn generate( &self, model: &dyn Llm, request: LlmRequest, stream: bool, ) -> Result<Pin<Box<dyn Stream<Item = Result<LlmResponse, AdkError>> + Send>>, AdkError>
Calls model under this scope.
Refuses the call while one of the scope’s kill switches is frozen
(with_governance), then hands it to
Llm::generate_content_metered, which meters it as one model call
(generate_one_call) unless the model sends the request
to several providers and meters each of their calls itself.
§Errors
Returns the frozen control’s governance.frozen error, the ledger’s error when the
reservation is refused, a ResourceExhausted
error when the budget does not allow another call, or the model’s own error.
Sourcepub async fn generate_one_call<M>(
&self,
model: &M,
request: LlmRequest,
stream: bool,
) -> Result<Pin<Box<dyn Stream<Item = Result<LlmResponse, AdkError>> + Send>>, AdkError>
pub async fn generate_one_call<M>( &self, model: &M, request: LlmRequest, stream: bool, ) -> Result<Pin<Box<dyn Stream<Item = Result<LlmResponse, AdkError>> + Send>>, AdkError>
Meters one call to model as one model call.
Reserves the call’s upper-bound cost (Llm::max_cost_micro_usd, or
UNBOUNDED_HOLD_MICRO_USD when there is none), then the budget’s model call,
before the request is sent; a refusal from either stops the call. The returned
stream counts the call’s usage once and commits its cost at the turn-complete
response, or when the stream ends or is dropped. The spend is reserved under the
vendor of request.model (vendor_for_model) and committed under the provider
the response reports.
This is what Llm::generate_content_metered does unless a model overrides it.
§Errors
Returns the ledger’s error when the reservation is refused, a
ResourceExhausted error when the
budget does not allow another call, or the model’s own error.
Source§impl ModelCallScope
impl ModelCallScope
Sourcepub async fn begin_usage(&self, call: &UsageCall) -> Result<UsageHold, AdkError>
pub async fn begin_usage(&self, call: &UsageCall) -> Result<UsageHold, AdkError>
Checks the budget and reserves the spend for one call billed in units.
Reserves UsageCall::max_cost_micro_usd in the spend ledger — or
UNBOUNDED_HOLD_MICRO_USD when the call has no known price, which every covering
cap refuses — then checks the run budget, which refuses a call with no known price
under a cost cap, and holds UsageCall::units against its per-unit caps. Settle
the returned hold with UsageHold::commit once the call completes; a hold released
or dropped unsettled records nothing and returns the units it held.
§Errors
Returns the frozen control’s governance.frozen error while a kill switch is frozen,
the ledger’s error when the reservation is refused, or a
ResourceExhausted error when the
budget refuses the call — budget.units, naming the unit and its cap, when a
declared unit does not fit. Nothing has been sent when any of them refuses.
Sourcepub async fn meter<T, F>(
&self,
call: UsageCall,
future: F,
) -> Result<T, AdkError>
pub async fn meter<T, F>( &self, call: UsageCall, future: F, ) -> Result<T, AdkError>
Runs one call billed in units under this scope.
future is the call: it returns its value with the MeteredUsage it incurred.
The budget is checked and the spend reserved before future is polled
(begin_usage), the usage is committed when it succeeds, and
the hold is released when it fails. An unmetered scope runs future as is.
§Errors
A refusal from begin_usage, in which case future never
runs, or the error future returns.
§Example
use std::sync::Arc;
use adk_core::{
InMemorySpendLedger, MeteredUsage, ModelCallScope, SpendKey, SpendLedger, SpendLimits,
SpendPeriod, UsageCall, UsageUnit, UsageVector,
};
let limits = SpendLimits::new().limit(SpendKey::org("acme").per(SpendPeriod::Day), 1_000_000);
let ledger = Arc::new(InMemorySpendLedger::new(limits));
let scope = ModelCallScope::new().with_spend_ledger(ledger.clone(), "acme");
let call = UsageCall::new("muse", "muse-image-1.0").with_max_cost_micro_usd(10_000);
let image = scope
.meter(call, async {
let usage = MeteredUsage::new(UsageVector::new().with(UsageUnit::Images, 1))
.with_cost_micro_usd(10_000);
Ok(("image bytes", usage))
})
.await?;
assert_eq!(image, "image bytes");
assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 10_000);Trait Implementations§
Source§impl Clone for ModelCallScope
impl Clone for ModelCallScope
Source§fn clone(&self) -> ModelCallScope
fn clone(&self) -> ModelCallScope
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for ModelCallScope
impl Debug for ModelCallScope
Source§impl Default for ModelCallScope
impl Default for ModelCallScope
Source§fn default() -> ModelCallScope
fn default() -> ModelCallScope
Auto Trait Implementations§
impl !RefUnwindSafe for ModelCallScope
impl !UnwindSafe for ModelCallScope
impl Forget for ModelCallScope
impl Freeze for ModelCallScopewhere
*const ArcInner<BudgetTracker> is !null: Freeze,
PhantomData<ArcInner<BudgetTracker>>: Freeze,
*const ArcInner<dyn SpendLedger> is !null: Freeze,
PhantomData<ArcInner<dyn SpendLedger>>: Freeze,
*const u8 is !null: Freeze,
PhantomData<u8>: Freeze,
PhantomData<GovernanceControl>: Freeze,
impl Move for ModelCallScope
impl Send for ModelCallScopewhere
Arc<BudgetTracker>: Send,
Arc<dyn SpendLedger>: Send,
RawVecInner: Send,
Arc<ControlState>: Send,
impl Sync for ModelCallScopewhere
Arc<BudgetTracker>: Sync,
Arc<dyn SpendLedger>: Sync,
RawVecInner: Sync,
Arc<ControlState>: Sync,
impl Unpin for ModelCallScope
impl UnsafeUnpin for ModelCallScopewhere
*const ArcInner<BudgetTracker> is !null: UnsafeUnpin,
PhantomData<ArcInner<BudgetTracker>>: UnsafeUnpin,
*const ArcInner<dyn SpendLedger> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn SpendLedger>>: UnsafeUnpin,
*const u8 is !null: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
PhantomData<GovernanceControl>: UnsafeUnpin,
Blanket Implementations§
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
Source§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreimpl<T> MaybeSend for Twhere
T: Send,
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.