From 581ad651a4c451edd49205349f4b1f72e4a4a010 Mon Sep 17 00:00:00 2001 From: CraftBot Date: Mon, 19 Oct 2026 15:43:16 +0900 Subject: [PATCH 1/2] Show model aware context budget, fix KV cache more, fix /clear, and adjusted model context windows and budget --- agent_core/core/impl/action/router.py | 44 +- .../core/impl/event_stream/event_stream.py | 107 +- agent_core/core/impl/event_stream/manager.py | 19 + agent_core/core/impl/llm/interface.py | 325 ++++- agent_core/core/impl/session/manager.py | 53 +- agent_core/core/models/cache_lifetime.py | 112 ++ agent_core/core/models/catalog.py | 57 + agent_core/core/models/model_catalog.json | 1120 +++++++++++++++++ agent_core/core/models/provider_config.py | 43 + agent_file_system/AGENT.md | 28 +- app/agent_base.py | 47 +- app/config.py | 23 +- app/config/settings.json | 1 - app/data/agent_file_system_template/AGENT.md | 28 +- app/session/session_manager.py | 19 + app/ui_layer/adapters/browser_adapter.py | 43 +- .../Chat/ReasoningPicker.module.css | 75 ++ .../src/components/Chat/ReasoningPicker.tsx | 158 ++- .../frontend/src/components/layout/NavBar.tsx | 1 + .../browser/frontend/src/locales/en/chat.json | 14 + .../browser/frontend/src/locales/es/chat.json | 14 + .../browser/frontend/src/locales/id/chat.json | 14 + .../browser/frontend/src/locales/ja/chat.json | 14 + .../browser/frontend/src/locales/ko/chat.json | 14 + .../frontend/src/locales/zh-CN/chat.json | 14 + .../frontend/src/locales/zh-TW/chat.json | 14 + .../src/store/slices/reasoningSlice.ts | 28 +- .../browser/frontend/src/types/index.ts | 16 + app/ui_layer/commands/builtin/clear.py | 15 +- app/usage/session_storage.py | 65 + scripts/catalog_overrides.json | 17 + scripts/gen_model_catalog.py | 161 +++ tests/conftest.py | 23 - tests/llm/test_context_readout.py | 194 +++ tests/llm/test_reasoning_rules.py | 24 +- tests/llm/test_session_resume.py | 169 +++ tests/test_action_set_loading.py | 3 +- tests/test_context_budget.py | 198 ++- tests/test_event_stream_action_schemas.py | 42 +- tests/test_event_stream_datetime.py | 14 +- tests/test_event_stream_delivery.py | 62 +- tests/test_event_stream_oversize.py | 40 +- tests/test_event_stream_protection.py | 21 +- tests/test_session_clear.py | 225 ++++ 44 files changed, 3406 insertions(+), 312 deletions(-) create mode 100644 agent_core/core/models/cache_lifetime.py create mode 100644 agent_core/core/models/catalog.py create mode 100644 agent_core/core/models/model_catalog.json create mode 100644 scripts/catalog_overrides.json create mode 100644 scripts/gen_model_catalog.py create mode 100644 tests/llm/test_context_readout.py create mode 100644 tests/llm/test_session_resume.py create mode 100644 tests/test_session_clear.py diff --git a/agent_core/core/impl/action/router.py b/agent_core/core/impl/action/router.py index 1eda2dc1f..30b083d58 100644 --- a/agent_core/core/impl/action/router.py +++ b/agent_core/core/impl/action/router.py @@ -24,6 +24,7 @@ from agent_core.core.impl.llm.interface import LLMContextOverflowError from agent_core import get_event_stream_manager from agent_core.utils.logger import logger +from agent_core.utils.token import count_tokens def _is_visible_in_mode(action, GUI_mode: bool) -> bool: @@ -212,6 +213,36 @@ def render_prompt() -> str: # Internal helpers # ------------------------------------------------------------------ + def _fold(self, stream, system_prompt: str, static_prompt: Optional[str]) -> None: + """Fold ``stream``, keeping as much recent history as the budget allows. + + A fold keeps context.keep_recent_tokens of recent events, but never + more than half of the room the model's input budget leaves after + what a fold does not shrink: the system prompt, the prompt around + the event stream (``static_prompt``) and the running summary. So + every fold frees at least half of that room for new events, whatever + the model's window. + """ + from app.config import get_keep_recent_tokens + + room = ( + self.llm_interface.input_budget() + - count_tokens(system_prompt) + - count_tokens(static_prompt or "") + - count_tokens(stream.head_summary or "") + ) + stream.summarize_by_LLM( + keep_tokens=min(get_keep_recent_tokens(), max(room, 0) // 2) + ) + + def _checkpoint(self, stream, task_id: str, call_type: str) -> None: + """Tell the LLM interface how far the session history now covers the + stream (it saves the history as of this point, so a restart can + continue the session on the provider's cached prefix).""" + self.llm_interface.checkpoint_session( + task_id, call_type, stream.sync_marker(call_type) if stream else None + ) + async def _prompt_for_decision( self, prompt: str, @@ -237,7 +268,7 @@ async def _prompt_for_decision( max_retries = 3 last_error: Optional[Exception] = None current_prompt = prompt - # One fold per decision: a fold keeps at most keep_recent_tokens of what + # One fold per decision: a fold keeps at most its keep target of what # the model has read (new events count against it), so a request that # still does not fit is carrying new events too large to send in full. # Those are collapsed to pointers once; if it still does not fit, that @@ -315,7 +346,7 @@ async def _prompt_for_decision( f"[SESSION CACHE] Next request exceeds the context " f"budget; folding the event stream for {call_type}" ) - stream.summarize_by_LLM() + self._fold(stream, system_prompt, static_prompt) folded = True current_prompt = render_prompt() self.context_engine.reset_event_stream_sync( @@ -338,6 +369,7 @@ async def _prompt_for_decision( self.context_engine.mark_event_stream_synced( call_type, session_id=effective_session_id ) + self._checkpoint(stream, current_task_id, call_type) else: # No new events - this could mean summarization happened logger.info( @@ -373,10 +405,14 @@ async def _prompt_for_decision( self.context_engine.mark_event_stream_synced( call_type, session_id=effective_session_id ) + self._checkpoint(stream, current_task_id, call_type) else: # No session registered (simple task) - use prefix cache / regular response raw_response = await self.llm_interface.generate_response_async( - system_prompt, current_prompt, prompt_name=prompt_name + system_prompt, + current_prompt, + prompt_name=prompt_name, + usage_key=f"{current_task_id}:{call_type}", ) # The prompt carried the whole stream; a later fold may # collapse any of it now. @@ -442,7 +478,7 @@ async def _prompt_for_decision( f"[SESSION CACHE] Request exceeded the context budget; folding " f"the event stream and retrying once for {call_type}" ) - stream.summarize_by_LLM() + self._fold(stream, system_prompt, static_prompt) folded = True elif not stream.collapse_undelivered_oversize(): # Folded, and the new events have nothing left to shrink. diff --git a/agent_core/core/impl/event_stream/event_stream.py b/agent_core/core/impl/event_stream/event_stream.py index 6cc5685ab..9190cd6a4 100644 --- a/agent_core/core/impl/event_stream/event_stream.py +++ b/agent_core/core/impl/event_stream/event_stream.py @@ -10,11 +10,12 @@ log(kind, message, severity="INFO") -> int (event index) to_prompt_snapshot(max_events=60, include_summary=True) -> str summarize_by_rule() # force summarization of oldest chunk - summarize_by_LLM() # force summarization of oldest chunk + summarize_by_LLM(keep_tokens) # force summarization of oldest chunk """ from __future__ import annotations from datetime import datetime, timezone +import hashlib import re import time from pathlib import Path @@ -31,27 +32,6 @@ SEVERITIES = ("DEBUG", "INFO", "WARN", "ERROR") -def _configured_keep_recent_tokens() -> int: - """Read context.keep_recent_tokens from settings.json. - - app.config owns the defaults and already absorbs a missing file, bad JSON - and out-of-range values, so there is nothing left to guard here — a raised - ImportError means the app package is genuinely gone, which is a broken - install, not a case to paper over with a second copy of the numbers. - - The import is deferred because app.config imports agent_core at module - scope (``from agent_core import get_credential``), and agent_core's - __init__ loads this module — a module-scope import would close that cycle. - By stream-construction time every module is loaded and the import is fine. - - Read once per stream, so a settings.json edit applies to sessions created - after it; the main session's stream needs a restart. - """ - from app.config import get_keep_recent_tokens - - return get_keep_recent_tokens() - - # Messages longer than this are externalized to a temp file and replaced with a # pointer (+keywords) so a single large action output (e.g. get_notion, read_pdf, # an http_request body) can't bloat the prompt. ~8000 chars ≈ ~2000 tokens; the @@ -118,15 +98,13 @@ def __init__( llm: LLMInterfaceProtocol, temp_dir: Path | None = None, ) -> None: - # The stream never decides to fold on its own. The router asks for a - # fold (summarize_by_LLM) when the NEXT REQUEST would not fit the - # context budget; the only stream-side setting is how much recent - # history a fold keeps. Tests pin it by patching - # _configured_keep_recent_tokens (see the event_stream_limits fixture). + # The stream never decides to fold on its own, nor how much a fold + # keeps. The router asks for a fold (summarize_by_LLM) when the NEXT + # REQUEST would not fit the model's context budget, and says how many + # recent tokens to keep. self.head_summary: Optional[str] = None self.llm = llm self.tail_events: List[EventRecord] = [] - self.tail_keep_after_summarize_tokens = _configured_keep_recent_tokens() self.temp_dir = temp_dir self._lock = threading.RLock() @@ -442,18 +420,17 @@ def _find_token_cutoff(self, events: List[EventRecord], keep_tokens: int) -> int ) return cutoff - def _fold_cutoff(self) -> int: + def _fold_cutoff(self, keep_tokens: int) -> int: """How many leading tail events a fold may collapse. - The keep-recent window decides, except that a fold never reaches an - event the model has not received. The router asks for a fold right - after actions return, before their results are sent; folding those - results then hands the agent a summary or a pointer of output it never - saw, and it runs the same read again, which overflows again. + The keep-recent window (``keep_tokens``) decides, except that a fold + never reaches an event the model has not received. The router asks + for a fold right after actions return, before their results are sent; + folding those results then hands the agent a summary or a pointer of + output it never saw, and it runs the same read again, which overflows + again. """ - cutoff = self._find_token_cutoff( - self.tail_events, self.tail_keep_after_summarize_tokens - ) + cutoff = self._find_token_cutoff(self.tail_events, keep_tokens) first_undelivered = next( (i for i, r in enumerate(self.tail_events) if not r.delivered), len(self.tail_events), @@ -527,7 +504,7 @@ def collapse_undelivered_oversize(self) -> int: """Externalize oversized events the model has not received yet. For the router only, when a request still does not fit after a fold: - the fold keeps at most keep_recent_tokens of what the model had read + the fold keeps at most its keep target of what the model had read (new events count against it), so the events it has not received are too large to send in full. Pointers are the only way to hand them over. @@ -545,28 +522,27 @@ def collapse_undelivered_oversize(self) -> int: ) return reclaimed - def summarize_by_LLM(self) -> None: + def summarize_by_LLM(self, keep_tokens: int) -> None: """ - Summarize the oldest tail events using the language model. + Summarize the oldest tail events using the language model, keeping + about ``keep_tokens`` of the most recent events verbatim. This is a SYNCHRONOUS blocking call that holds the lock for the entire duration, including the LLM call. This ensures no events can be added while summarization is in progress. - - Called from log() which already holds the lock (RLock allows reentry). """ if not self.tail_events: return # Find cutoff based on tokens to keep (never past what the model has read) - cutoff = self._fold_cutoff() + cutoff = self._fold_cutoff(keep_tokens) # Collapse anything oversized that the recent-event pin is holding # verbatim BEFORE deciding whether an LLM call is warranted — that alone # often drops the stream back under the threshold for free. if self._shrink_pinned_oversize(cutoff): # Budget changed; the fold boundary moves with it. - cutoff = self._fold_cutoff() + cutoff = self._fold_cutoff(keep_tokens) if cutoff <= 0: # Nothing old enough to summarize @@ -811,11 +787,14 @@ def clear(self) -> None: self.tail_events.clear() self._total_tokens = 0 self._session_sync_points.clear() + # A new stream: its first event gets a fresh datetime marker. + self._last_datetime_ts = None # ───────────────────── Session Cache Delta Tracking ───────────────────── - def mark_delivered(self) -> None: - """Record that the model has received every event now in the tail. + def mark_delivered(self, up_to: Optional[int] = None) -> None: + """Record that the model has received every event now in the tail + (or the first ``up_to`` of them). Called once a request carrying the stream has been answered: through mark_session_synced on the session-cache paths, and by the router @@ -823,9 +802,43 @@ def mark_delivered(self) -> None: the next answered request, so a fold cannot collapse them first. """ with self._lock: - for rec in self.tail_events: + for rec in self.tail_events[:up_to]: rec.delivered = True + def sync_marker(self, call_type: str) -> Optional[Dict[str, Any]]: + """A session cache's sync point in a form that can be checked after + a restart: the point, the timestamps of the first and last event + before it, and a digest of the head summary. None when the call type + has no sync point.""" + with self._lock: + point = self._session_sync_points.get(call_type) + return None if point is None else self._marker_at(point) + + def restore_sync_point(self, call_type: str, marker: Dict[str, Any]) -> bool: + """Put back a sync point saved with sync_marker, but only if this + stream still holds the same events before it (same summary, same + first and last event). Otherwise there is none, and the next request + sends the whole stream.""" + with self._lock: + point = marker.get("point") + if not isinstance(point, int) or not 0 <= point <= len(self.tail_events): + return False + if self._marker_at(point) != marker: + return False + self._session_sync_points[call_type] = point + return True + + def _marker_at(self, point: int) -> Dict[str, Any]: + """Caller holds the lock.""" + return { + "point": point, + "first": self.tail_events[0].ts.isoformat() if point else None, + "last": self.tail_events[point - 1].ts.isoformat() if point else None, + "summary": hashlib.sha256( + (self.head_summary or "").encode("utf-8") + ).hexdigest(), + } + def replace_ui_artifact( self, artifact_id: str, replace: Callable[[Dict[str, Any]], Dict[str, Any]] ) -> int: diff --git a/agent_core/core/impl/event_stream/manager.py b/agent_core/core/impl/event_stream/manager.py index 79960eb01..2b0af9119 100644 --- a/agent_core/core/impl/event_stream/manager.py +++ b/agent_core/core/impl/event_stream/manager.py @@ -285,6 +285,25 @@ def _should_skip_event_type(self, kind: str) -> bool: """ return kind in SKIP_UNPROCESSED_EVENT_TYPES + def clear_event_log(self, session_id: str) -> None: + """Empty a session's EVENT.md (the session is starting over). + + The agent greps EVENT.md to recover detail its context no longer + holds, so a cleared conversation must not stay there. Its + EVENT_UNPROCESSED.md is kept: those events still go to long-term + memory at the next memory run. + """ + stream = self._streams.get(session_id) + if stream is None or stream.temp_dir is None: + return + with self._file_lock: + event_file = Path(stream.temp_dir) / "EVENT.md" + try: + if event_file.exists(): + event_file.write_text("", encoding="utf-8") + except OSError as e: + logger.warning(f"[EventStreamManager] Failed to clear EVENT.md: {e}") + def _log_to_files(self, kind: str, message: str, temp_dir: Optional[Path]) -> None: """ Append an event to the writing session's EVENT.md and (optionally) diff --git a/agent_core/core/impl/llm/interface.py b/agent_core/core/impl/llm/interface.py index 7badae86e..f9cefbb41 100644 --- a/agent_core/core/impl/llm/interface.py +++ b/agent_core/core/impl/llm/interface.py @@ -17,6 +17,7 @@ import contextvars import re import time +from dataclasses import asdict, dataclass from typing import Any, Dict, List, Optional, Set, Tuple @@ -42,12 +43,16 @@ RecordLLMCallHook, ) from agent_core.core.impl.llm import transports as _transports +from agent_core.core.impl.llm.types import LLMCallType +from agent_core.core.models.cache_lifetime import CacheLifetime, cache_lifetime +from agent_core.core.models.catalog import model_limits from agent_core.core.models.reasoning import ( ReasoningChoice, ReasoningDecision, ReasoningOptions, default_choice, reasoning_options as _reasoning_options, + reasoning_surface, resolve_reasoning, ) from agent_core.core.models.registry import ( @@ -80,6 +85,61 @@ ) +def _call_type_name(task_id: str, key: str) -> str: + """The call type a session key (":") was built from, + as its plain value. A key is built by formatting the call type, which for + an LLMCallType member is not its value (and may differ between Python + versions), so members are matched exactly rather than parsed.""" + for member in LLMCallType: + if key == f"{task_id}:{member}": + return member.value + return key[len(task_id) + 1 :] + + +def _call_type_from_name(name: str): + """The call type to build a session key from, for a saved plain value: + the LLMCallType member when there is one, so the key matches the ones + callers build with the member.""" + try: + return LLMCallType(name) + except ValueError: + return name + + +@dataclass(frozen=True) +class RequestUsage: + """What the provider reported for a session's last request.""" + + #: Input tokens the request carried (cached ones included): the size of + #: the session's context at that request. + input_tokens: int + #: Of those, how many the provider served from its prompt cache. + cached_tokens: int + #: Epoch seconds when the request started. Provider cache lifetimes + #: count from the start of the request that wrote or read the cache. + started_at: float + #: Where it was served (reasoning_surface) and by which model: the cache + #: it wrote belongs to them. + surface: str + model: str + + +@dataclass(frozen=True) +class _SessionCheckpoint: + """A session history as of its last synced request. + + How much of the history that request covered, the event stream's sync + marker at that moment, and the provider's input count for it. Saved + state is cut here, so it never holds a turn the stream has not recorded + as sent (a history grows in a worker thread before the router marks the + stream synced). + """ + + history_len: int + marker: Dict[str, Any] + input_tokens: Optional[int] + + class LLMContextOverflowError(RuntimeError): """The assembled request does not fit the configured context window. @@ -299,6 +359,14 @@ def __init__( # Input tokens the provider reported for each session's last request: # the exact size of the context that request carried. self._last_input_tokens: Dict[str, int] = {} + # Each session's last request as the provider reported it, for the + # chat input's context and cache readout. Unlike _last_input_tokens it + # survives a fold and a provider switch: it describes the request + # that was made, not the session history the next one builds on. + self._last_requests: Dict[str, RequestUsage] = {} + # Where each session history stood at its last synced request; what + # export_session saves so a restart can continue the session. + self._checkpoints: Dict[str, _SessionCheckpoint] = {} if ctx["byteplus"]: self.api_key = ctx["byteplus"]["api_key"] @@ -450,6 +518,7 @@ def reinitialize( self._session_system_prompts = {} self._session_histories = {} self._last_input_tokens = {} + self._checkpoints = {} # Reinitialize Gemini cache manager if self._gemini_client: @@ -503,6 +572,13 @@ def _report_usage_async( session_key = _active_session_key.get() if session_key is not None: self._last_input_tokens[session_key] = input_tokens + self._last_requests[session_key] = RequestUsage( + input_tokens=input_tokens, + cached_tokens=cached_tokens, + started_at=_llm_call_ctx.get().get("started_at") or time.time(), + surface=self.surface(), + model=self.model, + ) if not self._report_usage: return @@ -613,6 +689,7 @@ def _begin_call( "thinking_budget": thinking_budget, "reasoning_choice": reasoning_choice, "start": time.perf_counter(), + "started_at": time.time(), } ) @@ -780,18 +857,16 @@ def _check_context_fits( *, reasoning: Optional[ReasoningDecision], ) -> None: - """Refuse a request that cannot fit the configured context window. + """Refuse a request that cannot fit the model's context window. Counts the payload that is about to be sent: the system prompt plus - either the single user prompt or every accumulated message. Input and - the output reservation share the window. ``reasoning`` is the - request's decision, the same one its transport sends. + either the single user prompt or every accumulated message, against + _input_budget. ``reasoning`` is the request's decision, the same one + its transport sends. """ - from app.config import get_context_window - - window = get_context_window() + window, max_input = self._context_limits() reserved = self._output_reservation(reasoning) - budget = window - reserved + budget = self._input_budget(reasoning) total = count_tokens(system_prompt or "") if messages: @@ -808,12 +883,69 @@ def _check_context_fits( total += count_tokens(user_prompt) if total > budget: + input_cap = ( + f", input capped at {max_input}" + if max_input is not None and max_input == budget + else "" + ) raise LLMContextOverflowError( f"Request of ~{total} input tokens exceeds the {budget}-token budget " - f"({window} window - {reserved} reserved for output) for " + f"({window} window - {reserved} reserved for output{input_cap}) for " f"{self.provider}/{self.model}." ) + def _context_limits(self) -> Tuple[int, Optional[int]]: + """The window and input limit of the model this interface serves. + + From the model catalog (agent_core/core/models/catalog.py), looked up + per request, so a model switch or a fallback interface brings its own. + A model the catalog does not list (a local server, a custom endpoint) + uses settings.json model.context_window and has no input limit. + """ + limits = model_limits(self.provider, self.model, self._auth_mode) + if limits is not None: + return limits.context_window, limits.max_input_tokens + from app.config import get_context_window + + return get_context_window(), None + + def _input_budget(self, reasoning: Optional[ReasoningDecision]) -> int: + """Input tokens a request with this reasoning decision may carry. + + The window less the output cap the request sends, and never more than + the provider's input limit when it has one. + """ + window, max_input = self._context_limits() + budget = window - self._output_reservation(reasoning) + return budget if max_input is None else min(budget, max_input) + + def input_budget(self) -> int: + """Input tokens the next request of the call in flight may carry.""" + return self._input_budget(self.reasoning_decision()) + + def input_budget_for(self, choice: ReasoningChoice) -> int: + """input_budget for a request made at reasoning ``choice``.""" + return self._input_budget( + resolve_reasoning(self.provider, self.model, self._auth_mode, choice) + ) + + def prompt_cache_lifetime(self) -> Optional[CacheLifetime]: + """How long the provider keeps the prompt cache of a request to this + model, or None when it documents no lifetime.""" + if self.provider == "bedrock" and not self._bedrock_model_supports_caching(): + return None + return cache_lifetime(self.provider, self.model, self._auth_mode) + + def reports_cached_tokens(self) -> bool: + """Whether this provider's responses say how much input was cached.""" + profile = _get_registry().get(self.provider) + return profile is not None and profile.reports_cached_tokens + + def surface(self) -> str: + """Where requests are served: the provider, or its subscription + backend (reasoning_surface). A prompt cache never crosses surfaces.""" + return reasoning_surface(self.provider, self._auth_mode) + def reasoning_options(self) -> Optional[ReasoningOptions]: """What the chat-input reasoning picker offers for the model in use. @@ -1064,6 +1196,7 @@ async def generate_response_async( json_mode: bool = True, thinking_budget: Optional[int] = None, reasoning_choice: Optional[ReasoningChoice] = None, + usage_key: Optional[str] = None, ) -> str: """Async wrapper that defers the blocking call to a worker thread. @@ -1077,6 +1210,11 @@ async def generate_response_async( ``reasoning_choice`` overrides the bound session's reasoning choice for this call; pass it only for work done for a chat that has no session yet. + + ``usage_key`` (":") is the session request this + call is made for when the provider has no session path: its usage is + recorded under that key, as a session call's is (see last_request). + It changes nothing that is sent. """ # Stamp the context here, in the caller's context, so asyncio.to_thread # copies it into the worker thread where the capture runs. @@ -1085,13 +1223,17 @@ async def generate_response_async( thinking_budget=thinking_budget, reasoning_choice=reasoning_choice, ) - return await asyncio.to_thread( - self._generate_response_sync, - system_prompt, - user_prompt, - log_response, - json_mode, - ) + token = _active_session_key.set(usage_key) + try: + return await asyncio.to_thread( + self._generate_response_sync, + system_prompt, + user_prompt, + log_response, + json_mode, + ) + finally: + _active_session_key.reset(token) def reset_failure_counter(self) -> None: """Reset the consecutive failure counter. @@ -1191,6 +1333,7 @@ def end_session_cache(self, task_id: str, call_type: str) -> None: system_prompt = self._session_system_prompts.pop(session_key, None) self._session_histories.pop(session_key, None) self._last_input_tokens.pop(session_key, None) + self._checkpoints.pop(session_key, None) # Clean up provider-specific caches if self.provider == "byteplus" and self._byteplus_cache_manager: @@ -1211,14 +1354,129 @@ def reset_session_history(self, task_id: str, call_type: str) -> None: session_key = f"{task_id}:{call_type}" self._session_histories.pop(session_key, None) self._last_input_tokens.pop(session_key, None) + self._checkpoints.pop(session_key, None) if self._byteplus_cache_manager: # This provider keeps the history server-side; end that chain too. self._byteplus_cache_manager.end_session(task_id, call_type) + def checkpoint_session( + self, task_id: str, call_type: str, marker: Optional[Dict[str, Any]] + ) -> None: + """Record that the session's history covers its event stream up to + ``marker`` (EventStream.sync_marker), right after the router marked + the stream synced. export_session saves the history as of here.""" + key = f"{task_id}:{call_type}" + history = self._session_histories.get(key) + if marker is None or history is None: + self._checkpoints.pop(key, None) + return + self._checkpoints[key] = _SessionCheckpoint( + history_len=len(history), + marker=marker, + input_tokens=self._last_input_tokens.get(key), + ) + + def export_session(self, task_id: str) -> Dict[str, Dict[str, Any]]: + """The session's LLM state to save, per call type. + + The history as of its checkpoint (with the stream marker and the + input count) and the last request. Restored by import_session, the + first request after a restart continues the session instead of + starting a new prefix, so it hits the provider's cache while that + cache lives. + """ + prefix = f"{task_id}:" + state: Dict[str, Dict[str, Any]] = {} + for key in set(self._checkpoints) | set(self._last_requests): + if not key.startswith(prefix): + continue + entry: Dict[str, Any] = {"surface": self.surface()} + checkpoint = self._checkpoints.get(key) + if checkpoint is not None: + history = self._session_histories.get(key, []) + entry["history"] = list(history[: checkpoint.history_len]) + entry["marker"] = checkpoint.marker + entry["input_tokens"] = checkpoint.input_tokens + request = self._last_requests.get(key) + if request is not None: + entry["last_request"] = asdict(request) + state[_call_type_name(task_id, key)] = entry + return state + + def import_session( + self, task_id: str, state: Dict[str, Dict[str, Any]], stream + ) -> Optional[int]: + """Restore what export_session saved (at boot, before any request). + + The last request always comes back: it only describes a request that + was made. The history comes back only if the provider in use built + it (message formats differ between providers) and ``stream`` still + holds the events it covers (EventStream.restore_sync_point checks); + otherwise the session starts a new prefix on its next request. + + Returns the furthest sync point restored, or None if none was. + """ + furthest: Optional[int] = None + for name, entry in state.items(): + call_type = _call_type_from_name(name) + key = f"{task_id}:{call_type}" + request = entry.get("last_request") + if request: + try: + self._last_requests[key] = RequestUsage(**request) + except TypeError: + pass # saved by a different RequestUsage shape: discard + history = entry.get("history") + marker = entry.get("marker") + if not history or not marker or entry.get("surface") != self.surface(): + continue + if stream is None or not stream.restore_sync_point(call_type, marker): + continue + self._session_histories[key] = history + if entry.get("input_tokens") is not None: + self._last_input_tokens[key] = entry["input_tokens"] + self._checkpoints[key] = _SessionCheckpoint( + history_len=len(history), + marker=marker, + input_tokens=entry.get("input_tokens"), + ) + furthest = max(furthest or 0, marker["point"]) + return furthest + + def restart_session(self, task_id: str) -> None: + """Forget a session's conversation so its next request starts anew. + + Drops, for every call type of the session, what reset_session_history + drops (accumulated history, input count, BytePlus's server-side chain) + plus the last request. The registration stays, and so do caches other + sessions share: Gemini's explicit cache is keyed by the system prompt, + so deleting it (as end_all_session_caches does) would cost every + other session its cached prefix. + """ + prefix = f"{task_id}:" + call_types = { + key[len(prefix) :] + for state in ( + self._session_system_prompts, + self._session_histories, + self._last_input_tokens, + self._last_requests, + ) + for key in state + if key.startswith(prefix) + } + for call_type in call_types: + self.reset_session_history(task_id, call_type) + self._last_requests.pop(f"{prefix}{call_type}", None) + def last_input_tokens(self, task_id: str, call_type: str) -> Optional[int]: """Input tokens the provider reported for this session's last request.""" return self._last_input_tokens.get(f"{task_id}:{call_type}") + def last_request(self, task_id: str, call_type: str) -> Optional[RequestUsage]: + """This session's last request as the provider reported it.""" + return self._last_requests.get(f"{task_id}:{call_type}") + def fits_context( self, task_id: str, call_type: str, system_prompt: Optional[str], pending: str ) -> bool: @@ -1226,26 +1484,20 @@ def fits_context( Projection: the provider's own input count for the previous request (exact, and already paid for) plus a local count of only what is new, - plus the output reservation, against the window less the headroom the - summary request needs. On a session's first request there is no + against input_budget. On a session's first request there is no provider count yet, so the whole prompt is counted locally. - The output reservation is the one the pre-send check - (_check_context_fits) applies, including the reasoning output cap of - the session's choice, so the stream folds before that check could - refuse the request. + The budget is the one the pre-send check (_check_context_fits) + applies. The projection does not count the previous answer, so a + request it lets through can still fail that check; the router's + overflow handler then folds, before anything is sent. """ - from app.config import get_context_window, get_reserve_tokens - last = self._last_input_tokens.get(f"{task_id}:{call_type}") if last is None: projected = count_tokens(system_prompt or "") + count_tokens(pending) else: projected = last + count_tokens(pending) - return ( - projected + self._output_reservation(self.reasoning_decision()) - <= get_context_window() - get_reserve_tokens() - ) + return projected <= self.input_budget() def end_all_session_caches(self, task_id: str) -> None: """End ALL session/explicit caches for a task (all call types). @@ -1271,7 +1523,12 @@ def end_all_session_caches(self, task_id: str) -> None: # Clean up multi-turn message histories across all providers that # accumulate (anthropic, bedrock, openrouter-via-claude, gemini, # openai-subscription). - for state in (self._session_histories, self._last_input_tokens): + for state in ( + self._session_histories, + self._last_input_tokens, + self._last_requests, + self._checkpoints, + ): for key in [k for k in state if k.startswith(f"{task_id}:")]: state.pop(key, None) @@ -1306,11 +1563,11 @@ def has_session_cache(self, task_id: str, call_type: str) -> bool: return True if self.provider == "gemini" and self._gemini_cache_manager: return True - if ( - self.provider - in ("openai", "deepseek", "grok", "openrouter", "glm", "fugu") - and self.client - ): + # The same set create_session_cache registers and the session + # dispatcher serves. A hand-kept subset here sent every other + # accumulating provider down the stateless path, re-sending the + # whole prompt each turn instead of growing a cached prefix. + if self.provider in _session_cc_providers() and self.client: return True if self.provider == "anthropic" and self._anthropic_client: return True diff --git a/agent_core/core/impl/session/manager.py b/agent_core/core/impl/session/manager.py index 428abb665..5234c6418 100644 --- a/agent_core/core/impl/session/manager.py +++ b/agent_core/core/impl/session/manager.py @@ -236,9 +236,14 @@ def delete_session(self, session_id: str) -> bool: return True def clear_session(self, session_id: str) -> bool: - """Clear a session's conversation: event stream, todos, run counters. - - The session itself (title, loaded skills) is kept. + """Start a session over as a new session. + + Everything the agent knows about the session goes back to what + create_session gives it: event stream, LLM session state, todos, + token counters, loaded skills and per-session runtime state; a chat + goes back to "New chat" so its next request titles it again. Its + identity stays: id, type, workspace folder, Agent App project, + reasoning choice and GUI mode. The caller stops any run first. """ session = self.sessions.get(session_id) if not session: @@ -246,22 +251,33 @@ def clear_session(self, session_id: str) -> bool: session.todos = [] session.reset_run_counters() + session.total_input_tokens = 0 + session.total_output_tokens = 0 + session.total_cache_tokens = 0 + session.selected_skills = [] + if session.type == SessionType.CHAT: + session.title = "New chat" + StateSession.end(session_id) + StateSession.start( + session_id, current_session=session, gui_mode=session.gui_mode + ) - stream = self.event_stream_manager.get_stream_by_id(session_id) - if stream is not None and hasattr(stream, "clear"): - stream.clear() + # Only the session's own stream: get_stream_by_id falls back to the + # main session's, which a clear of another session must never touch. + if self.event_stream_manager and self.event_stream_manager.has_stream( + session_id + ): + self.event_stream_manager.get_stream_by_id(session_id).clear() - # Reset per-session LLM caches so the next call rebuilds from the - # now-empty stream. + # Forget the session's conversation on the LLM side and register it + # afresh, as create_session does, so the next request starts a new + # session prefix. Caches shared with other sessions are kept. if self.llm_interface and self.context_engine: - try: - self.llm_interface.remove_session_caches(session_id) - except Exception: - pass + self.llm_interface.restart_session(session_id) self._create_session_caches(session_id) self._persist(session) - logger.info(f"[SessionManager] Session {session_id} cleared") + logger.info(f"[SessionManager] Session {session_id} started over") return True def rename_session(self, session_id: str, title: str) -> bool: @@ -291,8 +307,9 @@ def restore_session(self, session: Session) -> Session: """Register a session loaded from persistence at boot. Compiles the action list (the installed action registry may have - changed between runs) and re-registers per-session state, but does - NOT touch the persisted event stream — the caller restores that. + changed between runs) and re-registers per-session state, including + its LLM session caches, but does NOT touch the persisted event + stream — the caller restores that. """ self._compile_actions(session) if not session.workspace_dir: @@ -304,6 +321,12 @@ def restore_session(self, session: Session) -> Session: StateSession.start( session.id, current_session=session, gui_mode=session.gui_mode ) + + # LLM session caches live in memory, so a restored session has none. + # Without them every turn takes the stateless path and resends the + # whole prompt, of which only the system prompt hits the KV cache. + if self.llm_interface and self.context_engine: + self._create_session_caches(session.id) return session # ─────────────────────── Todo Management ───────────────────────────────── diff --git a/agent_core/core/models/cache_lifetime.py b/agent_core/core/models/cache_lifetime.py new file mode 100644 index 000000000..cc1675b40 --- /dev/null +++ b/agent_core/core/models/cache_lifetime.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +"""How long a provider keeps the prompt cache of a session's last request. + +No provider reports an expiry time in its responses, so the cache of a +session's last request can only be timed from the lifetime the provider +documents, counted from the start of that request. Only providers that +document a lifetime have a row here: + +* EXACT: the provider guarantees at least this long after a request that + wrote or read the cache (OpenAI GPT-5.6+, Anthropic, Bedrock). +* TYPICAL: the provider only documents a usual figure and may drop the + cache sooner (OpenAI models before GPT-5.6). + +Every other provider caches best-effort or not at all (xAI evicts at any +time, DeepSeek within hours to days, local servers until the model unloads, +OpenRouter depends on the upstream it picks), so it has no row and no +countdown is shown for it. + +Keys follow the reasoning table: ``reasoning_surface(provider, auth_mode)`` +and the EXACT model id (no prefix or substring matching). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from typing import Dict, Mapping, Optional + +from agent_core.core.models.reasoning import reasoning_surface + + +class CacheLifetimeKind(str, Enum): + EXACT = "exact" + TYPICAL = "typical" + + +@dataclass(frozen=True) +class CacheLifetime: + """How long a request's prompt cache stays usable after it starts.""" + + kind: CacheLifetimeKind + seconds: int + #: Where the figure comes from. + source: str + + +_OPENAI_DOCS = "https://developers.openai.com/api/docs/guides/prompt-caching" + +#: prompt_cache_options.ttl defaults to "30m", its only value: a prefix stays +#: usable 30 minutes after its most recent write or reuse (a minimum). +_OPENAI_30_MIN = CacheLifetime(CacheLifetimeKind.EXACT, 30 * 60, _OPENAI_DOCS) + +#: Before GPT-5.6, in_memory entries "typically remain active for around 5 to +#: 10 minutes of inactivity" and 24h entries "around 30 minutes"; which one +#: applies depends on the organization, so the shorter figure is shown. +_OPENAI_TYPICAL = CacheLifetime(CacheLifetimeKind.TYPICAL, 5 * 60, _OPENAI_DOCS) + +#: The session path asks for ttl="1h" (transports/anthropic_messages.py); +#: every hit or write refreshes it, timed from the start of the request. +_ANTHROPIC_1_HOUR = CacheLifetime( + CacheLifetimeKind.EXACT, + 60 * 60, + "https://platform.claude.com/docs/en/build-with-claude/prompt-caching", +) + +#: cachePoint is sent without a ttl: five minutes, reset by each cache hit. +_BEDROCK_5_MIN = CacheLifetime( + CacheLifetimeKind.EXACT, + 5 * 60, + "https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html", +) + +#: Lifetime that applies to every model of a surface. +_SURFACE_LIFETIMES: Mapping[str, CacheLifetime] = { + "openai": _OPENAI_TYPICAL, + "anthropic": _ANTHROPIC_1_HOUR, + "bedrock": _BEDROCK_5_MIN, +} + + +def _models(lifetime: CacheLifetime, *model_ids: str) -> Dict[str, CacheLifetime]: + return {model_id: lifetime for model_id in model_ids} + + +#: Models whose lifetime differs from their surface's. +_MODEL_LIFETIMES: Mapping[str, Mapping[str, CacheLifetime]] = { + "openai": _models( + _OPENAI_30_MIN, + "gpt-5.6", + "gpt-5.6-sol", + "gpt-5.6-terra", + "gpt-5.6-luna", + "gpt-6-sol", + "gpt-6-luna", + "gpt-6-astra", + "gpt-6.1-sol", + ), +} + + +def cache_lifetime( + provider: Optional[str], model: Optional[str], auth_mode: str = "api_key" +) -> Optional[CacheLifetime]: + """The documented prompt-cache lifetime of ``model``, or None if the + provider documents none.""" + if not provider or not model: + return None + surface = reasoning_surface(provider, auth_mode) + by_model = _MODEL_LIFETIMES.get(surface, {}).get(model) + if by_model is not None: + return by_model + return _SURFACE_LIFETIMES.get(surface) diff --git a/agent_core/core/models/catalog.py b/agent_core/core/models/catalog.py new file mode 100644 index 000000000..276aa8e41 --- /dev/null +++ b/agent_core/core/models/catalog.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +"""Context limits per model, read from the vendored model catalog. + +model_catalog.json (next to this module, so it ships with the code and an +upgrade replaces it) is generated by scripts/gen_model_catalog.py from +models.dev, the Codex model catalogue (ChatGPT-subscription surface) and +scripts/catalog_overrides.json. Nothing is fetched at runtime. + +Rows are keyed ``/`` with the surface from +``reasoning_surface``, the same keys as the reasoning table, and match the +EXACT model id (no prefix or substring matching). A model with no row is not +catalogued; its caller uses settings.json model.context_window. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path +from typing import Mapping, Optional + +from agent_core.core.models.reasoning import reasoning_surface + +CATALOG_PATH = Path(__file__).with_name("model_catalog.json") + + +@dataclass(frozen=True) +class ModelLimits: + """What a model can take in one request.""" + + #: Input plus output tokens the model accepts. + context_window: int + #: Input tokens the provider accepts whatever output is requested, when + #: it caps input below the window (GPT-5: 272,000 of a 400,000 window). + max_input_tokens: Optional[int] = None + + +@lru_cache(maxsize=1) +def _rows() -> Mapping[str, Mapping[str, int]]: + with open(CATALOG_PATH, encoding="utf-8") as f: + return json.load(f)["models"] + + +def model_limits( + provider: Optional[str], model: Optional[str], auth_mode: str = "api_key" +) -> Optional[ModelLimits]: + """The catalogued limits of ``model`` on ``provider``, or None.""" + if not provider or not model: + return None + row = _rows().get(f"{reasoning_surface(provider, auth_mode)}/{model}") + if row is None: + return None + return ModelLimits( + context_window=row["context_window"], + max_input_tokens=row.get("max_input_tokens"), + ) diff --git a/agent_core/core/models/model_catalog.json b/agent_core/core/models/model_catalog.json new file mode 100644 index 000000000..13d4e2aa0 --- /dev/null +++ b/agent_core/core/models/model_catalog.json @@ -0,0 +1,1120 @@ +{ + "generator": "scripts/gen_model_catalog.py", + "sources": ["https://models.dev/api.json", "https://raw.githubusercontent.com/openai/codex/main/codex-rs/models-manager/models.json", "scripts/catalog_overrides.json"], + "models": { + "anthropic/claude-fable-5": {"context_window": 1000000}, + "anthropic/claude-fable-5-1": {"context_window": 1000000}, + "anthropic/claude-haiku-4-5": {"context_window": 200000}, + "anthropic/claude-haiku-4-5-20251001": {"context_window": 200000}, + "anthropic/claude-haiku-5-5": {"context_window": 1000000}, + "anthropic/claude-opus-4-5": {"context_window": 200000}, + "anthropic/claude-opus-4-5-20251101": {"context_window": 200000}, + "anthropic/claude-opus-4-6": {"context_window": 1000000}, + "anthropic/claude-opus-4-7": {"context_window": 1000000}, + "anthropic/claude-opus-4-8": {"context_window": 1000000}, + "anthropic/claude-opus-5": {"context_window": 1000000}, + "anthropic/claude-opus-5-5": {"context_window": 1000000}, + "anthropic/claude-sonnet-4-5": {"context_window": 200000}, + "anthropic/claude-sonnet-4-5-20250929": {"context_window": 200000}, + "anthropic/claude-sonnet-4-6": {"context_window": 1000000}, + "anthropic/claude-sonnet-5": {"context_window": 1000000}, + "anthropic/claude-sonnet-5-5": {"context_window": 1000000}, + "bedrock/amazon.nova-2-lite-v1:0": {"context_window": 1000000}, + "bedrock/amazon.nova-lite-v1:0": {"context_window": 300000}, + "bedrock/amazon.nova-micro-v1:0": {"context_window": 128000}, + "bedrock/amazon.nova-pro-v1:0": {"context_window": 300000}, + "bedrock/anthropic.claude-fable-5": {"context_window": 1000000}, + "bedrock/anthropic.claude-fable-5-1": {"context_window": 1000000}, + "bedrock/anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, + "bedrock/anthropic.claude-haiku-5-5": {"context_window": 1000000}, + "bedrock/anthropic.claude-opus-4-1-20250805-v1:0": {"context_window": 200000}, + "bedrock/anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, + "bedrock/anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, + "bedrock/anthropic.claude-opus-4-7": {"context_window": 1000000}, + "bedrock/anthropic.claude-opus-4-8": {"context_window": 1000000}, + "bedrock/anthropic.claude-opus-5": {"context_window": 1000000}, + "bedrock/anthropic.claude-opus-5-5": {"context_window": 1000000}, + "bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, + "bedrock/anthropic.claude-sonnet-4-6": {"context_window": 1000000}, + "bedrock/anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/anthropic.claude-sonnet-5-5": {"context_window": 1000000}, + "bedrock/apac.amazon.nova-lite-v1:0": {"context_window": 300000}, + "bedrock/apac.amazon.nova-micro-v1:0": {"context_window": 128000}, + "bedrock/apac.amazon.nova-pro-v1:0": {"context_window": 300000}, + "bedrock/apac.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, + "bedrock/au.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, + "bedrock/au.anthropic.claude-haiku-5-5": {"context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-4-7": {"context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-4-8": {"context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-5": {"context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-5-5": {"context_window": 1000000}, + "bedrock/au.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, + "bedrock/au.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, + "bedrock/au.anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/ca.amazon.nova-lite-v1:0": {"context_window": 300000}, + "bedrock/deepseek.r1-v1:0": {"context_window": 128000}, + "bedrock/deepseek.v3-v1:0": {"context_window": 163840}, + "bedrock/deepseek.v3.2": {"context_window": 163840}, + "bedrock/eu.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, + "bedrock/eu.amazon.nova-lite-v1:0": {"context_window": 300000}, + "bedrock/eu.amazon.nova-micro-v1:0": {"context_window": 128000}, + "bedrock/eu.amazon.nova-pro-v1:0": {"context_window": 300000}, + "bedrock/eu.anthropic.claude-fable-5": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, + "bedrock/eu.anthropic.claude-haiku-5-5": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, + "bedrock/eu.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-4-7": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-4-8": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-5": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-5-5": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, + "bedrock/eu.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, + "bedrock/eu.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/eu.anthropic.claude-sonnet-5-5": {"context_window": 1000000}, + "bedrock/eu.mistral.pixtral-large-2502-v1:0": {"context_window": 128000}, + "bedrock/global.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-fable-5": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-fable-5-1": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, + "bedrock/global.anthropic.claude-haiku-5-5": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, + "bedrock/global.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-4-7": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-4-8": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-5": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-5-5": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, + "bedrock/global.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, + "bedrock/global.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/global.anthropic.claude-sonnet-5-5": {"context_window": 1000000}, + "bedrock/global.moonshotai.kimi-k3": {"context_window": 1048576}, + "bedrock/global.openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.xai.grok-4.6": {"context_window": 500000}, + "bedrock/global.xai.grok-4.7": {"context_window": 500000}, + "bedrock/global.zai.glm-5.3": {"context_window": 1000000}, + "bedrock/google.gemma-3-12b-it": {"context_window": 131072}, + "bedrock/google.gemma-3-27b-it": {"context_window": 131072}, + "bedrock/google.gemma-3-4b-it": {"context_window": 131072}, + "bedrock/google.gemma-4-26b-a4b": {"context_window": 262144}, + "bedrock/google.gemma-4-31b": {"context_window": 262144}, + "bedrock/google.gemma-4-e2b": {"context_window": 131072}, + "bedrock/in.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, + "bedrock/in.anthropic.claude-opus-5": {"context_window": 1000000}, + "bedrock/in.anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/in.openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/in.openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/jp.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, + "bedrock/jp.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, + "bedrock/jp.anthropic.claude-haiku-5-5": {"context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-4-7": {"context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-4-8": {"context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-5": {"context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-5-5": {"context_window": 1000000}, + "bedrock/jp.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, + "bedrock/jp.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, + "bedrock/jp.anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/meta.llama3-1-70b-instruct-v1:0": {"context_window": 128000}, + "bedrock/meta.llama3-1-8b-instruct-v1:0": {"context_window": 128000}, + "bedrock/meta.llama3-3-70b-instruct-v1:0": {"context_window": 128000}, + "bedrock/meta.llama4-maverick-17b-instruct-v1:0": {"context_window": 1000000}, + "bedrock/meta.llama4-scout-17b-instruct-v1:0": {"context_window": 10000000}, + "bedrock/minimax.minimax-m2": {"context_window": 204608}, + "bedrock/minimax.minimax-m2.1": {"context_window": 196608}, + "bedrock/minimax.minimax-m2.5": {"context_window": 196608}, + "bedrock/mistral.devstral-2-123b": {"context_window": 262144}, + "bedrock/mistral.magistral-small-2509": {"context_window": 128000}, + "bedrock/mistral.ministral-3-14b-instruct": {"context_window": 128000}, + "bedrock/mistral.ministral-3-3b-instruct": {"context_window": 256000}, + "bedrock/mistral.ministral-3-8b-instruct": {"context_window": 128000}, + "bedrock/mistral.mistral-large-3-675b-instruct": {"context_window": 262144}, + "bedrock/mistral.pixtral-large-2502-v1:0": {"context_window": 128000}, + "bedrock/mistral.voxtral-mini-3b-2507": {"context_window": 32768}, + "bedrock/mistral.voxtral-small-24b-2507": {"context_window": 32768}, + "bedrock/moonshot.kimi-k2-thinking": {"context_window": 262144}, + "bedrock/moonshotai.kimi-k2.5": {"context_window": 262144}, + "bedrock/nvidia.nemotron-nano-12b-v2": {"context_window": 131072}, + "bedrock/nvidia.nemotron-nano-3-30b": {"context_window": 262144}, + "bedrock/nvidia.nemotron-nano-9b-v2": {"context_window": 131072}, + "bedrock/nvidia.nemotron-super-3-120b": {"context_window": 262144}, + "bedrock/openai.gpt-5.4": {"context_window": 1000000}, + "bedrock/openai.gpt-5.5": {"context_window": 1000000}, + "bedrock/openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-oss-120b": {"context_window": 131072}, + "bedrock/openai.gpt-oss-120b-1:0": {"context_window": 131072}, + "bedrock/openai.gpt-oss-20b": {"context_window": 131072}, + "bedrock/openai.gpt-oss-20b-1:0": {"context_window": 131072}, + "bedrock/openai.gpt-oss-safeguard-120b": {"context_window": 128000}, + "bedrock/openai.gpt-oss-safeguard-20b": {"context_window": 128000}, + "bedrock/qwen.qwen3-235b-a22b-2507-v1:0": {"context_window": 262144}, + "bedrock/qwen.qwen3-32b-v1:0": {"context_window": 32768}, + "bedrock/qwen.qwen3-coder-30b-a3b-v1:0": {"context_window": 262144}, + "bedrock/qwen.qwen3-coder-480b-a35b-v1:0": {"context_window": 131072}, + "bedrock/qwen.qwen3-coder-next": {"context_window": 262144}, + "bedrock/qwen.qwen3-next-80b-a3b": {"context_window": 262144}, + "bedrock/qwen.qwen3-vl-235b-a22b": {"context_window": 262144}, + "bedrock/us-gov.openai.gpt-oss-120b-1:0": {"context_window": 128000}, + "bedrock/us-gov.openai.gpt-oss-20b-1:0": {"context_window": 128000}, + "bedrock/us.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, + "bedrock/us.amazon.nova-lite-v1:0": {"context_window": 300000}, + "bedrock/us.amazon.nova-micro-v1:0": {"context_window": 128000}, + "bedrock/us.amazon.nova-premier-v1:0": {"context_window": 1000000}, + "bedrock/us.amazon.nova-pro-v1:0": {"context_window": 300000}, + "bedrock/us.anthropic.claude-fable-5": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-fable-5-1": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, + "bedrock/us.anthropic.claude-haiku-5-5": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-4-1-20250805-v1:0": {"context_window": 200000}, + "bedrock/us.anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, + "bedrock/us.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-4-7": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-4-8": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-5": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-5-5": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, + "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, + "bedrock/us.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/us.anthropic.claude-sonnet-5-5": {"context_window": 1000000}, + "bedrock/us.deepseek.r1-v1:0": {"context_window": 128000}, + "bedrock/us.meta.llama3-1-70b-instruct-v1:0": {"context_window": 128000}, + "bedrock/us.meta.llama3-1-8b-instruct-v1:0": {"context_window": 128000}, + "bedrock/us.meta.llama3-3-70b-instruct-v1:0": {"context_window": 128000}, + "bedrock/us.meta.llama4-maverick-17b-instruct-v1:0": {"context_window": 1000000}, + "bedrock/us.meta.llama4-scout-17b-instruct-v1:0": {"context_window": 10000000}, + "bedrock/us.mistral.pixtral-large-2502-v1:0": {"context_window": 128000}, + "bedrock/us.moonshotai.kimi-k3": {"context_window": 1048576}, + "bedrock/us.openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.writer.palmyra-x4-v1:0": {"context_window": 122880}, + "bedrock/us.writer.palmyra-x5-v1:0": {"context_window": 1040000}, + "bedrock/us.xai.grok-4.6": {"context_window": 500000}, + "bedrock/us.xai.grok-4.7": {"context_window": 500000}, + "bedrock/us.zai.glm-5.3": {"context_window": 1000000}, + "bedrock/writer.palmyra-x4-v1:0": {"context_window": 122880}, + "bedrock/writer.palmyra-x5-v1:0": {"context_window": 1040000}, + "bedrock/xai.grok-4.3": {"context_window": 1000000}, + "bedrock/xai.grok-4.6": {"context_window": 500000}, + "bedrock/zai.glm-4.7": {"context_window": 202752}, + "bedrock/zai.glm-4.7-flash": {"context_window": 202752}, + "bedrock/zai.glm-5": {"context_window": 202752}, + "cerebras/gpt-oss-120b": {"context_window": 131072}, + "cerebras/qwen-3.8-27b": {"context_window": 131072}, + "deepseek/deepseek-flash": {"context_window": 1000000}, + "deepseek/deepseek-v4-flash": {"context_window": 1000000}, + "deepseek/deepseek-v4-flash-vision-exp": {"context_window": 1000000}, + "deepseek/deepseek-v4-pro": {"context_window": 1000000}, + "fireworks/accounts/fireworks/models/deepseek-v4p1-flash": {"context_window": 1000000}, + "fireworks/accounts/fireworks/models/ember-1": {"context_window": 1048576}, + "fireworks/accounts/fireworks/models/glm-5p3": {"context_window": 1048573}, + "fireworks/accounts/fireworks/models/glm-5p3-flash": {"context_window": 1048573}, + "fireworks/accounts/fireworks/models/gpt-oss-120b": {"context_window": 131072}, + "fireworks/accounts/fireworks/models/inkling": {"context_window": 1048576}, + "fireworks/accounts/fireworks/models/kimi-k3": {"context_window": 1048576}, + "fireworks/accounts/fireworks/models/minimax-m3": {"context_window": 512000}, + "fireworks/accounts/fireworks/models/muse-spark-open": {"context_window": 1048576}, + "fireworks/accounts/fireworks/models/nemotron-3-ultra-nvfp4": {"context_window": 262144}, + "fireworks/accounts/fireworks/models/nemotron-lightning-3p5-30b-a3b": {"context_window": 262144}, + "fireworks/accounts/fireworks/models/qwen3p8-2p4t-a95b": {"context_window": 262144}, + "fireworks/accounts/fireworks/models/qwen3p8-max": {"context_window": 262144}, + "fireworks/accounts/fireworks/routers/deepseek-flash-latest": {"context_window": 1000000}, + "fireworks/accounts/fireworks/routers/glm-5p3-fast": {"context_window": 1048572}, + "fireworks/accounts/fireworks/routers/glm-fast-latest": {"context_window": 1048572}, + "fireworks/accounts/fireworks/routers/glm-flash-latest": {"context_window": 1048573}, + "fireworks/accounts/fireworks/routers/glm-latest": {"context_window": 1048573}, + "fireworks/accounts/fireworks/routers/kimi-fast-latest": {"context_window": 1048576}, + "fireworks/accounts/fireworks/routers/kimi-k3-fast": {"context_window": 1048576}, + "fireworks/accounts/fireworks/routers/kimi-latest": {"context_window": 1048576}, + "fireworks/accounts/fireworks/routers/minimax-latest": {"context_window": 512000}, + "fireworks/accounts/fireworks/routers/qwen-max-latest": {"context_window": 262144}, + "fugu/fugu": {"context_window": 1000000}, + "fugu/fugu-ultra": {"context_window": 1000000}, + "fugu/fugu-ultra-20260615": {"context_window": 1000000}, + "fugu/sakana-namazu": {"context_window": 262144}, + "gemini/deep-research-max-preview-04-2026": {"context_window": 131072}, + "gemini/deep-research-preview-04-2026": {"context_window": 131072}, + "gemini/gemini-2.5-computer-use-preview-10-2025": {"context_window": 128000}, + "gemini/gemini-2.5-flash": {"context_window": 1048576}, + "gemini/gemini-2.5-flash-image": {"context_window": 32768}, + "gemini/gemini-2.5-flash-lite": {"context_window": 1048576}, + "gemini/gemini-2.5-flash-preview-tts": {"context_window": 8192}, + "gemini/gemini-2.5-pro": {"context_window": 1048576}, + "gemini/gemini-2.5-pro-preview-tts": {"context_window": 8192}, + "gemini/gemini-3-flash-preview": {"context_window": 1048576}, + "gemini/gemini-3-pro-image": {"context_window": 65536}, + "gemini/gemini-3-pro-image-preview": {"context_window": 131072}, + "gemini/gemini-3.1-flash-image": {"context_window": 131072}, + "gemini/gemini-3.1-flash-image-preview": {"context_window": 65536}, + "gemini/gemini-3.1-flash-lite": {"context_window": 1048576}, + "gemini/gemini-3.1-flash-lite-image": {"context_window": 65536}, + "gemini/gemini-3.1-flash-lite-preview": {"context_window": 1048576}, + "gemini/gemini-3.1-flash-live-preview": {"context_window": 131072}, + "gemini/gemini-3.1-flash-tts-preview": {"context_window": 8192}, + "gemini/gemini-3.1-pro-preview": {"context_window": 1048576}, + "gemini/gemini-3.1-pro-preview-customtools": {"context_window": 1048576}, + "gemini/gemini-3.5-flash": {"context_window": 1048576}, + "gemini/gemini-3.5-flash-lite": {"context_window": 1048576}, + "gemini/gemini-3.5-live-translate-preview": {"context_window": 16384}, + "gemini/gemini-3.6-flash": {"context_window": 1048576}, + "gemini/gemini-3.7-flash": {"context_window": 1048576}, + "gemini/gemini-3.8-flash": {"context_window": 1048576}, + "gemini/gemini-4-argon": {"context_window": 1048576}, + "gemini/gemini-embedding-001": {"context_window": 2048}, + "gemini/gemini-embedding-2": {"context_window": 8192}, + "gemini/gemini-flash-latest": {"context_window": 1048576}, + "gemini/gemini-flash-lite-latest": {"context_window": 1048576}, + "gemini/gemini-omni-flash-preview": {"context_window": 131072}, + "gemini/gemma-4-26b-a4b-it": {"context_window": 262144}, + "gemini/gemma-4-31b-it": {"context_window": 262144}, + "gemini/lyria-3-clip-preview": {"context_window": 1048576}, + "gemini/lyria-3-pro-preview": {"context_window": 1048576}, + "gemini/veo-3.1-fast-generate-preview": {"context_window": 480}, + "gemini/veo-3.1-generate-preview": {"context_window": 480}, + "gemini/veo-3.1-lite-generate-preview": {"context_window": 480}, + "glm/glm-4.5": {"context_window": 131072}, + "glm/glm-4.5-air": {"context_window": 131072}, + "glm/glm-4.5-flash": {"context_window": 131072}, + "glm/glm-4.5v": {"context_window": 64000}, + "glm/glm-4.6": {"context_window": 204800}, + "glm/glm-4.6v": {"context_window": 128000}, + "glm/glm-4.6v-flash": {"context_window": 128000}, + "glm/glm-4.7": {"context_window": 204800}, + "glm/glm-4.7-flash": {"context_window": 200000}, + "glm/glm-4.7-flashx": {"context_window": 200000}, + "glm/glm-5": {"context_window": 204800}, + "glm/glm-5-turbo": {"context_window": 200000}, + "glm/glm-5.1": {"context_window": 200000}, + "glm/glm-5.2": {"context_window": 1000000}, + "glm/glm-5.3": {"context_window": 1000000}, + "glm/glm-5.3-flash": {"context_window": 1000000}, + "glm/glm-5.3-flashx": {"context_window": 1000000}, + "glm/glm-5v-turbo": {"context_window": 200000}, + "grok/grok-4.20-0309-non-reasoning": {"context_window": 1000000}, + "grok/grok-4.20-0309-reasoning": {"context_window": 1000000}, + "grok/grok-4.20-multi-agent-0309": {"context_window": 1000000}, + "grok/grok-4.3": {"context_window": 1000000}, + "grok/grok-4.5": {"context_window": 500000}, + "grok/grok-4.6": {"context_window": 500000}, + "grok/grok-4.7": {"context_window": 500000}, + "grok/grok-build-0.1": {"context_window": 256000}, + "grok/grok-imagine-image": {"context_window": 16000}, + "grok/grok-imagine-image-quality": {"context_window": 16000}, + "grok/grok-imagine-video": {"context_window": 1024}, + "grok/grok-imagine-video-1.5": {"context_window": 1024}, + "grok/grok-imagine-video-1.5-lite": {"context_window": 1024}, + "groq/allam-2-7b": {"context_window": 4096}, + "groq/canopylabs/orpheus-arabic-saudi": {"context_window": 4000}, + "groq/canopylabs/orpheus-v1-english": {"context_window": 4000}, + "groq/groq/compound": {"context_window": 131072}, + "groq/groq/compound-mini": {"context_window": 131072}, + "groq/llama-3.1-8b-instant": {"context_window": 131072}, + "groq/llama-3.3-70b-versatile": {"context_window": 131072}, + "groq/meta-llama/llama-prompt-guard-2-22m": {"context_window": 512}, + "groq/meta-llama/llama-prompt-guard-2-86m": {"context_window": 512}, + "groq/openai/gpt-oss-120b": {"context_window": 131072}, + "groq/openai/gpt-oss-20b": {"context_window": 131072}, + "groq/openai/gpt-oss-safeguard-20b": {"context_window": 131072}, + "groq/qwen/qwen3.6-27b": {"context_window": 131072}, + "groq/qwen/qwen3.8-27b": {"context_window": 131042}, + "huggingface/MiniMaxAI/MiniMax-M1-80k": {"context_window": 1000000}, + "huggingface/MiniMaxAI/MiniMax-M2": {"context_window": 204800}, + "huggingface/MiniMaxAI/MiniMax-M2.1": {"context_window": 204800}, + "huggingface/MiniMaxAI/MiniMax-M2.5": {"context_window": 204800}, + "huggingface/MiniMaxAI/MiniMax-M2.7": {"context_window": 204800}, + "huggingface/MiniMaxAI/MiniMax-M3": {"context_window": 524288}, + "huggingface/Qwen/Qwen2.5-Coder-32B-Instruct": {"context_window": 131072}, + "huggingface/Qwen/Qwen3-235B-A22B": {"context_window": 40960}, + "huggingface/Qwen/Qwen3-235B-A22B-Instruct-2507": {"context_window": 262144}, + "huggingface/Qwen/Qwen3-235B-A22B-Thinking-2507": {"context_window": 262144}, + "huggingface/Qwen/Qwen3-30B-A3B": {"context_window": 40960}, + "huggingface/Qwen/Qwen3-32B": {"context_window": 131072}, + "huggingface/Qwen/Qwen3-Coder-30B-A3B-Instruct": {"context_window": 262144}, + "huggingface/Qwen/Qwen3-Coder-480B-A35B-Instruct": {"context_window": 262144}, + "huggingface/Qwen/Qwen3-Coder-Next": {"context_window": 262144}, + "huggingface/Qwen/Qwen3-Embedding-4B": {"context_window": 32000}, + "huggingface/Qwen/Qwen3-Embedding-8B": {"context_window": 32000}, + "huggingface/Qwen/Qwen3-Next-80B-A3B-Instruct": {"context_window": 262144}, + "huggingface/Qwen/Qwen3-Next-80B-A3B-Thinking": {"context_window": 262144}, + "huggingface/Qwen/Qwen3-VL-235B-A22B-Instruct": {"context_window": 131072}, + "huggingface/Qwen/Qwen3-VL-235B-A22B-Thinking": {"context_window": 131072}, + "huggingface/Qwen/Qwen3-VL-30B-A3B-Instruct": {"context_window": 131072}, + "huggingface/Qwen/Qwen3.5-122B-A10B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.5-27B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.5-35B-A3B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.5-397B-A17B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.5-9B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.6-27B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.6-35B-A3B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.8-2.4T-A95B": {"context_window": 262144}, + "huggingface/Qwen/Qwen3.8-27B": {"context_window": 262144}, + "huggingface/XiaomiMiMo/MiMo-V2-Flash": {"context_window": 262144}, + "huggingface/XiaomiMiMo/MiMo-V2.5": {"context_window": 262144}, + "huggingface/XiaomiMiMo/MiMo-V2.5-Pro": {"context_window": 1048576}, + "huggingface/deepseek-ai/DeepSeek-R1": {"context_window": 64000}, + "huggingface/deepseek-ai/DeepSeek-R1-0528": {"context_window": 163840}, + "huggingface/deepseek-ai/DeepSeek-V3": {"context_window": 64000}, + "huggingface/deepseek-ai/DeepSeek-V3-0324": {"context_window": 163840}, + "huggingface/deepseek-ai/DeepSeek-V3.1": {"context_window": 131072}, + "huggingface/deepseek-ai/DeepSeek-V3.2": {"context_window": 163840}, + "huggingface/deepseek-ai/DeepSeek-V4-Flash": {"context_window": 1048576}, + "huggingface/deepseek-ai/DeepSeek-V4-Flash-0731": {"context_window": 1048576}, + "huggingface/deepseek-ai/DeepSeek-V4-Flash-Vision-Exp": {"context_window": 1048576}, + "huggingface/deepseek-ai/DeepSeek-V4-Pro": {"context_window": 1048576}, + "huggingface/deepseek-ai/DeepSeek-V4-Pro-0813": {"context_window": 1000000}, + "huggingface/deepseek-ai/DeepSeek-V4.1-Flash": {"context_window": 1048576}, + "huggingface/google/gemma-3-12b-it": {"context_window": 131072}, + "huggingface/google/gemma-3-27b-it": {"context_window": 131072}, + "huggingface/google/gemma-3-4b-it": {"context_window": 131072}, + "huggingface/google/gemma-4-26B-A4B-it": {"context_window": 262144}, + "huggingface/google/gemma-4-31B-it": {"context_window": 262144}, + "huggingface/meta-llama/Llama-3.1-8B-Instruct": {"context_window": 131072}, + "huggingface/meta-llama/Llama-3.3-70B-Instruct": {"context_window": 131072}, + "huggingface/moonshotai/Kimi-K2-Instruct": {"context_window": 131072}, + "huggingface/moonshotai/Kimi-K2-Instruct-0905": {"context_window": 262144}, + "huggingface/moonshotai/Kimi-K2-Thinking": {"context_window": 262144}, + "huggingface/moonshotai/Kimi-K2.5": {"context_window": 262144}, + "huggingface/moonshotai/Kimi-K2.6": {"context_window": 262144}, + "huggingface/moonshotai/Kimi-K2.7-Code": {"context_window": 262144}, + "huggingface/moonshotai/Kimi-K3": {"context_window": 1000000}, + "huggingface/openai/gpt-oss-120b": {"context_window": 131072}, + "huggingface/openai/gpt-oss-20b": {"context_window": 131072}, + "huggingface/stepfun-ai/Step-3.5-Flash": {"context_window": 262144}, + "huggingface/stepfun-ai/Step-3.7-Flash": {"context_window": 262144}, + "huggingface/tencent/Hy3": {"context_window": 262144, "max_input_tokens": 192000}, + "huggingface/tencent/Hy4-preview": {"context_window": 1000000}, + "huggingface/thinkingmachines/Inkling": {"context_window": 1048576}, + "huggingface/thinkingmachines/Inkling-Small": {"context_window": 524288}, + "huggingface/zai-org/AutoGLM-Phone-9B-Multilingual": {"context_window": 65536}, + "huggingface/zai-org/GLM-4.5": {"context_window": 131072}, + "huggingface/zai-org/GLM-4.5-Air": {"context_window": 131072}, + "huggingface/zai-org/GLM-4.5V": {"context_window": 65536}, + "huggingface/zai-org/GLM-4.6": {"context_window": 204800}, + "huggingface/zai-org/GLM-4.6V-Flash": {"context_window": 131072}, + "huggingface/zai-org/GLM-4.7": {"context_window": 204800}, + "huggingface/zai-org/GLM-4.7-Flash": {"context_window": 200000}, + "huggingface/zai-org/GLM-5": {"context_window": 202752}, + "huggingface/zai-org/GLM-5.1": {"context_window": 202752}, + "huggingface/zai-org/GLM-5.2": {"context_window": 262144}, + "huggingface/zai-org/GLM-5.3": {"context_window": 1048576}, + "huggingface/zai-org/GLM-5.3-Flash": {"context_window": 1048576}, + "minimax/MiniMax-M2": {"context_window": 204800}, + "minimax/MiniMax-M2.1": {"context_window": 204800}, + "minimax/MiniMax-M2.5": {"context_window": 204800}, + "minimax/MiniMax-M2.5-highspeed": {"context_window": 204800}, + "minimax/MiniMax-M2.7": {"context_window": 204800}, + "minimax/MiniMax-M2.7-highspeed": {"context_window": 204800}, + "minimax/MiniMax-M3": {"context_window": 1000000}, + "mistral/codestral-2508": {"context_window": 256000}, + "mistral/codestral-latest": {"context_window": 256000}, + "mistral/devstral-2512": {"context_window": 262144}, + "mistral/devstral-latest": {"context_window": 262144}, + "mistral/devstral-medium-2507": {"context_window": 128000}, + "mistral/devstral-medium-latest": {"context_window": 262144}, + "mistral/devstral-small-2505": {"context_window": 128000}, + "mistral/devstral-small-2507": {"context_window": 128000}, + "mistral/glm-5-2": {"context_window": 1048576}, + "mistral/labs-devstral-small-2512": {"context_window": 256000}, + "mistral/labs-leanstral-1-5-1": {"context_window": 262144}, + "mistral/magistral-medium-latest": {"context_window": 262144}, + "mistral/ministral-14b-2512": {"context_window": 262144}, + "mistral/ministral-3b-2512": {"context_window": 131072}, + "mistral/ministral-3b-latest": {"context_window": 131072}, + "mistral/ministral-8b-2512": {"context_window": 262144}, + "mistral/ministral-8b-latest": {"context_window": 262144}, + "mistral/mistral-embed": {"context_window": 8000}, + "mistral/mistral-large-2411": {"context_window": 131072}, + "mistral/mistral-large-2512": {"context_window": 262144}, + "mistral/mistral-large-4": {"context_window": 1048576}, + "mistral/mistral-large-latest": {"context_window": 262144}, + "mistral/mistral-medium-2505": {"context_window": 131072}, + "mistral/mistral-medium-2508": {"context_window": 262144}, + "mistral/mistral-medium-2604": {"context_window": 262144}, + "mistral/mistral-medium-latest": {"context_window": 262144}, + "mistral/mistral-nemo": {"context_window": 128000}, + "mistral/mistral-small-2506": {"context_window": 128000}, + "mistral/mistral-small-2603": {"context_window": 262144}, + "mistral/mistral-small-latest": {"context_window": 262144}, + "mistral/open-mistral-7b": {"context_window": 8000}, + "mistral/open-mistral-nemo": {"context_window": 128000}, + "mistral/open-mixtral-8x22b": {"context_window": 64000}, + "mistral/open-mixtral-8x7b": {"context_window": 32000}, + "mistral/pixtral-12b": {"context_window": 128000}, + "mistral/pixtral-large-latest": {"context_window": 128000}, + "mistral/voxtral-small-2507": {"context_window": 32768}, + "mistral/voxtral-small-latest": {"context_window": 32768}, + "mistral/zai-glm-5-2": {"context_window": 1048576}, + "mistral/zai-glm-5-3": {"context_window": 1048576}, + "moonshot/kimi-k2.6": {"context_window": 262144}, + "moonshot/kimi-k2.7-code": {"context_window": 262144}, + "moonshot/kimi-k2.7-code-highspeed": {"context_window": 262144}, + "moonshot/kimi-k3": {"context_window": 1048576}, + "nvidia/abacusai/dracarys-llama-3.1-70b-instruct": {"context_window": 128000}, + "nvidia/baai/bge-m3": {"context_window": 8192}, + "nvidia/black-forest-labs/flux.1-dev": {"context_window": 4096}, + "nvidia/black-forest-labs/flux_1-kontext-dev": {"context_window": 40960}, + "nvidia/black-forest-labs/flux_1-schnell": {"context_window": 77}, + "nvidia/black-forest-labs/flux_2-klein-4b": {"context_window": 40960}, + "nvidia/bytedance/seed-oss-36b-instruct": {"context_window": 262000}, + "nvidia/deepseek-ai/deepseek-v4-flash": {"context_window": 1048576}, + "nvidia/deepseek-ai/deepseek-v4-flash-0731": {"context_window": 1000000}, + "nvidia/deepseek-ai/deepseek-v4-pro": {"context_window": 1048576}, + "nvidia/deepseek-ai/deepseek-v4-pro-0813": {"context_window": 1000000}, + "nvidia/deepseek-ai/deepseek-v4.1-flash": {"context_window": 1000000}, + "nvidia/google/diffusiongemma-26b-a4b-it": {"context_window": 250000}, + "nvidia/google/gemma-2-2b-it": {"context_window": 128000}, + "nvidia/google/gemma-3-12b-it": {"context_window": 131072}, + "nvidia/google/gemma-3-4b-it": {"context_window": 131072}, + "nvidia/google/gemma-3n-e2b-it": {"context_window": 128000}, + "nvidia/google/gemma-3n-e4b-it": {"context_window": 128000}, + "nvidia/google/gemma-4-31b-it": {"context_window": 256000}, + "nvidia/google/google-paligemma": {"context_window": 128000}, + "nvidia/meta/esm2-650m": {"context_window": 128000}, + "nvidia/meta/esmfold": {"context_window": 128000}, + "nvidia/meta/llama-3.1-70b-instruct": {"context_window": 128000}, + "nvidia/meta/llama-3.1-8b-instruct": {"context_window": 16000}, + "nvidia/meta/llama-3.2-11b-vision-instruct": {"context_window": 128000}, + "nvidia/meta/llama-3.2-1b-instruct": {"context_window": 128000}, + "nvidia/meta/llama-3.2-3b-instruct": {"context_window": 32768}, + "nvidia/meta/llama-3.2-90b-vision-instruct": {"context_window": 128000}, + "nvidia/meta/llama-3.3-70b-instruct": {"context_window": 128000}, + "nvidia/meta/llama-4-maverick-17b-128e-instruct": {"context_window": 128000}, + "nvidia/meta/llama-guard-4-12b": {"context_window": 128000}, + "nvidia/meta/muse-glimmer-30b": {"context_window": 131072}, + "nvidia/microsoft/phi-4-mini-instruct": {"context_window": 131072}, + "nvidia/microsoft/phi-4-multimodal-instruct": {"context_window": 128000}, + "nvidia/minimaxai/minimax-m2.7": {"context_window": 204800}, + "nvidia/minimaxai/minimax-m3": {"context_window": 1000000}, + "nvidia/mistralai/magistral-small-2506": {"context_window": 32768}, + "nvidia/mistralai/ministral-14b-instruct-2512": {"context_window": 262144}, + "nvidia/mistralai/mistral-7b-instruct-v0.3": {"context_window": 65536}, + "nvidia/mistralai/mistral-large-3-675b-instruct-2512": {"context_window": 262144}, + "nvidia/mistralai/mistral-medium-3-instruct": {"context_window": 131072}, + "nvidia/mistralai/mistral-medium-3.5-128b": {"context_window": 262144}, + "nvidia/mistralai/mistral-nemotron": {"context_window": 128000}, + "nvidia/mistralai/mistral-small-4-119b-2603": {"context_window": 128000}, + "nvidia/mistralai/mixtral-8x22b-instruct": {"context_window": 65536}, + "nvidia/mistralai/mixtral-8x7b-instruct": {"context_window": 32768}, + "nvidia/moonshotai/kimi-k2.6": {"context_window": 262144}, + "nvidia/moonshotai/kimi-k3": {"context_window": 1048576}, + "nvidia/nvidia/bevformer": {"context_window": 128000}, + "nvidia/nvidia/cosmos-reason2-8b": {"context_window": 131072}, + "nvidia/nvidia/gliner-pii": {"context_window": 128000}, + "nvidia/nvidia/llama-3.1-nemotron-70b-instruct": {"context_window": 128000}, + "nvidia/nvidia/llama-3.1-nemotron-nano-8b-v1": {"context_window": 131072}, + "nvidia/nvidia/llama-3.1-nemotron-nano-vl-8b-v1": {"context_window": 32768}, + "nvidia/nvidia/llama-3.1-nemotron-safety-guard-8b-v3": {"context_window": 128000}, + "nvidia/nvidia/llama-3.1-nemotron-ultra-253b-v1": {"context_window": 128000}, + "nvidia/nvidia/llama-3.3-nemotron-super-49b-v1": {"context_window": 131072}, + "nvidia/nvidia/llama-3.3-nemotron-super-49b-v1.5": {"context_window": 131072}, + "nvidia/nvidia/llama-3_2-nemoretriever-300m-embed-v1": {"context_window": 32768}, + "nvidia/nvidia/llama-nemotron-embed-vl-1b-v2": {"context_window": 32768}, + "nvidia/nvidia/llama-nemotron-rerank-vl-1b-v2": {"context_window": 128000}, + "nvidia/nvidia/nemotron-3-content-safety": {"context_window": 128000}, + "nvidia/nvidia/nemotron-3-nano-30b-a3b": {"context_window": 131072}, + "nvidia/nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": {"context_window": 256000}, + "nvidia/nvidia/nemotron-3-ultra-550b-a55b": {"context_window": 1000000}, + "nvidia/nvidia/nemotron-3.5-content-safety": {"context_window": 128000}, + "nvidia/nvidia/nemotron-3.5-lightning-30b-a3b": {"context_window": 262144}, + "nvidia/nvidia/nemotron-3.5-super-vl-120b-a12b": {"context_window": 1048576}, + "nvidia/nvidia/nemotron-content-safety-reasoning-4b": {"context_window": 128000}, + "nvidia/nvidia/nemotron-mini-4b-instruct": {"context_window": 128000}, + "nvidia/nvidia/nemotron-nano-12b-v2-vl": {"context_window": 128000}, + "nvidia/nvidia/nemotron-voicechat": {"context_window": 128000}, + "nvidia/nvidia/nv-embed-v1": {"context_window": 32768}, + "nvidia/nvidia/nv-embedcode-7b-v1": {"context_window": 32768}, + "nvidia/nvidia/nvidia-nemotron-nano-9b-v2": {"context_window": 131072}, + "nvidia/nvidia/rerank-qa-mistral-4b": {"context_window": 128000}, + "nvidia/nvidia/riva-translate-4b-instruct-v1.1": {"context_window": 128000}, + "nvidia/nvidia/sparsedrive": {"context_window": 128000}, + "nvidia/nvidia/streampetr": {"context_window": 128000}, + "nvidia/nvidia/studiovoice": {"context_window": 128000}, + "nvidia/nvidia/usdcode": {"context_window": 128000}, + "nvidia/openai/gpt-oss-20b": {"context_window": 131072}, + "nvidia/poolside/laguna-xs-2.1": {"context_window": 262144}, + "nvidia/qwen/qwen2.5-coder-32b-instruct": {"context_window": 128000}, + "nvidia/qwen/qwen3-coder-480b-a35b-instruct": {"context_window": 262144}, + "nvidia/qwen/qwen3-next-80b-a3b-instruct": {"context_window": 262144}, + "nvidia/qwen/qwen3.5-122b-a10b": {"context_window": 262144}, + "nvidia/qwen/qwen3.5-397b-a17b": {"context_window": 262144}, + "nvidia/sarvamai/sarvam-m": {"context_window": 128000}, + "nvidia/stepfun-ai/step-3.5-flash": {"context_window": 256000}, + "nvidia/stepfun-ai/step-3.7-flash": {"context_window": 256000}, + "nvidia/thinkingmachines/inkling": {"context_window": 1048576}, + "nvidia/upstage/solar-10.7b-instruct": {"context_window": 128000}, + "nvidia/z-ai/glm-5.2": {"context_window": 1000000}, + "nvidia/z-ai/glm-5.3": {"context_window": 1000000}, + "nvidia/z-ai/glm-5.3-flash": {"context_window": 1000000}, + "openai/gpt-3.5-turbo": {"context_window": 16385}, + "openai/gpt-4": {"context_window": 8192}, + "openai/gpt-4-turbo": {"context_window": 128000}, + "openai/gpt-4.1": {"context_window": 1047576}, + "openai/gpt-4.1-mini": {"context_window": 1047576}, + "openai/gpt-4.1-nano": {"context_window": 1047576}, + "openai/gpt-4o": {"context_window": 128000}, + "openai/gpt-4o-2024-05-13": {"context_window": 128000}, + "openai/gpt-4o-2024-08-06": {"context_window": 128000}, + "openai/gpt-4o-2024-11-20": {"context_window": 128000}, + "openai/gpt-4o-mini": {"context_window": 128000}, + "openai/gpt-5": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-2025-08-07": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-mini": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-mini-2025-08-07": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-nano": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-nano-2025-08-07": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-pro": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.1": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.1-2025-11-13": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.2": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.2-2025-12-11": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.2-chat-latest": {"context_window": 128000}, + "openai/gpt-5.2-pro": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.3-chat-latest": {"context_window": 128000}, + "openai/gpt-5.3-codex": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.3-codex-spark": {"context_window": 128000, "max_input_tokens": 100000}, + "openai/gpt-5.4": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.4-2026-03-05": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.4-mini": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.4-mini-2026-03-17": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.4-nano": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.4-nano-2026-03-17": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.4-pro": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.5": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.5-2026-04-23": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.5-pro": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.6": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-daybreak-blue-latest": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-daybreak-red-latest": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-realtime-2.1": {"context_window": 128000, "max_input_tokens": 96000}, + "openai/o1": {"context_window": 200000}, + "openai/o1-pro": {"context_window": 200000}, + "openai/o3": {"context_window": 200000}, + "openai/o3-2025-04-16": {"context_window": 200000}, + "openai/o3-mini": {"context_window": 200000}, + "openai/o3-mini-2025-01-31": {"context_window": 200000}, + "openai/o3-pro": {"context_window": 200000}, + "openai/o4-mini": {"context_window": 200000}, + "openai/o4-mini-2025-04-16": {"context_window": 200000}, + "openai/text-embedding-3-large": {"context_window": 8191}, + "openai/text-embedding-3-small": {"context_window": 8191}, + "openai/text-embedding-ada-002": {"context_window": 8192}, + "openai_subscription/codex-auto-review": {"context_window": 272000}, + "openai_subscription/gpt-5.5": {"context_window": 272000}, + "openai_subscription/gpt-5.6-luna": {"context_window": 272000}, + "openai_subscription/gpt-5.6-sol": {"context_window": 272000}, + "openai_subscription/gpt-5.6-terra": {"context_window": 272000}, + "openai_subscription/gpt-6-astra": {"context_window": 272000}, + "openai_subscription/gpt-6-luna": {"context_window": 272000}, + "openai_subscription/gpt-6-sol": {"context_window": 272000}, + "openai_subscription/gpt-6.1-sol": {"context_window": 272000}, + "openai_subscription/gpt-daybreak-blue-latest": {"context_window": 272000}, + "openai_subscription/gpt-daybreak-red-latest": {"context_window": 372000}, + "openrouter/aion-labs/aion-2.0": {"context_window": 131072}, + "openrouter/aion-labs/aion-3.0": {"context_window": 131072}, + "openrouter/aion-labs/aion-3.0-mini": {"context_window": 131072}, + "openrouter/aion-labs/aion-3.5": {"context_window": 262144}, + "openrouter/aion-labs/aion-3.5-mini": {"context_window": 262144}, + "openrouter/aion-labs/aion-rp-llama-3.1-8b": {"context_window": 32768}, + "openrouter/amazon/nova-2-lite-v1": {"context_window": 1000000}, + "openrouter/amazon/nova-lite-v1": {"context_window": 300000}, + "openrouter/amazon/nova-micro-v1": {"context_window": 128000}, + "openrouter/amazon/nova-premier-v1": {"context_window": 1000000}, + "openrouter/amazon/nova-pro-v1": {"context_window": 300000}, + "openrouter/anthracite-org/magnum-v4-72b": {"context_window": 32768}, + "openrouter/anthropic/claude-fable-5": {"context_window": 1000000}, + "openrouter/anthropic/claude-fable-5.1": {"context_window": 1000000}, + "openrouter/anthropic/claude-haiku-4.5": {"context_window": 200000}, + "openrouter/anthropic/claude-haiku-5.5": {"context_window": 1000000}, + "openrouter/anthropic/claude-opus-4.1": {"context_window": 200000}, + "openrouter/anthropic/claude-opus-4.5": {"context_window": 200000}, + "openrouter/anthropic/claude-opus-4.6": {"context_window": 1000000}, + "openrouter/anthropic/claude-opus-4.7": {"context_window": 1000000}, + "openrouter/anthropic/claude-opus-4.8": {"context_window": 1000000}, + "openrouter/anthropic/claude-opus-5": {"context_window": 1000000}, + "openrouter/anthropic/claude-opus-5.5": {"context_window": 1000000}, + "openrouter/anthropic/claude-sonnet-4.5": {"context_window": 1000000}, + "openrouter/anthropic/claude-sonnet-4.6": {"context_window": 1000000}, + "openrouter/anthropic/claude-sonnet-5": {"context_window": 1000000}, + "openrouter/anthropic/claude-sonnet-5.5": {"context_window": 1000000}, + "openrouter/arcee-ai/trinity-large-thinking": {"context_window": 262144}, + "openrouter/bytedance-seed/seed-1.6": {"context_window": 262144}, + "openrouter/bytedance-seed/seed-1.6-flash": {"context_window": 262144}, + "openrouter/bytedance-seed/seed-2-1-turbo": {"context_window": 262144}, + "openrouter/bytedance-seed/seed-2.0-code": {"context_window": 262144}, + "openrouter/bytedance-seed/seed-2.0-lite": {"context_window": 262144}, + "openrouter/bytedance-seed/seed-2.0-mini": {"context_window": 262144}, + "openrouter/bytedance/ui-tars-1.5-7b": {"context_window": 128000}, + "openrouter/cognitivecomputations/dolphin-mistral-24b-venice-edition": {"context_window": 128000}, + "openrouter/cohere/command-a": {"context_window": 256000}, + "openrouter/cohere/command-a-plus": {"context_window": 192000}, + "openrouter/cohere/command-r-08-2024": {"context_window": 128000}, + "openrouter/cohere/command-r-plus-08-2024": {"context_window": 128000}, + "openrouter/cohere/command-r7b-12-2024": {"context_window": 128000}, + "openrouter/cohere/north-mini-code:free": {"context_window": 256000}, + "openrouter/deepseek/deepseek-chat": {"context_window": 163840}, + "openrouter/deepseek/deepseek-chat-v3-0324": {"context_window": 163840}, + "openrouter/deepseek/deepseek-chat-v3.1": {"context_window": 163840}, + "openrouter/deepseek/deepseek-r1": {"context_window": 64000}, + "openrouter/deepseek/deepseek-r1-0528": {"context_window": 163840}, + "openrouter/deepseek/deepseek-v3.1-terminus": {"context_window": 163840}, + "openrouter/deepseek/deepseek-v3.2": {"context_window": 163840}, + "openrouter/deepseek/deepseek-v3.2-exp": {"context_window": 163840}, + "openrouter/deepseek/deepseek-v4-flash": {"context_window": 1048576}, + "openrouter/deepseek/deepseek-v4-flash-0731": {"context_window": 1048576}, + "openrouter/deepseek/deepseek-v4-flash-vision-exp": {"context_window": 1048576}, + "openrouter/deepseek/deepseek-v4-pro": {"context_window": 1048576}, + "openrouter/deepseek/deepseek-v4-pro-0813": {"context_window": 1048576}, + "openrouter/deepseek/deepseek-v4.1-flash": {"context_window": 1048576}, + "openrouter/deepseek/deepseek-v4.1-flash-1017": {"context_window": 1048576}, + "openrouter/dots-studio/dots-3-note-preview:free": {"context_window": 512000}, + "openrouter/elorian/glimpse": {"context_window": 262144}, + "openrouter/fireworks/ember-1": {"context_window": 1048576}, + "openrouter/google/gemini-2.5-flash": {"context_window": 1048576}, + "openrouter/google/gemini-2.5-flash-image": {"context_window": 32768}, + "openrouter/google/gemini-2.5-flash-lite": {"context_window": 1048576}, + "openrouter/google/gemini-2.5-pro": {"context_window": 1048576}, + "openrouter/google/gemini-2.5-pro-preview": {"context_window": 1048576}, + "openrouter/google/gemini-3-flash-preview": {"context_window": 1048576}, + "openrouter/google/gemini-3-pro-image": {"context_window": 131072}, + "openrouter/google/gemini-3-pro-image-preview": {"context_window": 65536}, + "openrouter/google/gemini-3.1-flash-image": {"context_window": 131072}, + "openrouter/google/gemini-3.1-flash-image-preview": {"context_window": 65536}, + "openrouter/google/gemini-3.1-flash-lite": {"context_window": 1048576}, + "openrouter/google/gemini-3.1-flash-lite-image": {"context_window": 65536}, + "openrouter/google/gemini-3.1-flash-lite-preview": {"context_window": 1048576}, + "openrouter/google/gemini-3.1-pro-preview": {"context_window": 1048576}, + "openrouter/google/gemini-3.1-pro-preview-customtools": {"context_window": 1048576}, + "openrouter/google/gemini-3.5-flash": {"context_window": 1048576}, + "openrouter/google/gemini-3.5-flash-lite": {"context_window": 1048576}, + "openrouter/google/gemini-3.6-flash": {"context_window": 1048576}, + "openrouter/google/gemini-3.7-flash": {"context_window": 1048576}, + "openrouter/google/gemini-3.8-flash": {"context_window": 1048576}, + "openrouter/google/gemini-4-argon": {"context_window": 1048576}, + "openrouter/google/gemini-nano-banana-2.1": {"context_window": 65536}, + "openrouter/google/gemma-2-27b-it": {"context_window": 8192}, + "openrouter/google/gemma-3-12b-it": {"context_window": 131072}, + "openrouter/google/gemma-3-27b-it": {"context_window": 131072}, + "openrouter/google/gemma-3-4b-it": {"context_window": 131072}, + "openrouter/google/gemma-4-26b-a4b-it": {"context_window": 262144}, + "openrouter/google/gemma-4-26b-a4b-it:free": {"context_window": 262144}, + "openrouter/google/gemma-4-31b-it": {"context_window": 262144}, + "openrouter/google/gemma-4-31b-it:free": {"context_window": 262144}, + "openrouter/google/lyria-3-clip-preview": {"context_window": 1048576}, + "openrouter/google/lyria-3-pro-preview": {"context_window": 1048576}, + "openrouter/gryphe/mythomax-l2-13b": {"context_window": 8192}, + "openrouter/ibm-granite/granite-4.0-h-micro": {"context_window": 131000}, + "openrouter/ibm-granite/granite-4.2-8b": {"context_window": 131072}, + "openrouter/inception/mercury-2": {"context_window": 128000}, + "openrouter/inception/mercury-2.5": {"context_window": 260000}, + "openrouter/inclusionai/ling-3.0-flash": {"context_window": 262144}, + "openrouter/inclusionai/ling-3.0-flash-vl": {"context_window": 131072}, + "openrouter/inclusionai/ling-3.1-flash": {"context_window": 262144}, + "openrouter/inference-net/schematron-v2-small": {"context_window": 128000}, + "openrouter/inference-net/schematron-v2-turbo": {"context_window": 128000}, + "openrouter/liquid/lfm-2.5-2.6b:free": {"context_window": 65536}, + "openrouter/liquid/lfm-2.5-24b-a2b": {"context_window": 128000}, + "openrouter/mancer/weaver": {"context_window": 8000}, + "openrouter/meituan/longcat-2.0": {"context_window": 1048756}, + "openrouter/meta-llama/llama-3.1-70b-instruct": {"context_window": 131072}, + "openrouter/meta-llama/llama-3.1-8b-instruct": {"context_window": 131072}, + "openrouter/meta-llama/llama-3.2-1b-instruct": {"context_window": 60000}, + "openrouter/meta-llama/llama-3.2-3b-instruct": {"context_window": 131072}, + "openrouter/meta-llama/llama-3.3-70b-instruct": {"context_window": 131072}, + "openrouter/meta-llama/llama-4-maverick": {"context_window": 1048576}, + "openrouter/meta-llama/llama-4-scout": {"context_window": 1310720}, + "openrouter/meta-llama/llama-guard-4-12b": {"context_window": 163840}, + "openrouter/meta/muse-glimmer-30b": {"context_window": 131072}, + "openrouter/meta/muse-spark-1.1": {"context_window": 1048576}, + "openrouter/meta/muse-spark-1.2": {"context_window": 1048576}, + "openrouter/meta/muse-spark-1.2-contributor": {"context_window": 1048576}, + "openrouter/meta/muse-spark-1.3": {"context_window": 1048576}, + "openrouter/meta/muse-spark-1.3-contributor": {"context_window": 1048576}, + "openrouter/meta/muse-spark-open": {"context_window": 1048576}, + "openrouter/meta/muse-wonder": {"context_window": 1048576}, + "openrouter/microsoft/phi-4": {"context_window": 16384}, + "openrouter/microsoft/wizardlm-2-8x22b": {"context_window": 65535}, + "openrouter/minimax/minimax-01": {"context_window": 1000192}, + "openrouter/minimax/minimax-m1": {"context_window": 1000000}, + "openrouter/minimax/minimax-m2": {"context_window": 204800}, + "openrouter/minimax/minimax-m2-her": {"context_window": 65536}, + "openrouter/minimax/minimax-m2.1": {"context_window": 204800}, + "openrouter/minimax/minimax-m2.5": {"context_window": 204800}, + "openrouter/minimax/minimax-m2.7": {"context_window": 204800}, + "openrouter/minimax/minimax-m3": {"context_window": 1048576}, + "openrouter/mistralai/codestral-2508": {"context_window": 256000}, + "openrouter/mistralai/devstral-2512": {"context_window": 262144}, + "openrouter/mistralai/ministral-14b-2512": {"context_window": 262144}, + "openrouter/mistralai/ministral-3b-2512": {"context_window": 131072}, + "openrouter/mistralai/ministral-8b-2512": {"context_window": 262144}, + "openrouter/mistralai/mistral-large": {"context_window": 128000}, + "openrouter/mistralai/mistral-large-2407": {"context_window": 131072}, + "openrouter/mistralai/mistral-large-2512": {"context_window": 262144}, + "openrouter/mistralai/mistral-large-4-0": {"context_window": 1048576}, + "openrouter/mistralai/mistral-medium-3": {"context_window": 131072}, + "openrouter/mistralai/mistral-medium-3-5": {"context_window": 262144}, + "openrouter/mistralai/mistral-medium-3.1": {"context_window": 131072}, + "openrouter/mistralai/mistral-nemo": {"context_window": 131072}, + "openrouter/mistralai/mistral-saba": {"context_window": 32768}, + "openrouter/mistralai/mistral-small-24b-instruct-2501": {"context_window": 32768}, + "openrouter/mistralai/mistral-small-2603": {"context_window": 262144}, + "openrouter/mistralai/mistral-small-3.1-24b-instruct": {"context_window": 128000}, + "openrouter/mistralai/mistral-small-3.2-24b-instruct": {"context_window": 256000}, + "openrouter/mistralai/mixtral-8x22b-instruct": {"context_window": 65536}, + "openrouter/mistralai/voxtral-small-24b-2507": {"context_window": 32768}, + "openrouter/moondream/moondream3-preview": {"context_window": 32000}, + "openrouter/moondream/moondream3.1-9b-a2b": {"context_window": 32000}, + "openrouter/moonshotai/kimi-k2": {"context_window": 131072}, + "openrouter/moonshotai/kimi-k2-0905": {"context_window": 262144}, + "openrouter/moonshotai/kimi-k2-thinking": {"context_window": 262144}, + "openrouter/moonshotai/kimi-k2.5": {"context_window": 262144}, + "openrouter/moonshotai/kimi-k2.6": {"context_window": 262144}, + "openrouter/moonshotai/kimi-k2.7-code": {"context_window": 262144}, + "openrouter/moonshotai/kimi-k3": {"context_window": 1048576}, + "openrouter/morph/morph-v3-fast": {"context_window": 81920}, + "openrouter/morph/morph-v3-large": {"context_window": 262144}, + "openrouter/nex-agi/nex-n2.5-mini": {"context_window": 262144}, + "openrouter/nex-agi/nex-n2.5-pro": {"context_window": 262144}, + "openrouter/nousresearch/hermes-3-llama-3.1-405b": {"context_window": 131072}, + "openrouter/nousresearch/hermes-3-llama-3.1-70b": {"context_window": 131072}, + "openrouter/nousresearch/hermes-4-405b": {"context_window": 131072}, + "openrouter/nvidia/nemotron-3-nano-30b-a3b": {"context_window": 262144}, + "openrouter/nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free": {"context_window": 256000}, + "openrouter/nvidia/nemotron-3-super-120b-a12b": {"context_window": 262144}, + "openrouter/nvidia/nemotron-3-super-120b-a12b:free": {"context_window": 262144}, + "openrouter/nvidia/nemotron-3-ultra-550b-a55b": {"context_window": 262144}, + "openrouter/nvidia/nemotron-3-ultra-550b-a55b:free": {"context_window": 1000000}, + "openrouter/nvidia/nemotron-3.5-content-safety": {"context_window": 131072}, + "openrouter/nvidia/nemotron-3.5-content-safety:free": {"context_window": 128000}, + "openrouter/nvidia/nemotron-3.5-lightning": {"context_window": 262144}, + "openrouter/nvidia/nemotron-3.5-lightning:free": {"context_window": 1000000}, + "openrouter/nvidia/nemotron-3.5-super-vl": {"context_window": 1048576}, + "openrouter/nvidia/nemotron-3.5-super-vl:free": {"context_window": 1000000}, + "openrouter/openai/gpt-3.5-turbo": {"context_window": 16385}, + "openrouter/openai/gpt-3.5-turbo-0613": {"context_window": 4095}, + "openrouter/openai/gpt-3.5-turbo-16k": {"context_window": 16385}, + "openrouter/openai/gpt-3.5-turbo-instruct": {"context_window": 4095}, + "openrouter/openai/gpt-4": {"context_window": 8191}, + "openrouter/openai/gpt-4-turbo": {"context_window": 128000}, + "openrouter/openai/gpt-4.1": {"context_window": 1047576}, + "openrouter/openai/gpt-4.1-mini": {"context_window": 1047576}, + "openrouter/openai/gpt-4.1-nano": {"context_window": 1047576}, + "openrouter/openai/gpt-4o": {"context_window": 128000}, + "openrouter/openai/gpt-4o-2024-05-13": {"context_window": 128000}, + "openrouter/openai/gpt-4o-2024-08-06": {"context_window": 128000}, + "openrouter/openai/gpt-4o-2024-11-20": {"context_window": 128000}, + "openrouter/openai/gpt-4o-mini": {"context_window": 128000}, + "openrouter/openai/gpt-4o-mini-2024-07-18": {"context_window": 128000}, + "openrouter/openai/gpt-5": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5-image": {"context_window": 400000}, + "openrouter/openai/gpt-5-image-mini": {"context_window": 400000}, + "openrouter/openai/gpt-5-mini": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5-nano": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5-pro": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.1": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.1-codex": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.1-codex-max": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.1-codex-mini": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.2": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.2-chat": {"context_window": 128000}, + "openrouter/openai/gpt-5.2-codex": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.2-pro": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.3-codex": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.4": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.4-image-2": {"context_window": 272000}, + "openrouter/openai/gpt-5.4-mini": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.4-nano": {"context_window": 400000, "max_input_tokens": 272000}, + "openrouter/openai/gpt-5.4-pro": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.5": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.5-pro": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.6-luna-pro": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.6-sol-pro": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-5.6-terra-pro": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-6-astra-pro": {"context_window": 1050000}, + "openrouter/openai/gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-6-luna-pro": {"context_window": 1050000}, + "openrouter/openai/gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-6-sol-pro": {"context_window": 1050000}, + "openrouter/openai/gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "openrouter/openai/gpt-6.1-sol-pro": {"context_window": 1050000}, + "openrouter/openai/gpt-audio": {"context_window": 128000}, + "openrouter/openai/gpt-audio-mini": {"context_window": 128000}, + "openrouter/openai/gpt-chat-latest": {"context_window": 400000}, + "openrouter/openai/gpt-oss-120b": {"context_window": 131072}, + "openrouter/openai/gpt-oss-20b": {"context_window": 131072}, + "openrouter/openai/gpt-oss-safeguard-20b": {"context_window": 131072}, + "openrouter/openai/o1": {"context_window": 200000}, + "openrouter/openai/o1-pro": {"context_window": 200000}, + "openrouter/openai/o3": {"context_window": 200000}, + "openrouter/openai/o3-mini": {"context_window": 200000}, + "openrouter/openai/o3-mini-high": {"context_window": 200000}, + "openrouter/openai/o3-pro": {"context_window": 200000}, + "openrouter/openai/o4-mini": {"context_window": 200000}, + "openrouter/openai/o4-mini-high": {"context_window": 200000}, + "openrouter/openrouter/auto": {"context_window": 2000000}, + "openrouter/openrouter/bodybuilder": {"context_window": 128000}, + "openrouter/openrouter/free": {"context_window": 200000}, + "openrouter/openrouter/fusion": {"context_window": 1000000}, + "openrouter/openrouter/pareto-code": {"context_window": 2000000}, + "openrouter/perceptron/perceptron-mk1": {"context_window": 32768}, + "openrouter/perceptron/perceptron-mk1.5": {"context_window": 36864}, + "openrouter/perplexity/sonar": {"context_window": 127072}, + "openrouter/perplexity/sonar-deep-research": {"context_window": 128000}, + "openrouter/perplexity/sonar-pro": {"context_window": 200000}, + "openrouter/perplexity/sonar-pro-search": {"context_window": 200000}, + "openrouter/perplexity/sonar-reasoning-pro": {"context_window": 128000}, + "openrouter/poolside/laguna-s-2.1": {"context_window": 1048576}, + "openrouter/poolside/laguna-s-2.1:free": {"context_window": 262144}, + "openrouter/poolside/laguna-xs-2.1": {"context_window": 262144}, + "openrouter/poolside/laguna-xs-2.1:free": {"context_window": 262144}, + "openrouter/prism-ml/ternary-bonsai-2-27b": {"context_window": 262144}, + "openrouter/qwen/qwen-2.5-72b-instruct": {"context_window": 32768}, + "openrouter/qwen/qwen-2.5-7b-instruct": {"context_window": 32768}, + "openrouter/qwen/qwen-2.5-coder-32b-instruct": {"context_window": 32768}, + "openrouter/qwen/qwen-plus": {"context_window": 1000000}, + "openrouter/qwen/qwen2.5-vl-72b-instruct": {"context_window": 128000}, + "openrouter/qwen/qwen3-14b": {"context_window": 40960}, + "openrouter/qwen/qwen3-235b-a22b-2507": {"context_window": 262144}, + "openrouter/qwen/qwen3-235b-a22b-thinking-2507": {"context_window": 128000}, + "openrouter/qwen/qwen3-30b-a3b": {"context_window": 40960}, + "openrouter/qwen/qwen3-30b-a3b-instruct-2507": {"context_window": 262144}, + "openrouter/qwen/qwen3-32b": {"context_window": 131072}, + "openrouter/qwen/qwen3-coder": {"context_window": 262144}, + "openrouter/qwen/qwen3-coder-30b-a3b-instruct": {"context_window": 262144}, + "openrouter/qwen/qwen3-coder-flash": {"context_window": 1000000}, + "openrouter/qwen/qwen3-coder-next": {"context_window": 262144}, + "openrouter/qwen/qwen3-next-80b-a3b-instruct": {"context_window": 262144}, + "openrouter/qwen/qwen3-next-80b-a3b-thinking": {"context_window": 262144}, + "openrouter/qwen/qwen3-vl-235b-a22b-instruct": {"context_window": 262144}, + "openrouter/qwen/qwen3-vl-30b-a3b-instruct": {"context_window": 262144}, + "openrouter/qwen/qwen3-vl-30b-a3b-thinking": {"context_window": 262144}, + "openrouter/qwen/qwen3-vl-8b-instruct": {"context_window": 262144}, + "openrouter/qwen/qwen3.5-122b-a10b": {"context_window": 262144}, + "openrouter/qwen/qwen3.5-27b": {"context_window": 262144}, + "openrouter/qwen/qwen3.5-35b-a3b": {"context_window": 262144}, + "openrouter/qwen/qwen3.5-397b-a17b": {"context_window": 262144}, + "openrouter/qwen/qwen3.5-9b": {"context_window": 262144}, + "openrouter/qwen/qwen3.5-flash-02-23": {"context_window": 1000000}, + "openrouter/qwen/qwen3.5-plus-02-15": {"context_window": 1000000}, + "openrouter/qwen/qwen3.5-plus-20260420": {"context_window": 1000000}, + "openrouter/qwen/qwen3.6-27b": {"context_window": 262144}, + "openrouter/qwen/qwen3.6-35b-a3b": {"context_window": 262144}, + "openrouter/qwen/qwen3.6-flash": {"context_window": 1000000}, + "openrouter/qwen/qwen3.6-plus": {"context_window": 1000000}, + "openrouter/qwen/qwen3.7-flash": {"context_window": 1000000, "max_input_tokens": 991808}, + "openrouter/qwen/qwen3.7-max": {"context_window": 1000000}, + "openrouter/qwen/qwen3.7-plus": {"context_window": 1000000}, + "openrouter/qwen/qwen3.8-2.4t-a95b": {"context_window": 1048576}, + "openrouter/qwen/qwen3.8-27b": {"context_window": 1000000}, + "openrouter/qwen/qwen3.8-flash": {"context_window": 1000000}, + "openrouter/qwen/qwen3.8-max-0902": {"context_window": 1000000}, + "openrouter/qwen/qwen3.8-max-prime": {"context_window": 1000000}, + "openrouter/qwen/qwen3.8-omni-flash": {"context_window": 1000000}, + "openrouter/reflection/beam-1.0-501b-a23b": {"context_window": 1048576}, + "openrouter/rekaai/reka-edge": {"context_window": 16384}, + "openrouter/rekaai/reka-flash-3": {"context_window": 65536}, + "openrouter/relace/relace-apply-3": {"context_window": 256000}, + "openrouter/relace/relace-search": {"context_window": 256000}, + "openrouter/sakana/fugu-max": {"context_window": 1000000}, + "openrouter/sakana/fugu-ultra": {"context_window": 1000000}, + "openrouter/sakana/fugu-ultra-v2": {"context_window": 1000000}, + "openrouter/sakana/sakana-namazu": {"context_window": 262144}, + "openrouter/sao10k/l3-lunaris-8b": {"context_window": 8192}, + "openrouter/sao10k/l3.1-euryale-70b": {"context_window": 131072}, + "openrouter/sao10k/l3.3-euryale-70b": {"context_window": 131072}, + "openrouter/scaledown/extract": {"context_window": 1000000}, + "openrouter/scaledown/summarize": {"context_window": 1000000}, + "openrouter/stepfun/step-3.5-flash": {"context_window": 262144}, + "openrouter/stepfun/step-3.7-flash": {"context_window": 262144, "max_input_tokens": 256000}, + "openrouter/stepfun/step-5-preview": {"context_window": 1048576, "max_input_tokens": 1000000}, + "openrouter/tencent/hunyuan-a13b-instruct": {"context_window": 131072}, + "openrouter/tencent/hy-mt2-1.8b": {"context_window": 8192}, + "openrouter/tencent/hy-mt2-30b-a3b": {"context_window": 8192}, + "openrouter/tencent/hy-mt2-7b": {"context_window": 8192}, + "openrouter/tencent/hy3": {"context_window": 262144, "max_input_tokens": 192000}, + "openrouter/tencent/hy3-preview": {"context_window": 262144}, + "openrouter/tencent/hy4-preview": {"context_window": 1048576}, + "openrouter/thedrummer/cydonia-24b-v4.1": {"context_window": 131072}, + "openrouter/thedrummer/skyfall-36b-v2": {"context_window": 32768}, + "openrouter/thedrummer/unslopnemo-12b": {"context_window": 1024000}, + "openrouter/thinkingmachines/inkling": {"context_window": 524288}, + "openrouter/thinkingmachines/inkling-small": {"context_window": 524288}, + "openrouter/thinkingmachines/inkling-small:free": {"context_window": 1048576}, + "openrouter/thinkingmachines/inkling:free": {"context_window": 1048576}, + "openrouter/unbiased/pareto-26.9": {"context_window": 262144}, + "openrouter/undi95/remm-slerp-l2-13b": {"context_window": 6144}, + "openrouter/upstage/solar-mini4": {"context_window": 524288}, + "openrouter/upstage/solar-pro-3": {"context_window": 131072}, + "openrouter/upstage/solar-pro4": {"context_window": 524288}, + "openrouter/writer/palmyra-x5": {"context_window": 1040000}, + "openrouter/x-ai/grok-4.20": {"context_window": 2000000}, + "openrouter/x-ai/grok-4.20-multi-agent": {"context_window": 2000000}, + "openrouter/x-ai/grok-4.3": {"context_window": 1000000}, + "openrouter/x-ai/grok-4.5": {"context_window": 500000}, + "openrouter/x-ai/grok-4.6": {"context_window": 500000}, + "openrouter/x-ai/grok-4.7": {"context_window": 500000}, + "openrouter/x-ai/grok-build-0.1": {"context_window": 256000}, + "openrouter/xiaomi/mimo-v2.5": {"context_window": 1050000}, + "openrouter/xiaomi/mimo-v2.5-pro": {"context_window": 1050000}, + "openrouter/xiaomi/mimo-v2.6-flash": {"context_window": 1050000}, + "openrouter/xiaomi/mimo-v2.6-pro": {"context_window": 1050000}, + "openrouter/xiaomi/mimo-v2.6-pro-ultraspeed": {"context_window": 1048576}, + "openrouter/xingchen-agi/xing4.0-29b-a4b:free": {"context_window": 262144}, + "openrouter/z-ai/glm-4.5": {"context_window": 131072}, + "openrouter/z-ai/glm-4.5-air": {"context_window": 131072}, + "openrouter/z-ai/glm-4.5v": {"context_window": 65536}, + "openrouter/z-ai/glm-4.6": {"context_window": 204800}, + "openrouter/z-ai/glm-4.6v": {"context_window": 131072}, + "openrouter/z-ai/glm-4.7": {"context_window": 204800}, + "openrouter/z-ai/glm-4.7-flash": {"context_window": 200000}, + "openrouter/z-ai/glm-5": {"context_window": 204800}, + "openrouter/z-ai/glm-5-turbo": {"context_window": 202752}, + "openrouter/z-ai/glm-5.1": {"context_window": 204800}, + "openrouter/z-ai/glm-5.2": {"context_window": 1048576}, + "openrouter/z-ai/glm-5.3": {"context_window": 1048576}, + "openrouter/z-ai/glm-5.3-flash": {"context_window": 1048576}, + "openrouter/z-ai/glm-5.3-flashx": {"context_window": 1048576}, + "openrouter/z-ai/glm-5.3-prime": {"context_window": 1000000}, + "openrouter/z-ai/glm-5v-turbo": {"context_window": 202752}, + "openrouter/~anthropic/claude-fable-latest": {"context_window": 1000000}, + "openrouter/~anthropic/claude-haiku-latest": {"context_window": 1000000}, + "openrouter/~anthropic/claude-opus-latest": {"context_window": 1000000}, + "openrouter/~anthropic/claude-sonnet-latest": {"context_window": 1000000}, + "openrouter/~deepseek/deepseek-flash-latest": {"context_window": 1048576}, + "openrouter/~deepseek/deepseek-pro-latest": {"context_window": 1048576}, + "openrouter/~deepseek/deepseek-v4-flash-latest": {"context_window": 1048576}, + "openrouter/~google/gemini-flash-latest": {"context_window": 1048576}, + "openrouter/~google/gemini-pro-latest": {"context_window": 1048576}, + "openrouter/~moonshotai/kimi-latest": {"context_window": 1048576}, + "openrouter/~openai/gpt-astra-latest": {"context_window": 1050000}, + "openrouter/~openai/gpt-luna-latest": {"context_window": 1050000}, + "openrouter/~openai/gpt-mini-latest": {"context_window": 400000}, + "openrouter/~openai/gpt-sol-latest": {"context_window": 1050000}, + "openrouter/~openai/gpt-terra-latest": {"context_window": 1050000}, + "openrouter/~unbiased/pareto-latest": {"context_window": 262144}, + "openrouter/~x-ai/grok-latest": {"context_window": 500000}, + "openrouter/~z-ai/glm-flash-latest": {"context_window": 1048576}, + "openrouter/~z-ai/glm-latest": {"context_window": 1048576}, + "perplexity/sonar": {"context_window": 128000}, + "perplexity/sonar-deep-research": {"context_window": 128000}, + "perplexity/sonar-pro": {"context_window": 200000}, + "perplexity/sonar-reasoning-pro": {"context_window": 128000}, + "qwen/deepseek-v4-flash-0731": {"context_window": 1000000}, + "qwen/glm-5.2": {"context_window": 1000000}, + "qwen/kimi-k3": {"context_window": 1048576}, + "qwen/qvq-max": {"context_window": 131072}, + "qwen/qwen-flash": {"context_window": 1000000}, + "qwen/qwen-max": {"context_window": 32768}, + "qwen/qwen-mt-plus": {"context_window": 16384}, + "qwen/qwen-mt-turbo": {"context_window": 16384}, + "qwen/qwen-omni-turbo": {"context_window": 32768}, + "qwen/qwen-omni-turbo-realtime": {"context_window": 32768}, + "qwen/qwen-plus": {"context_window": 1000000}, + "qwen/qwen-plus-character-ja": {"context_window": 8192}, + "qwen/qwen-turbo": {"context_window": 1000000}, + "qwen/qwen-vl-max": {"context_window": 131072}, + "qwen/qwen-vl-ocr": {"context_window": 34096}, + "qwen/qwen-vl-plus": {"context_window": 131072}, + "qwen/qwen2-5-14b-instruct": {"context_window": 131072}, + "qwen/qwen2-5-32b-instruct": {"context_window": 131072}, + "qwen/qwen2-5-72b-instruct": {"context_window": 131072}, + "qwen/qwen2-5-7b-instruct": {"context_window": 131072}, + "qwen/qwen2-5-omni-7b": {"context_window": 32768}, + "qwen/qwen2-5-vl-72b-instruct": {"context_window": 131072}, + "qwen/qwen2-5-vl-7b-instruct": {"context_window": 131072}, + "qwen/qwen3-14b": {"context_window": 131072}, + "qwen/qwen3-235b-a22b": {"context_window": 131072}, + "qwen/qwen3-32b": {"context_window": 131072}, + "qwen/qwen3-8b": {"context_window": 131072}, + "qwen/qwen3-asr-flash": {"context_window": 53248}, + "qwen/qwen3-coder-30b-a3b-instruct": {"context_window": 262144}, + "qwen/qwen3-coder-480b-a35b-instruct": {"context_window": 262144}, + "qwen/qwen3-coder-flash": {"context_window": 1000000}, + "qwen/qwen3-coder-plus": {"context_window": 1048576}, + "qwen/qwen3-livetranslate-flash-realtime": {"context_window": 53248}, + "qwen/qwen3-max": {"context_window": 262144}, + "qwen/qwen3-next-80b-a3b-instruct": {"context_window": 131072}, + "qwen/qwen3-next-80b-a3b-thinking": {"context_window": 131072}, + "qwen/qwen3-omni-flash": {"context_window": 65536}, + "qwen/qwen3-omni-flash-realtime": {"context_window": 65536}, + "qwen/qwen3-vl-235b-a22b": {"context_window": 131072}, + "qwen/qwen3-vl-30b-a3b": {"context_window": 131072}, + "qwen/qwen3-vl-plus": {"context_window": 262144}, + "qwen/qwen3.5-122b-a10b": {"context_window": 262144}, + "qwen/qwen3.5-27b": {"context_window": 262144}, + "qwen/qwen3.5-35b-a3b": {"context_window": 262144}, + "qwen/qwen3.5-397b-a17b": {"context_window": 262144}, + "qwen/qwen3.5-flash": {"context_window": 1000000}, + "qwen/qwen3.5-plus": {"context_window": 1000000}, + "qwen/qwen3.6-27b": {"context_window": 262144}, + "qwen/qwen3.6-35b-a3b": {"context_window": 262144}, + "qwen/qwen3.6-flash": {"context_window": 1000000}, + "qwen/qwen3.6-max-preview": {"context_window": 262144}, + "qwen/qwen3.6-plus": {"context_window": 1000000}, + "qwen/qwen3.7-flash": {"context_window": 1000000, "max_input_tokens": 991808}, + "qwen/qwen3.7-max": {"context_window": 1000000}, + "qwen/qwen3.7-plus": {"context_window": 1000000}, + "qwen/qwen3.8-flash": {"context_window": 1000000}, + "qwen/qwen3.8-max": {"context_window": 1000000}, + "qwen/qwen3.8-omni-flash": {"context_window": 1000000}, + "qwen/qwq-plus": {"context_window": 131072}, + "together/LiquidAI/LFM2-24B-A2B": {"context_window": 32768}, + "together/MiniMaxAI/MiniMax-M2.5": {"context_window": 204800}, + "together/MiniMaxAI/MiniMax-M2.7": {"context_window": 196608}, + "together/MiniMaxAI/MiniMax-M3": {"context_window": 524288}, + "together/Qwen/Qwen2.5-7B-Instruct-Turbo": {"context_window": 32768}, + "together/Qwen/Qwen3-235B-A22B-Instruct-2507-tput": {"context_window": 262144}, + "together/Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": {"context_window": 262144}, + "together/Qwen/Qwen3-Coder-Next-FP8": {"context_window": 262144}, + "together/Qwen/Qwen3.5-397B-A17B": {"context_window": 262144}, + "together/Qwen/Qwen3.5-9B": {"context_window": 262144}, + "together/Qwen/Qwen3.6-Plus": {"context_window": 1000000}, + "together/Qwen/Qwen3.7-Max": {"context_window": 1000000}, + "together/deepseek-ai/DeepSeek-R1": {"context_window": 163839}, + "together/deepseek-ai/DeepSeek-V3": {"context_window": 131072}, + "together/deepseek-ai/DeepSeek-V3-1": {"context_window": 131072}, + "together/deepseek-ai/DeepSeek-V4-Flash-0731": {"context_window": 1048576}, + "together/deepseek-ai/DeepSeek-V4-Pro-0813": {"context_window": 1048576}, + "together/deepseek-ai/DeepSeek-V4.1-Flash": {"context_window": 1048576}, + "together/essentialai/Rnj-1-Instruct": {"context_window": 32768}, + "together/meta-llama/Llama-3.3-70B-Instruct-Turbo": {"context_window": 131072}, + "together/moonshotai/Kimi-K3": {"context_window": 1048576}, + "together/nvidia/nemotron-3-ultra-550b-a55b": {"context_window": 512300}, + "together/openai/gpt-oss-120b": {"context_window": 131072}, + "together/thinkingmachines/Inkling": {"context_window": 524288}, + "together/zai-org/GLM-5": {"context_window": 202752}, + "together/zai-org/GLM-5.1": {"context_window": 202752}, + "together/zai-org/GLM-5.2": {"context_window": 1048575}, + "together/zai-org/GLM-5.3": {"context_window": 1048576}, + "together/zai-org/GLM-5.3-Flash": {"context_window": 1048575} + } +} diff --git a/agent_core/core/models/provider_config.py b/agent_core/core/models/provider_config.py index 2be66cff8..7075e4eb3 100644 --- a/agent_core/core/models/provider_config.py +++ b/agent_core/core/models/provider_config.py @@ -73,6 +73,14 @@ class ProviderProfile: # Frontend opts into the catalog-aware model picker (OpenRouter). supports_catalog_picker: bool = False + # ── model catalog (agent_core/core/models/catalog.py) ───────────── + # models.dev provider id whose rows scripts/gen_model_catalog.py copies + # into the model catalog for this provider (each model's context window + # and input limit). Must serve the same model ids at the same endpoint. + # None -> not catalogued, so settings.json model.context_window applies: + # local servers run whatever window the user loaded. + catalog_provider: Optional[str] = None + # ── models ──────────────────────────────────────────────────────── # {InterfaceType: default model id} (was MODEL_REGISTRY row). default_models: Mapping[InterfaceType, Optional[str]] = field(default_factory=dict) @@ -94,6 +102,12 @@ class ProviderProfile: # providers that already receive it today (NFR-3: golden payloads # must not change). supports_prompt_cache_key: bool = False + # Whether responses report how many input tokens came from the provider's + # cache. False -> the cached count is always 0 whatever the provider did + # (Fireworks puts it in a header only; HF-router, hosted NVIDIA NIM, + # Ollama and the local OpenAI-compatible servers by default omit it), so + # a cache hit rate cannot be shown for it. + reports_cached_tokens: bool = True # Temperature policy for the chat_completions wire (Hermes-style): # None -> send the caller's temperature (default behavior) # OMIT_TEMPERATURE -> do NOT send temperature (Kimi/Moonshot thinking @@ -172,6 +186,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): PROVIDER_CONFIG: Dict[str, ProviderProfile] = { "openai": ProviderProfile( key="openai", + catalog_provider="openai", session_accumulation=True, api_key_env="OPENAI_API_KEY", display_name="OpenAI", @@ -219,6 +234,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "gemini": ProviderProfile( key="gemini", + catalog_provider="google", api_key_env="GOOGLE_API_KEY", display_name="Google Gemini", wire="gemini_native", @@ -234,6 +250,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "anthropic": ProviderProfile( key="anthropic", + catalog_provider="anthropic", api_key_env="ANTHROPIC_API_KEY", display_name="Anthropic", wire="anthropic_messages", @@ -251,6 +268,8 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "byteplus": ProviderProfile( key="byteplus", + # No catalog_provider: models.dev lists only the China Volcengine + # endpoint, whose doubao-* ids are not the international ids below. api_key_env="BYTEPLUS_API_KEY", base_url_env="BYTEPLUS_BASE_URL", default_base_url="https://ark.ap-southeast.bytepluses.com/api/v3", @@ -272,6 +291,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "remote": ProviderProfile( key="remote", + reports_cached_tokens=False, base_url_env="REMOTE_MODEL_URL", default_base_url="http://localhost:11434", display_name="Local (Ollama)", @@ -288,6 +308,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "minimax": ProviderProfile( key="minimax", + catalog_provider="minimax", api_key_env="MINIMAX_API_KEY", # International OpenAI-compatible endpoint (verified 2026-08-17: # platform.minimax.io). The old api.minimax.chat domain is RETIRED. @@ -328,6 +349,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "deepseek": ProviderProfile( key="deepseek", + catalog_provider="deepseek", session_accumulation=True, api_key_env="DEEPSEEK_API_KEY", default_base_url="https://api.deepseek.com", @@ -346,6 +368,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "moonshot": ProviderProfile( key="moonshot", + catalog_provider="moonshotai", api_key_env="MOONSHOT_API_KEY", # International endpoint (verified 2026-08-17: platform.kimi.ai). base_url_env="MOONSHOT_BASE_URL", @@ -382,6 +405,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "grok": ProviderProfile( key="grok", + catalog_provider="xai", session_accumulation=True, api_key_env="XAI_API_KEY", default_base_url="https://api.x.ai/v1", @@ -404,6 +428,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "glm": ProviderProfile( key="glm", + catalog_provider="zai", session_accumulation=True, # Z.ai (Zhipu AI) GLM models -- OpenAI-compatible API. api_key_env="ZAI_API_KEY", @@ -424,6 +449,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "fugu": ProviderProfile( key="fugu", + catalog_provider="sakana", session_accumulation=True, # Sakana AI Fugu -- OpenAI-compatible API. api_key_env="SAKANA_API_KEY", @@ -444,6 +470,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "openrouter": ProviderProfile( key="openrouter", + catalog_provider="openrouter", session_accumulation=True, api_key_env="OPENROUTER_API_KEY", base_url_env="OPENROUTER_BASE_URL", @@ -466,6 +493,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "bedrock": ProviderProfile( key="bedrock", + catalog_provider="amazon-bedrock", # Bedrock uses the boto3 credential chain (access_key / secret_key / # session_token) read from settings.json by the factory. There is no # single API key, so api_key_env stays None. base_url_env carries the @@ -498,6 +526,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): # docs/PROVIDER_LAYER_CATCHUP.md section 8.3/8.4) ────────────────── "groq": ProviderProfile( key="groq", + catalog_provider="groq", session_accumulation=True, api_key_env="GROQ_API_KEY", base_url_env="GROQ_BASE_URL", @@ -526,6 +555,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "mistral": ProviderProfile( key="mistral", + catalog_provider="mistral", session_accumulation=True, api_key_env="MISTRAL_API_KEY", base_url_env="MISTRAL_BASE_URL", @@ -553,6 +583,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "together": ProviderProfile( key="together", + catalog_provider="togetherai", session_accumulation=True, api_key_env="TOGETHER_API_KEY", base_url_env="TOGETHER_BASE_URL", @@ -576,6 +607,8 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "fireworks": ProviderProfile( key="fireworks", + catalog_provider="fireworks-ai", + reports_cached_tokens=False, session_accumulation=True, api_key_env="FIREWORKS_API_KEY", base_url_env="FIREWORKS_BASE_URL", @@ -599,6 +632,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "cerebras": ProviderProfile( key="cerebras", + catalog_provider="cerebras", session_accumulation=True, api_key_env="CEREBRAS_API_KEY", base_url_env="CEREBRAS_BASE_URL", @@ -628,6 +662,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "qwen": ProviderProfile( key="qwen", + catalog_provider="alibaba", session_accumulation=True, api_key_env="DASHSCOPE_API_KEY", base_url_env="DASHSCOPE_BASE_URL", @@ -655,6 +690,8 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "huggingface": ProviderProfile( key="huggingface", + catalog_provider="huggingface", + reports_cached_tokens=False, session_accumulation=True, api_key_env="HF_TOKEN", base_url_env="HF_ROUTER_BASE_URL", @@ -677,6 +714,8 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "nvidia": ProviderProfile( key="nvidia", + catalog_provider="nvidia", + reports_cached_tokens=False, session_accumulation=True, api_key_env="NVIDIA_API_KEY", base_url_env="NVIDIA_BASE_URL", @@ -697,6 +736,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "perplexity": ProviderProfile( key="perplexity", + catalog_provider="perplexity", session_accumulation=True, api_key_env="PERPLEXITY_API_KEY", base_url_env="PERPLEXITY_BASE_URL", @@ -750,6 +790,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): # ), "lmstudio": ProviderProfile( key="lmstudio", + reports_cached_tokens=False, session_accumulation=True, base_url_env="LMSTUDIO_BASE_URL", default_base_url="http://localhost:1234/v1", @@ -778,6 +819,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "vllm": ProviderProfile( key="vllm", + reports_cached_tokens=False, session_accumulation=True, base_url_env="VLLM_BASE_URL", default_base_url="http://localhost:8000/v1", @@ -798,6 +840,7 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "llamacpp": ProviderProfile( key="llamacpp", + reports_cached_tokens=False, session_accumulation=True, base_url_env="LLAMACPP_BASE_URL", default_base_url="http://localhost:8080/v1", diff --git a/agent_file_system/AGENT.md b/agent_file_system/AGENT.md index c5a04597d..3228021da 100644 --- a/agent_file_system/AGENT.md +++ b/agent_file_system/AGENT.md @@ -1,5 +1,5 @@ --- -version: 11 +version: 13 purpose: agent operations manual --- @@ -487,8 +487,10 @@ SERVER provider 5xx, temporary Retryable. Usually transien CONNECTION timeout / network Retryable once connectivity is back. CONTEXT_ request exceeds context window Auto-handled: the harness folds (summarizes) OVERFLOW the event stream once, then retries. Still too - big means model.context_window is set too - small; surface that, do not hand-retry. + big means the request cannot fit the model's + window (for a model the catalog does not list, + model.context_window may be set too small); + surface that, do not hand-retry. BAD_REQUEST / other Investigate before retrying. UNKNOWN ``` @@ -1590,7 +1592,9 @@ Run `/help` for the live list. If you need to verify a specific command, read it ``` /help [command] list all commands, or detail one. Always available. /menu show the main menu (Browser mode only; hidden) -/clear (alias /cls) clear THIS session's conversation +/clear (alias /cls) start THIS session over: its conversation and your context of it + (event stream, todos, loaded skills, NOTE.md, EVENT.md) are cleared; + long-term memory stays /reset delete all chat sessions + clear action history/context /exit quit the application /update (alias /upgrade) check for updates and update CraftBot [--check] @@ -1672,7 +1676,7 @@ If a user types a slash command and you receive the resulting run or message: - The runtime processes the command BEFORE you see it. Your role is to react to its outcome, not to re-execute. - For `/`, the runtime starts a run with the skill pre-loaded. You take over from there. - For `/ connect` or `/cred status`, the result lands in the chat as text. The user may then ask you to do something with the now-connected integration. -- For `/clear`, `/reset`, `/exit`: state changes happen immediately. You may not have continuity with prior conversation after these. +- For `/clear`, `/reset`, `/exit`: state changes happen immediately. You have no continuity with the prior conversation after these; after `/clear` the session continues as a new one. --- @@ -1834,9 +1838,10 @@ memory: item_word_limit: int (default 150; words per stored memory item) processing_threshold: int (default 25; min total unprocessed events before a memory run fires) -context: (event-stream budget; a fold is decided on the WHOLE request) - reserve_tokens: int (default 16384; headroom the fold/summary request itself needs) - keep_recent_tokens: int (default 20000; recent events kept verbatim after a fold) +context: (event-stream budget; a fold is decided on the WHOLE request, + against the serving model's window less its output cap) + keep_recent_tokens: int (default 20000; most recent events kept verbatim after a fold, + never more than half the room the model's budget leaves) model: llm_provider: any provider key registered in the code (see ## Models); @@ -1848,9 +1853,10 @@ model: image_gen_model / video_gen_model: string | null slow_mode: bool (true throttles requests for rate-limited providers) slow_mode_tpm_limit: int (default 30000; tokens per minute when slow_mode is true) - context_window: int (default 128000; the configured model's context window in tokens; - drives the context-overflow fold; set it to match your model or - requests get force-summarized, then rejected. See ## Errors.) + context_window: int (default 128000; the context window, in tokens, of a model the + bundled model catalog does not list: local servers, custom + endpoints. Set it to the window the server loaded. A catalogued + model uses its own window and ignores this. See ## Errors.) api_keys: openai: string (sk-...) diff --git a/app/agent_base.py b/app/agent_base.py index f732f2923..16836ed79 100644 --- a/app/agent_base.py +++ b/app/agent_base.py @@ -548,12 +548,22 @@ async def delete_session(self, session_id: str) -> bool: return self.session_manager.delete_session(session_id) async def clear_session(self, session_id: str) -> bool: - """Clear a session's conversation (event stream, todos, budgets). + """Start a session over as a new session (/clear, the chat's clear). + + A run in flight is stopped first: it would otherwise carry on the old + work into the fresh session. Then the agent-side state is reset and + saved, event stream included (see SessionManager.clear_session), and + so is the LLM state, so a restart cannot bring the old one back. Chat-message rows are cleared by the adapter (chat storage is a UI concern); this handles the agent-side state. """ - return self.session_manager.clear_session(session_id) + if session_id in self.busy_sessions: + await self.request_run_stop(session_id) + if not self.session_manager.clear_session(session_id): + return False + self._persist_llm_session(session_id) + return True def close_ui_artifact(self, session_id: str, artifact_id: str) -> int: """The user closed a Generative UI output: the session's events keep @@ -1190,6 +1200,21 @@ def _persist_session_stream(self, session_id: str) -> None: logger.warning( f"[PERSIST] Event stream persist failed for {session_id}: {e}" ) + self._persist_llm_session(session_id) + + def _persist_llm_session(self, session_id: str) -> None: + """Save a session's LLM state (LLMInterface.export_session), so a + restart continues the session instead of starting a new prefix.""" + try: + from app.usage.session_storage import get_session_storage + + get_session_storage().persist_llm_session( + session_id, self.llm.export_session(session_id) + ) + except Exception as e: + logger.warning( + f"[PERSIST] LLM session persist failed for {session_id}: {e}" + ) def _invalidate_session_caches(self, session_id: str) -> None: """Rebuild a session's LLM caches after a capability change.""" @@ -1246,6 +1271,10 @@ async def _select_action(self, trigger_data: TriggerData) -> tuple[list, str]: query=trigger_data.query, session_id=trigger_data.session_id, ) + # The decision request's context size and cache use are recorded on + # the LLM interface now; send them to the chat input's reasoning menu. + if self.ui_controller: + await self.ui_controller.notify_session_updated(trigger_data.session_id) if not action_decisions: raise ValueError("Action router returned no decision.") @@ -3770,8 +3799,17 @@ def _restore_sessions(self) -> None: stream._total_tokens = sum( get_cached_token_count(r) for r in records ) - # The model read this history before the restart. - stream.mark_delivered() + # The LLM session comes back where the stream still holds + # what it covers, so the first request continues the + # session on the provider's cached prefix. + synced = self.llm.import_session( + session.id, storage.get_llm_session(session.id), stream + ) + # The model read this history before the restart: up to + # the sync point when the session continues (its next + # request sends the rest), all of it otherwise (its next + # request sends everything). + stream.mark_delivered(synced) logger.info( f"[RESTORE] Restored session '{session.title}' " @@ -3811,6 +3849,7 @@ def _persist_all_sessions(self) -> None: session_id, self.event_stream_manager.get_stream_by_id(session_id), ) + self._persist_llm_session(session_id) count += 1 except Exception as e: logger.warning( diff --git a/app/config.py b/app/config.py index 1aecf9341..756dbd702 100644 --- a/app/config.py +++ b/app/config.py @@ -63,10 +63,11 @@ def invalidate_settings_cache() -> None: # Context budget settings. The decision to summarize the event stream is made -# on the WHOLE request (see ActionRouter / LLMInterface.fits_context): -# model.context_window the model's window, in tokens -# context.reserve_tokens headroom the summary request itself needs -# context.keep_recent_tokens recent events kept verbatim after a fold +# on the WHOLE request against the serving model's own window, from the model +# catalog (see ActionRouter / LLMInterface.fits_context): +# model.context_window the window of a model the catalog does not +# list (local servers, custom endpoints) +# context.keep_recent_tokens most recent events kept verbatim after a fold # A key that is absent takes the shipped value from _get_default_settings(); # a key that is present but invalid is a ConfigurationError. @@ -89,7 +90,6 @@ def _get_default_settings() -> Dict[str, Any]: "proactive": {"enabled": True}, "memory": {"enabled": True}, "context": { - "reserve_tokens": 16384, "keep_recent_tokens": 20000, }, "model": { @@ -230,12 +230,13 @@ def _setting(section: str, key: str) -> Any: def get_context_window() -> int: - """The configured model's context window in tokens (model.context_window).""" + """Context window, in tokens, of a model the model catalog does not list + (model.context_window). A catalogued model uses its own window.""" value = _setting("model", "context_window") if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ConfigurationError( "settings.json model.context_window must be a positive integer: the " - "context window of the configured model, in tokens." + "context window, in tokens, of a model the model catalog does not list." ) return value @@ -249,13 +250,9 @@ def _get_positive_int(section: str, key: str) -> int: return value -def get_reserve_tokens() -> int: - """Headroom kept free for the summary request (context.reserve_tokens).""" - return _get_positive_int("context", "reserve_tokens") - - def get_keep_recent_tokens() -> int: - """Recent event-stream tokens kept verbatim after a fold (context.keep_recent_tokens).""" + """Most recent event-stream tokens kept verbatim after a fold + (context.keep_recent_tokens); a fold keeps less when the budget is tight.""" return _get_positive_int("context", "keep_recent_tokens") diff --git a/app/config/settings.json b/app/config/settings.json index dd5c5cb39..c9bd15ffa 100644 --- a/app/config/settings.json +++ b/app/config/settings.json @@ -16,7 +16,6 @@ "processing_threshold": 23 }, "context": { - "reserve_tokens": 16384, "keep_recent_tokens": 20000 }, "model": { diff --git a/app/data/agent_file_system_template/AGENT.md b/app/data/agent_file_system_template/AGENT.md index c5a04597d..3228021da 100644 --- a/app/data/agent_file_system_template/AGENT.md +++ b/app/data/agent_file_system_template/AGENT.md @@ -1,5 +1,5 @@ --- -version: 11 +version: 13 purpose: agent operations manual --- @@ -487,8 +487,10 @@ SERVER provider 5xx, temporary Retryable. Usually transien CONNECTION timeout / network Retryable once connectivity is back. CONTEXT_ request exceeds context window Auto-handled: the harness folds (summarizes) OVERFLOW the event stream once, then retries. Still too - big means model.context_window is set too - small; surface that, do not hand-retry. + big means the request cannot fit the model's + window (for a model the catalog does not list, + model.context_window may be set too small); + surface that, do not hand-retry. BAD_REQUEST / other Investigate before retrying. UNKNOWN ``` @@ -1590,7 +1592,9 @@ Run `/help` for the live list. If you need to verify a specific command, read it ``` /help [command] list all commands, or detail one. Always available. /menu show the main menu (Browser mode only; hidden) -/clear (alias /cls) clear THIS session's conversation +/clear (alias /cls) start THIS session over: its conversation and your context of it + (event stream, todos, loaded skills, NOTE.md, EVENT.md) are cleared; + long-term memory stays /reset delete all chat sessions + clear action history/context /exit quit the application /update (alias /upgrade) check for updates and update CraftBot [--check] @@ -1672,7 +1676,7 @@ If a user types a slash command and you receive the resulting run or message: - The runtime processes the command BEFORE you see it. Your role is to react to its outcome, not to re-execute. - For `/`, the runtime starts a run with the skill pre-loaded. You take over from there. - For `/ connect` or `/cred status`, the result lands in the chat as text. The user may then ask you to do something with the now-connected integration. -- For `/clear`, `/reset`, `/exit`: state changes happen immediately. You may not have continuity with prior conversation after these. +- For `/clear`, `/reset`, `/exit`: state changes happen immediately. You have no continuity with the prior conversation after these; after `/clear` the session continues as a new one. --- @@ -1834,9 +1838,10 @@ memory: item_word_limit: int (default 150; words per stored memory item) processing_threshold: int (default 25; min total unprocessed events before a memory run fires) -context: (event-stream budget; a fold is decided on the WHOLE request) - reserve_tokens: int (default 16384; headroom the fold/summary request itself needs) - keep_recent_tokens: int (default 20000; recent events kept verbatim after a fold) +context: (event-stream budget; a fold is decided on the WHOLE request, + against the serving model's window less its output cap) + keep_recent_tokens: int (default 20000; most recent events kept verbatim after a fold, + never more than half the room the model's budget leaves) model: llm_provider: any provider key registered in the code (see ## Models); @@ -1848,9 +1853,10 @@ model: image_gen_model / video_gen_model: string | null slow_mode: bool (true throttles requests for rate-limited providers) slow_mode_tpm_limit: int (default 30000; tokens per minute when slow_mode is true) - context_window: int (default 128000; the configured model's context window in tokens; - drives the context-overflow fold; set it to match your model or - requests get force-summarized, then rejected. See ## Errors.) + context_window: int (default 128000; the context window, in tokens, of a model the + bundled model catalog does not list: local servers, custom + endpoints. Set it to the window the server loaded. A catalogued + model uses its own window and ignores this. See ## Errors.) api_keys: openai: string (sk-...) diff --git a/app/session/session_manager.py b/app/session/session_manager.py index ad805c371..49ef8c8f9 100644 --- a/app/session/session_manager.py +++ b/app/session/session_manager.py @@ -169,6 +169,25 @@ def _prepare_workspace_dir(self, session_id: str) -> Path: ) return session_dir + def clear_session(self, session_id: str) -> bool: + """Start a session over, its workspace files included: NOTE.md goes + back to the fresh scratchpad and EVENT.md is emptied, as a new + session has them. Other files in the workspace (the user's) stay.""" + if not super().clear_session(session_id): + return False + session = self.get(session_id) + if session is not None and session.workspace_dir: + try: + (Path(session.workspace_dir) / "NOTE.md").write_text( + _NOTE_SCRATCHPAD_HEADER, encoding="utf-8" + ) + except OSError as e: + logger.warning( + f"[SessionManager] Failed to reset NOTE.md for {session_id}: {e}" + ) + self.event_stream_manager.clear_event_log(session_id) + return True + def add_post_update_todos_hook(self, hook: PostUpdateTodosHook) -> None: """Register a hook that fires after every update_todos call. diff --git a/app/ui_layer/adapters/browser_adapter.py b/app/ui_layer/adapters/browser_adapter.py index 8538bfd91..ab357d7f1 100644 --- a/app/ui_layer/adapters/browser_adapter.py +++ b/app/ui_layer/adapters/browser_adapter.py @@ -4349,9 +4349,13 @@ def _record_answer() -> list: # Session Handlers (sidebar surface) # ───────────────────────────────────────────────────────────────────── - @staticmethod - def _session_info(session) -> Dict[str, Any]: + def _session_info(self, session) -> Dict[str, Any]: """SessionInfo wire shape for a Session.""" + from agent_core.core.impl.llm import LLMCallType + + usage = self._controller.agent.llm.last_request( + session.id, LLMCallType.ACTION_SELECTION + ) return { "id": session.id, "type": session.type, @@ -4360,6 +4364,19 @@ def _session_info(session) -> Dict[str, Any]: "lastActiveAt": session.last_active_at, "agentAppProjectId": session.agent_app_project_id, "reasoningEffort": session.reasoning_effort, + # The last decision request, for the reasoning menu's context and + # cache readout; null until the session's first request. + "lastRequest": ( + { + "inputTokens": usage.input_tokens, + "cachedTokens": usage.cached_tokens, + "startedAt": round(usage.started_at * 1000), + "surface": usage.surface, + "model": usage.model, + } + if usage is not None + else None + ), } @staticmethod @@ -4431,10 +4448,23 @@ async def _handle_reasoning_options_get(self, ws) -> None: """ llm = self._controller.agent.llm options = llm.reasoning_options() + lifetime = llm.prompt_cache_lifetime() data: Dict[str, Any] = { "success": True, "model": llm.model, + "surface": llm.surface(), "configurable": options is not None, + # The input budget (where the event stream is summarized) at each + # choice: a reasoning level's output cap comes out of the window. + "inputBudgets": { + choice.value: llm.input_budget_for(choice) for choice in ReasoningChoice + }, + "cacheLifetime": ( + {"kind": lifetime.kind.value, "seconds": lifetime.seconds} + if lifetime is not None + else None + ), + "reportsCachedTokens": llm.reports_cached_tokens(), } if options is not None: data.update( @@ -4457,6 +4487,9 @@ async def _handle_session_clear(self, data: Dict[str, Any]) -> None: try: from app.usage import get_action_storage, get_chat_storage + # Agent side first: it stops a run in flight, whose last rows + # must go with the conversation rather than land after the clear. + await self._controller.agent.clear_session(session_id) try: # Ordered storage worker: runs after any insert still queued # for this session, so no message resurfaces after the clear. @@ -4469,7 +4502,6 @@ async def _handle_session_clear(self, data: Dict[str, Any]) -> None: get_action_storage().clear_items(session_id) except Exception: pass - await self._controller.agent.clear_session(session_id) await self.broadcast_session_cleared(session_id) except Exception as e: logger.error(f"[SESSION] Clear failed for {session_id}: {e}") @@ -4538,7 +4570,9 @@ async def broadcast_session_cleared(self, session_id: str) -> None: Called by the /clear command (which has already cleared storage and agent-side state) and by the session_clear handler. The activity - feed is part of the conversation, so its items go with it. + feed is part of the conversation, so its items go with it. The + session started over, so its info (a chat's title, the reasoning + menu's context readout) is sent again too. """ self._chat.drop_session_messages(session_id) self._action_panel.drop_session_items(session_id) @@ -4548,6 +4582,7 @@ async def broadcast_session_cleared(self, session_id: str) -> None: "data": {"sessionId": session_id}, } ) + await self.broadcast_session_updated(session_id) # ───────────────────────────────────────────────────────────────────── # Settings Operation Handlers diff --git a/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.module.css b/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.module.css index e0fcd8804..669901fab 100644 --- a/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.module.css +++ b/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.module.css @@ -100,3 +100,78 @@ font-size: 11px; line-height: 1.4; } + +/* A model whose reasoning is not adjustable: why there are no choices. */ +.notice { + padding: 2px 10px 6px; + color: var(--text-tertiary); + font-size: 11px; + line-height: 1.4; +} + +/* Context and cache readout under the choices (read-only, not hoverable). */ +.readout { + display: flex; + flex-direction: column; + gap: 6px; + margin-top: 4px; + padding: 8px 10px 6px; + border-top: 1px solid var(--border-primary); + font-size: var(--text-xs); +} + +.row { + display: flex; + align-items: center; + gap: var(--space-2); + color: var(--text-secondary); + white-space: nowrap; +} + +.rowIcon { + flex-shrink: 0; + color: var(--text-tertiary); +} + +.rowLabel { + flex: 1; +} + +.rowValue { + color: var(--text-primary); + font-variant-numeric: tabular-nums; +} + +.rowDetail { + color: var(--text-tertiary); + font-size: 11px; + font-variant-numeric: tabular-nums; +} + +.bar { + height: 4px; + border-radius: 2px; + background: var(--bg-tertiary); + overflow: hidden; +} + +.barFill { + height: 100%; + border-radius: 2px; + background: var(--color-success); + transition: width var(--transition-fast); +} + +.barWarn { + background: var(--color-warning); +} + +.barHigh { + background: var(--color-error); +} + +.caption { + margin-top: -2px; + color: var(--text-tertiary); + font-size: 11px; +} diff --git a/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.tsx b/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.tsx index 3e50a23a8..f26933f95 100644 --- a/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.tsx +++ b/app/ui_layer/browser/frontend/src/components/Chat/ReasoningPicker.tsx @@ -1,13 +1,15 @@ import { useEffect, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' -import { Brain, Check, ChevronDown } from 'lucide-react' -import type { ReasoningChoice } from '../../types' +import { Brain, Check, ChevronDown, DatabaseZap, Gauge, Timer } from 'lucide-react' +import type { LastRequest, ReasoningChoice } from '../../types' import { useWebSocket } from '../../contexts/WebSocketContext' import { usePersistedState } from '../../hooks' +import { formatNumber } from '../../i18n/format' import { useAppSelector } from '../../store/hooks' import { RESOURCES, useResource } from '../../store/resources' import { selectReasoningOptions } from '../../store/selectors/reasoning' import { selectSessionById } from '../../store/selectors/sessions' +import type { ReasoningOptions } from '../../store/slices/reasoningSlice' import { UI_STATE } from '../../store/uiState' import styles from './ReasoningPicker.module.css' @@ -25,6 +27,121 @@ const CHOICE_LABEL_KEYS = { const isReasoningChoice = (value: string): value is ReasoningChoice => Object.prototype.hasOwnProperty.call(CHOICE_LABEL_KEYS, value) +/** Context fill (of the summary point) where the bar turns amber, then red. */ +const CONTEXT_WARN = 0.7 +const CONTEXT_HIGH = 0.9 + +const compactTokens = (n: number): string => + formatNumber(n, { notation: 'compact', maximumFractionDigits: 1 }) + +const percent = (ratio: number): string => + formatNumber(ratio, { style: 'percent', maximumFractionDigits: 0 }) + +/** Remaining time as m:ss, or h:mm:ss from an hour up. */ +function formatRemaining(ms: number): string { + const total = Math.ceil(ms / 1000) + const h = Math.floor(total / 3600) + const m = Math.floor((total % 3600) / 60) + const s = String(total % 60).padStart(2, '0') + return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${s}` +} + +interface ContextReadoutProps { + options: ReasoningOptions + /** The choice the next request runs at (its budget applies). */ + choice: ReasoningChoice + lastRequest: LastRequest | null + /** The menu is open: tick the countdown. */ + live: boolean +} + +/** + * How full the session's context is and how its prompt cache stands, as of + * its last request. "Context" is that request's input against the budget at + * the current choice: the event stream is summarized when the next request + * would not fit. The cache belongs to the model that served the request, so + * after a model switch it reads as not cached yet. The countdown runs from + * the request's start over the provider's documented lifetime ("~" where the + * provider only gives a typical figure); providers that document none, or + * report no cached count, say so instead of showing a made-up number. + */ +function ContextReadout({ options, choice, lastRequest, live }: ContextReadoutProps) { + const { t } = useTranslation(['chat', 'common']) + const [now, setNow] = useState(() => Date.now()) + const lifetime = options.cacheLifetime + const cached = + lastRequest !== null && + lastRequest.surface === options.surface && + lastRequest.model === options.model + + useEffect(() => { + if (!live || !cached || lifetime === null) return + setNow(Date.now()) + const timer = window.setInterval(() => setNow(Date.now()), 1000) + return () => window.clearInterval(timer) + }, [live, cached, lifetime]) + + const budget = options.inputBudgets[choice] + const used = lastRequest?.inputTokens ?? null + const fill = used === null ? 0 : used / budget + const fillClass = + fill >= CONTEXT_HIGH ? styles.barHigh : fill >= CONTEXT_WARN ? styles.barWarn : '' + + let cacheValue: string + if (!cached) cacheValue = t('chat:reasoning.cache.notYet') + else if (!options.reportsCachedTokens) cacheValue = t('chat:reasoning.cache.notReported') + else + cacheValue = t('chat:reasoning.cache.hit', { + percent: percent(lastRequest.inputTokens > 0 ? lastRequest.cachedTokens / lastRequest.inputTokens : 0), + }) + + let expiryValue: string | null = null + if (cached) { + if (lifetime === null) expiryValue = t('chat:reasoning.cache.noExpiry') + else { + const remaining = lastRequest.startedAt + lifetime.seconds * 1000 - now + if (remaining <= 0) expiryValue = t('chat:reasoning.cache.expired') + else if (lifetime.kind === 'typical') + expiryValue = t('chat:reasoning.cache.about', { time: formatRemaining(remaining) }) + else expiryValue = formatRemaining(remaining) + } + } + + return ( +
+
+ + {t('chat:reasoning.context.label')} + + {used === null ? '–' : compactTokens(used)} / {compactTokens(budget)} + + {used !== null && {percent(fill)}} +
+
+
+
+
+ {t('chat:reasoning.context.summarizesAt', { max: compactTokens(budget) })} +
+
+ + {t('chat:reasoning.cache.label')} + {cacheValue} +
+ {expiryValue !== null && ( +
+ + {t('chat:reasoning.cache.timeLeft')} + {expiryValue} +
+ )} +
+ ) +} + interface ReasoningPickerProps { /** The chat this composer belongs to ('new' for the draft view). */ sessionId: string @@ -40,6 +157,9 @@ interface ReasoningPickerProps { * first message creates the session (untouched: the default level). A stored * choice the model lacks shows the level actually used instead (the backend * clamps it the way pi does and keeps the stored choice for other models). + * + * Below the choices, the chat's context and cache readout (ContextReadout). + * A model whose reasoning is not adjustable still opens the menu for it. */ export function ReasoningPicker({ sessionId }: ReasoningPickerProps) { const { t } = useTranslation(['chat', 'common']) @@ -55,6 +175,7 @@ export function ReasoningPicker({ sessionId }: ReasoningPickerProps) { // or the main session before the backend has sent it). const stored: ReasoningChoice | null = sessionId === 'new' ? draftChoice : (session?.reasoningEffort ?? null) + const lastRequest = session?.lastRequest ?? null useEffect(() => { if (!open) return @@ -72,19 +193,45 @@ export function ReasoningPicker({ sessionId }: ReasoningPickerProps) { const levelLabel = (value: string): string => isReasoningChoice(value) ? choiceLabel(value) : t('chat:reasoning.dynamic') - if (!options || !options.configurable) { + if (!options) { return (
+ +
+ ) + } + + if (!options.configurable) { + return ( +
+ {open && ( +
+
{t('chat:reasoning.header', { model: options.model })}
+
{t('chat:reasoning.notConfigurable', { model: options.model })}
+ +
+ )}
) } @@ -152,6 +299,7 @@ export function ReasoningPicker({ sessionId }: ReasoningPickerProps) { {t('chat:reasoning.clamped', { requested: choiceLabel(requested), effective: summary(effective) })}
)} + )} diff --git a/app/ui_layer/browser/frontend/src/components/layout/NavBar.tsx b/app/ui_layer/browser/frontend/src/components/layout/NavBar.tsx index a5509492e..14d4b66f4 100644 --- a/app/ui_layer/browser/frontend/src/components/layout/NavBar.tsx +++ b/app/ui_layer/browser/frontend/src/components/layout/NavBar.tsx @@ -789,6 +789,7 @@ export function NavBar({ collapsed = false, onToggleCollapsed }: NavBarProps) { createdAt: '', lastActiveAt: '', reasoningEffort: null, + lastRequest: null, } return ( diff --git a/app/ui_layer/browser/frontend/src/locales/en/chat.json b/app/ui_layer/browser/frontend/src/locales/en/chat.json index f37ce7688..f7fca2f1b 100644 --- a/app/ui_layer/browser/frontend/src/locales/en/chat.json +++ b/app/ui_layer/browser/frontend/src/locales/en/chat.json @@ -74,6 +74,20 @@ "defaultTag": "Default", "notConfigurable": "Reasoning isn't adjustable for {{model}}", "clamped": "{{requested}} isn't available on this model, so {{effective}} is used.", + "context": { + "label": "Context", + "summarizesAt": "Summarizes at {{max}}" + }, + "cache": { + "label": "Cache", + "hit": "{{percent}} cached", + "notReported": "Not reported", + "notYet": "Not cached yet", + "timeLeft": "Time left", + "about": "~{{time}}", + "expired": "Expired", + "noExpiry": "No fixed expiry" + }, "choice": { "provider_default": "Provider default", "off": "Off", diff --git a/app/ui_layer/browser/frontend/src/locales/es/chat.json b/app/ui_layer/browser/frontend/src/locales/es/chat.json index d5177215d..8c7ac5b31 100644 --- a/app/ui_layer/browser/frontend/src/locales/es/chat.json +++ b/app/ui_layer/browser/frontend/src/locales/es/chat.json @@ -40,6 +40,20 @@ "defaultTag": "Predeterminado", "notConfigurable": "El razonamiento no es ajustable en {{model}}", "clamped": "{{requested}} no está disponible en este modelo, así que se usa {{effective}}.", + "context": { + "label": "Contexto", + "summarizesAt": "Se resume al llegar a {{max}}" + }, + "cache": { + "label": "Caché", + "hit": "{{percent}} en caché", + "notReported": "No informado", + "notYet": "Aún sin caché", + "timeLeft": "Tiempo restante", + "about": "~{{time}}", + "expired": "Caducada", + "noExpiry": "Sin caducidad fija" + }, "choice": { "provider_default": "Predeterminado del proveedor", "off": "Desactivado", diff --git a/app/ui_layer/browser/frontend/src/locales/id/chat.json b/app/ui_layer/browser/frontend/src/locales/id/chat.json index 3eacc84ab..c1bf6195e 100644 --- a/app/ui_layer/browser/frontend/src/locales/id/chat.json +++ b/app/ui_layer/browser/frontend/src/locales/id/chat.json @@ -40,6 +40,20 @@ "defaultTag": "Bawaan", "notConfigurable": "Penalaran tidak dapat diatur untuk {{model}}", "clamped": "{{requested}} tidak tersedia pada model ini, jadi {{effective}} yang digunakan.", + "context": { + "label": "Konteks", + "summarizesAt": "Diringkas pada {{max}}" + }, + "cache": { + "label": "Cache", + "hit": "{{percent}} dari cache", + "notReported": "Tidak dilaporkan", + "notYet": "Belum ada cache", + "timeLeft": "Sisa waktu", + "about": "~{{time}}", + "expired": "Kedaluwarsa", + "noExpiry": "Tanpa batas waktu tetap" + }, "choice": { "provider_default": "Bawaan penyedia", "off": "Mati", diff --git a/app/ui_layer/browser/frontend/src/locales/ja/chat.json b/app/ui_layer/browser/frontend/src/locales/ja/chat.json index f894ad383..a8e44aada 100644 --- a/app/ui_layer/browser/frontend/src/locales/ja/chat.json +++ b/app/ui_layer/browser/frontend/src/locales/ja/chat.json @@ -40,6 +40,20 @@ "defaultTag": "既定", "notConfigurable": "{{model}} では推論を調整できません", "clamped": "{{requested}} はこのモデルでは使えないため、{{effective}} を使用します。", + "context": { + "label": "コンテキスト", + "summarizesAt": "{{max}} で要約" + }, + "cache": { + "label": "キャッシュ", + "hit": "{{percent}} キャッシュ済み", + "notReported": "報告なし", + "notYet": "まだキャッシュなし", + "timeLeft": "残り時間", + "about": "~{{time}}", + "expired": "期限切れ", + "noExpiry": "有効期限なし" + }, "choice": { "provider_default": "プロバイダーの既定", "off": "オフ", diff --git a/app/ui_layer/browser/frontend/src/locales/ko/chat.json b/app/ui_layer/browser/frontend/src/locales/ko/chat.json index 6600f6766..7e91cc04a 100644 --- a/app/ui_layer/browser/frontend/src/locales/ko/chat.json +++ b/app/ui_layer/browser/frontend/src/locales/ko/chat.json @@ -40,6 +40,20 @@ "defaultTag": "기본값", "notConfigurable": "{{model}}에서는 추론을 조정할 수 없습니다", "clamped": "이 모델에서는 {{requested}}을(를) 사용할 수 없어 {{effective}}을(를) 사용합니다.", + "context": { + "label": "컨텍스트", + "summarizesAt": "{{max}}에서 요약" + }, + "cache": { + "label": "캐시", + "hit": "{{percent}} 캐시됨", + "notReported": "보고되지 않음", + "notYet": "아직 캐시 없음", + "timeLeft": "남은 시간", + "about": "~{{time}}", + "expired": "만료됨", + "noExpiry": "고정 만료 없음" + }, "choice": { "provider_default": "제공자 기본값", "off": "끄기", diff --git a/app/ui_layer/browser/frontend/src/locales/zh-CN/chat.json b/app/ui_layer/browser/frontend/src/locales/zh-CN/chat.json index bb293ede2..6d917a50a 100644 --- a/app/ui_layer/browser/frontend/src/locales/zh-CN/chat.json +++ b/app/ui_layer/browser/frontend/src/locales/zh-CN/chat.json @@ -40,6 +40,20 @@ "defaultTag": "默认", "notConfigurable": "{{model}} 不支持调整推理", "clamped": "此模型不支持“{{requested}}”,因此使用“{{effective}}”。", + "context": { + "label": "上下文", + "summarizesAt": "达到 {{max}} 时总结" + }, + "cache": { + "label": "缓存", + "hit": "{{percent}} 已缓存", + "notReported": "未报告", + "notYet": "尚未缓存", + "timeLeft": "剩余时间", + "about": "~{{time}}", + "expired": "已过期", + "noExpiry": "无固定有效期" + }, "choice": { "provider_default": "服务商默认", "off": "关闭", diff --git a/app/ui_layer/browser/frontend/src/locales/zh-TW/chat.json b/app/ui_layer/browser/frontend/src/locales/zh-TW/chat.json index 907ddb81d..472c49512 100644 --- a/app/ui_layer/browser/frontend/src/locales/zh-TW/chat.json +++ b/app/ui_layer/browser/frontend/src/locales/zh-TW/chat.json @@ -40,6 +40,20 @@ "defaultTag": "預設", "notConfigurable": "{{model}} 不支援調整推理", "clamped": "此模型不支援「{{requested}}」,因此使用「{{effective}}」。", + "context": { + "label": "上下文", + "summarizesAt": "達到 {{max}} 時摘要" + }, + "cache": { + "label": "快取", + "hit": "{{percent}} 已快取", + "notReported": "未回報", + "notYet": "尚未快取", + "timeLeft": "剩餘時間", + "about": "~{{time}}", + "expired": "已過期", + "noExpiry": "無固定有效期" + }, "choice": { "provider_default": "供應商預設", "off": "關閉", diff --git a/app/ui_layer/browser/frontend/src/store/slices/reasoningSlice.ts b/app/ui_layer/browser/frontend/src/store/slices/reasoningSlice.ts index fe229a391..045f57a17 100644 --- a/app/ui_layer/browser/frontend/src/store/slices/reasoningSlice.ts +++ b/app/ui_layer/browser/frontend/src/store/slices/reasoningSlice.ts @@ -7,12 +7,32 @@ import { register } from '../socket/messageRegistry' // so it tracks model switches; the CHOICE is per session and lives on the // session (SessionInfo.reasoningEffort) or, for a draft chat, in UI state. +/** How long the provider keeps a request's prompt cache. 'exact': guaranteed + * at least this long; 'typical': the provider's usual figure only. */ +export interface CacheLifetime { + kind: 'exact' | 'typical' + seconds: number +} + +/** What every model reports, adjustable reasoning or not. */ +interface ModelContext { + model: string + /** Where requests are served (provider, or its subscription backend). */ + surface: string + /** Input tokens a request may carry at each choice; the event stream is + * summarized when the next request would carry more. */ + inputBudgets: Record + /** null: the provider documents no cache lifetime. */ + cacheLifetime: CacheLifetime | null + /** false: responses never say what was cached, so no hit rate exists. */ + reportsCachedTokens: boolean +} + export type ReasoningOptions = /** The model has no reasoning rule: nothing is adjustable. */ - | { configurable: false; model: string } - | { + | (ModelContext & { configurable: false }) + | (ModelContext & { configurable: true - model: string /** Selectable choices in display order. */ choices: ReasoningChoice[] /** The model's default level (marked "Default"; new chats start here). */ @@ -21,7 +41,7 @@ export type ReasoningOptions = providerDefault: string /** Effective choice for every stored choice (pi-style clamping). */ resolution: Record - } + }) interface ReasoningState { options: ReasoningOptions | null diff --git a/app/ui_layer/browser/frontend/src/types/index.ts b/app/ui_layer/browser/frontend/src/types/index.ts index ea770b8c7..4defa4ae3 100644 --- a/app/ui_layer/browser/frontend/src/types/index.ts +++ b/app/ui_layer/browser/frontend/src/types/index.ts @@ -97,6 +97,22 @@ export interface SessionInfo { /** Always set by the backend; null only on the client-side placeholder for * the main session before the backend has sent it. */ reasoningEffort: ReasoningChoice | null + /** The session's last decision request as the provider reported it; null + * until its first request (also after a restart). */ + lastRequest: LastRequest | null +} + +/** One LLM request's context size and cache use (the reasoning menu readout). */ +export interface LastRequest { + /** Input tokens the request carried, cached ones included. */ + inputTokens: number + /** Of those, how many the provider served from its prompt cache. */ + cachedTokens: number + /** Epoch ms when the request started; cache lifetimes count from here. */ + startedAt: number + /** Where it was served and by which model: its cache belongs to them. */ + surface: string + model: string } // ───────────────────────────────────────────────────────────────────── diff --git a/app/ui_layer/commands/builtin/clear.py b/app/ui_layer/commands/builtin/clear.py index 25a362ac2..684b10927 100644 --- a/app/ui_layer/commands/builtin/clear.py +++ b/app/ui_layer/commands/builtin/clear.py @@ -1,4 +1,4 @@ -"""Clear command implementation — clears the current session's conversation.""" +"""Clear command implementation: starts the current session over.""" from __future__ import annotations @@ -10,7 +10,8 @@ class ClearCommand(Command): - """Clear the current session's conversation.""" + """Start the current session over: its conversation and the agent's + context of it are cleared, and it continues as a new session.""" @property def name(self) -> str: @@ -22,7 +23,7 @@ def aliases(self) -> List[str]: @property def description(self) -> str: - return "Clear this session's conversation" + return "Clear this session's conversation and context (starts it over)" @property def requires_session(self) -> bool: @@ -40,15 +41,17 @@ async def execute( """Execute the clear command for the session it was typed in.""" target = session_id or MAIN_SESSION_ID + # Start the session over on the agent side (stops a run in flight, + # resets its context and files). First, so the stopped run's last + # rows are cleared with the rest of the conversation. + await self._controller.agent.clear_session(target) + # Clear persisted chat + activity rows for this session from app.usage import get_action_storage, get_chat_storage get_chat_storage().clear_messages(target) get_action_storage().clear_items(target) - # Clear the agent-side session state (event stream, todos, budgets) - await self._controller.agent.clear_session(target) - # Tell the UI to drop the session's rendered conversation. Always # session-scoped: a /clear must never touch other sessions. adapter = self._controller.active_adapter diff --git a/app/usage/session_storage.py b/app/usage/session_storage.py index 595091d7a..fc23ed48c 100644 --- a/app/usage/session_storage.py +++ b/app/usage/session_storage.py @@ -87,6 +87,19 @@ def _init_db(self) -> None: ON event_records(stream_id, position) """) + # A session's LLM state per call type (LLMInterface.export_session): + # restored at boot so a restart continues the session on the + # provider's cached prefix instead of starting a new one. + cursor.execute(""" + CREATE TABLE IF NOT EXISTS llm_sessions ( + session_id TEXT NOT NULL, + call_type TEXT NOT NULL, + state_json TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY (session_id, call_type) + ) + """) + # Old task-system tables are gone for good. cursor.execute("DROP TABLE IF EXISTS active_tasks") cursor.execute("DROP TABLE IF EXISTS conversation_history") @@ -131,6 +144,7 @@ def remove_session(self, session_id: str) -> None: conn.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,)) conn.execute("DELETE FROM event_records WHERE stream_id = ?", (session_id,)) conn.execute("DELETE FROM event_streams WHERE stream_id = ?", (session_id,)) + conn.execute("DELETE FROM llm_sessions WHERE session_id = ?", (session_id,)) conn.commit() def get_session(self, session_id: str) -> Optional[Dict[str, Any]]: @@ -257,6 +271,56 @@ def get_event_stream( return head_summary, records + # ─────────────────────── LLM Session Persistence ──────────────────────── + + def persist_llm_session( + self, session_id: str, state: Dict[str, Dict[str, Any]] + ) -> None: + """Replace a session's saved LLM state with ``state`` (call type -> + LLMInterface.export_session entry). An empty state removes it.""" + now = datetime.now(timezone.utc).isoformat() + rows = [] + for call_type, entry in state.items(): + try: + rows.append((session_id, call_type, json.dumps(entry), now)) + except (TypeError, ValueError) as e: + # A history that is not plain JSON cannot be restored as sent; + # the session then starts a new prefix after a restart. + logger.warning( + f"[SessionStorage] LLM state for {session_id}:{call_type} " + f"is not serializable, not saved: {e}" + ) + with sqlite3.connect(self._db_path) as conn: + conn.execute("DELETE FROM llm_sessions WHERE session_id = ?", (session_id,)) + conn.executemany( + """ + INSERT INTO llm_sessions (session_id, call_type, state_json, updated_at) + VALUES (?, ?, ?, ?) + """, + rows, + ) + conn.commit() + + def get_llm_session(self, session_id: str) -> Dict[str, Dict[str, Any]]: + """A session's saved LLM state (call type -> entry).""" + with sqlite3.connect(self._db_path) as conn: + cursor = conn.cursor() + cursor.execute( + "SELECT call_type, state_json FROM llm_sessions WHERE session_id = ?", + (session_id,), + ) + rows = cursor.fetchall() + state: Dict[str, Dict[str, Any]] = {} + for call_type, state_json in rows: + try: + state[call_type] = json.loads(state_json) + except (ValueError, TypeError): + logger.warning( + f"[SessionStorage] Skipping corrupt LLM state for " + f"{session_id}:{call_type}" + ) + return state + # ─────────────────────── Utilities ─────────────────────────────────────── def clear_all(self) -> None: @@ -265,6 +329,7 @@ def clear_all(self) -> None: conn.execute("DELETE FROM sessions") conn.execute("DELETE FROM event_records") conn.execute("DELETE FROM event_streams") + conn.execute("DELETE FROM llm_sessions") conn.commit() logger.info("[SessionStorage] Cleared all session data") diff --git a/scripts/catalog_overrides.json b/scripts/catalog_overrides.json new file mode 100644 index 000000000..01051a8ea --- /dev/null +++ b/scripts/catalog_overrides.json @@ -0,0 +1,17 @@ +{ + "about": "Rows scripts/gen_model_catalog.py adds to the model catalog because its sources lack them. OpenAI's dated snapshots are listed same_as the alias that points to them, so they share its limits.", + "models": { + "openai/gpt-5-2025-08-07": {"same_as": "openai/gpt-5"}, + "openai/gpt-5-mini-2025-08-07": {"same_as": "openai/gpt-5-mini"}, + "openai/gpt-5-nano-2025-08-07": {"same_as": "openai/gpt-5-nano"}, + "openai/gpt-5.1-2025-11-13": {"same_as": "openai/gpt-5.1"}, + "openai/gpt-5.2-2025-12-11": {"same_as": "openai/gpt-5.2"}, + "openai/gpt-5.4-2026-03-05": {"same_as": "openai/gpt-5.4"}, + "openai/gpt-5.4-mini-2026-03-17": {"same_as": "openai/gpt-5.4-mini"}, + "openai/gpt-5.4-nano-2026-03-17": {"same_as": "openai/gpt-5.4-nano"}, + "openai/gpt-5.5-2026-04-23": {"same_as": "openai/gpt-5.5"}, + "openai/o3-2025-04-16": {"same_as": "openai/o3"}, + "openai/o3-mini-2025-01-31": {"same_as": "openai/o3-mini"}, + "openai/o4-mini-2025-04-16": {"same_as": "openai/o4-mini"} + } +} diff --git a/scripts/gen_model_catalog.py b/scripts/gen_model_catalog.py new file mode 100644 index 000000000..350b25fd5 --- /dev/null +++ b/scripts/gen_model_catalog.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""Generate agent_core/core/models/model_catalog.json, the model catalog. + +The catalog holds each model's context window and, where the provider caps +input below the window, its input limit. LLMInterface budgets every request +from it (agent_core/core/models/catalog.py); a model with no row uses +settings.json model.context_window. + +Sources, all structured fields (nothing is inferred from a model's name): + +* models.dev (MODELS_DEV_URL): ``limit.context`` and ``limit.input`` of every + model of each provider profile's ``catalog_provider`` + (agent_core/core/models/provider_config.py), keyed ``/``. +* the Codex model catalogue (CODEX_CATALOG_URL): ``context_window`` of each + model on the ChatGPT-subscription surface, the window Codex runs it at. +* scripts/catalog_overrides.json: rows both sources lack. A row is either + ``{"same_as": ""}``, which copies a row the sources produced, + or ``{"context_window": N}`` with an optional ``"max_input_tokens"``. + +The output is deterministic (sorted, one row per line, no timestamps), so a +regeneration diff shows exactly which models changed. Run it by hand when +providers ship models; nothing is fetched at runtime. + +Usage: + python scripts/gen_model_catalog.py +""" + +from __future__ import annotations + +import argparse +import json +import ssl +import sys +import urllib.request +from pathlib import Path +from typing import Any, Dict + +REPO_ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO_ROOT)) + +from agent_core.core.models.catalog import CATALOG_PATH # noqa: E402 +from agent_core.core.models.provider_config import PROVIDER_CONFIG # noqa: E402 +from agent_core.core.models.reasoning import ( # noqa: E402 + SUBSCRIPTION_AUTH_MODE, + reasoning_surface, +) + +MODELS_DEV_URL = "https://models.dev/api.json" +CODEX_CATALOG_URL = ( + "https://raw.githubusercontent.com/openai/codex/main/" + "codex-rs/models-manager/models.json" +) +OVERRIDES_PATH = Path(__file__).with_name("catalog_overrides.json") + +Row = Dict[str, int] + + +def _fetch_json(url: str) -> Any: + import certifi + + # certifi's bundle, not the OS store: a broken certificate in the Windows + # store fails the default context before any request is made. + context = ssl.create_default_context(cafile=certifi.where()) + request = urllib.request.Request( + url, headers={"User-Agent": "CraftBot gen_model_catalog.py"} + ) + with urllib.request.urlopen(request, timeout=60, context=context) as response: + return json.load(response) + + +def _positive_int(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value > 0 + + +def _models_dev_rows(models_dev: Dict[str, Any]) -> Dict[str, Row]: + rows: Dict[str, Row] = {} + for profile in PROVIDER_CONFIG.values(): + if profile.catalog_provider is None: + continue + models = models_dev[profile.catalog_provider]["models"] + for model_id, model in models.items(): + limit = model.get("limit") or {} + context = limit.get("context") + if not _positive_int(context): + continue + row: Row = {"context_window": context} + if _positive_int(limit.get("input")) and limit["input"] < context: + row["max_input_tokens"] = limit["input"] + rows[f"{profile.key}/{model_id}"] = row + return rows + + +def _codex_rows(codex: Dict[str, Any]) -> Dict[str, Row]: + surface = reasoning_surface("openai", SUBSCRIPTION_AUTH_MODE) + return { + f"{surface}/{model['slug']}": {"context_window": model["context_window"]} + for model in codex["models"] + if _positive_int(model.get("context_window")) + } + + +def _override_rows(sourced: Dict[str, Row]) -> Dict[str, Row]: + overrides = json.loads(OVERRIDES_PATH.read_text(encoding="utf-8"))["models"] + rows: Dict[str, Row] = {} + for key, override in overrides.items(): + if "same_as" in override: + target = sourced.get(override["same_as"]) + if target is None: + raise SystemExit( + f"{OVERRIDES_PATH.name}: {key} is same_as " + f"{override['same_as']}, which no source lists" + ) + rows[key] = dict(target) + continue + if not _positive_int(override.get("context_window")): + raise SystemExit(f"{OVERRIDES_PATH.name}: {key} needs a context_window") + row: Row = {"context_window": override["context_window"]} + if "max_input_tokens" in override: + if not _positive_int(override["max_input_tokens"]): + raise SystemExit( + f"{OVERRIDES_PATH.name}: {key} has an invalid max_input_tokens" + ) + row["max_input_tokens"] = override["max_input_tokens"] + rows[key] = row + return rows + + +def _render(rows: Dict[str, Row]) -> str: + items = sorted(rows.items()) + lines = [ + "{", + ' "generator": "scripts/gen_model_catalog.py",', + ' "sources": ' + + json.dumps( + [MODELS_DEV_URL, CODEX_CATALOG_URL, "scripts/catalog_overrides.json"] + ) + + ",", + ' "models": {', + ] + for index, (key, row) in enumerate(items): + comma = "," if index < len(items) - 1 else "" + lines.append(f" {json.dumps(key)}: {json.dumps(row, sort_keys=True)}{comma}") + lines += [" }", "}"] + return "\n".join(lines) + "\n" + + +def main() -> int: + argparse.ArgumentParser(description=__doc__).parse_args() + sourced = _models_dev_rows(_fetch_json(MODELS_DEV_URL)) + sourced.update(_codex_rows(_fetch_json(CODEX_CATALOG_URL))) + rows = {**sourced, **_override_rows(sourced)} + + text = _render(rows) + json.loads(text) # the hand-rendered layout must stay valid JSON + CATALOG_PATH.write_text(text, encoding="utf-8", newline="\n") + print(f"wrote {len(rows)} models to {CATALOG_PATH.relative_to(REPO_ROOT)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/conftest.py b/tests/conftest.py index 7b28746c2..874a9ebdc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -45,31 +45,8 @@ def _with_window(reload: bool = False): model["context_window"] = 128000 settings["model"] = model context = dict(settings.get("context") or {}) - context.setdefault("reserve_tokens", 16384) context.setdefault("keep_recent_tokens", 20000) settings["context"] = context return settings monkeypatch.setattr(app_config, "get_settings", _with_window) - - -@pytest.fixture -def event_stream_limits(monkeypatch): - """Pin how much recent history an EventStream keeps after a fold. - - The stream never folds on its own; tests call summarize_by_LLM() when - they want one. This pins keep_recent_tokens so a local settings.json - edit cannot change what an event-stream test exercises. The import is - inside the fixture so collecting unrelated tests does not pull in - event_stream (and sklearn with it). - """ - from agent_core.core.impl.event_stream import event_stream as event_stream_module - - def _pin(keep_recent_tokens: int = 10000) -> None: - monkeypatch.setattr( - event_stream_module, - "_configured_keep_recent_tokens", - lambda: keep_recent_tokens, - ) - - return _pin diff --git a/tests/llm/test_context_readout.py b/tests/llm/test_context_readout.py new file mode 100644 index 000000000..b6698639b --- /dev/null +++ b/tests/llm/test_context_readout.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +"""The reasoning menu's context and cache readout, and the KV cache under it. + +The readout shows a session's last decision request (its input against the +budget, how much the provider served from cache, and how long that cache +lasts). These tests pin: + +* recording it changes nothing that is sent (payloads stay byte-identical); +* it is recorded on the session path and on the stateless path alike; +* every provider whose profile accumulates a session history takes the + session path (a hand-kept subset of them used to re-send the whole prompt + every turn); +* cache lifetimes exist only where the provider documents one; +* the wire payloads the menu reads. +""" + +from __future__ import annotations + +import asyncio +import time +from types import SimpleNamespace + +import pytest + +from agent_core.core.impl.llm import LLMCallType +from agent_core.core.models.cache_lifetime import CacheLifetimeKind, cache_lifetime +from agent_core.core.models.catalog import ModelLimits +from agent_core.core.models.reasoning import ReasoningChoice +from agent_core.core.models.registry import session_cc_providers + +from .golden.conftest import build_interface + +ACTION = LLMCallType.ACTION_SELECTION + + +# ──────────────────────── recording the last request ──────────────────────── + + +def test_the_usage_key_changes_nothing_sent(monkeypatch): + iface, recorder = build_interface(monkeypatch, "openai", "gpt-6-luna") + asyncio.run(iface.generate_response_async("SYSTEM", "USER")) + asyncio.run( + iface.generate_response_async("SYSTEM", "USER", usage_key=f"s1:{ACTION}") + ) + first, second = recorder.calls + assert first["payload"] == second["payload"] + + +def test_a_stateless_decision_records_its_request(monkeypatch): + iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + asyncio.run(iface.generate_response_async("SYSTEM", "USER")) + assert iface.last_request("s1", ACTION) is None # no key: not a decision + + before = time.time() + asyncio.run( + iface.generate_response_async("SYSTEM", "USER", usage_key=f"s1:{ACTION}") + ) + usage = iface.last_request("s1", ACTION) + assert usage is not None + assert (usage.input_tokens, usage.cached_tokens) == (100, 0) + assert (usage.surface, usage.model) == ("openai", "gpt-6-luna") + assert before <= usage.started_at <= time.time() + + +def test_a_session_decision_records_its_request(monkeypatch): + iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + iface.create_session_cache("s1", ACTION, "SYSTEM") + iface.generate_response_with_session("s1", ACTION, "USER", log_response=False) + usage = iface.last_request("s1", ACTION) + assert usage is not None and usage.input_tokens == 100 + + +def test_the_record_outlives_a_fold_but_not_the_session(monkeypatch): + iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + iface.create_session_cache("s1", ACTION, "SYSTEM") + iface.generate_response_with_session("s1", ACTION, "USER", log_response=False) + iface.reset_session_history("s1", ACTION) # a fold + assert iface.last_request("s1", ACTION) is not None + iface.end_all_session_caches("s1") + assert iface.last_request("s1", ACTION) is None + + +# ─────────────────────────── the session path ─────────────────────────── + + +@pytest.mark.parametrize("provider", sorted(session_cc_providers())) +def test_every_accumulating_provider_takes_the_session_path(monkeypatch, provider): + iface, _ = build_interface(monkeypatch, provider, "some-model") + iface.create_session_cache("s1", ACTION, "SYSTEM") + assert iface.has_session_cache("s1", ACTION) + + +# ─────────────────────────── cache lifetimes ─────────────────────────── + + +def test_cache_lifetimes_exist_only_where_documented(): + luna = cache_lifetime("openai", "gpt-6-luna") + assert luna.kind is CacheLifetimeKind.EXACT and luna.seconds == 30 * 60 + older = cache_lifetime("openai", "gpt-5.2-2025-12-11") + assert older.kind is CacheLifetimeKind.TYPICAL and older.seconds == 5 * 60 + claude = cache_lifetime("anthropic", "claude-sonnet-4-6") + assert claude.kind is CacheLifetimeKind.EXACT and claude.seconds == 60 * 60 + # Undocumented or best-effort: no countdown. + assert cache_lifetime("openai", "gpt-6.1-sol", "subscription") is None + assert cache_lifetime("grok", "grok-4.3") is None + assert cache_lifetime("deepseek", "deepseek-v4-pro") is None + assert cache_lifetime("openrouter", "openai/gpt-6.1-sol") is None + assert cache_lifetime("lmstudio", "openai/gpt-oss-20b") is None + + +def test_the_gpt_5_6_rows_name_real_models(): + from agent_core.core.models.cache_lifetime import _MODEL_LIFETIMES + from agent_core.core.models.catalog import model_limits + + for model in _MODEL_LIFETIMES["openai"]: + assert model_limits("openai", model) is not None, model + + +def test_bedrock_counts_down_only_for_models_that_take_cache_points(monkeypatch): + claude, _ = build_interface( + monkeypatch, "bedrock", "us.anthropic.claude-haiku-4-5-20251001-v1:0" + ) + assert claude.prompt_cache_lifetime().seconds == 5 * 60 + llama, _ = build_interface(monkeypatch, "bedrock", "meta.llama3-70b-instruct-v1:0") + assert llama.prompt_cache_lifetime() is None + + +def test_providers_that_never_report_cached_tokens_say_so(monkeypatch): + fireworks, _ = build_interface(monkeypatch, "fireworks", "some-model") + openai, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + assert fireworks.reports_cached_tokens() is False + assert openai.reports_cached_tokens() is True + + +# ─────────────────────────── budgets per choice ─────────────────────────── + + +def test_each_choice_has_its_own_budget(monkeypatch): + import agent_core.core.impl.llm.interface as interface_module + + iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + iface.max_tokens = 8000 + monkeypatch.setattr( + interface_module, "model_limits", lambda *a: ModelLimits(200_000) + ) + assert iface.input_budget_for(ReasoningChoice.OFF) == 192_000 + assert iface.input_budget_for(ReasoningChoice.HIGH) == 168_000 + assert iface.input_budget_for(ReasoningChoice.XHIGH) == 136_000 + + +# ─────────────────────────── wire payloads ─────────────────────────── + + +def _adapter(llm, sent): + async def send_to(_ws, message): + sent.append(message) + + return SimpleNamespace( + _controller=SimpleNamespace(agent=SimpleNamespace(llm=llm)), + _send_to=send_to, + ) + + +def test_the_reasoning_options_carry_budgets_and_cache_facts(monkeypatch): + from app.ui_layer.adapters.browser_adapter import BrowserAdapter + + iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + sent = [] + asyncio.run( + BrowserAdapter._handle_reasoning_options_get(_adapter(iface, sent), None) + ) + data = sent[0]["data"] + assert data["surface"] == "openai" + assert set(data["inputBudgets"]) == {choice.value for choice in ReasoningChoice} + assert data["cacheLifetime"] == {"kind": "exact", "seconds": 1800} + assert data["reportsCachedTokens"] is True + + +def test_the_session_info_carries_the_last_request(monkeypatch): + from agent_core.core.session import Session + from app.ui_layer.adapters.browser_adapter import BrowserAdapter + + iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + adapter = _adapter(iface, []) + session = Session.from_dict({"id": "s1"}) + assert BrowserAdapter._session_info(adapter, session)["lastRequest"] is None + + asyncio.run( + iface.generate_response_async("SYSTEM", "USER", usage_key=f"s1:{ACTION}") + ) + last = BrowserAdapter._session_info(adapter, session)["lastRequest"] + assert last["inputTokens"] == 100 and last["cachedTokens"] == 0 + assert last["surface"] == "openai" and last["model"] == "gpt-6-luna" + assert abs(last["startedAt"] - time.time() * 1000) < 60_000 diff --git a/tests/llm/test_reasoning_rules.py b/tests/llm/test_reasoning_rules.py index 07ab26c9d..30ae8fbe6 100644 --- a/tests/llm/test_reasoning_rules.py +++ b/tests/llm/test_reasoning_rules.py @@ -747,8 +747,11 @@ def test_gemini_caller_budget_wins_over_the_session(monkeypatch, bound_session): def test_context_check_reserves_the_requests_reasoning_cap(monkeypatch, bound_session): + import agent_core.core.impl.llm.interface as interface_module import app.config as app_config + # Uncatalogued, so the settings window applies. + monkeypatch.setattr(interface_module, "model_limits", lambda *a: None) monkeypatch.setattr(app_config, "get_context_window", lambda: 40_000) prompt = "word " * 12_000 # ~12k tokens: fits 40k - 8k, not 40k - 32k @@ -824,11 +827,12 @@ def test_each_model_and_choice_is_logged_once(monkeypatch, bound_session): def test_fold_check_reserves_the_same_cap_as_the_pre_send_check( monkeypatch, bound_session ): + import agent_core.core.impl.llm.interface as interface_module import app.config as app_config - # window 128,000 - reserve 16,384 - the output reservation. + # window 128,000 - the output reservation. + monkeypatch.setattr(interface_module, "model_limits", lambda *a: None) monkeypatch.setattr(app_config, "get_context_window", lambda: 128_000) - monkeypatch.setattr(app_config, "get_reserve_tokens", lambda: 16_384) def assert_folds_after(iface, last_input_tokens: int) -> None: key = "task:action_selection" @@ -839,15 +843,15 @@ def assert_folds_after(iface, last_input_tokens: int) -> None: unruled, _ = build_interface(monkeypatch, "openai", "gpt-4o") unruled.max_tokens = APP_MAX_TOKENS - assert_folds_after(unruled, 103_616) # the caller's 8,000 + assert_folds_after(unruled, 120_000) # the caller's 8,000 ruled, _ = build_interface(monkeypatch, "openai", "gpt-5.2-2025-12-11") ruled.max_tokens = APP_MAX_TOKENS - assert_folds_after(ruled, 79_616) # default high: 32,000 + assert_folds_after(ruled, 96_000) # default high: 32,000 with bound_session(C.XHIGH): - assert_folds_after(ruled, 47_616) # 64,000 + assert_folds_after(ruled, 64_000) # 64,000 with bound_session(C.OFF): - assert_folds_after(ruled, 103_616) # no reasoning: the caller's 8,000 + assert_folds_after(ruled, 120_000) # no reasoning: the caller's 8,000 def test_decision_follows_a_model_switch(monkeypatch): @@ -1022,11 +1026,16 @@ def test_reasoning_options_handler(monkeypatch): unruled, _ = build_interface(monkeypatch, "openai", "gpt-4o") adapter = _adapter_with(SimpleNamespace(llm=unruled)) asyncio.run(adapter._handle_reasoning_options_get(ws=None)) - assert adapter.sent[0]["data"] == { + data = adapter.sent[0]["data"] + assert {key: data[key] for key in ("success", "model", "configurable")} == { "success": True, "model": "gpt-4o", "configurable": False, } + # No reasoning parameter is sent, so every choice has the same budget. + assert len(set(data["inputBudgets"].values())) == 1 + assert data["cacheLifetime"] == {"kind": "typical", "seconds": 300} + assert data["reportsCachedTokens"] is True def test_session_reasoning_set_handler(tmp_path: Path): @@ -1035,6 +1044,7 @@ def test_session_reasoning_set_handler(tmp_path: Path): agent = SimpleNamespace( session_manager=manager, set_session_reasoning_effort=manager.set_reasoning_effort, + llm=SimpleNamespace(last_request=lambda task_id, call_type: None), ) adapter = _adapter_with(agent) try: diff --git a/tests/llm/test_session_resume.py b/tests/llm/test_session_resume.py new file mode 100644 index 000000000..d2d740f3d --- /dev/null +++ b/tests/llm/test_session_resume.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +"""A restart continues each session on the provider's cached prefix. + +A session's LLM history used to live only in memory, so the first request +after a restart started a new session: the whole prompt as one new message, +of which a provider that caches at message boundaries reuses only the system +prompt (observed 2026-10-19: 8,305 of 21,053 cached). The history is now +saved with the session and restored at boot when it still matches the +restored event stream. These tests pin: + +* the first request after a restart starts with exactly the messages of the + last request before it (so the provider's cache applies); +* nothing is restored that would not match: another provider's history, a + stream that was folded or cleared since, a turn not yet marked as sent; +* the saved state survives JSON and the session storage. +""" + +from __future__ import annotations + +import json + +from agent_core.core.event_stream.event import EventRecord +from agent_core.core.impl.event_stream.event_stream import EventStream +from agent_core.core.impl.llm import LLMCallType + +from .golden.conftest import build_interface + +ACTION = LLMCallType.ACTION_SELECTION + + +def _decide(iface, stream, task_id="s1"): + """One decision the way the router makes it on the session path.""" + if stream.has_session_sync(ACTION): + prompt, _ = stream.get_delta_events(ACTION) + else: + iface.reset_session_history(task_id, ACTION) + prompt = stream.to_prompt_snapshot() + iface.generate_response_with_session( + task_id, + ACTION, + prompt, + system_prompt_for_new_session="SYSTEM", + log_response=False, + ) + stream.mark_session_synced(ACTION) + iface.checkpoint_session(task_id, ACTION, stream.sync_marker(ACTION)) + + +def _session_before_restart(monkeypatch): + iface, recorder = build_interface(monkeypatch, "openai", "gpt-6-luna") + iface.create_session_cache("s1", ACTION, "SYSTEM") + stream = EventStream(llm=None, temp_dir=None) + stream.log("action_end", "event one") + _decide(iface, stream) + stream.log("action_end", "event two") + _decide(iface, stream) + return iface, recorder, stream + + +def _restart(monkeypatch, iface, stream, provider="openai", model="gpt-6-luna"): + """Save, then rebuild everything from what was saved, as a boot does.""" + saved = json.loads(json.dumps(iface.export_session("s1"))) + records = [EventRecord.from_dict(r.to_dict()) for r in stream.tail_events] + head = stream.head_summary + + new_iface, recorder = build_interface(monkeypatch, provider, model) + new_iface.create_session_cache("s1", ACTION, "SYSTEM") + new_stream = EventStream(llm=None, temp_dir=None) + new_stream.head_summary = head + new_stream.tail_events = records + synced = new_iface.import_session("s1", saved, new_stream) + return new_iface, recorder, new_stream, synced + + +def test_the_first_request_after_a_restart_continues_the_cached_prefix(monkeypatch): + iface, recorder, stream = _session_before_restart(monkeypatch) + before = recorder.calls[-1]["payload"]["messages"] + + new_iface, new_recorder, new_stream, synced = _restart(monkeypatch, iface, stream) + assert synced == len(stream.tail_events) + + new_stream.log("action_end", "event three") + _decide(new_iface, new_stream) + after = new_recorder.calls[-1]["payload"]["messages"] + + assert after[: len(before)] == before + assert "event three" in after[-1]["content"] + assert "event two" not in after[-1]["content"] # already sent before the restart + + +def test_the_readout_survives_a_restart(monkeypatch): + iface, _, stream = _session_before_restart(monkeypatch) + new_iface, _, _, _ = _restart(monkeypatch, iface, stream) + assert new_iface.last_request("s1", ACTION) == iface.last_request("s1", ACTION) + + +def test_another_providers_history_is_not_restored(monkeypatch): + iface, _, stream = _session_before_restart(monkeypatch) + new_iface, _, new_stream, synced = _restart( + monkeypatch, iface, stream, provider="anthropic", model="claude-sonnet-4-6" + ) + assert synced is None + assert not new_stream.has_session_sync(ACTION) + assert new_iface._session_histories == {} + + +def test_a_stream_folded_since_is_not_continued(monkeypatch): + iface, _, stream = _session_before_restart(monkeypatch) + saved = json.loads(json.dumps(iface.export_session("s1"))) + stream.head_summary = "a fold happened after the save" + new_iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + assert new_iface.import_session("s1", saved, stream) is None + + +def test_a_cleared_stream_is_not_continued(monkeypatch): + iface, _, stream = _session_before_restart(monkeypatch) + saved = json.loads(json.dumps(iface.export_session("s1"))) + stream.clear() + stream.log("action_end", "a new conversation") + new_iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + assert new_iface.import_session("s1", saved, stream) is None + + +def test_a_turn_not_yet_marked_sent_is_not_saved(monkeypatch): + # The history grows in the worker thread before the router marks the + # stream synced; a save in between must stop at the last checkpoint. + iface, _, stream = _session_before_restart(monkeypatch) + checkpointed = iface.export_session("s1")[ACTION]["history"] + stream.log("action_end", "event three") + prompt, _ = stream.get_delta_events(ACTION) + iface.generate_response_with_session( + "s1", ACTION, prompt, system_prompt_for_new_session="SYSTEM", log_response=False + ) + assert iface.export_session("s1")[ACTION]["history"] == checkpointed + + +def test_a_fold_drops_the_checkpoint(monkeypatch): + iface, _, _ = _session_before_restart(monkeypatch) + iface.reset_session_history("s1", ACTION) + assert "history" not in iface.export_session("s1")[ACTION] + + +def test_the_saved_state_round_trips_through_session_storage(tmp_path, monkeypatch): + from app.usage.session_storage import SessionStorage + + storage = SessionStorage(db_path=str(tmp_path / "sessions.db")) + iface, _, _ = _session_before_restart(monkeypatch) + state = iface.export_session("s1") + storage.persist_llm_session("s1", state) + assert storage.get_llm_session("s1") == json.loads(json.dumps(state)) + + storage.persist_llm_session("s1", {}) # a cleared session + assert storage.get_llm_session("s1") == {} + + storage.persist_llm_session("s1", state) + storage.remove_session("s1") + assert storage.get_llm_session("s1") == {} + + +def test_events_after_the_restored_sync_point_stay_unsent(monkeypatch): + # They reach the model with the first request after the restart; until + # then a fold must not collapse them (see test_event_stream_delivery.py). + iface, _, stream = _session_before_restart(monkeypatch) + stream.log("action_end", "logged after the last request") + _, _, new_stream, synced = _restart(monkeypatch, iface, stream) + new_stream.mark_delivered(synced) # what the boot restore does + delivered = [record.delivered for record in new_stream.tail_events] + assert delivered == [True] * synced + [False] * (len(delivered) - synced) + assert not delivered[-1] diff --git a/tests/test_action_set_loading.py b/tests/test_action_set_loading.py index e3c250428..7b66ae109 100644 --- a/tests/test_action_set_loading.py +++ b/tests/test_action_set_loading.py @@ -92,10 +92,9 @@ def generate_response(self, **kw): # pragma: no cover - never folds here @pytest.fixture -def loader(sessions, tmp_path, monkeypatch, event_stream_limits): +def loader(sessions, tmp_path, monkeypatch): import app.internal_action_interface as iai - event_stream_limits(10000) stream = EventStream(llm=_NoLLM(), temp_dir=tmp_path / "events") monkeypatch.setattr(iai.InternalActionInterface, "session_manager", sessions) monkeypatch.setattr( diff --git a/tests/test_context_budget.py b/tests/test_context_budget.py index 71606962d..1ac28d0a8 100644 --- a/tests/test_context_budget.py +++ b/tests/test_context_budget.py @@ -5,14 +5,19 @@ threshold on the event stream alone and an independent cap on the session history. There is one decision now, and it is made on the whole request the way pi and OpenClaw make it -- the provider's own input count for the previous -request plus what is new -- against the window less the headroom the summary -request needs. These tests pin: +request plus what is new -- against the serving model's input budget: its +window (from the model catalog; settings.json for a model the catalog does not +list) less the output cap the request sends, never above the provider's input +limit. These tests pin: * the history cap is gone; a fold resets the history WITHOUT ending the session, so the router keeps the session path and its cached prefix; * the cache markers the providers need are still on the wire; * the provider's input count is recorded per session and drives fits_context; -* the event stream never folds on its own -- only on request; +* the budget comes from the serving model: catalog window, input cap, and the + settings window only for an uncatalogued model; +* the event stream never folds on its own -- only on request -- and a fold + keeps at most half of the room the budget leaves; * an overflow is surfaced as one typed error, never counted as a provider failure, never retried on a fallback provider; * the settings are configuration with shipped defaults, invalid values error. @@ -23,16 +28,18 @@ import pytest +import agent_core.core.impl.llm.interface as interface_module from agent_core.core.errors import ErrorCategory from agent_core.core.impl.llm.interface import LLMContextOverflowError, LLMInterface +from agent_core.core.models.catalog import ModelLimits, model_limits from agent_core.utils.token import count_tokens from app import config as app_config from app.models.factory import ModelFactory WINDOW = 128000 -RESERVE = 16384 MAX_TOKENS = 8000 -FOLD_POINT = WINDOW - RESERVE - MAX_TOKENS # 103,616 input tokens +# grok-3 is not catalogued, so the settings window applies. +FOLD_POINT = WINDOW - MAX_TOKENS # 120,000 input tokens def _ctx(provider, model, anthropic_client=None): @@ -63,13 +70,10 @@ def _make(provider="grok", model="grok-3", anthropic_client=None): ) -def _settings(context_window=WINDOW, reserve_tokens=RESERVE, keep_recent_tokens=20000): +def _settings(context_window=WINDOW, keep_recent_tokens=20000): return { "model": {"context_window": context_window}, - "context": { - "reserve_tokens": reserve_tokens, - "keep_recent_tokens": keep_recent_tokens, - }, + "context": {"keep_recent_tokens": keep_recent_tokens}, } @@ -147,6 +151,34 @@ def test_router_decides_on_the_request_and_restarts_without_ending(): assert "except LLMContextOverflowError" in src +def test_a_restored_session_takes_the_session_path_like_a_new_one(tmp_path): + """The LLM keeps session caches in memory, so a session restored at boot + must register them again. Without them every turn took the stateless + path, where only the system prompt hit the provider's KV cache (observed + 2026-10-18 in lui_9a07529e: 9% of 1.65M input tokens cached).""" + from agent_core.core.impl.llm import LLMCallType + from agent_core.core.impl.session.manager import SessionManager + from agent_core.core.session import Session + from agent_core.core.state.session import StateSession + + iface = _make() + engine = SimpleNamespace(make_prompt=lambda **kw: ("SYSTEM", "")) + manager = SessionManager( + event_stream_manager=None, + llm_interface=iface, + context_engine=engine, + workspace_root=tmp_path, + ) + created = manager.create_session() + restored = manager.restore_session(Session.from_dict({"id": "s-restored"})) + try: + for session in (created, restored): + assert iface.has_session_cache(session.id, LLMCallType.ACTION_SELECTION) + finally: + for session_id in (created.id, restored.id): + StateSession.end(session_id) + + def test_subagent_first_turn_resets_history(): from pathlib import Path @@ -260,23 +292,142 @@ def test_fits_context_counts_the_whole_prompt_on_a_sessions_first_request(): assert iface.fits_context("task", "action_selection", system, too_big) is False -def test_the_shipped_fold_point_for_a_128k_window(): - """window 128,000 - reserve 16,384 - output 8,000: fold when input passes 103,616.""" +def _folds_after(iface, last_input_tokens): + key = "task:action_selection" + iface._last_input_tokens[key] = last_input_tokens + fits = iface.fits_context("task", "action_selection", "s", "") + iface._last_input_tokens[key] = last_input_tokens + 1 + return fits and not iface.fits_context("task", "action_selection", "s", "") + + +def test_an_uncatalogued_model_folds_at_the_settings_window(): + """window 128,000 - output 8,000: fold when input passes 120,000.""" + iface = _make() + with patch.object(app_config, "get_settings", return_value=_settings()): + assert _folds_after(iface, 120_000) + + +def test_a_catalogued_model_folds_at_its_own_window(): + """The settings window is ignored: 200,000 - output 8,000.""" iface = _make() + with ( + patch.object(app_config, "get_settings", return_value=_settings()), + patch.object(interface_module, "model_limits", lambda *a: ModelLimits(200_000)), + ): + assert _folds_after(iface, 192_000) + + +def test_the_providers_input_limit_caps_the_budget(): + """GPT-5's shape: a 400,000 window that takes at most 272,000 of input.""" + iface = _make() + limits = ModelLimits(400_000, max_input_tokens=272_000) + with patch.object(interface_module, "model_limits", lambda *a: limits): + assert _folds_after(iface, 272_000) + with pytest.raises(LLMContextOverflowError, match="input capped at 272000"): + iface._check_context_fits( + "system", "word " * 280_000, reasoning=iface.reasoning_decision() + ) + + +def test_the_budget_follows_a_model_switch(): + iface = _make() + windows = {"small-model": ModelLimits(64_000), "big-model": ModelLimits(1_000_000)} + with patch.object( + interface_module, "model_limits", lambda provider, model, auth: windows[model] + ): + iface.model = "small-model" + assert iface.input_budget() == 56_000 + iface.model = "big-model" + assert iface.input_budget() == 992_000 + + +# ------------------------------------------------------------- the catalog + + +def test_catalog_lookups_are_exact_and_per_surface(): + # The log's model: a dated snapshot shares its alias's row. + assert model_limits("openai", "gpt-5.2-2025-12-11") == model_limits( + "openai", "gpt-5.2" + ) + assert model_limits("openai", "gpt-5.2").max_input_tokens is not None + # The ChatGPT-subscription surface has its own rows (the Codex windows). + api = model_limits("openai", "gpt-6.1-sol") + subscription = model_limits("openai", "gpt-6.1-sol", "subscription") + assert api is not None and subscription is not None and api != subscription + # No prefix or substring matching. + assert model_limits("openai", "gpt-6.1") is None + assert model_limits("openai", "gpt-6.1-sol-x") is None + # Local servers run whatever window the user loaded. + assert model_limits("lmstudio", "openai/gpt-oss-20b") is None + + +def test_every_catalog_row_is_well_formed(): + import json + + from agent_core.core.models.catalog import CATALOG_PATH + from agent_core.core.models.provider_config import PROVIDER_CONFIG + + rows = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))["models"] + surfaces = {key for key, p in PROVIDER_CONFIG.items() if p.catalog_provider} + surfaces.add("openai_subscription") + assert rows + for key, row in rows.items(): + surface, _, model_id = key.partition("/") + assert surface in surfaces and model_id, key + assert set(row) <= {"context_window", "max_input_tokens"}, key + assert isinstance(row["context_window"], int) and row["context_window"] > 0 + if "max_input_tokens" in row: + assert 0 < row["max_input_tokens"] < row["context_window"], key + + +# ------------------------------------------------- how much a fold keeps + + +class _KeepRecordingStream: + head_summary = None + + def __init__(self): + self.keep_tokens = [] + + def summarize_by_LLM(self, keep_tokens): + self.keep_tokens.append(keep_tokens) + + +def _fold_keep(budget, system, static, stream=None): + from agent_core.core.impl.action.router import ActionRouter + + stream = stream or _KeepRecordingStream() + llm = SimpleNamespace(input_budget=lambda: budget) with patch.object(app_config, "get_settings", return_value=_settings()): - iface._last_input_tokens["task:action_selection"] = 103_616 - assert iface.fits_context("task", "action_selection", "s", "") is True - iface._last_input_tokens["task:action_selection"] = 103_617 - assert iface.fits_context("task", "action_selection", "s", "") is False + ActionRouter(None, llm, None)._fold(stream, system, static) + return stream.keep_tokens[0] + + +def test_a_fold_keeps_the_setting_when_the_budget_has_room(): + assert _fold_keep(900_000, "system " * 1000, "prompt " * 5000) == 20000 + + +def test_a_fold_keeps_at_most_half_the_room_the_budget_leaves(): + system, static = "system " * 1000, "prompt " * 5000 + fixed = count_tokens(system) + count_tokens(static) + assert _fold_keep(fixed + 24_000, system, static) == 12_000 + # Nothing left after the fixed prompt: keep nothing beyond the pinned tail. + assert _fold_keep(fixed - 1, system, static) == 0 + + +def test_the_running_summary_is_part_of_what_a_fold_does_not_shrink(): + stream = _KeepRecordingStream() + stream.head_summary = "summary " * 4000 + budget = 10_000 + count_tokens(stream.head_summary) + assert _fold_keep(budget, "", None, stream=stream) == 5_000 # ----------------------------------------- the stream folds only on request -def test_the_event_stream_never_folds_on_its_own(event_stream_limits): +def test_the_event_stream_never_folds_on_its_own(): from agent_core.core.impl.event_stream.event_stream import EventStream - event_stream_limits(100) llm = _CountingLLM() es = EventStream(llm=llm, temp_dir=None) for i in range(400): @@ -284,7 +435,7 @@ def test_the_event_stream_never_folds_on_its_own(event_stream_limits): assert llm.calls == 0 and es.head_summary is None es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=100) assert llm.calls == 1 and es.head_summary is not None @@ -349,18 +500,16 @@ def test_shipped_defaults_apply_when_keys_are_absent(): app_config, "get_settings", return_value={"model": {}, "context": {}} ): assert app_config.get_context_window() == 128000 - assert app_config.get_reserve_tokens() == 16384 assert app_config.get_keep_recent_tokens() == 20000 @pytest.mark.parametrize("value", [0, -1, True, "16384", 12.5]) -@pytest.mark.parametrize("key", ["reserve_tokens", "keep_recent_tokens"]) -def test_an_invalid_context_setting_is_a_configuration_error(key, value): +def test_an_invalid_keep_recent_tokens_is_a_configuration_error(value): settings = _settings() - settings["context"][key] = value + settings["context"]["keep_recent_tokens"] = value with patch.object(app_config, "get_settings", return_value=settings): with pytest.raises(app_config.ConfigurationError): - getattr(app_config, f"get_{key}")() + app_config.get_keep_recent_tokens() def test_no_fallback_constants_and_no_fractions_remain(): @@ -373,5 +522,6 @@ def test_no_fallback_constants_and_no_fractions_remain(): "stream_fraction_of_window", "tail_keep_fraction", "get_context_limits", + "reserve_tokens", ): assert token not in source, token diff --git a/tests/test_event_stream_action_schemas.py b/tests/test_event_stream_action_schemas.py index 7bdd9c44a..47a3f7324 100644 --- a/tests/test_event_stream_action_schemas.py +++ b/tests/test_event_stream_action_schemas.py @@ -20,6 +20,9 @@ ) +KEEP_TOKENS = 2000 + + class _RecordingLLM: consecutive_failures = 0 _max_consecutive_failures = 5 @@ -32,8 +35,7 @@ def generate_response(self, user_prompt=None, prompt_name=None, **kw): return "SUMMARY OF OLD EVENTS" -def _stream(tmp_path, event_stream_limits, keep_recent_tokens=2000): - event_stream_limits(keep_recent_tokens) +def _stream(tmp_path): llm = _RecordingLLM() return EventStream(llm=llm, temp_dir=tmp_path / "events"), llm @@ -61,8 +63,8 @@ def _schema_records(es): return [r for r in es.tail_events if r.event.event_type is EventType.ACTION_SCHEMAS] -def test_large_schemas_stay_inline(tmp_path, event_stream_limits): - es, _ = _stream(tmp_path, event_stream_limits) +def test_large_schemas_stay_inline(tmp_path): + es, _ = _stream(tmp_path) body = "s " * MAX_EVENT_INLINE_CHARS _log_schemas(es, ["send_gmail"], body=body) @@ -71,26 +73,26 @@ def test_large_schemas_stay_inline(tmp_path, event_stream_limits): assert not list((tmp_path / "events").glob("*.txt")) -def test_a_fold_never_collapses_schemas_in_place(tmp_path, event_stream_limits): - es, _ = _stream(tmp_path, event_stream_limits, keep_recent_tokens=100_000) +def test_a_fold_never_collapses_schemas_in_place(tmp_path): + es, _ = _stream(tmp_path) _fill(es, 5) _log_schemas(es, ["send_gmail"], body="s " * MAX_EVENT_INLINE_CHARS) es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=100_000) (rec,) = _schema_records(es) assert len(rec.event.message) > MAX_EVENT_INLINE_CHARS -def test_schemas_in_use_survive_a_fold(tmp_path, event_stream_limits): - es, llm = _stream(tmp_path, event_stream_limits) +def test_schemas_in_use_survive_a_fold(tmp_path): + es, llm = _stream(tmp_path) _log_schemas(es, ["send_gmail", "list_gmail"]) _fill(es, 40) _log_call(es, "send_gmail") # newest: in the kept tail es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=KEEP_TOKENS) assert es.head_summary == "SUMMARY OF OLD EVENTS" (rec,) = _schema_records(es) @@ -100,16 +102,14 @@ def test_schemas_in_use_survive_a_fold(tmp_path, event_stream_limits): assert all("SCHEMA BODY" not in p for p in llm.prompts) -def test_unused_schemas_are_dropped_unsummarized_with_a_note( - tmp_path, event_stream_limits -): - es, llm = _stream(tmp_path, event_stream_limits) +def test_unused_schemas_are_dropped_unsummarized_with_a_note(tmp_path): + es, llm = _stream(tmp_path) _log_schemas(es, ["post_discord"]) _log_call(es, "post_discord") # used, but long ago _fill(es, 40) es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=KEEP_TOKENS) assert _schema_records(es) == [] assert all("SCHEMA BODY" not in p for p in llm.prompts) @@ -126,23 +126,21 @@ def test_unused_schemas_are_dropped_unsummarized_with_a_note( assert es._total_tokens == sum(get_cached_token_count(r) for r in es.tail_events) -def test_only_schemas_old_enough_are_dropped_without_an_llm_call( - tmp_path, event_stream_limits -): - es, llm = _stream(tmp_path, event_stream_limits, keep_recent_tokens=600) +def test_only_schemas_old_enough_are_dropped_without_an_llm_call(tmp_path): + es, llm = _stream(tmp_path) _log_schemas(es, ["post_discord"], body="s " * 3000) _fill(es, 2) es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=600) assert _schema_records(es) == [] assert llm.prompts == [] assert es.head_summary is None -def test_actions_with_schemas_lists_the_live_tail(tmp_path, event_stream_limits): - es, _ = _stream(tmp_path, event_stream_limits) +def test_actions_with_schemas_lists_the_live_tail(tmp_path): + es, _ = _stream(tmp_path) assert es.actions_with_schemas() == set() _log_schemas(es, ["send_gmail", "list_gmail"]) _log_schemas(es, ["post_discord"]) diff --git a/tests/test_event_stream_datetime.py b/tests/test_event_stream_datetime.py index 6fd5799ca..d2c6310be 100644 --- a/tests/test_event_stream_datetime.py +++ b/tests/test_event_stream_datetime.py @@ -29,8 +29,7 @@ def _kinds(es): return [r.event.kind for r in es.tail_events] -def test_first_event_gets_a_datetime_marker(event_stream_limits): - event_stream_limits() +def test_first_event_gets_a_datetime_marker(): es = EventStream(llm=_FakeLLM()) es.log("action_end", "did a thing") kinds = _kinds(es) @@ -43,16 +42,14 @@ def test_first_event_gets_a_datetime_marker(event_stream_limits): assert re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b", msg) -def test_no_datetime_spam_within_window(event_stream_limits): - event_stream_limits() +def test_no_datetime_spam_within_window(): es = EventStream(llm=_FakeLLM()) for i in range(20): es.log("action_end", f"event {i}") assert _kinds(es).count("datetime") == 1 # only the first -def test_datetime_refreshes_after_interval(event_stream_limits): - event_stream_limits() +def test_datetime_refreshes_after_interval(): es = EventStream(llm=_FakeLLM()) es.log("action_end", "first") # Force the last stamp into the past to simulate >30 min elapsed. @@ -63,13 +60,12 @@ def test_datetime_refreshes_after_interval(event_stream_limits): assert _kinds(es).count("datetime") == 2 -def test_datetime_restamped_after_summarization(event_stream_limits): - event_stream_limits(100) +def test_datetime_restamped_after_summarization(): es = EventStream(llm=_FakeLLM()) for i in range(400): es.log("action_end", f"action {i} produced some output text to add tokens") es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=100) assert es.head_summary is not None # A current datetime marker is always present (re-stamped post-summary). assert any(r.event.kind == "datetime" for r in es.tail_events) diff --git a/tests/test_event_stream_delivery.py b/tests/test_event_stream_delivery.py index 565f08774..74ccb7de5 100644 --- a/tests/test_event_stream_delivery.py +++ b/tests/test_event_stream_delivery.py @@ -30,6 +30,9 @@ ) +KEEP_TOKENS = 2000 + + class _RecordingLLM: consecutive_failures = 0 _max_consecutive_failures = 5 @@ -42,8 +45,7 @@ def generate_response(self, user_prompt=None, prompt_name=None, **kw): return "SUMMARY OF OLD EVENTS" -def _stream(tmp_path, event_stream_limits, keep_recent_tokens=2000): - event_stream_limits(keep_recent_tokens) +def _stream(tmp_path): llm = _RecordingLLM() return EventStream(llm=llm, temp_dir=tmp_path / "events"), llm @@ -57,10 +59,8 @@ def _read_result(i, size): return f"READ RESULT {i}: " + ("line of file content " * size) -def test_new_events_start_undelivered_and_mark_delivered_covers_the_tail( - tmp_path, event_stream_limits -): - es, _ = _stream(tmp_path, event_stream_limits) +def test_new_events_start_undelivered_and_mark_delivered_covers_the_tail(tmp_path): + es, _ = _stream(tmp_path) _history(es, 3) assert not any(r.delivered for r in es.tail_events) @@ -71,27 +71,27 @@ def test_new_events_start_undelivered_and_mark_delivered_covers_the_tail( assert not es.tail_events[-1].delivered -def test_a_session_sync_marks_delivery(tmp_path, event_stream_limits): - es, _ = _stream(tmp_path, event_stream_limits) +def test_a_session_sync_marks_delivery(tmp_path): + es, _ = _stream(tmp_path) _history(es, 3) es.mark_session_synced("action_selection") assert all(r.delivered for r in es.tail_events) -def test_a_fold_leaves_unread_results_verbatim(tmp_path, event_stream_limits): +def test_a_fold_leaves_unread_results_verbatim(tmp_path): """The log's case: the agent's parallel reads return, then the fold runs.""" - es, llm = _stream(tmp_path, event_stream_limits) + es, llm = _stream(tmp_path) _history(es) es.mark_delivered() - # Larger than keep_recent_tokens together, and each one oversized: before + # Larger than the keep target together, and each one oversized: before # the fix, every one of them became a pointer or a summary line. results = [_read_result(i, 1200) for i in range(3)] assert all(len(r) > MAX_EVENT_INLINE_CHARS for r in results) for r in results: es.log("action_end", r, action_name="read_file") - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=KEEP_TOKENS) messages = [r.event.message for r in es.tail_events] for r in results: @@ -103,27 +103,25 @@ def test_a_fold_leaves_unread_results_verbatim(tmp_path, event_stream_limits): assert not any(m.startswith("old step") for m in messages) -def test_read_results_collapse_once_the_model_has_them(tmp_path, event_stream_limits): +def test_read_results_collapse_once_the_model_has_them(tmp_path): # A keep window the read result fits in, so it stays in the tail. - es, _ = _stream(tmp_path, event_stream_limits, keep_recent_tokens=6000) + es, _ = _stream(tmp_path) _history(es) es.mark_delivered() es.log("action_end", _read_result(0, 1200), action_name="read_file") - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=6000) assert not list((tmp_path / "events").glob("event_read_file_*.txt")) es.mark_session_synced("action_selection") # the agent's next turn - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=6000) rec = next(r for r in es.tail_events if r.event.action_name == "read_file") assert len(rec.event.message) <= MAX_EVENT_INLINE_CHARS assert list((tmp_path / "events").glob("event_read_file_*.txt")) -def test_collapse_undelivered_oversize_only_touches_new_events( - tmp_path, event_stream_limits -): - es, _ = _stream(tmp_path, event_stream_limits) +def test_collapse_undelivered_oversize_only_touches_new_events(tmp_path): + es, _ = _stream(tmp_path) read_before = _read_result(0, 1200) es.log("action_end", read_before, action_name="read_file") es.mark_delivered() @@ -172,6 +170,10 @@ def has_session_cache(self, task_id, call_type): def reset_session_history(self, task_id, call_type): pass + def input_budget(self): + # Room to spare, so each fold keeps context.keep_recent_tokens. + return 1_000_000 + async def generate_response_async(self, system_prompt, user_prompt, **kw): from agent_core.core.impl.llm.interface import LLMContextOverflowError @@ -183,10 +185,12 @@ async def generate_response_async(self, system_prompt, user_prompt, **kw): def _router(monkeypatch, stream, llm): import agent_core.core.impl.action.router as router_module + from app import config as app_config monkeypatch.setattr( router_module, "get_event_stream_manager", lambda: _Manager(stream) ) + monkeypatch.setattr(app_config, "get_keep_recent_tokens", lambda: KEEP_TOKENS) return router_module.ActionRouter(None, llm, _ContextEngine()) @@ -201,10 +205,8 @@ def _decide(router, stream): ) -def test_router_folds_then_collapses_new_events_that_cannot_fit( - tmp_path, event_stream_limits, monkeypatch -): - es, summarizer = _stream(tmp_path, event_stream_limits) +def test_router_folds_then_collapses_new_events_that_cannot_fit(tmp_path, monkeypatch): + es, summarizer = _stream(tmp_path) _history(es) es.mark_delivered() es.log("action_end", _read_result(0, 1200), action_name="read_file") @@ -220,12 +222,10 @@ def test_router_folds_then_collapses_new_events_that_cannot_fit( assert all(r.delivered for r in es.tail_events) -def test_router_gives_up_when_nothing_is_left_to_shrink( - tmp_path, event_stream_limits, monkeypatch -): +def test_router_gives_up_when_nothing_is_left_to_shrink(tmp_path, monkeypatch): from agent_core.core.impl.llm.interface import LLMContextOverflowError - es, _ = _stream(tmp_path, event_stream_limits) + es, _ = _stream(tmp_path) _history(es) es.mark_delivered() # Many new results, each just under the externalization threshold. @@ -238,10 +238,8 @@ def test_router_gives_up_when_nothing_is_left_to_shrink( assert len(llm.sent) == 2 # refused, refused after the fold, then gave up -def test_a_stateless_answer_marks_the_stream_delivered( - tmp_path, event_stream_limits, monkeypatch -): - es, _ = _stream(tmp_path, event_stream_limits) +def test_a_stateless_answer_marks_the_stream_delivered(tmp_path, monkeypatch): + es, _ = _stream(tmp_path) _history(es, 3) llm = _StatelessLLM() diff --git a/tests/test_event_stream_oversize.py b/tests/test_event_stream_oversize.py index a884c7a71..641eaabf0 100644 --- a/tests/test_event_stream_oversize.py +++ b/tests/test_event_stream_oversize.py @@ -24,6 +24,9 @@ ) +KEEP_TOKENS = 10000 + + class _CountingLLM: consecutive_failures = 0 _max_consecutive_failures = 5 @@ -36,26 +39,23 @@ def generate_response(self, user_prompt=None, prompt_name=None, **kw): return "SUMMARY OF OLD EVENTS" -def _stream(tmp_path, llm, event_stream_limits): - event_stream_limits(10000) +def _stream(tmp_path, llm): return EventStream(llm=llm, temp_dir=tmp_path / "events") -def test_appending_never_folds_on_its_own(tmp_path, event_stream_limits): +def test_appending_never_folds_on_its_own(tmp_path): """The decision lives with the router; log() only appends.""" llm = _CountingLLM() - es = _stream(tmp_path, llm, event_stream_limits) + es = _stream(tmp_path, llm) for i in range(400): es.log("action_end", f"action {i} completed " + "x " * 200) assert llm.calls == 0 assert es.head_summary is None -def test_oversized_pinned_event_is_collapsed_in_place_by_a_fold( - tmp_path, event_stream_limits -): +def test_oversized_pinned_event_is_collapsed_in_place_by_a_fold(tmp_path): llm = _CountingLLM() - es = _stream(tmp_path, llm, event_stream_limits) + es = _stream(tmp_path, llm) for i in range(60): es.log("action_end", f"action {i} completed " + "x " * 200) @@ -66,7 +66,7 @@ def test_oversized_pinned_event_is_collapsed_in_place_by_a_fold( es.mark_delivered() # the agent read it last turn before = es._total_tokens - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=KEEP_TOKENS) assert es._total_tokens < before # The record survives so the UI can still pair action_start <-> action_end... @@ -78,13 +78,11 @@ def test_oversized_pinned_event_is_collapsed_in_place_by_a_fold( assert written and written[0].read_text(encoding="utf-8") == giant.strip() -def test_a_fold_gets_under_budget_and_a_second_one_is_free( - tmp_path, event_stream_limits -): - """One requested fold must leave the stream near keep_recent_tokens, with +def test_a_fold_gets_under_budget_and_a_second_one_is_free(tmp_path): + """One requested fold must leave the stream near its keep target, with protected events intact; asking again with nothing foldable costs no call.""" llm = _CountingLLM() - es = _stream(tmp_path, llm, event_stream_limits) + es = _stream(tmp_path, llm) es.log("requirements", "[ ] done_when: the ledger reconciles") for i in range(300): @@ -97,20 +95,20 @@ def test_a_fold_gets_under_budget_and_a_second_one_is_free( ) es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=KEEP_TOKENS) after_first = es._total_tokens assert ( - after_first < 10000 + 4000 - ) # keep_recent_tokens plus a pinned/protected margin + after_first < KEEP_TOKENS + 4000 + ) # the keep target plus a pinned/protected margin assert any(r.event.kind == "requirements" for r in es.tail_events) calls = llm.calls - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=KEEP_TOKENS) assert llm.calls == calls assert es._total_tokens <= after_first -def test_tiny_foldable_region_is_pruned_not_summarized(tmp_path, event_stream_limits): +def test_tiny_foldable_region_is_pruned_not_summarized(tmp_path): """The 31,907 -> 31,529 case: a 15s LLM call that reclaimed 378 tokens. When the tail is dominated by events summarization is not allowed to touch @@ -118,7 +116,7 @@ def test_tiny_foldable_region_is_pruned_not_summarized(tmp_path, event_stream_li be far too small to be worth a blocking round trip. Prune it instead. """ llm = _CountingLLM() - es = _stream(tmp_path, llm, event_stream_limits) + es = _stream(tmp_path, llm) # A small foldable prefix the model has read... for i in range(3): @@ -128,7 +126,7 @@ def test_tiny_foldable_region_is_pruned_not_summarized(tmp_path, event_stream_li for i in range(80): es.log("action_end", f"result {i}: " + "r " * 500) - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=KEEP_TOKENS) assert llm.calls == 0 messages = [r.event.message for r in es.tail_events] diff --git a/tests/test_event_stream_protection.py b/tests/test_event_stream_protection.py index 661c4b1e5..d8939606e 100644 --- a/tests/test_event_stream_protection.py +++ b/tests/test_event_stream_protection.py @@ -29,10 +29,8 @@ def generate_response(self, user_prompt=None, prompt_name=None, **kw): return "SUMMARY OF OLD EVENTS" -def test_requirements_survive_summarization(event_stream_limits): +def test_requirements_survive_summarization(): assert "requirements" in PROTECTED_SUMMARY_KINDS - - event_stream_limits(100) es = EventStream(llm=_FakeLLM()) # The protected contract, logged FIRST so it becomes the oldest event. @@ -48,7 +46,7 @@ def test_requirements_survive_summarization(event_stream_limits): ) es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=100) kinds = [r.event.kind for r in es.tail_events] # Summarization actually happened (old filler collapsed into the summary)… @@ -63,19 +61,17 @@ def test_requirements_survive_summarization(event_stream_limits): assert any("chronological version table" in r.event.message for r in kept) -def test_protected_only_region_is_noop(event_stream_limits): +def test_protected_only_region_is_noop(): # If the only summarizable-aged content is protected, nothing is collapsed # (and it doesn't crash). - event_stream_limits(100) es = EventStream(llm=_FakeLLM()) es.log("requirements", "\n [ ] x: y\n done_when: z") es.mark_delivered() - es.summarize_by_LLM() # force; region is tiny + protected + es.summarize_by_LLM(keep_tokens=100) # force; region is tiny + protected assert any(r.event.kind == "requirements" for r in es.tail_events) -def test_only_the_newest_requirements_snapshot_stays_pinned(event_stream_limits): - event_stream_limits(100) +def test_only_the_newest_requirements_snapshot_stays_pinned(): llm = _FakeLLM() es = EventStream(llm=llm) @@ -88,7 +84,7 @@ def test_only_the_newest_requirements_snapshot_stays_pinned(event_stream_limits) es.log("action_end", f"{task}: step {i} produced some output text") es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=100) kept = [r for r in es.tail_events if r.event.kind == "requirements"] assert len(kept) == 1 @@ -98,11 +94,10 @@ def test_only_the_newest_requirements_snapshot_stays_pinned(event_stream_limits) assert "scope: send emails" in llm.prompts[0] -def test_a_superseded_requirements_update_folds_too(event_stream_limits): +def test_a_superseded_requirements_update_folds_too(): """set_requirement re-issues the COMPLETE list on every update (e.g. the Verify pass marking items satisfied), so only the latest one is the contract.""" - event_stream_limits(100) es = EventStream(llm=_FakeLLM()) es.log("requirements", "\n [ ] scope: send five emails") for i in range(100): @@ -112,7 +107,7 @@ def test_a_superseded_requirements_update_folds_too(event_stream_limits): es.log("action_end", f"later step {i} produced some output text too") es.mark_delivered() - es.summarize_by_LLM() + es.summarize_by_LLM(keep_tokens=100) kept = [r.event.message for r in es.tail_events if r.event.kind == "requirements"] assert kept == ["[SAT] scope: send five emails"] diff --git a/tests/test_session_clear.py b/tests/test_session_clear.py new file mode 100644 index 000000000..2476f936b --- /dev/null +++ b/tests/test_session_clear.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +"""/clear starts a session over as a new session. + +It used to clear only the conversation on screen plus the event stream and +todos: the session kept its loaded skills, token totals, title, NOTE.md and +EVENT.md (both named in every prompt), the LLM interface kept its history +(the cleanup called a method that does not exist), and a run in flight +carried on. These tests pin what a clear resets and what it must not touch: +other sessions' streams and caches shared between sessions. +""" + +from __future__ import annotations + +import asyncio +import time +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +from agent_core.core.impl.event_stream.manager import EventStreamManager +from agent_core.core.impl.llm import LLMCallType +from agent_core.core.impl.llm.interface import LLMInterface, RequestUsage +from agent_core.core.impl.session.manager import SessionManager +from agent_core.core.session import MAIN_SESSION_ID, Session, SessionType +from agent_core.core.state.session import StateSession +from app.models.factory import ModelFactory + +ACTION = LLMCallType.ACTION_SELECTION + + +def _llm(provider="grok", model="grok-4.3"): + ctx = { + "provider": provider, + "model": model, + "client": object(), + "gemini_client": None, + "remote_url": None, + "byteplus": None, + "anthropic_client": None, + "bedrock_client": None, + "initialized": True, + "auth_mode": "api_key", + } + with patch.object(ModelFactory, "create", return_value=ctx): + return LLMInterface(provider=provider, model=model, api_key="k", base_url="") + + +def _manager(tmp_path, llm=None, own_streams=True): + streams = EventStreamManager(llm=None) + manager = SessionManager( + event_stream_manager=streams, + llm_interface=llm, + context_engine=SimpleNamespace(make_prompt=lambda **kw: ("SYSTEM", "")), + workspace_root=tmp_path, + on_stream_create=( + (lambda sid, wd: streams.create_stream(sid, wd)) if own_streams else None + ), + ) + return manager, streams + + +def _talked(manager, streams, llm, session): + """A session mid-conversation: events, todos, a skill, LLM history.""" + stream = streams.get_stream_by_id(session.id) + stream.log("action_end", "old work " + "x " * 50) + stream.head_summary = "SUMMARY OF OLD WORK" + manager.update_todos(session.id, [{"content": "Collect: old", "status": "pending"}]) + session.selected_skills = ["old-skill"] + session.total_input_tokens = 5000 + session.title = "Weather in Fukuoka" + if llm is not None: + key = f"{session.id}:{ACTION}" + llm._session_histories[key] = [{"role": "user", "content": "old"}] + llm._last_input_tokens[key] = 5000 + llm._last_requests[key] = RequestUsage( + 5000, 4000, time.time(), "grok", "grok-4.3" + ) + + +def test_a_cleared_session_starts_over_as_a_new_one(tmp_path): + llm = _llm() + manager, streams = _manager(tmp_path, llm) + session = manager.create_session() + _talked(manager, streams, llm, session) + properties_before = StateSession.get(session.id).agent_properties + try: + assert manager.clear_session(session.id) + + stream = streams.get_stream_by_id(session.id) + assert stream.tail_events == [] and stream.head_summary is None + assert session.todos == [] and session.selected_skills == [] + assert session.total_input_tokens == 0 + assert session.title == "New chat" # titled again from its next request + assert StateSession.get(session.id).agent_properties is not properties_before + # The LLM forgot the conversation but still serves it on the session path. + key = f"{session.id}:{ACTION}" + assert key not in llm._session_histories + assert llm.last_input_tokens(session.id, ACTION) is None + assert llm.last_request(session.id, ACTION) is None + assert llm.has_session_cache(session.id, ACTION) + finally: + StateSession.end(session.id) + + +def test_a_clear_keeps_the_sessions_identity(tmp_path): + manager, streams = _manager(tmp_path) + session = manager.restore_session( + Session.from_dict( + { + "id": "lui_app", + "type": SessionType.AGENT_APP, + "title": "Command Center", + "agent_app_project_id": "9a07529e", + "reasoning_effort": "high", + } + ) + ) + streams.create_stream(session.id, Path(session.workspace_dir)) + try: + manager.clear_session(session.id) + assert session.title == "Command Center" # only chats are retitled + assert session.agent_app_project_id == "9a07529e" + assert session.reasoning_effort == "high" + finally: + StateSession.end(session.id) + + +def test_a_clear_never_touches_another_sessions_stream(tmp_path): + # get_stream_by_id falls back to the main stream for a session with none. + manager, streams = _manager(tmp_path, own_streams=False) + streams.get_main_stream().log("action_end", "main's own work") + session = manager.create_session() + try: + manager.clear_session(session.id) + assert streams.get_main_stream().tail_events + finally: + StateSession.end(session.id) + + +def test_a_clear_keeps_caches_other_sessions_share(tmp_path): + # Gemini's explicit cache is keyed by system prompt, shared by every + # session: deleting it would cost all of them their cached prefix. + llm = _llm() + deleted = [] + llm._gemini_cache_manager = SimpleNamespace( + invalidate_cache=lambda *a: deleted.append(a) + ) + llm.provider = "gemini" + llm.create_session_cache("s1", ACTION, "SYSTEM") + llm.restart_session("s1") + assert deleted == [] + + +# ─────────────────────────── workspace files ─────────────────────────── + + +def test_a_clear_resets_the_files_named_in_every_prompt(tmp_path): + from app.session.session_manager import _NOTE_SCRATCHPAD_HEADER + from app.session.session_manager import SessionManager as AppSessionManager + + streams = EventStreamManager(llm=None) + manager = AppSessionManager(event_stream_manager=streams) + manager.workspace_root = tmp_path # never the real agent workspace + manager._on_session_persist = None # never the real session storage + session = manager.create_session() + workspace = Path(session.workspace_dir) + try: + (workspace / "NOTE.md").write_text("old plan", encoding="utf-8") + (workspace / "EVENT.md").write_text("old events", encoding="utf-8") + (workspace / "EVENT_UNPROCESSED.md").write_text("for memory", encoding="utf-8") + (workspace / "report.pdf").write_bytes(b"user file") + + assert manager.clear_session(session.id) + + assert (workspace / "NOTE.md").read_text( + encoding="utf-8" + ) == _NOTE_SCRATCHPAD_HEADER + assert (workspace / "EVENT.md").read_text(encoding="utf-8") == "" + # Long-term memory still learns from the cleared conversation. + assert (workspace / "EVENT_UNPROCESSED.md").read_text( + encoding="utf-8" + ) == "for memory" + assert (workspace / "report.pdf").read_bytes() == b"user file" + finally: + StateSession.end(session.id) + + +# ─────────────────────────── the agent entry ─────────────────────────── + + +def test_a_run_in_flight_is_stopped_before_the_clear_and_the_reset_is_saved(): + from app.agent_base import AgentBase + + calls = [] + + async def request_run_stop(session_id): + calls.append(("stop", session_id)) + return True + + agent = SimpleNamespace( + busy_sessions={"s1"}, + request_run_stop=request_run_stop, + session_manager=SimpleNamespace( + clear_session=lambda session_id: calls.append(("clear", session_id)) or True + ), + # The saved LLM state goes too, or a restart would bring it back. + _persist_llm_session=lambda session_id: calls.append(("save", session_id)), + ) + assert asyncio.run(AgentBase.clear_session(agent, "s1")) + assert calls == [("stop", "s1"), ("clear", "s1"), ("save", "s1")] + + calls.clear() + agent.busy_sessions = set() + asyncio.run(AgentBase.clear_session(agent, "s1")) + assert calls == [("clear", "s1"), ("save", "s1")] # idle: nothing to stop + + +def test_the_main_session_keeps_its_title(tmp_path): + manager, _ = _manager(tmp_path) + main = manager.ensure_main() + try: + manager.clear_session(MAIN_SESSION_ID) + assert main.title == "Main" + finally: + StateSession.end(MAIN_SESSION_ID) From 6e216754bc9bb9c5587676caecc936a9791e9631 Mon Sep 17 00:00:00 2001 From: CraftBot Date: Mon, 19 Oct 2026 17:31:39 +0900 Subject: [PATCH 2/2] Update model catalog to also handle cache expiration --- agent_core/core/impl/llm/interface.py | 20 +- agent_core/core/models/cache_lifetime.py | 112 ------ agent_core/core/models/catalog.py | 68 +++- agent_core/core/models/model_catalog.json | 426 +++++++++++----------- agent_core/core/models/provider_config.py | 43 --- scripts/catalog_overrides.json | 17 - scripts/gen_model_catalog.py | 197 +++++----- scripts/model_catalog_sources.json | 81 ++++ tests/llm/test_context_readout.py | 82 ++--- tests/llm/test_reasoning_rules.py | 9 +- tests/test_context_budget.py | 71 ++-- tests/test_model_catalog_generator.py | 156 ++++++++ 12 files changed, 732 insertions(+), 550 deletions(-) delete mode 100644 agent_core/core/models/cache_lifetime.py delete mode 100644 scripts/catalog_overrides.json create mode 100644 scripts/model_catalog_sources.json create mode 100644 tests/test_model_catalog_generator.py diff --git a/agent_core/core/impl/llm/interface.py b/agent_core/core/impl/llm/interface.py index f9cefbb41..670fa6302 100644 --- a/agent_core/core/impl/llm/interface.py +++ b/agent_core/core/impl/llm/interface.py @@ -44,8 +44,11 @@ ) from agent_core.core.impl.llm import transports as _transports from agent_core.core.impl.llm.types import LLMCallType -from agent_core.core.models.cache_lifetime import CacheLifetime, cache_lifetime -from agent_core.core.models.catalog import model_limits +from agent_core.core.models.catalog import ( + CacheLifetime, + model_limits, + reports_cached_tokens as _reports_cached_tokens, +) from agent_core.core.models.reasoning import ( ReasoningChoice, ReasoningDecision, @@ -931,15 +934,14 @@ def input_budget_for(self, choice: ReasoningChoice) -> int: def prompt_cache_lifetime(self) -> Optional[CacheLifetime]: """How long the provider keeps the prompt cache of a request to this - model, or None when it documents no lifetime.""" - if self.provider == "bedrock" and not self._bedrock_model_supports_caching(): - return None - return cache_lifetime(self.provider, self.model, self._auth_mode) + model (model catalog); None when the catalog gives none.""" + limits = model_limits(self.provider, self.model, self._auth_mode) + return limits.cache_lifetime if limits is not None else None def reports_cached_tokens(self) -> bool: - """Whether this provider's responses say how much input was cached.""" - profile = _get_registry().get(self.provider) - return profile is not None and profile.reports_cached_tokens + """Whether this provider's responses say how much input was cached + (model catalog).""" + return _reports_cached_tokens(self.provider, self._auth_mode) def surface(self) -> str: """Where requests are served: the provider, or its subscription diff --git a/agent_core/core/models/cache_lifetime.py b/agent_core/core/models/cache_lifetime.py deleted file mode 100644 index cc1675b40..000000000 --- a/agent_core/core/models/cache_lifetime.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -"""How long a provider keeps the prompt cache of a session's last request. - -No provider reports an expiry time in its responses, so the cache of a -session's last request can only be timed from the lifetime the provider -documents, counted from the start of that request. Only providers that -document a lifetime have a row here: - -* EXACT: the provider guarantees at least this long after a request that - wrote or read the cache (OpenAI GPT-5.6+, Anthropic, Bedrock). -* TYPICAL: the provider only documents a usual figure and may drop the - cache sooner (OpenAI models before GPT-5.6). - -Every other provider caches best-effort or not at all (xAI evicts at any -time, DeepSeek within hours to days, local servers until the model unloads, -OpenRouter depends on the upstream it picks), so it has no row and no -countdown is shown for it. - -Keys follow the reasoning table: ``reasoning_surface(provider, auth_mode)`` -and the EXACT model id (no prefix or substring matching). -""" - -from __future__ import annotations - -from dataclasses import dataclass -from enum import Enum -from typing import Dict, Mapping, Optional - -from agent_core.core.models.reasoning import reasoning_surface - - -class CacheLifetimeKind(str, Enum): - EXACT = "exact" - TYPICAL = "typical" - - -@dataclass(frozen=True) -class CacheLifetime: - """How long a request's prompt cache stays usable after it starts.""" - - kind: CacheLifetimeKind - seconds: int - #: Where the figure comes from. - source: str - - -_OPENAI_DOCS = "https://developers.openai.com/api/docs/guides/prompt-caching" - -#: prompt_cache_options.ttl defaults to "30m", its only value: a prefix stays -#: usable 30 minutes after its most recent write or reuse (a minimum). -_OPENAI_30_MIN = CacheLifetime(CacheLifetimeKind.EXACT, 30 * 60, _OPENAI_DOCS) - -#: Before GPT-5.6, in_memory entries "typically remain active for around 5 to -#: 10 minutes of inactivity" and 24h entries "around 30 minutes"; which one -#: applies depends on the organization, so the shorter figure is shown. -_OPENAI_TYPICAL = CacheLifetime(CacheLifetimeKind.TYPICAL, 5 * 60, _OPENAI_DOCS) - -#: The session path asks for ttl="1h" (transports/anthropic_messages.py); -#: every hit or write refreshes it, timed from the start of the request. -_ANTHROPIC_1_HOUR = CacheLifetime( - CacheLifetimeKind.EXACT, - 60 * 60, - "https://platform.claude.com/docs/en/build-with-claude/prompt-caching", -) - -#: cachePoint is sent without a ttl: five minutes, reset by each cache hit. -_BEDROCK_5_MIN = CacheLifetime( - CacheLifetimeKind.EXACT, - 5 * 60, - "https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html", -) - -#: Lifetime that applies to every model of a surface. -_SURFACE_LIFETIMES: Mapping[str, CacheLifetime] = { - "openai": _OPENAI_TYPICAL, - "anthropic": _ANTHROPIC_1_HOUR, - "bedrock": _BEDROCK_5_MIN, -} - - -def _models(lifetime: CacheLifetime, *model_ids: str) -> Dict[str, CacheLifetime]: - return {model_id: lifetime for model_id in model_ids} - - -#: Models whose lifetime differs from their surface's. -_MODEL_LIFETIMES: Mapping[str, Mapping[str, CacheLifetime]] = { - "openai": _models( - _OPENAI_30_MIN, - "gpt-5.6", - "gpt-5.6-sol", - "gpt-5.6-terra", - "gpt-5.6-luna", - "gpt-6-sol", - "gpt-6-luna", - "gpt-6-astra", - "gpt-6.1-sol", - ), -} - - -def cache_lifetime( - provider: Optional[str], model: Optional[str], auth_mode: str = "api_key" -) -> Optional[CacheLifetime]: - """The documented prompt-cache lifetime of ``model``, or None if the - provider documents none.""" - if not provider or not model: - return None - surface = reasoning_surface(provider, auth_mode) - by_model = _MODEL_LIFETIMES.get(surface, {}).get(model) - if by_model is not None: - return by_model - return _SURFACE_LIFETIMES.get(surface) diff --git a/agent_core/core/models/catalog.py b/agent_core/core/models/catalog.py index 276aa8e41..2223e896e 100644 --- a/agent_core/core/models/catalog.py +++ b/agent_core/core/models/catalog.py @@ -1,57 +1,97 @@ # -*- coding: utf-8 -*- -"""Context limits per model, read from the vendored model catalog. +"""What a model can take, and what its provider does, read from the vendored +model catalog. model_catalog.json (next to this module, so it ships with the code and an -upgrade replaces it) is generated by scripts/gen_model_catalog.py from -models.dev, the Codex model catalogue (ChatGPT-subscription surface) and -scripts/catalog_overrides.json. Nothing is fetched at runtime. +upgrade replaces it) is generated by scripts/gen_model_catalog.py from the +sources and facts in scripts/model_catalog_sources.json. Nothing is fetched +at runtime, and no model or provider fact lives in code: what the catalog +does not list gets the defaults below. -Rows are keyed ``/`` with the surface from +Model rows are keyed ``/`` with the surface from ``reasoning_surface``, the same keys as the reasoning table, and match the -EXACT model id (no prefix or substring matching). A model with no row is not -catalogued; its caller uses settings.json model.context_window. +EXACT model id (no prefix or substring matching). + +Defaults for what the catalog does not list: + +* a model: no row (None); callers use settings.json model.context_window + and show no cache countdown; +* a surface: its responses report cached input. """ from __future__ import annotations import json from dataclasses import dataclass +from enum import Enum from functools import lru_cache from pathlib import Path -from typing import Mapping, Optional +from typing import Any, Mapping, Optional from agent_core.core.models.reasoning import reasoning_surface CATALOG_PATH = Path(__file__).with_name("model_catalog.json") +class CacheLifetimeKind(str, Enum): + #: The provider keeps the cache at least this long after a request. + EXACT = "exact" + #: The provider's usual figure only; it may drop the cache sooner. + TYPICAL = "typical" + + +@dataclass(frozen=True) +class CacheLifetime: + """How long a request's prompt cache stays usable after it starts.""" + + kind: CacheLifetimeKind + seconds: int + + @dataclass(frozen=True) class ModelLimits: - """What a model can take in one request.""" + """What the catalog says about one model.""" #: Input plus output tokens the model accepts. context_window: int #: Input tokens the provider accepts whatever output is requested, when - #: it caps input below the window (GPT-5: 272,000 of a 400,000 window). + #: it caps input below the window. max_input_tokens: Optional[int] = None + #: How long the provider keeps the model's prompt cache; None when the + #: provider documents no lifetime. + cache_lifetime: Optional[CacheLifetime] = None @lru_cache(maxsize=1) -def _rows() -> Mapping[str, Mapping[str, int]]: +def _catalog() -> Mapping[str, Any]: with open(CATALOG_PATH, encoding="utf-8") as f: - return json.load(f)["models"] + return json.load(f) def model_limits( provider: Optional[str], model: Optional[str], auth_mode: str = "api_key" ) -> Optional[ModelLimits]: - """The catalogued limits of ``model`` on ``provider``, or None.""" + """The catalogued facts of ``model`` on ``provider``, or None.""" if not provider or not model: return None - row = _rows().get(f"{reasoning_surface(provider, auth_mode)}/{model}") + row = _catalog()["models"].get(f"{reasoning_surface(provider, auth_mode)}/{model}") if row is None: return None + lifetime = row.get("cache_lifetime") return ModelLimits( context_window=row["context_window"], max_input_tokens=row.get("max_input_tokens"), + cache_lifetime=( + CacheLifetime(CacheLifetimeKind(lifetime["kind"]), lifetime["seconds"]) + if lifetime + else None + ), ) + + +def reports_cached_tokens(provider: Optional[str], auth_mode: str = "api_key") -> bool: + """Whether ``provider``'s responses say how much input came from cache.""" + if not provider: + return True + facts = _catalog()["surfaces"].get(reasoning_surface(provider, auth_mode), {}) + return facts.get("reports_cached_tokens", True) diff --git a/agent_core/core/models/model_catalog.json b/agent_core/core/models/model_catalog.json index 13d4e2aa0..1d4cbc00e 100644 --- a/agent_core/core/models/model_catalog.json +++ b/agent_core/core/models/model_catalog.json @@ -1,128 +1,136 @@ { - "generator": "scripts/gen_model_catalog.py", - "sources": ["https://models.dev/api.json", "https://raw.githubusercontent.com/openai/codex/main/codex-rs/models-manager/models.json", "scripts/catalog_overrides.json"], + "generator": "scripts/gen_model_catalog.py from scripts/model_catalog_sources.json", + "surfaces": { + "fireworks": {"reports_cached_tokens": false}, + "huggingface": {"reports_cached_tokens": false}, + "llamacpp": {"reports_cached_tokens": false}, + "lmstudio": {"reports_cached_tokens": false}, + "nvidia": {"reports_cached_tokens": false}, + "remote": {"reports_cached_tokens": false}, + "vllm": {"reports_cached_tokens": false} + }, "models": { - "anthropic/claude-fable-5": {"context_window": 1000000}, - "anthropic/claude-fable-5-1": {"context_window": 1000000}, - "anthropic/claude-haiku-4-5": {"context_window": 200000}, - "anthropic/claude-haiku-4-5-20251001": {"context_window": 200000}, - "anthropic/claude-haiku-5-5": {"context_window": 1000000}, - "anthropic/claude-opus-4-5": {"context_window": 200000}, - "anthropic/claude-opus-4-5-20251101": {"context_window": 200000}, - "anthropic/claude-opus-4-6": {"context_window": 1000000}, - "anthropic/claude-opus-4-7": {"context_window": 1000000}, - "anthropic/claude-opus-4-8": {"context_window": 1000000}, - "anthropic/claude-opus-5": {"context_window": 1000000}, - "anthropic/claude-opus-5-5": {"context_window": 1000000}, - "anthropic/claude-sonnet-4-5": {"context_window": 200000}, - "anthropic/claude-sonnet-4-5-20250929": {"context_window": 200000}, - "anthropic/claude-sonnet-4-6": {"context_window": 1000000}, - "anthropic/claude-sonnet-5": {"context_window": 1000000}, - "anthropic/claude-sonnet-5-5": {"context_window": 1000000}, - "bedrock/amazon.nova-2-lite-v1:0": {"context_window": 1000000}, - "bedrock/amazon.nova-lite-v1:0": {"context_window": 300000}, - "bedrock/amazon.nova-micro-v1:0": {"context_window": 128000}, - "bedrock/amazon.nova-pro-v1:0": {"context_window": 300000}, - "bedrock/anthropic.claude-fable-5": {"context_window": 1000000}, - "bedrock/anthropic.claude-fable-5-1": {"context_window": 1000000}, - "bedrock/anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, - "bedrock/anthropic.claude-haiku-5-5": {"context_window": 1000000}, - "bedrock/anthropic.claude-opus-4-1-20250805-v1:0": {"context_window": 200000}, - "bedrock/anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, - "bedrock/anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, - "bedrock/anthropic.claude-opus-4-7": {"context_window": 1000000}, - "bedrock/anthropic.claude-opus-4-8": {"context_window": 1000000}, - "bedrock/anthropic.claude-opus-5": {"context_window": 1000000}, - "bedrock/anthropic.claude-opus-5-5": {"context_window": 1000000}, - "bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, - "bedrock/anthropic.claude-sonnet-4-6": {"context_window": 1000000}, - "bedrock/anthropic.claude-sonnet-5": {"context_window": 1000000}, - "bedrock/anthropic.claude-sonnet-5-5": {"context_window": 1000000}, - "bedrock/apac.amazon.nova-lite-v1:0": {"context_window": 300000}, - "bedrock/apac.amazon.nova-micro-v1:0": {"context_window": 128000}, - "bedrock/apac.amazon.nova-pro-v1:0": {"context_window": 300000}, - "bedrock/apac.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, - "bedrock/au.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, - "bedrock/au.anthropic.claude-haiku-5-5": {"context_window": 1000000}, - "bedrock/au.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, - "bedrock/au.anthropic.claude-opus-4-7": {"context_window": 1000000}, - "bedrock/au.anthropic.claude-opus-4-8": {"context_window": 1000000}, - "bedrock/au.anthropic.claude-opus-5": {"context_window": 1000000}, - "bedrock/au.anthropic.claude-opus-5-5": {"context_window": 1000000}, - "bedrock/au.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, - "bedrock/au.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, - "bedrock/au.anthropic.claude-sonnet-5": {"context_window": 1000000}, - "bedrock/ca.amazon.nova-lite-v1:0": {"context_window": 300000}, + "anthropic/claude-fable-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-fable-5-1": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-haiku-4-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 200000}, + "anthropic/claude-haiku-4-5-20251001": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 200000}, + "anthropic/claude-haiku-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-opus-4-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 200000}, + "anthropic/claude-opus-4-5-20251101": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 200000}, + "anthropic/claude-opus-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-opus-4-7": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-opus-4-8": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-opus-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-sonnet-4-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 200000}, + "anthropic/claude-sonnet-4-5-20250929": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 200000}, + "anthropic/claude-sonnet-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "anthropic/claude-sonnet-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 3600}, "context_window": 1000000}, + "bedrock/amazon.nova-2-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/amazon.nova-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/amazon.nova-micro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 128000}, + "bedrock/amazon.nova-pro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/anthropic.claude-fable-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-fable-5-1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-haiku-4-5-20251001-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/anthropic.claude-haiku-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-opus-4-1-20250805-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/anthropic.claude-opus-4-5-20251101-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/anthropic.claude-opus-4-6-v1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-opus-4-7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-opus-4-8": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-opus-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/anthropic.claude-sonnet-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/anthropic.claude-sonnet-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/apac.amazon.nova-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/apac.amazon.nova-micro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 128000}, + "bedrock/apac.amazon.nova-pro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/apac.anthropic.claude-sonnet-4-20250514-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/au.anthropic.claude-haiku-4-5-20251001-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/au.anthropic.claude-haiku-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-4-6-v1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-4-7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-4-8": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/au.anthropic.claude-opus-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/au.anthropic.claude-sonnet-4-5-20250929-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/au.anthropic.claude-sonnet-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/au.anthropic.claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/ca.amazon.nova-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, "bedrock/deepseek.r1-v1:0": {"context_window": 128000}, "bedrock/deepseek.v3-v1:0": {"context_window": 163840}, "bedrock/deepseek.v3.2": {"context_window": 163840}, - "bedrock/eu.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, - "bedrock/eu.amazon.nova-lite-v1:0": {"context_window": 300000}, - "bedrock/eu.amazon.nova-micro-v1:0": {"context_window": 128000}, - "bedrock/eu.amazon.nova-pro-v1:0": {"context_window": 300000}, - "bedrock/eu.anthropic.claude-fable-5": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, - "bedrock/eu.anthropic.claude-haiku-5-5": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, - "bedrock/eu.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-opus-4-7": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-opus-4-8": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-opus-5": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-opus-5-5": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, - "bedrock/eu.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, - "bedrock/eu.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-sonnet-5": {"context_window": 1000000}, - "bedrock/eu.anthropic.claude-sonnet-5-5": {"context_window": 1000000}, + "bedrock/eu.amazon.nova-2-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.amazon.nova-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/eu.amazon.nova-micro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 128000}, + "bedrock/eu.amazon.nova-pro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/eu.anthropic.claude-fable-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-haiku-4-5-20251001-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/eu.anthropic.claude-haiku-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-4-5-20251101-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/eu.anthropic.claude-opus-4-6-v1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-4-7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-4-8": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-opus-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-sonnet-4-20250514-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/eu.anthropic.claude-sonnet-4-5-20250929-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/eu.anthropic.claude-sonnet-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/eu.anthropic.claude-sonnet-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, "bedrock/eu.mistral.pixtral-large-2502-v1:0": {"context_window": 128000}, - "bedrock/global.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-fable-5": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-fable-5-1": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, - "bedrock/global.anthropic.claude-haiku-5-5": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, - "bedrock/global.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-opus-4-7": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-opus-4-8": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-opus-5": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-opus-5-5": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, - "bedrock/global.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, - "bedrock/global.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-sonnet-5": {"context_window": 1000000}, - "bedrock/global.anthropic.claude-sonnet-5-5": {"context_window": 1000000}, - "bedrock/global.moonshotai.kimi-k3": {"context_window": 1048576}, - "bedrock/global.openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/global.openai.gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/global.openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/global.openai.gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/global.openai.gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/global.openai.gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/global.openai.gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/global.xai.grok-4.6": {"context_window": 500000}, - "bedrock/global.xai.grok-4.7": {"context_window": 500000}, - "bedrock/global.zai.glm-5.3": {"context_window": 1000000}, + "bedrock/global.amazon.nova-2-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-fable-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-fable-5-1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-haiku-4-5-20251001-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/global.anthropic.claude-haiku-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-4-5-20251101-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/global.anthropic.claude-opus-4-6-v1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-4-7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-4-8": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-opus-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-sonnet-4-20250514-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/global.anthropic.claude-sonnet-4-5-20250929-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/global.anthropic.claude-sonnet-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.anthropic.claude-sonnet-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/global.moonshotai.kimi-k3": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1048576}, + "bedrock/global.openai.gpt-5.6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-5.6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-5.6-terra": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6-astra": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.openai.gpt-6.1-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/global.xai.grok-4.6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 500000}, + "bedrock/global.xai.grok-4.7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 500000}, + "bedrock/global.zai.glm-5.3": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, "bedrock/google.gemma-3-12b-it": {"context_window": 131072}, "bedrock/google.gemma-3-27b-it": {"context_window": 131072}, "bedrock/google.gemma-3-4b-it": {"context_window": 131072}, "bedrock/google.gemma-4-26b-a4b": {"context_window": 262144}, "bedrock/google.gemma-4-31b": {"context_window": 262144}, "bedrock/google.gemma-4-e2b": {"context_window": 131072}, - "bedrock/in.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, - "bedrock/in.anthropic.claude-opus-5": {"context_window": 1000000}, - "bedrock/in.anthropic.claude-sonnet-5": {"context_window": 1000000}, - "bedrock/in.openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/in.openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/jp.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, - "bedrock/jp.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, - "bedrock/jp.anthropic.claude-haiku-5-5": {"context_window": 1000000}, - "bedrock/jp.anthropic.claude-opus-4-7": {"context_window": 1000000}, - "bedrock/jp.anthropic.claude-opus-4-8": {"context_window": 1000000}, - "bedrock/jp.anthropic.claude-opus-5": {"context_window": 1000000}, - "bedrock/jp.anthropic.claude-opus-5-5": {"context_window": 1000000}, - "bedrock/jp.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, - "bedrock/jp.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, - "bedrock/jp.anthropic.claude-sonnet-5": {"context_window": 1000000}, + "bedrock/in.anthropic.claude-haiku-4-5-20251001-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/in.anthropic.claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/in.anthropic.claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/in.openai.gpt-5.6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/in.openai.gpt-5.6-terra": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/jp.amazon.nova-2-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/jp.anthropic.claude-haiku-4-5-20251001-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/jp.anthropic.claude-haiku-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-4-7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-4-8": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/jp.anthropic.claude-opus-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/jp.anthropic.claude-sonnet-4-5-20250929-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/jp.anthropic.claude-sonnet-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/jp.anthropic.claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, "bedrock/meta.llama3-1-70b-instruct-v1:0": {"context_window": 128000}, "bedrock/meta.llama3-1-8b-instruct-v1:0": {"context_window": 128000}, "bedrock/meta.llama3-3-70b-instruct-v1:0": {"context_window": 128000}, @@ -146,15 +154,15 @@ "bedrock/nvidia.nemotron-nano-3-30b": {"context_window": 262144}, "bedrock/nvidia.nemotron-nano-9b-v2": {"context_window": 131072}, "bedrock/nvidia.nemotron-super-3-120b": {"context_window": 262144}, - "bedrock/openai.gpt-5.4": {"context_window": 1000000}, - "bedrock/openai.gpt-5.5": {"context_window": 1000000}, - "bedrock/openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/openai.gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/openai.gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/openai.gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/openai.gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/openai.gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-5.4": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/openai.gpt-5.5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/openai.gpt-5.6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-5.6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-5.6-terra": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6-astra": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/openai.gpt-6.1-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, "bedrock/openai.gpt-oss-120b": {"context_window": 131072}, "bedrock/openai.gpt-oss-120b-1:0": {"context_window": 131072}, "bedrock/openai.gpt-oss-20b": {"context_window": 131072}, @@ -170,27 +178,27 @@ "bedrock/qwen.qwen3-vl-235b-a22b": {"context_window": 262144}, "bedrock/us-gov.openai.gpt-oss-120b-1:0": {"context_window": 128000}, "bedrock/us-gov.openai.gpt-oss-20b-1:0": {"context_window": 128000}, - "bedrock/us.amazon.nova-2-lite-v1:0": {"context_window": 1000000}, - "bedrock/us.amazon.nova-lite-v1:0": {"context_window": 300000}, - "bedrock/us.amazon.nova-micro-v1:0": {"context_window": 128000}, - "bedrock/us.amazon.nova-premier-v1:0": {"context_window": 1000000}, - "bedrock/us.amazon.nova-pro-v1:0": {"context_window": 300000}, - "bedrock/us.anthropic.claude-fable-5": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-fable-5-1": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0": {"context_window": 200000}, - "bedrock/us.anthropic.claude-haiku-5-5": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-opus-4-1-20250805-v1:0": {"context_window": 200000}, - "bedrock/us.anthropic.claude-opus-4-5-20251101-v1:0": {"context_window": 200000}, - "bedrock/us.anthropic.claude-opus-4-6-v1": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-opus-4-7": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-opus-4-8": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-opus-5": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-opus-5-5": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0": {"context_window": 200000}, - "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"context_window": 200000}, - "bedrock/us.anthropic.claude-sonnet-4-6": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-sonnet-5": {"context_window": 1000000}, - "bedrock/us.anthropic.claude-sonnet-5-5": {"context_window": 1000000}, + "bedrock/us.amazon.nova-2-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.amazon.nova-lite-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/us.amazon.nova-micro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 128000}, + "bedrock/us.amazon.nova-premier-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.amazon.nova-pro-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 300000}, + "bedrock/us.anthropic.claude-fable-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-fable-5-1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/us.anthropic.claude-haiku-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-4-1-20250805-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/us.anthropic.claude-opus-4-5-20251101-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/us.anthropic.claude-opus-4-6-v1": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-4-7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-4-8": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-opus-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 200000}, + "bedrock/us.anthropic.claude-sonnet-4-6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-sonnet-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/us.anthropic.claude-sonnet-5-5": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, "bedrock/us.deepseek.r1-v1:0": {"context_window": 128000}, "bedrock/us.meta.llama3-1-70b-instruct-v1:0": {"context_window": 128000}, "bedrock/us.meta.llama3-1-8b-instruct-v1:0": {"context_window": 128000}, @@ -198,23 +206,23 @@ "bedrock/us.meta.llama4-maverick-17b-instruct-v1:0": {"context_window": 1000000}, "bedrock/us.meta.llama4-scout-17b-instruct-v1:0": {"context_window": 10000000}, "bedrock/us.mistral.pixtral-large-2502-v1:0": {"context_window": 128000}, - "bedrock/us.moonshotai.kimi-k3": {"context_window": 1048576}, - "bedrock/us.openai.gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/us.openai.gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/us.openai.gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/us.openai.gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/us.openai.gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/us.openai.gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "bedrock/us.openai.gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.moonshotai.kimi-k3": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1048576}, + "bedrock/us.openai.gpt-5.6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-5.6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-5.6-terra": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6-astra": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "bedrock/us.openai.gpt-6.1-sol": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, "bedrock/us.writer.palmyra-x4-v1:0": {"context_window": 122880}, "bedrock/us.writer.palmyra-x5-v1:0": {"context_window": 1040000}, - "bedrock/us.xai.grok-4.6": {"context_window": 500000}, - "bedrock/us.xai.grok-4.7": {"context_window": 500000}, - "bedrock/us.zai.glm-5.3": {"context_window": 1000000}, + "bedrock/us.xai.grok-4.6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 500000}, + "bedrock/us.xai.grok-4.7": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 500000}, + "bedrock/us.zai.glm-5.3": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, "bedrock/writer.palmyra-x4-v1:0": {"context_window": 122880}, "bedrock/writer.palmyra-x5-v1:0": {"context_window": 1040000}, - "bedrock/xai.grok-4.3": {"context_window": 1000000}, - "bedrock/xai.grok-4.6": {"context_window": 500000}, + "bedrock/xai.grok-4.3": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 1000000}, + "bedrock/xai.grok-4.6": {"cache_lifetime": {"kind": "exact", "seconds": 300}, "context_window": 500000}, "bedrock/zai.glm-4.7": {"context_window": 202752}, "bedrock/zai.glm-4.7-flash": {"context_window": 202752}, "bedrock/zai.glm-5": {"context_window": 202752}, @@ -225,6 +233,7 @@ "deepseek/deepseek-v4-flash-vision-exp": {"context_window": 1000000}, "deepseek/deepseek-v4-pro": {"context_window": 1000000}, "fireworks/accounts/fireworks/models/deepseek-v4p1-flash": {"context_window": 1000000}, + "fireworks/accounts/fireworks/models/deepseek-v4p1-flash-1017": {"context_window": 1000000}, "fireworks/accounts/fireworks/models/ember-1": {"context_window": 1048576}, "fireworks/accounts/fireworks/models/glm-5p3": {"context_window": 1048573}, "fireworks/accounts/fireworks/models/glm-5p3-flash": {"context_window": 1048573}, @@ -559,68 +568,69 @@ "nvidia/sarvamai/sarvam-m": {"context_window": 128000}, "nvidia/stepfun-ai/step-3.5-flash": {"context_window": 256000}, "nvidia/stepfun-ai/step-3.7-flash": {"context_window": 256000}, + "nvidia/stepfun-ai/step-5-preview": {"context_window": 1048576}, "nvidia/thinkingmachines/inkling": {"context_window": 1048576}, "nvidia/upstage/solar-10.7b-instruct": {"context_window": 128000}, "nvidia/z-ai/glm-5.2": {"context_window": 1000000}, "nvidia/z-ai/glm-5.3": {"context_window": 1000000}, "nvidia/z-ai/glm-5.3-flash": {"context_window": 1000000}, - "openai/gpt-3.5-turbo": {"context_window": 16385}, + "openai/gpt-3.5-turbo": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 16385}, "openai/gpt-4": {"context_window": 8192}, "openai/gpt-4-turbo": {"context_window": 128000}, - "openai/gpt-4.1": {"context_window": 1047576}, - "openai/gpt-4.1-mini": {"context_window": 1047576}, - "openai/gpt-4.1-nano": {"context_window": 1047576}, - "openai/gpt-4o": {"context_window": 128000}, + "openai/gpt-4.1": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1047576}, + "openai/gpt-4.1-mini": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1047576}, + "openai/gpt-4.1-nano": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1047576}, + "openai/gpt-4o": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000}, "openai/gpt-4o-2024-05-13": {"context_window": 128000}, - "openai/gpt-4o-2024-08-06": {"context_window": 128000}, - "openai/gpt-4o-2024-11-20": {"context_window": 128000}, - "openai/gpt-4o-mini": {"context_window": 128000}, - "openai/gpt-5": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5-2025-08-07": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5-mini": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5-mini-2025-08-07": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5-nano": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5-nano-2025-08-07": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-4o-2024-08-06": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000}, + "openai/gpt-4o-2024-11-20": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000}, + "openai/gpt-4o-mini": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000}, + "openai/gpt-5": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-2025-08-07": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-mini": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-mini-2025-08-07": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-nano": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5-nano-2025-08-07": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, "openai/gpt-5-pro": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.1": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.1-2025-11-13": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.2": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.2-2025-12-11": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.2-chat-latest": {"context_window": 128000}, + "openai/gpt-5.1": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.1-2025-11-13": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.2": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.2-2025-12-11": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.2-chat-latest": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000}, "openai/gpt-5.2-pro": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.3-chat-latest": {"context_window": 128000}, - "openai/gpt-5.3-codex": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.3-codex-spark": {"context_window": 128000, "max_input_tokens": 100000}, - "openai/gpt-5.4": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.4-2026-03-05": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.4-mini": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.4-mini-2026-03-17": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.4-nano": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-5.4-nano-2026-03-17": {"context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.3-chat-latest": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000}, + "openai/gpt-5.3-codex": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.3-codex-spark": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000, "max_input_tokens": 100000}, + "openai/gpt-5.4": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.4-2026-03-05": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.4-mini": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.4-mini-2026-03-17": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.4-nano": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-5.4-nano-2026-03-17": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, "openai/gpt-5.4-pro": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.5": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.5-2026-04-23": {"context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.5": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.5-2026-04-23": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, "openai/gpt-5.5-pro": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.6": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-5.6-terra": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-6-astra": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-6-luna": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-6-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-6.1-sol": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-daybreak-blue-latest": {"context_window": 1050000, "max_input_tokens": 922000}, - "openai/gpt-daybreak-red-latest": {"context_window": 400000, "max_input_tokens": 272000}, - "openai/gpt-realtime-2.1": {"context_window": 128000, "max_input_tokens": 96000}, - "openai/o1": {"context_window": 200000}, + "openai/gpt-5.6": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-5.6-terra": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6-astra": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-6.1-sol": {"cache_lifetime": {"kind": "exact", "seconds": 1800}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-daybreak-blue-latest": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 1050000, "max_input_tokens": 922000}, + "openai/gpt-daybreak-red-latest": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 400000, "max_input_tokens": 272000}, + "openai/gpt-realtime-2.1": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 128000, "max_input_tokens": 96000}, + "openai/o1": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 200000}, "openai/o1-pro": {"context_window": 200000}, - "openai/o3": {"context_window": 200000}, - "openai/o3-2025-04-16": {"context_window": 200000}, - "openai/o3-mini": {"context_window": 200000}, - "openai/o3-mini-2025-01-31": {"context_window": 200000}, + "openai/o3": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 200000}, + "openai/o3-2025-04-16": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 200000}, + "openai/o3-mini": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 200000}, + "openai/o3-mini-2025-01-31": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 200000}, "openai/o3-pro": {"context_window": 200000}, - "openai/o4-mini": {"context_window": 200000}, - "openai/o4-mini-2025-04-16": {"context_window": 200000}, + "openai/o4-mini": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 200000}, + "openai/o4-mini-2025-04-16": {"cache_lifetime": {"kind": "typical", "seconds": 300}, "context_window": 200000}, "openai/text-embedding-3-large": {"context_window": 8191}, "openai/text-embedding-3-small": {"context_window": 8191}, "openai/text-embedding-ada-002": {"context_window": 8192}, @@ -796,7 +806,7 @@ "openrouter/moonshotai/kimi-k2.6": {"context_window": 262144}, "openrouter/moonshotai/kimi-k2.7-code": {"context_window": 262144}, "openrouter/moonshotai/kimi-k3": {"context_window": 1048576}, - "openrouter/morph/morph-v3-fast": {"context_window": 81920}, + "openrouter/morph/morph-v3-fast": {"context_window": 262144}, "openrouter/morph/morph-v3-large": {"context_window": 262144}, "openrouter/nex-agi/nex-n2.5-mini": {"context_window": 262144}, "openrouter/nex-agi/nex-n2.5-pro": {"context_window": 262144}, @@ -970,6 +980,7 @@ "openrouter/thinkingmachines/inkling-small": {"context_window": 524288}, "openrouter/thinkingmachines/inkling-small:free": {"context_window": 1048576}, "openrouter/thinkingmachines/inkling:free": {"context_window": 1048576}, + "openrouter/unbiased/pareto-26.10": {"context_window": 1048576}, "openrouter/unbiased/pareto-26.9": {"context_window": 262144}, "openrouter/undi95/remm-slerp-l2-13b": {"context_window": 6144}, "openrouter/upstage/solar-mini4": {"context_window": 524288}, @@ -1020,7 +1031,7 @@ "openrouter/~openai/gpt-mini-latest": {"context_window": 400000}, "openrouter/~openai/gpt-sol-latest": {"context_window": 1050000}, "openrouter/~openai/gpt-terra-latest": {"context_window": 1050000}, - "openrouter/~unbiased/pareto-latest": {"context_window": 262144}, + "openrouter/~unbiased/pareto-latest": {"context_window": 1048576}, "openrouter/~x-ai/grok-latest": {"context_window": 500000}, "openrouter/~z-ai/glm-flash-latest": {"context_window": 1048576}, "openrouter/~z-ai/glm-latest": {"context_window": 1048576}, @@ -1107,9 +1118,12 @@ "together/deepseek-ai/DeepSeek-V4.1-Flash": {"context_window": 1048576}, "together/essentialai/Rnj-1-Instruct": {"context_window": 32768}, "together/meta-llama/Llama-3.3-70B-Instruct-Turbo": {"context_window": 131072}, + "together/meta-models/Muse-Spark-Open-816B-A42B": {"context_window": 1048576}, "together/moonshotai/Kimi-K3": {"context_window": 1048576}, + "together/nvidia/NVIDIA-Nemotron-3.5-Super-VL": {"context_window": 262144}, "together/nvidia/nemotron-3-ultra-550b-a55b": {"context_window": 512300}, "together/openai/gpt-oss-120b": {"context_window": 131072}, + "together/reflection/Beam-1.0-501B-A23B": {"context_window": 1048576}, "together/thinkingmachines/Inkling": {"context_window": 524288}, "together/zai-org/GLM-5": {"context_window": 202752}, "together/zai-org/GLM-5.1": {"context_window": 202752}, diff --git a/agent_core/core/models/provider_config.py b/agent_core/core/models/provider_config.py index 7075e4eb3..2be66cff8 100644 --- a/agent_core/core/models/provider_config.py +++ b/agent_core/core/models/provider_config.py @@ -73,14 +73,6 @@ class ProviderProfile: # Frontend opts into the catalog-aware model picker (OpenRouter). supports_catalog_picker: bool = False - # ── model catalog (agent_core/core/models/catalog.py) ───────────── - # models.dev provider id whose rows scripts/gen_model_catalog.py copies - # into the model catalog for this provider (each model's context window - # and input limit). Must serve the same model ids at the same endpoint. - # None -> not catalogued, so settings.json model.context_window applies: - # local servers run whatever window the user loaded. - catalog_provider: Optional[str] = None - # ── models ──────────────────────────────────────────────────────── # {InterfaceType: default model id} (was MODEL_REGISTRY row). default_models: Mapping[InterfaceType, Optional[str]] = field(default_factory=dict) @@ -102,12 +94,6 @@ class ProviderProfile: # providers that already receive it today (NFR-3: golden payloads # must not change). supports_prompt_cache_key: bool = False - # Whether responses report how many input tokens came from the provider's - # cache. False -> the cached count is always 0 whatever the provider did - # (Fireworks puts it in a header only; HF-router, hosted NVIDIA NIM, - # Ollama and the local OpenAI-compatible servers by default omit it), so - # a cache hit rate cannot be shown for it. - reports_cached_tokens: bool = True # Temperature policy for the chat_completions wire (Hermes-style): # None -> send the caller's temperature (default behavior) # OMIT_TEMPERATURE -> do NOT send temperature (Kimi/Moonshot thinking @@ -186,7 +172,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): PROVIDER_CONFIG: Dict[str, ProviderProfile] = { "openai": ProviderProfile( key="openai", - catalog_provider="openai", session_accumulation=True, api_key_env="OPENAI_API_KEY", display_name="OpenAI", @@ -234,7 +219,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "gemini": ProviderProfile( key="gemini", - catalog_provider="google", api_key_env="GOOGLE_API_KEY", display_name="Google Gemini", wire="gemini_native", @@ -250,7 +234,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "anthropic": ProviderProfile( key="anthropic", - catalog_provider="anthropic", api_key_env="ANTHROPIC_API_KEY", display_name="Anthropic", wire="anthropic_messages", @@ -268,8 +251,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "byteplus": ProviderProfile( key="byteplus", - # No catalog_provider: models.dev lists only the China Volcengine - # endpoint, whose doubao-* ids are not the international ids below. api_key_env="BYTEPLUS_API_KEY", base_url_env="BYTEPLUS_BASE_URL", default_base_url="https://ark.ap-southeast.bytepluses.com/api/v3", @@ -291,7 +272,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "remote": ProviderProfile( key="remote", - reports_cached_tokens=False, base_url_env="REMOTE_MODEL_URL", default_base_url="http://localhost:11434", display_name="Local (Ollama)", @@ -308,7 +288,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "minimax": ProviderProfile( key="minimax", - catalog_provider="minimax", api_key_env="MINIMAX_API_KEY", # International OpenAI-compatible endpoint (verified 2026-08-17: # platform.minimax.io). The old api.minimax.chat domain is RETIRED. @@ -349,7 +328,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "deepseek": ProviderProfile( key="deepseek", - catalog_provider="deepseek", session_accumulation=True, api_key_env="DEEPSEEK_API_KEY", default_base_url="https://api.deepseek.com", @@ -368,7 +346,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "moonshot": ProviderProfile( key="moonshot", - catalog_provider="moonshotai", api_key_env="MOONSHOT_API_KEY", # International endpoint (verified 2026-08-17: platform.kimi.ai). base_url_env="MOONSHOT_BASE_URL", @@ -405,7 +382,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "grok": ProviderProfile( key="grok", - catalog_provider="xai", session_accumulation=True, api_key_env="XAI_API_KEY", default_base_url="https://api.x.ai/v1", @@ -428,7 +404,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "glm": ProviderProfile( key="glm", - catalog_provider="zai", session_accumulation=True, # Z.ai (Zhipu AI) GLM models -- OpenAI-compatible API. api_key_env="ZAI_API_KEY", @@ -449,7 +424,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "fugu": ProviderProfile( key="fugu", - catalog_provider="sakana", session_accumulation=True, # Sakana AI Fugu -- OpenAI-compatible API. api_key_env="SAKANA_API_KEY", @@ -470,7 +444,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "openrouter": ProviderProfile( key="openrouter", - catalog_provider="openrouter", session_accumulation=True, api_key_env="OPENROUTER_API_KEY", base_url_env="OPENROUTER_BASE_URL", @@ -493,7 +466,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "bedrock": ProviderProfile( key="bedrock", - catalog_provider="amazon-bedrock", # Bedrock uses the boto3 credential chain (access_key / secret_key / # session_token) read from settings.json by the factory. There is no # single API key, so api_key_env stays None. base_url_env carries the @@ -526,7 +498,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): # docs/PROVIDER_LAYER_CATCHUP.md section 8.3/8.4) ────────────────── "groq": ProviderProfile( key="groq", - catalog_provider="groq", session_accumulation=True, api_key_env="GROQ_API_KEY", base_url_env="GROQ_BASE_URL", @@ -555,7 +526,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "mistral": ProviderProfile( key="mistral", - catalog_provider="mistral", session_accumulation=True, api_key_env="MISTRAL_API_KEY", base_url_env="MISTRAL_BASE_URL", @@ -583,7 +553,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "together": ProviderProfile( key="together", - catalog_provider="togetherai", session_accumulation=True, api_key_env="TOGETHER_API_KEY", base_url_env="TOGETHER_BASE_URL", @@ -607,8 +576,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "fireworks": ProviderProfile( key="fireworks", - catalog_provider="fireworks-ai", - reports_cached_tokens=False, session_accumulation=True, api_key_env="FIREWORKS_API_KEY", base_url_env="FIREWORKS_BASE_URL", @@ -632,7 +599,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "cerebras": ProviderProfile( key="cerebras", - catalog_provider="cerebras", session_accumulation=True, api_key_env="CEREBRAS_API_KEY", base_url_env="CEREBRAS_BASE_URL", @@ -662,7 +628,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "qwen": ProviderProfile( key="qwen", - catalog_provider="alibaba", session_accumulation=True, api_key_env="DASHSCOPE_API_KEY", base_url_env="DASHSCOPE_BASE_URL", @@ -690,8 +655,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "huggingface": ProviderProfile( key="huggingface", - catalog_provider="huggingface", - reports_cached_tokens=False, session_accumulation=True, api_key_env="HF_TOKEN", base_url_env="HF_ROUTER_BASE_URL", @@ -714,8 +677,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "nvidia": ProviderProfile( key="nvidia", - catalog_provider="nvidia", - reports_cached_tokens=False, session_accumulation=True, api_key_env="NVIDIA_API_KEY", base_url_env="NVIDIA_BASE_URL", @@ -736,7 +697,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "perplexity": ProviderProfile( key="perplexity", - catalog_provider="perplexity", session_accumulation=True, api_key_env="PERPLEXITY_API_KEY", base_url_env="PERPLEXITY_BASE_URL", @@ -790,7 +750,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): # ), "lmstudio": ProviderProfile( key="lmstudio", - reports_cached_tokens=False, session_accumulation=True, base_url_env="LMSTUDIO_BASE_URL", default_base_url="http://localhost:1234/v1", @@ -819,7 +778,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "vllm": ProviderProfile( key="vllm", - reports_cached_tokens=False, session_accumulation=True, base_url_env="VLLM_BASE_URL", default_base_url="http://localhost:8000/v1", @@ -840,7 +798,6 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): ), "llamacpp": ProviderProfile( key="llamacpp", - reports_cached_tokens=False, session_accumulation=True, base_url_env="LLAMACPP_BASE_URL", default_base_url="http://localhost:8080/v1", diff --git a/scripts/catalog_overrides.json b/scripts/catalog_overrides.json deleted file mode 100644 index 01051a8ea..000000000 --- a/scripts/catalog_overrides.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "about": "Rows scripts/gen_model_catalog.py adds to the model catalog because its sources lack them. OpenAI's dated snapshots are listed same_as the alias that points to them, so they share its limits.", - "models": { - "openai/gpt-5-2025-08-07": {"same_as": "openai/gpt-5"}, - "openai/gpt-5-mini-2025-08-07": {"same_as": "openai/gpt-5-mini"}, - "openai/gpt-5-nano-2025-08-07": {"same_as": "openai/gpt-5-nano"}, - "openai/gpt-5.1-2025-11-13": {"same_as": "openai/gpt-5.1"}, - "openai/gpt-5.2-2025-12-11": {"same_as": "openai/gpt-5.2"}, - "openai/gpt-5.4-2026-03-05": {"same_as": "openai/gpt-5.4"}, - "openai/gpt-5.4-mini-2026-03-17": {"same_as": "openai/gpt-5.4-mini"}, - "openai/gpt-5.4-nano-2026-03-17": {"same_as": "openai/gpt-5.4-nano"}, - "openai/gpt-5.5-2026-04-23": {"same_as": "openai/gpt-5.5"}, - "openai/o3-2025-04-16": {"same_as": "openai/o3"}, - "openai/o3-mini-2025-01-31": {"same_as": "openai/o3-mini"}, - "openai/o4-mini-2025-04-16": {"same_as": "openai/o4-mini"} - } -} diff --git a/scripts/gen_model_catalog.py b/scripts/gen_model_catalog.py index 350b25fd5..7564ce200 100644 --- a/scripts/gen_model_catalog.py +++ b/scripts/gen_model_catalog.py @@ -1,25 +1,17 @@ #!/usr/bin/env python3 """Generate agent_core/core/models/model_catalog.json, the model catalog. -The catalog holds each model's context window and, where the provider caps -input below the window, its input limit. LLMInterface budgets every request -from it (agent_core/core/models/catalog.py); a model with no row uses -settings.json model.context_window. - -Sources, all structured fields (nothing is inferred from a model's name): - -* models.dev (MODELS_DEV_URL): ``limit.context`` and ``limit.input`` of every - model of each provider profile's ``catalog_provider`` - (agent_core/core/models/provider_config.py), keyed ``/``. -* the Codex model catalogue (CODEX_CATALOG_URL): ``context_window`` of each - model on the ChatGPT-subscription surface, the window Codex runs it at. -* scripts/catalog_overrides.json: rows both sources lack. A row is either - ``{"same_as": ""}``, which copies a row the sources produced, - or ``{"context_window": N}`` with an optional ``"max_input_tokens"``. - +Per model: its context window, its input limit when the provider caps input +below the window, and how long the provider keeps its prompt cache. Per +surface: whether responses report cached input. agent_core/core/models/ +catalog.py reads it, with defaults for whatever it does not list. + +Every fact comes from scripts/model_catalog_sources.json (see its "about"): +the sources to read, facts per surface, facts per model. This script only +knows how to parse each source format; it names no model, provider or URL. The output is deterministic (sorted, one row per line, no timestamps), so a -regeneration diff shows exactly which models changed. Run it by hand when -providers ship models; nothing is fetched at runtime. +regeneration diff shows exactly what changed. Run it by hand when providers +change. Usage: python scripts/gen_model_catalog.py @@ -33,26 +25,26 @@ import sys import urllib.request from pathlib import Path -from typing import Any, Dict +from typing import Any, Callable, Dict REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT)) -from agent_core.core.models.catalog import CATALOG_PATH # noqa: E402 -from agent_core.core.models.provider_config import PROVIDER_CONFIG # noqa: E402 -from agent_core.core.models.reasoning import ( # noqa: E402 - SUBSCRIPTION_AUTH_MODE, - reasoning_surface, +from agent_core.core.models.catalog import ( # noqa: E402 + CATALOG_PATH, + CacheLifetimeKind, ) -MODELS_DEV_URL = "https://models.dev/api.json" -CODEX_CATALOG_URL = ( - "https://raw.githubusercontent.com/openai/codex/main/" - "codex-rs/models-manager/models.json" -) -OVERRIDES_PATH = Path(__file__).with_name("catalog_overrides.json") +SOURCES_PATH = Path(__file__).with_name("model_catalog_sources.json") + +#: Fields a model row carries; any other key in the sources file is a note. +ROW_FIELDS = ("context_window", "max_input_tokens", "cache_lifetime") + +Row = Dict[str, Any] -Row = Dict[str, int] + +class CatalogError(ValueError): + """model_catalog_sources.json or a source does not make a valid catalog.""" def _fetch_json(url: str) -> Any: @@ -72,13 +64,15 @@ def _positive_int(value: Any) -> bool: return isinstance(value, int) and not isinstance(value, bool) and value > 0 -def _models_dev_rows(models_dev: Dict[str, Any]) -> Dict[str, Row]: +def _models_dev_rows( + source: Dict[str, Any], data: Any, surfaces: Dict +) -> Dict[str, Row]: + """models.dev: limit.context / limit.input per model. A surface's cache + lifetime goes to the models models.dev prices cache reads for.""" rows: Dict[str, Row] = {} - for profile in PROVIDER_CONFIG.values(): - if profile.catalog_provider is None: - continue - models = models_dev[profile.catalog_provider]["models"] - for model_id, model in models.items(): + for surface, provider_id in source["providers"].items(): + lifetime = surfaces.get(surface, {}).get("cache_lifetime") + for model_id, model in data[provider_id]["models"].items(): limit = model.get("limit") or {} context = limit.get("context") if not _positive_int(context): @@ -86,74 +80,113 @@ def _models_dev_rows(models_dev: Dict[str, Any]) -> Dict[str, Row]: row: Row = {"context_window": context} if _positive_int(limit.get("input")) and limit["input"] < context: row["max_input_tokens"] = limit["input"] - rows[f"{profile.key}/{model_id}"] = row + if lifetime and (model.get("cost") or {}).get("cache_read") is not None: + row["cache_lifetime"] = lifetime + rows[f"{surface}/{model_id}"] = row return rows -def _codex_rows(codex: Dict[str, Any]) -> Dict[str, Row]: - surface = reasoning_surface("openai", SUBSCRIPTION_AUTH_MODE) +def _codex_rows(source: Dict[str, Any], data: Any, surfaces: Dict) -> Dict[str, Row]: + """The Codex model catalogue: context_window per model slug.""" + surface = source["surface"] return { f"{surface}/{model['slug']}": {"context_window": model["context_window"]} - for model in codex["models"] + for model in data["models"] if _positive_int(model.get("context_window")) } -def _override_rows(sourced: Dict[str, Row]) -> Dict[str, Row]: - overrides = json.loads(OVERRIDES_PATH.read_text(encoding="utf-8"))["models"] +#: Source formats this script can read, by the "format" a source names. +PARSERS: Dict[str, Callable[[Dict[str, Any], Any, Dict], Dict[str, Row]]] = { + "models.dev": _models_dev_rows, + "codex": _codex_rows, +} + + +def _check_row(key: str, row: Row) -> None: + if not _positive_int(row.get("context_window")): + raise CatalogError(f"{key}: no source lists it and it gives no context_window") + if "max_input_tokens" in row and not _positive_int(row["max_input_tokens"]): + raise CatalogError(f"{key}: invalid max_input_tokens") + lifetime = row.get("cache_lifetime") + if lifetime is not None: + if lifetime.get("kind") not in {kind.value for kind in CacheLifetimeKind}: + raise CatalogError( + f"{key}: unknown cache_lifetime kind {lifetime.get('kind')!r}" + ) + if not _positive_int(lifetime.get("seconds")): + raise CatalogError(f"{key}: invalid cache_lifetime seconds") + + +def _model_rows(sourced: Dict[str, Row], models: Dict[str, Dict]) -> Dict[str, Row]: + """The sources file's per-model facts merged over the sourced rows.""" rows: Dict[str, Row] = {} - for key, override in overrides.items(): - if "same_as" in override: - target = sourced.get(override["same_as"]) - if target is None: - raise SystemExit( - f"{OVERRIDES_PATH.name}: {key} is same_as " - f"{override['same_as']}, which no source lists" - ) - rows[key] = dict(target) - continue - if not _positive_int(override.get("context_window")): - raise SystemExit(f"{OVERRIDES_PATH.name}: {key} needs a context_window") - row: Row = {"context_window": override["context_window"]} - if "max_input_tokens" in override: - if not _positive_int(override["max_input_tokens"]): - raise SystemExit( - f"{OVERRIDES_PATH.name}: {key} has an invalid max_input_tokens" - ) - row["max_input_tokens"] = override["max_input_tokens"] - rows[key] = row + for key, facts in models.items(): + same_as = facts.get("same_as") + if same_as is not None and same_as not in sourced: + raise CatalogError(f"{key}: same_as {same_as}, which no source lists") + base = sourced[same_as] if same_as is not None else sourced.get(key, {}) + rows[key] = {**base, **{f: facts[f] for f in ROW_FIELDS if f in facts}} return rows -def _render(rows: Dict[str, Row]) -> str: - items = sorted(rows.items()) +def build_catalog( + config: Dict[str, Any], fetch: Callable[[str], Any] +) -> Dict[str, Any]: + """The catalog from the sources file's ``config``, reading each source's + URL with ``fetch``.""" + surfaces: Dict[str, Dict[str, Any]] = config.get("surfaces", {}) + sourced: Dict[str, Row] = {} + for source in config["sources"]: + parse = PARSERS.get(source["format"]) + if parse is None: + raise CatalogError(f"unknown source format {source['format']!r}") + sourced.update(parse(source, fetch(source["url"]), surfaces)) + models = {**sourced, **_model_rows(sourced, config.get("models", {}))} + for key, row in models.items(): + _check_row(key, row) + return { + "surfaces": { + surface: {"reports_cached_tokens": facts["reports_cached_tokens"]} + for surface, facts in surfaces.items() + if "reports_cached_tokens" in facts + }, + "models": models, + } + + +def _render(catalog: Dict[str, Any]) -> str: + def section(name: str, rows: Dict[str, Any], last: bool) -> list: + items = sorted(rows.items()) + lines = [f' "{name}": {{'] + for index, (key, row) in enumerate(items): + comma = "," if index < len(items) - 1 else "" + lines.append( + f" {json.dumps(key)}: {json.dumps(row, sort_keys=True)}{comma}" + ) + lines.append(" }" if last else " },") + return lines + lines = [ "{", - ' "generator": "scripts/gen_model_catalog.py",', - ' "sources": ' - + json.dumps( - [MODELS_DEV_URL, CODEX_CATALOG_URL, "scripts/catalog_overrides.json"] - ) - + ",", - ' "models": {', + ' "generator": "scripts/gen_model_catalog.py from scripts/model_catalog_sources.json",', + *section("surfaces", catalog["surfaces"], last=False), + *section("models", catalog["models"], last=True), + "}", ] - for index, (key, row) in enumerate(items): - comma = "," if index < len(items) - 1 else "" - lines.append(f" {json.dumps(key)}: {json.dumps(row, sort_keys=True)}{comma}") - lines += [" }", "}"] return "\n".join(lines) + "\n" def main() -> int: argparse.ArgumentParser(description=__doc__).parse_args() - sourced = _models_dev_rows(_fetch_json(MODELS_DEV_URL)) - sourced.update(_codex_rows(_fetch_json(CODEX_CATALOG_URL))) - rows = {**sourced, **_override_rows(sourced)} - - text = _render(rows) + config = json.loads(SOURCES_PATH.read_text(encoding="utf-8")) + catalog = build_catalog(config, _fetch_json) + text = _render(catalog) json.loads(text) # the hand-rendered layout must stay valid JSON CATALOG_PATH.write_text(text, encoding="utf-8", newline="\n") - print(f"wrote {len(rows)} models to {CATALOG_PATH.relative_to(REPO_ROOT)}") + print( + f"wrote {len(catalog['models'])} models to {CATALOG_PATH.relative_to(REPO_ROOT)}" + ) return 0 diff --git a/scripts/model_catalog_sources.json b/scripts/model_catalog_sources.json new file mode 100644 index 000000000..f14bfb08c --- /dev/null +++ b/scripts/model_catalog_sources.json @@ -0,0 +1,81 @@ +{ + "about": "Hand-maintained input of scripts/gen_model_catalog.py, which writes agent_core/core/models/model_catalog.json. Everything here changes when providers change, so it is data: edit it and rerun the generator. sources: where each model's limits come from. surfaces: facts about a surface (a CraftBot provider key, or its subscription surface). Its cache_lifetime applies to every model of it that the source prices cache reads for; reports_cached_tokens says whether its responses report cached input (default true). models: facts per model, merged over what the sources give; same_as first copies another model's row.", + "sources": [ + { + "format": "models.dev", + "url": "https://models.dev/api.json", + "note": "CraftBot provider key -> models.dev provider id; both must serve the same model ids at the same endpoint. Not mapped: byteplus (models.dev lists only the China Volcengine naming) and local servers (they run whatever window the user loaded).", + "providers": { + "anthropic": "anthropic", + "bedrock": "amazon-bedrock", + "cerebras": "cerebras", + "deepseek": "deepseek", + "fireworks": "fireworks-ai", + "fugu": "sakana", + "gemini": "google", + "glm": "zai", + "grok": "xai", + "groq": "groq", + "huggingface": "huggingface", + "minimax": "minimax", + "mistral": "mistral", + "moonshot": "moonshotai", + "nvidia": "nvidia", + "openai": "openai", + "openrouter": "openrouter", + "perplexity": "perplexity", + "qwen": "alibaba", + "together": "togetherai" + } + }, + { + "format": "codex", + "url": "https://raw.githubusercontent.com/openai/codex/main/codex-rs/models-manager/models.json", + "note": "The ChatGPT-subscription backend's model catalogue: the window Codex runs each model at.", + "surface": "openai_subscription" + } + ], + "surfaces": { + "openai": { + "cache_lifetime": {"kind": "typical", "seconds": 300}, + "note": "Before GPT-5.6 a cached prefix typically lasts 5 to 10 minutes idle (in_memory) or about 30 minutes (24h retention), depending on the organization: the shorter figure. From GPT-5.6 on it lasts at least 30 minutes after its last write or reuse; those models are listed under models." + }, + "anthropic": { + "cache_lifetime": {"kind": "exact", "seconds": 3600}, + "note": "CraftBot asks for ttl=1h on session calls (transports/anthropic_messages.py); every hit or write restarts it, counted from the request's start." + }, + "bedrock": { + "cache_lifetime": {"kind": "exact", "seconds": 300}, + "note": "cachePoint is sent without a ttl: five minutes, restarted by every cache hit." + }, + "fireworks": {"reports_cached_tokens": false, "note": "Reports cached input in a response header only."}, + "huggingface": {"reports_cached_tokens": false}, + "nvidia": {"reports_cached_tokens": false}, + "remote": {"reports_cached_tokens": false, "note": "Ollama's API reports no cached count."}, + "lmstudio": {"reports_cached_tokens": false}, + "vllm": {"reports_cached_tokens": false, "note": "Only with --enable-prompt-tokens-details, which is off by default."}, + "llamacpp": {"reports_cached_tokens": false} + }, + "models": { + "openai/gpt-5-2025-08-07": {"same_as": "openai/gpt-5"}, + "openai/gpt-5-mini-2025-08-07": {"same_as": "openai/gpt-5-mini"}, + "openai/gpt-5-nano-2025-08-07": {"same_as": "openai/gpt-5-nano"}, + "openai/gpt-5.1-2025-11-13": {"same_as": "openai/gpt-5.1"}, + "openai/gpt-5.2-2025-12-11": {"same_as": "openai/gpt-5.2"}, + "openai/gpt-5.4-2026-03-05": {"same_as": "openai/gpt-5.4"}, + "openai/gpt-5.4-mini-2026-03-17": {"same_as": "openai/gpt-5.4-mini"}, + "openai/gpt-5.4-nano-2026-03-17": {"same_as": "openai/gpt-5.4-nano"}, + "openai/gpt-5.5-2026-04-23": {"same_as": "openai/gpt-5.5"}, + "openai/o3-2025-04-16": {"same_as": "openai/o3"}, + "openai/o3-mini-2025-01-31": {"same_as": "openai/o3-mini"}, + "openai/o4-mini-2025-04-16": {"same_as": "openai/o4-mini"}, + "openai/gpt-5.6": {"cache_lifetime": {"kind": "exact", "seconds": 1800}}, + "openai/gpt-5.6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 1800}}, + "openai/gpt-5.6-terra": {"cache_lifetime": {"kind": "exact", "seconds": 1800}}, + "openai/gpt-5.6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 1800}}, + "openai/gpt-6-sol": {"cache_lifetime": {"kind": "exact", "seconds": 1800}}, + "openai/gpt-6-luna": {"cache_lifetime": {"kind": "exact", "seconds": 1800}}, + "openai/gpt-6-astra": {"cache_lifetime": {"kind": "exact", "seconds": 1800}}, + "openai/gpt-6.1-sol": {"cache_lifetime": {"kind": "exact", "seconds": 1800}} + } +} diff --git a/tests/llm/test_context_readout.py b/tests/llm/test_context_readout.py index b6698639b..8a14c701e 100644 --- a/tests/llm/test_context_readout.py +++ b/tests/llm/test_context_readout.py @@ -10,7 +10,8 @@ * every provider whose profile accumulates a session history takes the session path (a hand-kept subset of them used to re-send the whole prompt every turn); -* cache lifetimes exist only where the provider documents one; +* cache facts come from the model catalog, with defaults for what it does + not list; * the wire payloads the menu reads. """ @@ -23,8 +24,12 @@ import pytest from agent_core.core.impl.llm import LLMCallType -from agent_core.core.models.cache_lifetime import CacheLifetimeKind, cache_lifetime -from agent_core.core.models.catalog import ModelLimits +from agent_core.core.models.catalog import ( + CacheLifetime, + CacheLifetimeKind, + ModelLimits, + reports_cached_tokens, +) from agent_core.core.models.reasoning import ReasoningChoice from agent_core.core.models.registry import session_cc_providers @@ -32,6 +37,25 @@ ACTION = LLMCallType.ACTION_SELECTION +#: A catalog of made-up models, so these tests pin behavior, not provider data. +FAKE_CATALOG = { + "surfaces": {"quiet": {"reports_cached_tokens": False}}, + "models": { + "openai/timed-model": { + "context_window": 400_000, + "cache_lifetime": {"kind": "exact", "seconds": 1800}, + }, + "openai/untimed-model": {"context_window": 128_000}, + }, +} + + +@pytest.fixture +def fake_catalog(monkeypatch): + import agent_core.core.models.catalog as catalog + + monkeypatch.setattr(catalog, "_catalog", lambda: FAKE_CATALOG) + # ──────────────────────── recording the last request ──────────────────────── @@ -90,46 +114,22 @@ def test_every_accumulating_provider_takes_the_session_path(monkeypatch, provide assert iface.has_session_cache("s1", ACTION) -# ─────────────────────────── cache lifetimes ─────────────────────────── - +# ─────────────────────────── cache facts ─────────────────────────── -def test_cache_lifetimes_exist_only_where_documented(): - luna = cache_lifetime("openai", "gpt-6-luna") - assert luna.kind is CacheLifetimeKind.EXACT and luna.seconds == 30 * 60 - older = cache_lifetime("openai", "gpt-5.2-2025-12-11") - assert older.kind is CacheLifetimeKind.TYPICAL and older.seconds == 5 * 60 - claude = cache_lifetime("anthropic", "claude-sonnet-4-6") - assert claude.kind is CacheLifetimeKind.EXACT and claude.seconds == 60 * 60 - # Undocumented or best-effort: no countdown. - assert cache_lifetime("openai", "gpt-6.1-sol", "subscription") is None - assert cache_lifetime("grok", "grok-4.3") is None - assert cache_lifetime("deepseek", "deepseek-v4-pro") is None - assert cache_lifetime("openrouter", "openai/gpt-6.1-sol") is None - assert cache_lifetime("lmstudio", "openai/gpt-oss-20b") is None +def test_the_cache_lifetime_comes_from_the_catalog(monkeypatch, fake_catalog): + timed, _ = build_interface(monkeypatch, "openai", "timed-model") + assert timed.prompt_cache_lifetime() == CacheLifetime(CacheLifetimeKind.EXACT, 1800) + # Catalogued without one, or not catalogued at all: no countdown. + untimed, _ = build_interface(monkeypatch, "openai", "untimed-model") + assert untimed.prompt_cache_lifetime() is None + unknown, _ = build_interface(monkeypatch, "openai", "unknown-model") + assert unknown.prompt_cache_lifetime() is None -def test_the_gpt_5_6_rows_name_real_models(): - from agent_core.core.models.cache_lifetime import _MODEL_LIFETIMES - from agent_core.core.models.catalog import model_limits - for model in _MODEL_LIFETIMES["openai"]: - assert model_limits("openai", model) is not None, model - - -def test_bedrock_counts_down_only_for_models_that_take_cache_points(monkeypatch): - claude, _ = build_interface( - monkeypatch, "bedrock", "us.anthropic.claude-haiku-4-5-20251001-v1:0" - ) - assert claude.prompt_cache_lifetime().seconds == 5 * 60 - llama, _ = build_interface(monkeypatch, "bedrock", "meta.llama3-70b-instruct-v1:0") - assert llama.prompt_cache_lifetime() is None - - -def test_providers_that_never_report_cached_tokens_say_so(monkeypatch): - fireworks, _ = build_interface(monkeypatch, "fireworks", "some-model") - openai, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") - assert fireworks.reports_cached_tokens() is False - assert openai.reports_cached_tokens() is True +def test_cached_input_is_reported_unless_the_catalog_says_not(fake_catalog): + assert reports_cached_tokens("quiet") is False + assert reports_cached_tokens("openai") is True # not listed: the default # ─────────────────────────── budgets per choice ─────────────────────────── @@ -161,10 +161,10 @@ async def send_to(_ws, message): ) -def test_the_reasoning_options_carry_budgets_and_cache_facts(monkeypatch): +def test_the_reasoning_options_carry_budgets_and_cache_facts(monkeypatch, fake_catalog): from app.ui_layer.adapters.browser_adapter import BrowserAdapter - iface, _ = build_interface(monkeypatch, "openai", "gpt-6-luna") + iface, _ = build_interface(monkeypatch, "openai", "timed-model") sent = [] asyncio.run( BrowserAdapter._handle_reasoning_options_get(_adapter(iface, sent), None) diff --git a/tests/llm/test_reasoning_rules.py b/tests/llm/test_reasoning_rules.py index 30ae8fbe6..b902aafe4 100644 --- a/tests/llm/test_reasoning_rules.py +++ b/tests/llm/test_reasoning_rules.py @@ -1034,8 +1034,13 @@ def test_reasoning_options_handler(monkeypatch): } # No reasoning parameter is sent, so every choice has the same budget. assert len(set(data["inputBudgets"].values())) == 1 - assert data["cacheLifetime"] == {"kind": "typical", "seconds": 300} - assert data["reportsCachedTokens"] is True + lifetime = unruled.prompt_cache_lifetime() + assert data["cacheLifetime"] == ( + None + if lifetime is None + else {"kind": lifetime.kind.value, "seconds": lifetime.seconds} + ) + assert data["reportsCachedTokens"] is unruled.reports_cached_tokens() def test_session_reasoning_set_handler(tmp_path: Path): diff --git a/tests/test_context_budget.py b/tests/test_context_budget.py index 1ac28d0a8..39c369909 100644 --- a/tests/test_context_budget.py +++ b/tests/test_context_budget.py @@ -344,40 +344,63 @@ def test_the_budget_follows_a_model_switch(): # ------------------------------------------------------------- the catalog -def test_catalog_lookups_are_exact_and_per_surface(): - # The log's model: a dated snapshot shares its alias's row. - assert model_limits("openai", "gpt-5.2-2025-12-11") == model_limits( - "openai", "gpt-5.2" +def test_catalog_lookups_are_exact_and_per_surface(monkeypatch): + import agent_core.core.models.catalog as catalog + + monkeypatch.setattr( + catalog, + "_catalog", + lambda: { + "surfaces": {}, + "models": { + "openai/some-model": { + "context_window": 400_000, + "max_input_tokens": 272_000, + }, + "openai_subscription/some-model": {"context_window": 272_000}, + }, + }, ) - assert model_limits("openai", "gpt-5.2").max_input_tokens is not None - # The ChatGPT-subscription surface has its own rows (the Codex windows). - api = model_limits("openai", "gpt-6.1-sol") - subscription = model_limits("openai", "gpt-6.1-sol", "subscription") - assert api is not None and subscription is not None and api != subscription - # No prefix or substring matching. - assert model_limits("openai", "gpt-6.1") is None - assert model_limits("openai", "gpt-6.1-sol-x") is None - # Local servers run whatever window the user loaded. - assert model_limits("lmstudio", "openai/gpt-oss-20b") is None - - -def test_every_catalog_row_is_well_formed(): + api = model_limits("openai", "some-model") + assert api == ModelLimits(400_000, max_input_tokens=272_000) + # The ChatGPT-subscription surface has rows of its own. + assert model_limits("openai", "some-model", "subscription") == ModelLimits(272_000) + # No prefix or substring matching; an unlisted model is not catalogued. + assert model_limits("openai", "some") is None + assert model_limits("openai", "some-model-x") is None + assert model_limits("lmstudio", "some-model") is None + + +def test_the_shipped_catalog_is_well_formed(): import json - from agent_core.core.models.catalog import CATALOG_PATH + from agent_core.core.models.catalog import CATALOG_PATH, CacheLifetimeKind from agent_core.core.models.provider_config import PROVIDER_CONFIG + from agent_core.core.models.reasoning import ( + SUBSCRIPTION_AUTH_MODE, + reasoning_surface, + ) - rows = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))["models"] - surfaces = {key for key, p in PROVIDER_CONFIG.items() if p.catalog_provider} - surfaces.add("openai_subscription") - assert rows - for key, row in rows.items(): + catalog = json.loads(CATALOG_PATH.read_text(encoding="utf-8")) + surfaces = { + reasoning_surface(key, auth) + for key in PROVIDER_CONFIG + for auth in ("api_key", SUBSCRIPTION_AUTH_MODE) + } + assert set(catalog["surfaces"]) <= surfaces + for facts in catalog["surfaces"].values(): + assert set(facts) == {"reports_cached_tokens"} + assert catalog["models"] + for key, row in catalog["models"].items(): surface, _, model_id = key.partition("/") assert surface in surfaces and model_id, key - assert set(row) <= {"context_window", "max_input_tokens"}, key + assert set(row) <= {"context_window", "max_input_tokens", "cache_lifetime"}, key assert isinstance(row["context_window"], int) and row["context_window"] > 0 if "max_input_tokens" in row: assert 0 < row["max_input_tokens"] < row["context_window"], key + if "cache_lifetime" in row: + CacheLifetimeKind(row["cache_lifetime"]["kind"]) + assert row["cache_lifetime"]["seconds"] > 0, key # ------------------------------------------------- how much a fold keeps diff --git a/tests/test_model_catalog_generator.py b/tests/test_model_catalog_generator.py new file mode 100644 index 000000000..15ed31f92 --- /dev/null +++ b/tests/test_model_catalog_generator.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +"""scripts/gen_model_catalog.py builds the model catalog from data only. + +Every model, provider and URL lives in scripts/model_catalog_sources.json; +the generator only parses source formats. These tests feed it made-up +sources (no network) and pin how facts combine: a surface's cache lifetime +goes to the models the source prices cache reads for, per-model facts merge +over sourced rows, same_as copies a row first, and anything that cannot make +a valid row is an error rather than a guess. +""" + +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +def _generator(): + spec = importlib.util.spec_from_file_location( + "gen_model_catalog", ROOT / "scripts" / "gen_model_catalog.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +gen = _generator() + +TIMED = {"kind": "typical", "seconds": 300} +SOURCES = { + "https://source.test/models.json": { + "alpha-upstream": { + "models": { + "priced": { + "limit": {"context": 400_000, "input": 272_000}, + "cost": {"cache_read": 0.1}, + }, + "unpriced": {"limit": {"context": 128_000}}, + "no-limit": {"limit": {}}, + } + } + }, + "https://source.test/codex.json": { + "models": [ + {"slug": "sub-model", "context_window": 272_000}, + {"slug": "no-window"}, + ] + }, +} + + +def _config(models=None, surfaces=None): + return { + "sources": [ + { + "format": "models.dev", + "url": "https://source.test/models.json", + "providers": {"alpha": "alpha-upstream"}, + }, + { + "format": "codex", + "url": "https://source.test/codex.json", + "surface": "alpha_subscription", + }, + ], + "surfaces": surfaces + if surfaces is not None + else { + "alpha": {"cache_lifetime": TIMED}, + "beta": {"reports_cached_tokens": False}, + }, + "models": models or {}, + } + + +def _build(config): + return gen.build_catalog(config, SOURCES.__getitem__) + + +def test_rows_come_from_the_sources_as_configured(): + models = _build(_config())["models"] + assert models["alpha/priced"] == { + "context_window": 400_000, + "max_input_tokens": 272_000, + "cache_lifetime": TIMED, # the source prices its cache reads + } + assert models["alpha/unpriced"] == {"context_window": 128_000} + assert models["alpha_subscription/sub-model"] == {"context_window": 272_000} + assert ( + "alpha/no-limit" not in models and "alpha_subscription/no-window" not in models + ) + + +def test_model_facts_merge_over_the_sourced_row(): + exact = {"kind": "exact", "seconds": 1800} + models = _build( + _config(models={"alpha/priced": {"cache_lifetime": exact, "note": "why"}}) + )["models"] + assert models["alpha/priced"] == { + "context_window": 400_000, + "max_input_tokens": 272_000, + "cache_lifetime": exact, + } + + +def test_same_as_copies_a_sourced_row(): + models = _build(_config(models={"alpha/priced-2026": {"same_as": "alpha/priced"}}))[ + "models" + ] + assert models["alpha/priced-2026"] == models["alpha/priced"] + + +def test_only_surface_facts_the_runtime_reads_are_carried(): + assert _build(_config())["surfaces"] == {"beta": {"reports_cached_tokens": False}} + + +@pytest.mark.parametrize( + "config", + [ + _config(models={"alpha/missing": {"cache_lifetime": TIMED}}), # no window + _config(models={"alpha/copy": {"same_as": "alpha/missing"}}), + _config( + surfaces={"alpha": {"cache_lifetime": {"kind": "forever", "seconds": 1}}} + ), + {**_config(), "sources": [{"format": "unknown", "url": "x"}]}, + ], +) +def test_what_cannot_make_a_valid_row_is_an_error(config): + with pytest.raises(gen.CatalogError): + _build(config) + + +def test_the_sources_file_names_only_known_formats_and_surfaces(): + from agent_core.core.models.provider_config import PROVIDER_CONFIG + from agent_core.core.models.reasoning import ( + SUBSCRIPTION_AUTH_MODE, + reasoning_surface, + ) + + config = json.loads(gen.SOURCES_PATH.read_text(encoding="utf-8")) + known = { + reasoning_surface(key, auth) + for key in PROVIDER_CONFIG + for auth in ("api_key", SUBSCRIPTION_AUTH_MODE) + } + for source in config["sources"]: + assert source["format"] in gen.PARSERS + assert set(source.get("providers", {})) <= known + assert source.get("surface") is None or source["surface"] in known + assert set(config["surfaces"]) <= known + assert {key.partition("/")[0] for key in config["models"]} <= known