@langchain/core 1.1.47 → 1.1.49-dev-1781044436312
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.
- package/CHANGELOG.md +25 -0
- package/dist/callbacks/base.cjs +2 -3
- package/dist/callbacks/base.cjs.map +1 -1
- package/dist/callbacks/base.js +1 -2
- package/dist/callbacks/base.js.map +1 -1
- package/dist/callbacks/dispatch/index.cjs.map +1 -1
- package/dist/callbacks/dispatch/index.js.map +1 -1
- package/dist/callbacks/manager.cjs +7 -8
- package/dist/callbacks/manager.cjs.map +1 -1
- package/dist/callbacks/manager.js +1 -2
- package/dist/callbacks/manager.js.map +1 -1
- package/dist/example_selectors/conditional.cjs.map +1 -1
- package/dist/example_selectors/conditional.js.map +1 -1
- package/dist/example_selectors/length_based.cjs.map +1 -1
- package/dist/example_selectors/length_based.js.map +1 -1
- package/dist/example_selectors/semantic_similarity.cjs.map +1 -1
- package/dist/example_selectors/semantic_similarity.js.map +1 -1
- package/dist/indexing/base.cjs +3 -4
- package/dist/indexing/base.cjs.map +1 -1
- package/dist/indexing/base.js +1 -2
- package/dist/indexing/base.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/compat.cjs.map +1 -1
- package/dist/language_models/compat.js.map +1 -1
- package/dist/language_models/llms.cjs.map +1 -1
- package/dist/language_models/llms.js.map +1 -1
- package/dist/language_models/stream.cjs.map +1 -1
- package/dist/language_models/stream.js.map +1 -1
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.js.map +1 -1
- package/dist/memory.cjs.map +1 -1
- package/dist/memory.js.map +1 -1
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts +9 -0
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts +9 -0
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/block_translators/anthropic.cjs.map +1 -1
- package/dist/messages/block_translators/anthropic.js.map +1 -1
- package/dist/messages/block_translators/bedrock_converse.cjs.map +1 -1
- package/dist/messages/block_translators/bedrock_converse.js.map +1 -1
- package/dist/messages/block_translators/google.cjs.map +1 -1
- package/dist/messages/block_translators/google.js.map +1 -1
- package/dist/messages/block_translators/google_vertexai.cjs.map +1 -1
- package/dist/messages/block_translators/google_vertexai.js.map +1 -1
- package/dist/messages/block_translators/index.cjs +2 -0
- package/dist/messages/block_translators/index.cjs.map +1 -1
- package/dist/messages/block_translators/index.js +2 -0
- package/dist/messages/block_translators/index.js.map +1 -1
- package/dist/messages/block_translators/openai.cjs.map +1 -1
- package/dist/messages/block_translators/openai.js.map +1 -1
- package/dist/messages/block_translators/openrouter.cjs +101 -0
- package/dist/messages/block_translators/openrouter.cjs.map +1 -0
- package/dist/messages/block_translators/openrouter.js +101 -0
- package/dist/messages/block_translators/openrouter.js.map +1 -0
- package/dist/messages/index.d.cts +2 -2
- package/dist/messages/index.d.ts +2 -2
- package/dist/messages/modifier.cjs +6 -0
- package/dist/messages/modifier.cjs.map +1 -1
- package/dist/messages/modifier.d.cts +9 -4
- package/dist/messages/modifier.d.cts.map +1 -1
- package/dist/messages/modifier.d.ts +9 -4
- package/dist/messages/modifier.d.ts.map +1 -1
- package/dist/messages/modifier.js +6 -0
- package/dist/messages/modifier.js.map +1 -1
- package/dist/messages/transformers.cjs.map +1 -1
- package/dist/messages/transformers.js.map +1 -1
- package/dist/messages/utils.cjs +16 -2
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.d.cts +9 -1
- package/dist/messages/utils.d.cts.map +1 -1
- package/dist/messages/utils.d.ts +9 -1
- package/dist/messages/utils.d.ts.map +1 -1
- package/dist/messages/utils.js +16 -2
- package/dist/messages/utils.js.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.js.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/output_parsers/xml.cjs.map +1 -1
- package/dist/output_parsers/xml.js.map +1 -1
- package/dist/prompts/base.cjs.map +1 -1
- package/dist/prompts/base.js.map +1 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/image.cjs.map +1 -1
- package/dist/prompts/image.js.map +1 -1
- package/dist/prompts/prompt.cjs +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.d.cts +1 -1
- package/dist/prompts/prompt.d.ts +1 -1
- package/dist/prompts/prompt.js +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/string.cjs.map +1 -1
- package/dist/prompts/string.js.map +1 -1
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js.map +1 -1
- package/dist/retrievers/index.cjs.map +1 -1
- package/dist/retrievers/index.js.map +1 -1
- package/dist/runnables/base.cjs +2 -3
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js +1 -2
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/branch.cjs.map +1 -1
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/graph.cjs +6 -8
- package/dist/runnables/graph.cjs.map +1 -1
- package/dist/runnables/graph.js +1 -3
- package/dist/runnables/graph.js.map +1 -1
- package/dist/runnables/graph_mermaid.cjs.map +1 -1
- package/dist/runnables/graph_mermaid.js.map +1 -1
- package/dist/runnables/history.cjs.map +1 -1
- package/dist/runnables/history.js.map +1 -1
- package/dist/runnables/router.cjs.map +1 -1
- package/dist/runnables/router.js.map +1 -1
- package/dist/runnables/utils.cjs.map +1 -1
- package/dist/runnables/utils.js.map +1 -1
- package/dist/singletons/async_local_storage/context.cjs.map +1 -1
- package/dist/singletons/async_local_storage/context.js.map +1 -1
- package/dist/singletons/async_local_storage/index.cjs.map +1 -1
- package/dist/singletons/async_local_storage/index.js.map +1 -1
- package/dist/testing/fake_model_builder.cjs.map +1 -1
- package/dist/testing/fake_model_builder.js.map +1 -1
- package/dist/testing/matchers.cjs.map +1 -1
- package/dist/testing/matchers.js.map +1 -1
- package/dist/tracers/console.cjs.map +1 -1
- package/dist/tracers/console.js.map +1 -1
- package/dist/tracers/event_stream.cjs.map +1 -1
- package/dist/tracers/event_stream.js.map +1 -1
- package/dist/tracers/tracer_langchain.cjs.map +1 -1
- package/dist/tracers/tracer_langchain.js.map +1 -1
- package/dist/utils/callbacks.cjs.map +1 -1
- package/dist/utils/callbacks.js.map +1 -1
- package/dist/utils/context.cjs.map +1 -1
- package/dist/utils/context.js.map +1 -1
- package/dist/utils/env.cjs.map +1 -1
- package/dist/utils/env.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js.map +1 -1
- package/dist/utils/json_schema.cjs.map +1 -1
- package/dist/utils/json_schema.js.map +1 -1
- package/dist/utils/sax-js/sax.cjs.map +1 -1
- package/dist/utils/sax-js/sax.js.map +1 -1
- package/dist/utils/ssrf.cjs.map +1 -1
- package/dist/utils/ssrf.js.map +1 -1
- package/dist/utils/stream.d.cts +2 -2
- package/dist/utils/stream.d.cts.map +1 -1
- package/dist/utils/stream.d.ts +2 -2
- package/dist/utils/stream.d.ts.map +1 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/testing/embeddings.cjs.map +1 -1
- package/dist/utils/testing/embeddings.js.map +1 -1
- package/dist/utils/testing/vectorstores.cjs.map +1 -1
- package/dist/utils/testing/vectorstores.js.map +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/utils/uuid/index.cjs +33 -22
- package/dist/utils/uuid/index.cjs.map +1 -1
- package/dist/utils/uuid/index.d.cts +25 -12
- package/dist/utils/uuid/index.d.cts.map +1 -0
- package/dist/utils/uuid/index.d.ts +25 -12
- package/dist/utils/uuid/index.d.ts.map +1 -0
- package/dist/utils/uuid/index.js +23 -12
- package/dist/utils/uuid/index.js.map +1 -1
- package/dist/utils/uuid/v35.cjs.map +1 -1
- package/dist/utils/uuid/v35.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/pipeline.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/pipeline.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/set.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/set.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.cjs +26 -0
- package/dist/utils/zod-to-json-schema/parsers/string.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.js +26 -0
- package/dist/utils/zod-to-json-schema/parsers/string.js.map +1 -1
- package/dist/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/package.json +5 -5
- package/agents.cjs +0 -1
- package/agents.d.cts +0 -1
- package/agents.d.ts +0 -1
- package/agents.js +0 -1
- package/caches.cjs +0 -1
- package/caches.d.cts +0 -1
- package/caches.d.ts +0 -1
- package/caches.js +0 -1
- package/callbacks/base.cjs +0 -1
- package/callbacks/base.d.cts +0 -1
- package/callbacks/base.d.ts +0 -1
- package/callbacks/base.js +0 -1
- package/callbacks/dispatch/web.cjs +0 -1
- package/callbacks/dispatch/web.d.cts +0 -1
- package/callbacks/dispatch/web.d.ts +0 -1
- package/callbacks/dispatch/web.js +0 -1
- package/callbacks/dispatch.cjs +0 -1
- package/callbacks/dispatch.d.cts +0 -1
- package/callbacks/dispatch.d.ts +0 -1
- package/callbacks/dispatch.js +0 -1
- package/callbacks/manager.cjs +0 -1
- package/callbacks/manager.d.cts +0 -1
- package/callbacks/manager.d.ts +0 -1
- package/callbacks/manager.js +0 -1
- package/callbacks/promises.cjs +0 -1
- package/callbacks/promises.d.cts +0 -1
- package/callbacks/promises.d.ts +0 -1
- package/callbacks/promises.js +0 -1
- package/chat_history.cjs +0 -1
- package/chat_history.d.cts +0 -1
- package/chat_history.d.ts +0 -1
- package/chat_history.js +0 -1
- package/context.cjs +0 -1
- package/context.d.cts +0 -1
- package/context.d.ts +0 -1
- package/context.js +0 -1
- package/dist/utils/uuid/max.d.cts +0 -5
- package/dist/utils/uuid/max.d.cts.map +0 -1
- package/dist/utils/uuid/max.d.ts +0 -5
- package/dist/utils/uuid/max.d.ts.map +0 -1
- package/dist/utils/uuid/nil.d.cts +0 -5
- package/dist/utils/uuid/nil.d.cts.map +0 -1
- package/dist/utils/uuid/nil.d.ts +0 -5
- package/dist/utils/uuid/nil.d.ts.map +0 -1
- package/document_loaders/base.cjs +0 -1
- package/document_loaders/base.d.cts +0 -1
- package/document_loaders/base.d.ts +0 -1
- package/document_loaders/base.js +0 -1
- package/document_loaders/langsmith.cjs +0 -1
- package/document_loaders/langsmith.d.cts +0 -1
- package/document_loaders/langsmith.d.ts +0 -1
- package/document_loaders/langsmith.js +0 -1
- package/documents.cjs +0 -1
- package/documents.d.cts +0 -1
- package/documents.d.ts +0 -1
- package/documents.js +0 -1
- package/embeddings.cjs +0 -1
- package/embeddings.d.cts +0 -1
- package/embeddings.d.ts +0 -1
- package/embeddings.js +0 -1
- package/errors.cjs +0 -1
- package/errors.d.cts +0 -1
- package/errors.d.ts +0 -1
- package/errors.js +0 -1
- package/example_selectors.cjs +0 -1
- package/example_selectors.d.cts +0 -1
- package/example_selectors.d.ts +0 -1
- package/example_selectors.js +0 -1
- package/indexing.cjs +0 -1
- package/indexing.d.cts +0 -1
- package/indexing.d.ts +0 -1
- package/indexing.js +0 -1
- package/language_models/base.cjs +0 -1
- package/language_models/base.d.cts +0 -1
- package/language_models/base.d.ts +0 -1
- package/language_models/base.js +0 -1
- package/language_models/chat_models.cjs +0 -1
- package/language_models/chat_models.d.cts +0 -1
- package/language_models/chat_models.d.ts +0 -1
- package/language_models/chat_models.js +0 -1
- package/language_models/compat.cjs +0 -1
- package/language_models/compat.d.cts +0 -1
- package/language_models/compat.d.ts +0 -1
- package/language_models/compat.js +0 -1
- package/language_models/event.cjs +0 -1
- package/language_models/event.d.cts +0 -1
- package/language_models/event.d.ts +0 -1
- package/language_models/event.js +0 -1
- package/language_models/llms.cjs +0 -1
- package/language_models/llms.d.cts +0 -1
- package/language_models/llms.d.ts +0 -1
- package/language_models/llms.js +0 -1
- package/language_models/profile.cjs +0 -1
- package/language_models/profile.d.cts +0 -1
- package/language_models/profile.d.ts +0 -1
- package/language_models/profile.js +0 -1
- package/language_models/stream.cjs +0 -1
- package/language_models/stream.d.cts +0 -1
- package/language_models/stream.d.ts +0 -1
- package/language_models/stream.js +0 -1
- package/language_models/structured_output.cjs +0 -1
- package/language_models/structured_output.d.cts +0 -1
- package/language_models/structured_output.d.ts +0 -1
- package/language_models/structured_output.js +0 -1
- package/load/serializable.cjs +0 -1
- package/load/serializable.d.cts +0 -1
- package/load/serializable.d.ts +0 -1
- package/load/serializable.js +0 -1
- package/load.cjs +0 -1
- package/load.d.cts +0 -1
- package/load.d.ts +0 -1
- package/load.js +0 -1
- package/memory.cjs +0 -1
- package/memory.d.cts +0 -1
- package/memory.d.ts +0 -1
- package/memory.js +0 -1
- package/messages/tool.cjs +0 -1
- package/messages/tool.d.cts +0 -1
- package/messages/tool.d.ts +0 -1
- package/messages/tool.js +0 -1
- package/messages.cjs +0 -1
- package/messages.d.cts +0 -1
- package/messages.d.ts +0 -1
- package/messages.js +0 -1
- package/output_parsers/openai_functions.cjs +0 -1
- package/output_parsers/openai_functions.d.cts +0 -1
- package/output_parsers/openai_functions.d.ts +0 -1
- package/output_parsers/openai_functions.js +0 -1
- package/output_parsers/openai_tools.cjs +0 -1
- package/output_parsers/openai_tools.d.cts +0 -1
- package/output_parsers/openai_tools.d.ts +0 -1
- package/output_parsers/openai_tools.js +0 -1
- package/output_parsers.cjs +0 -1
- package/output_parsers.d.cts +0 -1
- package/output_parsers.d.ts +0 -1
- package/output_parsers.js +0 -1
- package/outputs.cjs +0 -1
- package/outputs.d.cts +0 -1
- package/outputs.d.ts +0 -1
- package/outputs.js +0 -1
- package/prompt_values.cjs +0 -1
- package/prompt_values.d.cts +0 -1
- package/prompt_values.d.ts +0 -1
- package/prompt_values.js +0 -1
- package/prompts.cjs +0 -1
- package/prompts.d.cts +0 -1
- package/prompts.d.ts +0 -1
- package/prompts.js +0 -1
- package/retrievers/document_compressors.cjs +0 -1
- package/retrievers/document_compressors.d.cts +0 -1
- package/retrievers/document_compressors.d.ts +0 -1
- package/retrievers/document_compressors.js +0 -1
- package/retrievers.cjs +0 -1
- package/retrievers.d.cts +0 -1
- package/retrievers.d.ts +0 -1
- package/retrievers.js +0 -1
- package/runnables/graph.cjs +0 -1
- package/runnables/graph.d.cts +0 -1
- package/runnables/graph.d.ts +0 -1
- package/runnables/graph.js +0 -1
- package/runnables.cjs +0 -1
- package/runnables.d.cts +0 -1
- package/runnables.d.ts +0 -1
- package/runnables.js +0 -1
- package/singletons.cjs +0 -1
- package/singletons.d.cts +0 -1
- package/singletons.d.ts +0 -1
- package/singletons.js +0 -1
- package/stores.cjs +0 -1
- package/stores.d.cts +0 -1
- package/stores.d.ts +0 -1
- package/stores.js +0 -1
- package/structured_query.cjs +0 -1
- package/structured_query.d.cts +0 -1
- package/structured_query.d.ts +0 -1
- package/structured_query.js +0 -1
- package/tools.cjs +0 -1
- package/tools.d.cts +0 -1
- package/tools.d.ts +0 -1
- package/tools.js +0 -1
- package/tracers/base.cjs +0 -1
- package/tracers/base.d.cts +0 -1
- package/tracers/base.d.ts +0 -1
- package/tracers/base.js +0 -1
- package/tracers/console.cjs +0 -1
- package/tracers/console.d.cts +0 -1
- package/tracers/console.d.ts +0 -1
- package/tracers/console.js +0 -1
- package/tracers/log_stream.cjs +0 -1
- package/tracers/log_stream.d.cts +0 -1
- package/tracers/log_stream.d.ts +0 -1
- package/tracers/log_stream.js +0 -1
- package/tracers/run_collector.cjs +0 -1
- package/tracers/run_collector.d.cts +0 -1
- package/tracers/run_collector.d.ts +0 -1
- package/tracers/run_collector.js +0 -1
- package/tracers/tracer_langchain.cjs +0 -1
- package/tracers/tracer_langchain.d.cts +0 -1
- package/tracers/tracer_langchain.d.ts +0 -1
- package/tracers/tracer_langchain.js +0 -1
- package/types/stream.cjs +0 -1
- package/types/stream.d.cts +0 -1
- package/types/stream.d.ts +0 -1
- package/types/stream.js +0 -1
- package/utils/async_caller.cjs +0 -1
- package/utils/async_caller.d.cts +0 -1
- package/utils/async_caller.d.ts +0 -1
- package/utils/async_caller.js +0 -1
- package/utils/chunk_array.cjs +0 -1
- package/utils/chunk_array.d.cts +0 -1
- package/utils/chunk_array.d.ts +0 -1
- package/utils/chunk_array.js +0 -1
- package/utils/context.cjs +0 -1
- package/utils/context.d.cts +0 -1
- package/utils/context.d.ts +0 -1
- package/utils/context.js +0 -1
- package/utils/env.cjs +0 -1
- package/utils/env.d.cts +0 -1
- package/utils/env.d.ts +0 -1
- package/utils/env.js +0 -1
- package/utils/event_source_parse.cjs +0 -1
- package/utils/event_source_parse.d.cts +0 -1
- package/utils/event_source_parse.d.ts +0 -1
- package/utils/event_source_parse.js +0 -1
- package/utils/format.cjs +0 -1
- package/utils/format.d.cts +0 -1
- package/utils/format.d.ts +0 -1
- package/utils/format.js +0 -1
- package/utils/function_calling.cjs +0 -1
- package/utils/function_calling.d.cts +0 -1
- package/utils/function_calling.d.ts +0 -1
- package/utils/function_calling.js +0 -1
- package/utils/hash.cjs +0 -1
- package/utils/hash.d.cts +0 -1
- package/utils/hash.d.ts +0 -1
- package/utils/hash.js +0 -1
- package/utils/json_patch.cjs +0 -1
- package/utils/json_patch.d.cts +0 -1
- package/utils/json_patch.d.ts +0 -1
- package/utils/json_patch.js +0 -1
- package/utils/json_schema.cjs +0 -1
- package/utils/json_schema.d.cts +0 -1
- package/utils/json_schema.d.ts +0 -1
- package/utils/json_schema.js +0 -1
- package/utils/math.cjs +0 -1
- package/utils/math.d.cts +0 -1
- package/utils/math.d.ts +0 -1
- package/utils/math.js +0 -1
- package/utils/ssrf.cjs +0 -1
- package/utils/ssrf.d.cts +0 -1
- package/utils/ssrf.d.ts +0 -1
- package/utils/ssrf.js +0 -1
- package/utils/standard_schema.cjs +0 -1
- package/utils/standard_schema.d.cts +0 -1
- package/utils/standard_schema.d.ts +0 -1
- package/utils/standard_schema.js +0 -1
- package/utils/stream.cjs +0 -1
- package/utils/stream.d.cts +0 -1
- package/utils/stream.d.ts +0 -1
- package/utils/stream.js +0 -1
- package/utils/testing.cjs +0 -1
- package/utils/testing.d.cts +0 -1
- package/utils/testing.d.ts +0 -1
- package/utils/testing.js +0 -1
- package/utils/tiktoken.cjs +0 -1
- package/utils/tiktoken.d.cts +0 -1
- package/utils/tiktoken.d.ts +0 -1
- package/utils/tiktoken.js +0 -1
- package/utils/types.cjs +0 -1
- package/utils/types.d.cts +0 -1
- package/utils/types.d.ts +0 -1
- package/utils/types.js +0 -1
- package/utils/uuid.cjs +0 -1
- package/utils/uuid.d.cts +0 -1
- package/utils/uuid.d.ts +0 -1
- package/utils/uuid.js +0 -1
- package/vectorstores.cjs +0 -1
- package/vectorstores.d.cts +0 -1
- package/vectorstores.d.ts +0 -1
- package/vectorstores.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.cjs","names":["isOpenAIDataBlock","convertToV1FromOpenAIDataBlock","_isObject","_isArray","_isString","_isContentBlock","iife"],"sources":["../../../src/messages/block_translators/openai.ts"],"sourcesContent":["import type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { convertToV1FromOpenAIDataBlock, isOpenAIDataBlock } from \"./data.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isObject,\n _isString,\n iife,\n} from \"./utils.js\";\n\n/**\n * Converts a ChatOpenAICompletions message to an array of v1 standard content blocks.\n *\n * This function processes an AI message from ChatOpenAICompletions API format\n * and converts it to the standardized v1 content block format. It handles both\n * string content and structured content blocks, as well as tool calls.\n *\n * @param message - The AI message containing ChatOpenAICompletions formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage(\"Hello world\");\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns: [{ type: \"text\", text: \"Hello world\" }]\n * ```\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ]);\n * message.tool_calls = [\n * { id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" },\n * // { type: \"tool_call\", id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletions(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk from OpenAI's chat completions API and converts\n * it to the standardized v1 content block format. It handles both string and array content,\n * as well as tool calls that may be present in the chunk.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage(\"Hello\");\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns: [{ type: \"text\", text: \"Hello\" }]\n * ```\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage([\n * { type: \"text\", text: \"Processing...\" }\n * ]);\n * chunk.tool_calls = [\n * { id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Processing...\" },\n * // { type: \"tool_call\", id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsChunk(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n\n // TODO: parse chunk position information\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks.\n *\n * This function processes content blocks from OpenAI's Chat Completions API format\n * and converts them to the standardized v1 content block format. It handles both\n * OpenAI-specific data blocks (which require conversion) and standard blocks\n * (which are passed through with type assertion).\n *\n * @param blocks - Array of content blocks in ChatOpenAICompletions format\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const openaiBlocks = [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsInput(\n blocks: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n const convertedBlocks: Array<ContentBlock.Standard> = [];\n for (const block of blocks) {\n if (isOpenAIDataBlock(block)) {\n convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));\n } else {\n convertedBlocks.push(block as ContentBlock.Standard);\n }\n }\n return convertedBlocks;\n}\n\nfunction convertResponsesAnnotation(\n annotation: ContentBlock\n): ContentBlock | ContentBlock.Citation {\n if (annotation.type === \"url_citation\") {\n const { url, title, start_index, end_index } = annotation;\n return {\n type: \"citation\",\n url,\n title,\n startIndex: start_index,\n endIndex: end_index,\n };\n }\n if (annotation.type === \"file_citation\") {\n const { file_id, filename, index } = annotation;\n return {\n type: \"citation\",\n title: filename,\n startIndex: index,\n endIndex: index,\n fileId: file_id,\n };\n }\n return annotation;\n}\n\n/**\n * Converts a ChatOpenAIResponses message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing OpenAI Responses-specific content blocks\n * and converts them to the standardized v1 content block format. It handles reasoning summaries,\n * text content with annotations, tool calls, and various tool outputs including code interpreter,\n * web search, file search, computer calls, and MCP-related blocks.\n *\n * @param message - The AI message containing OpenAI Responses-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: [{ type: \"text\", text: \"Hello world\", annotations: [] }],\n * tool_calls: [{ id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }],\n * additional_kwargs: {\n * reasoning: { summary: [{ text: \"Let me calculate this...\" }] },\n * tool_outputs: [\n * {\n * type: \"code_interpreter_call\",\n * code: \"print('hello')\",\n * outputs: [{ type: \"logs\", logs: \"hello\" }]\n * }\n * ]\n * }\n * });\n *\n * const standardBlocks = convertToV1FromResponses(message);\n * // Returns:\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me calculate this...\" },\n * // { type: \"text\", text: \"Hello world\", annotations: [] },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } },\n * // { type: \"code_interpreter_call\", code: \"print('hello')\" },\n * // { type: \"code_interpreter_result\", output: [{ type: \"code_interpreter_output\", returnCode: 0, stdout: \"hello\" }] }\n * // ]\n * ```\n */\nexport function convertToV1FromResponses(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n if (\n _isObject(message.additional_kwargs?.reasoning) &&\n _isArray(message.additional_kwargs.reasoning.summary)\n ) {\n const summary =\n message.additional_kwargs.reasoning.summary.reduce<string>(\n (acc, item) => {\n if (_isObject(item) && _isString(item.text)) {\n return `${acc}${item.text}`;\n }\n return acc;\n },\n \"\"\n );\n yield {\n type: \"reasoning\",\n reasoning: summary,\n };\n }\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n if (_isContentBlock(block, \"text\")) {\n const {\n text,\n annotations,\n phase,\n extras: existingExtras,\n ...rest\n } = block;\n const extras: Record<string, unknown> = _isObject(existingExtras)\n ? { ...(existingExtras as Record<string, unknown>) }\n : {};\n if (_isString(phase)) {\n extras.phase = phase;\n }\n const extrasSpread = Object.keys(extras).length > 0 ? { extras } : {};\n if (Array.isArray(annotations)) {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n annotations: annotations.map(convertResponsesAnnotation),\n };\n } else {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n };\n }\n }\n }\n for (const toolCall of message.tool_calls ?? []) {\n yield {\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n };\n }\n if (\n _isObject(message.additional_kwargs) &&\n _isArray(message.additional_kwargs.tool_outputs)\n ) {\n for (const toolOutput of message.additional_kwargs.tool_outputs) {\n if (_isContentBlock(toolOutput, \"web_search_call\")) {\n /**\n * Build args from available action data.\n * The ResponseFunctionWebSearch base type only has id, status, type.\n * The action field (with query, sources, etc.) may be present at\n * runtime when the `include` parameter includes \"web_search_call.action.sources\".\n */\n const webSearchArgs: Record<string, unknown> = {};\n if (\n _isObject(toolOutput.action) &&\n _isString(toolOutput.action.query)\n ) {\n webSearchArgs.query = toolOutput.action.query;\n }\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: webSearchArgs,\n };\n // Emit a server_tool_call_result when the search has completed or failed\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n const output: Record<string, unknown> = {};\n if (_isObject(toolOutput.action)) {\n output.action = toolOutput.action;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output,\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"file_search_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"file_search\",\n args: {\n queries: _isArray(toolOutput.queries) ? toolOutput.queries : [],\n },\n };\n // Emit a server_tool_call_result when results are available\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output: _isArray(toolOutput.results)\n ? { results: toolOutput.results }\n : {},\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"computer_call\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"code_interpreter_call\")) {\n if (_isString(toolOutput.code)) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"code_interpreter\",\n args: { code: toolOutput.code },\n };\n }\n if (_isArray(toolOutput.outputs)) {\n const returnCode = iife(() => {\n if (toolOutput.status === \"in_progress\") return undefined;\n if (toolOutput.status === \"completed\") return 0;\n if (toolOutput.status === \"incomplete\") return 127;\n if (toolOutput.status === \"interpreting\") return undefined;\n if (toolOutput.status === \"failed\") return 1;\n return undefined;\n });\n for (const output of toolOutput.outputs) {\n if (_isContentBlock(output, \"logs\")) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: toolOutput.id ?? \"\",\n status: \"success\",\n output: {\n type: \"code_interpreter_output\",\n returnCode: returnCode ?? 0,\n stderr: [0, undefined].includes(returnCode)\n ? undefined\n : String(output.logs),\n stdout: [0, undefined].includes(returnCode)\n ? String(output.logs)\n : undefined,\n },\n };\n continue;\n }\n }\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_call\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_list_tools\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_list_tools\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_approval_request\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_call\")) {\n const toolSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.arguments)) {\n Object.assign(toolSearchArgs, toolOutput.arguments);\n }\n const toolSearchCallExtras: Record<string, unknown> = {};\n if (_isString(toolOutput.execution)) {\n toolSearchCallExtras.execution = toolOutput.execution;\n }\n if (_isString(toolOutput.status)) {\n toolSearchCallExtras.status = toolOutput.status;\n }\n if (_isString(toolOutput.call_id)) {\n toolSearchCallExtras.call_id = toolOutput.call_id;\n }\n yield {\n id: _isString(toolOutput.id) ? toolOutput.id : \"\",\n type: \"server_tool_call\",\n name: \"tool_search\",\n args: toolSearchArgs,\n ...(Object.keys(toolSearchCallExtras).length > 0\n ? { extras: toolSearchCallExtras }\n : {}),\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_output\")) {\n const toolSearchOutputExtras: Record<string, unknown> = {\n name: \"tool_search\",\n };\n if (_isString(toolOutput.execution)) {\n toolSearchOutputExtras.execution = toolOutput.execution;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status:\n toolOutput.status === \"completed\"\n ? \"success\"\n : toolOutput.status === \"failed\"\n ? \"error\"\n : \"success\",\n output: {\n tools: _isArray(toolOutput.tools) ? toolOutput.tools : [],\n },\n extras: toolSearchOutputExtras,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"image_generation_call\")) {\n // Convert image_generation_call to proper image content block if result is available\n if (_isString(toolOutput.result)) {\n yield {\n type: \"image\",\n mimeType: \"image/png\",\n data: toolOutput.result,\n id: _isString(toolOutput.id) ? toolOutput.id : undefined,\n metadata: {\n status: _isString(toolOutput.status)\n ? toolOutput.status\n : undefined,\n },\n };\n }\n // Also yield as non_standard for backwards compatibility\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n }\n if (_isObject(toolOutput)) {\n yield { type: \"non_standard\", value: toolOutput };\n }\n }\n }\n }\n return Array.from(iterateContent());\n}\n\n/**\n * Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk containing OpenAI-specific content blocks\n * and converts them to the standardized v1 content block format. It handles both the\n * regular message content and tool call chunks that are specific to streaming responses.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const messageChunk = new AIMessageChunk({\n * content: [{ type: \"text\", text: \"Hello\" }],\n * tool_call_chunks: [\n * { id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * ]\n * });\n *\n * const standardBlocks = convertToV1FromResponsesChunk(messageChunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"tool_call_chunk\", id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * // ]\n * ```\n */\nexport function convertToV1FromResponsesChunk(\n message: AIMessageChunk\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n yield* convertToV1FromResponses(message);\n for (const toolCallChunk of message.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n args: toolCallChunk.args,\n };\n }\n }\n return Array.from(iterateContent());\n}\n\nexport const ChatOpenAITranslator: StandardContentBlockTranslator = {\n translateContent: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletions(message);\n }\n return convertToV1FromResponses(message);\n },\n translateContentChunk: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletionsChunk(message);\n }\n return convertToV1FromResponsesChunk(message);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,+BACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;AAC/C,KAAI,OAAO,QAAQ,YAAY;MAEzB,QAAQ,QAAQ,SAAS,EAC3B,QAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;GACf,CAAC;OAGJ,QAAO,KAAK,GAAG,oCAAoC,QAAQ,QAAQ,CAAC;AAEtE,MAAK,MAAM,YAAY,QAAQ,cAAc,EAAE,CAC7C,QAAO,KAAK;EACV,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS;EACf,MAAM,SAAS;EAChB,CAAC;AAEJ,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCT,SAAgB,oCACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;AAC/C,KAAI,OAAO,QAAQ,YAAY;MAEzB,QAAQ,QAAQ,SAAS,EAC3B,QAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;GACf,CAAC;OAGJ,QAAO,KAAK,GAAG,oC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AO,oCAAoC,QAAQ;AAErD,SAAO,8BAA8B,QAAQ;;CAEhD"}
|
|
1
|
+
{"version":3,"file":"openai.cjs","names":["isOpenAIDataBlock","convertToV1FromOpenAIDataBlock","_isObject","_isArray","_isString","_isContentBlock","iife"],"sources":["../../../src/messages/block_translators/openai.ts"],"sourcesContent":["import type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { convertToV1FromOpenAIDataBlock, isOpenAIDataBlock } from \"./data.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isObject,\n _isString,\n iife,\n} from \"./utils.js\";\n\n/**\n * Converts a ChatOpenAICompletions message to an array of v1 standard content blocks.\n *\n * This function processes an AI message from ChatOpenAICompletions API format\n * and converts it to the standardized v1 content block format. It handles both\n * string content and structured content blocks, as well as tool calls.\n *\n * @param message - The AI message containing ChatOpenAICompletions formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage(\"Hello world\");\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns: [{ type: \"text\", text: \"Hello world\" }]\n * ```\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ]);\n * message.tool_calls = [\n * { id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" },\n * // { type: \"tool_call\", id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletions(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk from OpenAI's chat completions API and converts\n * it to the standardized v1 content block format. It handles both string and array content,\n * as well as tool calls that may be present in the chunk.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage(\"Hello\");\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns: [{ type: \"text\", text: \"Hello\" }]\n * ```\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage([\n * { type: \"text\", text: \"Processing...\" }\n * ]);\n * chunk.tool_calls = [\n * { id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Processing...\" },\n * // { type: \"tool_call\", id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsChunk(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n\n // TODO: parse chunk position information\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks.\n *\n * This function processes content blocks from OpenAI's Chat Completions API format\n * and converts them to the standardized v1 content block format. It handles both\n * OpenAI-specific data blocks (which require conversion) and standard blocks\n * (which are passed through with type assertion).\n *\n * @param blocks - Array of content blocks in ChatOpenAICompletions format\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const openaiBlocks = [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsInput(\n blocks: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n const convertedBlocks: Array<ContentBlock.Standard> = [];\n for (const block of blocks) {\n if (isOpenAIDataBlock(block)) {\n convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));\n } else {\n convertedBlocks.push(block as ContentBlock.Standard);\n }\n }\n return convertedBlocks;\n}\n\nfunction convertResponsesAnnotation(\n annotation: ContentBlock\n): ContentBlock | ContentBlock.Citation {\n if (annotation.type === \"url_citation\") {\n const { url, title, start_index, end_index } = annotation;\n return {\n type: \"citation\",\n url,\n title,\n startIndex: start_index,\n endIndex: end_index,\n };\n }\n if (annotation.type === \"file_citation\") {\n const { file_id, filename, index } = annotation;\n return {\n type: \"citation\",\n title: filename,\n startIndex: index,\n endIndex: index,\n fileId: file_id,\n };\n }\n return annotation;\n}\n\n/**\n * Converts a ChatOpenAIResponses message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing OpenAI Responses-specific content blocks\n * and converts them to the standardized v1 content block format. It handles reasoning summaries,\n * text content with annotations, tool calls, and various tool outputs including code interpreter,\n * web search, file search, computer calls, and MCP-related blocks.\n *\n * @param message - The AI message containing OpenAI Responses-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: [{ type: \"text\", text: \"Hello world\", annotations: [] }],\n * tool_calls: [{ id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }],\n * additional_kwargs: {\n * reasoning: { summary: [{ text: \"Let me calculate this...\" }] },\n * tool_outputs: [\n * {\n * type: \"code_interpreter_call\",\n * code: \"print('hello')\",\n * outputs: [{ type: \"logs\", logs: \"hello\" }]\n * }\n * ]\n * }\n * });\n *\n * const standardBlocks = convertToV1FromResponses(message);\n * // Returns:\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me calculate this...\" },\n * // { type: \"text\", text: \"Hello world\", annotations: [] },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } },\n * // { type: \"code_interpreter_call\", code: \"print('hello')\" },\n * // { type: \"code_interpreter_result\", output: [{ type: \"code_interpreter_output\", returnCode: 0, stdout: \"hello\" }] }\n * // ]\n * ```\n */\nexport function convertToV1FromResponses(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n if (\n _isObject(message.additional_kwargs?.reasoning) &&\n _isArray(message.additional_kwargs.reasoning.summary)\n ) {\n const summary =\n message.additional_kwargs.reasoning.summary.reduce<string>(\n (acc, item) => {\n if (_isObject(item) && _isString(item.text)) {\n return `${acc}${item.text}`;\n }\n return acc;\n },\n \"\"\n );\n yield {\n type: \"reasoning\",\n reasoning: summary,\n };\n }\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n if (_isContentBlock(block, \"text\")) {\n const {\n text,\n annotations,\n phase,\n extras: existingExtras,\n ...rest\n } = block;\n const extras: Record<string, unknown> = _isObject(existingExtras)\n ? { ...(existingExtras as Record<string, unknown>) }\n : {};\n if (_isString(phase)) {\n extras.phase = phase;\n }\n const extrasSpread = Object.keys(extras).length > 0 ? { extras } : {};\n if (Array.isArray(annotations)) {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n annotations: annotations.map(convertResponsesAnnotation),\n };\n } else {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n };\n }\n }\n }\n for (const toolCall of message.tool_calls ?? []) {\n yield {\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n };\n }\n if (\n _isObject(message.additional_kwargs) &&\n _isArray(message.additional_kwargs.tool_outputs)\n ) {\n for (const toolOutput of message.additional_kwargs.tool_outputs) {\n if (_isContentBlock(toolOutput, \"web_search_call\")) {\n /**\n * Build args from available action data.\n * The ResponseFunctionWebSearch base type only has id, status, type.\n * The action field (with query, sources, etc.) may be present at\n * runtime when the `include` parameter includes \"web_search_call.action.sources\".\n */\n const webSearchArgs: Record<string, unknown> = {};\n if (\n _isObject(toolOutput.action) &&\n _isString(toolOutput.action.query)\n ) {\n webSearchArgs.query = toolOutput.action.query;\n }\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: webSearchArgs,\n };\n // Emit a server_tool_call_result when the search has completed or failed\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n const output: Record<string, unknown> = {};\n if (_isObject(toolOutput.action)) {\n output.action = toolOutput.action;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output,\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"file_search_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"file_search\",\n args: {\n queries: _isArray(toolOutput.queries) ? toolOutput.queries : [],\n },\n };\n // Emit a server_tool_call_result when results are available\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output: _isArray(toolOutput.results)\n ? { results: toolOutput.results }\n : {},\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"computer_call\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"code_interpreter_call\")) {\n if (_isString(toolOutput.code)) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"code_interpreter\",\n args: { code: toolOutput.code },\n };\n }\n if (_isArray(toolOutput.outputs)) {\n const returnCode = iife(() => {\n if (toolOutput.status === \"in_progress\") return undefined;\n if (toolOutput.status === \"completed\") return 0;\n if (toolOutput.status === \"incomplete\") return 127;\n if (toolOutput.status === \"interpreting\") return undefined;\n if (toolOutput.status === \"failed\") return 1;\n return undefined;\n });\n for (const output of toolOutput.outputs) {\n if (_isContentBlock(output, \"logs\")) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: toolOutput.id ?? \"\",\n status: \"success\",\n output: {\n type: \"code_interpreter_output\",\n returnCode: returnCode ?? 0,\n stderr: [0, undefined].includes(returnCode)\n ? undefined\n : String(output.logs),\n stdout: [0, undefined].includes(returnCode)\n ? String(output.logs)\n : undefined,\n },\n };\n continue;\n }\n }\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_call\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_list_tools\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_list_tools\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_approval_request\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_call\")) {\n const toolSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.arguments)) {\n Object.assign(toolSearchArgs, toolOutput.arguments);\n }\n const toolSearchCallExtras: Record<string, unknown> = {};\n if (_isString(toolOutput.execution)) {\n toolSearchCallExtras.execution = toolOutput.execution;\n }\n if (_isString(toolOutput.status)) {\n toolSearchCallExtras.status = toolOutput.status;\n }\n if (_isString(toolOutput.call_id)) {\n toolSearchCallExtras.call_id = toolOutput.call_id;\n }\n yield {\n id: _isString(toolOutput.id) ? toolOutput.id : \"\",\n type: \"server_tool_call\",\n name: \"tool_search\",\n args: toolSearchArgs,\n ...(Object.keys(toolSearchCallExtras).length > 0\n ? { extras: toolSearchCallExtras }\n : {}),\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_output\")) {\n const toolSearchOutputExtras: Record<string, unknown> = {\n name: \"tool_search\",\n };\n if (_isString(toolOutput.execution)) {\n toolSearchOutputExtras.execution = toolOutput.execution;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status:\n toolOutput.status === \"completed\"\n ? \"success\"\n : toolOutput.status === \"failed\"\n ? \"error\"\n : \"success\",\n output: {\n tools: _isArray(toolOutput.tools) ? toolOutput.tools : [],\n },\n extras: toolSearchOutputExtras,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"image_generation_call\")) {\n // Convert image_generation_call to proper image content block if result is available\n if (_isString(toolOutput.result)) {\n yield {\n type: \"image\",\n mimeType: \"image/png\",\n data: toolOutput.result,\n id: _isString(toolOutput.id) ? toolOutput.id : undefined,\n metadata: {\n status: _isString(toolOutput.status)\n ? toolOutput.status\n : undefined,\n },\n };\n }\n // Also yield as non_standard for backwards compatibility\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n }\n if (_isObject(toolOutput)) {\n yield { type: \"non_standard\", value: toolOutput };\n }\n }\n }\n }\n return Array.from(iterateContent());\n}\n\n/**\n * Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk containing OpenAI-specific content blocks\n * and converts them to the standardized v1 content block format. It handles both the\n * regular message content and tool call chunks that are specific to streaming responses.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const messageChunk = new AIMessageChunk({\n * content: [{ type: \"text\", text: \"Hello\" }],\n * tool_call_chunks: [\n * { id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * ]\n * });\n *\n * const standardBlocks = convertToV1FromResponsesChunk(messageChunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"tool_call_chunk\", id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * // ]\n * ```\n */\nexport function convertToV1FromResponsesChunk(\n message: AIMessageChunk\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n yield* convertToV1FromResponses(message);\n for (const toolCallChunk of message.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n args: toolCallChunk.args,\n };\n }\n }\n return Array.from(iterateContent());\n}\n\nexport const ChatOpenAITranslator: StandardContentBlockTranslator = {\n translateContent: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletions(message);\n }\n return convertToV1FromResponses(message);\n },\n translateContentChunk: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletionsChunk(message);\n }\n return convertToV1FromResponsesChunk(message);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,+BACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;AAC/C,KAAI,OAAO,QAAQ,YAAY;MAEzB,QAAQ,QAAQ,SAAS,EAC3B,QAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;GACf,CAAC;OAGJ,QAAO,KAAK,GAAG,oCAAoC,QAAQ,QAAQ,CAAC;AAEtE,MAAK,MAAM,YAAY,QAAQ,cAAc,EAAE,CAC7C,QAAO,KAAK;EACV,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS;EACf,MAAM,SAAS;EAChB,CAAC;AAEJ,QAAO;;;;;;;;;;;;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L,QAAO,MAAM,KAAK,gBAAgB,CAAC;;AAGrC,MAAa,uBAAuD;CAClE,mBAAmB,YAAY;AAC7B,MAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,+BAA+B,QAAQ;AAEhD,SAAO,yBAAyB,QAAQ;;CAE1C,wBAAwB,YAAY;AAClC,MAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,oCAAoC,QAAQ;AAErD,SAAO,8BAA8B,QAAQ;;CAEhD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.js","names":[],"sources":["../../../src/messages/block_translators/openai.ts"],"sourcesContent":["import type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { convertToV1FromOpenAIDataBlock, isOpenAIDataBlock } from \"./data.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isObject,\n _isString,\n iife,\n} from \"./utils.js\";\n\n/**\n * Converts a ChatOpenAICompletions message to an array of v1 standard content blocks.\n *\n * This function processes an AI message from ChatOpenAICompletions API format\n * and converts it to the standardized v1 content block format. It handles both\n * string content and structured content blocks, as well as tool calls.\n *\n * @param message - The AI message containing ChatOpenAICompletions formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage(\"Hello world\");\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns: [{ type: \"text\", text: \"Hello world\" }]\n * ```\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ]);\n * message.tool_calls = [\n * { id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" },\n * // { type: \"tool_call\", id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletions(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk from OpenAI's chat completions API and converts\n * it to the standardized v1 content block format. It handles both string and array content,\n * as well as tool calls that may be present in the chunk.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage(\"Hello\");\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns: [{ type: \"text\", text: \"Hello\" }]\n * ```\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage([\n * { type: \"text\", text: \"Processing...\" }\n * ]);\n * chunk.tool_calls = [\n * { id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Processing...\" },\n * // { type: \"tool_call\", id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsChunk(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n\n // TODO: parse chunk position information\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks.\n *\n * This function processes content blocks from OpenAI's Chat Completions API format\n * and converts them to the standardized v1 content block format. It handles both\n * OpenAI-specific data blocks (which require conversion) and standard blocks\n * (which are passed through with type assertion).\n *\n * @param blocks - Array of content blocks in ChatOpenAICompletions format\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const openaiBlocks = [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsInput(\n blocks: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n const convertedBlocks: Array<ContentBlock.Standard> = [];\n for (const block of blocks) {\n if (isOpenAIDataBlock(block)) {\n convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));\n } else {\n convertedBlocks.push(block as ContentBlock.Standard);\n }\n }\n return convertedBlocks;\n}\n\nfunction convertResponsesAnnotation(\n annotation: ContentBlock\n): ContentBlock | ContentBlock.Citation {\n if (annotation.type === \"url_citation\") {\n const { url, title, start_index, end_index } = annotation;\n return {\n type: \"citation\",\n url,\n title,\n startIndex: start_index,\n endIndex: end_index,\n };\n }\n if (annotation.type === \"file_citation\") {\n const { file_id, filename, index } = annotation;\n return {\n type: \"citation\",\n title: filename,\n startIndex: index,\n endIndex: index,\n fileId: file_id,\n };\n }\n return annotation;\n}\n\n/**\n * Converts a ChatOpenAIResponses message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing OpenAI Responses-specific content blocks\n * and converts them to the standardized v1 content block format. It handles reasoning summaries,\n * text content with annotations, tool calls, and various tool outputs including code interpreter,\n * web search, file search, computer calls, and MCP-related blocks.\n *\n * @param message - The AI message containing OpenAI Responses-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: [{ type: \"text\", text: \"Hello world\", annotations: [] }],\n * tool_calls: [{ id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }],\n * additional_kwargs: {\n * reasoning: { summary: [{ text: \"Let me calculate this...\" }] },\n * tool_outputs: [\n * {\n * type: \"code_interpreter_call\",\n * code: \"print('hello')\",\n * outputs: [{ type: \"logs\", logs: \"hello\" }]\n * }\n * ]\n * }\n * });\n *\n * const standardBlocks = convertToV1FromResponses(message);\n * // Returns:\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me calculate this...\" },\n * // { type: \"text\", text: \"Hello world\", annotations: [] },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } },\n * // { type: \"code_interpreter_call\", code: \"print('hello')\" },\n * // { type: \"code_interpreter_result\", output: [{ type: \"code_interpreter_output\", returnCode: 0, stdout: \"hello\" }] }\n * // ]\n * ```\n */\nexport function convertToV1FromResponses(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n if (\n _isObject(message.additional_kwargs?.reasoning) &&\n _isArray(message.additional_kwargs.reasoning.summary)\n ) {\n const summary =\n message.additional_kwargs.reasoning.summary.reduce<string>(\n (acc, item) => {\n if (_isObject(item) && _isString(item.text)) {\n return `${acc}${item.text}`;\n }\n return acc;\n },\n \"\"\n );\n yield {\n type: \"reasoning\",\n reasoning: summary,\n };\n }\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n if (_isContentBlock(block, \"text\")) {\n const {\n text,\n annotations,\n phase,\n extras: existingExtras,\n ...rest\n } = block;\n const extras: Record<string, unknown> = _isObject(existingExtras)\n ? { ...(existingExtras as Record<string, unknown>) }\n : {};\n if (_isString(phase)) {\n extras.phase = phase;\n }\n const extrasSpread = Object.keys(extras).length > 0 ? { extras } : {};\n if (Array.isArray(annotations)) {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n annotations: annotations.map(convertResponsesAnnotation),\n };\n } else {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n };\n }\n }\n }\n for (const toolCall of message.tool_calls ?? []) {\n yield {\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n };\n }\n if (\n _isObject(message.additional_kwargs) &&\n _isArray(message.additional_kwargs.tool_outputs)\n ) {\n for (const toolOutput of message.additional_kwargs.tool_outputs) {\n if (_isContentBlock(toolOutput, \"web_search_call\")) {\n /**\n * Build args from available action data.\n * The ResponseFunctionWebSearch base type only has id, status, type.\n * The action field (with query, sources, etc.) may be present at\n * runtime when the `include` parameter includes \"web_search_call.action.sources\".\n */\n const webSearchArgs: Record<string, unknown> = {};\n if (\n _isObject(toolOutput.action) &&\n _isString(toolOutput.action.query)\n ) {\n webSearchArgs.query = toolOutput.action.query;\n }\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: webSearchArgs,\n };\n // Emit a server_tool_call_result when the search has completed or failed\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n const output: Record<string, unknown> = {};\n if (_isObject(toolOutput.action)) {\n output.action = toolOutput.action;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output,\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"file_search_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"file_search\",\n args: {\n queries: _isArray(toolOutput.queries) ? toolOutput.queries : [],\n },\n };\n // Emit a server_tool_call_result when results are available\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output: _isArray(toolOutput.results)\n ? { results: toolOutput.results }\n : {},\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"computer_call\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"code_interpreter_call\")) {\n if (_isString(toolOutput.code)) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"code_interpreter\",\n args: { code: toolOutput.code },\n };\n }\n if (_isArray(toolOutput.outputs)) {\n const returnCode = iife(() => {\n if (toolOutput.status === \"in_progress\") return undefined;\n if (toolOutput.status === \"completed\") return 0;\n if (toolOutput.status === \"incomplete\") return 127;\n if (toolOutput.status === \"interpreting\") return undefined;\n if (toolOutput.status === \"failed\") return 1;\n return undefined;\n });\n for (const output of toolOutput.outputs) {\n if (_isContentBlock(output, \"logs\")) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: toolOutput.id ?? \"\",\n status: \"success\",\n output: {\n type: \"code_interpreter_output\",\n returnCode: returnCode ?? 0,\n stderr: [0, undefined].includes(returnCode)\n ? undefined\n : String(output.logs),\n stdout: [0, undefined].includes(returnCode)\n ? String(output.logs)\n : undefined,\n },\n };\n continue;\n }\n }\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_call\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_list_tools\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_list_tools\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_approval_request\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_call\")) {\n const toolSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.arguments)) {\n Object.assign(toolSearchArgs, toolOutput.arguments);\n }\n const toolSearchCallExtras: Record<string, unknown> = {};\n if (_isString(toolOutput.execution)) {\n toolSearchCallExtras.execution = toolOutput.execution;\n }\n if (_isString(toolOutput.status)) {\n toolSearchCallExtras.status = toolOutput.status;\n }\n if (_isString(toolOutput.call_id)) {\n toolSearchCallExtras.call_id = toolOutput.call_id;\n }\n yield {\n id: _isString(toolOutput.id) ? toolOutput.id : \"\",\n type: \"server_tool_call\",\n name: \"tool_search\",\n args: toolSearchArgs,\n ...(Object.keys(toolSearchCallExtras).length > 0\n ? { extras: toolSearchCallExtras }\n : {}),\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_output\")) {\n const toolSearchOutputExtras: Record<string, unknown> = {\n name: \"tool_search\",\n };\n if (_isString(toolOutput.execution)) {\n toolSearchOutputExtras.execution = toolOutput.execution;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status:\n toolOutput.status === \"completed\"\n ? \"success\"\n : toolOutput.status === \"failed\"\n ? \"error\"\n : \"success\",\n output: {\n tools: _isArray(toolOutput.tools) ? toolOutput.tools : [],\n },\n extras: toolSearchOutputExtras,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"image_generation_call\")) {\n // Convert image_generation_call to proper image content block if result is available\n if (_isString(toolOutput.result)) {\n yield {\n type: \"image\",\n mimeType: \"image/png\",\n data: toolOutput.result,\n id: _isString(toolOutput.id) ? toolOutput.id : undefined,\n metadata: {\n status: _isString(toolOutput.status)\n ? toolOutput.status\n : undefined,\n },\n };\n }\n // Also yield as non_standard for backwards compatibility\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n }\n if (_isObject(toolOutput)) {\n yield { type: \"non_standard\", value: toolOutput };\n }\n }\n }\n }\n return Array.from(iterateContent());\n}\n\n/**\n * Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk containing OpenAI-specific content blocks\n * and converts them to the standardized v1 content block format. It handles both the\n * regular message content and tool call chunks that are specific to streaming responses.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const messageChunk = new AIMessageChunk({\n * content: [{ type: \"text\", text: \"Hello\" }],\n * tool_call_chunks: [\n * { id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * ]\n * });\n *\n * const standardBlocks = convertToV1FromResponsesChunk(messageChunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"tool_call_chunk\", id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * // ]\n * ```\n */\nexport function convertToV1FromResponsesChunk(\n message: AIMessageChunk\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n yield* convertToV1FromResponses(message);\n for (const toolCallChunk of message.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n args: toolCallChunk.args,\n };\n }\n }\n return Array.from(iterateContent());\n}\n\nexport const ChatOpenAITranslator: StandardContentBlockTranslator = {\n translateContent: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletions(message);\n }\n return convertToV1FromResponses(message);\n },\n translateContentChunk: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletionsChunk(message);\n }\n return convertToV1FromResponsesChunk(message);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,+BACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;AAC/C,KAAI,OAAO,QAAQ,YAAY;MAEzB,QAAQ,QAAQ,SAAS,EAC3B,QAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;GACf,CAAC;OAGJ,QAAO,KAAK,GAAG,oCAAoC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wBAAwB,YAAY;AAClC,MAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,oCAAoC,QAAQ;AAErD,SAAO,8BAA8B,QAAQ;;CAEhD"}
|
|
1
|
+
{"version":3,"file":"openai.js","names":[],"sources":["../../../src/messages/block_translators/openai.ts"],"sourcesContent":["import type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { convertToV1FromOpenAIDataBlock, isOpenAIDataBlock } from \"./data.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isObject,\n _isString,\n iife,\n} from \"./utils.js\";\n\n/**\n * Converts a ChatOpenAICompletions message to an array of v1 standard content blocks.\n *\n * This function processes an AI message from ChatOpenAICompletions API format\n * and converts it to the standardized v1 content block format. It handles both\n * string content and structured content blocks, as well as tool calls.\n *\n * @param message - The AI message containing ChatOpenAICompletions formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage(\"Hello world\");\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns: [{ type: \"text\", text: \"Hello world\" }]\n * ```\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ]);\n * message.tool_calls = [\n * { id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" },\n * // { type: \"tool_call\", id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletions(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk from OpenAI's chat completions API and converts\n * it to the standardized v1 content block format. It handles both string and array content,\n * as well as tool calls that may be present in the chunk.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage(\"Hello\");\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns: [{ type: \"text\", text: \"Hello\" }]\n * ```\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage([\n * { type: \"text\", text: \"Processing...\" }\n * ]);\n * chunk.tool_calls = [\n * { id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Processing...\" },\n * // { type: \"tool_call\", id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsChunk(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n\n // TODO: parse chunk position information\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks.\n *\n * This function processes content blocks from OpenAI's Chat Completions API format\n * and converts them to the standardized v1 content block format. It handles both\n * OpenAI-specific data blocks (which require conversion) and standard blocks\n * (which are passed through with type assertion).\n *\n * @param blocks - Array of content blocks in ChatOpenAICompletions format\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const openaiBlocks = [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsInput(\n blocks: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n const convertedBlocks: Array<ContentBlock.Standard> = [];\n for (const block of blocks) {\n if (isOpenAIDataBlock(block)) {\n convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));\n } else {\n convertedBlocks.push(block as ContentBlock.Standard);\n }\n }\n return convertedBlocks;\n}\n\nfunction convertResponsesAnnotation(\n annotation: ContentBlock\n): ContentBlock | ContentBlock.Citation {\n if (annotation.type === \"url_citation\") {\n const { url, title, start_index, end_index } = annotation;\n return {\n type: \"citation\",\n url,\n title,\n startIndex: start_index,\n endIndex: end_index,\n };\n }\n if (annotation.type === \"file_citation\") {\n const { file_id, filename, index } = annotation;\n return {\n type: \"citation\",\n title: filename,\n startIndex: index,\n endIndex: index,\n fileId: file_id,\n };\n }\n return annotation;\n}\n\n/**\n * Converts a ChatOpenAIResponses message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing OpenAI Responses-specific content blocks\n * and converts them to the standardized v1 content block format. It handles reasoning summaries,\n * text content with annotations, tool calls, and various tool outputs including code interpreter,\n * web search, file search, computer calls, and MCP-related blocks.\n *\n * @param message - The AI message containing OpenAI Responses-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: [{ type: \"text\", text: \"Hello world\", annotations: [] }],\n * tool_calls: [{ id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }],\n * additional_kwargs: {\n * reasoning: { summary: [{ text: \"Let me calculate this...\" }] },\n * tool_outputs: [\n * {\n * type: \"code_interpreter_call\",\n * code: \"print('hello')\",\n * outputs: [{ type: \"logs\", logs: \"hello\" }]\n * }\n * ]\n * }\n * });\n *\n * const standardBlocks = convertToV1FromResponses(message);\n * // Returns:\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me calculate this...\" },\n * // { type: \"text\", text: \"Hello world\", annotations: [] },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } },\n * // { type: \"code_interpreter_call\", code: \"print('hello')\" },\n * // { type: \"code_interpreter_result\", output: [{ type: \"code_interpreter_output\", returnCode: 0, stdout: \"hello\" }] }\n * // ]\n * ```\n */\nexport function convertToV1FromResponses(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n if (\n _isObject(message.additional_kwargs?.reasoning) &&\n _isArray(message.additional_kwargs.reasoning.summary)\n ) {\n const summary =\n message.additional_kwargs.reasoning.summary.reduce<string>(\n (acc, item) => {\n if (_isObject(item) && _isString(item.text)) {\n return `${acc}${item.text}`;\n }\n return acc;\n },\n \"\"\n );\n yield {\n type: \"reasoning\",\n reasoning: summary,\n };\n }\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n if (_isContentBlock(block, \"text\")) {\n const {\n text,\n annotations,\n phase,\n extras: existingExtras,\n ...rest\n } = block;\n const extras: Record<string, unknown> = _isObject(existingExtras)\n ? { ...(existingExtras as Record<string, unknown>) }\n : {};\n if (_isString(phase)) {\n extras.phase = phase;\n }\n const extrasSpread = Object.keys(extras).length > 0 ? { extras } : {};\n if (Array.isArray(annotations)) {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n annotations: annotations.map(convertResponsesAnnotation),\n };\n } else {\n yield {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n };\n }\n }\n }\n for (const toolCall of message.tool_calls ?? []) {\n yield {\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n };\n }\n if (\n _isObject(message.additional_kwargs) &&\n _isArray(message.additional_kwargs.tool_outputs)\n ) {\n for (const toolOutput of message.additional_kwargs.tool_outputs) {\n if (_isContentBlock(toolOutput, \"web_search_call\")) {\n /**\n * Build args from available action data.\n * The ResponseFunctionWebSearch base type only has id, status, type.\n * The action field (with query, sources, etc.) may be present at\n * runtime when the `include` parameter includes \"web_search_call.action.sources\".\n */\n const webSearchArgs: Record<string, unknown> = {};\n if (\n _isObject(toolOutput.action) &&\n _isString(toolOutput.action.query)\n ) {\n webSearchArgs.query = toolOutput.action.query;\n }\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: webSearchArgs,\n };\n // Emit a server_tool_call_result when the search has completed or failed\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n const output: Record<string, unknown> = {};\n if (_isObject(toolOutput.action)) {\n output.action = toolOutput.action;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output,\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"file_search_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"file_search\",\n args: {\n queries: _isArray(toolOutput.queries) ? toolOutput.queries : [],\n },\n };\n // Emit a server_tool_call_result when results are available\n if (\n toolOutput.status === \"completed\" ||\n toolOutput.status === \"failed\"\n ) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output: _isArray(toolOutput.results)\n ? { results: toolOutput.results }\n : {},\n };\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"computer_call\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"code_interpreter_call\")) {\n if (_isString(toolOutput.code)) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"code_interpreter\",\n args: { code: toolOutput.code },\n };\n }\n if (_isArray(toolOutput.outputs)) {\n const returnCode = iife(() => {\n if (toolOutput.status === \"in_progress\") return undefined;\n if (toolOutput.status === \"completed\") return 0;\n if (toolOutput.status === \"incomplete\") return 127;\n if (toolOutput.status === \"interpreting\") return undefined;\n if (toolOutput.status === \"failed\") return 1;\n return undefined;\n });\n for (const output of toolOutput.outputs) {\n if (_isContentBlock(output, \"logs\")) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: toolOutput.id ?? \"\",\n status: \"success\",\n output: {\n type: \"code_interpreter_output\",\n returnCode: returnCode ?? 0,\n stderr: [0, undefined].includes(returnCode)\n ? undefined\n : String(output.logs),\n stdout: [0, undefined].includes(returnCode)\n ? String(output.logs)\n : undefined,\n },\n };\n continue;\n }\n }\n }\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_call\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_list_tools\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_list_tools\",\n args: toolOutput.input,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"mcp_approval_request\")) {\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_call\")) {\n const toolSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.arguments)) {\n Object.assign(toolSearchArgs, toolOutput.arguments);\n }\n const toolSearchCallExtras: Record<string, unknown> = {};\n if (_isString(toolOutput.execution)) {\n toolSearchCallExtras.execution = toolOutput.execution;\n }\n if (_isString(toolOutput.status)) {\n toolSearchCallExtras.status = toolOutput.status;\n }\n if (_isString(toolOutput.call_id)) {\n toolSearchCallExtras.call_id = toolOutput.call_id;\n }\n yield {\n id: _isString(toolOutput.id) ? toolOutput.id : \"\",\n type: \"server_tool_call\",\n name: \"tool_search\",\n args: toolSearchArgs,\n ...(Object.keys(toolSearchCallExtras).length > 0\n ? { extras: toolSearchCallExtras }\n : {}),\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"tool_search_output\")) {\n const toolSearchOutputExtras: Record<string, unknown> = {\n name: \"tool_search\",\n };\n if (_isString(toolOutput.execution)) {\n toolSearchOutputExtras.execution = toolOutput.execution;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status:\n toolOutput.status === \"completed\"\n ? \"success\"\n : toolOutput.status === \"failed\"\n ? \"error\"\n : \"success\",\n output: {\n tools: _isArray(toolOutput.tools) ? toolOutput.tools : [],\n },\n extras: toolSearchOutputExtras,\n };\n continue;\n } else if (_isContentBlock(toolOutput, \"image_generation_call\")) {\n // Convert image_generation_call to proper image content block if result is available\n if (_isString(toolOutput.result)) {\n yield {\n type: \"image\",\n mimeType: \"image/png\",\n data: toolOutput.result,\n id: _isString(toolOutput.id) ? toolOutput.id : undefined,\n metadata: {\n status: _isString(toolOutput.status)\n ? toolOutput.status\n : undefined,\n },\n };\n }\n // Also yield as non_standard for backwards compatibility\n yield { type: \"non_standard\", value: toolOutput };\n continue;\n }\n if (_isObject(toolOutput)) {\n yield { type: \"non_standard\", value: toolOutput };\n }\n }\n }\n }\n return Array.from(iterateContent());\n}\n\n/**\n * Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk containing OpenAI-specific content blocks\n * and converts them to the standardized v1 content block format. It handles both the\n * regular message content and tool call chunks that are specific to streaming responses.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const messageChunk = new AIMessageChunk({\n * content: [{ type: \"text\", text: \"Hello\" }],\n * tool_call_chunks: [\n * { id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * ]\n * });\n *\n * const standardBlocks = convertToV1FromResponsesChunk(messageChunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"tool_call_chunk\", id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * // ]\n * ```\n */\nexport function convertToV1FromResponsesChunk(\n message: AIMessageChunk\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n yield* convertToV1FromResponses(message);\n for (const toolCallChunk of message.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n args: toolCallChunk.args,\n };\n }\n }\n return Array.from(iterateContent());\n}\n\nexport const ChatOpenAITranslator: StandardContentBlockTranslator = {\n translateContent: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletions(message);\n }\n return convertToV1FromResponses(message);\n },\n translateContentChunk: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletionsChunk(message);\n }\n return convertToV1FromResponsesChunk(message);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,+BACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;AAC/C,KAAI,OAAO,QAAQ,YAAY;MAEzB,QAAQ,QAAQ,SAAS,EAC3B,QAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;GACf,CAAC;OAGJ,QAAO,KAAK,GAAG,oCAAoC,QAAQ,QAAQ,CAAC;AAEtE,MAAK,MAAM,YAAY,QAAQ,cAAc,EAAE,CAC7C,QAAO,KAAK;EACV,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS;EACf,MAAM,SAAS;EAChB,CAAC;AAEJ,QAAO;;;;;;;;;;;;;;;;;;;;;;;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translators/openrouter.ts
|
|
3
|
+
/**
|
|
4
|
+
* Converts an OpenRouter AI message to an array of v1 standard content blocks.
|
|
5
|
+
*
|
|
6
|
+
* OpenRouter returns reasoning output through two places on the Chat
|
|
7
|
+
* Completions response:
|
|
8
|
+
*
|
|
9
|
+
* 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes
|
|
10
|
+
* the model's chain of thought. The `@langchain/openrouter` converter
|
|
11
|
+
* normalizes this into `additional_kwargs.reasoning_content` so it matches
|
|
12
|
+
* the DeepSeek convention already used elsewhere in LangChain.
|
|
13
|
+
* 2. `message.reasoning_details` / `delta.reasoning_details` — a structured
|
|
14
|
+
* array of provider-specific reasoning artifacts (see the
|
|
15
|
+
* `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in
|
|
16
|
+
* the OpenRouter API types). The converter preserves these verbatim under
|
|
17
|
+
* `additional_kwargs.reasoning_details` for round-tripping back to the
|
|
18
|
+
* provider on subsequent turns (e.g. Anthropic extended thinking requires
|
|
19
|
+
* the original `signature` to be echoed back).
|
|
20
|
+
*
|
|
21
|
+
* When `reasoning_details` is present, visible blocks are emitted from
|
|
22
|
+
* `reasoning.summary` / `reasoning.text` entries. If the array contains only
|
|
23
|
+
* opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`
|
|
24
|
+
* string is used as a fallback when available.
|
|
25
|
+
*
|
|
26
|
+
* @param message - The AI message containing OpenRouter-formatted content
|
|
27
|
+
* @returns Array of content blocks in v1 standard format
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* const message = new AIMessage({
|
|
32
|
+
* content: "The answer is 42",
|
|
33
|
+
* additional_kwargs: { reasoning_content: "Let me think about this..." },
|
|
34
|
+
* response_metadata: { model_provider: "openrouter" },
|
|
35
|
+
* });
|
|
36
|
+
* message.contentBlocks;
|
|
37
|
+
* // [
|
|
38
|
+
* // { type: "reasoning", reasoning: "Let me think about this..." },
|
|
39
|
+
* // { type: "text", text: "The answer is 42" }
|
|
40
|
+
* // ]
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
function convertToV1FromOpenRouterMessage(message) {
|
|
44
|
+
const blocks = [];
|
|
45
|
+
const reasoningDetails = message.additional_kwargs?.reasoning_details;
|
|
46
|
+
let hasVisibleReasoningFromDetails = false;
|
|
47
|
+
if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) for (const detail of reasoningDetails) {
|
|
48
|
+
if (detail == null || typeof detail !== "object") continue;
|
|
49
|
+
const type = detail.type;
|
|
50
|
+
if (type === "reasoning.summary") {
|
|
51
|
+
const summary = detail.summary;
|
|
52
|
+
if (require_utils._isString(summary) && summary.length > 0) {
|
|
53
|
+
blocks.push({
|
|
54
|
+
type: "reasoning",
|
|
55
|
+
reasoning: summary
|
|
56
|
+
});
|
|
57
|
+
hasVisibleReasoningFromDetails = true;
|
|
58
|
+
}
|
|
59
|
+
} else if (type === "reasoning.text") {
|
|
60
|
+
const text = detail.text;
|
|
61
|
+
if (require_utils._isString(text) && text.length > 0) {
|
|
62
|
+
blocks.push({
|
|
63
|
+
type: "reasoning",
|
|
64
|
+
reasoning: text
|
|
65
|
+
});
|
|
66
|
+
hasVisibleReasoningFromDetails = true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!hasVisibleReasoningFromDetails) {
|
|
71
|
+
const reasoningContent = message.additional_kwargs?.reasoning_content;
|
|
72
|
+
if (require_utils._isString(reasoningContent) && reasoningContent.length > 0) blocks.push({
|
|
73
|
+
type: "reasoning",
|
|
74
|
+
reasoning: reasoningContent
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (typeof message.content === "string") {
|
|
78
|
+
if (message.content.length > 0) blocks.push({
|
|
79
|
+
type: "text",
|
|
80
|
+
text: message.content
|
|
81
|
+
});
|
|
82
|
+
} else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && require_utils._isString(block.text)) blocks.push({
|
|
83
|
+
type: "text",
|
|
84
|
+
text: block.text
|
|
85
|
+
});
|
|
86
|
+
for (const toolCall of message.tool_calls ?? []) blocks.push({
|
|
87
|
+
type: "tool_call",
|
|
88
|
+
id: toolCall.id,
|
|
89
|
+
name: toolCall.name,
|
|
90
|
+
args: toolCall.args
|
|
91
|
+
});
|
|
92
|
+
return blocks;
|
|
93
|
+
}
|
|
94
|
+
const ChatOpenRouterTranslator = {
|
|
95
|
+
translateContent: convertToV1FromOpenRouterMessage,
|
|
96
|
+
translateContentChunk: convertToV1FromOpenRouterMessage
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
exports.ChatOpenRouterTranslator = ChatOpenRouterTranslator;
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=openrouter.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openrouter.cjs","names":["_isString"],"sources":["../../../src/messages/block_translators/openrouter.ts"],"sourcesContent":["import { AIMessage } from \"../ai.js\";\nimport { ContentBlock } from \"../content/index.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { _isString } from \"./utils.js\";\n\n/**\n * Converts an OpenRouter AI message to an array of v1 standard content blocks.\n *\n * OpenRouter returns reasoning output through two places on the Chat\n * Completions response:\n *\n * 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes\n * the model's chain of thought. The `@langchain/openrouter` converter\n * normalizes this into `additional_kwargs.reasoning_content` so it matches\n * the DeepSeek convention already used elsewhere in LangChain.\n * 2. `message.reasoning_details` / `delta.reasoning_details` — a structured\n * array of provider-specific reasoning artifacts (see the\n * `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in\n * the OpenRouter API types). The converter preserves these verbatim under\n * `additional_kwargs.reasoning_details` for round-tripping back to the\n * provider on subsequent turns (e.g. Anthropic extended thinking requires\n * the original `signature` to be echoed back).\n *\n * When `reasoning_details` is present, visible blocks are emitted from\n * `reasoning.summary` / `reasoning.text` entries. If the array contains only\n * opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`\n * string is used as a fallback when available.\n *\n * @param message - The AI message containing OpenRouter-formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: \"The answer is 42\",\n * additional_kwargs: { reasoning_content: \"Let me think about this...\" },\n * response_metadata: { model_provider: \"openrouter\" },\n * });\n * message.contentBlocks;\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me think about this...\" },\n * // { type: \"text\", text: \"The answer is 42\" }\n * // ]\n * ```\n */\nexport function convertToV1FromOpenRouterMessage(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n\n // Prefer structured reasoning_details when present — they can carry\n // multiple distinct reasoning artifacts (summary, encrypted, text).\n const reasoningDetails = message.additional_kwargs?.reasoning_details;\n let hasVisibleReasoningFromDetails = false;\n if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) {\n for (const detail of reasoningDetails) {\n if (detail == null || typeof detail !== \"object\") continue;\n const type = (detail as { type?: unknown }).type;\n if (type === \"reasoning.summary\") {\n const summary = (detail as { summary?: unknown }).summary;\n if (_isString(summary) && summary.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: summary });\n hasVisibleReasoningFromDetails = true;\n }\n } else if (type === \"reasoning.text\") {\n const text = (detail as { text?: unknown }).text;\n if (_isString(text) && text.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: text });\n hasVisibleReasoningFromDetails = true;\n }\n }\n // `reasoning.encrypted` details carry no human-readable text (only an\n // opaque `data` blob that must be echoed back to the provider), so they\n // do not become visible reasoning blocks. They stay in\n // `additional_kwargs.reasoning_details` for round-tripping.\n }\n }\n\n if (!hasVisibleReasoningFromDetails) {\n const reasoningContent = message.additional_kwargs?.reasoning_content;\n if (_isString(reasoningContent) && reasoningContent.length > 0) {\n blocks.push({\n type: \"reasoning\",\n reasoning: reasoningContent,\n });\n }\n }\n\n // Handle text content (string or multi-block array).\n if (typeof message.content === \"string\") {\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n for (const block of message.content) {\n if (\n typeof block === \"object\" &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n _isString(block.text)\n ) {\n blocks.push({\n type: \"text\",\n text: block.text,\n });\n }\n }\n }\n\n // Add tool calls if present.\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n\n return blocks;\n}\n\nexport const ChatOpenRouterTranslator: StandardContentBlockTranslator = {\n translateContent: convertToV1FromOpenRouterMessage,\n translateContentChunk: convertToV1FromOpenRouterMessage,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,iCACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;CAI/C,MAAM,mBAAmB,QAAQ,mBAAmB;CACpD,IAAI,iCAAiC;AACrC,KAAI,MAAM,QAAQ,iBAAiB,IAAI,iBAAiB,SAAS,EAC/D,MAAK,MAAM,UAAU,kBAAkB;AACrC,MAAI,UAAU,QAAQ,OAAO,WAAW,SAAU;EAClD,MAAM,OAAQ,OAA8B;AAC5C,MAAI,SAAS,qBAAqB;GAChC,MAAM,UAAW,OAAiC;AAClD,OAAIA,cAAAA,UAAU,QAAQ,IAAI,QAAQ,SAAS,GAAG;AAC5C,WAAO,KAAK;KAAE,MAAM;KAAa,WAAW;KAAS,CAAC;AACtD,qCAAiC;;aAE1B,SAAS,kBAAkB;GACpC,MAAM,OAAQ,OAA8B;AAC5C,OAAIA,cAAAA,UAAU,KAAK,IAAI,KAAK,SAAS,GAAG;AACtC,WAAO,KAAK;KAAE,MAAM;KAAa,WAAW;KAAM,CAAC;AACnD,qCAAiC;;;;AAUzC,KAAI,CAAC,gCAAgC;EACnC,MAAM,mBAAmB,QAAQ,mBAAmB;AACpD,MAAIA,cAAAA,UAAU,iBAAiB,IAAI,iBAAiB,SAAS,EAC3D,QAAO,KAAK;GACV,MAAM;GACN,WAAW;GACZ,CAAC;;AAKN,KAAI,OAAO,QAAQ,YAAY;MACzB,QAAQ,QAAQ,SAAS,EAC3B,QAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;GACf,CAAC;OAGJ,MAAK,MAAM,SAAS,QAAQ,QAC1B,KACE,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,UACf,UAAU,SACVA,cAAAA,UAAU,MAAM,KAAK,CAErB,QAAO,KAAK;EACV,MAAM;EACN,MAAM,MAAM;EACb,CAAC;AAMR,MAAK,MAAM,YAAY,QAAQ,cAAc,EAAE,CAC7C,QAAO,KAAK;EACV,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS;EACf,MAAM,SAAS;EAChB,CAAC;AAGJ,QAAO;;AAGT,MAAa,2BAA2D;CACtE,kBAAkB;CAClB,uBAAuB;CACxB"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { _isString } from "./utils.js";
|
|
2
|
+
//#region src/messages/block_translators/openrouter.ts
|
|
3
|
+
/**
|
|
4
|
+
* Converts an OpenRouter AI message to an array of v1 standard content blocks.
|
|
5
|
+
*
|
|
6
|
+
* OpenRouter returns reasoning output through two places on the Chat
|
|
7
|
+
* Completions response:
|
|
8
|
+
*
|
|
9
|
+
* 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes
|
|
10
|
+
* the model's chain of thought. The `@langchain/openrouter` converter
|
|
11
|
+
* normalizes this into `additional_kwargs.reasoning_content` so it matches
|
|
12
|
+
* the DeepSeek convention already used elsewhere in LangChain.
|
|
13
|
+
* 2. `message.reasoning_details` / `delta.reasoning_details` — a structured
|
|
14
|
+
* array of provider-specific reasoning artifacts (see the
|
|
15
|
+
* `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in
|
|
16
|
+
* the OpenRouter API types). The converter preserves these verbatim under
|
|
17
|
+
* `additional_kwargs.reasoning_details` for round-tripping back to the
|
|
18
|
+
* provider on subsequent turns (e.g. Anthropic extended thinking requires
|
|
19
|
+
* the original `signature` to be echoed back).
|
|
20
|
+
*
|
|
21
|
+
* When `reasoning_details` is present, visible blocks are emitted from
|
|
22
|
+
* `reasoning.summary` / `reasoning.text` entries. If the array contains only
|
|
23
|
+
* opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`
|
|
24
|
+
* string is used as a fallback when available.
|
|
25
|
+
*
|
|
26
|
+
* @param message - The AI message containing OpenRouter-formatted content
|
|
27
|
+
* @returns Array of content blocks in v1 standard format
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* const message = new AIMessage({
|
|
32
|
+
* content: "The answer is 42",
|
|
33
|
+
* additional_kwargs: { reasoning_content: "Let me think about this..." },
|
|
34
|
+
* response_metadata: { model_provider: "openrouter" },
|
|
35
|
+
* });
|
|
36
|
+
* message.contentBlocks;
|
|
37
|
+
* // [
|
|
38
|
+
* // { type: "reasoning", reasoning: "Let me think about this..." },
|
|
39
|
+
* // { type: "text", text: "The answer is 42" }
|
|
40
|
+
* // ]
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
function convertToV1FromOpenRouterMessage(message) {
|
|
44
|
+
const blocks = [];
|
|
45
|
+
const reasoningDetails = message.additional_kwargs?.reasoning_details;
|
|
46
|
+
let hasVisibleReasoningFromDetails = false;
|
|
47
|
+
if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) for (const detail of reasoningDetails) {
|
|
48
|
+
if (detail == null || typeof detail !== "object") continue;
|
|
49
|
+
const type = detail.type;
|
|
50
|
+
if (type === "reasoning.summary") {
|
|
51
|
+
const summary = detail.summary;
|
|
52
|
+
if (_isString(summary) && summary.length > 0) {
|
|
53
|
+
blocks.push({
|
|
54
|
+
type: "reasoning",
|
|
55
|
+
reasoning: summary
|
|
56
|
+
});
|
|
57
|
+
hasVisibleReasoningFromDetails = true;
|
|
58
|
+
}
|
|
59
|
+
} else if (type === "reasoning.text") {
|
|
60
|
+
const text = detail.text;
|
|
61
|
+
if (_isString(text) && text.length > 0) {
|
|
62
|
+
blocks.push({
|
|
63
|
+
type: "reasoning",
|
|
64
|
+
reasoning: text
|
|
65
|
+
});
|
|
66
|
+
hasVisibleReasoningFromDetails = true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!hasVisibleReasoningFromDetails) {
|
|
71
|
+
const reasoningContent = message.additional_kwargs?.reasoning_content;
|
|
72
|
+
if (_isString(reasoningContent) && reasoningContent.length > 0) blocks.push({
|
|
73
|
+
type: "reasoning",
|
|
74
|
+
reasoning: reasoningContent
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (typeof message.content === "string") {
|
|
78
|
+
if (message.content.length > 0) blocks.push({
|
|
79
|
+
type: "text",
|
|
80
|
+
text: message.content
|
|
81
|
+
});
|
|
82
|
+
} else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) blocks.push({
|
|
83
|
+
type: "text",
|
|
84
|
+
text: block.text
|
|
85
|
+
});
|
|
86
|
+
for (const toolCall of message.tool_calls ?? []) blocks.push({
|
|
87
|
+
type: "tool_call",
|
|
88
|
+
id: toolCall.id,
|
|
89
|
+
name: toolCall.name,
|
|
90
|
+
args: toolCall.args
|
|
91
|
+
});
|
|
92
|
+
return blocks;
|
|
93
|
+
}
|
|
94
|
+
const ChatOpenRouterTranslator = {
|
|
95
|
+
translateContent: convertToV1FromOpenRouterMessage,
|
|
96
|
+
translateContentChunk: convertToV1FromOpenRouterMessage
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
export { ChatOpenRouterTranslator };
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=openrouter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openrouter.js","names":[],"sources":["../../../src/messages/block_translators/openrouter.ts"],"sourcesContent":["import { AIMessage } from \"../ai.js\";\nimport { ContentBlock } from \"../content/index.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { _isString } from \"./utils.js\";\n\n/**\n * Converts an OpenRouter AI message to an array of v1 standard content blocks.\n *\n * OpenRouter returns reasoning output through two places on the Chat\n * Completions response:\n *\n * 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes\n * the model's chain of thought. The `@langchain/openrouter` converter\n * normalizes this into `additional_kwargs.reasoning_content` so it matches\n * the DeepSeek convention already used elsewhere in LangChain.\n * 2. `message.reasoning_details` / `delta.reasoning_details` — a structured\n * array of provider-specific reasoning artifacts (see the\n * `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in\n * the OpenRouter API types). The converter preserves these verbatim under\n * `additional_kwargs.reasoning_details` for round-tripping back to the\n * provider on subsequent turns (e.g. Anthropic extended thinking requires\n * the original `signature` to be echoed back).\n *\n * When `reasoning_details` is present, visible blocks are emitted from\n * `reasoning.summary` / `reasoning.text` entries. If the array contains only\n * opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`\n * string is used as a fallback when available.\n *\n * @param message - The AI message containing OpenRouter-formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: \"The answer is 42\",\n * additional_kwargs: { reasoning_content: \"Let me think about this...\" },\n * response_metadata: { model_provider: \"openrouter\" },\n * });\n * message.contentBlocks;\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me think about this...\" },\n * // { type: \"text\", text: \"The answer is 42\" }\n * // ]\n * ```\n */\nexport function convertToV1FromOpenRouterMessage(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n\n // Prefer structured reasoning_details when present — they can carry\n // multiple distinct reasoning artifacts (summary, encrypted, text).\n const reasoningDetails = message.additional_kwargs?.reasoning_details;\n let hasVisibleReasoningFromDetails = false;\n if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) {\n for (const detail of reasoningDetails) {\n if (detail == null || typeof detail !== \"object\") continue;\n const type = (detail as { type?: unknown }).type;\n if (type === \"reasoning.summary\") {\n const summary = (detail as { summary?: unknown }).summary;\n if (_isString(summary) && summary.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: summary });\n hasVisibleReasoningFromDetails = true;\n }\n } else if (type === \"reasoning.text\") {\n const text = (detail as { text?: unknown }).text;\n if (_isString(text) && text.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: text });\n hasVisibleReasoningFromDetails = true;\n }\n }\n // `reasoning.encrypted` details carry no human-readable text (only an\n // opaque `data` blob that must be echoed back to the provider), so they\n // do not become visible reasoning blocks. They stay in\n // `additional_kwargs.reasoning_details` for round-tripping.\n }\n }\n\n if (!hasVisibleReasoningFromDetails) {\n const reasoningContent = message.additional_kwargs?.reasoning_content;\n if (_isString(reasoningContent) && reasoningContent.length > 0) {\n blocks.push({\n type: \"reasoning\",\n reasoning: reasoningContent,\n });\n }\n }\n\n // Handle text content (string or multi-block array).\n if (typeof message.content === \"string\") {\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n for (const block of message.content) {\n if (\n typeof block === \"object\" &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n _isString(block.text)\n ) {\n blocks.push({\n type: \"text\",\n text: block.text,\n });\n }\n }\n }\n\n // Add tool calls if present.\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n\n return blocks;\n}\n\nexport const ChatOpenRouterTranslator: StandardContentBlockTranslator = {\n translateContent: convertToV1FromOpenRouterMessage,\n translateContentChunk: convertToV1FromOpenRouterMessage,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,iCACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;CAI/C,MAAM,mBAAmB,QAAQ,mBAA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ageChunk, ChatMessageFields, isChatMessage, isChat
|
|
|
8
8
|
import { FunctionMessage, FunctionMessageChunk, FunctionMessageFields, isFunctionMessage, isFunctionMessageChunk } from "./function.cjs";
|
|
9
9
|
import { HumanMessage, HumanMessageChunk, HumanMessageFields, isHumanMessage, isHumanMessageChunk } from "./human.cjs";
|
|
10
10
|
import { SystemMessage, SystemMessageChunk, SystemMessageFields, isSystemMessage, isSystemMessageChunk } from "./system.cjs";
|
|
11
|
-
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.cjs";
|
|
11
|
+
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, RawInputToolCallChunk, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.cjs";
|
|
12
12
|
import { $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeMessageStructure, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, Message, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, StandardMessageStructure, isMessage } from "./message.cjs";
|
|
13
13
|
import { RemoveMessage, RemoveMessageFields } from "./modifier.cjs";
|
|
14
14
|
import { FilterMessagesFields, MessageChunkUnion, MessageTypeOrClass, MessageUnion, TrimMessagesFields, defaultTextSplitter, filterMessages, mergeMessageRuns, trimMessages } from "./transformers.cjs";
|
|
15
|
-
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, ProviderFormatTypes, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
|
15
|
+
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, ProviderFormatTypes, RawInputToolCallChunk, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
package/dist/messages/index.d.ts
CHANGED
|
@@ -8,8 +8,8 @@ import { ChatMessage, ChatMessageChunk, ChatMessageFields, isChatMessage, isChat
|
|
|
8
8
|
import { FunctionMessage, FunctionMessageChunk, FunctionMessageFields, isFunctionMessage, isFunctionMessageChunk } from "./function.js";
|
|
9
9
|
import { HumanMessage, HumanMessageChunk, HumanMessageFields, isHumanMessage, isHumanMessageChunk } from "./human.js";
|
|
10
10
|
import { SystemMessage, SystemMessageChunk, SystemMessageFields, isSystemMessage, isSystemMessageChunk } from "./system.js";
|
|
11
|
-
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.js";
|
|
11
|
+
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, RawInputToolCallChunk, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.js";
|
|
12
12
|
import { $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeMessageStructure, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, Message, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, StandardMessageStructure, isMessage } from "./message.js";
|
|
13
13
|
import { RemoveMessage, RemoveMessageFields } from "./modifier.js";
|
|
14
14
|
import { FilterMessagesFields, MessageChunkUnion, MessageTypeOrClass, MessageUnion, TrimMessagesFields, defaultTextSplitter, filterMessages, mergeMessageRuns, trimMessages } from "./transformers.js";
|
|
15
|
-
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, ProviderFormatTypes, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
|
15
|
+
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, ProviderFormatTypes, RawInputToolCallChunk, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
|
@@ -2,6 +2,12 @@ const require_base = require("./base.cjs");
|
|
|
2
2
|
//#region src/messages/modifier.ts
|
|
3
3
|
/**
|
|
4
4
|
* Message responsible for deleting other messages.
|
|
5
|
+
*
|
|
6
|
+
* `RemoveMessage` is intentionally not generic over `MessageStructure`.
|
|
7
|
+
* Its content is always `[]` (empty), so carrying a structure type parameter
|
|
8
|
+
* would only cause unnecessary type incompatibilities when mixing messages
|
|
9
|
+
* from different structure configurations (e.g. passing a `RemoveMessage`
|
|
10
|
+
* into an API that expects `Message<CustomToolCall>`).
|
|
5
11
|
*/
|
|
6
12
|
var RemoveMessage = class extends require_base.BaseMessage {
|
|
7
13
|
type = "remove";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modifier.cjs","names":["BaseMessage"],"sources":["../../src/messages/modifier.ts"],"sourcesContent":["import { BaseMessage, BaseMessageFields } from \"./base.js\";\
|
|
1
|
+
{"version":3,"file":"modifier.cjs","names":["BaseMessage"],"sources":["../../src/messages/modifier.ts"],"sourcesContent":["import { BaseMessage, BaseMessageFields } from \"./base.js\";\n\nexport interface RemoveMessageFields extends Omit<\n BaseMessageFields,\n \"content\"\n> {\n /**\n * The ID of the message to remove.\n */\n id: string;\n}\n\n/**\n * Message responsible for deleting other messages.\n *\n * `RemoveMessage` is intentionally not generic over `MessageStructure`.\n * Its content is always `[]` (empty), so carrying a structure type parameter\n * would only cause unnecessary type incompatibilities when mixing messages\n * from different structure configurations (e.g. passing a `RemoveMessage`\n * into an API that expects `Message<CustomToolCall>`).\n */\nexport class RemoveMessage extends BaseMessage {\n readonly type = \"remove\" as const;\n\n /**\n * The ID of the message to remove.\n */\n id: string;\n\n constructor(fields: RemoveMessageFields) {\n super({\n ...fields,\n content: [],\n });\n this.id = fields.id;\n }\n\n override get _printableFields(): Record<string, unknown> {\n return {\n ...super._printableFields,\n id: this.id,\n };\n }\n\n static isInstance(obj: unknown): obj is RemoveMessage {\n return super.isInstance(obj) && obj.type === \"remove\";\n }\n}\n"],"mappings":";;;;;;;;;;;AAqBA,IAAa,gBAAb,cAAmCA,aAAAA,YAAY;CAC7C,OAAgB;;;;CAKhB;CAEA,YAAY,QAA6B;AACvC,QAAM;GACJ,GAAG;GACH,SAAS,EAAE;GACZ,CAAC;AACF,OAAK,KAAK,OAAO;;CAGnB,IAAa,mBAA4C;AACvD,SAAO;GACL,GAAG,MAAM;GACT,IAAI,KAAK;GACV;;CAGH,OAAO,WAAW,KAAoC;AACpD,SAAO,MAAM,WAAW,IAAI,IAAI,IAAI,SAAS"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { BaseMessage, BaseMessageFields } from "./base.cjs";
|
|
2
|
-
import { MessageStructure } from "./message.cjs";
|
|
3
2
|
|
|
4
3
|
//#region src/messages/modifier.d.ts
|
|
5
|
-
interface RemoveMessageFields
|
|
4
|
+
interface RemoveMessageFields extends Omit<BaseMessageFields, "content"> {
|
|
6
5
|
/**
|
|
7
6
|
* The ID of the message to remove.
|
|
8
7
|
*/
|
|
@@ -10,14 +9,20 @@ interface RemoveMessageFields<TStructure extends MessageStructure = MessageStruc
|
|
|
10
9
|
}
|
|
11
10
|
/**
|
|
12
11
|
* Message responsible for deleting other messages.
|
|
12
|
+
*
|
|
13
|
+
* `RemoveMessage` is intentionally not generic over `MessageStructure`.
|
|
14
|
+
* Its content is always `[]` (empty), so carrying a structure type parameter
|
|
15
|
+
* would only cause unnecessary type incompatibilities when mixing messages
|
|
16
|
+
* from different structure configurations (e.g. passing a `RemoveMessage`
|
|
17
|
+
* into an API that expects `Message<CustomToolCall>`).
|
|
13
18
|
*/
|
|
14
|
-
declare class RemoveMessage
|
|
19
|
+
declare class RemoveMessage extends BaseMessage {
|
|
15
20
|
readonly type: "remove";
|
|
16
21
|
/**
|
|
17
22
|
* The ID of the message to remove.
|
|
18
23
|
*/
|
|
19
24
|
id: string;
|
|
20
|
-
constructor(fields: RemoveMessageFields
|
|
25
|
+
constructor(fields: RemoveMessageFields);
|
|
21
26
|
get _printableFields(): Record<string, unknown>;
|
|
22
27
|
static isInstance(obj: unknown): obj is RemoveMessage;
|
|
23
28
|
}
|