langchain-core 1.0.0a3__py3-none-any.whl → 1.0.0a5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. langchain_core/_api/beta_decorator.py +6 -5
  2. langchain_core/_api/deprecation.py +11 -11
  3. langchain_core/callbacks/manager.py +2 -2
  4. langchain_core/callbacks/usage.py +2 -2
  5. langchain_core/document_loaders/langsmith.py +1 -1
  6. langchain_core/indexing/api.py +30 -30
  7. langchain_core/language_models/chat_models.py +7 -6
  8. langchain_core/language_models/fake_chat_models.py +5 -2
  9. langchain_core/load/serializable.py +1 -1
  10. langchain_core/messages/__init__.py +9 -15
  11. langchain_core/messages/ai.py +75 -9
  12. langchain_core/messages/base.py +79 -37
  13. langchain_core/messages/block_translators/__init__.py +11 -1
  14. langchain_core/messages/block_translators/anthropic.py +151 -134
  15. langchain_core/messages/block_translators/bedrock.py +73 -26
  16. langchain_core/messages/block_translators/bedrock_converse.py +270 -22
  17. langchain_core/messages/block_translators/langchain_v0.py +180 -43
  18. langchain_core/messages/block_translators/openai.py +224 -42
  19. langchain_core/messages/chat.py +4 -1
  20. langchain_core/messages/content.py +56 -112
  21. langchain_core/messages/function.py +9 -5
  22. langchain_core/messages/human.py +6 -2
  23. langchain_core/messages/modifier.py +1 -0
  24. langchain_core/messages/system.py +9 -2
  25. langchain_core/messages/tool.py +31 -14
  26. langchain_core/messages/utils.py +89 -83
  27. langchain_core/outputs/chat_generation.py +10 -6
  28. langchain_core/prompt_values.py +6 -2
  29. langchain_core/prompts/chat.py +6 -3
  30. langchain_core/prompts/few_shot.py +4 -1
  31. langchain_core/runnables/base.py +4 -1
  32. langchain_core/runnables/graph_ascii.py +1 -1
  33. langchain_core/tools/base.py +1 -2
  34. langchain_core/tools/convert.py +1 -1
  35. langchain_core/utils/aiter.py +1 -1
  36. langchain_core/utils/function_calling.py +5 -6
  37. langchain_core/utils/iter.py +1 -1
  38. langchain_core/vectorstores/in_memory.py +5 -5
  39. langchain_core/version.py +1 -1
  40. {langchain_core-1.0.0a3.dist-info → langchain_core-1.0.0a5.dist-info}/METADATA +8 -8
  41. {langchain_core-1.0.0a3.dist-info → langchain_core-1.0.0a5.dist-info}/RECORD +43 -43
  42. {langchain_core-1.0.0a3.dist-info → langchain_core-1.0.0a5.dist-info}/WHEEL +0 -0
  43. {langchain_core-1.0.0a3.dist-info → langchain_core-1.0.0a5.dist-info}/entry_points.txt +0 -0
@@ -20,6 +20,31 @@ if TYPE_CHECKING:
20
20
  from langchain_core.prompts.chat import ChatPromptTemplate
21
21
 
22
22
 
23
+ def _extract_reasoning_from_additional_kwargs(
24
+ message: BaseMessage,
25
+ ) -> Optional[types.ReasoningContentBlock]:
26
+ """Extract `reasoning_content` from `additional_kwargs`.
27
+
28
+ Handles reasoning content stored in various formats:
29
+ - `additional_kwargs["reasoning_content"]` (string) - Ollama, DeepSeek, XAI, Groq
30
+
31
+ Args:
32
+ message: The message to extract reasoning from.
33
+
34
+ Returns:
35
+ A `ReasoningContentBlock` if reasoning content is found, None otherwise.
36
+ """
37
+ from langchain_core.messages.content import create_reasoning_block # noqa: PLC0415
38
+
39
+ additional_kwargs = getattr(message, "additional_kwargs", {})
40
+
41
+ reasoning_content = additional_kwargs.get("reasoning_content")
42
+ if reasoning_content is not None and isinstance(reasoning_content, str):
43
+ return create_reasoning_block(reasoning=reasoning_content)
44
+
45
+ return None
46
+
47
+
23
48
  class TextAccessor(str):
24
49
  """String-like object that supports both property and method access patterns.
25
50
 
@@ -69,7 +94,7 @@ class TextAccessor(str):
69
94
  class BaseMessage(Serializable):
70
95
  """Base abstract message class.
71
96
 
72
- Messages are the inputs and outputs of ChatModels.
97
+ Messages are the inputs and outputs of ``ChatModel``s.
73
98
  """
74
99
 
75
100
  content: Union[str, list[Union[str, dict]]]
@@ -80,17 +105,18 @@ class BaseMessage(Serializable):
80
105
 
81
106
  For example, for a message from an AI, this could include tool calls as
82
107
  encoded by the model provider.
108
+
83
109
  """
84
110
 
85
111
  response_metadata: dict = Field(default_factory=dict)
86
- """Response metadata. For example: response headers, logprobs, token counts, model
87
- name."""
112
+ """Examples: response headers, logprobs, token counts, model name."""
88
113
 
89
114
  type: str
90
115
  """The type of the message. Must be a string that is unique to the message type.
91
116
 
92
117
  The purpose of this field is to allow for easy identification of the message type
93
118
  when deserializing messages.
119
+
94
120
  """
95
121
 
96
122
  name: Optional[str] = None
@@ -100,11 +126,15 @@ class BaseMessage(Serializable):
100
126
 
101
127
  Usage of this field is optional, and whether it's used or not is up to the
102
128
  model implementation.
129
+
103
130
  """
104
131
 
105
132
  id: Optional[str] = Field(default=None, coerce_numbers_to_str=True)
106
- """An optional unique identifier for the message. This should ideally be
107
- provided by the provider/model which created the message."""
133
+ """An optional unique identifier for the message.
134
+
135
+ This should ideally be provided by the provider/model which created the message.
136
+
137
+ """
108
138
 
109
139
  model_config = ConfigDict(
110
140
  extra="allow",
@@ -131,7 +161,15 @@ class BaseMessage(Serializable):
131
161
  content_blocks: Optional[list[types.ContentBlock]] = None,
132
162
  **kwargs: Any,
133
163
  ) -> None:
134
- """Specify ``content`` as positional arg or ``content_blocks`` for typing."""
164
+ """Initialize ``BaseMessage``.
165
+
166
+ Specify ``content`` as positional arg or ``content_blocks`` for typing.
167
+
168
+ Args:
169
+ content: The string contents of the message.
170
+ content_blocks: Typed standard content.
171
+ kwargs: Additional arguments to pass to the parent class.
172
+ """
135
173
  if content_blocks is not None:
136
174
  super().__init__(content=content_blocks, **kwargs)
137
175
  else:
@@ -139,7 +177,7 @@ class BaseMessage(Serializable):
139
177
 
140
178
  @classmethod
141
179
  def is_lc_serializable(cls) -> bool:
142
- """BaseMessage is serializable.
180
+ """``BaseMessage`` is serializable.
143
181
 
144
182
  Returns:
145
183
  True
@@ -157,33 +195,19 @@ class BaseMessage(Serializable):
157
195
 
158
196
  @property
159
197
  def content_blocks(self) -> list[types.ContentBlock]:
160
- r"""Return ``content`` as a list of standardized :class:`~langchain_core.messages.content.ContentBlock`\s.
161
-
162
- .. important::
163
-
164
- To use this property correctly, the corresponding ``ChatModel`` must support
165
- ``message_version='v1'`` or higher (and it must be set):
166
-
167
- .. code-block:: python
168
-
169
- from langchain.chat_models import init_chat_model
170
- llm = init_chat_model("...", message_version="v1")
171
-
172
- # or
173
-
174
- from langchain-openai import ChatOpenAI
175
- llm = ChatOpenAI(model="gpt-4o", message_version="v1")
176
-
177
- Otherwise, the property will perform best-effort parsing to standard types,
178
- though some content may be misinterpreted.
198
+ r"""Load content blocks from the message content.
179
199
 
180
200
  .. versionadded:: 1.0.0
181
201
 
182
- """ # noqa: E501
202
+ """
203
+ # Needed here to avoid circular import, as these classes import BaseMessages
183
204
  from langchain_core.messages import content as types # noqa: PLC0415
184
205
  from langchain_core.messages.block_translators.anthropic import ( # noqa: PLC0415
185
206
  _convert_to_v1_from_anthropic_input,
186
207
  )
208
+ from langchain_core.messages.block_translators.bedrock_converse import ( # noqa: PLC0415
209
+ _convert_to_v1_from_converse_input,
210
+ )
187
211
  from langchain_core.messages.block_translators.langchain_v0 import ( # noqa: PLC0415
188
212
  _convert_v0_multimodal_input_to_v1,
189
213
  )
@@ -192,28 +216,39 @@ class BaseMessage(Serializable):
192
216
  )
193
217
 
194
218
  blocks: list[types.ContentBlock] = []
195
-
196
- # First pass: convert to standard blocks
197
219
  content = (
220
+ # Transpose string content to list, otherwise assumed to be list
198
221
  [self.content]
199
222
  if isinstance(self.content, str) and self.content
200
223
  else self.content
201
224
  )
202
225
  for item in content:
203
226
  if isinstance(item, str):
227
+ # Plain string content is treated as a text block
204
228
  blocks.append({"type": "text", "text": item})
205
229
  elif isinstance(item, dict):
206
230
  item_type = item.get("type")
207
231
  if item_type not in types.KNOWN_BLOCK_TYPES:
232
+ # Handle all provider-specific or None type blocks as non-standard -
233
+ # we'll come back to these later
208
234
  blocks.append({"type": "non_standard", "value": item})
209
235
  else:
236
+ # Guard against v0 blocks that share the same `type` keys
237
+ if "source_type" in item:
238
+ blocks.append({"type": "non_standard", "value": item})
239
+ continue
240
+
241
+ # This can't be a v0 block (since they require `source_type`),
242
+ # so it's a known v1 block type
210
243
  blocks.append(cast("types.ContentBlock", item))
211
244
 
212
- # Subsequent passes: attempt to unpack non-standard blocks
245
+ # Subsequent passes: attempt to unpack non-standard blocks.
246
+ # The block is left as non-standard if conversion fails.
213
247
  for parsing_step in [
214
248
  _convert_v0_multimodal_input_to_v1,
215
249
  _convert_to_v1_from_chat_completions_input,
216
250
  _convert_to_v1_from_anthropic_input,
251
+ _convert_to_v1_from_converse_input,
217
252
  ]:
218
253
  blocks = parsing_step(blocks)
219
254
  return blocks
@@ -230,6 +265,7 @@ class BaseMessage(Serializable):
230
265
 
231
266
  Returns:
232
267
  The text content of the message.
268
+
233
269
  """
234
270
  if isinstance(self.content, str):
235
271
  text_value = self.content
@@ -273,6 +309,7 @@ class BaseMessage(Serializable):
273
309
 
274
310
  Returns:
275
311
  A pretty representation of the message.
312
+
276
313
  """
277
314
  title = get_msg_title_repr(self.type.title() + " Message", bold=html)
278
315
  # TODO: handle non-string content.
@@ -292,11 +329,12 @@ def merge_content(
292
329
  """Merge multiple message contents.
293
330
 
294
331
  Args:
295
- first_content: The first content. Can be a string or a list.
296
- contents: The other contents. Can be a string or a list.
332
+ first_content: The first ``content``. Can be a string or a list.
333
+ contents: The other ``content``s. Can be a string or a list.
297
334
 
298
335
  Returns:
299
336
  The merged content.
337
+
300
338
  """
301
339
  merged: Union[str, list[Union[str, dict]]]
302
340
  merged = "" if first_content is None else first_content
@@ -348,9 +386,10 @@ class BaseMessageChunk(BaseMessage):
348
386
 
349
387
  For example,
350
388
 
351
- `AIMessageChunk(content="Hello") + AIMessageChunk(content=" World")`
389
+ ``AIMessageChunk(content="Hello") + AIMessageChunk(content=" World")``
390
+
391
+ will give ``AIMessageChunk(content="Hello World")``
352
392
 
353
- will give `AIMessageChunk(content="Hello World")`
354
393
  """
355
394
  if isinstance(other, BaseMessageChunk):
356
395
  # If both are (subclasses of) BaseMessageChunk,
@@ -398,8 +437,9 @@ def message_to_dict(message: BaseMessage) -> dict:
398
437
  message: Message to convert.
399
438
 
400
439
  Returns:
401
- Message as a dict. The dict will have a "type" key with the message type
402
- and a "data" key with the message data as a dict.
440
+ Message as a dict. The dict will have a ``type`` key with the message type
441
+ and a ``data`` key with the message data as a dict.
442
+
403
443
  """
404
444
  return {"type": message.type, "data": message.model_dump()}
405
445
 
@@ -408,10 +448,11 @@ def messages_to_dict(messages: Sequence[BaseMessage]) -> list[dict]:
408
448
  """Convert a sequence of Messages to a list of dictionaries.
409
449
 
410
450
  Args:
411
- messages: Sequence of messages (as BaseMessages) to convert.
451
+ messages: Sequence of messages (as ``BaseMessage``s) to convert.
412
452
 
413
453
  Returns:
414
454
  List of messages as dicts.
455
+
415
456
  """
416
457
  return [message_to_dict(m) for m in messages]
417
458
 
@@ -425,6 +466,7 @@ def get_msg_title_repr(title: str, *, bold: bool = False) -> str:
425
466
 
426
467
  Returns:
427
468
  The title representation.
469
+
428
470
  """
429
471
  padded = " " + title + " "
430
472
  sep_len = (80 - len(padded)) // 2
@@ -1,4 +1,14 @@
1
- """Derivations of standard content blocks from provider content."""
1
+ """Derivations of standard content blocks from provider content.
2
+
3
+ ``AIMessage`` will first attempt to use a provider-specific translator if
4
+ ``model_provider`` is set in ``response_metadata`` on the message. Consequently, each
5
+ provider translator must handle all possible content response types from the provider,
6
+ including text.
7
+
8
+ If no provider is set, or if the provider does not have a registered translator,
9
+ ``AIMessage`` will fall back to best-effort parsing of the content into blocks using
10
+ the implementation in ``BaseMessage``.
11
+ """
2
12
 
3
13
  from __future__ import annotations
4
14
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  import json
4
4
  from collections.abc import Iterable
5
- from typing import Any, Optional, cast
5
+ from typing import Any, Optional, Union, cast
6
6
 
7
7
  from langchain_core.messages import AIMessage, AIMessageChunk
8
8
  from langchain_core.messages import content as types
@@ -17,7 +17,7 @@ def _populate_extras(
17
17
 
18
18
  for key, value in block.items():
19
19
  if key not in known_fields:
20
- if "extras" not in block:
20
+ if "extras" not in standard_block:
21
21
  # Below type-ignores are because mypy thinks a non-standard block can
22
22
  # get here, although we exclude them above.
23
23
  standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
@@ -29,7 +29,21 @@ def _populate_extras(
29
29
  def _convert_to_v1_from_anthropic_input(
30
30
  content: list[types.ContentBlock],
31
31
  ) -> list[types.ContentBlock]:
32
- """Attempt to unpack non-standard blocks."""
32
+ """Convert Anthropic format blocks to v1 format.
33
+
34
+ During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1
35
+ block as a ``'non_standard'`` block with the original block stored in the ``value``
36
+ field. This function attempts to unpack those blocks and convert any blocks that
37
+ might be Anthropic format to v1 ContentBlocks.
38
+
39
+ If conversion fails, the block is left as a ``'non_standard'`` block.
40
+
41
+ Args:
42
+ content: List of content blocks to process.
43
+
44
+ Returns:
45
+ Updated list with Anthropic blocks converted to v1 format.
46
+ """
33
47
 
34
48
  def _iter_blocks() -> Iterable[types.ContentBlock]:
35
49
  blocks: list[dict[str, Any]] = [
@@ -186,10 +200,12 @@ def _convert_citation_to_v1(citation: dict[str, Any]) -> types.Annotation:
186
200
  def _convert_to_v1_from_anthropic(message: AIMessage) -> list[types.ContentBlock]:
187
201
  """Convert Anthropic message content to v1 format."""
188
202
  if isinstance(message.content, str):
189
- message.content = [{"type": "text", "text": message.content}]
203
+ content: list[Union[str, dict]] = [{"type": "text", "text": message.content}]
204
+ else:
205
+ content = message.content
190
206
 
191
207
  def _iter_blocks() -> Iterable[types.ContentBlock]:
192
- for block in message.content:
208
+ for block in content:
193
209
  if not isinstance(block, dict):
194
210
  continue
195
211
  block_type = block.get("type")
@@ -268,159 +284,160 @@ def _convert_to_v1_from_anthropic(message: AIMessage) -> list[types.ContentBlock
268
284
  tool_call_block["index"] = block["index"]
269
285
  yield tool_call_block
270
286
 
271
- elif (
272
- block_type == "input_json_delta"
273
- and isinstance(message, AIMessageChunk)
274
- and len(message.tool_call_chunks) == 1
287
+ elif block_type == "input_json_delta" and isinstance(
288
+ message, AIMessageChunk
275
289
  ):
276
- tool_call_chunk = (
277
- message.tool_call_chunks[0].copy() # type: ignore[assignment]
278
- )
279
- if "type" not in tool_call_chunk:
280
- tool_call_chunk["type"] = "tool_call_chunk"
281
- yield tool_call_chunk
290
+ if len(message.tool_call_chunks) == 1:
291
+ tool_call_chunk = (
292
+ message.tool_call_chunks[0].copy() # type: ignore[assignment]
293
+ )
294
+ if "type" not in tool_call_chunk:
295
+ tool_call_chunk["type"] = "tool_call_chunk"
296
+ yield tool_call_chunk
282
297
 
283
- elif block_type == "server_tool_use":
284
- if block.get("name") == "web_search":
285
- web_search_call: types.WebSearchCall = {"type": "web_search_call"}
298
+ else:
299
+ server_tool_call_chunk: types.ServerToolCallChunk = {
300
+ "type": "server_tool_call_chunk",
301
+ "args": block.get("partial_json", ""),
302
+ }
303
+ if "index" in block:
304
+ server_tool_call_chunk["index"] = block["index"]
305
+ yield server_tool_call_chunk
286
306
 
287
- if query := block.get("input", {}).get("query"):
288
- web_search_call["query"] = query
307
+ elif block_type == "server_tool_use":
308
+ if block.get("name") == "code_execution":
309
+ server_tool_use_name = "code_interpreter"
310
+ else:
311
+ server_tool_use_name = block.get("name", "")
312
+ if (
313
+ isinstance(message, AIMessageChunk)
314
+ and block.get("input") == {}
315
+ and "partial_json" not in block
316
+ and message.chunk_position != "last"
317
+ ):
318
+ # First chunk in a stream
319
+ server_tool_call_chunk = {
320
+ "type": "server_tool_call_chunk",
321
+ "name": server_tool_use_name,
322
+ "args": "",
323
+ "id": block.get("id", ""),
324
+ }
325
+ if "index" in block:
326
+ server_tool_call_chunk["index"] = block["index"]
327
+ known_fields = {"type", "name", "input", "id", "index"}
328
+ _populate_extras(server_tool_call_chunk, block, known_fields)
329
+ yield server_tool_call_chunk
330
+ else:
331
+ server_tool_call: types.ServerToolCall = {
332
+ "type": "server_tool_call",
333
+ "name": server_tool_use_name,
334
+ "args": block.get("input", {}),
335
+ "id": block.get("id", ""),
336
+ }
289
337
 
290
- elif block.get("input") == {} and "partial_json" in block:
338
+ if block.get("input") == {} and "partial_json" in block:
291
339
  try:
292
340
  input_ = json.loads(block["partial_json"])
293
- if isinstance(input_, dict) and "query" in input_:
294
- web_search_call["query"] = input_["query"]
341
+ if isinstance(input_, dict):
342
+ server_tool_call["args"] = input_
295
343
  except json.JSONDecodeError:
296
344
  pass
297
345
 
298
- if "id" in block:
299
- web_search_call["id"] = block["id"]
300
346
  if "index" in block:
301
- web_search_call["index"] = block["index"]
302
- known_fields = {"type", "name", "input", "id", "index"}
303
- for key, value in block.items():
304
- if key not in known_fields:
305
- if "extras" not in web_search_call:
306
- web_search_call["extras"] = {}
307
- web_search_call["extras"][key] = value
308
- yield web_search_call
309
-
310
- elif block.get("name") == "code_execution":
311
- code_interpreter_call: types.CodeInterpreterCall = {
312
- "type": "code_interpreter_call"
347
+ server_tool_call["index"] = block["index"]
348
+ known_fields = {
349
+ "type",
350
+ "name",
351
+ "input",
352
+ "partial_json",
353
+ "id",
354
+ "index",
313
355
  }
356
+ _populate_extras(server_tool_call, block, known_fields)
314
357
 
315
- if code := block.get("input", {}).get("code"):
316
- code_interpreter_call["code"] = code
358
+ yield server_tool_call
359
+
360
+ elif block_type == "mcp_tool_use":
361
+ if (
362
+ isinstance(message, AIMessageChunk)
363
+ and block.get("input") == {}
364
+ and "partial_json" not in block
365
+ and message.chunk_position != "last"
366
+ ):
367
+ # First chunk in a stream
368
+ server_tool_call_chunk = {
369
+ "type": "server_tool_call_chunk",
370
+ "name": "remote_mcp",
371
+ "args": "",
372
+ "id": block.get("id", ""),
373
+ }
374
+ if "name" in block:
375
+ server_tool_call_chunk["extras"] = {"tool_name": block["name"]}
376
+ known_fields = {"type", "name", "input", "id", "index"}
377
+ _populate_extras(server_tool_call_chunk, block, known_fields)
378
+ if "index" in block:
379
+ server_tool_call_chunk["index"] = block["index"]
380
+ yield server_tool_call_chunk
381
+ else:
382
+ server_tool_call = {
383
+ "type": "server_tool_call",
384
+ "name": "remote_mcp",
385
+ "args": block.get("input", {}),
386
+ "id": block.get("id", ""),
387
+ }
317
388
 
318
- elif block.get("input") == {} and "partial_json" in block:
389
+ if block.get("input") == {} and "partial_json" in block:
319
390
  try:
320
391
  input_ = json.loads(block["partial_json"])
321
- if isinstance(input_, dict) and "code" in input_:
322
- code_interpreter_call["code"] = input_["code"]
392
+ if isinstance(input_, dict):
393
+ server_tool_call["args"] = input_
323
394
  except json.JSONDecodeError:
324
395
  pass
325
396
 
326
- if "id" in block:
327
- code_interpreter_call["id"] = block["id"]
397
+ if "name" in block:
398
+ server_tool_call["extras"] = {"tool_name": block["name"]}
399
+ known_fields = {
400
+ "type",
401
+ "name",
402
+ "input",
403
+ "partial_json",
404
+ "id",
405
+ "index",
406
+ }
407
+ _populate_extras(server_tool_call, block, known_fields)
328
408
  if "index" in block:
329
- code_interpreter_call["index"] = block["index"]
330
- known_fields = {"type", "name", "input", "id", "index"}
331
- for key, value in block.items():
332
- if key not in known_fields:
333
- if "extras" not in code_interpreter_call:
334
- code_interpreter_call["extras"] = {}
335
- code_interpreter_call["extras"][key] = value
336
- yield code_interpreter_call
409
+ server_tool_call["index"] = block["index"]
337
410
 
338
- else:
339
- new_block: types.NonStandardContentBlock = {
340
- "type": "non_standard",
341
- "value": block,
342
- }
343
- if "index" in new_block["value"]:
344
- new_block["index"] = new_block["value"].pop("index")
345
- yield new_block
346
-
347
- elif block_type == "web_search_tool_result":
348
- web_search_result: types.WebSearchResult = {"type": "web_search_result"}
349
- if "tool_use_id" in block:
350
- web_search_result["id"] = block["tool_use_id"]
351
- if "index" in block:
352
- web_search_result["index"] = block["index"]
353
-
354
- if web_search_result_content := block.get("content", []):
355
- if "extras" not in web_search_result:
356
- web_search_result["extras"] = {}
357
- urls = []
358
- extra_content = []
359
- for result_content in web_search_result_content:
360
- if isinstance(result_content, dict):
361
- if "url" in result_content:
362
- urls.append(result_content["url"])
363
- extra_content.append(result_content)
364
- web_search_result["extras"]["content"] = extra_content
365
- if urls:
366
- web_search_result["urls"] = urls
367
- yield web_search_result
368
-
369
- elif block_type == "code_execution_tool_result":
370
- code_interpreter_result: types.CodeInterpreterResult = {
371
- "type": "code_interpreter_result",
372
- "output": [],
373
- }
374
- if "tool_use_id" in block:
375
- code_interpreter_result["id"] = block["tool_use_id"]
376
- if "index" in block:
377
- code_interpreter_result["index"] = block["index"]
411
+ yield server_tool_call
378
412
 
379
- code_interpreter_output: types.CodeInterpreterOutput = {
380
- "type": "code_interpreter_output"
413
+ elif block_type and block_type.endswith("_tool_result"):
414
+ server_tool_result: types.ServerToolResult = {
415
+ "type": "server_tool_result",
416
+ "tool_call_id": block.get("tool_use_id", ""),
417
+ "status": "success",
418
+ "extras": {"block_type": block_type},
381
419
  }
420
+ if output := block.get("content", []):
421
+ server_tool_result["output"] = output
422
+ if isinstance(output, dict) and output.get(
423
+ "error_code" # web_search, code_interpreter
424
+ ):
425
+ server_tool_result["status"] = "error"
426
+ if block.get("is_error"): # mcp_tool_result
427
+ server_tool_result["status"] = "error"
428
+ if "index" in block:
429
+ server_tool_result["index"] = block["index"]
382
430
 
383
- code_execution_content = block.get("content", {})
384
- if code_execution_content.get("type") == "code_execution_result":
385
- if "return_code" in code_execution_content:
386
- code_interpreter_output["return_code"] = code_execution_content[
387
- "return_code"
388
- ]
389
- if "stdout" in code_execution_content:
390
- code_interpreter_output["stdout"] = code_execution_content[
391
- "stdout"
392
- ]
393
- if stderr := code_execution_content.get("stderr"):
394
- code_interpreter_output["stderr"] = stderr
395
- if (
396
- output := code_interpreter_output.get("content")
397
- ) and isinstance(output, list):
398
- if "extras" not in code_interpreter_result:
399
- code_interpreter_result["extras"] = {}
400
- code_interpreter_result["extras"]["content"] = output
401
- for output_block in output:
402
- if "file_id" in output_block:
403
- if "file_ids" not in code_interpreter_output:
404
- code_interpreter_output["file_ids"] = []
405
- code_interpreter_output["file_ids"].append(
406
- output_block["file_id"]
407
- )
408
- code_interpreter_result["output"].append(code_interpreter_output)
409
-
410
- elif (
411
- code_execution_content.get("type")
412
- == "code_execution_tool_result_error"
413
- ):
414
- if "extras" not in code_interpreter_result:
415
- code_interpreter_result["extras"] = {}
416
- code_interpreter_result["extras"]["error_code"] = (
417
- code_execution_content.get("error_code")
418
- )
431
+ known_fields = {"type", "tool_use_id", "content", "is_error", "index"}
432
+ _populate_extras(server_tool_result, block, known_fields)
419
433
 
420
- yield code_interpreter_result
434
+ yield server_tool_result
421
435
 
422
436
  else:
423
- new_block = {"type": "non_standard", "value": block}
437
+ new_block: types.NonStandardContentBlock = {
438
+ "type": "non_standard",
439
+ "value": block,
440
+ }
424
441
  if "index" in new_block["value"]:
425
442
  new_block["index"] = new_block["value"].pop("index")
426
443
  yield new_block
@@ -429,12 +446,12 @@ def _convert_to_v1_from_anthropic(message: AIMessage) -> list[types.ContentBlock
429
446
 
430
447
 
431
448
  def translate_content(message: AIMessage) -> list[types.ContentBlock]:
432
- """Derive standard content blocks from a message with OpenAI content."""
449
+ """Derive standard content blocks from a message with Anthropic content."""
433
450
  return _convert_to_v1_from_anthropic(message)
434
451
 
435
452
 
436
453
  def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
437
- """Derive standard content blocks from a message chunk with OpenAI content."""
454
+ """Derive standard content blocks from a message chunk with Anthropic content."""
438
455
  return _convert_to_v1_from_anthropic(message)
439
456
 
440
457