@langchain/anthropic 1.5.1 → 1.5.3

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 (130) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/chat_models.cjs +32 -3
  3. package/dist/chat_models.cjs.map +1 -1
  4. package/dist/chat_models.d.cts +6 -4
  5. package/dist/chat_models.d.cts.map +1 -1
  6. package/dist/chat_models.d.ts +5 -3
  7. package/dist/chat_models.d.ts.map +1 -1
  8. package/dist/chat_models.js +32 -2
  9. package/dist/chat_models.js.map +1 -1
  10. package/dist/index.d.cts +1 -1
  11. package/dist/index.d.ts +1 -1
  12. package/dist/output_parsers.cjs +0 -1
  13. package/dist/output_parsers.cjs.map +1 -1
  14. package/dist/output_parsers.js.map +1 -1
  15. package/dist/profiles.cjs +28 -164
  16. package/dist/profiles.cjs.map +1 -1
  17. package/dist/profiles.js +28 -164
  18. package/dist/profiles.js.map +1 -1
  19. package/dist/tools/bash.cjs +0 -1
  20. package/dist/tools/bash.cjs.map +1 -1
  21. package/dist/tools/bash.d.cts +0 -1
  22. package/dist/tools/bash.d.cts.map +1 -1
  23. package/dist/tools/bash.d.ts +0 -1
  24. package/dist/tools/bash.d.ts.map +1 -1
  25. package/dist/tools/bash.js.map +1 -1
  26. package/dist/tools/codeExecution.cjs.map +1 -1
  27. package/dist/tools/codeExecution.d.cts +0 -1
  28. package/dist/tools/codeExecution.d.cts.map +1 -1
  29. package/dist/tools/codeExecution.d.ts +0 -1
  30. package/dist/tools/codeExecution.d.ts.map +1 -1
  31. package/dist/tools/codeExecution.js.map +1 -1
  32. package/dist/tools/computer.cjs +0 -1
  33. package/dist/tools/computer.cjs.map +1 -1
  34. package/dist/tools/computer.d.cts +0 -1
  35. package/dist/tools/computer.d.cts.map +1 -1
  36. package/dist/tools/computer.d.ts +0 -1
  37. package/dist/tools/computer.d.ts.map +1 -1
  38. package/dist/tools/computer.js.map +1 -1
  39. package/dist/tools/index.cjs.map +1 -1
  40. package/dist/tools/index.d.cts +1 -2
  41. package/dist/tools/index.d.cts.map +1 -1
  42. package/dist/tools/index.d.ts +1 -2
  43. package/dist/tools/index.d.ts.map +1 -1
  44. package/dist/tools/index.js.map +1 -1
  45. package/dist/tools/mcpToolset.cjs.map +1 -1
  46. package/dist/tools/mcpToolset.d.cts +1 -2
  47. package/dist/tools/mcpToolset.d.cts.map +1 -1
  48. package/dist/tools/mcpToolset.d.ts +1 -2
  49. package/dist/tools/mcpToolset.d.ts.map +1 -1
  50. package/dist/tools/mcpToolset.js.map +1 -1
  51. package/dist/tools/memory.cjs +0 -1
  52. package/dist/tools/memory.cjs.map +1 -1
  53. package/dist/tools/memory.d.cts +0 -1
  54. package/dist/tools/memory.d.cts.map +1 -1
  55. package/dist/tools/memory.d.ts +0 -1
  56. package/dist/tools/memory.d.ts.map +1 -1
  57. package/dist/tools/memory.js.map +1 -1
  58. package/dist/tools/textEditor.cjs +0 -1
  59. package/dist/tools/textEditor.cjs.map +1 -1
  60. package/dist/tools/textEditor.d.cts +0 -1
  61. package/dist/tools/textEditor.d.cts.map +1 -1
  62. package/dist/tools/textEditor.d.ts +0 -1
  63. package/dist/tools/textEditor.d.ts.map +1 -1
  64. package/dist/tools/textEditor.js.map +1 -1
  65. package/dist/tools/toolSearch.cjs.map +1 -1
  66. package/dist/tools/toolSearch.d.cts +0 -1
  67. package/dist/tools/toolSearch.d.cts.map +1 -1
  68. package/dist/tools/toolSearch.d.ts +0 -1
  69. package/dist/tools/toolSearch.d.ts.map +1 -1
  70. package/dist/tools/toolSearch.js.map +1 -1
  71. package/dist/tools/types.cjs +28 -1
  72. package/dist/tools/types.cjs.map +1 -1
  73. package/dist/tools/types.d.cts +0 -1
  74. package/dist/tools/types.d.cts.map +1 -1
  75. package/dist/tools/types.d.ts +0 -1
  76. package/dist/tools/types.d.ts.map +1 -1
  77. package/dist/tools/types.js +1 -1
  78. package/dist/tools/types.js.map +1 -1
  79. package/dist/tools/webFetch.cjs.map +1 -1
  80. package/dist/tools/webFetch.d.cts +0 -1
  81. package/dist/tools/webFetch.d.cts.map +1 -1
  82. package/dist/tools/webFetch.d.ts +0 -1
  83. package/dist/tools/webFetch.d.ts.map +1 -1
  84. package/dist/tools/webFetch.js.map +1 -1
  85. package/dist/tools/webSearch.cjs.map +1 -1
  86. package/dist/tools/webSearch.d.cts +0 -1
  87. package/dist/tools/webSearch.d.cts.map +1 -1
  88. package/dist/tools/webSearch.d.ts +0 -1
  89. package/dist/tools/webSearch.d.ts.map +1 -1
  90. package/dist/tools/webSearch.js.map +1 -1
  91. package/dist/types.d.cts +1 -2
  92. package/dist/types.d.cts.map +1 -1
  93. package/dist/types.d.ts +1 -2
  94. package/dist/types.d.ts.map +1 -1
  95. package/dist/utils/content.cjs +0 -1
  96. package/dist/utils/content.cjs.map +1 -1
  97. package/dist/utils/content.js.map +1 -1
  98. package/dist/utils/errors.cjs +1 -1
  99. package/dist/utils/errors.cjs.map +1 -1
  100. package/dist/utils/errors.js +1 -1
  101. package/dist/utils/errors.js.map +1 -1
  102. package/dist/utils/index.cjs.map +1 -1
  103. package/dist/utils/index.js.map +1 -1
  104. package/dist/utils/message_inputs.cjs +1 -1
  105. package/dist/utils/message_inputs.cjs.map +1 -1
  106. package/dist/utils/message_inputs.js +1 -1
  107. package/dist/utils/message_inputs.js.map +1 -1
  108. package/dist/utils/message_outputs.cjs +5 -2
  109. package/dist/utils/message_outputs.cjs.map +1 -1
  110. package/dist/utils/message_outputs.js +5 -1
  111. package/dist/utils/message_outputs.js.map +1 -1
  112. package/dist/utils/params.cjs +5 -1
  113. package/dist/utils/params.cjs.map +1 -1
  114. package/dist/utils/params.js +4 -2
  115. package/dist/utils/params.js.map +1 -1
  116. package/dist/utils/prompts.cjs.map +1 -1
  117. package/dist/utils/prompts.d.cts +0 -1
  118. package/dist/utils/prompts.d.cts.map +1 -1
  119. package/dist/utils/prompts.d.ts +0 -1
  120. package/dist/utils/prompts.d.ts.map +1 -1
  121. package/dist/utils/prompts.js.map +1 -1
  122. package/dist/utils/standard.cjs +2 -2
  123. package/dist/utils/standard.cjs.map +1 -1
  124. package/dist/utils/standard.js +2 -2
  125. package/dist/utils/standard.js.map +1 -1
  126. package/dist/utils/stream_events.cjs.map +1 -1
  127. package/dist/utils/stream_events.js.map +1 -1
  128. package/dist/utils/tools.cjs.map +1 -1
  129. package/dist/utils/tools.js.map +1 -1
  130. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"standard.cjs","names":["iife"],"sources":["../../src/utils/standard.ts"],"sourcesContent":["import type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n BaseMessage,\n ContentBlock,\n ResponseMetadata,\n} from \"@langchain/core/messages\";\nimport { iife } from \"./index.js\";\n\nfunction _isStandardAnnotation(\n annotation: unknown\n): annotation is ContentBlock.Citation {\n return (\n typeof annotation === \"object\" &&\n annotation !== null &&\n \"type\" in annotation &&\n annotation.type === \"citation\"\n );\n}\n\nfunction _formatStandardCitations(\n annotations: ContentBlock.Citation[]\n): Anthropic.Beta.BetaTextCitation[] {\n function* iterateAnnotations() {\n for (const annotation of annotations) {\n if (_isStandardAnnotation(annotation)) {\n if (annotation.source === \"char\") {\n yield {\n type: \"char_location\" as const,\n file_id: annotation.url ?? \"\",\n start_char_index: annotation.startIndex ?? 0,\n end_char_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"page\") {\n yield {\n type: \"page_location\" as const,\n file_id: annotation.url ?? \"\",\n start_page_number: annotation.startIndex ?? 0,\n end_page_number: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"block\") {\n yield {\n type: \"content_block_location\" as const,\n file_id: annotation.url ?? \"\",\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"url\") {\n yield {\n type: \"web_search_result_location\" as const,\n url: annotation.url ?? \"\",\n title: annotation.title ?? null,\n encrypted_index: String(annotation.startIndex ?? 0),\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"search\") {\n yield {\n type: \"search_result_location\" as const,\n title: annotation.title ?? null,\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n search_result_index: 0,\n source: annotation.source ?? \"\",\n cited_text: annotation.citedText ?? \"\",\n };\n }\n }\n }\n }\n return Array.from(iterateAnnotations());\n}\n\nfunction _formatBase64Data(data: string | Uint8Array): string {\n if (typeof data === \"string\") return data;\n else return _encodeUint8Array(data);\n}\n\nfunction _encodeUint8Array(data: Uint8Array): string {\n const output = [];\n for (let i = 0, { length } = data; i < length; i++) {\n output.push(String.fromCharCode(data[i]));\n }\n return btoa(output.join(\"\"));\n}\n\nfunction _normalizeMimeType(mimeType?: string | null): string {\n return (mimeType ?? \"\").split(\";\")[0].toLowerCase();\n}\n\nfunction _extractMetadataValue<T>(\n metadata: unknown,\n key: string\n): T | undefined {\n if (\n metadata !== undefined &&\n metadata !== null &&\n typeof metadata === \"object\" &&\n key in metadata\n ) {\n return (metadata as Record<string, unknown>)[key] as T;\n }\n return undefined;\n}\n\nfunction _applyDocumentMetadata(\n block: Anthropic.Beta.BetaRequestDocumentBlock,\n metadata: unknown\n): Anthropic.Beta.BetaRequestDocumentBlock {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n const citations =\n _extractMetadataValue<Anthropic.Beta.BetaCitationsConfigParam | null>(\n metadata,\n \"citations\"\n );\n if (citations !== undefined) {\n block.citations = citations;\n }\n const context = _extractMetadataValue<string | null>(metadata, \"context\");\n if (context !== undefined) {\n block.context = context;\n }\n const title = _extractMetadataValue<string | null>(metadata, \"title\");\n if (title !== undefined) {\n block.title = title;\n }\n return block;\n}\n\nfunction _applyImageMetadata(\n block: Anthropic.Beta.BetaImageBlockParam,\n metadata: unknown\n): Anthropic.Beta.BetaImageBlockParam {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n return block;\n}\n\nfunction _hasAllowedImageMimeType(\n mimeType: string\n): mimeType is \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\" {\n const ALLOWED_IMAGE_MIME_TYPES = new Set([\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n ]);\n return ALLOWED_IMAGE_MIME_TYPES.has(mimeType);\n}\n\nexport function _formatStandardContent(\n message: BaseMessage\n): Anthropic.Beta.BetaContentBlockParam[] {\n const result: Anthropic.Beta.BetaContentBlockParam[] = [];\n const responseMetadata = message.response_metadata as ResponseMetadata;\n const isAnthropicMessage =\n \"model_provider\" in responseMetadata &&\n responseMetadata?.model_provider === \"anthropic\";\n for (const block of message.contentBlocks) {\n if (block.type === \"text\") {\n if (block.annotations) {\n result.push({\n type: \"text\",\n text: block.text,\n citations: _formatStandardCitations(\n block.annotations as ContentBlock.Citation[]\n ),\n });\n } else {\n result.push({\n type: \"text\",\n text: block.text,\n });\n }\n } else if (block.type === \"tool_call\") {\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name,\n input: block.args,\n });\n } else if (block.type === \"tool_call_chunk\") {\n const input = iife(() => {\n if (typeof block.args !== \"string\") {\n return block.args;\n }\n try {\n return JSON.parse(block.args);\n } catch {\n return {};\n }\n });\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name ?? \"\",\n input,\n });\n } else if (block.type === \"reasoning\" && isAnthropicMessage) {\n result.push({\n type: \"thinking\",\n thinking: block.reasoning,\n signature: String(block.signature),\n });\n } else if (block.type === \"server_tool_call\" && isAnthropicMessage) {\n if (block.name === \"web_search\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n }\n } else if (block.type === \"server_tool_call_result\" && isAnthropicMessage) {\n if (block.name === \"web_search\" && Array.isArray(block.output.urls)) {\n const content = block.output.urls.map((url) => ({\n type: \"web_search_result\" as const,\n title: \"\",\n encrypted_content: \"\",\n url,\n }));\n result.push({\n type: \"web_search_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n content,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"code_execution_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n } else if (block.name === \"mcp_tool_result\") {\n result.push({\n type: \"mcp_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n }\n } else if (block.type === \"audio\") {\n throw new Error(\"Anthropic does not support audio content blocks.\");\n } else if (block.type === \"file\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"application/pdf\" || mimeType === \"\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"\" || mimeType === \"application/pdf\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: \"application/pdf\",\n },\n },\n metadata\n )\n );\n } else if (mimeType === \"text/plain\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n metadata\n )\n );\n } else {\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"content\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n ],\n },\n },\n metadata\n )\n );\n } else {\n throw new Error(\n `Unsupported file mime type for Anthropic base64 source: ${mimeType}`\n );\n }\n }\n continue;\n }\n throw new Error(\n \"File content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"image\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType) || \"image/png\";\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n metadata\n )\n );\n }\n continue;\n }\n throw new Error(\n \"Image content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"video\") {\n // no-op\n } else if (block.type === \"text-plain\") {\n if (block.data) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n block.metadata\n )\n );\n }\n } else if (block.type === \"non_standard\" && isAnthropicMessage) {\n result.push(block.value as Anthropic.Beta.BetaContentBlockParam);\n }\n }\n return result;\n}\n"],"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C,MAAM,WAAW,MAAM;AACvB,MAAI,MAAM,QAAQ;AAChB,UAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,SAAS,MAAM;KAChB;IACF,EACD,SACD,CACF;AACD;;AAEF,MAAI,MAAM,KAAK;AACb,UAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,KAAK,MAAM;KACZ;IACF,EACD,SACD,CACF;AACD;;AAEF,MAAI,MAAM,MAAM;GACd,MAAM,WAAW,mBAAmB,MAAM,SAAS,IAAI;AACvD,OAAI,yBAAyB,SAAS,CACpC,QAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,MAAM,kBAAkB,MAAM,KAAK;KACnC,YAAY;KACb;IACF,EACD,SACD,CACF;AAEH;;AAEF,QAAM,IAAI,MACR,oEACD;YACQ,MAAM,SAAS,SAAS,YAExB,MAAM,SAAS;MACpB,MAAM,KACR,QAAO,KACL,uBACE;GACE,MAAM;GACN,QAAQ;IACN,MAAM;IACN,MAAM,kBAAkB,MAAM,KAAK;IACnC,YAAY;IACb;GACF,EACD,MAAM,SACP,CACF;YAEM,MAAM,SAAS,kBAAkB,mBAC1C,QAAO,KAAK,MAAM,MAA8C;AAGpE,QAAO"}
1
+ {"version":3,"file":"standard.cjs","names":["iife"],"sources":["../../src/utils/standard.ts"],"sourcesContent":["import type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n BaseMessage,\n ContentBlock,\n ResponseMetadata,\n} from \"@langchain/core/messages\";\nimport { iife } from \"./index.js\";\n\nfunction _isStandardAnnotation(\n annotation: unknown\n): annotation is ContentBlock.Citation {\n return (\n typeof annotation === \"object\" &&\n annotation !== null &&\n \"type\" in annotation &&\n annotation.type === \"citation\"\n );\n}\n\nfunction _formatStandardCitations(\n annotations: ContentBlock.Citation[]\n): Anthropic.Beta.BetaTextCitation[] {\n function* iterateAnnotations() {\n for (const annotation of annotations) {\n if (_isStandardAnnotation(annotation)) {\n if (annotation.source === \"char\") {\n yield {\n type: \"char_location\" as const,\n file_id: annotation.url ?? \"\",\n start_char_index: annotation.startIndex ?? 0,\n end_char_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"page\") {\n yield {\n type: \"page_location\" as const,\n file_id: annotation.url ?? \"\",\n start_page_number: annotation.startIndex ?? 0,\n end_page_number: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"block\") {\n yield {\n type: \"content_block_location\" as const,\n file_id: annotation.url ?? \"\",\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"url\") {\n yield {\n type: \"web_search_result_location\" as const,\n url: annotation.url ?? \"\",\n title: annotation.title ?? null,\n encrypted_index: String(annotation.startIndex ?? 0),\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"search\") {\n yield {\n type: \"search_result_location\" as const,\n title: annotation.title ?? null,\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n search_result_index: 0,\n source: annotation.source ?? \"\",\n cited_text: annotation.citedText ?? \"\",\n };\n }\n }\n }\n }\n return Array.from(iterateAnnotations());\n}\n\nfunction _formatBase64Data(data: string | Uint8Array): string {\n if (typeof data === \"string\") return data;\n else return _encodeUint8Array(data);\n}\n\nfunction _encodeUint8Array(data: Uint8Array): string {\n const output = [];\n for (let i = 0, { length } = data; i < length; i++) {\n output.push(String.fromCharCode(data[i]));\n }\n return btoa(output.join(\"\"));\n}\n\nfunction _normalizeMimeType(mimeType?: string | null): string {\n return (mimeType ?? \"\").split(\";\")[0].toLowerCase();\n}\n\nfunction _extractMetadataValue<T>(\n metadata: unknown,\n key: string\n): T | undefined {\n if (\n metadata !== undefined &&\n metadata !== null &&\n typeof metadata === \"object\" &&\n key in metadata\n ) {\n return (metadata as Record<string, unknown>)[key] as T;\n }\n return undefined;\n}\n\nfunction _applyDocumentMetadata(\n block: Anthropic.Beta.BetaRequestDocumentBlock,\n metadata: unknown\n): Anthropic.Beta.BetaRequestDocumentBlock {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n const citations =\n _extractMetadataValue<Anthropic.Beta.BetaCitationsConfigParam | null>(\n metadata,\n \"citations\"\n );\n if (citations !== undefined) {\n block.citations = citations;\n }\n const context = _extractMetadataValue<string | null>(metadata, \"context\");\n if (context !== undefined) {\n block.context = context;\n }\n const title = _extractMetadataValue<string | null>(metadata, \"title\");\n if (title !== undefined) {\n block.title = title;\n }\n return block;\n}\n\nfunction _applyImageMetadata(\n block: Anthropic.Beta.BetaImageBlockParam,\n metadata: unknown\n): Anthropic.Beta.BetaImageBlockParam {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n return block;\n}\n\nfunction _hasAllowedImageMimeType(\n mimeType: string\n): mimeType is \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\" {\n const ALLOWED_IMAGE_MIME_TYPES = new Set([\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n ]);\n return ALLOWED_IMAGE_MIME_TYPES.has(mimeType);\n}\n\nexport function _formatStandardContent(\n message: BaseMessage\n): Anthropic.Beta.BetaContentBlockParam[] {\n const result: Anthropic.Beta.BetaContentBlockParam[] = [];\n const responseMetadata = message.response_metadata as ResponseMetadata;\n const isAnthropicMessage =\n \"model_provider\" in responseMetadata &&\n responseMetadata?.model_provider === \"anthropic\";\n for (const block of message.contentBlocks) {\n if (block.type === \"text\") {\n if (block.annotations) {\n result.push({\n type: \"text\",\n text: block.text,\n citations: _formatStandardCitations(\n block.annotations as ContentBlock.Citation[]\n ),\n });\n } else {\n result.push({\n type: \"text\",\n text: block.text,\n });\n }\n } else if (block.type === \"tool_call\") {\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name,\n input: block.args,\n });\n } else if (block.type === \"tool_call_chunk\") {\n const input = iife(() => {\n if (typeof block.args !== \"string\") {\n return block.args;\n }\n try {\n return JSON.parse(block.args);\n } catch {\n return {};\n }\n });\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name ?? \"\",\n input,\n });\n } else if (block.type === \"reasoning\" && isAnthropicMessage) {\n result.push({\n type: \"thinking\",\n thinking: block.reasoning,\n signature: String(block.signature),\n });\n } else if (block.type === \"server_tool_call\" && isAnthropicMessage) {\n if (block.name === \"web_search\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n }\n } else if (block.type === \"server_tool_call_result\" && isAnthropicMessage) {\n if (block.name === \"web_search\" && Array.isArray(block.output.urls)) {\n const content = block.output.urls.map((url) => ({\n type: \"web_search_result\" as const,\n title: \"\",\n encrypted_content: \"\",\n url,\n }));\n result.push({\n type: \"web_search_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n content,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"code_execution_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n } else if (block.name === \"mcp_tool_result\") {\n result.push({\n type: \"mcp_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n }\n } else if (block.type === \"audio\") {\n throw new Error(\"Anthropic does not support audio content blocks.\");\n } else if (block.type === \"file\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"application/pdf\" || mimeType === \"\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"\" || mimeType === \"application/pdf\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: \"application/pdf\",\n },\n },\n metadata\n )\n );\n } else if (mimeType === \"text/plain\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n metadata\n )\n );\n } else {\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"content\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n ],\n },\n },\n metadata\n )\n );\n } else {\n throw new Error(\n `Unsupported file mime type for Anthropic base64 source: ${mimeType}`\n );\n }\n }\n continue;\n }\n throw new Error(\n \"File content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"image\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType) || \"image/png\";\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n metadata\n )\n );\n }\n continue;\n }\n throw new Error(\n \"Image content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"video\") {\n // no-op\n } else if (block.type === \"text-plain\") {\n if (block.data) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n block.metadata\n )\n );\n }\n } else if (block.type === \"non_standard\" && isAnthropicMessage) {\n result.push(block.value as Anthropic.Beta.BetaContentBlockParam);\n }\n }\n return result;\n}\n"],"mappings":";;AAQA,SAAS,sBACP,YACqC;CACrC,OACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU,cACV,WAAW,SAAS;AAExB;AAEA,SAAS,yBACP,aACmC;CACnC,UAAU,qBAAqB;EAC7B,KAAK,MAAM,cAAc,aACvB,IAAI,sBAAsB,UAAU,GAC9B;OAAA,WAAW,WAAW,QACxB,MAAM;IACJ,MAAM;IACN,SAAS,WAAW,OAAO;IAC3B,kBAAkB,WAAW,cAAc;IAC3C,gBAAgB,WAAW,YAAY;IACvC,gBAAgB,WAAW,SAAS;IACpC,gBAAgB;IAChB,YAAY,WAAW,aAAa;GACtC;QACK,IAAI,WAAW,WAAW,QAC/B,MAAM;IACJ,MAAM;IACN,SAAS,WAAW,OAAO;IAC3B,mBAAmB,WAAW,cAAc;IAC5C,iBAAiB,WAAW,YAAY;IACxC,gBAAgB,WAAW,SAAS;IACpC,gBAAgB;IAChB,YAAY,WAAW,aAAa;GACtC;QACK,IAAI,WAAW,WAAW,SAC/B,MAAM;IACJ,MAAM;IACN,SAAS,WAAW,OAAO;IAC3B,mBAAmB,WAAW,cAAc;IAC5C,iBAAiB,WAAW,YAAY;IACxC,g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GACF,GACA,QACF,CACF;GAEF;EACF;EACA,MAAM,IAAI,MACR,mEACF;CACF,OAAO,IAAI,MAAM,SAAS,SAAS,CAEnC,OAAO,IAAI,MAAM,SAAS,cACpB;MAAA,MAAM,MACR,OAAO,KACL,uBACE;GACE,MAAM;GACN,QAAQ;IACN,MAAM;IACN,MAAM,kBAAkB,MAAM,IAAI;IAClC,YAAY;GACd;EACF,GACA,MAAM,QACR,CACF;CAAA,OAEG,IAAI,MAAM,SAAS,kBAAkB,oBAC1C,OAAO,KAAK,MAAM,KAA6C;CAGnE,OAAO;AACT"}
@@ -85,12 +85,12 @@ function _applyImageMetadata(block, metadata) {
85
85
  return block;
86
86
  }
87
87
  function _hasAllowedImageMimeType(mimeType) {
88
- return new Set([
88
+ return (/* @__PURE__ */ new Set([
89
89
  "image/jpeg",
90
90
  "image/png",
91
91
  "image/gif",
92
92
  "image/webp"
93
- ]).has(mimeType);
93
+ ])).has(mimeType);
94
94
  }
95
95
  function _formatStandardContent(message) {
96
96
  const result = [];
@@ -1 +1 @@
1
- {"version":3,"file":"standard.js","names":[],"sources":["../../src/utils/standard.ts"],"sourcesContent":["import type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n BaseMessage,\n ContentBlock,\n ResponseMetadata,\n} from \"@langchain/core/messages\";\nimport { iife } from \"./index.js\";\n\nfunction _isStandardAnnotation(\n annotation: unknown\n): annotation is ContentBlock.Citation {\n return (\n typeof annotation === \"object\" &&\n annotation !== null &&\n \"type\" in annotation &&\n annotation.type === \"citation\"\n );\n}\n\nfunction _formatStandardCitations(\n annotations: ContentBlock.Citation[]\n): Anthropic.Beta.BetaTextCitation[] {\n function* iterateAnnotations() {\n for (const annotation of annotations) {\n if (_isStandardAnnotation(annotation)) {\n if (annotation.source === \"char\") {\n yield {\n type: \"char_location\" as const,\n file_id: annotation.url ?? \"\",\n start_char_index: annotation.startIndex ?? 0,\n end_char_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"page\") {\n yield {\n type: \"page_location\" as const,\n file_id: annotation.url ?? \"\",\n start_page_number: annotation.startIndex ?? 0,\n end_page_number: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"block\") {\n yield {\n type: \"content_block_location\" as const,\n file_id: annotation.url ?? \"\",\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"url\") {\n yield {\n type: \"web_search_result_location\" as const,\n url: annotation.url ?? \"\",\n title: annotation.title ?? null,\n encrypted_index: String(annotation.startIndex ?? 0),\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"search\") {\n yield {\n type: \"search_result_location\" as const,\n title: annotation.title ?? null,\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n search_result_index: 0,\n source: annotation.source ?? \"\",\n cited_text: annotation.citedText ?? \"\",\n };\n }\n }\n }\n }\n return Array.from(iterateAnnotations());\n}\n\nfunction _formatBase64Data(data: string | Uint8Array): string {\n if (typeof data === \"string\") return data;\n else return _encodeUint8Array(data);\n}\n\nfunction _encodeUint8Array(data: Uint8Array): string {\n const output = [];\n for (let i = 0, { length } = data; i < length; i++) {\n output.push(String.fromCharCode(data[i]));\n }\n return btoa(output.join(\"\"));\n}\n\nfunction _normalizeMimeType(mimeType?: string | null): string {\n return (mimeType ?? \"\").split(\";\")[0].toLowerCase();\n}\n\nfunction _extractMetadataValue<T>(\n metadata: unknown,\n key: string\n): T | undefined {\n if (\n metadata !== undefined &&\n metadata !== null &&\n typeof metadata === \"object\" &&\n key in metadata\n ) {\n return (metadata as Record<string, unknown>)[key] as T;\n }\n return undefined;\n}\n\nfunction _applyDocumentMetadata(\n block: Anthropic.Beta.BetaRequestDocumentBlock,\n metadata: unknown\n): Anthropic.Beta.BetaRequestDocumentBlock {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n const citations =\n _extractMetadataValue<Anthropic.Beta.BetaCitationsConfigParam | null>(\n metadata,\n \"citations\"\n );\n if (citations !== undefined) {\n block.citations = citations;\n }\n const context = _extractMetadataValue<string | null>(metadata, \"context\");\n if (context !== undefined) {\n block.context = context;\n }\n const title = _extractMetadataValue<string | null>(metadata, \"title\");\n if (title !== undefined) {\n block.title = title;\n }\n return block;\n}\n\nfunction _applyImageMetadata(\n block: Anthropic.Beta.BetaImageBlockParam,\n metadata: unknown\n): Anthropic.Beta.BetaImageBlockParam {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n return block;\n}\n\nfunction _hasAllowedImageMimeType(\n mimeType: string\n): mimeType is \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\" {\n const ALLOWED_IMAGE_MIME_TYPES = new Set([\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n ]);\n return ALLOWED_IMAGE_MIME_TYPES.has(mimeType);\n}\n\nexport function _formatStandardContent(\n message: BaseMessage\n): Anthropic.Beta.BetaContentBlockParam[] {\n const result: Anthropic.Beta.BetaContentBlockParam[] = [];\n const responseMetadata = message.response_metadata as ResponseMetadata;\n const isAnthropicMessage =\n \"model_provider\" in responseMetadata &&\n responseMetadata?.model_provider === \"anthropic\";\n for (const block of message.contentBlocks) {\n if (block.type === \"text\") {\n if (block.annotations) {\n result.push({\n type: \"text\",\n text: block.text,\n citations: _formatStandardCitations(\n block.annotations as ContentBlock.Citation[]\n ),\n });\n } else {\n result.push({\n type: \"text\",\n text: block.text,\n });\n }\n } else if (block.type === \"tool_call\") {\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name,\n input: block.args,\n });\n } else if (block.type === \"tool_call_chunk\") {\n const input = iife(() => {\n if (typeof block.args !== \"string\") {\n return block.args;\n }\n try {\n return JSON.parse(block.args);\n } catch {\n return {};\n }\n });\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name ?? \"\",\n input,\n });\n } else if (block.type === \"reasoning\" && isAnthropicMessage) {\n result.push({\n type: \"thinking\",\n thinking: block.reasoning,\n signature: String(block.signature),\n });\n } else if (block.type === \"server_tool_call\" && isAnthropicMessage) {\n if (block.name === \"web_search\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n }\n } else if (block.type === \"server_tool_call_result\" && isAnthropicMessage) {\n if (block.name === \"web_search\" && Array.isArray(block.output.urls)) {\n const content = block.output.urls.map((url) => ({\n type: \"web_search_result\" as const,\n title: \"\",\n encrypted_content: \"\",\n url,\n }));\n result.push({\n type: \"web_search_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n content,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"code_execution_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n } else if (block.name === \"mcp_tool_result\") {\n result.push({\n type: \"mcp_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n }\n } else if (block.type === \"audio\") {\n throw new Error(\"Anthropic does not support audio content blocks.\");\n } else if (block.type === \"file\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"application/pdf\" || mimeType === \"\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"\" || mimeType === \"application/pdf\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: \"application/pdf\",\n },\n },\n metadata\n )\n );\n } else if (mimeType === \"text/plain\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n metadata\n )\n );\n } else {\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"content\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n ],\n },\n },\n metadata\n )\n );\n } else {\n throw new Error(\n `Unsupported file mime type for Anthropic base64 source: ${mimeType}`\n );\n }\n }\n continue;\n }\n throw new Error(\n \"File content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"image\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType) || \"image/png\";\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n metadata\n )\n );\n }\n continue;\n }\n throw new Error(\n \"Image content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"video\") {\n // no-op\n } else if (block.type === \"text-plain\") {\n if (block.data) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n block.metadata\n )\n );\n }\n } else if (block.type === \"non_standard\" && isAnthropicMessage) {\n result.push(block.value as Anthropic.Beta.BetaContentBlockParam);\n }\n }\n return result;\n}\n"],"mappings":";;AAQA,SAAS,sBACP,YACqC;AACrC,QACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU,cACV,WAAW,SAAS;;AAIxB,SAAS,yBACP,aACmC;CACnC,UAAU,qBAAqB;AAC7B,OAAK,MAAM,cAAc,YACvB,KAAI,sBAAsB,WAAW;OAC/B,WAAW,WAAW,OACxB,OAAM;IACJ,MAAM;IACN,SAAS,WAAW,OAAO;IAC3B,kBAAkB,WAAW,cAAc;IAC3C,gBAAgB,WAAW,YAAY;IACvC,gBAAgB,WAAW,SAAS;IACpC,gBAAgB;IAChB,YAAY,WAAW,aAAa;IACrC;YACQ,WAAW,WAAW,OAC/B,OAAM;IACJ,MAAM;IACN,SAAS,WAAW,OAAO;IAC3B,mBAAmB,WAAW,cAAc;IAC5C,iBAAiB,WAAW,YAAY;IACxC,gBAAgB,WAAW,SAAS;IACpC,gBAAgB;IAChB,YAAY,WAAW,aAAa;IACrC;YACQ,WAAW,WAAW,QAC/B,OAAM;IACJ,MAAM;IACN,SAAS,WAAW,OAAO;IAC3B,mBAAmB,WAAW,cAAc;IAC5C,iBAAiB,WAAW,YAAY;IACxC,gBAAgB,WAAW,SAAS;IACpC,gBAAgB;IAChB,YAAY,WAAW,aAAa;IACrC;YACQ,WAAW,WAAW,MAC/B,OAAM;IACJ,MAAM;IACN,KAAK,WAAW,OAAO;IACvB,OAAO,WAAW,SAAS;IAC3B,iBAAiB,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AK;KACnC,YAAY;KACb;IACF,EACD,SACD,CACF;YAEG,yBAAyB,SAAS,CACpC,QAAO,KACL,uBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,SAAS,CACP;MACE,MAAM;MACN,QAAQ;OACN,MAAM;OACN,MAAM,kBAAkB,MAAM,KAAK;OACnC,YAAY;OACb;MACF,CACF;KACF;IACF,EACD,SACD,CACF;OAED,OAAM,IAAI,MACR,2DAA2D,WAC5D;AAGL;;AAEF,QAAM,IAAI,MACR,mEACD;YACQ,MAAM,SAAS,SAAS;EACjC,MAAM,WAAW,MAAM;AACvB,MAAI,MAAM,QAAQ;AAChB,UAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,SAAS,MAAM;KAChB;IACF,EACD,SACD,CACF;AACD;;AAEF,MAAI,MAAM,KAAK;AACb,UAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,KAAK,MAAM;KACZ;IACF,EACD,SACD,CACF;AACD;;AAEF,MAAI,MAAM,MAAM;GACd,MAAM,WAAW,mBAAmB,MAAM,SAAS,IAAI;AACvD,OAAI,yBAAyB,SAAS,CACpC,QAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,MAAM,kBAAkB,MAAM,KAAK;KACnC,YAAY;KACb;IACF,EACD,SACD,CACF;AAEH;;AAEF,QAAM,IAAI,MACR,oEACD;YACQ,MAAM,SAAS,SAAS,YAExB,MAAM,SAAS;MACpB,MAAM,KACR,QAAO,KACL,uBACE;GACE,MAAM;GACN,QAAQ;IACN,MAAM;IACN,MAAM,kBAAkB,MAAM,KAAK;IACnC,YAAY;IACb;GACF,EACD,MAAM,SACP,CACF;YAEM,MAAM,SAAS,kBAAkB,mBAC1C,QAAO,KAAK,MAAM,MAA8C;AAGpE,QAAO"}
1
+ {"version":3,"file":"standard.js","names":[],"sources":["../../src/utils/standard.ts"],"sourcesContent":["import type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n BaseMessage,\n ContentBlock,\n ResponseMetadata,\n} from \"@langchain/core/messages\";\nimport { iife } from \"./index.js\";\n\nfunction _isStandardAnnotation(\n annotation: unknown\n): annotation is ContentBlock.Citation {\n return (\n typeof annotation === \"object\" &&\n annotation !== null &&\n \"type\" in annotation &&\n annotation.type === \"citation\"\n );\n}\n\nfunction _formatStandardCitations(\n annotations: ContentBlock.Citation[]\n): Anthropic.Beta.BetaTextCitation[] {\n function* iterateAnnotations() {\n for (const annotation of annotations) {\n if (_isStandardAnnotation(annotation)) {\n if (annotation.source === \"char\") {\n yield {\n type: \"char_location\" as const,\n file_id: annotation.url ?? \"\",\n start_char_index: annotation.startIndex ?? 0,\n end_char_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"page\") {\n yield {\n type: \"page_location\" as const,\n file_id: annotation.url ?? \"\",\n start_page_number: annotation.startIndex ?? 0,\n end_page_number: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"block\") {\n yield {\n type: \"content_block_location\" as const,\n file_id: annotation.url ?? \"\",\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n document_title: annotation.title ?? null,\n document_index: 0,\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"url\") {\n yield {\n type: \"web_search_result_location\" as const,\n url: annotation.url ?? \"\",\n title: annotation.title ?? null,\n encrypted_index: String(annotation.startIndex ?? 0),\n cited_text: annotation.citedText ?? \"\",\n };\n } else if (annotation.source === \"search\") {\n yield {\n type: \"search_result_location\" as const,\n title: annotation.title ?? null,\n start_block_index: annotation.startIndex ?? 0,\n end_block_index: annotation.endIndex ?? 0,\n search_result_index: 0,\n source: annotation.source ?? \"\",\n cited_text: annotation.citedText ?? \"\",\n };\n }\n }\n }\n }\n return Array.from(iterateAnnotations());\n}\n\nfunction _formatBase64Data(data: string | Uint8Array): string {\n if (typeof data === \"string\") return data;\n else return _encodeUint8Array(data);\n}\n\nfunction _encodeUint8Array(data: Uint8Array): string {\n const output = [];\n for (let i = 0, { length } = data; i < length; i++) {\n output.push(String.fromCharCode(data[i]));\n }\n return btoa(output.join(\"\"));\n}\n\nfunction _normalizeMimeType(mimeType?: string | null): string {\n return (mimeType ?? \"\").split(\";\")[0].toLowerCase();\n}\n\nfunction _extractMetadataValue<T>(\n metadata: unknown,\n key: string\n): T | undefined {\n if (\n metadata !== undefined &&\n metadata !== null &&\n typeof metadata === \"object\" &&\n key in metadata\n ) {\n return (metadata as Record<string, unknown>)[key] as T;\n }\n return undefined;\n}\n\nfunction _applyDocumentMetadata(\n block: Anthropic.Beta.BetaRequestDocumentBlock,\n metadata: unknown\n): Anthropic.Beta.BetaRequestDocumentBlock {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n const citations =\n _extractMetadataValue<Anthropic.Beta.BetaCitationsConfigParam | null>(\n metadata,\n \"citations\"\n );\n if (citations !== undefined) {\n block.citations = citations;\n }\n const context = _extractMetadataValue<string | null>(metadata, \"context\");\n if (context !== undefined) {\n block.context = context;\n }\n const title = _extractMetadataValue<string | null>(metadata, \"title\");\n if (title !== undefined) {\n block.title = title;\n }\n return block;\n}\n\nfunction _applyImageMetadata(\n block: Anthropic.Beta.BetaImageBlockParam,\n metadata: unknown\n): Anthropic.Beta.BetaImageBlockParam {\n const cacheControl =\n _extractMetadataValue<Anthropic.Beta.BetaCacheControlEphemeral | null>(\n metadata,\n \"cache_control\"\n );\n if (cacheControl !== undefined) {\n block.cache_control = cacheControl;\n }\n return block;\n}\n\nfunction _hasAllowedImageMimeType(\n mimeType: string\n): mimeType is \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\" {\n const ALLOWED_IMAGE_MIME_TYPES = new Set([\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n ]);\n return ALLOWED_IMAGE_MIME_TYPES.has(mimeType);\n}\n\nexport function _formatStandardContent(\n message: BaseMessage\n): Anthropic.Beta.BetaContentBlockParam[] {\n const result: Anthropic.Beta.BetaContentBlockParam[] = [];\n const responseMetadata = message.response_metadata as ResponseMetadata;\n const isAnthropicMessage =\n \"model_provider\" in responseMetadata &&\n responseMetadata?.model_provider === \"anthropic\";\n for (const block of message.contentBlocks) {\n if (block.type === \"text\") {\n if (block.annotations) {\n result.push({\n type: \"text\",\n text: block.text,\n citations: _formatStandardCitations(\n block.annotations as ContentBlock.Citation[]\n ),\n });\n } else {\n result.push({\n type: \"text\",\n text: block.text,\n });\n }\n } else if (block.type === \"tool_call\") {\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name,\n input: block.args,\n });\n } else if (block.type === \"tool_call_chunk\") {\n const input = iife(() => {\n if (typeof block.args !== \"string\") {\n return block.args;\n }\n try {\n return JSON.parse(block.args);\n } catch {\n return {};\n }\n });\n result.push({\n type: \"tool_use\",\n id: block.id ?? \"\",\n name: block.name ?? \"\",\n input,\n });\n } else if (block.type === \"reasoning\" && isAnthropicMessage) {\n result.push({\n type: \"thinking\",\n thinking: block.reasoning,\n signature: String(block.signature),\n });\n } else if (block.type === \"server_tool_call\" && isAnthropicMessage) {\n if (block.name === \"web_search\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"server_tool_use\",\n name: block.name,\n id: block.id ?? \"\",\n input: block.args,\n });\n }\n } else if (block.type === \"server_tool_call_result\" && isAnthropicMessage) {\n if (block.name === \"web_search\" && Array.isArray(block.output.urls)) {\n const content = block.output.urls.map((url) => ({\n type: \"web_search_result\" as const,\n title: \"\",\n encrypted_content: \"\",\n url,\n }));\n result.push({\n type: \"web_search_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n content,\n });\n } else if (block.name === \"code_execution\") {\n result.push({\n type: \"code_execution_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n } else if (block.name === \"mcp_tool_result\") {\n result.push({\n type: \"mcp_tool_result\",\n tool_use_id: block.toolCallId ?? \"\",\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: block.output as any,\n });\n }\n } else if (block.type === \"audio\") {\n throw new Error(\"Anthropic does not support audio content blocks.\");\n } else if (block.type === \"file\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"application/pdf\" || mimeType === \"\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType);\n if (mimeType === \"\" || mimeType === \"application/pdf\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: \"application/pdf\",\n },\n },\n metadata\n )\n );\n } else if (mimeType === \"text/plain\") {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n metadata\n )\n );\n } else {\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"content\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n ],\n },\n },\n metadata\n )\n );\n } else {\n throw new Error(\n `Unsupported file mime type for Anthropic base64 source: ${mimeType}`\n );\n }\n }\n continue;\n }\n throw new Error(\n \"File content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"image\") {\n const metadata = block.metadata;\n if (block.fileId) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"file\",\n file_id: block.fileId,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.url) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"url\",\n url: block.url,\n },\n },\n metadata\n )\n );\n continue;\n }\n if (block.data) {\n const mimeType = _normalizeMimeType(block.mimeType) || \"image/png\";\n if (_hasAllowedImageMimeType(mimeType)) {\n result.push(\n _applyImageMetadata(\n {\n type: \"image\",\n source: {\n type: \"base64\",\n data: _formatBase64Data(block.data),\n media_type: mimeType,\n },\n },\n metadata\n )\n );\n }\n continue;\n }\n throw new Error(\n \"Image content block must include a fileId, url, or data property.\"\n );\n } else if (block.type === \"video\") {\n // no-op\n } else if (block.type === \"text-plain\") {\n if (block.data) {\n result.push(\n _applyDocumentMetadata(\n {\n type: \"document\",\n source: {\n type: \"text\",\n data: _formatBase64Data(block.data),\n media_type: \"text/plain\",\n },\n },\n block.metadata\n )\n );\n }\n } else if (block.type === \"non_standard\" && isAnthropicMessage) {\n result.push(block.value as Anthropic.Beta.BetaContentBlockParam);\n }\n }\n return result;\n}\n"],"mappings":";;AAQA,SAAS,sBACP,YACqC;CACrC,OACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU,cACV,WAAW,SAAS;AAExB;AAEA,SAAS,yBACP,aACmC;CACnC,UAAU,qBAAqB;EAC7B,KAAK,MAAM,cAAc,aACvB,IAAI,sBAAsB,UAAU,GAC9B;OAAA,WAAW,WAAW,QACxB,MAAM;IACJ,MAAM;IACN,SAAS,WAAW,OAAO;IAC3B,kBAAkB,WAAW,cAAc;IAC3C,gBAAgB,WAAW,YAAY;IACvC,gBAAgB,WAAW,SAAS;IACpC,gBAAgB;IAChB,YAAY,WAAW,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A;EACF;EACA,IAAI,MAAM,KAAK;GACb,OAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,KAAK,MAAM;IACb;GACF,GACA,QACF,CACF;GACA;EACF;EACA,IAAI,MAAM,MAAM;GACd,MAAM,WAAW,mBAAmB,MAAM,QAAQ,KAAK;GACvD,IAAI,yBAAyB,QAAQ,GACnC,OAAO,KACL,oBACE;IACE,MAAM;IACN,QAAQ;KACN,MAAM;KACN,MAAM,kBAAkB,MAAM,IAAI;KAClC,YAAY;IACd;GACF,GACA,QACF,CACF;GAEF;EACF;EACA,MAAM,IAAI,MACR,mEACF;CACF,OAAO,IAAI,MAAM,SAAS,SAAS,CAEnC,OAAO,IAAI,MAAM,SAAS,cACpB;MAAA,MAAM,MACR,OAAO,KACL,uBACE;GACE,MAAM;GACN,QAAQ;IACN,MAAM;IACN,MAAM,kBAAkB,MAAM,IAAI;IAClC,YAAY;GACd;EACF,GACA,MAAM,QACR,CACF;CAAA,OAEG,IAAI,MAAM,SAAS,kBAAkB,oBAC1C,OAAO,KAAK,MAAM,KAA6C;CAGnE,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"stream_events.cjs","names":[],"sources":["../../src/utils/stream_events.ts"],"sourcesContent":["/**\n * Converts a raw Anthropic SSE event stream into LangChain ChatModelStreamEvents.\n *\n * @module\n */\n\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ChatModelStreamEvent,\n ContentBlockDelta,\n FinishReason,\n} from \"@langchain/core/language_models/event\";\nimport type { ContentBlock, UsageMetadata } from \"@langchain/core/messages\";\nimport type { AnthropicMessageStreamEvent } from \"../types.js\";\n\n// ─── Public API ─────────────────────────────────────────────────\n\nexport interface ConvertAnthropicStreamOptions {\n streamUsage?: boolean;\n}\n\n/**\n * Convert an async iterable of raw Anthropic stream events into\n * LangChain `ChatModelStreamEvent`s with typed deltas.\n */\nexport async function* convertAnthropicStream(\n source: AsyncIterable<AnthropicMessageStreamEvent>,\n options: ConvertAnthropicStreamOptions = {}\n): AsyncGenerator<ChatModelStreamEvent> {\n const shouldStreamUsage = options.streamUsage ?? true;\n\n // Track accumulated state per content block (for finalization)\n const blockAccumulators = new Map<\n number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n >();\n let usageSnapshot: UsageMetadata | undefined;\n let stopReason: string | null = null;\n\n for await (const data of source) {\n switch (data.type) {\n // ── Message lifecycle ──────────────────────────────────\n case \"message_start\": {\n const { usage, id, model } = data.message;\n if (usage && shouldStreamUsage) {\n usageSnapshot = buildUsageSnapshot(usage);\n }\n yield {\n event: \"message-start\" as const,\n id,\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n };\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"message_start\",\n payload: { model, id },\n };\n break;\n }\n\n case \"message_delta\": {\n stopReason = data.delta.stop_reason;\n if (shouldStreamUsage && data.usage) {\n if (!usageSnapshot) {\n usageSnapshot = {\n input_tokens: 0,\n output_tokens: data.usage.output_tokens,\n total_tokens: data.usage.output_tokens,\n };\n } else {\n usageSnapshot = {\n ...usageSnapshot,\n output_tokens:\n usageSnapshot.output_tokens + data.usage.output_tokens,\n total_tokens:\n usageSnapshot.input_tokens +\n usageSnapshot.output_tokens +\n data.usage.output_tokens,\n };\n }\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n if (\n \"context_management\" in data.delta &&\n data.delta.context_management\n ) {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"context_management\",\n payload: data.delta.context_management,\n };\n }\n break;\n }\n\n case \"message_stop\": {\n yield {\n event: \"message-finish\" as const,\n reason: mapStopReason(stopReason),\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n metadata: { model_provider: \"anthropic\" },\n };\n break;\n }\n\n // ── Content block lifecycle ───────────────────────────\n case \"content_block_start\": {\n const { index, content_block } = data;\n const mapped = mapBlockToContentBlock(content_block, index);\n blockAccumulators.set(index, { ...mapped });\n yield {\n event: \"content-block-start\" as const,\n index,\n content: mapped,\n };\n break;\n }\n\n case \"content_block_delta\": {\n const { index, delta } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const { contentDelta, accumulated } = applyAnthropicDelta(acc, delta);\n blockAccumulators.set(index, accumulated);\n\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: contentDelta,\n };\n break;\n }\n\n case \"content_block_stop\": {\n const { index } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const finalized = finalizeBlock(acc);\n yield {\n event: \"content-block-finish\" as const,\n index,\n content: finalized,\n };\n blockAccumulators.delete(index);\n break;\n }\n\n // ── Unhandled → provider passthrough ───────────────────\n default: {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: data.type,\n payload: data,\n };\n break;\n }\n }\n }\n}\n\n// ─── Internal helpers ───────────────────────────────────────────\n\nfunction mapStopReason(stopReason: string | null | undefined): FinishReason {\n switch (stopReason) {\n case \"end_turn\":\n case \"stop_sequence\":\n return \"stop\";\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"length\";\n default:\n return \"stop\";\n }\n}\n\nfunction buildUsageSnapshot(\n usage: Anthropic.Messages.Usage | Record<string, number>\n): UsageMetadata {\n const cacheCreation =\n (usage as Record<string, number>).cache_creation_input_tokens ?? 0;\n const cacheRead =\n (usage as Record<string, number>).cache_read_input_tokens ?? 0;\n const totalInput = usage.input_tokens + cacheCreation + cacheRead;\n return {\n input_tokens: totalInput,\n output_tokens: usage.output_tokens,\n total_tokens: totalInput + usage.output_tokens,\n input_token_details: {\n cache_creation: cacheCreation,\n cache_read: cacheRead,\n },\n };\n}\n\nfunction mapBlockToContentBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n block: any,\n index: number\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n switch (block.type) {\n case \"text\":\n return { type: \"text\" as const, text: block.text ?? \"\", index };\n case \"thinking\":\n return {\n type: \"reasoning\" as const,\n reasoning: block.thinking ?? \"\",\n index,\n };\n case \"redacted_thinking\":\n return { type: \"non_standard\" as const, value: { ...block }, index };\n case \"tool_use\":\n return {\n type: \"tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n case \"server_tool_use\":\n return {\n type: \"server_tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n default:\n return { type: \"non_standard\" as const, value: { ...block }, index };\n }\n}\n\n/**\n * Map an Anthropic content_block_delta to a content block delta\n * and update the accumulated state.\n */\nfunction applyAnthropicDelta(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n delta: any\n): {\n contentDelta: ContentBlockDelta;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>;\n} {\n switch (delta.type) {\n case \"text_delta\":\n return {\n contentDelta: { type: \"text-delta\" as const, text: delta.text },\n accumulated: {\n ...accumulated,\n text: (accumulated.text ?? \"\") + delta.text,\n },\n };\n\n case \"thinking_delta\":\n return {\n contentDelta: {\n type: \"reasoning-delta\" as const,\n reasoning: delta.thinking,\n },\n accumulated: {\n ...accumulated,\n reasoning: (accumulated.reasoning ?? \"\") + delta.thinking,\n },\n };\n\n case \"input_json_delta\": {\n const newArgs = (accumulated.args ?? \"\") + delta.partial_json;\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, args: newArgs },\n },\n accumulated: { ...accumulated, args: newArgs },\n };\n }\n\n case \"citations_delta\": {\n const annotations = [...(accumulated.annotations ?? []), delta.citation];\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: accumulated.type,\n annotations,\n },\n },\n accumulated: {\n ...accumulated,\n annotations,\n },\n };\n }\n\n case \"signature_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, signature: delta.signature },\n },\n accumulated: { ...accumulated, signature: delta.signature },\n };\n\n case \"compaction_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: \"non_standard\",\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n },\n accumulated: {\n ...accumulated,\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n };\n\n default:\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, ...delta },\n },\n accumulated,\n };\n }\n}\n\nfunction finalizeBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>\n): ContentBlock {\n if (\n accumulated.type === \"tool_call_chunk\" ||\n accumulated.type === \"server_tool_call_chunk\"\n ) {\n const finalType =\n accumulated.type === \"tool_call_chunk\"\n ? (\"tool_call\" as const)\n : (\"server_tool_call\" as const);\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(accumulated.args || \"{}\");\n } catch {\n return {\n type: \"invalid_tool_call\" as const,\n id: accumulated.id,\n name: accumulated.name,\n args: accumulated.args,\n error: \"Failed to parse tool call arguments as JSON\",\n } as ContentBlock.Tools.InvalidToolCall;\n }\n return {\n type: finalType,\n id: accumulated.id,\n name: accumulated.name,\n args: parsedArgs,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n\n const { index: _index, ...rest } = accumulated;\n return rest as ContentBlock;\n}\n"],"mappings":";;;;;AAyBA,gBAAuB,uBACrB,QACA,UAAyC,EAAE,EACL;CACtC,MAAM,oBAAoB,QAAQ,eAAe;CAGjD,MAAM,oCAAoB,IAAI,KAI3B;CACH,IAAI;CACJ,IAAI,aAA4B;AAEhC,YAAW,MAAM,QAAQ,OACvB,SAAQ,KAAK,MAAb;EAEE,KAAK,iBAAiB;GACpB,MAAM,EAAE,OAAO,IAAI,UAAU,KAAK;AAClC,OAAI,SAAS,kBACX,iBAAgB,mBAAmB,MAAM;AAE3C,SAAM;IACJ,OAAO;IACP;IACA,GAAI,gBAAgB,EAAE,OAAO,eAAe,GAAG,EA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ACA;EACP,IAAI;AACJ,MAAI;AACF,gBAAa,KAAK,MAAM,YAAY,QAAQ,KAAK;UAC3C;AACN,UAAO;IACL,MAAM;IACN,IAAI,YAAY;IAChB,MAAM,YAAY;IAClB,MAAM,YAAY;IAClB,OAAO;IACR;;AAEH,SAAO;GACL,MAAM;GACN,IAAI,YAAY;GAChB,MAAM,YAAY;GAClB,MAAM;GAEP;;CAGH,MAAM,EAAE,OAAO,QAAQ,GAAG,SAAS;AACnC,QAAO"}
1
+ {"version":3,"file":"stream_events.cjs","names":[],"sources":["../../src/utils/stream_events.ts"],"sourcesContent":["/**\n * Converts a raw Anthropic SSE event stream into LangChain ChatModelStreamEvents.\n *\n * @module\n */\n\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ChatModelStreamEvent,\n ContentBlockDelta,\n FinishReason,\n} from \"@langchain/core/language_models/event\";\nimport type { ContentBlock, UsageMetadata } from \"@langchain/core/messages\";\nimport type { AnthropicMessageStreamEvent } from \"../types.js\";\n\n// ─── Public API ─────────────────────────────────────────────────\n\nexport interface ConvertAnthropicStreamOptions {\n streamUsage?: boolean;\n}\n\n/**\n * Convert an async iterable of raw Anthropic stream events into\n * LangChain `ChatModelStreamEvent`s with typed deltas.\n */\nexport async function* convertAnthropicStream(\n source: AsyncIterable<AnthropicMessageStreamEvent>,\n options: ConvertAnthropicStreamOptions = {}\n): AsyncGenerator<ChatModelStreamEvent> {\n const shouldStreamUsage = options.streamUsage ?? true;\n\n // Track accumulated state per content block (for finalization)\n const blockAccumulators = new Map<\n number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n >();\n let usageSnapshot: UsageMetadata | undefined;\n let stopReason: string | null = null;\n\n for await (const data of source) {\n switch (data.type) {\n // ── Message lifecycle ──────────────────────────────────\n case \"message_start\": {\n const { usage, id, model } = data.message;\n if (usage && shouldStreamUsage) {\n usageSnapshot = buildUsageSnapshot(usage);\n }\n yield {\n event: \"message-start\" as const,\n id,\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n };\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"message_start\",\n payload: { model, id },\n };\n break;\n }\n\n case \"message_delta\": {\n stopReason = data.delta.stop_reason;\n if (shouldStreamUsage && data.usage) {\n if (!usageSnapshot) {\n usageSnapshot = {\n input_tokens: 0,\n output_tokens: data.usage.output_tokens,\n total_tokens: data.usage.output_tokens,\n };\n } else {\n usageSnapshot = {\n ...usageSnapshot,\n output_tokens:\n usageSnapshot.output_tokens + data.usage.output_tokens,\n total_tokens:\n usageSnapshot.input_tokens +\n usageSnapshot.output_tokens +\n data.usage.output_tokens,\n };\n }\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n if (\n \"context_management\" in data.delta &&\n data.delta.context_management\n ) {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"context_management\",\n payload: data.delta.context_management,\n };\n }\n break;\n }\n\n case \"message_stop\": {\n yield {\n event: \"message-finish\" as const,\n reason: mapStopReason(stopReason),\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n metadata: { model_provider: \"anthropic\" },\n };\n break;\n }\n\n // ── Content block lifecycle ───────────────────────────\n case \"content_block_start\": {\n const { index, content_block } = data;\n const mapped = mapBlockToContentBlock(content_block, index);\n blockAccumulators.set(index, { ...mapped });\n yield {\n event: \"content-block-start\" as const,\n index,\n content: mapped,\n };\n break;\n }\n\n case \"content_block_delta\": {\n const { index, delta } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const { contentDelta, accumulated } = applyAnthropicDelta(acc, delta);\n blockAccumulators.set(index, accumulated);\n\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: contentDelta,\n };\n break;\n }\n\n case \"content_block_stop\": {\n const { index } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const finalized = finalizeBlock(acc);\n yield {\n event: \"content-block-finish\" as const,\n index,\n content: finalized,\n };\n blockAccumulators.delete(index);\n break;\n }\n\n // ── Unhandled → provider passthrough ───────────────────\n default: {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: data.type,\n payload: data,\n };\n break;\n }\n }\n }\n}\n\n// ─── Internal helpers ───────────────────────────────────────────\n\nfunction mapStopReason(stopReason: string | null | undefined): FinishReason {\n switch (stopReason) {\n case \"end_turn\":\n case \"stop_sequence\":\n return \"stop\";\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"length\";\n default:\n return \"stop\";\n }\n}\n\nfunction buildUsageSnapshot(\n usage: Anthropic.Messages.Usage | Record<string, number>\n): UsageMetadata {\n const cacheCreation =\n (usage as Record<string, number>).cache_creation_input_tokens ?? 0;\n const cacheRead =\n (usage as Record<string, number>).cache_read_input_tokens ?? 0;\n const totalInput = usage.input_tokens + cacheCreation + cacheRead;\n return {\n input_tokens: totalInput,\n output_tokens: usage.output_tokens,\n total_tokens: totalInput + usage.output_tokens,\n input_token_details: {\n cache_creation: cacheCreation,\n cache_read: cacheRead,\n },\n };\n}\n\nfunction mapBlockToContentBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n block: any,\n index: number\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n switch (block.type) {\n case \"text\":\n return { type: \"text\" as const, text: block.text ?? \"\", index };\n case \"thinking\":\n return {\n type: \"reasoning\" as const,\n reasoning: block.thinking ?? \"\",\n index,\n };\n case \"redacted_thinking\":\n return { type: \"non_standard\" as const, value: { ...block }, index };\n case \"tool_use\":\n return {\n type: \"tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n case \"server_tool_use\":\n return {\n type: \"server_tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n default:\n return { type: \"non_standard\" as const, value: { ...block }, index };\n }\n}\n\n/**\n * Map an Anthropic content_block_delta to a content block delta\n * and update the accumulated state.\n */\nfunction applyAnthropicDelta(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n delta: any\n): {\n contentDelta: ContentBlockDelta;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>;\n} {\n switch (delta.type) {\n case \"text_delta\":\n return {\n contentDelta: { type: \"text-delta\" as const, text: delta.text },\n accumulated: {\n ...accumulated,\n text: (accumulated.text ?? \"\") + delta.text,\n },\n };\n\n case \"thinking_delta\":\n return {\n contentDelta: {\n type: \"reasoning-delta\" as const,\n reasoning: delta.thinking,\n },\n accumulated: {\n ...accumulated,\n reasoning: (accumulated.reasoning ?? \"\") + delta.thinking,\n },\n };\n\n case \"input_json_delta\": {\n const newArgs = (accumulated.args ?? \"\") + delta.partial_json;\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, args: newArgs },\n },\n accumulated: { ...accumulated, args: newArgs },\n };\n }\n\n case \"citations_delta\": {\n const annotations = [...(accumulated.annotations ?? []), delta.citation];\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: accumulated.type,\n annotations,\n },\n },\n accumulated: {\n ...accumulated,\n annotations,\n },\n };\n }\n\n case \"signature_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, signature: delta.signature },\n },\n accumulated: { ...accumulated, signature: delta.signature },\n };\n\n case \"compaction_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: \"non_standard\",\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n },\n accumulated: {\n ...accumulated,\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n };\n\n default:\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, ...delta },\n },\n accumulated,\n };\n }\n}\n\nfunction finalizeBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>\n): ContentBlock {\n if (\n accumulated.type === \"tool_call_chunk\" ||\n accumulated.type === \"server_tool_call_chunk\"\n ) {\n const finalType =\n accumulated.type === \"tool_call_chunk\"\n ? (\"tool_call\" as const)\n : (\"server_tool_call\" as const);\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(accumulated.args || \"{}\");\n } catch {\n return {\n type: \"invalid_tool_call\" as const,\n id: accumulated.id,\n name: accumulated.name,\n args: accumulated.args,\n error: \"Failed to parse tool call arguments as JSON\",\n } as ContentBlock.Tools.InvalidToolCall;\n }\n return {\n type: finalType,\n id: accumulated.id,\n name: accumulated.name,\n args: parsedArgs,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n\n const { index: _index, ...rest } = accumulated;\n return rest as ContentBlock;\n}\n"],"mappings":";;;;;AAyBA,gBAAuB,uBACrB,QACA,UAAyC,CAAC,GACJ;CACtC,MAAM,oBAAoB,QAAQ,eAAe;CAGjD,MAAM,oCAAoB,IAAI,IAI5B;CACF,IAAI;CACJ,IAAI,aAA4B;CAEhC,WAAW,MAAM,QAAQ,QACvB,QAAQ,KAAK,MAAb;EAEE,KAAK,iBAAiB;GACpB,MAAM,EAAE,OAAO,IAAI,UAAU,KAAK;GAClC,IAAI,SAAS,mBACX,gBAAgB,mBAAmB,KAAK;GAE1C,MAAM;IACJ,OAAO;IACP;IACA,GAAI,gBAAgB,EAAE,OAAO,cAAc,IAAI,CAAC;GAClD;GACA,MAAM;IACJ,OAAO;IACP,UAAU;IACV,MAAM;IACN,SAAS;KAAE;KAAO;IAAG;GACvB;GACA;EACF;EAEA,KAAK;GACH,aAAa,KAAK,MAAM;GACxB,IAAI,qBAAqB,KAAK,OAAO;IACnC,IAAI,CAAC,eACH,gBAAgB;KACd,cAAc;KACd,eAAe,KAAK,MAAM;KAC1B,cAAc,KAAK,MAAM;IAC3B;SAEA,gBAAgB;KACd,GAAG;KACH,eACE,cAAc,gBAAgB,KAAK,MAAM;KAC3C,cACE,cAAc,eACd,cAAc,gBACd,KAAK,MAAM;IACf;IAEF,MAAM;KAAE,OAAO;KAAkB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file":"stream_events.js","names":[],"sources":["../../src/utils/stream_events.ts"],"sourcesContent":["/**\n * Converts a raw Anthropic SSE event stream into LangChain ChatModelStreamEvents.\n *\n * @module\n */\n\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ChatModelStreamEvent,\n ContentBlockDelta,\n FinishReason,\n} from \"@langchain/core/language_models/event\";\nimport type { ContentBlock, UsageMetadata } from \"@langchain/core/messages\";\nimport type { AnthropicMessageStreamEvent } from \"../types.js\";\n\n// ─── Public API ─────────────────────────────────────────────────\n\nexport interface ConvertAnthropicStreamOptions {\n streamUsage?: boolean;\n}\n\n/**\n * Convert an async iterable of raw Anthropic stream events into\n * LangChain `ChatModelStreamEvent`s with typed deltas.\n */\nexport async function* convertAnthropicStream(\n source: AsyncIterable<AnthropicMessageStreamEvent>,\n options: ConvertAnthropicStreamOptions = {}\n): AsyncGenerator<ChatModelStreamEvent> {\n const shouldStreamUsage = options.streamUsage ?? true;\n\n // Track accumulated state per content block (for finalization)\n const blockAccumulators = new Map<\n number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n >();\n let usageSnapshot: UsageMetadata | undefined;\n let stopReason: string | null = null;\n\n for await (const data of source) {\n switch (data.type) {\n // ── Message lifecycle ──────────────────────────────────\n case \"message_start\": {\n const { usage, id, model } = data.message;\n if (usage && shouldStreamUsage) {\n usageSnapshot = buildUsageSnapshot(usage);\n }\n yield {\n event: \"message-start\" as const,\n id,\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n };\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"message_start\",\n payload: { model, id },\n };\n break;\n }\n\n case \"message_delta\": {\n stopReason = data.delta.stop_reason;\n if (shouldStreamUsage && data.usage) {\n if (!usageSnapshot) {\n usageSnapshot = {\n input_tokens: 0,\n output_tokens: data.usage.output_tokens,\n total_tokens: data.usage.output_tokens,\n };\n } else {\n usageSnapshot = {\n ...usageSnapshot,\n output_tokens:\n usageSnapshot.output_tokens + data.usage.output_tokens,\n total_tokens:\n usageSnapshot.input_tokens +\n usageSnapshot.output_tokens +\n data.usage.output_tokens,\n };\n }\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n if (\n \"context_management\" in data.delta &&\n data.delta.context_management\n ) {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"context_management\",\n payload: data.delta.context_management,\n };\n }\n break;\n }\n\n case \"message_stop\": {\n yield {\n event: \"message-finish\" as const,\n reason: mapStopReason(stopReason),\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n metadata: { model_provider: \"anthropic\" },\n };\n break;\n }\n\n // ── Content block lifecycle ───────────────────────────\n case \"content_block_start\": {\n const { index, content_block } = data;\n const mapped = mapBlockToContentBlock(content_block, index);\n blockAccumulators.set(index, { ...mapped });\n yield {\n event: \"content-block-start\" as const,\n index,\n content: mapped,\n };\n break;\n }\n\n case \"content_block_delta\": {\n const { index, delta } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const { contentDelta, accumulated } = applyAnthropicDelta(acc, delta);\n blockAccumulators.set(index, accumulated);\n\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: contentDelta,\n };\n break;\n }\n\n case \"content_block_stop\": {\n const { index } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const finalized = finalizeBlock(acc);\n yield {\n event: \"content-block-finish\" as const,\n index,\n content: finalized,\n };\n blockAccumulators.delete(index);\n break;\n }\n\n // ── Unhandled → provider passthrough ───────────────────\n default: {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: data.type,\n payload: data,\n };\n break;\n }\n }\n }\n}\n\n// ─── Internal helpers ───────────────────────────────────────────\n\nfunction mapStopReason(stopReason: string | null | undefined): FinishReason {\n switch (stopReason) {\n case \"end_turn\":\n case \"stop_sequence\":\n return \"stop\";\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"length\";\n default:\n return \"stop\";\n }\n}\n\nfunction buildUsageSnapshot(\n usage: Anthropic.Messages.Usage | Record<string, number>\n): UsageMetadata {\n const cacheCreation =\n (usage as Record<string, number>).cache_creation_input_tokens ?? 0;\n const cacheRead =\n (usage as Record<string, number>).cache_read_input_tokens ?? 0;\n const totalInput = usage.input_tokens + cacheCreation + cacheRead;\n return {\n input_tokens: totalInput,\n output_tokens: usage.output_tokens,\n total_tokens: totalInput + usage.output_tokens,\n input_token_details: {\n cache_creation: cacheCreation,\n cache_read: cacheRead,\n },\n };\n}\n\nfunction mapBlockToContentBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n block: any,\n index: number\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n switch (block.type) {\n case \"text\":\n return { type: \"text\" as const, text: block.text ?? \"\", index };\n case \"thinking\":\n return {\n type: \"reasoning\" as const,\n reasoning: block.thinking ?? \"\",\n index,\n };\n case \"redacted_thinking\":\n return { type: \"non_standard\" as const, value: { ...block }, index };\n case \"tool_use\":\n return {\n type: \"tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n case \"server_tool_use\":\n return {\n type: \"server_tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n default:\n return { type: \"non_standard\" as const, value: { ...block }, index };\n }\n}\n\n/**\n * Map an Anthropic content_block_delta to a content block delta\n * and update the accumulated state.\n */\nfunction applyAnthropicDelta(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n delta: any\n): {\n contentDelta: ContentBlockDelta;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>;\n} {\n switch (delta.type) {\n case \"text_delta\":\n return {\n contentDelta: { type: \"text-delta\" as const, text: delta.text },\n accumulated: {\n ...accumulated,\n text: (accumulated.text ?? \"\") + delta.text,\n },\n };\n\n case \"thinking_delta\":\n return {\n contentDelta: {\n type: \"reasoning-delta\" as const,\n reasoning: delta.thinking,\n },\n accumulated: {\n ...accumulated,\n reasoning: (accumulated.reasoning ?? \"\") + delta.thinking,\n },\n };\n\n case \"input_json_delta\": {\n const newArgs = (accumulated.args ?? \"\") + delta.partial_json;\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, args: newArgs },\n },\n accumulated: { ...accumulated, args: newArgs },\n };\n }\n\n case \"citations_delta\": {\n const annotations = [...(accumulated.annotations ?? []), delta.citation];\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: accumulated.type,\n annotations,\n },\n },\n accumulated: {\n ...accumulated,\n annotations,\n },\n };\n }\n\n case \"signature_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, signature: delta.signature },\n },\n accumulated: { ...accumulated, signature: delta.signature },\n };\n\n case \"compaction_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: \"non_standard\",\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n },\n accumulated: {\n ...accumulated,\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n };\n\n default:\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, ...delta },\n },\n accumulated,\n };\n }\n}\n\nfunction finalizeBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>\n): ContentBlock {\n if (\n accumulated.type === \"tool_call_chunk\" ||\n accumulated.type === \"server_tool_call_chunk\"\n ) {\n const finalType =\n accumulated.type === \"tool_call_chunk\"\n ? (\"tool_call\" as const)\n : (\"server_tool_call\" as const);\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(accumulated.args || \"{}\");\n } catch {\n return {\n type: \"invalid_tool_call\" as const,\n id: accumulated.id,\n name: accumulated.name,\n args: accumulated.args,\n error: \"Failed to parse tool call arguments as JSON\",\n } as ContentBlock.Tools.InvalidToolCall;\n }\n return {\n type: finalType,\n id: accumulated.id,\n name: accumulated.name,\n args: parsedArgs,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n\n const { index: _index, ...rest } = accumulated;\n return rest as ContentBlock;\n}\n"],"mappings":";;;;;AAyBA,gBAAuB,uBACrB,QACA,UAAyC,EAAE,EACL;CACtC,MAAM,oBAAoB,QAAQ,eAAe;CAGjD,MAAM,oCAAoB,IAAI,KAI3B;CACH,IAAI;CACJ,IAAI,aAA4B;AAEhC,YAAW,MAAM,QAAQ,OACvB,SAAQ,KAAK,MAAb;EAEE,KAAK,iBAAiB;GACpB,MAAM,EAAE,OAAO,IAAI,UAAU,KAAK;AAClC,OAAI,SAAS,kBACX,iBAAgB,mBAAmB,MAAM;AAE3C,SAAM;IACJ,OAAO;IACP;IACA,GAAI,gBAAgB,EAAE,OAAO,eAAe,GAAG,EAAE;IAClD;AACD,SAAM;IACJ,OAAO;IACP,UAAU;IACV,MAAM;IACN,SAAS;KAAE;KAAO;KAAI;IACvB;AACD;;EAGF,KAAK;AACH,gBAAa,KAAK,MAAM;AACxB,OAAI,qBAAqB,KAAK,OAAO;AACnC,QAAI,CAAC,cACH,iBAAgB;KACd,cAAc;KACd,eAAe,KAAK,MAAM;KAC1B,cAAc,KAAK,MAAM;KAC1B;QAED,iBAAgB;KACd,GAAG;KACH,eACE,cAAc,gBAAgB,KAAK,MAAM;KAC3C,cACE,cAAc,eACd,cAAc,gBACd,KAAK,MAAM;KACd;AAEH,UAAM;KAAE,OAAO;KAAkB,OAAO;KAAe;;AAEzD,OACE,wBAAwB,KAAK,SAC7B,KAAK,MAAM,mBAEX,OAAM;IACJ,OAAO;IACP,UAAU;IACV,MAAM;IACN,SAAS,KAAK,MAAM;IACrB;AAEH;EAGF,KAAK;AACH,SAAM;IACJ,OAAO;IACP,QAAQ,cAAc,WAAW;IACjC,GAAI,gBAAgB,EAAE,OAAO,eAAe,GAAG,EAAE;IACjD,UAAU,EAAE,gBAAgB,aAAa;IAC1C;AACD;EAIF,KAAK,uBAAuB;GAC1B,M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;GACD,aAAa;IAAE,GAAG;IAAa,WAAW,MAAM;IAAW;GAC5D;EAEH,KAAK,mBACH,QAAO;GACL,cAAc;IACZ,MAAM;IACN,QAAQ;KACN,MAAM;KACN,OAAO;MAAE,GAAI,YAAY,SAAS,EAAE;MAAG,YAAY;MAAO;KAC3D;IACF;GACD,aAAa;IACX,GAAG;IACH,OAAO;KAAE,GAAI,YAAY,SAAS,EAAE;KAAG,YAAY;KAAO;IAC3D;GACF;EAEH,QACE,QAAO;GACL,cAAc;IACZ,MAAM;IACN,QAAQ;KAAE,MAAM,YAAY;KAAM,GAAG;KAAO;IAC7C;GACD;GACD;;;AAIP,SAAS,cAEP,aACc;AACd,KACE,YAAY,SAAS,qBACrB,YAAY,SAAS,0BACrB;EACA,MAAM,YACJ,YAAY,SAAS,oBAChB,cACA;EACP,IAAI;AACJ,MAAI;AACF,gBAAa,KAAK,MAAM,YAAY,QAAQ,KAAK;UAC3C;AACN,UAAO;IACL,MAAM;IACN,IAAI,YAAY;IAChB,MAAM,YAAY;IAClB,MAAM,YAAY;IAClB,OAAO;IACR;;AAEH,SAAO;GACL,MAAM;GACN,IAAI,YAAY;GAChB,MAAM,YAAY;GAClB,MAAM;GAEP;;CAGH,MAAM,EAAE,OAAO,QAAQ,GAAG,SAAS;AACnC,QAAO"}
1
+ {"version":3,"file":"stream_events.js","names":[],"sources":["../../src/utils/stream_events.ts"],"sourcesContent":["/**\n * Converts a raw Anthropic SSE event stream into LangChain ChatModelStreamEvents.\n *\n * @module\n */\n\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ChatModelStreamEvent,\n ContentBlockDelta,\n FinishReason,\n} from \"@langchain/core/language_models/event\";\nimport type { ContentBlock, UsageMetadata } from \"@langchain/core/messages\";\nimport type { AnthropicMessageStreamEvent } from \"../types.js\";\n\n// ─── Public API ─────────────────────────────────────────────────\n\nexport interface ConvertAnthropicStreamOptions {\n streamUsage?: boolean;\n}\n\n/**\n * Convert an async iterable of raw Anthropic stream events into\n * LangChain `ChatModelStreamEvent`s with typed deltas.\n */\nexport async function* convertAnthropicStream(\n source: AsyncIterable<AnthropicMessageStreamEvent>,\n options: ConvertAnthropicStreamOptions = {}\n): AsyncGenerator<ChatModelStreamEvent> {\n const shouldStreamUsage = options.streamUsage ?? true;\n\n // Track accumulated state per content block (for finalization)\n const blockAccumulators = new Map<\n number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n >();\n let usageSnapshot: UsageMetadata | undefined;\n let stopReason: string | null = null;\n\n for await (const data of source) {\n switch (data.type) {\n // ── Message lifecycle ──────────────────────────────────\n case \"message_start\": {\n const { usage, id, model } = data.message;\n if (usage && shouldStreamUsage) {\n usageSnapshot = buildUsageSnapshot(usage);\n }\n yield {\n event: \"message-start\" as const,\n id,\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n };\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"message_start\",\n payload: { model, id },\n };\n break;\n }\n\n case \"message_delta\": {\n stopReason = data.delta.stop_reason;\n if (shouldStreamUsage && data.usage) {\n if (!usageSnapshot) {\n usageSnapshot = {\n input_tokens: 0,\n output_tokens: data.usage.output_tokens,\n total_tokens: data.usage.output_tokens,\n };\n } else {\n usageSnapshot = {\n ...usageSnapshot,\n output_tokens:\n usageSnapshot.output_tokens + data.usage.output_tokens,\n total_tokens:\n usageSnapshot.input_tokens +\n usageSnapshot.output_tokens +\n data.usage.output_tokens,\n };\n }\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n if (\n \"context_management\" in data.delta &&\n data.delta.context_management\n ) {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: \"context_management\",\n payload: data.delta.context_management,\n };\n }\n break;\n }\n\n case \"message_stop\": {\n yield {\n event: \"message-finish\" as const,\n reason: mapStopReason(stopReason),\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n metadata: { model_provider: \"anthropic\" },\n };\n break;\n }\n\n // ── Content block lifecycle ───────────────────────────\n case \"content_block_start\": {\n const { index, content_block } = data;\n const mapped = mapBlockToContentBlock(content_block, index);\n blockAccumulators.set(index, { ...mapped });\n yield {\n event: \"content-block-start\" as const,\n index,\n content: mapped,\n };\n break;\n }\n\n case \"content_block_delta\": {\n const { index, delta } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const { contentDelta, accumulated } = applyAnthropicDelta(acc, delta);\n blockAccumulators.set(index, accumulated);\n\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: contentDelta,\n };\n break;\n }\n\n case \"content_block_stop\": {\n const { index } = data;\n const acc = blockAccumulators.get(index);\n if (!acc) break;\n\n const finalized = finalizeBlock(acc);\n yield {\n event: \"content-block-finish\" as const,\n index,\n content: finalized,\n };\n blockAccumulators.delete(index);\n break;\n }\n\n // ── Unhandled → provider passthrough ───────────────────\n default: {\n yield {\n event: \"provider\" as const,\n provider: \"anthropic\",\n name: data.type,\n payload: data,\n };\n break;\n }\n }\n }\n}\n\n// ─── Internal helpers ───────────────────────────────────────────\n\nfunction mapStopReason(stopReason: string | null | undefined): FinishReason {\n switch (stopReason) {\n case \"end_turn\":\n case \"stop_sequence\":\n return \"stop\";\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"length\";\n default:\n return \"stop\";\n }\n}\n\nfunction buildUsageSnapshot(\n usage: Anthropic.Messages.Usage | Record<string, number>\n): UsageMetadata {\n const cacheCreation =\n (usage as Record<string, number>).cache_creation_input_tokens ?? 0;\n const cacheRead =\n (usage as Record<string, number>).cache_read_input_tokens ?? 0;\n const totalInput = usage.input_tokens + cacheCreation + cacheRead;\n return {\n input_tokens: totalInput,\n output_tokens: usage.output_tokens,\n total_tokens: totalInput + usage.output_tokens,\n input_token_details: {\n cache_creation: cacheCreation,\n cache_read: cacheRead,\n },\n };\n}\n\nfunction mapBlockToContentBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n block: any,\n index: number\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n switch (block.type) {\n case \"text\":\n return { type: \"text\" as const, text: block.text ?? \"\", index };\n case \"thinking\":\n return {\n type: \"reasoning\" as const,\n reasoning: block.thinking ?? \"\",\n index,\n };\n case \"redacted_thinking\":\n return { type: \"non_standard\" as const, value: { ...block }, index };\n case \"tool_use\":\n return {\n type: \"tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n case \"server_tool_use\":\n return {\n type: \"server_tool_call_chunk\" as const,\n id: block.id,\n name: block.name,\n args: \"\",\n index,\n };\n default:\n return { type: \"non_standard\" as const, value: { ...block }, index };\n }\n}\n\n/**\n * Map an Anthropic content_block_delta to a content block delta\n * and update the accumulated state.\n */\nfunction applyAnthropicDelta(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n delta: any\n): {\n contentDelta: ContentBlockDelta;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>;\n} {\n switch (delta.type) {\n case \"text_delta\":\n return {\n contentDelta: { type: \"text-delta\" as const, text: delta.text },\n accumulated: {\n ...accumulated,\n text: (accumulated.text ?? \"\") + delta.text,\n },\n };\n\n case \"thinking_delta\":\n return {\n contentDelta: {\n type: \"reasoning-delta\" as const,\n reasoning: delta.thinking,\n },\n accumulated: {\n ...accumulated,\n reasoning: (accumulated.reasoning ?? \"\") + delta.thinking,\n },\n };\n\n case \"input_json_delta\": {\n const newArgs = (accumulated.args ?? \"\") + delta.partial_json;\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, args: newArgs },\n },\n accumulated: { ...accumulated, args: newArgs },\n };\n }\n\n case \"citations_delta\": {\n const annotations = [...(accumulated.annotations ?? []), delta.citation];\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: accumulated.type,\n annotations,\n },\n },\n accumulated: {\n ...accumulated,\n annotations,\n },\n };\n }\n\n case \"signature_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, signature: delta.signature },\n },\n accumulated: { ...accumulated, signature: delta.signature },\n };\n\n case \"compaction_delta\":\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: {\n type: \"non_standard\",\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n },\n accumulated: {\n ...accumulated,\n value: { ...(accumulated.value ?? {}), compaction: delta },\n },\n };\n\n default:\n return {\n contentDelta: {\n type: \"block-delta\" as const,\n fields: { type: accumulated.type, ...delta },\n },\n accumulated,\n };\n }\n}\n\nfunction finalizeBlock(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n accumulated: Record<string, any>\n): ContentBlock {\n if (\n accumulated.type === \"tool_call_chunk\" ||\n accumulated.type === \"server_tool_call_chunk\"\n ) {\n const finalType =\n accumulated.type === \"tool_call_chunk\"\n ? (\"tool_call\" as const)\n : (\"server_tool_call\" as const);\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(accumulated.args || \"{}\");\n } catch {\n return {\n type: \"invalid_tool_call\" as const,\n id: accumulated.id,\n name: accumulated.name,\n args: accumulated.args,\n error: \"Failed to parse tool call arguments as JSON\",\n } as ContentBlock.Tools.InvalidToolCall;\n }\n return {\n type: finalType,\n id: accumulated.id,\n name: accumulated.name,\n args: parsedArgs,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n\n const { index: _index, ...rest } = accumulated;\n return rest as ContentBlock;\n}\n"],"mappings":";;;;;AAyBA,gBAAuB,uBACrB,QACA,UAAyC,CAAC,GACJ;CACtC,MAAM,oBAAoB,QAAQ,eAAe;CAGjD,MAAM,oCAAoB,IAAI,IAI5B;CACF,IAAI;CACJ,IAAI,aAA4B;CAEhC,WAAW,MAAM,QAAQ,QACvB,QAAQ,KAAK,MAAb;EAEE,KAAK,iBAAiB;GACpB,MAAM,EAAE,OAAO,IAAI,UAAU,KAAK;GAClC,IAAI,SAAS,mBACX,gBA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Y;KAAM,GAAG;IAAM;GAC7C;GACA;EACF;CACJ;AACF;AAEA,SAAS,cAEP,aACc;CACd,IACE,YAAY,SAAS,qBACrB,YAAY,SAAS,0BACrB;EACA,MAAM,YACJ,YAAY,SAAS,oBAChB,cACA;EACP,IAAI;EACJ,IAAI;GACF,aAAa,KAAK,MAAM,YAAY,QAAQ,IAAI;EAClD,QAAQ;GACN,OAAO;IACL,MAAM;IACN,IAAI,YAAY;IAChB,MAAM,YAAY;IAClB,MAAM,YAAY;IAClB,OAAO;GACT;EACF;EACA,OAAO;GACL,MAAM;GACN,IAAI,YAAY;GAChB,MAAM,YAAY;GAClB,MAAM;EAER;CACF;CAEA,MAAM,EAAE,OAAO,QAAQ,GAAG,SAAS;CACnC,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"tools.cjs","names":["z"],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from \"@anthropic-ai/sdk\";\nimport * as z from \"zod/v4\";\nimport { AnthropicToolChoice } from \"../types.js\";\n\nexport function handleToolChoice(\n toolChoice?: AnthropicToolChoice\n):\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined {\n if (!toolChoice) {\n return undefined;\n } else if (toolChoice === \"any\" || toolChoice === \"required\") {\n // \"required\" is OpenAI-style, map to Anthropic's \"any\" which forces tool use\n return {\n type: \"any\",\n };\n } else if (toolChoice === \"auto\") {\n return {\n type: \"auto\",\n };\n } else if (toolChoice === \"none\") {\n return {\n type: \"none\",\n };\n } else if (typeof toolChoice === \"string\") {\n return {\n type: \"tool\",\n name: toolChoice,\n };\n } else {\n return toolChoice;\n }\n}\n\nexport const AnthropicToolExtrasSchema = z.object({\n cache_control: z\n .custom<Anthropic.Messages.CacheControlEphemeral>()\n .optional()\n .nullable(),\n defer_loading: z.boolean().optional(),\n input_examples: z.array(z.unknown()).optional(),\n allowed_callers: z.array(z.unknown()).optional(),\n strict: z.boolean().optional(),\n});\n\n/**\n * Mapping of Anthropic tool types to their required beta feature flags.\n *\n * This constant defines which beta header is needed for specific tool types\n * when making requests to the Anthropic API. Beta features are experimental\n * capabilities that may change or be removed.\n */\nexport const ANTHROPIC_TOOL_BETAS: Record<string, string> = {\n tool_search_tool_regex_20251119: \"advanced-tool-use-2025-11-20\",\n tool_search_tool_bm25_20251119: \"advanced-tool-use-2025-11-20\",\n memory_20250818: \"context-management-2025-06-27\",\n web_fetch_20250910: \"web-fetch-2025-09-10\",\n code_execution_20250825: \"code-execution-2025-08-25\",\n computer_20251124: \"computer-use-2025-11-24\",\n computer_20250124: \"computer-use-2025-01-24\",\n mcp_toolset: \"mcp-client-2025-11-20\",\n};\n"],"mappings":";;;;AAIA,SAAgB,iBACd,YAMY;AACZ,KAAI,CAAC,WACH;UACS,eAAe,SAAS,eAAe,WAEhD,QAAO,EACL,MAAM,OACP;UACQ,eAAe,OACxB,QAAO,EACL,MAAM,QACP;UACQ,eAAe,OACxB,QAAO,EACL,MAAM,QACP;UACQ,OAAO,eAAe,SAC/B,QAAO;EACL,MAAM;EACN,MAAM;EACP;KAED,QAAO;;AAIX,MAAa,4BAA4BA,OAAE,OAAO;CAChD,eAAeA,OACZ,QAAkD,CAClD,UAAU,CACV,UAAU;CACb,eAAeA,OAAE,SAAS,CAAC,UAAU;CACrC,gBAAgBA,OAAE,MAAMA,OAAE,SAAS,CAAC,CAAC,UAAU;CAC/C,iBAAiBA,OAAE,MAAMA,OAAE,SAAS,CAAC,CAAC,UAAU;CAChD,QAAQA,OAAE,SAAS,CAAC,UAAU;CAC/B,CAAC;;;;;;;;AASF,MAAa,uBAA+C;CAC1D,iCAAiC;CACjC,gCAAgC;CAChC,iBAAiB;CACjB,oBAAoB;CACpB,yBAAyB;CACzB,mBAAmB;CACnB,mBAAmB;CACnB,aAAa;CACd"}
1
+ {"version":3,"file":"tools.cjs","names":["z"],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from \"@anthropic-ai/sdk\";\nimport * as z from \"zod/v4\";\nimport { AnthropicToolChoice } from \"../types.js\";\n\nexport function handleToolChoice(\n toolChoice?: AnthropicToolChoice\n):\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined {\n if (!toolChoice) {\n return undefined;\n } else if (toolChoice === \"any\" || toolChoice === \"required\") {\n // \"required\" is OpenAI-style, map to Anthropic's \"any\" which forces tool use\n return {\n type: \"any\",\n };\n } else if (toolChoice === \"auto\") {\n return {\n type: \"auto\",\n };\n } else if (toolChoice === \"none\") {\n return {\n type: \"none\",\n };\n } else if (typeof toolChoice === \"string\") {\n return {\n type: \"tool\",\n name: toolChoice,\n };\n } else {\n return toolChoice;\n }\n}\n\nexport const AnthropicToolExtrasSchema = z.object({\n cache_control: z\n .custom<Anthropic.Messages.CacheControlEphemeral>()\n .optional()\n .nullable(),\n defer_loading: z.boolean().optional(),\n input_examples: z.array(z.unknown()).optional(),\n allowed_callers: z.array(z.unknown()).optional(),\n strict: z.boolean().optional(),\n});\n\n/**\n * Mapping of Anthropic tool types to their required beta feature flags.\n *\n * This constant defines which beta header is needed for specific tool types\n * when making requests to the Anthropic API. Beta features are experimental\n * capabilities that may change or be removed.\n */\nexport const ANTHROPIC_TOOL_BETAS: Record<string, string> = {\n tool_search_tool_regex_20251119: \"advanced-tool-use-2025-11-20\",\n tool_search_tool_bm25_20251119: \"advanced-tool-use-2025-11-20\",\n memory_20250818: \"context-management-2025-06-27\",\n web_fetch_20250910: \"web-fetch-2025-09-10\",\n code_execution_20250825: \"code-execution-2025-08-25\",\n computer_20251124: \"computer-use-2025-11-24\",\n computer_20250124: \"computer-use-2025-01-24\",\n mcp_toolset: \"mcp-client-2025-11-20\",\n};\n"],"mappings":";;;;AAIA,SAAgB,iBACd,YAMY;CACZ,IAAI,CAAC,YACH;MACK,IAAI,eAAe,SAAS,eAAe,YAEhD,OAAO,EACL,MAAM,MACR;MACK,IAAI,eAAe,QACxB,OAAO,EACL,MAAM,OACR;MACK,IAAI,eAAe,QACxB,OAAO,EACL,MAAM,OACR;MACK,IAAI,OAAO,eAAe,UAC/B,OAAO;EACL,MAAM;EACN,MAAM;CACR;MAEA,OAAO;AAEX;AAEA,MAAa,4BAA4BA,OAAE,OAAO;CAChD,eAAeA,OACZ,OAAiD,CAAC,CAClD,SAAS,CAAC,CACV,SAAS;CACZ,eAAeA,OAAE,QAAQ,CAAC,CAAC,SAAS;CACpC,gBAAgBA,OAAE,MAAMA,OAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;CAC9C,iBAAiBA,OAAE,MAAMA,OAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;CAC/C,QAAQA,OAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;;;;;;;;AASD,MAAa,uBAA+C;CAC1D,iCAAiC;CACjC,gCAAgC;CAChC,iBAAiB;CACjB,oBAAoB;CACpB,yBAAyB;CACzB,mBAAmB;CACnB,mBAAmB;CACnB,aAAa;AACf"}
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":["z"],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from \"@anthropic-ai/sdk\";\nimport * as z from \"zod/v4\";\nimport { AnthropicToolChoice } from \"../types.js\";\n\nexport function handleToolChoice(\n toolChoice?: AnthropicToolChoice\n):\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined {\n if (!toolChoice) {\n return undefined;\n } else if (toolChoice === \"any\" || toolChoice === \"required\") {\n // \"required\" is OpenAI-style, map to Anthropic's \"any\" which forces tool use\n return {\n type: \"any\",\n };\n } else if (toolChoice === \"auto\") {\n return {\n type: \"auto\",\n };\n } else if (toolChoice === \"none\") {\n return {\n type: \"none\",\n };\n } else if (typeof toolChoice === \"string\") {\n return {\n type: \"tool\",\n name: toolChoice,\n };\n } else {\n return toolChoice;\n }\n}\n\nexport const AnthropicToolExtrasSchema = z.object({\n cache_control: z\n .custom<Anthropic.Messages.CacheControlEphemeral>()\n .optional()\n .nullable(),\n defer_loading: z.boolean().optional(),\n input_examples: z.array(z.unknown()).optional(),\n allowed_callers: z.array(z.unknown()).optional(),\n strict: z.boolean().optional(),\n});\n\n/**\n * Mapping of Anthropic tool types to their required beta feature flags.\n *\n * This constant defines which beta header is needed for specific tool types\n * when making requests to the Anthropic API. Beta features are experimental\n * capabilities that may change or be removed.\n */\nexport const ANTHROPIC_TOOL_BETAS: Record<string, string> = {\n tool_search_tool_regex_20251119: \"advanced-tool-use-2025-11-20\",\n tool_search_tool_bm25_20251119: \"advanced-tool-use-2025-11-20\",\n memory_20250818: \"context-management-2025-06-27\",\n web_fetch_20250910: \"web-fetch-2025-09-10\",\n code_execution_20250825: \"code-execution-2025-08-25\",\n computer_20251124: \"computer-use-2025-11-24\",\n computer_20250124: \"computer-use-2025-01-24\",\n mcp_toolset: \"mcp-client-2025-11-20\",\n};\n"],"mappings":";;AAIA,SAAgB,iBACd,YAMY;AACZ,KAAI,CAAC,WACH;UACS,eAAe,SAAS,eAAe,WAEhD,QAAO,EACL,MAAM,OACP;UACQ,eAAe,OACxB,QAAO,EACL,MAAM,QACP;UACQ,eAAe,OACxB,QAAO,EACL,MAAM,QACP;UACQ,OAAO,eAAe,SAC/B,QAAO;EACL,MAAM;EACN,MAAM;EACP;KAED,QAAO;;AAIX,MAAa,4BAA4BA,IAAE,OAAO;CAChD,eAAeA,IACZ,QAAkD,CAClD,UAAU,CACV,UAAU;CACb,eAAeA,IAAE,SAAS,CAAC,UAAU;CACrC,gBAAgBA,IAAE,MAAMA,IAAE,SAAS,CAAC,CAAC,UAAU;CAC/C,iBAAiBA,IAAE,MAAMA,IAAE,SAAS,CAAC,CAAC,UAAU;CAChD,QAAQA,IAAE,SAAS,CAAC,UAAU;CAC/B,CAAC;;;;;;;;AASF,MAAa,uBAA+C;CAC1D,iCAAiC;CACjC,gCAAgC;CAChC,iBAAiB;CACjB,oBAAoB;CACpB,yBAAyB;CACzB,mBAAmB;CACnB,mBAAmB;CACnB,aAAa;CACd"}
1
+ {"version":3,"file":"tools.js","names":["z"],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from \"@anthropic-ai/sdk\";\nimport * as z from \"zod/v4\";\nimport { AnthropicToolChoice } from \"../types.js\";\n\nexport function handleToolChoice(\n toolChoice?: AnthropicToolChoice\n):\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined {\n if (!toolChoice) {\n return undefined;\n } else if (toolChoice === \"any\" || toolChoice === \"required\") {\n // \"required\" is OpenAI-style, map to Anthropic's \"any\" which forces tool use\n return {\n type: \"any\",\n };\n } else if (toolChoice === \"auto\") {\n return {\n type: \"auto\",\n };\n } else if (toolChoice === \"none\") {\n return {\n type: \"none\",\n };\n } else if (typeof toolChoice === \"string\") {\n return {\n type: \"tool\",\n name: toolChoice,\n };\n } else {\n return toolChoice;\n }\n}\n\nexport const AnthropicToolExtrasSchema = z.object({\n cache_control: z\n .custom<Anthropic.Messages.CacheControlEphemeral>()\n .optional()\n .nullable(),\n defer_loading: z.boolean().optional(),\n input_examples: z.array(z.unknown()).optional(),\n allowed_callers: z.array(z.unknown()).optional(),\n strict: z.boolean().optional(),\n});\n\n/**\n * Mapping of Anthropic tool types to their required beta feature flags.\n *\n * This constant defines which beta header is needed for specific tool types\n * when making requests to the Anthropic API. Beta features are experimental\n * capabilities that may change or be removed.\n */\nexport const ANTHROPIC_TOOL_BETAS: Record<string, string> = {\n tool_search_tool_regex_20251119: \"advanced-tool-use-2025-11-20\",\n tool_search_tool_bm25_20251119: \"advanced-tool-use-2025-11-20\",\n memory_20250818: \"context-management-2025-06-27\",\n web_fetch_20250910: \"web-fetch-2025-09-10\",\n code_execution_20250825: \"code-execution-2025-08-25\",\n computer_20251124: \"computer-use-2025-11-24\",\n computer_20250124: \"computer-use-2025-01-24\",\n mcp_toolset: \"mcp-client-2025-11-20\",\n};\n"],"mappings":";;AAIA,SAAgB,iBACd,YAMY;CACZ,IAAI,CAAC,YACH;MACK,IAAI,eAAe,SAAS,eAAe,YAEhD,OAAO,EACL,MAAM,MACR;MACK,IAAI,eAAe,QACxB,OAAO,EACL,MAAM,OACR;MACK,IAAI,eAAe,QACxB,OAAO,EACL,MAAM,OACR;MACK,IAAI,OAAO,eAAe,UAC/B,OAAO;EACL,MAAM;EACN,MAAM;CACR;MAEA,OAAO;AAEX;AAEA,MAAa,4BAA4BA,IAAE,OAAO;CAChD,eAAeA,IACZ,OAAiD,CAAC,CAClD,SAAS,CAAC,CACV,SAAS;CACZ,eAAeA,IAAE,QAAQ,CAAC,CAAC,SAAS;CACpC,gBAAgBA,IAAE,MAAMA,IAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;CAC9C,iBAAiBA,IAAE,MAAMA,IAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;CAC/C,QAAQA,IAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;;;;;;;;AASD,MAAa,uBAA+C;CAC1D,iCAAiC;CACjC,gCAAgC;CAChC,iBAAiB;CACjB,oBAAoB;CACpB,yBAAyB;CACzB,mBAAmB;CACnB,mBAAmB;CACnB,aAAa;AACf"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/anthropic",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
4
4
  "description": "Anthropic integrations for LangChain.js",
5
5
  "author": "LangChain",
6
6
  "license": "MIT",
@@ -14,25 +14,25 @@
14
14
  },
15
15
  "homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/providers/langchain-anthropic/",
16
16
  "dependencies": {
17
- "@anthropic-ai/sdk": "^0.103.0",
17
+ "@anthropic-ai/sdk": "^0.115.0",
18
18
  "zod": "^3.25.76 || ^4"
19
19
  },
20
20
  "peerDependencies": {
21
- "@langchain/core": "^1.2.1"
21
+ "@langchain/core": "^1.2.4"
22
22
  },
23
23
  "devDependencies": {
24
- "@anthropic-ai/vertex-sdk": "^0.16.1",
24
+ "@anthropic-ai/vertex-sdk": "^0.19.0",
25
25
  "@cfworker/json-schema": "^4.1.1",
26
26
  "@tsconfig/recommended": "^1.0.10",
27
- "@vitest/coverage-v8": "^4.1.8",
27
+ "@vitest/coverage-v8": "^4.1.10",
28
28
  "dotenv": "^17.4.0",
29
29
  "dpdm": "^3.14.0",
30
30
  "rimraf": "^6.1.3",
31
- "typescript": "~6.0.3",
31
+ "typescript": "~7.0.2",
32
32
  "vitest": "^4.1.8",
33
- "@langchain/core": "^1.2.1",
34
- "@langchain/standard-tests": "0.0.23",
35
- "@langchain/tsconfig": "0.0.1"
33
+ "@langchain/core": "^1.2.4",
34
+ "@langchain/tsconfig": "0.0.1",
35
+ "@langchain/standard-tests": "0.0.23"
36
36
  },
37
37
  "publishConfig": {
38
38
  "access": "public"