langchain-ai/deepagents · error · ValueError

Could not apply {CONTEXT_SIZE_ENV_KEY} to model profile

Error message

Could not apply {CONTEXT_SIZE_ENV_KEY} to model profile

What it means

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.

Source

Thrown at libs/talon/deepagents_talon/runtime.py:827

def _has_summarization_tool_middleware(
    middleware: Sequence[AgentMiddleware[Any, Any, Any]],
) -> bool:
    return any(isinstance(item, SummarizationToolMiddleware) for item in middleware)


def _apply_context_size(model: BaseChatModel, context_size: int) -> None:
    profile = getattr(model, "profile", None)
    merged = (
        {**profile, "max_input_tokens": context_size}
        if isinstance(profile, dict)
        else {"max_input_tokens": context_size}
    )
    try:
        cast("Any", model).profile = merged
    except (AttributeError, TypeError, ValueError) as exc:
        msg = f"Could not apply {CONTEXT_SIZE_ENV_KEY} to model profile"
        raise ValueError(msg) from exc


def _is_openai_model(model: str) -> bool:
    return model.startswith("openai:")


def _current_cron_origin() -> CronOrigin:
    origin = _CRON_ORIGIN.get()
    if origin is None:
        msg = "cron tools must be called from within a Talon conversation"
        raise RuntimeError(msg)
    return origin


def _cron_origin_from_request(request: AgentRequest) -> CronOrigin:
    channel = request.metadata.get("channel")
    message_id = request.metadata.get("message_id")
    origin_conversation_id = request.metadata.get("origin_conversation_id")

View on GitHub (pinned to a1af029e6e)

Solutions

  1. Check the model class: `profile` must be a writable dict attribute; upgrade the provider package if it recently changed profile handling
  2. Remove/unset the context-size env var so the model profile is left untouched
  3. Use a model implementation known to support profile overrides (standard `init_chat_model` providers)

Example fix

# before
@property
def profile(self):
    return self._profile
# after
@property
def profile(self):
    return self._profile

@profile.setter
def profile(self, value):
    self._profile = dict(value)
Defensive patterns

Strategy: validation

Validate before calling

model = init_chat_model(model_name)
if os.environ.get("DEEPAGENTS_TALON_CONTEXT_SIZE"):
    if not hasattr(model, "profile"):
        raise TypeError(f"{type(model).__name__} does not support profile overrides")
    try:
        model.profile = {**getattr(model, "profile", {}), "max_input_tokens": 100000}
    except (AttributeError, TypeError, ValueError) as exc:
        raise TypeError(f"cannot set profile on {type(model).__name__}: {exc}") from exc

Type guard

def supports_profile_override(model: object) -> bool:
    return isinstance(getattr(type(model), "profile", None), property) and \
        getattr(type(model).profile, "fset", None) is not None

Try / catch

try:
    resolved = runtime.resolve_model()
except ValueError as exc:
    if "Could not apply" in str(exc):
        logger.warning("model profile override unsupported; continuing with defaults")
        resolved = fallback_model()
    else:
        raise

Prevention

When it happens

Trigger: 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__`.

Common situations: 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.

Related errors


AI-assisted analysis of langchain-ai/deepagents@a1af029e6e (2026-08-29). Data as JSON: /api/errors/65d08d56f14a0851. Report an issue: GitHub.