Skip to content

Commit e3f6adf

Browse files
authored
feat(anthropic): support top-level param for skills via container; updates thinking display mode (#39962)
1 parent c253f54 commit e3f6adf

4 files changed

Lines changed: 234 additions & 13 deletions

File tree

‎libs/partners/anthropic/langchain_anthropic/chat_models.py‎

Lines changed: 73 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,6 @@ class AnthropicTool(TypedDict):
177177
_TOOL_TYPE_TO_BETA: dict[str, str] = {
178178
"web_fetch_20250910": "web-fetch-2025-09-10",
179179
"code_execution_20250522": "code-execution-2025-05-22",
180-
"code_execution_20250825": "code-execution-2025-08-25",
181180
"mcp_toolset": "mcp-client-2025-11-20",
182181
"memory_20250818": "context-management-2025-06-27",
183182
"computer_20250124": "computer-use-2025-01-24",
@@ -816,6 +815,15 @@ def _format_messages(
816815
return system, formatted_messages
817816

818817

818+
def _container_id(container: Any) -> str | None:
819+
"""Return the container ID from either accepted `container` shape."""
820+
if isinstance(container, str):
821+
return container
822+
if isinstance(container, dict):
823+
return container.get("id")
824+
return None
825+
826+
819827
def _collect_code_execution_tool_ids(formatted_messages: list[dict]) -> set[str]:
820828
"""Collect `tool_use` IDs that were called by `code_execution`.
821829
@@ -1255,6 +1263,28 @@ class ChatAnthropic(BaseChatModel):
12551263
[context management](https://platform.claude.com/docs/en/build-with-claude/context-editing).
12561264
"""
12571265

1266+
container: dict[str, Any] | str | None = None
1267+
"""Code execution container for the request.
1268+
1269+
Either a container ID from a previous response, or a dict of container
1270+
parameters — notably
1271+
[skills](https://platform.claude.com/docs/en/build-with-claude/skills-guide)
1272+
to load into the container. Skills require a
1273+
[code execution](https://docs.langchain.com/oss/python/integrations/chat/anthropic#code-execution)
1274+
tool to be bound.
1275+
1276+
```python
1277+
model = ChatAnthropic(
1278+
model="claude-opus-5",
1279+
container={
1280+
"skills": [{"type": "anthropic", "skill_id": "pptx", "version": "latest"}]
1281+
},
1282+
).bind_tools([{"type": "code_execution_20260521", "name": "code_execution"}])
1283+
```
1284+
1285+
Can also be passed at call time, which overrides the value set here.
1286+
"""
1287+
12581288
reuse_last_container: bool | None = None
12591289
"""Automatically reuse container from most recent response (code execution).
12601290
@@ -1582,6 +1612,7 @@ def _get_request_payload(
15821612
"betas": self.betas,
15831613
"context_management": self.context_management,
15841614
"mcp_servers": self.mcp_servers,
1615+
"container": self.container,
15851616
"user_profile_id": self.user_profile_id,
15861617
"system": system,
15871618
**self.model_kwargs,
@@ -1667,19 +1698,43 @@ def _get_request_payload(
16671698
output_config = payload.setdefault("output_config", {})
16681699
output_config["format"] = payload.pop("output_format")
16691700

1670-
if self.reuse_last_container:
1671-
# Check for most recent AIMessage with container set in response_metadata
1672-
# and set as a top-level param on the request
1701+
container = payload.get("container")
1702+
1703+
if self.reuse_last_container and not _container_id(container):
1704+
# Reuse the container from the most recent response (code execution)
16731705
for message in reversed(messages):
16741706
if (
16751707
isinstance(message, AIMessage)
1676-
and (container := message.response_metadata.get("container"))
1677-
and isinstance(container, dict)
1678-
and (container_id := container.get("id"))
1708+
and isinstance(
1709+
last_container := message.response_metadata.get("container"),
1710+
dict,
1711+
)
1712+
and (container_id := last_container.get("id"))
16791713
):
1680-
payload["container"] = container_id
1714+
payload["container"] = (
1715+
{**container, "id": container_id}
1716+
if isinstance(container, dict)
1717+
else container_id
1718+
)
16811719
break
16821720

1721+
if (
1722+
isinstance(container, dict)
1723+
and container.get("skills")
1724+
and not any(
1725+
isinstance(tool, dict)
1726+
and str(tool.get("type", "")).startswith("code_execution")
1727+
for tool in (payload.get("tools") or [])
1728+
)
1729+
):
1730+
warnings.warn(
1731+
"Skills require a code execution tool to be bound, e.g. "
1732+
'`bind_tools([{"type": "code_execution_20260521", '
1733+
'"name": "code_execution"}])`.',
1734+
UserWarning,
1735+
stacklevel=2,
1736+
)
1737+
16831738
# Note: Beta headers are no longer required for structured outputs
16841739
# (output_config.format or strict tool use) as they are now generally available
16851740
if "tools" in payload and isinstance(payload["tools"], list):
@@ -1731,6 +1786,16 @@ def _get_request_payload(
17311786
else:
17321787
payload["betas"] = [required_beta]
17331788

1789+
# Auto-append required beta for the `updates` thinking display mode
1790+
thinking = payload.get("thinking")
1791+
if isinstance(thinking, dict) and thinking.get("display") == "updates":
1792+
required_beta = "thinking-display-updates-2026-08-18"
1793+
if payload.get("betas"):
1794+
if required_beta not in payload["betas"]:
1795+
payload["betas"] = [*payload["betas"], required_beta]
1796+
else:
1797+
payload["betas"] = [required_beta]
1798+
17341799
# Auto-append required beta for user_profile_id
17351800
if payload.get("user_profile_id"):
17361801
required_beta = "user-profiles-2026-03-24"
18.2 KB
Binary file not shown.

‎libs/partners/anthropic/tests/integration_tests/test_chat_models.py‎

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1884,17 +1884,22 @@ def test_code_execution_old(output_version: Literal["v0", "v1"]) -> None:
18841884
)
18851885

18861886

1887+
def _collect_file_ids(content: Any) -> list[str]:
1888+
"""Recursively collect `file_id` values from response content."""
1889+
if isinstance(content, dict):
1890+
found = [content["file_id"]] if "file_id" in content else []
1891+
return found + [fid for v in content.values() for fid in _collect_file_ids(v)]
1892+
if isinstance(content, list):
1893+
return [fid for item in content for fid in _collect_file_ids(item)]
1894+
return []
1895+
1896+
18871897
@pytest.mark.default_cassette("test_code_execution.yaml.gz")
18881898
@pytest.mark.vcr
18891899
@pytest.mark.parametrize("output_version", ["v0", "v1"])
18901900
def test_code_execution(output_version: Literal["v0", "v1"]) -> None:
1891-
"""Note: this is a beta feature.
1892-
1893-
TODO: Update to remove beta once generally available.
1894-
"""
18951901
llm = ChatAnthropic(
18961902
model=MODEL_NAME, # type: ignore[call-arg]
1897-
betas=["code-execution-2025-08-25"],
18981903
output_version=output_version,
18991904
)
19001905

@@ -1952,6 +1957,61 @@ def test_code_execution(output_version: Literal["v0", "v1"]) -> None:
19521957
)
19531958

19541959

1960+
@pytest.mark.default_cassette("test_skills.yaml.gz")
1961+
@pytest.mark.vcr
1962+
@pytest.mark.parametrize("output_version", ["v0", "v1"])
1963+
def test_skills(output_version: Literal["v0", "v1"]) -> None:
1964+
"""Load an Anthropic skill into the code execution container."""
1965+
skills = [{"type": "anthropic", "skill_id": "xlsx"}]
1966+
code_execution = {"type": "code_execution_20250825", "name": "code_execution"}
1967+
llm = ChatAnthropic(
1968+
model=MODEL_NAME, # type: ignore[call-arg]
1969+
container={"skills": skills},
1970+
reuse_last_container=True,
1971+
output_version=output_version,
1972+
)
1973+
llm_with_tools = llm.bind_tools([code_execution])
1974+
1975+
input_message = {
1976+
"role": "user",
1977+
"content": "Create an xlsx file with a single cell containing the number 42.",
1978+
}
1979+
1980+
# Stream the first turn. `.output` blocks until the stream finishes and
1981+
# returns the aggregated message.
1982+
# `stream_events` is typed as `Iterator[Any]` on a bound model; the v3
1983+
# protocol returns a `ChatModelStream`.
1984+
stream = cast("Any", llm_with_tools.stream_events([input_message], version="v3"))
1985+
first_response = stream.output
1986+
1987+
# The skill ran in the container and wrote a file.
1988+
container_id = first_response.response_metadata["container"]["id"]
1989+
assert container_id
1990+
assert _collect_file_ids(first_response.content)
1991+
1992+
# `reuse_last_container` supplies the container ID on the next turn without
1993+
# dropping the skills.
1994+
messages: list = [
1995+
input_message,
1996+
first_response,
1997+
{"role": "user", "content": "Now change the cell to 43."},
1998+
]
1999+
payload = llm._get_request_payload(messages, tools=[code_execution])
2000+
assert payload["container"] == {"id": container_id, "skills": skills}
2001+
2002+
# The aggregated stream is valid history, so the follow-up round-trips.
2003+
second_response = llm_with_tools.invoke(messages)
2004+
block_types = {block["type"] for block in second_response.content} # type: ignore[index]
2005+
if output_version == "v0":
2006+
assert {
2007+
"text",
2008+
"server_tool_use",
2009+
"bash_code_execution_tool_result",
2010+
} <= block_types
2011+
else:
2012+
assert {"text", "server_tool_call", "server_tool_result"} <= block_types
2013+
2014+
19552015
@pytest.mark.default_cassette("test_remote_mcp.yaml.gz")
19562016
@pytest.mark.vcr
19572017
@pytest.mark.parametrize("output_version", ["v0", "v1"])

‎libs/partners/anthropic/tests/unit_tests/test_chat_models.py‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4985,3 +4985,99 @@ def test_unrelated_type_error_propagates_unchanged() -> None:
49854985
llm.invoke([HumanMessage(content="test")])
49864986

49874987
assert exc_info.value is unrelated_error
4988+
4989+
4990+
_CODE_EXECUTION_TOOL = [{"type": "code_execution_20250825", "name": "code_execution"}]
4991+
_PPTX_SKILL = [{"type": "anthropic", "skill_id": "pptx", "version": "latest"}]
4992+
4993+
4994+
def test_container_init_param() -> None:
4995+
"""`container` set at construction is included in the payload."""
4996+
llm = ChatAnthropic(model=MODEL_NAME, container={"skills": _PPTX_SKILL})
4997+
payload = llm._get_request_payload(
4998+
[HumanMessage("Hello, world!")], tools=_CODE_EXECUTION_TOOL
4999+
)
5000+
assert payload["container"] == {"skills": _PPTX_SKILL}
5001+
5002+
5003+
def test_container_runtime_overrides_init() -> None:
5004+
"""A call-time `container` takes precedence over the init value."""
5005+
llm = ChatAnthropic(model=MODEL_NAME, container={"skills": _PPTX_SKILL})
5006+
payload = llm._get_request_payload(
5007+
[HumanMessage("Hello, world!")],
5008+
tools=_CODE_EXECUTION_TOOL,
5009+
container="container_runtime",
5010+
)
5011+
assert payload["container"] == "container_runtime"
5012+
5013+
5014+
def test_container_merged_with_reused_container() -> None:
5015+
"""`reuse_last_container` supplies an ID without dropping other keys."""
5016+
llm = ChatAnthropic(
5017+
model=MODEL_NAME, container={"skills": _PPTX_SKILL}, reuse_last_container=True
5018+
)
5019+
messages = [
5020+
HumanMessage("Hello, world!"),
5021+
AIMessage("Done.", response_metadata={"container": {"id": "container_123"}}),
5022+
HumanMessage("Now edit it."),
5023+
]
5024+
payload = llm._get_request_payload(messages, tools=_CODE_EXECUTION_TOOL)
5025+
assert payload["container"] == {"id": "container_123", "skills": _PPTX_SKILL}
5026+
5027+
5028+
def test_reuse_last_container_without_container_param() -> None:
5029+
"""Without a `container`, a reused container is passed as a bare ID."""
5030+
llm = ChatAnthropic(model=MODEL_NAME, reuse_last_container=True)
5031+
messages = [
5032+
HumanMessage("Hello, world!"),
5033+
AIMessage("Done.", response_metadata={"container": {"id": "container_123"}}),
5034+
HumanMessage("Again."),
5035+
]
5036+
payload = llm._get_request_payload(messages, tools=_CODE_EXECUTION_TOOL)
5037+
assert payload["container"] == "container_123"
5038+
5039+
5040+
def test_reuse_last_container_does_not_override_explicit_id() -> None:
5041+
"""An explicitly passed container ID wins over `reuse_last_container`."""
5042+
llm = ChatAnthropic(model=MODEL_NAME, reuse_last_container=True)
5043+
messages = [
5044+
HumanMessage("Hello, world!"),
5045+
AIMessage("Done.", response_metadata={"container": {"id": "container_123"}}),
5046+
HumanMessage("Again."),
5047+
]
5048+
payload = llm._get_request_payload(
5049+
messages, tools=_CODE_EXECUTION_TOOL, container="container_explicit"
5050+
)
5051+
assert payload["container"] == "container_explicit"
5052+
5053+
5054+
def test_container_absent_by_default() -> None:
5055+
"""When unset, `container` is stripped from the payload."""
5056+
llm = ChatAnthropic(model=MODEL_NAME)
5057+
payload = llm._get_request_payload([HumanMessage("Hello, world!")])
5058+
assert "container" not in payload
5059+
5060+
5061+
def test_skills_without_code_execution_tool_warns() -> None:
5062+
"""Skills are inert without a code execution tool, so warn."""
5063+
llm = ChatAnthropic(model=MODEL_NAME, container={"skills": _PPTX_SKILL})
5064+
with pytest.warns(UserWarning, match="code execution tool"):
5065+
llm._get_request_payload([HumanMessage("Hello, world!")])
5066+
5067+
5068+
def test_thinking_display_updates_enables_beta() -> None:
5069+
"""`display="updates"` auto-enables its beta, routing through beta.messages."""
5070+
llm = ChatAnthropic(
5071+
model=MODEL_NAME, thinking={"type": "adaptive", "display": "updates"}
5072+
)
5073+
payload = llm._get_request_payload([HumanMessage("Hello, world!")])
5074+
assert "thinking-display-updates-2026-08-18" in payload["betas"]
5075+
5076+
5077+
def test_thinking_display_summarized_does_not_enable_beta() -> None:
5078+
"""Other `display` values are generally available."""
5079+
llm = ChatAnthropic(
5080+
model=MODEL_NAME, thinking={"type": "adaptive", "display": "summarized"}
5081+
)
5082+
payload = llm._get_request_payload([HumanMessage("Hello, world!")])
5083+
assert "betas" not in payload

0 commit comments

Comments
 (0)