From 110885dfa82948d1ee821a67032a91ff60f19e9f Mon Sep 17 00:00:00 2001 From: Gopalji Gaur Date: Thu, 15 Oct 2026 08:49:36 +0200 Subject: [PATCH 1/3] fix(core): read the model map where LiteLLM would ask a provider's server LiteLLM's get_model_info and supports_* lookups send a synchronous HTTP request for Ollama models its map lacks (POST /api/show to OLLAMA_API_BASE or localhost, ignoring the deployment's api_base), and always for Lemonade and Hugging Face models. The context window, the compaction window and the response schema checks ran them on the event loop. For those providers, read litellm.model_cost under provider/model, else model, as the multimodal input check does. Other providers keep LiteLLM's own lookups. A router deployment of those providers merges its model_info over the map entry, as the router does. --- cyclops/core/compaction.py | 23 ++- cyclops/core/completion.py | 3 +- cyclops/core/providers.py | 41 +++- docs/guide/agents.md | 2 +- tests/test_model_info.py | 209 +++++++++++++++++++++ tests/test_provider_options.py | 9 +- website/src/content/docs/guides/agents.mdx | 2 +- 7 files changed, 271 insertions(+), 18 deletions(-) create mode 100644 tests/test_model_info.py diff --git a/cyclops/core/compaction.py b/cyclops/core/compaction.py index d793dd0..404f57a 100644 --- a/cyclops/core/compaction.py +++ b/cyclops/core/compaction.py @@ -8,6 +8,7 @@ from cyclops.core.completion import _acompletion, _completion_kwargs, _usage from cyclops.core.events import Compacted +from cyclops.core.providers import _asks_server, _model_info from cyclops.core.types import AgentConfig, Compaction, Usage from cyclops.toolkit.types import ToolResult @@ -27,18 +28,20 @@ def _window(config: AgentConfig) -> Optional[_Limits]: """ windows = [] if config.router is None: - try: - info: Any = litellm.get_model_info(config.model) - except Exception: # not mapped - return None - windows.append((config.model, info)) + windows.append((config.model, _model_info(config.model))) else: for deployment in config.router.get_model_list(config.model) or []: - try: - info = config.router.get_router_model_info(deployment, config.model) - except Exception: # not mapped - return None - windows.append((deployment["litellm_params"]["model"], info)) + model = deployment["litellm_params"]["model"] + provider = deployment["litellm_params"].get("custom_llm_provider") + if _asks_server(model, provider): + # The deployment's model_info over the map's, as the router merges them. + info = {**_model_info(model, provider), **deployment["model_info"]} + else: + try: + info = config.router.get_router_model_info(deployment, config.model) + except Exception: # not mapped + return None + windows.append((model, info)) limits = [ (model, info.get("max_input_tokens"), info.get("max_output_tokens")) for model, info in windows diff --git a/cyclops/core/completion.py b/cyclops/core/completion.py index 0d250f8..2a88cdf 100644 --- a/cyclops/core/completion.py +++ b/cyclops/core/completion.py @@ -25,6 +25,7 @@ _caches_at_markers, _every_deployment, _native_schema, + _response_schema, _takes_param, ) from cyclops.core.types import AgentConfig, Usage @@ -57,7 +58,7 @@ def _completion_kwargs( # With tools only where LiteLLM sends the schema natively: elsewhere it # may emulate it with a forced tool call, which blocks the agent's tools. if response_model is not None and ( - (mode == "none" and _every_deployment(config, litellm.supports_response_schema)) + (mode == "none" and _every_deployment(config, _response_schema)) or (mode == "native" and _every_deployment(config, _native_schema)) ): kwargs["response_format"] = response_model diff --git a/cyclops/core/providers.py b/cyclops/core/providers.py index d274509..d93f700 100644 --- a/cyclops/core/providers.py +++ b/cyclops/core/providers.py @@ -22,6 +22,9 @@ # only for Anthropic models). Gemini turns them into billed cachedContents # resources instead, and OpenAI caches without them. _CACHE_MARKER_PROVIDERS = {"anthropic", "bedrock"} +# LiteLLM's model info lookups ask these providers' servers (Ollama only for +# models its map lacks), blocking the caller and ignoring the deployment's api_base. +_SERVER_INFO_PROVIDERS = {"huggingface", "lemonade", "ollama", "ollama_chat"} # A check of one deployment: its model, its custom_llm_provider, then any arguments. _Check = Callable[..., bool] @@ -46,19 +49,49 @@ def _caches_at_markers(model: str, custom_llm_provider: Optional[str]) -> bool: ) +def _asks_server(model: str, custom_llm_provider: Optional[str]) -> bool: + """True if LiteLLM's model info lookups would ask the provider's server.""" + try: + provider = litellm.get_llm_provider(model, custom_llm_provider)[1] + except Exception: # unknown provider + return False + return provider in _SERVER_INFO_PROVIDERS + + +def _model_info(model: str, custom_llm_provider: Optional[str] = None) -> Any: + """LiteLLM's info for the model; empty if it has none. + + Where LiteLLM would ask the provider's server, its model map is read + instead, under provider/model, else model. + """ + if _asks_server(model, custom_llm_provider): + name, provider = litellm.get_llm_provider(model, custom_llm_provider)[:2] + costs = litellm.model_cost + return costs.get(f"{provider}/{name}") or costs.get(name) or {} + try: + return litellm.get_model_info(model, custom_llm_provider) + except Exception: # not mapped + return {} + + def _native_schema(model: str, custom_llm_provider: Optional[str] = None) -> bool: """True if LiteLLM's own entry for this provider lists native structured output. Not `supports_native_structured_output`: it falls back to another provider's entry, while the Vertex AI builder reads only its own. """ - try: - info = litellm.get_model_info(model, custom_llm_provider) - except Exception: # not mapped - return False + info = _model_info(model, custom_llm_provider) return info.get("supports_native_structured_output") is True +def _response_schema(model: str, custom_llm_provider: Optional[str]) -> bool: + """`litellm.supports_response_schema`, without asking the provider's server.""" + if _asks_server(model, custom_llm_provider): + info = _model_info(model, custom_llm_provider) + return info.get("supports_response_schema") is True + return litellm.supports_response_schema(model, custom_llm_provider) + + def _takes_param(model: str, custom_llm_provider: Optional[str], param: str) -> bool: """True if LiteLLM lists `param` as supported.""" supported = litellm.get_supported_openai_params( diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 7853e78..65d3834 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -347,7 +347,7 @@ The summary is an ordinary message in the transcript, so a [session](sessions.md The summarizing request carries the older messages as a plain text transcript, and its `max_tokens` is `keep` of the window, capped at the summarizing model's output limit, so the summary fits where the summarized messages were. It is sent without the agent's reasoning options, whose thinking budget that limit could fall under. When the transcript doesn't fit the rest of the summarizing model's window, the oldest messages are left out, with a note of how many; a window with no room for any of it raises a `RuntimeError`. A summary that comes back empty, cut by its output limit or filtered raises a `RuntimeError` and leaves the transcript as it was; its usage still counts. An earlier summary is not summarized again on its own, and when a compaction leaves the request past the threshold, as with a long summary or a long kept tail, the run logs a warning and does not compact again. -Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. +Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. For Ollama, Lemonade and Hugging Face models Cyclops reads only LiteLLM's model map, since `get_model_info` would ask the provider's server (Ollama's only for a model the map lacks) and block the run; register a local model's limits the same way. With a `session_store`, the save after a compaction stores the whole session, since earlier messages changed. diff --git a/tests/test_model_info.py b/tests/test_model_info.py new file mode 100644 index 0000000..775e63d --- /dev/null +++ b/tests/test_model_info.py @@ -0,0 +1,209 @@ +"""Tests that model info lookups never ask a provider's server.""" + +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +import httpx +import litellm +import pytest +from litellm import Choices, Message, ModelResponse, Usage +from litellm.types.utils import ChatCompletionMessageToolCall, Function +from pydantic import BaseModel + +from cyclops import Agent, AgentConfig, Compaction, Session, tool +from cyclops.core.compaction import _window +from cyclops.core.providers import _holds + +# LiteLLM's lookups ask these providers' servers (Ollama's for unmapped models). +SERVER_PROVIDERS = ["ollama", "ollama_chat", "lemonade", "huggingface"] +REGISTERED = "ollama/cyclops-registered" +litellm.register_model( + { + REGISTERED: { + "max_input_tokens": 400, + "max_output_tokens": 100, + "litellm_provider": "ollama", + "mode": "chat", + } + } +) + + +class Answer(BaseModel): + value: int + + +@tool +def add(a: int, b: int) -> int: + """Add two numbers.""" + return a + b + + +def _response(content=None, tool_calls=None): + response = ModelResponse( + choices=[Choices(message=Message(content=content, tool_calls=tool_calls))], + usage=Usage(prompt_tokens=1, completion_tokens=1, total_tokens=2), + ) + # As LiteLLM prices a response, so the run asks for no cost. + response._hidden_params["response_cost"] = 0.0 + return response + + +def _add_call(): + return ChatCompletionMessageToolCall( + id="call_1", function=Function(name="add", arguments='{"a": 1, "b": 2}') + ) + + +def _overflow(model): + return litellm.ContextWindowExceededError( + message="too long", model=model, llm_provider="ollama" + ) + + +def _unmapped(provider): + """A new model name each time, since LiteLLM caches its lookups.""" + return f"{provider}/cyclops-{uuid4().hex}" + + +def _router(model, **model_info): + return litellm.Router( + model_list=[ + { + "model_name": "local", + "litellm_params": {"model": model, "api_base": "http://gpu:11434"}, + "model_info": model_info, + } + ] + ) + + +@pytest.fixture +def requests(): + """Fail every HTTP request LiteLLM sends, and record its URL.""" + urls = [] + + def send(self, request, **kwargs): + urls.append(str(request.url)) + raise httpx.ConnectError("no network in tests", request=request) + + async def asend(self, request, **kwargs): + return send(self, request) + + _holds.cache_clear() + with ( + patch.object(httpx.Client, "send", send), + patch.object(httpx.AsyncClient, "send", asend), + ): + yield urls + + +@pytest.fixture(params=[False, True], ids=["model", "router"]) +def routed(request): + return request.param + + +@pytest.fixture(params=SERVER_PROVIDERS) +def config(request, routed, requests): + """A config for an unmapped model of the provider, or a router of one.""" + model = _unmapped(request.param) + if not routed: + return AgentConfig(model=model) + config = AgentConfig(model="local", router=_router(model)) + # LiteLLM's Router asks the server as it is built. + requests.clear() + return config + + +def _complete(config, *replies): + target = config.router or litellm + return patch.object(target, "acompletion", new=AsyncMock(side_effect=replies)) + + +@pytest.mark.parametrize("tools", [[add], []]) +def test_the_capability_checks_ask_no_server(config, requests, tools): + config = config.model_copy( + update={"reasoning_effort": "low", "prompt_caching": True} + ) + replies = [_response(tool_calls=[_add_call()])] if tools else [] + with _complete(config, *replies, _response('{"value": 3}')): + answer = Agent(config, tools=tools).run("1 + 2?", response_model=Answer) + + assert answer == Answer(value=3) + assert requests == [] + + +def test_an_overflow_without_known_limits_ends_the_run(config, requests): + with _complete(config, _overflow(config.model)) as mock: + result = Agent(config).run_with_response("Go on.") + + assert mock.call_count == 1 + assert isinstance(result.error, litellm.ContextWindowExceededError) + assert requests == [] + + +def test_compaction_without_known_limits_raises(config, requests): + config = config.model_copy(update={"compaction": Compaction()}) + session = Session(messages=[{"role": "user", "content": "Hi."}]) + + with _complete(config) as mock: + result = Agent(config).run_with_response("Go on.", session=session) + with pytest.raises(ValueError, match="register_model"): + Agent(config).compact(session) + + mock.assert_not_called() + assert isinstance(result.error, ValueError) + assert "register_model" in str(result.error) + assert requests == [] + + +def test_a_summarizing_model_without_known_limits_raises(requests): + config = AgentConfig( + model=REGISTERED, compaction=Compaction(model=_unmapped("ollama")) + ) + + with _complete(config) as mock: + result = Agent(config).run_with_response("Go on.") + + mock.assert_not_called() + assert isinstance(result.error, ValueError) + assert requests == [] + + +def test_a_registered_model_gets_its_window(requests): + assert _window(AgentConfig(model=REGISTERED)) == (REGISTERED, 400, 100) + assert requests == [] + + +def test_a_registered_model_is_compacted(requests): + config = AgentConfig(model=REGISTERED, compaction=Compaction()) + session = Session(messages=[{"role": "user", "content": "word " * 350}]) + + with _complete(config, _response("Summary."), _response("Done.")) as mock: + result = Agent(config).run_with_response("Go on.", session=session) + + assert result.content == "Done." + assert mock.call_count == 2 + assert requests == [] + + +def test_a_mapped_lemonade_model_gets_its_window(requests): + model = next( + k for k, v in litellm.model_cost.items() if v["litellm_provider"] == "lemonade" + ) + info = litellm.model_cost[model] + + limits = _window(AgentConfig(model=model)) + + assert limits == (model, info["max_input_tokens"], info["max_output_tokens"]) + assert requests == [] + + +@pytest.mark.parametrize("provider", SERVER_PROVIDERS) +def test_a_router_deployment_gets_the_window_of_its_model_info(provider, requests): + model = _unmapped(provider) + router = _router(model, max_input_tokens=9000, max_output_tokens=900) + requests.clear() + + assert _window(AgentConfig(model="local", router=router)) == (model, 9000, 900) + assert requests == [] diff --git a/tests/test_provider_options.py b/tests/test_provider_options.py index ce0da79..9c3e5fc 100644 --- a/tests/test_provider_options.py +++ b/tests/test_provider_options.py @@ -29,6 +29,7 @@ _holds, _lacks_tools, _native_schema, + _response_schema, _takes_param, _takes_tool_message_images, ) @@ -1092,7 +1093,7 @@ def test_response_model_native_schema_needs_every_router_deployment(): _CHECKS = [ - (litellm.supports_response_schema,), + (_response_schema,), (_native_schema,), (_takes_param, "reasoning_effort"), (_takes_param, "thinking"), @@ -1143,6 +1144,12 @@ def test_every_deployment_decides_as_each_check(check): assert _every_deployment(config, *check) is expected +@pytest.mark.parametrize("model, provider", _MODELS) +def test_the_response_schema_check_decides_as_litellm(model, provider): + expected = litellm.supports_response_schema(model, provider) + assert _response_schema(model, provider) is expected + + def test_every_deployment_is_false_without_deployments(): config = AgentConfig(model="other", router=_router(("gpt-4o-mini", None))) assert _every_deployment(config, _takes_param, "reasoning_effort") is False diff --git a/website/src/content/docs/guides/agents.mdx b/website/src/content/docs/guides/agents.mdx index 0576edd..3671d49 100644 --- a/website/src/content/docs/guides/agents.mdx +++ b/website/src/content/docs/guides/agents.mdx @@ -353,7 +353,7 @@ The summary is an ordinary message in the transcript, so a [session](/guides/ses The summarizing request carries the older messages as a plain text transcript, and its `max_tokens` is `keep` of the window, capped at the summarizing model's output limit, so the summary fits where the summarized messages were. It is sent without the agent's reasoning options, whose thinking budget that limit could fall under. When the transcript doesn't fit the rest of the summarizing model's window, the oldest messages are left out, with a note of how many; a window with no room for any of it raises a `RuntimeError`. A summary that comes back empty, cut by its output limit or filtered raises a `RuntimeError` and leaves the transcript as it was; its usage still counts. An earlier summary is not summarized again on its own, and when a compaction leaves the request past the threshold, as with a long summary or a long kept tail, the run logs a warning and does not compact again. -Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. +Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. For Ollama, Lemonade and Hugging Face models Cyclops reads only LiteLLM's model map, since `get_model_info` would ask the provider's server (Ollama's only for a model the map lacks) and block the run; register a local model's limits the same way. With a `session_store`, the save after a compaction stores the whole session, since earlier messages changed. From 146d968e67807c5229470a63348d11f1910dfc58 Mon Sep 17 00:00:00 2001 From: Gopalji Gaur Date: Thu, 15 Oct 2026 09:07:11 +0200 Subject: [PATCH 2/3] fix(core): share one model info helper with the input check The input check reads _model_info, so other providers get LiteLLM's lookup and its normalization (bedrock/converse/ routes, fine-tuned ids), and Ollama, Lemonade and Hugging Face still read only the model map. The map's bare name entry is read only when it is for the same provider or none, as LiteLLM matches entries. Docs: the context window section says how to register an unmapped Ollama model's limits, which also stops LiteLLM's own per-completion /api/show requests. --- cyclops/core/providers.py | 21 +++++++++---------- docs/guide/agents.md | 21 ++++++++++++++++++- docs/guide/multimodal.md | 4 ++-- tests/test_model_info.py | 20 +++++++++++++++++- tests/test_multimodal.py | 2 ++ website/src/content/docs/guides/agents.mdx | 21 ++++++++++++++++++- .../src/content/docs/guides/multimodal.mdx | 4 ++-- 7 files changed, 75 insertions(+), 18 deletions(-) diff --git a/cyclops/core/providers.py b/cyclops/core/providers.py index d93f700..a4c062f 100644 --- a/cyclops/core/providers.py +++ b/cyclops/core/providers.py @@ -62,12 +62,16 @@ def _model_info(model: str, custom_llm_provider: Optional[str] = None) -> Any: """LiteLLM's info for the model; empty if it has none. Where LiteLLM would ask the provider's server, its model map is read - instead, under provider/model, else model. + instead: the entry under provider/model, else model, if it is for that + provider or none, as LiteLLM matches them. """ if _asks_server(model, custom_llm_provider): name, provider = litellm.get_llm_provider(model, custom_llm_provider)[:2] - costs = litellm.model_cost - return costs.get(f"{provider}/{name}") or costs.get(name) or {} + for key in (f"{provider}/{name}", name): + info = litellm.model_cost.get(key) + if info is not None and info.get("litellm_provider") in (None, provider): + return info + return {} try: return litellm.get_model_info(model, custom_llm_provider) except Exception: # not mapped @@ -109,16 +113,11 @@ def _lacks_tools(model: str, custom_llm_provider: Optional[str]) -> bool: def _takes_input(model: str, custom_llm_provider: Optional[str], flag: str) -> bool: - """False only if LiteLLM's model map sets `flag` to false for the model. + """False only if LiteLLM's info sets `flag` to false for the model. - Most entries leave the flags out. The entry is read from litellm.model_cost - under provider/model, else model: get_model_info asks some providers - (Ollama) over the network. + Most entries leave the flags out. """ - model, provider = litellm.get_llm_provider(model, custom_llm_provider)[:2] - costs = litellm.model_cost - info = costs.get(f"{provider}/{model}") or costs.get(model) or {} - return info.get(flag) is not False + return _model_info(model, custom_llm_provider).get(flag) is not False def _deployments(config: AgentConfig) -> List[Dict[str, Any]]: diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 65d3834..5e51f95 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -326,6 +326,25 @@ The run reads each completion's `finish_reason`, as LiteLLM normalizes it across A long conversation, or a large tool result, eventually outgrows the model's context window. Two settings keep requests within it: compaction summarizes older messages, and `max_tool_output_chars` caps each tool result. A request that still overflows is retried with what fits. Both are off by default, as in other agent libraries, since compaction makes an extra completion and replaces what the model saw with a summary. +Compaction and overflow recovery take the model's limits from LiteLLM. For Ollama, Lemonade and Hugging Face models Cyclops reads only LiteLLM's model map, since LiteLLM's `get_model_info` would ask the provider's server and block the run. A model the map lacks, such as `ollama/qwen3:4b`, gets no limits: compaction raises `ValueError` and an overflow is not retried. Register its limits at startup, keyed by the exact model string, with the context length your server runs it with: + +```python +import litellm + +litellm.register_model( + { + "ollama/qwen3:4b": { + "max_input_tokens": 32768, + "max_output_tokens": 8192, + "litellm_provider": "ollama", + "mode": "chat", + } + } +) +``` + +Registering it also stops LiteLLM's own `/api/show` requests: for an Ollama model its map lacks, LiteLLM prices each completion by asking the server, four or five requests per completion, sent to `OLLAMA_API_BASE` or localhost even when the model has its own `api_base`. + ### Compaction ```python @@ -347,7 +366,7 @@ The summary is an ordinary message in the transcript, so a [session](sessions.md The summarizing request carries the older messages as a plain text transcript, and its `max_tokens` is `keep` of the window, capped at the summarizing model's output limit, so the summary fits where the summarized messages were. It is sent without the agent's reasoning options, whose thinking budget that limit could fall under. When the transcript doesn't fit the rest of the summarizing model's window, the oldest messages are left out, with a note of how many; a window with no room for any of it raises a `RuntimeError`. A summary that comes back empty, cut by its output limit or filtered raises a `RuntimeError` and leaves the transcript as it was; its usage still counts. An earlier summary is not summarized again on its own, and when a compaction leaves the request past the threshold, as with a long summary or a long kept tail, the run logs a warning and does not compact again. -Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. For Ollama, Lemonade and Hugging Face models Cyclops reads only LiteLLM's model map, since `get_model_info` would ask the provider's server (Ollama's only for a model the map lacks) and block the run; register a local model's limits the same way. +Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. With a `session_store`, the save after a compaction stores the whole session, since earlier messages changed. diff --git a/docs/guide/multimodal.md b/docs/guide/multimodal.md index 9cc3756..5a36194 100644 --- a/docs/guide/multimodal.md +++ b/docs/guide/multimodal.md @@ -49,13 +49,13 @@ As LiteLLM 1.105 sends them: Anthropic gets `image` and `document` blocks, with ## Models that can't take the input -Before the run starts, Cyclops reads LiteLLM's model map (`litellm.model_cost`, the entry under `provider/model`, else `model`) for the model, each of its deployments in a `router` (not the router's fallback groups) and each of its `fallback_models`, since they all read the same history. If the entry sets `supports_vision` to false and an image is sent, `supports_pdf_input` to false and a PDF is sent, or `supports_audio_input` to false and audio is sent, the run raises `ValueError`, so nothing is sent and no part is dropped: +Before the run starts, Cyclops reads LiteLLM's model info (`litellm.get_model_info`, or for Ollama, Lemonade and Hugging Face only its model map, so no provider is asked over the network) for the model, each of its deployments in a `router` (not the router's fallback groups) and each of its `fallback_models`, since they all read the same history. If the entry sets `supports_vision` to false and an image is sent, `supports_pdf_input` to false and a PDF is sent, or `supports_audio_input` to false and audio is sent, the run raises `ValueError`, so nothing is sent and no part is dropped: ```text o3-mini, one of its deployments or one of its fallback models can't take image input: LiteLLM's model map sets supports_vision to false for one of them; if that is wrong, correct its entry with litellm.register_model at startup ``` -Only an explicit false counts. Most entries leave these flags out, and a model with no entry at all, such as one on a custom OpenAI compatible endpoint, gets the parts and its provider decides, as in Pydantic AI, the OpenAI Agents SDK and the Vercel AI SDK, which don't check. The check reads only `litellm.model_cost`, the map LiteLLM ships plus any entries registered in this process, never a provider over the network. Capability checks are cached per process, so call `litellm.register_model` at startup, before the first run. A file whose media type is unknown (a `file_id` without `format`) is not checked. +Only an explicit false counts. Most entries leave these flags out, and a model with no entry at all, such as one on a custom OpenAI compatible endpoint, gets the parts and its provider decides, as in Pydantic AI, the OpenAI Agents SDK and the Vercel AI SDK, which don't check. The check reads only the map LiteLLM ships plus any entries registered in this process, never a provider over the network. Capability checks are cached per process, so call `litellm.register_model` at startup, before the first run. A file whose media type is unknown (a `file_id` without `format`) is not checked. ## Steering, sessions and guards diff --git a/tests/test_model_info.py b/tests/test_model_info.py index 775e63d..55e810d 100644 --- a/tests/test_model_info.py +++ b/tests/test_model_info.py @@ -12,7 +12,7 @@ from cyclops import Agent, AgentConfig, Compaction, Session, tool from cyclops.core.compaction import _window -from cyclops.core.providers import _holds +from cyclops.core.providers import _holds, _model_info # LiteLLM's lookups ask these providers' servers (Ollama's for unmapped models). SERVER_PROVIDERS = ["ollama", "ollama_chat", "lemonade", "huggingface"] @@ -133,6 +133,17 @@ def test_the_capability_checks_ask_no_server(config, requests, tools): assert requests == [] +def test_the_input_check_asks_no_server(config, requests): + image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}} + content = [{"type": "text", "text": "What is this?"}, image] + + with _complete(config, _response("A cat.")) as mock: + assert Agent(config).run(content) == "A cat." + + assert mock.call_args.kwargs["messages"][-1]["content"] == content + assert requests == [] + + def test_an_overflow_without_known_limits_ends_the_run(config, requests): with _complete(config, _overflow(config.model)) as mock: result = Agent(config).run_with_response("Go on.") @@ -170,6 +181,13 @@ def test_a_summarizing_model_without_known_limits_raises(requests): assert requests == [] +def test_another_providers_entry_is_not_read(requests): + # The bare name has an OpenAI entry. + assert _model_info("ollama/gpt-4o") == {} + assert _model_info("ollama/llama2")["max_input_tokens"] + assert requests == [] + + def test_a_registered_model_gets_its_window(requests): assert _window(AgentConfig(model=REGISTERED)) == (REGISTERED, 400, 100) assert requests == [] diff --git a/tests/test_multimodal.py b/tests/test_multimodal.py index dd02759..84bbf88 100644 --- a/tests/test_multimodal.py +++ b/tests/test_multimodal.py @@ -143,6 +143,8 @@ def _file(**file): (NO_PDF, _file(file_id="file-123", format="application/pdf"), "pdf"), (NO_AUDIO, AUDIO, "audio"), (NO_AUDIO, _file(file_data="data:audio/wav;base64,UklGRg=="), "audio"), + # A route LiteLLM's lookup strips to find the entry. + ("bedrock/converse/moonshotai.kimi-k2.5", AUDIO, "audio"), ], ) def test_unsupported_input_raises_before_any_completion(model, part, kind): diff --git a/website/src/content/docs/guides/agents.mdx b/website/src/content/docs/guides/agents.mdx index 3671d49..1d25311 100644 --- a/website/src/content/docs/guides/agents.mdx +++ b/website/src/content/docs/guides/agents.mdx @@ -332,6 +332,25 @@ The run reads each completion's `finish_reason`, as LiteLLM normalizes it across A long conversation, or a large tool result, eventually outgrows the model's context window. Two settings keep requests within it: compaction summarizes older messages, and `max_tool_output_chars` caps each tool result. A request that still overflows is retried with what fits. Both are off by default, as in other agent libraries, since compaction makes an extra completion and replaces what the model saw with a summary. +Compaction and overflow recovery take the model's limits from LiteLLM. For Ollama, Lemonade and Hugging Face models Cyclops reads only LiteLLM's model map, since LiteLLM's `get_model_info` would ask the provider's server and block the run. A model the map lacks, such as `ollama/qwen3:4b`, gets no limits: compaction raises `ValueError` and an overflow is not retried. Register its limits at startup, keyed by the exact model string, with the context length your server runs it with: + +```python +import litellm + +litellm.register_model( + { + "ollama/qwen3:4b": { + "max_input_tokens": 32768, + "max_output_tokens": 8192, + "litellm_provider": "ollama", + "mode": "chat", + } + } +) +``` + +Registering it also stops LiteLLM's own `/api/show` requests: for an Ollama model its map lacks, LiteLLM prices each completion by asking the server, four or five requests per completion, sent to `OLLAMA_API_BASE` or localhost even when the model has its own `api_base`. + ### Compaction ```python @@ -353,7 +372,7 @@ The summary is an ordinary message in the transcript, so a [session](/guides/ses The summarizing request carries the older messages as a plain text transcript, and its `max_tokens` is `keep` of the window, capped at the summarizing model's output limit, so the summary fits where the summarized messages were. It is sent without the agent's reasoning options, whose thinking budget that limit could fall under. When the transcript doesn't fit the rest of the summarizing model's window, the oldest messages are left out, with a note of how many; a window with no room for any of it raises a `RuntimeError`. A summary that comes back empty, cut by its output limit or filtered raises a `RuntimeError` and leaves the transcript as it was; its usage still counts. An earlier summary is not summarized again on its own, and when a compaction leaves the request past the threshold, as with a long summary or a long kept tail, the run logs a warning and does not compact again. -Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. For Ollama, Lemonade and Hugging Face models Cyclops reads only LiteLLM's model map, since `get_model_info` would ask the provider's server (Ollama's only for a model the map lacks) and block the run; register a local model's limits the same way. +Token counts are LiteLLM's: close for OpenAI models and an estimate for others, so the threshold leaves room. Through a `router`, the deployment with the smallest `max_input_tokens` sets the limit. Compaction needs that limit: with `compaction` set, a model LiteLLM has no `max_input_tokens` for ends the run with a `ValueError` at its first step, as LangChain's summarization does; `litellm.register_model` adds the limits. The same goes for the summarizing `model`. With a `session_store`, the save after a compaction stores the whole session, since earlier messages changed. diff --git a/website/src/content/docs/guides/multimodal.mdx b/website/src/content/docs/guides/multimodal.mdx index 52b8655..9d37ae5 100644 --- a/website/src/content/docs/guides/multimodal.mdx +++ b/website/src/content/docs/guides/multimodal.mdx @@ -52,13 +52,13 @@ As LiteLLM 1.105 sends them: Anthropic gets `image` and `document` blocks, with ## Models that can't take the input -Before the run starts, Cyclops reads LiteLLM's model map (`litellm.model_cost`, the entry under `provider/model`, else `model`) for the model, each of its deployments in a `router` (not the router's fallback groups) and each of its `fallback_models`, since they all read the same history. If the entry sets `supports_vision` to false and an image is sent, `supports_pdf_input` to false and a PDF is sent, or `supports_audio_input` to false and audio is sent, the run raises `ValueError`, so nothing is sent and no part is dropped: +Before the run starts, Cyclops reads LiteLLM's model info (`litellm.get_model_info`, or for Ollama, Lemonade and Hugging Face only its model map, so no provider is asked over the network) for the model, each of its deployments in a `router` (not the router's fallback groups) and each of its `fallback_models`, since they all read the same history. If the entry sets `supports_vision` to false and an image is sent, `supports_pdf_input` to false and a PDF is sent, or `supports_audio_input` to false and audio is sent, the run raises `ValueError`, so nothing is sent and no part is dropped: ```text o3-mini, one of its deployments or one of its fallback models can't take image input: LiteLLM's model map sets supports_vision to false for one of them; if that is wrong, correct its entry with litellm.register_model at startup ``` -Only an explicit false counts. Most entries leave these flags out, and a model with no entry at all, such as one on a custom OpenAI compatible endpoint, gets the parts and its provider decides, as in Pydantic AI, the OpenAI Agents SDK and the Vercel AI SDK, which don't check. The check reads only `litellm.model_cost`, the map LiteLLM ships plus any entries registered in this process, never a provider over the network. Capability checks are cached per process, so call `litellm.register_model` at startup, before the first run. A file whose media type is unknown (a `file_id` without `format`) is not checked. +Only an explicit false counts. Most entries leave these flags out, and a model with no entry at all, such as one on a custom OpenAI compatible endpoint, gets the parts and its provider decides, as in Pydantic AI, the OpenAI Agents SDK and the Vercel AI SDK, which don't check. The check reads only the map LiteLLM ships plus any entries registered in this process, never a provider over the network. Capability checks are cached per process, so call `litellm.register_model` at startup, before the first run. A file whose media type is unknown (a `file_id` without `format`) is not checked. ## Steering, sessions and guards From 1b5c983babbec932b81e0054821b25bc1ee86cc5 Mon Sep 17 00:00:00 2001 From: Gopalji Gaur Date: Thu, 15 Oct 2026 09:16:34 +0200 Subject: [PATCH 3/3] docs: most of LiteLLM's /api/show requests go to OLLAMA_API_BASE or localhost --- docs/guide/agents.md | 2 +- website/src/content/docs/guides/agents.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 5e51f95..e131ceb 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -343,7 +343,7 @@ litellm.register_model( ) ``` -Registering it also stops LiteLLM's own `/api/show` requests: for an Ollama model its map lacks, LiteLLM prices each completion by asking the server, four or five requests per completion, sent to `OLLAMA_API_BASE` or localhost even when the model has its own `api_base`. +Registering it also stops LiteLLM's own `/api/show` requests: for an Ollama model its map lacks, LiteLLM prices each completion by asking the server, four or five requests per completion, sent mostly to `OLLAMA_API_BASE` or localhost even when the model has its own `api_base`. ### Compaction diff --git a/website/src/content/docs/guides/agents.mdx b/website/src/content/docs/guides/agents.mdx index 1d25311..22e9132 100644 --- a/website/src/content/docs/guides/agents.mdx +++ b/website/src/content/docs/guides/agents.mdx @@ -349,7 +349,7 @@ litellm.register_model( ) ``` -Registering it also stops LiteLLM's own `/api/show` requests: for an Ollama model its map lacks, LiteLLM prices each completion by asking the server, four or five requests per completion, sent to `OLLAMA_API_BASE` or localhost even when the model has its own `api_base`. +Registering it also stops LiteLLM's own `/api/show` requests: for an Ollama model its map lacks, LiteLLM prices each completion by asking the server, four or five requests per completion, sent mostly to `OLLAMA_API_BASE` or localhost even when the model has its own `api_base`. ### Compaction