pub trait Model:
Send
+ Sync
+ 'static {
// Required methods
fn stream(
&self,
request: ModelRequest,
) -> BoxStream<'static, Result<ModelStreamEvent>>;
fn get_config(&self) -> BaseModelConfig;
fn update_config(&self, config: BaseModelConfig) -> Result<()>;
// Provided methods
fn stream_aggregated(
&self,
request: ModelRequest,
) -> BoxStream<'static, Result<AggregatedEvent>> { ... }
fn model_id(&self) -> Option<String> { ... }
fn model_info(&self) -> ModelInfo { ... }
fn stateful(&self) -> bool { ... }
fn count_tokens<'life0, 'life1, 'async_trait>(
&'life0 self,
messages: &'life1 [Message],
options: CountTokensOptions,
) -> Pin<Box<dyn Future<Output = Result<u64>> + Send + 'async_trait>>
where Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait { ... }
fn summarize<'life0, 'async_trait>(
&'life0 self,
messages: Vec<Message>,
options: SummarizeOptions,
) -> Pin<Box<dyn Future<Output = Result<SummarizeResult>> + Send + 'async_trait>>
where Self: 'async_trait,
'life0: 'async_trait { ... }
fn estimate_utilization(&self, input_tokens: u64) -> f64 { ... }
}Expand description
A model provider (Model).
Implement stream, get_config and
update_config; everything else has a default. Agents hold models as
Arc<dyn Model>, so a provider keeps its configuration behind interior locking. A provider that
overrides a default and still needs it calls the free function behind it:
base_model_info with ModelInfo::merge for
model_info, estimate_tokens for count_tokens
and summarize_client_side for
summarize. Use crate::async_trait on the impl when overriding
the async methods.
use std::sync::RwLock;
use futures::StreamExt;
use strands::models::streaming::{
ModelContentBlockDeltaEvent, ModelContentBlockStartEvent, ModelContentBlockStopEvent,
ModelMessageStartEvent, ModelMessageStopEvent, ModelStreamEvent, TextDelta,
};
use strands::models::{AggregatedEvent, BaseModelConfig, BoxStream, Model, ModelRequest};
use strands::{Message, Role, StopReason};
/// Replies with the text of the last message.
#[derive(Default)]
struct EchoModel {
config: RwLock<BaseModelConfig>,
}
#[strands::async_trait]
impl Model for EchoModel {
fn stream(&self, request: ModelRequest) -> BoxStream<'static, strands::Result<ModelStreamEvent>> {
let text = request.messages.last().map(Message::text).unwrap_or_default();
let events: Vec<ModelStreamEvent> = vec![
ModelMessageStartEvent::new(Role::Assistant).into(),
ModelContentBlockStartEvent::new().into(),
ModelContentBlockDeltaEvent::new(TextDelta::new(text)).into(),
ModelContentBlockStopEvent::new().into(),
ModelMessageStopEvent::new(StopReason::EndTurn).into(),
];
Box::pin(futures::stream::iter(events.into_iter().map(Ok)))
}
fn get_config(&self) -> BaseModelConfig {
self.config.read().unwrap().clone()
}
fn update_config(&self, config: BaseModelConfig) -> strands::Result<()> {
self.config.write().unwrap().merge(config);
Ok(())
}
}
let model = EchoModel::default();
let request = ModelRequest::builder().messages(vec![Message::user("ping")]).build();
futures::executor::block_on(async {
let mut stream = model.stream_aggregated(request);
while let Some(item) = stream.next().await {
if let AggregatedEvent::Done(result) = item.unwrap() {
assert_eq!(result.message.text(), "ping");
}
}
});Required Methods§
Sourcefn stream(
&self,
request: ModelRequest,
) -> BoxStream<'static, Result<ModelStreamEvent>>
fn stream( &self, request: ModelRequest, ) -> BoxStream<'static, Result<ModelStreamEvent>>
Streams the model’s response to request as raw events.
The stream is 'static so the call can be spawned: clone what the stream needs (a config
snapshot, a client handle) out of &self.
§Errors
Report failures as stream items, translating provider errors to the SDK’s model errors so
the agent can react: ModelThrottledError and
ModelNetworkError are retried by the default retry strategy,
and ContextWindowOverflowError makes the
conversation manager reduce the context. Keep the provider’s error as the source.
Sourcefn get_config(&self) -> BaseModelConfig
fn get_config(&self) -> BaseModelConfig
The current configuration.
Sourcefn update_config(&self, config: BaseModelConfig) -> Result<()>
fn update_config(&self, config: BaseModelConfig) -> Result<()>
Merges config into the configuration: every field it sets replaces the current value
(BaseModelConfig::merge).
§Errors
The provider rejects the update (for example a model id its client cannot be rebuilt for); the configuration is left unchanged.
Provided Methods§
Sourcefn stream_aggregated(
&self,
request: ModelRequest,
) -> BoxStream<'static, Result<AggregatedEvent>>
fn stream_aggregated( &self, request: ModelRequest, ) -> BoxStream<'static, Result<AggregatedEvent>>
Streams the response with content blocks and the final message assembled.
Yields every raw event, then each completed ContentBlock, and ends with
AggregatedEvent::Done. Errors that are not model errors are wrapped in ModelError;
model errors such as ContextWindowOverflowError,
ModelThrottledError and MaxTokensError (which carries the
partial message) pass through.
Sourcefn model_info(&self) -> ModelInfo
fn model_info(&self) -> ModelInfo
Everything the SDK knows about the configured model, resolved on each call.
Layers, later ones winning: the shared model info for the model id, temporary_messages
off (a provider that supports them turns them back on), deferred_tool_loading as Stubs
unless the shared info says Unsupported (a provider that defers natively says Native),
the context_window_limit config value, and the model_info config override
(base_model_info). A provider that knows
better overrides this method, layering its facts over base_model_info and the user’s
override on top with ModelInfo::merge; it must not call
stateful, which reads this method.
Sourcefn stateful(&self) -> bool
fn stateful(&self) -> bool
Whether the model keeps conversation state server-side (stateful), from
model_info().capabilities.stateful; false when unknown.
When true, the agent sends only the latest message and clears its local history after each
invocation.
Sourcefn count_tokens<'life0, 'life1, 'async_trait>(
&'life0 self,
messages: &'life1 [Message],
options: CountTokensOptions,
) -> Pin<Box<dyn Future<Output = Result<u64>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
fn count_tokens<'life0, 'life1, 'async_trait>(
&'life0 self,
messages: &'life1 [Message],
options: CountTokensOptions,
) -> Pin<Box<dyn Future<Output = Result<u64>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
Estimates the input tokens of a request before sending it.
The default is estimate_tokens, a character heuristic (text length / 4, JSON length / 2)
that counts only the latest user message’s injected blocks, the ones a model reads.
Providers with a native counting API override it and fall back to estimate_tokens on
failure.
Sourcefn summarize<'life0, 'async_trait>(
&'life0 self,
messages: Vec<Message>,
options: SummarizeOptions,
) -> Pin<Box<dyn Future<Output = Result<SummarizeResult>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
fn summarize<'life0, 'async_trait>(
&'life0 self,
messages: Vec<Message>,
options: SummarizeOptions,
) -> Pin<Box<dyn Future<Output = Result<SummarizeResult>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
Summarizes messages, a request as the caller would send it to stream
(summarize).
The default sends that request closed by an instruction not to act on it or call tools,
followed by instructions (or the default ones), so a caller replaying its own conversation
can share its prompt cache. The summary is the reply’s text, including a reply cut off at the
output limit or a stop sequence; a reply that ends for another reason (a tool call, a
cancellation, a guardrail) or holds no text gives an empty result. Every summary is a
SummaryBlock; the default leaves its provider unset. A provider whose model info reports
server_side_summary overrides this to summarize server-side and sets provider, falling
back to summarize_client_side.
Sourcefn estimate_utilization(&self, input_tokens: u64) -> f64
fn estimate_utilization(&self, input_tokens: u64) -> f64
The fraction of the context window that input_tokens fills; above 1.0 means overflow.
Uses model_info().limits.context_window, or the default limit with a one-time warning when
it is unknown.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".