[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7928ZNXMBK093Q2MGEN25CQ":3,"skill-same:01M7928ZNXMBK093Q2MGEN25CQ":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":38,"commitSha":39,"skillDirectory":40,"forksCount":41,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M7928ZNXMBK093Q2MGEN25CQ","langchain-content-blocks",null,"Works correctly with LangChain 1.0's typed content blocks on AIMessage.content\n— text, tool_use, image, thinking, document — across Claude, GPT-4o, and\nGemini, including multi-modal composition and tool-call iteration. Use when\ncomposing multi-modal messages, iterating tool_use blocks, handling Claude's\nthinking content, or unifying image inputs across providers. Trigger with\n\"langchain content blocks\", \"AIMessage.content\", \"tool_use block\", \"claude\nimage input\", \"langchain multimodal\", \"thinking block replay\",\n\"claude citations\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-content-blocks\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-content-blocks\ndescription: |\n  Works correctly with LangChain 1.0's typed content blocks on AIMessage.content\n  — text, tool_use, image, thinking, document — across Claude, GPT-4o, and\n  Gemini, including multi-modal composition and tool-call iteration. Use when\n  composing multi-modal messages, iterating tool_use blocks, handling Claude's\n  thinking content, or unifying image inputs across providers. Trigger with\n  \"langchain content blocks\", \"AIMessage.content\", \"tool_use block\", \"claude\n  image input\", \"langchain multimodal\", \"thinking block replay\",\n  \"claude citations\".\nallowed-tools: Read, Write, Edit, Bash(python:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, content-blocks, multimodal, tool-use]\ncompatible-with: claude-code, codex\n---\n\n# LangChain Content Blocks (Python)\n\n## Overview\n\nOn Claude, `AIMessage.content` is `list[dict]` even for pure text — so any\ncode from an OpenAI-first tutorial that calls `message.content.lower()` or\n`message.content.split()` crashes with `AttributeError: 'list' object has\nno attribute 'lower'` on the first production Claude call (P02).\nMulti-modal code that works on GPT-4o breaks on Claude because pre-1.0\nimage-block shapes differed across providers (P64). Multi-turn Claude\nreplay with extended thinking fails with\n`anthropic.BadRequestError: missing signature` when prior `thinking`\nblocks are stripped. Forced `tool_choice` prevents\n`stop_reason=\"end_turn\"` and loops forever (P63).\n\nThis is the deep-dive companion to `langchain-model-inference`. That\nskill's `references\u002Fcontent-blocks.md` covers the `str` vs `list[dict]`\ndivergence and a safe text extractor. **This skill goes further**:\n\n- `tool_use` block iteration mechanics — IDs, args as dict vs JSON string, streaming deltas\n- `thinking` blocks — signature, redaction, multi-turn replay semantics\n- `document` blocks — Claude citations API, source types, citation extraction\n- Multi-modal composition — universal 1.0 `image` shape, per-provider adapter behavior\n- Per-provider size limits (Anthropic 5 MB\u002Fimage up to 20 images, OpenAI 20 MB\u002Fimage, Gemini 20 MB\u002Frequest)\n\nPin: `langchain-core 1.0.x`, `langchain-anthropic >= 1.0`,\n`langchain-openai >= 1.0`, `anthropic >= 0.40`. Pain-catalog anchors:\nP02, P58, P63, P64.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`\n- At least one provider package: `pip install langchain-anthropic langchain-openai`\n- For extended thinking: `langchain-anthropic >= 1.0` and Claude Sonnet 4+ \u002F Opus 4+\n- For citations: `anthropic >= 0.40` and Claude Sonnet 4+\n- Familiarity with `langchain-model-inference` (reads `references\u002Fcontent-blocks.md` first)\n\n## Instructions\n\n### Step 1 — Learn the block-type taxonomy\n\nLangChain 1.0 defines six typed content blocks on `AIMessage.content`\n(and on chunks during streaming):\n\n| Block type | Produced by | Notes |\n|------------|-------------|-------|\n| `text` | All providers | On Claude, always wrapped as `[{\"type\":\"text\",\"text\":\"...\"}]` |\n| `tool_use` | Claude, GPT-4o, Gemini | Always round-trip via `msg.tool_calls`, not hand-parsed |\n| `tool_result` | You (via `ToolMessage`) | One per `tool_use`; `tool_call_id` must match byte-for-byte |\n| `image` | Claude vision, GPT-4o, Gemini | Universal 1.0 shape; adapter handles wire format per provider |\n| `thinking` | Claude extended thinking only | Must preserve `signature` for replay |\n| `document` | Claude citations API (Sonnet 4+) | Input-side only; citations attach to output `text` blocks |\n\nSee [Block-Type Matrix](references\u002Fblock-type-matrix.md) for the full table\nwith streaming behavior and per-type gotchas.\n\n### Step 2 — Iterate mixed content safely\n\nFor most code, use the helpers:\n\n```python\ntext = msg.text()                    # concatenated text across all text blocks\ntool_calls = msg.tool_calls          # normalized list[ToolCall]\nusage = msg.usage_metadata           # input_tokens, output_tokens, cache_*\n```\n\nHand-roll block iteration only when you need to (a) preserve order,\n(b) extract `thinking` blocks for replay, or (c) read `citations`\nmetadata from `text` blocks. Order-preserving iteration:\n\n```python\nfrom langchain_core.messages import AIMessage\n\ndef iter_blocks(msg: AIMessage):\n    if isinstance(msg.content, str):\n        yield \"text\", {\"type\": \"text\", \"text\": msg.content}\n        return\n    for block in msg.content:\n        if isinstance(block, dict):\n            yield block.get(\"type\", \"unknown\"), block\n        else:\n            yield getattr(block, \"type\", \"unknown\"), block\n```\n\n### Step 3 — Compose multi-modal messages with the universal `image` block\n\n```python\nimport base64\nfrom pathlib import Path\nfrom langchain_core.messages import HumanMessage\n\ndef image_block(path: str) -> dict:\n    data = base64.standard_b64encode(Path(path).read_bytes()).decode(\"ascii\")\n    mime = {\"png\": \"image\u002Fpng\", \"jpg\": \"image\u002Fjpeg\",\n            \"jpeg\": \"image\u002Fjpeg\", \"webp\": \"image\u002Fwebp\"}[\n        Path(path).suffix.lstrip(\".\").lower()]\n    return {\n        \"type\": \"image\",\n        \"source_type\": \"base64\",   # or \"url\"\n        \"data\": data,\n        \"mime_type\": mime,\n    }\n\nmsg = HumanMessage(content=[\n    image_block(\"screenshot.png\"),                         # put image FIRST\n    {\"type\": \"text\", \"text\": \"What is broken here?\"},      # instruction LAST\n])\nresponse = claude.invoke([msg])\n```\n\nThree invariants:\n\n1. `content` **must be `list[dict]`** when including non-text blocks.\n2. Put the image *before* the instruction — Claude attends most to trailing tokens.\n3. Respect provider limits (Anthropic: 5 MB\u002Fimage, up to 20 images; OpenAI: 20 MB\u002Fimage; Gemini: 20 MB\u002Frequest total).\n\nLangChain's adapter translates the universal shape to each provider's\nwire format. See [Multi-Modal Composition](references\u002Fmultimodal-composition.md)\nfor the full adapter table, MIME-type compatibility, and the\n`document`\u002Fcitations pattern.\n\n### Step 4 — Iterate `tool_use` correctly across stream deltas\n\nCanonical non-streaming:\n\n```python\nfor tc in msg.tool_calls:\n    output = tools[tc[\"name\"]](**tc[\"args\"])\n    history.append(ToolMessage(content=str(output), tool_call_id=tc[\"id\"]))\n```\n\n`tc[\"args\"]` is already a parsed `dict` — do not `json.loads` it.\n`tc[\"id\"]` is provider-shaped (`toolu_*` on Anthropic, `call_*` on\nOpenAI, 24+ chars) and must be copied verbatim to the `ToolMessage`.\n\nStreaming is different. `tool_use.input` arrives as partial JSON\nfragments across `on_chat_model_stream` events. Buffer with\n`tool_call_chunks`, parse once at `on_chat_model_end`:\n\n```python\nfrom collections import defaultdict\nimport json\n\npartial = defaultdict(str)   # index -> accumulated JSON fragment\nmeta = {}                     # index -> {name, id}\n\nasync for event in model.astream_events({\"messages\": [...]}, version=\"v2\"):\n    if event[\"event\"] != \"on_chat_model_stream\":\n        continue\n    for tc_chunk in getattr(event[\"data\"][\"chunk\"], \"tool_call_chunks\", []) or []:\n        idx = tc_chunk[\"index\"]\n        if tc_chunk.get(\"name\"):\n            meta[idx] = {\"name\": tc_chunk[\"name\"], \"id\": tc_chunk[\"id\"]}\n        if tc_chunk.get(\"args\"):\n            partial[idx] += tc_chunk[\"args\"]\n\ncompleted = [{**meta[i], \"args\": json.loads(partial[i])} for i in meta]\n```\n\nSee [Tool-Use Iteration](references\u002Ftool-use-iteration.md) for\nmulti-tool-per-turn handling, `ToolMessage` ordering, and the forced-\n`tool_choice` infinite-loop trap (P63).\n\n### Step 5 — Preserve Claude `thinking` blocks for replay\n\nClaude extended thinking (Sonnet 4+, Opus 4+) returns `thinking` blocks\ncarrying a cryptographic `signature`. The next turn must round-trip\nthose blocks **intact** or Anthropic rejects the request:\n\n```\nanthropic.BadRequestError: messages.1.content.0: missing signature\n```\n\nThe foot-gun: `msg.text()` strips thinking blocks. Never do:\n\n```python\n# WRONG — thinking blocks lost, replay fails\nhistory.append(AIMessage(content=ai_1.text()))\n```\n\nCorrect — pass the `AIMessage` back verbatim:\n\n```python\nhistory.append(ai_1)   # preserves full content list + signatures\n```\n\nFor persistence across sessions, serialize with\n`messages_to_dict(...)` (not custom JSON), which preserves block\nstructure:\n\n```python\nimport json\nfrom langchain_core.messages import messages_to_dict, messages_from_dict\n\nserialized = json.dumps(messages_to_dict([ai_1]))\nrestored = messages_from_dict(json.loads(serialized))\n```\n\nSee [Thinking Blocks](references\u002Fthinking-blocks.md) for redaction\nhandling, the budget-tokens rule, and the interaction with tool calls.\n\n### Step 6 — Provider-adapter checklist\n\nBefore sending any multi-modal or tool-using message:\n\n1. Is `content` a `list[dict]` when it contains non-text blocks?\n2. Are image blocks in the universal 1.0 shape (`source_type`, `data`, `mime_type`)?\n3. Is each image under the target provider's limit? (5 MB \u002F 20 MB \u002F 20 MB total.)\n4. If `tool_use` is involved, am I passing `msg.tool_calls` — not parsed `content`?\n5. If extended thinking is on, am I returning the full `AIMessage` — not `msg.text()`?\n6. System message at position 0 (P58) — not reordered by middleware?\n\n## Output\n\n- Block-type matrix applied to a specific response (which types present, which helper used)\n- Safe iteration that preserves order, citations, and thinking signatures\n- Multi-modal `HumanMessage` in the universal 1.0 `image` shape, portable across Claude\u002FGPT-4o\u002FGemini\n- `tool_use` stream-delta accumulator that buffers partial `input` JSON and parses once at end\n- Multi-turn Claude replay that keeps `thinking` blocks intact (no `missing signature` errors)\n- `document`\u002Fcitations extractor that reads `citations` metadata from `text` blocks\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `AttributeError: 'list' object has no attribute 'lower'` | Treating `AIMessage.content` as `str` on Claude (P02) | Use `msg.text()` or iterate blocks |\n| `anthropic.BadRequestError: messages.N.content.M: missing signature` | Stripped `thinking` block on replay | Pass `AIMessage` object back verbatim; never rebuild from `text()` |\n| `anthropic.BadRequestError: tool_use_id not found in corresponding tool_result` | Typo \u002F case mismatch in `ToolMessage.tool_call_id` | Copy `tc[\"id\"]` verbatim |\n| `anthropic.BadRequestError: tool_use ids were found without tool_result blocks` | Skipped a tool call | Emit one `ToolMessage` per `tool_call` (use `status=\"error\"` on failure) |\n| `anthropic.BadRequestError: image exceeds 5 MB limit` | Un-resized screenshot | Pre-resize to \u003C 5 MB (1024x1024 JPEG 85 is ~500 KB) |\n| `openai.BadRequestError: Invalid image data` | Hand-rolled `image_url` with wrong prefix | Use the universal block; adapter emits the `data:image\u002F...;base64,` prefix |\n| Infinite agent loop | Forced `tool_choice` inside a loop (P63) | Use `tool_choice=\"auto\"` for agents; forced-choice only for single-call extraction |\n| `json.JSONDecodeError` inside stream loop | Parsing partial `tool_use.input` fragment | Buffer in a `defaultdict(str)`; parse once at `on_chat_model_end` |\n| Citations silently missing | Read via `msg.text()` which strips metadata | Iterate `msg.content` and read `block[\"citations\"]` on text blocks |\n\n## Examples\n\n### Single-shot multi-modal on Claude + GPT-4o with one message object\n\n```python\nmsg = HumanMessage(content=[\n    image_block(\"ui.png\"),\n    {\"type\": \"text\", \"text\": \"Identify the broken UI element.\"},\n])\n# Same message works on both providers via adapter translation\nclaude_resp = claude.invoke([msg])\ngpt4o_resp = gpt4o.invoke([msg])\n```\n\n### Multi-turn Claude replay with extended thinking\n\n```python\nclaude = ChatAnthropic(\n    model=\"claude-sonnet-4-6\",\n    max_tokens=8192,\n    thinking={\"type\": \"enabled\", \"budget_tokens\": 4096},\n)\n\nai_1 = claude.invoke([HumanMessage(content=\"What is the capital of France?\")])\n# ai_1.content == [{\"type\":\"thinking\",...,\"signature\":\"...\"}, {\"type\":\"text\",...}]\n\n# Turn 2 — pass ai_1 VERBATIM\nai_2 = claude.invoke([\n    HumanMessage(content=\"What is the capital of France?\"),\n    ai_1,                                                    # thinking preserved\n    HumanMessage(content=\"And the population?\"),\n])\n```\n\nSee [Thinking Blocks](references\u002Fthinking-blocks.md) for the full replay\ninvariants and persistence pattern.\n\n### Extracting Claude citations from `document` input\n\n```python\ndoc_block = {\n    \"type\": \"document\",\n    \"source\": {\"type\": \"base64\", \"media_type\": \"application\u002Fpdf\", \"data\": pdf_b64},\n    \"title\": \"Q3 Earnings Report\",\n    \"citations\": {\"enabled\": True},\n}\nresp = claude.invoke([HumanMessage(content=[\n    doc_block,\n    {\"type\": \"text\", \"text\": \"What drove revenue this quarter?\"},\n])])\n\nfor block in resp.content:\n    if block.get(\"type\") != \"text\":\n        continue\n    print(block[\"text\"])\n    for c in block.get(\"citations\", []):\n        print(f\"  -> {c['document_title']}: {c['cited_text']!r}\")\n```\n\n`msg.text()` flattens this — you lose citations. See\n[Multi-Modal Composition](references\u002Fmultimodal-composition.md) for the\nfull `document` block reference including supported source types.\n\n### Streaming `tool_use` with live argument rendering\n\nSee [Tool-Use Iteration](references\u002Ftool-use-iteration.md) for the\ncomplete `tool_call_chunks` accumulator including multi-tool-per-turn\nhandling and the `ToolMessage` ordering invariant.\n\n## Resources\n\n- [LangChain messages concept](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Fmessages\u002F)\n- [LangChain multimodality](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Fmultimodality\u002F)\n- [`AIMessage` API reference](https:\u002F\u002Fpython.langchain.com\u002Fapi_reference\u002Fcore\u002Fmessages\u002Flangchain_core.messages.ai.AIMessage.html)\n- [Anthropic content blocks \u002F messages API](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fapi\u002Fmessages-examples)\n- [Anthropic extended thinking](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fbuild-with-claude\u002Fextended-thinking)\n- [Anthropic citations](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fbuild-with-claude\u002Fcitations)\n- [OpenAI vision](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fvision)\n- [Gemini multimodal](https:\u002F\u002Fai.google.dev\u002Fgemini-api\u002Fdocs\u002Fvision)\n- Companion skill: `langchain-model-inference` (read its `references\u002Fcontent-blocks.md` for the `str` vs `list[dict]` fundamentals)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P02, P58, P63, P64)\n","# LangChain Content Blocks (Python)\n\n## Overview\n\nOn Claude, `AIMessage.content` is `list[dict]` even for pure text — so any\ncode from an OpenAI-first tutorial that calls `message.content.lower()` or\n`message.content.split()` crashes with `AttributeError: 'list' object has\nno attribute 'lower'` on the first production Claude call (P02).\nMulti-modal code that works on GPT-4o breaks on Claude because pre-1.0\nimage-block shapes differed across providers (P64). Multi-turn Claude\nreplay with extended thinking fails with\n`anthropic.BadRequestError: missing signature` when prior `thinking`\nblocks are stripped. Forced `tool_choice` prevents\n`stop_reason=\"end_turn\"` and loops forever (P63).\n\nThis is the deep-dive companion to `langchain-model-inference`. That\nskill's `references\u002Fcontent-blocks.md` covers the `str` vs `list[dict]`\ndivergence and a safe text extractor. **This skill goes further**:\n\n- `tool_use` block iteration mechanics — IDs, args as dict vs JSON string, streaming deltas\n- `thinking` blocks — signature, redaction, multi-turn replay semantics\n- `document` blocks — Claude citations API, source types, citation extraction\n- Multi-modal composition — universal 1.0 `image` shape, per-provider adapter behavior\n- Per-provider size limits (Anthropic 5 MB\u002Fimage up to 20 images, OpenAI 20 MB\u002Fimage, Gemini 20 MB\u002Frequest)\n\nPin: `langchain-core 1.0.x`, `langchain-anthropic >= 1.0`,\n`langchain-openai >= 1.0`, `anthropic >= 0.40`. Pain-catalog anchors:\nP02, P58, P63, P64.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`\n- At least one provider package: `pip install langchain-anthropic langchain-openai`\n- For extended thinking: `langchain-anthropic >= 1.0` and Claude Sonnet 4+ \u002F Opus 4+\n- For citations: `anthropic >= 0.40` and Claude Sonnet 4+\n- Familiarity with `langchain-model-inference` (reads `references\u002Fcontent-blocks.md` first)\n\n## Instructions\n\n### Step 1 — Learn the block-type taxonomy\n\nLangChain 1.0 defines six typed content blocks on `AIMessage.content`\n(and on chunks during streaming):\n\n| Block type | Produced by | Notes |\n|------------|-------------|-------|\n| `text` | All providers | On Claude, always wrapped as `[{\"type\":\"text\",\"text\":\"...\"}]` |\n| `tool_use` | Claude, GPT-4o, Gemini | Always round-trip via `msg.tool_calls`, not hand-parsed |\n| `tool_result` | You (via `ToolMessage`) | One per `tool_use`; `tool_call_id` must match byte-for-byte |\n| `image` | Claude vision, GPT-4o, Gemini | Universal 1.0 shape; adapter handles wire format per provider |\n| `thinking` | Claude extended thinking only | Must preserve `signature` for replay |\n| `document` | Claude citations API (Sonnet 4+) | Input-side only; citations attach to output `text` blocks |\n\nSee [Block-Type Matrix](references\u002Fblock-type-matrix.md) for the full table\nwith streaming behavior and per-type gotchas.\n\n### Step 2 — Iterate mixed content safely\n\nFor most code, use the helpers:\n\n```python\ntext = msg.text()                    # concatenated text across all text blocks\ntool_calls = msg.tool_calls          # normalized list[ToolCall]\nusage = msg.usage_metadata           # input_tokens, output_tokens, cache_*\n```\n\nHand-roll block iteration only when you need to (a) preserve order,\n(b) extract `thinking` blocks for replay, or (c) read `citations`\nmetadata from `text` blocks. Order-preserving iteration:\n\n```python\nfrom langchain_core.messages import AIMessage\n\ndef iter_blocks(msg: AIMessage):\n    if isinstance(msg.content, str):\n        yield \"text\", {\"type\": \"text\", \"text\": msg.content}\n        return\n    for block in msg.content:\n        if isinstance(block, dict):\n            yield block.get(\"type\", \"unknown\"), block\n        else:\n            yield getattr(block, \"type\", \"unknown\"), block\n```\n\n### Step 3 — Compose multi-modal messages with the universal `image` block\n\n```python\nimport base64\nfrom pathlib import Path\nfrom langchain_core.messages import HumanMessage\n\ndef image_block(path: str) -> dict:\n    data = base64.standard_b64encode(Path(path).read_bytes()).decode(\"ascii\")\n    mime = {\"png\": \"image\u002Fpng\", \"jpg\": \"image\u002Fjpeg\",\n            \"jpeg\": \"image\u002Fjpeg\", \"webp\": \"image\u002Fwebp\"}[\n        Path(path).suffix.lstrip(\".\").lower()]\n    return {\n        \"type\": \"image\",\n        \"source_type\": \"base64\",   # or \"url\"\n        \"data\": data,\n        \"mime_type\": mime,\n    }\n\nmsg = HumanMessage(content=[\n    image_block(\"screenshot.png\"),                         # put image FIRST\n    {\"type\": \"text\", \"text\": \"What is broken here?\"},      # instruction LAST\n])\nresponse = claude.invoke([msg])\n```\n\nThree invariants:\n\n1. `content` **must be `list[dict]`** when including non-text blocks.\n2. Put the image *before* the instruction — Claude attends most to trailing tokens.\n3. Respect provider limits (Anthropic: 5 MB\u002Fimage, up to 20 images; OpenAI: 20 MB\u002Fimage; Gemini: 20 MB\u002Frequest total).\n\nLangChain's adapter translates the universal shape to each provider's\nwire format. See [Multi-Modal Composition](references\u002Fmultimodal-composition.md)\nfor the full adapter table, MIME-type compatibility, and the\n`document`\u002Fcitations pattern.\n\n### Step 4 — Iterate `tool_use` correctly across stream deltas\n\nCanonical non-streaming:\n\n```python\nfor tc in msg.tool_calls:\n    output = tools[tc[\"name\"]](**tc[\"args\"])\n    history.append(ToolMessage(content=str(output), tool_call_id=tc[\"id\"]))\n```\n\n`tc[\"args\"]` is already a parsed `dict` — do not `json.loads` it.\n`tc[\"id\"]` is provider-shaped (`toolu_*` on Anthropic, `call_*` on\nOpenAI, 24+ chars) and must be copied verbatim to the `ToolMessage`.\n\nStreaming is different. `tool_use.input` arrives as partial JSON\nfragments across `on_chat_model_stream` events. Buffer with\n`tool_call_chunks`, parse once at `on_chat_model_end`:\n\n```python\nfrom collections import defaultdict\nimport json\n\npartial = defaultdict(str)   # index -> accumulated JSON fragment\nmeta = {}                     # index -> {name, id}\n\nasync for event in model.astream_events({\"messages\": [...]}, version=\"v2\"):\n    if event[\"event\"] != \"on_chat_model_stream\":\n        continue\n    for tc_chunk in getattr(event[\"data\"][\"chunk\"], \"tool_call_chunks\", []) or []:\n        idx = tc_chunk[\"index\"]\n        if tc_chunk.get(\"name\"):\n            meta[idx] = {\"name\": tc_chunk[\"name\"], \"id\": tc_chunk[\"id\"]}\n        if tc_chunk.get(\"args\"):\n            partial[idx] += tc_chunk[\"args\"]\n\ncompleted = [{**meta[i], \"args\": json.loads(partial[i])} for i in meta]\n```\n\nSee [Tool-Use Iteration](references\u002Ftool-use-iteration.md) for\nmulti-tool-per-turn handling, `ToolMessage` ordering, and the forced-\n`tool_choice` infinite-loop trap (P63).\n\n### Step 5 — Preserve Claude `thinking` blocks for replay\n\nClaude extended thinking (Sonnet 4+, Opus 4+) returns `thinking` blocks\ncarrying a cryptographic `signature`. The next turn must round-trip\nthose blocks **intact** or Anthropic rejects the request:\n\n```\nanthropic.BadRequestError: messages.1.content.0: missing signature\n```\n\nThe foot-gun: `msg.text()` strips thinking blocks. Never do:\n\n```python\n# WRONG — thinking blocks lost, replay fails\nhistory.append(AIMessage(content=ai_1.text()))\n```\n\nCorrect — pass the `AIMessage` back verbatim:\n\n```python\nhistory.append(ai_1)   # preserves full content list + signatures\n```\n\nFor persistence across sessions, serialize with\n`messages_to_dict(...)` (not custom JSON), which preserves block\nstructure:\n\n```python\nimport json\nfrom langchain_core.messages import messages_to_dict, messages_from_dict\n\nserialized = json.dumps(messages_to_dict([ai_1]))\nrestored = messages_from_dict(json.loads(serialized))\n```\n\nSee [Thinking Blocks](references\u002Fthinking-blocks.md) for redaction\nhandling, the budget-tokens rule, and the interaction with tool calls.\n\n### Step 6 — Provider-adapter checklist\n\nBefore sending any multi-modal or tool-using message:\n\n1. Is `content` a `list[dict]` when it contains non-text blocks?\n2. Are image blocks in the universal 1.0 shape (`source_type`, `data`, `mime_type`)?\n3. Is each image under the target provider's limit? (5 MB \u002F 20 MB \u002F 20 MB total.)\n4. If `tool_use` is involved, am I passing `msg.tool_calls` — not parsed `content`?\n5. If extended thinking is on, am I returning the full `AIMessage` — not `msg.text()`?\n6. System message at position 0 (P58) — not reordered by middleware?\n\n## Output\n\n- Block-type matrix applied to a specific response (which types present, which helper used)\n- Safe iteration that preserves order, citations, and thinking signatures\n- Multi-modal `HumanMessage` in the universal 1.0 `image` shape, portable across Claude\u002FGPT-4o\u002FGemini\n- `tool_use` stream-delta accumulator that buffers partial `input` JSON and parses once at end\n- Multi-turn Claude replay that keeps `thinking` blocks intact (no `missing signature` errors)\n- `document`\u002Fcitations extractor that reads `citations` metadata from `text` blocks\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `AttributeError: 'list' object has no attribute 'lower'` | Treating `AIMessage.content` as `str` on Claude (P02) | Use `msg.text()` or iterate blocks |\n| `anthropic.BadRequestError: messages.N.content.M: missing signature` | Stripped `thinking` block on replay | Pass `AIMessage` object back verbatim; never rebuild from `text()` |\n| `anthropic.BadRequestError: tool_use_id not found in corresponding tool_result` | Typo \u002F case mismatch in `ToolMessage.tool_call_id` | Copy `tc[\"id\"]` verbatim |\n| `anthropic.BadRequestError: tool_use ids were found without tool_result blocks` | Skipped a tool call | Emit one `ToolMessage` per `tool_call` (use `status=\"error\"` on failure) |\n| `anthropic.BadRequestError: image exceeds 5 MB limit` | Un-resized screenshot | Pre-resize to \u003C 5 MB (1024x1024 JPEG 85 is ~500 KB) |\n| `openai.BadRequestError: Invalid image data` | Hand-rolled `image_url` with wrong prefix | Use the universal block; adapter emits the `data:image\u002F...;base64,` prefix |\n| Infinite agent loop | Forced `tool_choice` inside a loop (P63) | Use `tool_choice=\"auto\"` for agents; forced-choice only for single-call extraction |\n| `json.JSONDecodeError` inside stream loop | Parsing partial `tool_use.input` fragment | Buffer in a `defaultdict(str)`; parse once at `on_chat_model_end` |\n| Citations silently missing | Read via `msg.text()` which strips metadata | Iterate `msg.content` and read `block[\"citations\"]` on text blocks |\n\n## Examples\n\n### Single-shot multi-modal on Claude + GPT-4o with one message object\n\n```python\nmsg = HumanMessage(content=[\n    image_block(\"ui.png\"),\n    {\"type\": \"text\", \"text\": \"Identify the broken UI element.\"},\n])\n# Same message works on both providers via adapter translation\nclaude_resp = claude.invoke([msg])\ngpt4o_resp = gpt4o.invoke([msg])\n```\n\n### Multi-turn Claude replay with extended thinking\n\n```python\nclaude = ChatAnthropic(\n    model=\"claude-sonnet-4-6\",\n    max_tokens=8192,\n    thinking={\"type\": \"enabled\", \"budget_tokens\": 4096},\n)\n\nai_1 = claude.invoke([HumanMessage(content=\"What is the capital of France?\")])\n# ai_1.content == [{\"type\":\"thinking\",...,\"signature\":\"...\"}, {\"type\":\"text\",...}]\n\n# Turn 2 — pass ai_1 VERBATIM\nai_2 = claude.invoke([\n    HumanMessage(content=\"What is the capital of France?\"),\n    ai_1,                                                    # thinking preserved\n    HumanMessage(content=\"And the population?\"),\n])\n```\n\nSee [Thinking Blocks](references\u002Fthinking-blocks.md) for the full replay\ninvariants and persistence pattern.\n\n### Extracting Claude citations from `document` input\n\n```python\ndoc_block = {\n    \"type\": \"document\",\n    \"source\": {\"type\": \"base64\", \"media_type\": \"application\u002Fpdf\", \"data\": pdf_b64},\n    \"title\": \"Q3 Earnings Report\",\n    \"citations\": {\"enabled\": True},\n}\nresp = claude.invoke([HumanMessage(content=[\n    doc_block,\n    {\"type\": \"text\", \"text\": \"What drove revenue this quarter?\"},\n])])\n\nfor block in resp.content:\n    if block.get(\"type\") != \"text\":\n        continue\n    print(block[\"text\"])\n    for c in block.get(\"citations\", []):\n        print(f\"  -> {c['document_title']}: {c['cited_text']!r}\")\n```\n\n`msg.text()` flattens this — you lose citations. See\n[Multi-Modal Composition](references\u002Fmultimodal-composition.md) for the\nfull `document` block reference including supported source types.\n\n### Streaming `tool_use` with live argument rendering\n\nSee [Tool-Use Iteration](references\u002Ftool-use-iteration.md) for the\ncomplete `tool_call_chunks` accumulator including multi-tool-per-turn\nhandling and the `ToolMessage` ordering invariant.\n\n## Resources\n\n- [LangChain messages concept](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Fmessages\u002F)\n- [LangChain multimodality](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Fmultimodality\u002F)\n- [`AIMessage` API reference](https:\u002F\u002Fpython.langchain.com\u002Fapi_reference\u002Fcore\u002Fmessages\u002Flangchain_core.messages.ai.AIMessage.html)\n- [Anthropic content blocks \u002F messages API](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fapi\u002Fmessages-examples)\n- [Anthropic extended thinking](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fbuild-with-claude\u002Fextended-thinking)\n- [Anthropic citations](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fbuild-with-claude\u002Fcitations)\n- [OpenAI vision](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fvision)\n- [Gemini multimodal](https:\u002F\u002Fai.google.dev\u002Fgemini-api\u002Fdocs\u002Fvision)\n- Companion skill: `langchain-model-inference` (read its `references\u002Fcontent-blocks.md` for the `str` vs `list[dict]` fundamentals)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P02, P58, P63, P64)\n",{"name":5,"tags":24,"author":33,"license":15,"version":34,"description":35,"allowed-tools":36,"compatible-with":37},[25,26,27,28,29,30,31,32],"saas","langchain","langgraph","python","langchain-1.0","content-blocks","multimodal","tool-use","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Works correctly with LangChain 1.0's typed content blocks on AIMessage.content\n— text, tool_use, image, thinking, document — across Claude, GPT-4o, and\nGemini, including multi-modal composition and tool-call iteration. Use when\ncomposing multi-modal messages, iterating tool_use blocks, handling Claude's\nthinking content, or unifying image inputs across providers. Trigger with\n\"langchain content blocks\", \"AIMessage.content\", \"tool_use block\", \"claude\nimage input\", \"langchain multimodal\", \"thinking block replay\",\n\"claude citations\".\n","Read, Write, Edit, Bash(python:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-content-blocks",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-content-blocks",{"tool":53,"command":54},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-content-blocks",{"tool":56,"command":57},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-content-blocks","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-content-blocks\u002FSKILL.md",true,[],[62,69,76,83,90,98],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]