Skip to main content

RouterLLM

Struct RouterLLM 

Source
pub struct RouterLLM { /* private fields */ }
Expand description

A chat model pool with routing and fallback.

See the module docs for design rationale.

Implementations§

Source§

impl RouterLLM

Source

pub fn new(strategy: RoutingStrategy) -> Self

Create an empty router with the given strategy. Add models via the with_* builder methods.

Source

pub fn with_budget(self, budget: Arc<RouterBudget>) -> Self

Attaches a shared RouterBudget. Every subsequent call projects its prompt spend against the remaining budget, skips paid slots once the breaker is tripped (free slots stay reachable as fallback), and records the model-reported token usage after a successful call.

Source

pub fn with_registry(self, registry: Arc<ModelRegistry>) -> Self

Attaches a model registry. Keyed slots (RouterLLM::with_model_as) then take their RoutingStrategy::LowestCost weight from the registry’s blended per-1K price. An explicit cost from RouterLLM::with_cost always wins; a key the registry cannot resolve sorts last (treated as infinitely expensive).

Source

pub fn with_name(self, name: impl Into<String>) -> Self

Set a human-readable name returned by model_name.

Source

pub fn with_model<M>(self, model: M) -> Self
where M: BaseChatModel + 'static, M::Error: Error + Send + Sync + 'static,

Register a model.

Source

pub fn with_cost<M>(self, model: M, cost: f64) -> Self
where M: BaseChatModel + 'static, M::Error: Error + Send + Sync + 'static,

Register a model with a relative cost used by RoutingStrategy::LowestCost.

Source

pub fn with_model_as<M, K>(self, model: M, registry_key: K) -> Self
where M: BaseChatModel + 'static, M::Error: Error + Send + Sync + 'static, K: Into<String>,

Register a model keyed as "<provider>/<model-id>" in the attached ModelRegistry (see RouterLLM::with_registry). Under RoutingStrategy::LowestCost the slot is weighted by the registry’s blended per-1K price; other strategies ignore the key.

Source

pub fn with_priced_model<M>(self, model: M, price: ModelPrice) -> Self
where M: BaseChatModel + 'static, M::Error: Error + Send + Sync + 'static,

Register a model with an explicit per-token ModelPrice. The price both participates in RoutingStrategy::LowestCost (blended) and prices projected/actual spend for an attached RouterBudget.

Source

pub fn with_model_rate_limited<M>(self, model: M, limit: ModelRateLimit) -> Self
where M: BaseChatModel + 'static, M::Error: Error + Send + Sync + 'static,

Register a model behind a per-model ModelRateLimit (B13). Saturated slots queue callers FIFO; when the queue is full or the configured wait timeout elapses, the call skips to the next candidate model.

Source

pub fn with_last_price(self, price: ModelPrice) -> Self

Attaches a ModelPrice to the most recently registered slot.

Use to combine registration styles, e.g. a keyed slot whose registry entry lacks pricing. A no-op with a warning when no slot exists.

Source

pub fn with_last_rate_limit(self, limit: ModelRateLimit) -> Self

Attaches a ModelRateLimit to the most recently registered slot.

A no-op with a warning when no slot exists.

Source

pub fn with_fallbacks<M>(primary: M, fallbacks: Vec<M>) -> Self
where M: BaseChatModel + 'static, M::Error: Error + Send + Sync + 'static,

Convenience constructor for primary-first fallback over models of the same type. The primary is tried first; each fallback is tried in order until one succeeds.

Source

pub fn len(&self) -> usize

Number of registered models.

Source

pub fn is_empty(&self) -> bool

Whether no models are registered.

Trait Implementations§

Source§

impl BaseChatModel for RouterLLM

Source§

fn chat<'life0, 'async_trait>( &'life0 self, messages: Vec<Message>, config: Option<RunnableConfig>, ) -> Pin<Box<dyn Future<Output = Result<LLMResult, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Chat with the model. Read more
Source§

fn stream_chat<'life0, 'async_trait>( &'life0 self, messages: Vec<Message>, config: Option<RunnableConfig>, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<StreamChunk, Self::Error>> + Send>>, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Stream chat with the model. Read more
Source§

fn chat_with_system<'life0, 'async_trait>( &'life0 self, system: String, messages: Vec<Message>, ) -> Pin<Box<dyn Future<Output = Result<LLMResult, Self::Error>> + Send + 'async_trait>>
where Self: Sync + 'async_trait, 'life0: 'async_trait,

Chat with system prompt. Read more
Source§

fn bind_tools( &self, _tools: Vec<ToolDefinition>, ) -> Option<Box<dyn BaseChatModel<Error = Self::Error> + Send + Sync>>

Bind tool definitions for function calling. Read more
Source§

impl BaseLanguageModel<Vec<Message>, LLMResult> for RouterLLM

Source§

fn model_name(&self) -> &str

Returns the model name.
Source§

fn get_num_tokens(&self, text: &str) -> usize

Calculates token count for text. Read more
Source§

fn with_temperature(self, _temp: f32) -> Self

Sets the temperature parameter.
Source§

fn with_max_tokens(self, _max: usize) -> Self

Sets the max tokens limit.
Source§

fn temperature(&self) -> Option<f32>

Returns the temperature parameter.
Source§

fn max_tokens(&self) -> Option<usize>

Returns the max tokens limit.
Source§

impl Runnable<Vec<Message>, LLMResult> for RouterLLM

Source§

type Error = RouterError

Error type.
Source§

fn invoke<'life0, 'async_trait>( &'life0 self, input: Vec<Message>, config: Option<RunnableConfig>, ) -> Pin<Box<dyn Future<Output = Result<LLMResult, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Transforms single input to output. Read more
Source§

fn batch<'life0, 'async_trait>( &'life0 self, inputs: Vec<Input>, config: Option<RunnableConfig>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Output>, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Batch processing - transforms multiple inputs to outputs. Read more
Source§

fn batch_as_completed<'life0, 'async_trait>( &'life0 self, inputs: Vec<Input>, config: Option<RunnableConfig>, ) -> Pin<Box<dyn Future<Output = Result<Vec<(usize, Output)>, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Batch processing that returns results in completion order. Read more
Source§

fn stream<'life0, 'async_trait>( &'life0 self, input: Input, config: Option<RunnableConfig>, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Output, Self::Error>> + Send>>, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Streaming output - for real-time responses (LLM, etc). Read more
Source§

fn transform<'life0, 'async_trait>( &'life0 self, input: Pin<Box<dyn Stream<Item = Result<Input, Self::Error>> + Send>>, config: Option<RunnableConfig>, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<Output, Self::Error>> + Send + '_>>, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Stream-to-stream transformation - the core of LCEL streaming. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<M> StreamingStructuredOutputExt for M
where M: BaseChatModel,

Source§

fn stream_structured_output<'life0, 'life1, 'async_trait, T>( &'life0 self, schema: Value, prompt: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<T, StructuredOutputError>> + Send>>, StructuredOutputError>> + Send + 'async_trait>>
where T: DeserializeOwned + Serialize + Clone + PartialEq + Unpin + Send + Sync + 'static + 'async_trait, Self: Sync + 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Stream structured output from a chat model. Read more
Source§

impl<M> StructuredOutputExt for M
where M: BaseChatModel,

Source§

fn with_structured_output<'life0, 'life1, 'async_trait, T>( &'life0 self, schema: Value, prompt: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<T, StructuredOutputError>> + Send + 'async_trait>>
where T: 'async_trait + DeserializeOwned + Serialize + Send + Sync + 'static, Self: Sync + 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Call the LLM with a JSON schema and prompt, returning a parsed result of type T. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more