pub struct Context { /* private fields */ }Expand description
Manages the conversation state sent to an LLM provider.
A Context bundles together three things:
- Messages – the conversation history as a
Vec<ChatMessage> - Tools – the tools available to the model as a
Vec<ToolDefinition> - Configuration – optional
ReasoningEffortand prompt cache key
Pass a Context to StreamingModelProvider::stream_response to generate a response.
§Construction
use llm::{Context, ChatMessage, ContentBlock, ToolDefinition, types::IsoString};
let context = Context::new(
vec![
ChatMessage::System {
content: "You are a helpful assistant.".into(),
timestamp: IsoString::now(),
},
ChatMessage::User {
content: vec![ContentBlock::text("What is Rust?")],
timestamp: IsoString::now(),
},
],
vec![], // no tools
);§Managing messages
add_message– Append a single message.push_assistant_turn– Append an assistant response together with its tool call results in one step.clear_conversation– Remove all non-system messages.
§Conversation compaction
Long conversations can be compacted to stay within context limits:
messages_for_summary– Get non-system messages to feed to a summarizer.with_compacted_summary– Create a newContextwhere conversation messages are replaced by aChatMessage::Summary. The system prompt, tools, and configuration are preserved.
§Token estimation
estimated_token_count provides a rough pre-flight estimate using a ~4 bytes/token heuristic. This is intentionally approximate – use it to detect obvious overflow before calling the provider, not for precise accounting.
§Encrypted reasoning
filter_encrypted_reasoning creates a copy where encrypted reasoning content is kept only for messages from a matching model. This is necessary because encrypted reasoning tokens are model-specific and cannot be replayed to a different model.
Implementations§
Source§impl Context
impl Context
pub fn new(messages: Vec<ChatMessage>, tools: Vec<ToolDefinition>) -> Self
pub fn prompt_cache_key(&self) -> Option<&str>
pub fn set_prompt_cache_key(&mut self, key: Option<String>)
pub fn reasoning_effort(&self) -> Option<ReasoningEffort>
pub fn set_reasoning_effort(&mut self, effort: Option<ReasoningEffort>)
pub fn add_message(&mut self, message: ChatMessage)
pub fn set_tools(&mut self, tools: Vec<ToolDefinition>)
pub fn messages(&self) -> &Vec<ChatMessage>
pub fn tools(&self) -> &Vec<ToolDefinition>
Sourcepub fn message_count(&self) -> usize
pub fn message_count(&self) -> usize
Returns the number of messages in the context
Sourcepub fn estimated_token_count(&self) -> u32
pub fn estimated_token_count(&self) -> u32
Estimate total token count using the ~4 bytes/token heuristic. Includes messages and tool definitions. Used for pre-flight overflow detection.
Sourcepub fn push_assistant_turn(
&mut self,
content: &str,
reasoning: AssistantReasoning,
completed_tools: Vec<Result<ToolCallResult, ToolCallError>>,
)
pub fn push_assistant_turn( &mut self, content: &str, reasoning: AssistantReasoning, completed_tools: Vec<Result<ToolCallResult, ToolCallError>>, )
Build an assistant turn and its tool call results and append them to messages.
Sourcepub fn filter_encrypted_reasoning(&self, model: &LlmModel) -> Self
pub fn filter_encrypted_reasoning(&self, model: &LlmModel) -> Self
Return a copy with encrypted reasoning filtered for the given model. Encrypted content is kept only when its source model matches.
Sourcepub fn clear_conversation(&mut self)
pub fn clear_conversation(&mut self)
Clear all non-system messages, retaining only system prompts.
Sourcepub fn messages_for_summary(&self) -> Vec<&ChatMessage>
pub fn messages_for_summary(&self) -> Vec<&ChatMessage>
Get all non-system messages for summarization
Sourcepub fn with_compacted_summary(&self, summary: &str) -> Context
pub fn with_compacted_summary(&self, summary: &str) -> Context
Create a new context with all messages replaced by a summary. Preserves the system prompt and tools.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Context
impl<'de> Deserialize<'de> for Context
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Auto Trait Implementations§
impl Freeze for Context
impl RefUnwindSafe for Context
impl Send for Context
impl Sync for Context
impl Unpin for Context
impl UnsafeUnpin for Context
impl UnwindSafe for Context
Blanket Implementations§
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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 more