The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(model_metadata): read llama.cpp context from meta.n_ctx + accept sole model
Jordan60c721ada68f
diff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex c147ef126b1..b1163c76c4e 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -2140,11 +2140,36 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: strif resp.status_code == 200:data = resp.json()models_list = data.get("data", [])+ # Match by id; on single-model servers (e.g. llama.cpp) the+ # configured name rarely equals the reported id (a GGUF path),+ # so fall back to the sole model when nothing matches.+ matched = Nonefor m in models_list:if _model_id_matches(m.get("id", ""), model):- ctx = m.get("max_model_len") or m.get("context_length") or m.get("max_tokens")- if ctx and isinstance(ctx, (int, float)):- return int(ctx)+ matched = m+ break+ if matched is None and len(models_list) == 1:+ matched = models_list[0]+ if matched is not None:+ # llama.cpp nests the runtime context under meta.n_ctx; the+ # vLLM/OpenAI keys are also checked. Runtime n_ctx is+ # preferred over n_ctx_train (the training maximum, which+ # can be larger than what the server actually allocates).+ for source in (matched, matched.get("meta") or {}):+ if not isinstance(source, dict):+ continue+ for key in (+ "n_ctx",+ "context_length",+ "context_window",+ "max_model_len",+ "max_context_length",+ "max_tokens",+ "n_ctx_train",+ ):+ val = source.get(key)+ if isinstance(val, (int, float)) and val:+ return int(val)except Exception as exc:if _is_connect_timeout(exc):_note_endpoint_blackholed(server_url)diff --git a/tests/agent/test_model_metadata_local_ctx.py b/tests/agent/test_model_metadata_local_ctx.pyindex d99bef07c07..c428b5f8576 100644--- a/tests/agent/test_model_metadata_local_ctx.py+++ b/tests/agent/test_model_metadata_local_ctx.py@@ -172,12 +172,17 @@ class TestQueryLocalContextLengthModelsList:assert result == 131072def test_models_list_model_not_found_returns_none(self):- """Returns None when model is not in the /v1/models list."""+ """Returns None when the model is absent from a multi-model /v1/models+ list. (Single-model servers are accepted even when the configured name+ doesn't match the reported id — see the llama.cpp tests below.)"""from agent.model_metadata import _query_local_context_lengthdetail_resp = self._make_resp(404, {})list_resp = self._make_resp(200, {- "data": [{"id": "other-model", "max_model_len": 4096}]+ "data": [+ {"id": "other-model", "max_model_len": 4096},+ {"id": "yet-another-model", "max_model_len": 8192},+ ]})call_count = [0]@@ -199,6 +204,73 @@ class TestQueryLocalContextLengthModelsList:assert result is None+ def test_models_list_llamacpp_meta_n_ctx_sole_model(self):+ """llama.cpp nests the runtime context under meta.n_ctx and serves a+ single model whose id (a GGUF path) doesn't match the configured name.++ The sole model should be accepted and meta.n_ctx read, instead of+ returning None and falling back to a family default (e.g. qwen=131072).+ """+ from agent.model_metadata import _query_local_context_length++ detail_resp = self._make_resp(404, {})+ list_resp = self._make_resp(200, {+ "data": [+ {+ "id": "/app/models/qwen3.6-35b.gguf",+ "meta": {"n_ctx": 256000, "n_ctx_train": 262144},+ }+ ]+ })++ call_count = [0]+ def side_effect(url, **kwargs):+ call_count[0] += 1+ if call_count[0] == 1:+ return detail_resp # /v1/models/{model}+ return list_resp # /v1/models++ client_mock = MagicMock()+ client_mock.__enter__ = lambda s: client_mock+ client_mock.__exit__ = MagicMock(return_value=False)+ client_mock.post.return_value = self._make_resp(404, {})+ client_mock.get.side_effect = side_effect++ with patch("agent.model_metadata.detect_local_server_type", return_value=None), \+ patch("httpx.Client", return_value=client_mock):+ result = _query_local_context_length("qwen3.6-35b", "http://localhost:8080")++ assert result == 256000++ def test_models_list_llamacpp_prefers_runtime_n_ctx_over_train(self):+ """Runtime n_ctx (256000) is preferred over n_ctx_train (262144),+ since the server can only actually serve the runtime value."""+ from agent.model_metadata import _query_local_context_length++ detail_resp = self._make_resp(404, {})+ list_resp = self._make_resp(200, {+ "data": [+ {"id": "/app/models/m.gguf", "meta": {"n_ctx": 256000, "n_ctx_train": 262144}}+ ]+ })++ call_count = [0]+ def side_effect(url, **kwargs):+ call_count[0] += 1+ return detail_resp if call_count[0] == 1 else list_resp++ client_mock = MagicMock()+ client_mock.__enter__ = lambda s: client_mock+ client_mock.__exit__ = MagicMock(return_value=False)+ client_mock.post.return_value = self._make_resp(404, {})+ client_mock.get.side_effect = side_effect++ with patch("agent.model_metadata.detect_local_server_type", return_value=None), \+ patch("httpx.Client", return_value=client_mock):+ result = _query_local_context_length("m", "http://localhost:8080")++ assert result == 256000+class TestQueryLocalContextLengthLmStudio:"""_query_local_context_length with LM Studio native /api/v1/models response."""