The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(openhuman-core): add context window support for inference
Steven Enamakel873350f82d3e
diff --git a/crates/openhuman-core/src/inference/context_window.rs b/crates/openhuman-core/src/inference/context_window.rsnew file mode 100644index 0000000000..be9c0e5a2d--- /dev/null+++ b/crates/openhuman-core/src/inference/context_window.rs@@ -0,0 +1,285 @@+//! Resolving a turn's context window from the provider.+//!+//! The window drives pre-dispatch trimming and the compaction trigger, so a+//! wrong one is expensive both ways: too small and a 1M-token model compacts+//! at 128k; too large and the provider rejects the request. The order is:+//!+//! 1. **Config override**: a non-zero `context_window` on the matching+//! `config.model_registry` entry.+//! 2. **Provider-reported**: the provider's own model listing, discovered+//! through `tinyinference_llm::model::discover` (bounded, cached per+//! endpoint and model), lowered by any window the provider stated in a+//! context-overflow error on that endpoint (learned by the chat adapters).+//! 3. **Local runtime profile** for local providers (Ollama, LM Studio, ...).+//! 4. **Static guess**: the tier aliases, the cost catalog, and the generic+//! id-pattern table ([`super::model_context::static_context_window_for_model`]),+//! logged as a guess at `warn` once per model.+//!+//! The provider-sourced value is remembered per model, so the synchronous+//! [`super::model_context::context_window_for_model`] (usage meters, the+//! context breakdown) reports the same window the turn used.++use std::collections::{HashMap, HashSet};+use std::sync::{Mutex, OnceLock};++use tinyinference_llm::model::discover::{+ discover_model_limits_with, model_limits_cache, ModelLimitsCache, ModelListingFetcher,+};++use crate::config::Config;++/// Where a resolved window came from (stable labels for logs).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum WindowSource {+ /// `config.model_registry[].context_window`.+ ConfigOverride,+ /// The provider's listing (model-level or a pinned endpoint).+ ProviderReported,+ /// The window the provider stated in an overflow error.+ LearnedFromOverflow,+ /// The local runtime's profile default.+ LocalProfile,+ /// A static table: tier alias, cost catalog, or id pattern.+ StaticGuess,+ /// Nothing known.+ Unknown,+}++impl WindowSource {+ pub(crate) fn label(self) -> &'static str {+ match self {+ Self::ConfigOverride => "config_override",+ Self::ProviderReported => "provider_reported",+ Self::LearnedFromOverflow => "learned_from_overflow",+ Self::LocalProfile => "local_profile",+ Self::StaticGuess => "static_guess",+ Self::Unknown => "unknown",+ }+ }+}++/// A resolved window and its source.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct ResolvedWindow {+ pub(crate) window: Option<u64>,+ pub(crate) source: WindowSource,+}++/// The user's explicit window for `model`, from `config.model_registry`.+pub(crate) fn config_override(model: &str, config: &Config) -> Option<u64> {+ let model = model.trim();+ config+ .model_registry+ .iter()+ .find(|entry| entry.id.trim() == model && entry.context_window > 0)+ .map(|entry| u64::from(entry.context_window))+}++fn remembered() -> &'static Mutex<HashMap<String, u64>> {+ static MAP: OnceLock<Mutex<HashMap<String, u64>>> = OnceLock::new();+ MAP.get_or_init(|| Mutex::new(HashMap::new()))+}++/// The last provider-sourced (or overridden) window resolved for `model` in+/// this process.+pub(crate) fn remembered_window(model: &str) -> Option<u64> {+ remembered()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .get(&model.trim().to_ascii_lowercase())+ .copied()+}++fn remember_window(model: &str, window: u64) {+ remembered()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(model.trim().to_ascii_lowercase(), window);+}++/// Logs a static guess at `warn` the first time per model, `debug` after.+fn warn_static_guess(model: &str, window: Option<u64>, provider: &str) {+ static WARNED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();+ let first = WARNED+ .get_or_init(|| Mutex::new(HashSet::new()))+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(model.to_string());+ let route = provider.split(':').next().unwrap_or_default();+ if first {+ tracing::warn!(+ model,+ route,+ context_window = ?window,+ "[model_context] context window is a static guess — the provider did not report one"+ );+ } else {+ tracing::debug!(+ model,+ route,+ context_window = ?window,+ "[model_context] context window is a static guess"+ );+ }+}++/// The fetcher discovery uses. Unit tests never reach the network.+fn default_fetcher() -> Box<dyn ModelListingFetcher> {+ #[cfg(test)]+ {+ Box::new(OfflineFetcher)+ }+ #[cfg(not(test))]+ {+ Box::new(tinyinference_llm::model::discover::ReqwestListingFetcher::new(+ crate::config::build_runtime_proxy_client_with_timeouts("inference.model_limits", 5, 3),+ ))+ }+}++/// A fetcher that never reaches the network (every request fails).+#[cfg(test)]+struct OfflineFetcher;++#[cfg(test)]+#[async_trait::async_trait]+impl ModelListingFetcher for OfflineFetcher {+ async fn get_json(+ &self,+ url: &str,+ _headers: &[(String, String)],+ ) -> tinyinference_llm::Result<serde_json::Value> {+ Err(tinyinference_llm::Error::Catalog(format!(+ "offline in unit tests: {url}"+ )))+ }+}++/// Resolve the context window for `model` on the `role`'s `provider` route.+pub(crate) async fn resolve_context_window(+ role: &str,+ provider: &str,+ model: &str,+ config: &Config,+) -> Option<u64> {+ let fetcher = default_fetcher();+ resolve_context_window_with(+ fetcher.as_ref(),+ model_limits_cache(),+ role,+ provider,+ model,+ config,+ )+ .await+ .window+}++/// [`resolve_context_window`] with an explicit fetcher and cache.+pub(crate) async fn resolve_context_window_with(+ fetcher: &dyn ModelListingFetcher,+ cache: &ModelLimitsCache,+ role: &str,+ provider: &str,+ model: &str,+ config: &Config,+) -> ResolvedWindow {+ let resolved = resolve_inner(fetcher, cache, role, provider, model, config).await;+ if let Some(window) = resolved.window {+ if matches!(+ resolved.source,+ WindowSource::ConfigOverride+ | WindowSource::ProviderReported+ | WindowSource::LearnedFromOverflow+ ) {+ remember_window(model, window);+ }+ }+ tracing::debug!(+ role,+ model,+ context_window = ?resolved.window,+ source = resolved.source.label(),+ "[model_context] resolved context window"+ );+ resolved+}++async fn resolve_inner(+ fetcher: &dyn ModelListingFetcher,+ cache: &ModelLimitsCache,+ role: &str,+ provider: &str,+ model: &str,+ config: &Config,+) -> ResolvedWindow {+ if let Some(window) = config_override(model, config) {+ return ResolvedWindow {+ window: Some(window),+ source: WindowSource::ConfigOverride,+ };+ }++ let local_kind = tinyinference_local::profile::kind_from_provider_string(provider);+ if local_kind.is_none() {+ if let Some(request) =+ crate::inference::provider::factory::model_limits_request(role, provider, model, config)+ {+ let limits = discover_model_limits_with(fetcher, cache, &request).await;+ if let Some((window, limits)) = limits+ .as_ref()+ .and_then(|limits| limits.context_window.map(|window| (window, limits)))+ {+ let source = match limits.source {+ tinyinference_llm::model::discover::LimitSource::LearnedFromOverflow => {+ WindowSource::LearnedFromOverflow+ }+ _ => WindowSource::ProviderReported,+ };+ tracing::info!(+ role,+ model = %request.model,+ endpoint = %request.endpoint,+ context_window = window,+ max_output_tokens = ?limits.max_output_tokens,+ source = source.label(),+ "[model_context] context window from provider"+ );+ return ResolvedWindow {+ window: Some(window),+ source,+ };+ }+ }+ }++ let static_window = super::model_context::static_context_window_for_model(model);+ if local_kind.is_some() {+ let window = tinyinference_local::profile::context_window_with_local_fallback(+ model,+ static_window,+ local_kind,+ );+ return ResolvedWindow {+ window,+ source: if static_window.is_some() {+ WindowSource::StaticGuess+ } else {+ WindowSource::LocalProfile+ },+ };+ }+ warn_static_guess(model, static_window, provider);+ ResolvedWindow {+ window: static_window,+ source: if static_window.is_some() {+ WindowSource::StaticGuess+ } else {+ WindowSource::Unknown+ },+ }+}++#[cfg(test)]+#[path = "context_window_tests.rs"]+mod tests;diff --git a/vendor/tinyagents b/vendor/tinyagentsindex a917abedfb..a27ed48ab4 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit a917abedfba587e2eb1f0cd93654e37ef068301b+Subproject commit a27ed48ab4dac2685f23e0b12397b647bd5f8b19