{"record":{"id":"65d08d56f14a0851","repo":"langchain-ai/deepagents","slug":"could-not-apply-context-size-env-key-to-model-pr","errorCode":null,"errorMessage":"Could not apply {CONTEXT_SIZE_ENV_KEY} to model profile","messagePattern":"Could not apply (.+?) to model profile","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"libs/talon/deepagents_talon/runtime.py","lineNumber":827,"sourceCode":"\ndef _has_summarization_tool_middleware(\n    middleware: Sequence[AgentMiddleware[Any, Any, Any]],\n) -> bool:\n    return any(isinstance(item, SummarizationToolMiddleware) for item in middleware)\n\n\ndef _apply_context_size(model: BaseChatModel, context_size: int) -> None:\n    profile = getattr(model, \"profile\", None)\n    merged = (\n        {**profile, \"max_input_tokens\": context_size}\n        if isinstance(profile, dict)\n        else {\"max_input_tokens\": context_size}\n    )\n    try:\n        cast(\"Any\", model).profile = merged\n    except (AttributeError, TypeError, ValueError) as exc:\n        msg = f\"Could not apply {CONTEXT_SIZE_ENV_KEY} to model profile\"\n        raise ValueError(msg) from exc\n\n\ndef _is_openai_model(model: str) -> bool:\n    return model.startswith(\"openai:\")\n\n\ndef _current_cron_origin() -> CronOrigin:\n    origin = _CRON_ORIGIN.get()\n    if origin is None:\n        msg = \"cron tools must be called from within a Talon conversation\"\n        raise RuntimeError(msg)\n    return origin\n\n\ndef _cron_origin_from_request(request: AgentRequest) -> CronOrigin:\n    channel = request.metadata.get(\"channel\")\n    message_id = request.metadata.get(\"message_id\")\n    origin_conversation_id = request.metadata.get(\"origin_conversation_id\")","sourceCodeStart":809,"sourceCodeEnd":845,"githubUrl":"https://github.com/langchain-ai/deepagents/blob/a1af029e6e73cb17c36bff823d227747b28e91e1/libs/talon/deepagents_talon/runtime.py#L809-L845","documentation":"When a context size is configured via the context-size env var, Talon merges `max_input_tokens` into the resolved chat model's `profile` dict. If assigning the `profile` attribute fails (AttributeError, TypeError, or ValueError), the assignment is re-raised as this ValueError. It means the underlying model object does not accept a mutable profile of this shape.","triggerScenarios":"Calling `_resolve_model_from_env` with the context-size env var set, on a model implementation whose `profile` attribute is read-only, a non-dict-mutable object, or validates and rejects the merged dict during `__set__`.","commonSituations":"Custom or third-party chat-model wrappers that expose `profile` as a property without a setter; provider classes that changed their profile representation in a newer langchain version; frozen/pydantic model objects.","solutions":["Check the model class: `profile` must be a writable dict attribute; upgrade the provider package if it recently changed profile handling","Remove/unset the context-size env var so the model profile is left untouched","Use a model implementation known to support profile overrides (standard `init_chat_model` providers)"],"exampleFix":"# before\n@property\ndef profile(self):\n    return self._profile\n# after\n@property\ndef profile(self):\n    return self._profile\n\n@profile.setter\ndef profile(self, value):\n    self._profile = dict(value)","handlingStrategy":"validation","validationCode":"model = init_chat_model(model_name)\nif os.environ.get(\"DEEPAGENTS_TALON_CONTEXT_SIZE\"):\n    if not hasattr(model, \"profile\"):\n        raise TypeError(f\"{type(model).__name__} does not support profile overrides\")\n    try:\n        model.profile = {**getattr(model, \"profile\", {}), \"max_input_tokens\": 100000}\n    except (AttributeError, TypeError, ValueError) as exc:\n        raise TypeError(f\"cannot set profile on {type(model).__name__}: {exc}\") from exc","typeGuard":"def supports_profile_override(model: object) -> bool:\n    return isinstance(getattr(type(model), \"profile\", None), property) and \\\n        getattr(type(model).profile, \"fset\", None) is not None","tryCatchPattern":"try:\n    resolved = runtime.resolve_model()\nexcept ValueError as exc:\n    if \"Could not apply\" in str(exc):\n        logger.warning(\"model profile override unsupported; continuing with defaults\")\n        resolved = fallback_model()\n    else:\n        raise","preventionTips":["Prefer standard init_chat_model provider classes that support mutable profile dicts","Test custom model wrappers with a profile assignment before deploying","Pin provider package versions known to work with profile overrides"],"tags":["configuration","model","env-var","profile"],"backgroundTag":"model-profile-assignment-failed","analyzedSha":"a1af029e6e73cb17c36bff823d227747b28e91e1","analyzedAt":"2026-08-29T11:43:24.718Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}