@langchain/openai 1.5.5 → 1.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/azure/chat_models/common.cjs.map +1 -1
  3. package/dist/azure/chat_models/common.d.cts +1 -1
  4. package/dist/azure/chat_models/common.d.cts.map +1 -1
  5. package/dist/azure/chat_models/common.d.ts +1 -1
  6. package/dist/azure/chat_models/common.d.ts.map +1 -1
  7. package/dist/azure/chat_models/common.js.map +1 -1
  8. package/dist/azure/chat_models/completions.cjs.map +1 -1
  9. package/dist/azure/chat_models/completions.d.cts +0 -1
  10. package/dist/azure/chat_models/completions.d.cts.map +1 -1
  11. package/dist/azure/chat_models/completions.d.ts +0 -1
  12. package/dist/azure/chat_models/completions.d.ts.map +1 -1
  13. package/dist/azure/chat_models/completions.js.map +1 -1
  14. package/dist/azure/chat_models/index.cjs.map +1 -1
  15. package/dist/azure/chat_models/index.d.cts +1 -2
  16. package/dist/azure/chat_models/index.d.cts.map +1 -1
  17. package/dist/azure/chat_models/index.d.ts +0 -1
  18. package/dist/azure/chat_models/index.d.ts.map +1 -1
  19. package/dist/azure/chat_models/index.js.map +1 -1
  20. package/dist/azure/chat_models/responses.cjs.map +1 -1
  21. package/dist/azure/chat_models/responses.d.cts +0 -1
  22. package/dist/azure/chat_models/responses.d.cts.map +1 -1
  23. package/dist/azure/chat_models/responses.d.ts +0 -1
  24. package/dist/azure/chat_models/responses.d.ts.map +1 -1
  25. package/dist/azure/chat_models/responses.js.map +1 -1
  26. package/dist/azure/embeddings.cjs.map +1 -1
  27. package/dist/azure/embeddings.d.cts +2 -2
  28. package/dist/azure/embeddings.d.cts.map +1 -1
  29. package/dist/azure/embeddings.d.ts +2 -2
  30. package/dist/azure/embeddings.d.ts.map +1 -1
  31. package/dist/azure/embeddings.js.map +1 -1
  32. package/dist/azure/llms.cjs.map +1 -1
  33. package/dist/azure/llms.d.cts +0 -1
  34. package/dist/azure/llms.d.cts.map +1 -1
  35. package/dist/azure/llms.d.ts +0 -1
  36. package/dist/azure/llms.d.ts.map +1 -1
  37. package/dist/azure/llms.js.map +1 -1
  38. package/dist/chat_models/base.cjs +37 -3
  39. package/dist/chat_models/base.cjs.map +1 -1
  40. package/dist/chat_models/base.d.cts +6 -7
  41. package/dist/chat_models/base.d.cts.map +1 -1
  42. package/dist/chat_models/base.d.ts +5 -6
  43. package/dist/chat_models/base.d.ts.map +1 -1
  44. package/dist/chat_models/base.js +37 -3
  45. package/dist/chat_models/base.js.map +1 -1
  46. package/dist/chat_models/completions.cjs.map +1 -1
  47. package/dist/chat_models/completions.d.cts +0 -1
  48. package/dist/chat_models/completions.d.cts.map +1 -1
  49. package/dist/chat_models/completions.d.ts +0 -1
  50. package/dist/chat_models/completions.d.ts.map +1 -1
  51. package/dist/chat_models/completions.js.map +1 -1
  52. package/dist/chat_models/index.cjs.map +1 -1
  53. package/dist/chat_models/index.d.cts +14 -17
  54. package/dist/chat_models/index.d.cts.map +1 -1
  55. package/dist/chat_models/index.d.ts +14 -17
  56. package/dist/chat_models/index.d.ts.map +1 -1
  57. package/dist/chat_models/index.js.map +1 -1
  58. package/dist/chat_models/profiles.cjs.map +1 -1
  59. package/dist/chat_models/profiles.js.map +1 -1
  60. package/dist/chat_models/responses.cjs.map +1 -1
  61. package/dist/chat_models/responses.d.cts +0 -1
  62. package/dist/chat_models/responses.d.cts.map +1 -1
  63. package/dist/chat_models/responses.d.ts +0 -1
  64. package/dist/chat_models/responses.d.ts.map +1 -1
  65. package/dist/chat_models/responses.js.map +1 -1
  66. package/dist/converters/completions.cjs +2 -4
  67. package/dist/converters/completions.cjs.map +1 -1
  68. package/dist/converters/completions.d.cts +0 -1
  69. package/dist/converters/completions.d.cts.map +1 -1
  70. package/dist/converters/completions.d.ts +0 -1
  71. package/dist/converters/completions.d.ts.map +1 -1
  72. package/dist/converters/completions.js +2 -4
  73. package/dist/converters/completions.js.map +1 -1
  74. package/dist/converters/index.cjs +14 -2
  75. package/dist/converters/index.d.cts +2 -1
  76. package/dist/converters/index.d.ts +2 -1
  77. package/dist/converters/index.js +3 -3
  78. package/dist/converters/responses.cjs.map +1 -1
  79. package/dist/converters/responses.d.cts +0 -1
  80. package/dist/converters/responses.d.cts.map +1 -1
  81. package/dist/converters/responses.d.ts +0 -1
  82. package/dist/converters/responses.d.ts.map +1 -1
  83. package/dist/converters/responses.js.map +1 -1
  84. package/dist/embeddings.cjs.map +1 -1
  85. package/dist/embeddings.d.cts +2 -2
  86. package/dist/embeddings.d.cts.map +1 -1
  87. package/dist/embeddings.d.ts +2 -2
  88. package/dist/embeddings.d.ts.map +1 -1
  89. package/dist/embeddings.js.map +1 -1
  90. package/dist/index.d.cts +2 -1
  91. package/dist/index.d.ts +2 -1
  92. package/dist/llms.cjs +1 -1
  93. package/dist/llms.cjs.map +1 -1
  94. package/dist/llms.d.cts +1 -2
  95. package/dist/llms.d.cts.map +1 -1
  96. package/dist/llms.d.ts +1 -2
  97. package/dist/llms.d.ts.map +1 -1
  98. package/dist/llms.js +1 -1
  99. package/dist/llms.js.map +1 -1
  100. package/dist/tools/applyPatch.cjs +4 -0
  101. package/dist/tools/applyPatch.cjs.map +1 -1
  102. package/dist/tools/applyPatch.d.cts +1 -2
  103. package/dist/tools/applyPatch.d.cts.map +1 -1
  104. package/dist/tools/applyPatch.d.ts +1 -2
  105. package/dist/tools/applyPatch.d.ts.map +1 -1
  106. package/dist/tools/applyPatch.js +1 -1
  107. package/dist/tools/applyPatch.js.map +1 -1
  108. package/dist/tools/codeInterpreter.cjs.map +1 -1
  109. package/dist/tools/codeInterpreter.d.cts +0 -1
  110. package/dist/tools/codeInterpreter.d.cts.map +1 -1
  111. package/dist/tools/codeInterpreter.d.ts +0 -1
  112. package/dist/tools/codeInterpreter.d.ts.map +1 -1
  113. package/dist/tools/codeInterpreter.js.map +1 -1
  114. package/dist/tools/computerUse.cjs +1 -0
  115. package/dist/tools/computerUse.cjs.map +1 -1
  116. package/dist/tools/computerUse.d.cts +1 -2
  117. package/dist/tools/computerUse.d.cts.map +1 -1
  118. package/dist/tools/computerUse.d.ts +1 -2
  119. package/dist/tools/computerUse.d.ts.map +1 -1
  120. package/dist/tools/computerUse.js +1 -1
  121. package/dist/tools/computerUse.js.map +1 -1
  122. package/dist/tools/custom.cjs.map +1 -1
  123. package/dist/tools/custom.d.cts +1 -2
  124. package/dist/tools/custom.d.cts.map +1 -1
  125. package/dist/tools/custom.d.ts +1 -2
  126. package/dist/tools/custom.d.ts.map +1 -1
  127. package/dist/tools/custom.js.map +1 -1
  128. package/dist/tools/dalle.cjs.map +1 -1
  129. package/dist/tools/dalle.d.cts +0 -1
  130. package/dist/tools/dalle.d.cts.map +1 -1
  131. package/dist/tools/dalle.d.ts +0 -1
  132. package/dist/tools/dalle.d.ts.map +1 -1
  133. package/dist/tools/dalle.js.map +1 -1
  134. package/dist/tools/fileSearch.cjs.map +1 -1
  135. package/dist/tools/fileSearch.d.cts +0 -1
  136. package/dist/tools/fileSearch.d.cts.map +1 -1
  137. package/dist/tools/fileSearch.d.ts +0 -1
  138. package/dist/tools/fileSearch.d.ts.map +1 -1
  139. package/dist/tools/fileSearch.js.map +1 -1
  140. package/dist/tools/imageGeneration.cjs.map +1 -1
  141. package/dist/tools/imageGeneration.d.cts +0 -1
  142. package/dist/tools/imageGeneration.d.cts.map +1 -1
  143. package/dist/tools/imageGeneration.d.ts +0 -1
  144. package/dist/tools/imageGeneration.d.ts.map +1 -1
  145. package/dist/tools/imageGeneration.js.map +1 -1
  146. package/dist/tools/index.cjs +2 -1
  147. package/dist/tools/index.cjs.map +1 -1
  148. package/dist/tools/index.d.cts +1 -2
  149. package/dist/tools/index.d.cts.map +1 -1
  150. package/dist/tools/index.d.ts +1 -2
  151. package/dist/tools/index.d.ts.map +1 -1
  152. package/dist/tools/index.js +2 -2
  153. package/dist/tools/index.js.map +1 -1
  154. package/dist/tools/localShell.cjs +2 -0
  155. package/dist/tools/localShell.cjs.map +1 -1
  156. package/dist/tools/localShell.d.cts +1 -2
  157. package/dist/tools/localShell.d.cts.map +1 -1
  158. package/dist/tools/localShell.d.ts +1 -2
  159. package/dist/tools/localShell.d.ts.map +1 -1
  160. package/dist/tools/localShell.js +1 -1
  161. package/dist/tools/localShell.js.map +1 -1
  162. package/dist/tools/mcp.cjs.map +1 -1
  163. package/dist/tools/mcp.d.cts +0 -1
  164. package/dist/tools/mcp.d.cts.map +1 -1
  165. package/dist/tools/mcp.d.ts +0 -1
  166. package/dist/tools/mcp.d.ts.map +1 -1
  167. package/dist/tools/mcp.js.map +1 -1
  168. package/dist/tools/shell.cjs +1 -0
  169. package/dist/tools/shell.cjs.map +1 -1
  170. package/dist/tools/shell.d.cts +1 -2
  171. package/dist/tools/shell.d.cts.map +1 -1
  172. package/dist/tools/shell.d.ts +1 -2
  173. package/dist/tools/shell.d.ts.map +1 -1
  174. package/dist/tools/shell.js +1 -1
  175. package/dist/tools/shell.js.map +1 -1
  176. package/dist/tools/toolSearch.cjs.map +1 -1
  177. package/dist/tools/toolSearch.d.cts +0 -1
  178. package/dist/tools/toolSearch.d.cts.map +1 -1
  179. package/dist/tools/toolSearch.d.ts +0 -1
  180. package/dist/tools/toolSearch.d.ts.map +1 -1
  181. package/dist/tools/toolSearch.js.map +1 -1
  182. package/dist/tools/webSearch.cjs.map +1 -1
  183. package/dist/tools/webSearch.d.cts +1 -2
  184. package/dist/tools/webSearch.d.cts.map +1 -1
  185. package/dist/tools/webSearch.d.ts +1 -2
  186. package/dist/tools/webSearch.d.ts.map +1 -1
  187. package/dist/tools/webSearch.js.map +1 -1
  188. package/dist/types.d.cts +0 -1
  189. package/dist/types.d.cts.map +1 -1
  190. package/dist/types.d.ts +0 -1
  191. package/dist/types.d.ts.map +1 -1
  192. package/dist/utils/azure.cjs.map +1 -1
  193. package/dist/utils/azure.d.cts.map +1 -1
  194. package/dist/utils/azure.d.ts.map +1 -1
  195. package/dist/utils/azure.js.map +1 -1
  196. package/dist/utils/client.cjs.map +1 -1
  197. package/dist/utils/client.d.cts.map +1 -1
  198. package/dist/utils/client.d.ts.map +1 -1
  199. package/dist/utils/client.js.map +1 -1
  200. package/dist/utils/errors.cjs.map +1 -1
  201. package/dist/utils/errors.js.map +1 -1
  202. package/dist/utils/misc.cjs +2 -0
  203. package/dist/utils/misc.cjs.map +1 -1
  204. package/dist/utils/misc.d.cts +0 -1
  205. package/dist/utils/misc.d.cts.map +1 -1
  206. package/dist/utils/misc.d.ts +0 -1
  207. package/dist/utils/misc.d.ts.map +1 -1
  208. package/dist/utils/misc.js +1 -1
  209. package/dist/utils/misc.js.map +1 -1
  210. package/dist/utils/output.cjs.map +1 -1
  211. package/dist/utils/output.js.map +1 -1
  212. package/dist/utils/prompts.cjs.map +1 -1
  213. package/dist/utils/prompts.d.cts +0 -1
  214. package/dist/utils/prompts.d.cts.map +1 -1
  215. package/dist/utils/prompts.d.ts +0 -1
  216. package/dist/utils/prompts.d.ts.map +1 -1
  217. package/dist/utils/prompts.js.map +1 -1
  218. package/dist/utils/responses_stream_events.cjs.map +1 -1
  219. package/dist/utils/responses_stream_events.d.cts +0 -1
  220. package/dist/utils/responses_stream_events.d.cts.map +1 -1
  221. package/dist/utils/responses_stream_events.d.ts +0 -1
  222. package/dist/utils/responses_stream_events.d.ts.map +1 -1
  223. package/dist/utils/responses_stream_events.js.map +1 -1
  224. package/dist/utils/tools.cjs.map +1 -1
  225. package/dist/utils/tools.d.cts +2 -0
  226. package/dist/utils/tools.d.cts.map +1 -1
  227. package/dist/utils/tools.d.ts +2 -0
  228. package/dist/utils/tools.d.ts.map +1 -1
  229. package/dist/utils/tools.js.map +1 -1
  230. package/package.json +6 -6
package/dist/index.d.ts CHANGED
@@ -32,5 +32,6 @@ import { ConvertOpenAICompletionsStreamOptions, convertOpenAICompletionsStream }
32
32
  import { ConvertOpenAIResponsesStreamOptions, convertOpenAIResponsesStream } from "./utils/responses_stream_events.js";
33
33
  import { completionsApiContentBlockConverter, convertCompletionsDeltaToBaseMessageChunk, convertCompletionsMessageToBaseMessage, convertMessagesToCompletionsMessageParams, convertStandardContentBlockToCompletionsContentPart, convertStandardContentMessageToCompletionsMessage } from "./converters/completions.js";
34
34
  import { ResponsesCreate, ResponsesCreateInvoke, ResponsesInputItem, ResponsesParse, ResponsesParseInvoke, convertMessagesToResponsesInput, convertReasoningSummaryToResponsesReasoningItem, convertResponsesDeltaToChatGenerationChunk, convertResponsesMessageToAIMessage, convertResponsesUsageToUsageMetadata, convertStandardContentMessageToResponsesInput } from "./converters/responses.js";
35
+ import "./converters/index.js";
35
36
  import { ClientOptions, OpenAI as OpenAIClient, toFile } from "openai";
36
- export { ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchOperation, ApplyPatchOptions, ApplyPatchTool, ApplyPatchUpdateFileOperation, AzureChatOpenAI, AzureChatOpenAICompletions, type AzureChatOpenAIFields, AzureChatOpenAIResponses, AzureOpenAI, AzureOpenAIChatInput, AzureOpenAIEmbeddings, AzureOpenAIInput, BaseChatOpenAI, type BaseChatOpenAICallOptions, type BaseChatOpenAIFields, ChatOpenAI, type ChatOpenAICallOptions, ChatOpenAICompletions, type ChatOpenAICompletionsCallOptions, type ChatOpenAIFields, ChatOpenAIReasoningSummary, ChatOpenAIResponseFormat, ChatOpenAIResponses, type ChatOpenAIResponsesCallOptions, type ClientOptions, CodeInterpreterAutoContainer, CodeInterpreterMemoryLimit, CodeInterpreterOptions, CodeInterpreterTool, ComputerUseAction, ComputerUseClickAction, ComputerUseDoubleClickAction, ComputerUseDragAction, ComputerUseEnvironment, ComputerUseInput, ComputerUseKeypressAction, ComputerUseMoveAction, ComputerUseOptions, ComputerUseScreenshotAction, ComputerUseScrollAction, ComputerUseTool, ComputerUseTypeAction, ComputerUseWaitAction, type ConvertOpenAICompletionsStreamOptions, type ConvertOpenAIResponsesStreamOptions, DallEAPIWrapper, DallEAPIWrapperParams, FileSearchComparisonFilter, FileSearchComparisonType, FileSearchCompoundFilter, FileSearchFilter, FileSearchHybridSearchWeights, FileSearchOptions, FileSearchRankingOptions, FileSearchTool, HeadersLike, ImageGenerationInputMask, ImageGenerationOptions, ImageGenerationTool, LocalShellAction, LocalShellOptions, LocalShellTool, McpApprovalFilter, McpConnectorId, McpConnectorOptions, McpRemoteServerOptions, McpTool, McpToolFilter, OpenAI, OpenAIApiKey, OpenAIBaseInput, OpenAICacheRetentionParam, type OpenAICallOptions, type OpenAIChatInput, OpenAIChatModelId, OpenAIClient, OpenAICoreRequestOptions, OpenAIEmbeddingModelId, OpenAIEmbeddings, OpenAIEmbeddingsParams, OpenAIEndpointConfig, OpenAIImageModelId, OpenAIInput, OpenAIVerbosityParam, ResponseFormatConfiguration, ResponsesCreate, ResponsesCreateInvoke, ResponsesInputItem, ResponsesParse, ResponsesParseInvoke, ShellAction, ShellCallOutcome, ShellCommandOutput, ShellOptions, ShellResult, ShellTool, TiktokenModel, ToolSearchOptions, ToolSearchTool, WebSearchFilters, WebSearchOptions, WebSearchTool, completionsApiContentBlockConverter, convertCompletionsDeltaToBaseMessageChunk, convertCompletionsMessageToBaseMessage, convertMessagesToCompletionsMessageParams, convertMessagesToResponsesInput, convertOpenAICompletionsStream, convertOpenAIResponsesStream, convertPromptToOpenAI, convertReasoningSummaryToResponsesReasoningItem, convertResponsesDeltaToChatGenerationChunk, convertResponsesMessageToAIMessage, convertResponsesUsageToUsageMetadata, convertStandardContentBlockToCompletionsContentPart, convertStandardContentMessageToCompletionsMessage, convertStandardContentMessageToResponsesInput, customTool, getEndpoint, getFormattedEnv, getHeadersWithUserAgent, isHeaders, messageToOpenAIRole, normalizeHeaders, toFile, tools, wrapOpenAIClientError };
37
+ export { type ApplyPatchCreateFileOperation, type ApplyPatchDeleteFileOperation, type ApplyPatchOperation, type ApplyPatchOptions, type ApplyPatchTool, type ApplyPatchUpdateFileOperation, AzureChatOpenAI, AzureChatOpenAICompletions, type AzureChatOpenAIFields, AzureChatOpenAIResponses, AzureOpenAI, AzureOpenAIChatInput, AzureOpenAIEmbeddings, AzureOpenAIInput, BaseChatOpenAI, type BaseChatOpenAICallOptions, type BaseChatOpenAIFields, ChatOpenAI, type ChatOpenAICallOptions, ChatOpenAICompletions, type ChatOpenAICompletionsCallOptions, type ChatOpenAIFields, ChatOpenAIReasoningSummary, ChatOpenAIResponseFormat, ChatOpenAIResponses, type ChatOpenAIResponsesCallOptions, type ClientOptions, type CodeInterpreterAutoContainer, type CodeInterpreterMemoryLimit, type CodeInterpreterOptions, type CodeInterpreterTool, type ComputerUseAction, type ComputerUseClickAction, type ComputerUseDoubleClickAction, type ComputerUseDragAction, type ComputerUseEnvironment, type ComputerUseInput, type ComputerUseKeypressAction, type ComputerUseMoveAction, type ComputerUseOptions, type ComputerUseScreenshotAction, type ComputerUseScrollAction, type ComputerUseTool, type ComputerUseTypeAction, type ComputerUseWaitAction, type ConvertOpenAICompletionsStreamOptions, type ConvertOpenAIResponsesStreamOptions, DallEAPIWrapper, DallEAPIWrapperParams, type FileSearchComparisonFilter, type FileSearchComparisonType, type FileSearchCompoundFilter, type FileSearchFilter, type FileSearchHybridSearchWeights, type FileSearchOptions, type FileSearchRankingOptions, type FileSearchTool, HeadersLike, type ImageGenerationInputMask, type ImageGenerationOptions, type ImageGenerationTool, type LocalShellAction, type LocalShellOptions, type LocalShellTool, type McpApprovalFilter, type McpConnectorId, type McpConnectorOptions, type McpRemoteServerOptions, type McpTool, type McpToolFilter, OpenAI, OpenAIApiKey, OpenAIBaseInput, OpenAICacheRetentionParam, OpenAICallOptions, OpenAIChatInput, OpenAIChatModelId, OpenAIClient, OpenAICoreRequestOptions, OpenAIEmbeddingModelId, OpenAIEmbeddings, OpenAIEmbeddingsParams, OpenAIEndpointConfig, OpenAIImageModelId, OpenAIInput, OpenAIVerbosityParam, ResponseFormatConfiguration, ResponsesCreate, ResponsesCreateInvoke, ResponsesInputItem, ResponsesParse, ResponsesParseInvoke, type ShellAction, type ShellCallOutcome, type ShellCommandOutput, type ShellOptions, type ShellResult, type ShellTool, type TiktokenModel, type ToolSearchOptions, type ToolSearchTool, type WebSearchFilters, type WebSearchOptions, type WebSearchTool, completionsApiContentBlockConverter, convertCompletionsDeltaToBaseMessageChunk, convertCompletionsMessageToBaseMessage, convertMessagesToCompletionsMessageParams, convertMessagesToResponsesInput, convertOpenAICompletionsStream, convertOpenAIResponsesStream, convertPromptToOpenAI, convertReasoningSummaryToResponsesReasoningItem, convertResponsesDeltaToChatGenerationChunk, convertResponsesMessageToAIMessage, convertResponsesUsageToUsageMetadata, convertStandardContentBlockToCompletionsContentPart, convertStandardContentMessageToCompletionsMessage, convertStandardContentMessageToResponsesInput, customTool, getEndpoint, getFormattedEnv, getHeadersWithUserAgent, isHeaders, messageToOpenAIRole, normalizeHeaders, toFile, tools, wrapOpenAIClientError };
package/dist/llms.cjs CHANGED
@@ -82,7 +82,7 @@ var OpenAI = class extends _langchain_core_language_models_llms.BaseLLM {
82
82
  clientConfig;
83
83
  constructor(fields) {
84
84
  super(fields ?? {});
85
- this._addVersion("@langchain/openai", "1.5.5");
85
+ this._addVersion("@langchain/openai", "1.5.7");
86
86
  this.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? (0, _langchain_core_utils_env.getEnvironmentVariable)("OPENAI_API_KEY");
87
87
  this.apiKey = this.openAIApiKey;
88
88
  this.organization = fields?.configuration?.organization ?? (0, _langchain_core_utils_env.getEnvironmentVariable)("OPENAI_ORGANIZATION");
package/dist/llms.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"llms.cjs","names":["BaseLLM","GenerationChunk","wrapOpenAIClientError","getEndpoint","getHeadersWithUserAgent","OpenAIClient"],"sources":["../src/llms.ts"],"sourcesContent":["import type { TiktokenModel } from \"js-tiktoken/lite\";\nimport { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { calculateMaxTokens } from \"@langchain/core/language_models/base\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { GenerationChunk, type LLMResult } from \"@langchain/core/outputs\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n BaseLLM,\n type BaseLLMParams,\n} from \"@langchain/core/language_models/llms\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type {\n OpenAIApiKey,\n OpenAICallOptions,\n OpenAICoreRequestOptions,\n OpenAIInput,\n} from \"./types.js\";\nimport {\n OpenAIEndpointConfig,\n getEndpoint,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\nexport type { OpenAICallOptions, OpenAIInput };\n\n/**\n * Interface for tracking token usage in OpenAI calls.\n */\ninterface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n\n/**\n * Wrapper around OpenAI large language models.\n *\n * To use you should have the `openai` package installed, with the\n * `OPENAI_API_KEY` environment variable set.\n *\n * To use with Azure, import the `AzureOpenAI` class.\n *\n * @remarks\n * Any parameters that are valid to be passed to {@link\n * https://platform.openai.com/docs/api-reference/completions/create |\n * `openai.createCompletion`} can be passed through {@link modelKwargs}, even\n * if not explicitly available on this class.\n * @example\n * ```typescript\n * const model = new OpenAI({\n * modelName: \"gpt-4\",\n * temperature: 0.7,\n * maxTokens: 1000,\n * maxRetries: 5,\n * });\n *\n * const res = await model.invoke(\n * \"Question: What would be a good company name for a company that makes colorful socks?\\nAnswer:\"\n * );\n * console.log({ res });\n * ```\n */\nexport class OpenAI<CallOptions extends OpenAICallOptions = OpenAICallOptions>\n extends BaseLLM<CallOptions>\n implements Partial<OpenAIInput>\n{\n static lc_name() {\n return \"OpenAI\";\n }\n\n get callKeys() {\n return [...super.callKeys, \"options\"];\n }\n\n lc_serializable = true;\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n openAIApiKey: \"OPENAI_API_KEY\",\n apiKey: \"OPENAI_API_KEY\",\n organization: \"OPENAI_ORGANIZATION\",\n };\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n modelName: \"model\",\n openAIApiKey: \"openai_api_key\",\n apiKey: \"openai_api_key\",\n };\n }\n\n temperature?: number;\n\n maxTokens?: number;\n\n topP?: number;\n\n frequencyPenalty?: number;\n\n presencePenalty?: number;\n\n n = 1;\n\n bestOf?: number;\n\n logitBias?: Record<string, number>;\n\n model = \"gpt-3.5-turbo-instruct\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n modelKwargs?: OpenAIInput[\"modelKwargs\"];\n\n batchSize = 20;\n\n timeout?: number;\n\n stop?: string[];\n\n stopSequences?: string[];\n\n user?: string;\n\n streaming = false;\n\n openAIApiKey?: OpenAIApiKey;\n\n apiKey?: OpenAIApiKey;\n\n organization?: string;\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n constructor(\n fields?: Partial<OpenAIInput> &\n BaseLLMParams & {\n configuration?: ClientOptions;\n }\n ) {\n super(fields ?? {});\n this._addVersion(\"@langchain/openai\", __PKG_VERSION__);\n\n this.openAIApiKey =\n fields?.apiKey ??\n fields?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n this.apiKey = this.openAIApiKey;\n\n this.organization =\n fields?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model = fields?.model ?? fields?.modelName ?? this.model;\n if (\n (this.model?.startsWith(\"gpt-3.5-turbo\") ||\n this.model?.startsWith(\"gpt-4\") ||\n this.model?.startsWith(\"o1\")) &&\n !this.model?.includes(\"-instruct\")\n ) {\n throw new Error(\n [\n `Your chosen OpenAI model, \"${this.model}\", is a chat model and not a text-in/text-out LLM.`,\n `Passing it into the \"OpenAI\" class is no longer supported.`,\n `Please use the \"ChatOpenAI\" class instead.`,\n \"\",\n `See this page for more information:`,\n \"|\",\n `└> https://js.langchain.com/docs/integrations/chat/openai`,\n ].join(\"\\n\")\n );\n }\n this.modelName = this.model;\n this.modelKwargs = fields?.modelKwargs ?? {};\n this.batchSize = fields?.batchSize ?? this.batchSize;\n this.timeout = fields?.timeout;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.maxTokens = fields?.maxTokens ?? this.maxTokens;\n this.topP = fields?.topP ?? this.topP;\n this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;\n this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;\n this.n = fields?.n ?? this.n;\n this.bestOf = fields?.bestOf ?? this.bestOf;\n this.logitBias = fields?.logitBias;\n this.stop = fields?.stopSequences ?? fields?.stop;\n this.stopSequences = this.stop;\n this.user = fields?.user;\n\n this.streaming = fields?.streaming ?? false;\n\n if (this.streaming && this.bestOf && this.bestOf > 1) {\n throw new Error(\"Cannot stream results when bestOf > 1\");\n }\n\n this.clientConfig = {\n apiKey: this.apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> {\n return {\n model: this.model,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n top_p: this.topP,\n frequency_penalty: this.frequencyPenalty,\n presence_penalty: this.presencePenalty,\n n: this.n,\n best_of: this.bestOf,\n logit_bias: this.logitBias,\n stop: options?.stop ?? this.stopSequences,\n user: this.user,\n stream: this.streaming,\n ...this.modelKwargs,\n };\n }\n\n /** @ignore */\n _identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n ...this.clientConfig,\n };\n }\n\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return this._identifyingParams();\n }\n\n /**\n * Call out to OpenAI's endpoint with k unique prompts\n *\n * @param [prompts] - The prompts to pass into the model.\n * @param [options] - Optional list of stop words to use when generating.\n * @param [runManager] - Optional callback manager to use when generating.\n *\n * @returns The full LLM output.\n *\n * @example\n * ```ts\n * import { OpenAI } from \"langchain/llms/openai\";\n * const openai = new OpenAI();\n * const response = await openai.generate([\"Tell me a joke.\"]);\n * ```\n */\n async _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult> {\n const subPrompts = chunkArray(prompts, this.batchSize);\n const choices: OpenAIClient.CompletionChoice[] = [];\n const tokenUsage: TokenUsage = {};\n\n const params = this.invocationParams(options);\n\n if (params.max_tokens === -1) {\n if (prompts.length !== 1) {\n throw new Error(\n \"max_tokens set to -1 not supported for multiple inputs\"\n );\n }\n params.max_tokens = await calculateMaxTokens({\n prompt: prompts[0],\n // Cast here to allow for other models that may not fit the union\n modelName: this.model as TiktokenModel,\n });\n }\n\n for (let i = 0; i < subPrompts.length; i += 1) {\n const data = params.stream\n ? await (async () => {\n const choices: OpenAIClient.CompletionChoice[] = [];\n let response: Omit<OpenAIClient.Completion, \"choices\"> | undefined;\n const stream = await this.completionWithRetry(\n {\n ...params,\n stream: true,\n prompt: subPrompts[i],\n },\n options\n );\n for await (const message of stream) {\n // on the first message set the response properties\n if (!response) {\n response = {\n id: message.id,\n object: message.object,\n created: message.created,\n model: message.model,\n };\n }\n\n // on all messages, update choice\n for (const part of message.choices) {\n if (!choices[part.index]) {\n choices[part.index] = part;\n } else {\n const choice = choices[part.index];\n choice.text += part.text;\n choice.finish_reason = part.finish_reason;\n choice.logprobs = part.logprobs;\n }\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(part.text, {\n prompt: Math.floor(part.index / this.n),\n completion: part.index % this.n,\n });\n }\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n return { ...response, choices };\n })()\n : await this.completionWithRetry(\n {\n ...params,\n stream: false,\n prompt: subPrompts[i],\n },\n {\n signal: options.signal,\n ...options.options,\n }\n );\n\n choices.push(...data.choices);\n const {\n completion_tokens: completionTokens,\n prompt_tokens: promptTokens,\n total_tokens: totalTokens,\n } = data.usage\n ? data.usage\n : {\n completion_tokens: undefined,\n prompt_tokens: undefined,\n total_tokens: undefined,\n };\n\n if (completionTokens) {\n tokenUsage.completionTokens =\n (tokenUsage.completionTokens ?? 0) + completionTokens;\n }\n\n if (promptTokens) {\n tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;\n }\n\n if (totalTokens) {\n tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;\n }\n }\n\n const generations = chunkArray(choices, this.n).map((promptChoices) =>\n promptChoices.map((choice) => ({\n text: choice.text ?? \"\",\n generationInfo: {\n finishReason: choice.finish_reason,\n logprobs: choice.logprobs,\n },\n }))\n );\n return {\n generations,\n llmOutput: { tokenUsage },\n };\n }\n\n // TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation?\n async *_streamResponseChunks(\n input: string,\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<GenerationChunk> {\n const params = {\n ...this.invocationParams(options),\n prompt: input,\n stream: true as const,\n };\n const stream = await this.completionWithRetry(params, options);\n for await (const data of stream) {\n const choice = data?.choices[0];\n if (!choice) {\n continue;\n }\n const chunk = new GenerationChunk({\n text: choice.text,\n generationInfo: {\n finishReason: choice.finish_reason,\n },\n });\n yield chunk;\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(chunk.text ?? \"\");\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Completion>>;\n\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<OpenAIClient.Completions.Completion>;\n\n async completionWithRetry(\n request:\n | OpenAIClient.CompletionCreateParamsStreaming\n | OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<\n AsyncIterable<OpenAIClient.Completion> | OpenAIClient.Completions.Completion\n > {\n const requestOptions = this._getClientOptions(options);\n return this.caller.call(async () => {\n try {\n const res = await this.client.completions.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n protected _getClientOptions(\n options: OpenAICoreRequestOptions | undefined\n ): OpenAICoreRequestOptions {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {\n ...this.clientConfig,\n ...options,\n } as OpenAICoreRequestOptions;\n return requestOptions;\n }\n\n _llmType() {\n return \"openai\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAa,SAAb,cACUA,qCAAAA,QAEV;CACE,OAAO,UAAU;AACf,SAAO;;CAGT,IAAI,WAAW;AACb,SAAO,CAAC,GAAG,MAAM,UAAU,UAAU;;CAGvC,kBAAkB;CAElB,IAAI,aAAoD;AACtD,SAAO;GACL,cAAc;GACd,QAAQ;GACR,cAAc;GACf;;CAGH,IAAI,aAAqC;AACvC,SAAO;GACL,WAAW;GACX,cAAc;GACd,QAAQ;GACT;;CAGH;CAEA;CAEA;CAEA;CAEA;CAEA,IAAI;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UserAgent","OpenAIClient"],"sources":["../src/llms.ts"],"sourcesContent":["import type { TiktokenModel } from \"js-tiktoken/lite\";\nimport { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { calculateMaxTokens } from \"@langchain/core/language_models/base\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { GenerationChunk, type LLMResult } from \"@langchain/core/outputs\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n BaseLLM,\n type BaseLLMParams,\n} from \"@langchain/core/language_models/llms\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type {\n OpenAIApiKey,\n OpenAICallOptions,\n OpenAICoreRequestOptions,\n OpenAIInput,\n} from \"./types.js\";\nimport {\n OpenAIEndpointConfig,\n getEndpoint,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\nexport type { OpenAICallOptions, OpenAIInput };\n\n/**\n * Interface for tracking token usage in OpenAI calls.\n */\ninterface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n\n/**\n * Wrapper around OpenAI large language models.\n *\n * To use you should have the `openai` package installed, with the\n * `OPENAI_API_KEY` environment variable set.\n *\n * To use with Azure, import the `AzureOpenAI` class.\n *\n * @remarks\n * Any parameters that are valid to be passed to {@link\n * https://platform.openai.com/docs/api-reference/completions/create |\n * `openai.createCompletion`} can be passed through {@link modelKwargs}, even\n * if not explicitly available on this class.\n * @example\n * ```typescript\n * const model = new OpenAI({\n * modelName: \"gpt-4\",\n * temperature: 0.7,\n * maxTokens: 1000,\n * maxRetries: 5,\n * });\n *\n * const res = await model.invoke(\n * \"Question: What would be a good company name for a company that makes colorful socks?\\nAnswer:\"\n * );\n * console.log({ res });\n * ```\n */\nexport class OpenAI<CallOptions extends OpenAICallOptions = OpenAICallOptions>\n extends BaseLLM<CallOptions>\n implements Partial<OpenAIInput>\n{\n static lc_name() {\n return \"OpenAI\";\n }\n\n get callKeys() {\n return [...super.callKeys, \"options\"];\n }\n\n lc_serializable = true;\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n openAIApiKey: \"OPENAI_API_KEY\",\n apiKey: \"OPENAI_API_KEY\",\n organization: \"OPENAI_ORGANIZATION\",\n };\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n modelName: \"model\",\n openAIApiKey: \"openai_api_key\",\n apiKey: \"openai_api_key\",\n };\n }\n\n temperature?: number;\n\n maxTokens?: number;\n\n topP?: number;\n\n frequencyPenalty?: number;\n\n presencePenalty?: number;\n\n n = 1;\n\n bestOf?: number;\n\n logitBias?: Record<string, number>;\n\n model = \"gpt-3.5-turbo-instruct\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n modelKwargs?: OpenAIInput[\"modelKwargs\"];\n\n batchSize = 20;\n\n timeout?: number;\n\n stop?: string[];\n\n stopSequences?: string[];\n\n user?: string;\n\n streaming = false;\n\n openAIApiKey?: OpenAIApiKey;\n\n apiKey?: OpenAIApiKey;\n\n organization?: string;\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n constructor(\n fields?: Partial<OpenAIInput> &\n BaseLLMParams & {\n configuration?: ClientOptions;\n }\n ) {\n super(fields ?? {});\n this._addVersion(\"@langchain/openai\", __PKG_VERSION__);\n\n this.openAIApiKey =\n fields?.apiKey ??\n fields?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n this.apiKey = this.openAIApiKey;\n\n this.organization =\n fields?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model = fields?.model ?? fields?.modelName ?? this.model;\n if (\n (this.model?.startsWith(\"gpt-3.5-turbo\") ||\n this.model?.startsWith(\"gpt-4\") ||\n this.model?.startsWith(\"o1\")) &&\n !this.model?.includes(\"-instruct\")\n ) {\n throw new Error(\n [\n `Your chosen OpenAI model, \"${this.model}\", is a chat model and not a text-in/text-out LLM.`,\n `Passing it into the \"OpenAI\" class is no longer supported.`,\n `Please use the \"ChatOpenAI\" class instead.`,\n \"\",\n `See this page for more information:`,\n \"|\",\n `└> https://js.langchain.com/docs/integrations/chat/openai`,\n ].join(\"\\n\")\n );\n }\n this.modelName = this.model;\n this.modelKwargs = fields?.modelKwargs ?? {};\n this.batchSize = fields?.batchSize ?? this.batchSize;\n this.timeout = fields?.timeout;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.maxTokens = fields?.maxTokens ?? this.maxTokens;\n this.topP = fields?.topP ?? this.topP;\n this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;\n this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;\n this.n = fields?.n ?? this.n;\n this.bestOf = fields?.bestOf ?? this.bestOf;\n this.logitBias = fields?.logitBias;\n this.stop = fields?.stopSequences ?? fields?.stop;\n this.stopSequences = this.stop;\n this.user = fields?.user;\n\n this.streaming = fields?.streaming ?? false;\n\n if (this.streaming && this.bestOf && this.bestOf > 1) {\n throw new Error(\"Cannot stream results when bestOf > 1\");\n }\n\n this.clientConfig = {\n apiKey: this.apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> {\n return {\n model: this.model,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n top_p: this.topP,\n frequency_penalty: this.frequencyPenalty,\n presence_penalty: this.presencePenalty,\n n: this.n,\n best_of: this.bestOf,\n logit_bias: this.logitBias,\n stop: options?.stop ?? this.stopSequences,\n user: this.user,\n stream: this.streaming,\n ...this.modelKwargs,\n };\n }\n\n /** @ignore */\n _identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n ...this.clientConfig,\n };\n }\n\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return this._identifyingParams();\n }\n\n /**\n * Call out to OpenAI's endpoint with k unique prompts\n *\n * @param [prompts] - The prompts to pass into the model.\n * @param [options] - Optional list of stop words to use when generating.\n * @param [runManager] - Optional callback manager to use when generating.\n *\n * @returns The full LLM output.\n *\n * @example\n * ```ts\n * import { OpenAI } from \"langchain/llms/openai\";\n * const openai = new OpenAI();\n * const response = await openai.generate([\"Tell me a joke.\"]);\n * ```\n */\n async _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult> {\n const subPrompts = chunkArray(prompts, this.batchSize);\n const choices: OpenAIClient.CompletionChoice[] = [];\n const tokenUsage: TokenUsage = {};\n\n const params = this.invocationParams(options);\n\n if (params.max_tokens === -1) {\n if (prompts.length !== 1) {\n throw new Error(\n \"max_tokens set to -1 not supported for multiple inputs\"\n );\n }\n params.max_tokens = await calculateMaxTokens({\n prompt: prompts[0],\n // Cast here to allow for other models that may not fit the union\n modelName: this.model as TiktokenModel,\n });\n }\n\n for (let i = 0; i < subPrompts.length; i += 1) {\n const data = params.stream\n ? await (async () => {\n const choices: OpenAIClient.CompletionChoice[] = [];\n let response: Omit<OpenAIClient.Completion, \"choices\"> | undefined;\n const stream = await this.completionWithRetry(\n {\n ...params,\n stream: true,\n prompt: subPrompts[i],\n },\n options\n );\n for await (const message of stream) {\n // on the first message set the response properties\n if (!response) {\n response = {\n id: message.id,\n object: message.object,\n created: message.created,\n model: message.model,\n };\n }\n\n // on all messages, update choice\n for (const part of message.choices) {\n if (!choices[part.index]) {\n choices[part.index] = part;\n } else {\n const choice = choices[part.index];\n choice.text += part.text;\n choice.finish_reason = part.finish_reason;\n choice.logprobs = part.logprobs;\n }\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(part.text, {\n prompt: Math.floor(part.index / this.n),\n completion: part.index % this.n,\n });\n }\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n return { ...response, choices };\n })()\n : await this.completionWithRetry(\n {\n ...params,\n stream: false,\n prompt: subPrompts[i],\n },\n {\n signal: options.signal,\n ...options.options,\n }\n );\n\n choices.push(...data.choices);\n const {\n completion_tokens: completionTokens,\n prompt_tokens: promptTokens,\n total_tokens: totalTokens,\n } = data.usage\n ? data.usage\n : {\n completion_tokens: undefined,\n prompt_tokens: undefined,\n total_tokens: undefined,\n };\n\n if (completionTokens) {\n tokenUsage.completionTokens =\n (tokenUsage.completionTokens ?? 0) + completionTokens;\n }\n\n if (promptTokens) {\n tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;\n }\n\n if (totalTokens) {\n tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;\n }\n }\n\n const generations = chunkArray(choices, this.n).map((promptChoices) =>\n promptChoices.map((choice) => ({\n text: choice.text ?? \"\",\n generationInfo: {\n finishReason: choice.finish_reason,\n logprobs: choice.logprobs,\n },\n }))\n );\n return {\n generations,\n llmOutput: { tokenUsage },\n };\n }\n\n // TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation?\n async *_streamResponseChunks(\n input: string,\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<GenerationChunk> {\n const params = {\n ...this.invocationParams(options),\n prompt: input,\n stream: true as const,\n };\n const stream = await this.completionWithRetry(params, options);\n for await (const data of stream) {\n const choice = data?.choices[0];\n if (!choice) {\n continue;\n }\n const chunk = new GenerationChunk({\n text: choice.text,\n generationInfo: {\n finishReason: choice.finish_reason,\n },\n });\n yield chunk;\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(chunk.text ?? \"\");\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Completion>>;\n\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<OpenAIClient.Completions.Completion>;\n\n async completionWithRetry(\n request:\n | OpenAIClient.CompletionCreateParamsStreaming\n | OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<\n AsyncIterable<OpenAIClient.Completion> | OpenAIClient.Completions.Completion\n > {\n const requestOptions = this._getClientOptions(options);\n return this.caller.call(async () => {\n try {\n const res = await this.client.completions.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n protected _getClientOptions(\n options: OpenAICoreRequestOptions | undefined\n ): OpenAICoreRequestOptions {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {\n ...this.clientConfig,\n ...options,\n } as OpenAICoreRequestOptions;\n return requestOptions;\n }\n\n _llmType() {\n return \"openai\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAa,SAAb,cACUA,qCAAAA,QAEV;CACE,OAAO,UAAU;EACf,OAAO;CACT;CAEA,IAAI,WAAW;EACb,OA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;IACb,GAAG,KAAK;IACR,SAAS;IACT,SAAS,KAAK;IACd,YAAY;GACd;GAEA,IAAI,CAAC,OAAO,SACV,OAAO,OAAO;GAGhB,OAAO,iBAAiBC,cAAAA,wBAAwB,OAAO,cAAc;GAErE,KAAK,SAAS,IAAIC,OAAAA,OAAa,MAAM;EACvC;EAKA,OAAO;GAHL,GAAG,KAAK;GACR,GAAG;EAEe;CACtB;CAEA,WAAW;EACT,OAAO;CACT;AACF"}
package/dist/llms.d.cts CHANGED
@@ -3,7 +3,6 @@ import { ClientOptions, OpenAI } from "openai";
3
3
  import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
4
4
  import { GenerationChunk, LLMResult } from "@langchain/core/outputs";
5
5
  import { BaseLLM, BaseLLMParams } from "@langchain/core/language_models/llms";
6
-
7
6
  //#region src/llms.d.ts
8
7
  /**
9
8
  * Wrapper around OpenAI large language models.
@@ -117,5 +116,5 @@ declare class OpenAI$2<CallOptions extends OpenAICallOptions = OpenAICallOptions
117
116
  _llmType(): string;
118
117
  }
119
118
  //#endregion
120
- export { OpenAI$2 as OpenAI };
119
+ export { OpenAI$2 as OpenAI, type OpenAICallOptions, type OpenAIInput };
121
120
  //# sourceMappingURL=llms.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"llms.d.cts","names":[],"sources":["../src/llms.ts"],"mappings":";;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,QAAA,qBAA2B,iBAAA,GAAoB,iBAAA,UAClD,OAAA,CAAQ,WAAA,aACL,OAAA,CAAQ,WAAA;EAAA,OAEZ,OAAA,CAAA;EAAA,IAIH,QAAA,CAAA;EAIJ,eAAA;EAAA,IAEI,UAAA,CAAA;IAAA,CAAiB,GAAA;EAAA;EAAA,IAQjB,UAAA,CAAA,GAAc,MAAA;EAQlB,WAAA;EAEA,SAAA;EAEA,IAAA;EAEA,gBAAA;EAEA,eAAA;EAEA,CAAA;EAEA,MAAA;EAEA,SAAA,GAAY,MA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA+Da,SAAO,oBAAoB,oBAAoB,2BAClD,QAAQ,wBACL,QAAQ;SAEZ;MAIH;EAIJ;MAEI;KAAiB;;MAQjB,cAAc;EAQlB;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA,YAAY;EAEZ;;EAGA;EAEA,cAAc;EAEd;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA,eAAe;EAEf,SAAS;EAET;YAEU,QAAQ;YAER,cAAc;EAExB,YACE,SAAS,QAAQ,eACf;IACE,gBAAgB;;;;;EAqEtB,iBACE,sCACC,KAAK,OAAa;;EAmBrB,sBAAsB,KAAK,OAAa;IACtC;MACE;;;;EAWJ,qBAAqB,KAAK,OAAa;IACrC;MACE;;;;;;;;;;;;;;;;;EAoBE,UACJ,mBACA,oCACA,aAAa,2BACZ,QAAQ;EAyHJ,sBACL,eACA,oCACA,aAAa,2BACZ,eAAe;;;;;;;EAiCZ,oBACJ,SAAS,OAAa,iCACtB,UAAU,2BACT,QAAQ,cAAc,OAAa;EAEhC,oBACJ,SAAS,OAAa,oCACtB,UAAU,2BACT,QAAQ,OAAa,YAAY;;;;;;;YA+B1B,kBACR,SAAS,uCACR;EA8BH"}
package/dist/llms.d.ts CHANGED
@@ -3,7 +3,6 @@ import { ClientOptions, OpenAI } from "openai";
3
3
  import { GenerationChunk, LLMResult } from "@langchain/core/outputs";
4
4
  import { BaseLLM, BaseLLMParams } from "@langchain/core/language_models/llms";
5
5
  import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
6
-
7
6
  //#region src/llms.d.ts
8
7
  /**
9
8
  * Wrapper around OpenAI large language models.
@@ -117,5 +116,5 @@ declare class OpenAI$2<CallOptions extends OpenAICallOptions = OpenAICallOptions
117
116
  _llmType(): string;
118
117
  }
119
118
  //#endregion
120
- export { OpenAI$2 as OpenAI };
119
+ export { OpenAI$2 as OpenAI, type OpenAICallOptions, type OpenAIInput };
121
120
  //# sourceMappingURL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CACR;EA8BH"}
package/dist/llms.js CHANGED
@@ -82,7 +82,7 @@ var OpenAI$2 = class extends BaseLLM {
82
82
  clientConfig;
83
83
  constructor(fields) {
84
84
  super(fields ?? {});
85
- this._addVersion("@langchain/openai", "1.5.5");
85
+ this._addVersion("@langchain/openai", "1.5.7");
86
86
  this.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
87
87
  this.apiKey = this.openAIApiKey;
88
88
  this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION");
package/dist/llms.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"llms.js","names":["OpenAI","OpenAIClient"],"sources":["../src/llms.ts"],"sourcesContent":["import type { TiktokenModel } from \"js-tiktoken/lite\";\nimport { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { calculateMaxTokens } from \"@langchain/core/language_models/base\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { GenerationChunk, type LLMResult } from \"@langchain/core/outputs\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n BaseLLM,\n type BaseLLMParams,\n} from \"@langchain/core/language_models/llms\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type {\n OpenAIApiKey,\n OpenAICallOptions,\n OpenAICoreRequestOptions,\n OpenAIInput,\n} from \"./types.js\";\nimport {\n OpenAIEndpointConfig,\n getEndpoint,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\nexport type { OpenAICallOptions, OpenAIInput };\n\n/**\n * Interface for tracking token usage in OpenAI calls.\n */\ninterface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n\n/**\n * Wrapper around OpenAI large language models.\n *\n * To use you should have the `openai` package installed, with the\n * `OPENAI_API_KEY` environment variable set.\n *\n * To use with Azure, import the `AzureOpenAI` class.\n *\n * @remarks\n * Any parameters that are valid to be passed to {@link\n * https://platform.openai.com/docs/api-reference/completions/create |\n * `openai.createCompletion`} can be passed through {@link modelKwargs}, even\n * if not explicitly available on this class.\n * @example\n * ```typescript\n * const model = new OpenAI({\n * modelName: \"gpt-4\",\n * temperature: 0.7,\n * maxTokens: 1000,\n * maxRetries: 5,\n * });\n *\n * const res = await model.invoke(\n * \"Question: What would be a good company name for a company that makes colorful socks?\\nAnswer:\"\n * );\n * console.log({ res });\n * ```\n */\nexport class OpenAI<CallOptions extends OpenAICallOptions = OpenAICallOptions>\n extends BaseLLM<CallOptions>\n implements Partial<OpenAIInput>\n{\n static lc_name() {\n return \"OpenAI\";\n }\n\n get callKeys() {\n return [...super.callKeys, \"options\"];\n }\n\n lc_serializable = true;\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n openAIApiKey: \"OPENAI_API_KEY\",\n apiKey: \"OPENAI_API_KEY\",\n organization: \"OPENAI_ORGANIZATION\",\n };\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n modelName: \"model\",\n openAIApiKey: \"openai_api_key\",\n apiKey: \"openai_api_key\",\n };\n }\n\n temperature?: number;\n\n maxTokens?: number;\n\n topP?: number;\n\n frequencyPenalty?: number;\n\n presencePenalty?: number;\n\n n = 1;\n\n bestOf?: number;\n\n logitBias?: Record<string, number>;\n\n model = \"gpt-3.5-turbo-instruct\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n modelKwargs?: OpenAIInput[\"modelKwargs\"];\n\n batchSize = 20;\n\n timeout?: number;\n\n stop?: string[];\n\n stopSequences?: string[];\n\n user?: string;\n\n streaming = false;\n\n openAIApiKey?: OpenAIApiKey;\n\n apiKey?: OpenAIApiKey;\n\n organization?: string;\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n constructor(\n fields?: Partial<OpenAIInput> &\n BaseLLMParams & {\n configuration?: ClientOptions;\n }\n ) {\n super(fields ?? {});\n this._addVersion(\"@langchain/openai\", __PKG_VERSION__);\n\n this.openAIApiKey =\n fields?.apiKey ??\n fields?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n this.apiKey = this.openAIApiKey;\n\n this.organization =\n fields?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model = fields?.model ?? fields?.modelName ?? this.model;\n if (\n (this.model?.startsWith(\"gpt-3.5-turbo\") ||\n this.model?.startsWith(\"gpt-4\") ||\n this.model?.startsWith(\"o1\")) &&\n !this.model?.includes(\"-instruct\")\n ) {\n throw new Error(\n [\n `Your chosen OpenAI model, \"${this.model}\", is a chat model and not a text-in/text-out LLM.`,\n `Passing it into the \"OpenAI\" class is no longer supported.`,\n `Please use the \"ChatOpenAI\" class instead.`,\n \"\",\n `See this page for more information:`,\n \"|\",\n `└> https://js.langchain.com/docs/integrations/chat/openai`,\n ].join(\"\\n\")\n );\n }\n this.modelName = this.model;\n this.modelKwargs = fields?.modelKwargs ?? {};\n this.batchSize = fields?.batchSize ?? this.batchSize;\n this.timeout = fields?.timeout;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.maxTokens = fields?.maxTokens ?? this.maxTokens;\n this.topP = fields?.topP ?? this.topP;\n this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;\n this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;\n this.n = fields?.n ?? this.n;\n this.bestOf = fields?.bestOf ?? this.bestOf;\n this.logitBias = fields?.logitBias;\n this.stop = fields?.stopSequences ?? fields?.stop;\n this.stopSequences = this.stop;\n this.user = fields?.user;\n\n this.streaming = fields?.streaming ?? false;\n\n if (this.streaming && this.bestOf && this.bestOf > 1) {\n throw new Error(\"Cannot stream results when bestOf > 1\");\n }\n\n this.clientConfig = {\n apiKey: this.apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> {\n return {\n model: this.model,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n top_p: this.topP,\n frequency_penalty: this.frequencyPenalty,\n presence_penalty: this.presencePenalty,\n n: this.n,\n best_of: this.bestOf,\n logit_bias: this.logitBias,\n stop: options?.stop ?? this.stopSequences,\n user: this.user,\n stream: this.streaming,\n ...this.modelKwargs,\n };\n }\n\n /** @ignore */\n _identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n ...this.clientConfig,\n };\n }\n\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return this._identifyingParams();\n }\n\n /**\n * Call out to OpenAI's endpoint with k unique prompts\n *\n * @param [prompts] - The prompts to pass into the model.\n * @param [options] - Optional list of stop words to use when generating.\n * @param [runManager] - Optional callback manager to use when generating.\n *\n * @returns The full LLM output.\n *\n * @example\n * ```ts\n * import { OpenAI } from \"langchain/llms/openai\";\n * const openai = new OpenAI();\n * const response = await openai.generate([\"Tell me a joke.\"]);\n * ```\n */\n async _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult> {\n const subPrompts = chunkArray(prompts, this.batchSize);\n const choices: OpenAIClient.CompletionChoice[] = [];\n const tokenUsage: TokenUsage = {};\n\n const params = this.invocationParams(options);\n\n if (params.max_tokens === -1) {\n if (prompts.length !== 1) {\n throw new Error(\n \"max_tokens set to -1 not supported for multiple inputs\"\n );\n }\n params.max_tokens = await calculateMaxTokens({\n prompt: prompts[0],\n // Cast here to allow for other models that may not fit the union\n modelName: this.model as TiktokenModel,\n });\n }\n\n for (let i = 0; i < subPrompts.length; i += 1) {\n const data = params.stream\n ? await (async () => {\n const choices: OpenAIClient.CompletionChoice[] = [];\n let response: Omit<OpenAIClient.Completion, \"choices\"> | undefined;\n const stream = await this.completionWithRetry(\n {\n ...params,\n stream: true,\n prompt: subPrompts[i],\n },\n options\n );\n for await (const message of stream) {\n // on the first message set the response properties\n if (!response) {\n response = {\n id: message.id,\n object: message.object,\n created: message.created,\n model: message.model,\n };\n }\n\n // on all messages, update choice\n for (const part of message.choices) {\n if (!choices[part.index]) {\n choices[part.index] = part;\n } else {\n const choice = choices[part.index];\n choice.text += part.text;\n choice.finish_reason = part.finish_reason;\n choice.logprobs = part.logprobs;\n }\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(part.text, {\n prompt: Math.floor(part.index / this.n),\n completion: part.index % this.n,\n });\n }\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n return { ...response, choices };\n })()\n : await this.completionWithRetry(\n {\n ...params,\n stream: false,\n prompt: subPrompts[i],\n },\n {\n signal: options.signal,\n ...options.options,\n }\n );\n\n choices.push(...data.choices);\n const {\n completion_tokens: completionTokens,\n prompt_tokens: promptTokens,\n total_tokens: totalTokens,\n } = data.usage\n ? data.usage\n : {\n completion_tokens: undefined,\n prompt_tokens: undefined,\n total_tokens: undefined,\n };\n\n if (completionTokens) {\n tokenUsage.completionTokens =\n (tokenUsage.completionTokens ?? 0) + completionTokens;\n }\n\n if (promptTokens) {\n tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;\n }\n\n if (totalTokens) {\n tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;\n }\n }\n\n const generations = chunkArray(choices, this.n).map((promptChoices) =>\n promptChoices.map((choice) => ({\n text: choice.text ?? \"\",\n generationInfo: {\n finishReason: choice.finish_reason,\n logprobs: choice.logprobs,\n },\n }))\n );\n return {\n generations,\n llmOutput: { tokenUsage },\n };\n }\n\n // TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation?\n async *_streamResponseChunks(\n input: string,\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<GenerationChunk> {\n const params = {\n ...this.invocationParams(options),\n prompt: input,\n stream: true as const,\n };\n const stream = await this.completionWithRetry(params, options);\n for await (const data of stream) {\n const choice = data?.choices[0];\n if (!choice) {\n continue;\n }\n const chunk = new GenerationChunk({\n text: choice.text,\n generationInfo: {\n finishReason: choice.finish_reason,\n },\n });\n yield chunk;\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(chunk.text ?? \"\");\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Completion>>;\n\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<OpenAIClient.Completions.Completion>;\n\n async completionWithRetry(\n request:\n | OpenAIClient.CompletionCreateParamsStreaming\n | OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<\n AsyncIterable<OpenAIClient.Completion> | OpenAIClient.Completions.Completion\n > {\n const requestOptions = this._getClientOptions(options);\n return this.caller.call(async () => {\n try {\n const res = await this.client.completions.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n protected _getClientOptions(\n options: OpenAICoreRequestOptions | undefined\n ): OpenAICoreRequestOptions {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {\n ...this.clientConfig,\n ...options,\n } as OpenAICoreRequestOptions;\n return requestOptions;\n }\n\n _llmType() {\n return \"openai\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAaA,WAAb,cACU,QAEV;CACE,OAAO,UAAU;AACf,SAAO;;CAGT,IAAI,WAAW;AACb,SAAO,CAAC,GAAG,MAAM,UAAU,UAAU;;CAGvC,kBAAkB;CAElB,IAAI,aAAoD;AACtD,SAAO;GACL,cAAc;GACd,QAAQ;GACR,cAAc;GACf;;CAGH,IAAI,aAAqC;AACvC,SAAO;GACL,WAAW;GACX,cAAc;GACd,QAAQ;GACT;;CAGH;CAEA;CAEA;CAEA;CAEA;CAEA,IAAI;CAEJ;CAEA;CAEA,QAAQ;;CAGR;CAEA;CAEA,YAAY;CAEZ;CAEA;CAEA;CAEA;CAEA,YAAY;CAEZ;CAEA;CAEA;CAEA;CAEA;CAEA,YACE,QAIA;AACA,QAAM,UAAU,EAAE,CAAC;AACnB,OAAK,YAAY,qBAAA,QAAqC;AAEtD,OAAK,eACH,QAAQ,UACR,QAAQ,gBACR,uBAAuB,iBAAiB;AAC1C,OAAK,SAAS,KAAK;AAEnB,OAAK,eACH,QAAQ,eAAe,gBACvB,uBAAuB,sBAAsB;AAE/C,OAAK,QAAQ,QAAQ,SAAS,QAAQ,aAAa,KAAK;AACxD,OACG,KAAK,OAAO,WAAW,gBAAgB,IACtC,KAAK,OAAO,WAAW,QAAQ,IAC/B,KAAK,OAAO,WAAW,KAAK,KAC9B,CAAC,KAAK,OAAO,SAAS,YAAY,CAElC,OAAM,IAAI,MACR;GACE,8BAA8B,KAAK,MAAM;GACzC;GACA;GACA;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SACA,eACD;YAEM,GAAG;AAEV,UADc,sBAAsB,EACzB;;IAEb;;;;;;;;CASJ,kBACE,SAC0B;AAC1B,MAAI,CAAC,KAAK,QAAQ;GAKhB,MAAM,WAAW,YAAY,EAH3B,SAAS,KAAK,aAAa,SAGoB,CAAC;GAElD,MAAM,SAAS;IACb,GAAG,KAAK;IACR,SAAS;IACT,SAAS,KAAK;IACd,YAAY;IACb;AAED,OAAI,CAAC,OAAO,QACV,QAAO,OAAO;AAGhB,UAAO,iBAAiB,wBAAwB,OAAO,eAAe;AAEtE,QAAK,SAAS,IAAIC,OAAa,OAAO;;AAMxC,SAAO;GAHL,GAAG,KAAK;GACR,GAAG;GAEgB;;CAGvB,WAAW;AACT,SAAO"}
1
+ {"version":3,"file":"llms.js","names":["OpenAI","OpenAIClient"],"sources":["../src/llms.ts"],"sourcesContent":["import type { TiktokenModel } from \"js-tiktoken/lite\";\nimport { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { calculateMaxTokens } from \"@langchain/core/language_models/base\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { GenerationChunk, type LLMResult } from \"@langchain/core/outputs\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n BaseLLM,\n type BaseLLMParams,\n} from \"@langchain/core/language_models/llms\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type {\n OpenAIApiKey,\n OpenAICallOptions,\n OpenAICoreRequestOptions,\n OpenAIInput,\n} from \"./types.js\";\nimport {\n OpenAIEndpointConfig,\n getEndpoint,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\nexport type { OpenAICallOptions, OpenAIInput };\n\n/**\n * Interface for tracking token usage in OpenAI calls.\n */\ninterface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n\n/**\n * Wrapper around OpenAI large language models.\n *\n * To use you should have the `openai` package installed, with the\n * `OPENAI_API_KEY` environment variable set.\n *\n * To use with Azure, import the `AzureOpenAI` class.\n *\n * @remarks\n * Any parameters that are valid to be passed to {@link\n * https://platform.openai.com/docs/api-reference/completions/create |\n * `openai.createCompletion`} can be passed through {@link modelKwargs}, even\n * if not explicitly available on this class.\n * @example\n * ```typescript\n * const model = new OpenAI({\n * modelName: \"gpt-4\",\n * temperature: 0.7,\n * maxTokens: 1000,\n * maxRetries: 5,\n * });\n *\n * const res = await model.invoke(\n * \"Question: What would be a good company name for a company that makes colorful socks?\\nAnswer:\"\n * );\n * console.log({ res });\n * ```\n */\nexport class OpenAI<CallOptions extends OpenAICallOptions = OpenAICallOptions>\n extends BaseLLM<CallOptions>\n implements Partial<OpenAIInput>\n{\n static lc_name() {\n return \"OpenAI\";\n }\n\n get callKeys() {\n return [...super.callKeys, \"options\"];\n }\n\n lc_serializable = true;\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n openAIApiKey: \"OPENAI_API_KEY\",\n apiKey: \"OPENAI_API_KEY\",\n organization: \"OPENAI_ORGANIZATION\",\n };\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n modelName: \"model\",\n openAIApiKey: \"openai_api_key\",\n apiKey: \"openai_api_key\",\n };\n }\n\n temperature?: number;\n\n maxTokens?: number;\n\n topP?: number;\n\n frequencyPenalty?: number;\n\n presencePenalty?: number;\n\n n = 1;\n\n bestOf?: number;\n\n logitBias?: Record<string, number>;\n\n model = \"gpt-3.5-turbo-instruct\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n modelKwargs?: OpenAIInput[\"modelKwargs\"];\n\n batchSize = 20;\n\n timeout?: number;\n\n stop?: string[];\n\n stopSequences?: string[];\n\n user?: string;\n\n streaming = false;\n\n openAIApiKey?: OpenAIApiKey;\n\n apiKey?: OpenAIApiKey;\n\n organization?: string;\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n constructor(\n fields?: Partial<OpenAIInput> &\n BaseLLMParams & {\n configuration?: ClientOptions;\n }\n ) {\n super(fields ?? {});\n this._addVersion(\"@langchain/openai\", __PKG_VERSION__);\n\n this.openAIApiKey =\n fields?.apiKey ??\n fields?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n this.apiKey = this.openAIApiKey;\n\n this.organization =\n fields?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model = fields?.model ?? fields?.modelName ?? this.model;\n if (\n (this.model?.startsWith(\"gpt-3.5-turbo\") ||\n this.model?.startsWith(\"gpt-4\") ||\n this.model?.startsWith(\"o1\")) &&\n !this.model?.includes(\"-instruct\")\n ) {\n throw new Error(\n [\n `Your chosen OpenAI model, \"${this.model}\", is a chat model and not a text-in/text-out LLM.`,\n `Passing it into the \"OpenAI\" class is no longer supported.`,\n `Please use the \"ChatOpenAI\" class instead.`,\n \"\",\n `See this page for more information:`,\n \"|\",\n `└> https://js.langchain.com/docs/integrations/chat/openai`,\n ].join(\"\\n\")\n );\n }\n this.modelName = this.model;\n this.modelKwargs = fields?.modelKwargs ?? {};\n this.batchSize = fields?.batchSize ?? this.batchSize;\n this.timeout = fields?.timeout;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.maxTokens = fields?.maxTokens ?? this.maxTokens;\n this.topP = fields?.topP ?? this.topP;\n this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;\n this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;\n this.n = fields?.n ?? this.n;\n this.bestOf = fields?.bestOf ?? this.bestOf;\n this.logitBias = fields?.logitBias;\n this.stop = fields?.stopSequences ?? fields?.stop;\n this.stopSequences = this.stop;\n this.user = fields?.user;\n\n this.streaming = fields?.streaming ?? false;\n\n if (this.streaming && this.bestOf && this.bestOf > 1) {\n throw new Error(\"Cannot stream results when bestOf > 1\");\n }\n\n this.clientConfig = {\n apiKey: this.apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> {\n return {\n model: this.model,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n top_p: this.topP,\n frequency_penalty: this.frequencyPenalty,\n presence_penalty: this.presencePenalty,\n n: this.n,\n best_of: this.bestOf,\n logit_bias: this.logitBias,\n stop: options?.stop ?? this.stopSequences,\n user: this.user,\n stream: this.streaming,\n ...this.modelKwargs,\n };\n }\n\n /** @ignore */\n _identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n ...this.clientConfig,\n };\n }\n\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams(): Omit<OpenAIClient.CompletionCreateParams, \"prompt\"> & {\n model_name: string;\n } & ClientOptions {\n return this._identifyingParams();\n }\n\n /**\n * Call out to OpenAI's endpoint with k unique prompts\n *\n * @param [prompts] - The prompts to pass into the model.\n * @param [options] - Optional list of stop words to use when generating.\n * @param [runManager] - Optional callback manager to use when generating.\n *\n * @returns The full LLM output.\n *\n * @example\n * ```ts\n * import { OpenAI } from \"langchain/llms/openai\";\n * const openai = new OpenAI();\n * const response = await openai.generate([\"Tell me a joke.\"]);\n * ```\n */\n async _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult> {\n const subPrompts = chunkArray(prompts, this.batchSize);\n const choices: OpenAIClient.CompletionChoice[] = [];\n const tokenUsage: TokenUsage = {};\n\n const params = this.invocationParams(options);\n\n if (params.max_tokens === -1) {\n if (prompts.length !== 1) {\n throw new Error(\n \"max_tokens set to -1 not supported for multiple inputs\"\n );\n }\n params.max_tokens = await calculateMaxTokens({\n prompt: prompts[0],\n // Cast here to allow for other models that may not fit the union\n modelName: this.model as TiktokenModel,\n });\n }\n\n for (let i = 0; i < subPrompts.length; i += 1) {\n const data = params.stream\n ? await (async () => {\n const choices: OpenAIClient.CompletionChoice[] = [];\n let response: Omit<OpenAIClient.Completion, \"choices\"> | undefined;\n const stream = await this.completionWithRetry(\n {\n ...params,\n stream: true,\n prompt: subPrompts[i],\n },\n options\n );\n for await (const message of stream) {\n // on the first message set the response properties\n if (!response) {\n response = {\n id: message.id,\n object: message.object,\n created: message.created,\n model: message.model,\n };\n }\n\n // on all messages, update choice\n for (const part of message.choices) {\n if (!choices[part.index]) {\n choices[part.index] = part;\n } else {\n const choice = choices[part.index];\n choice.text += part.text;\n choice.finish_reason = part.finish_reason;\n choice.logprobs = part.logprobs;\n }\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(part.text, {\n prompt: Math.floor(part.index / this.n),\n completion: part.index % this.n,\n });\n }\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n return { ...response, choices };\n })()\n : await this.completionWithRetry(\n {\n ...params,\n stream: false,\n prompt: subPrompts[i],\n },\n {\n signal: options.signal,\n ...options.options,\n }\n );\n\n choices.push(...data.choices);\n const {\n completion_tokens: completionTokens,\n prompt_tokens: promptTokens,\n total_tokens: totalTokens,\n } = data.usage\n ? data.usage\n : {\n completion_tokens: undefined,\n prompt_tokens: undefined,\n total_tokens: undefined,\n };\n\n if (completionTokens) {\n tokenUsage.completionTokens =\n (tokenUsage.completionTokens ?? 0) + completionTokens;\n }\n\n if (promptTokens) {\n tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;\n }\n\n if (totalTokens) {\n tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;\n }\n }\n\n const generations = chunkArray(choices, this.n).map((promptChoices) =>\n promptChoices.map((choice) => ({\n text: choice.text ?? \"\",\n generationInfo: {\n finishReason: choice.finish_reason,\n logprobs: choice.logprobs,\n },\n }))\n );\n return {\n generations,\n llmOutput: { tokenUsage },\n };\n }\n\n // TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation?\n async *_streamResponseChunks(\n input: string,\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<GenerationChunk> {\n const params = {\n ...this.invocationParams(options),\n prompt: input,\n stream: true as const,\n };\n const stream = await this.completionWithRetry(params, options);\n for await (const data of stream) {\n const choice = data?.choices[0];\n if (!choice) {\n continue;\n }\n const chunk = new GenerationChunk({\n text: choice.text,\n generationInfo: {\n finishReason: choice.finish_reason,\n },\n });\n yield chunk;\n // oxlint-disable-next-line no-void\n void runManager?.handleLLMNewToken(chunk.text ?? \"\");\n }\n if (options.signal?.aborted) {\n throw new Error(\"AbortError\");\n }\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Completion>>;\n\n async completionWithRetry(\n request: OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<OpenAIClient.Completions.Completion>;\n\n async completionWithRetry(\n request:\n | OpenAIClient.CompletionCreateParamsStreaming\n | OpenAIClient.CompletionCreateParamsNonStreaming,\n options?: OpenAICoreRequestOptions\n ): Promise<\n AsyncIterable<OpenAIClient.Completion> | OpenAIClient.Completions.Completion\n > {\n const requestOptions = this._getClientOptions(options);\n return this.caller.call(async () => {\n try {\n const res = await this.client.completions.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /**\n * Calls the OpenAI API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n protected _getClientOptions(\n options: OpenAICoreRequestOptions | undefined\n ): OpenAICoreRequestOptions {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {\n ...this.clientConfig,\n ...options,\n } as OpenAICoreRequestOptions;\n return requestOptions;\n }\n\n _llmType() {\n return \"openai\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAaA,WAAb,cACU,QAEV;CACE,OAAO,UAAU;EACf,OAAO;CACT;CAEA,IAAI,WAAW;EACb,OAAO,CAAC,GAAG,MAAM,UAAU,SAAS;CACtC;CAEA,kBAAkB;CAElB,IAAI,aAAoD;EACtD,OAAO;GACL,cAAc;GACd,QAAQ;GACR,cAAc;EAChB;CACF;CAEA,IAAI,aAAqC;EACvC,OAAO;GACL,WAAW;GACX,cAAc;GACd,QAAQ;EACV;CACF;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,IAAI;CAEJ;CAEA;CAEA,QAAQ;;CAGR;CAEA;CAEA,YAAY;CAEZ;CAEA;CAEA;CAEA;CAEA,YAAY;CAEZ;CAEA;CAEA;CAEA;CAEA;CAEA,YACE,QAIA;EACA,MAAM,UAAU,CAAC,CAAC;EAClB,KAAK,YAAY,qBAAA,OAAoC;EAErD,KAAK,eACH,QAAQ,UACR,QAAQ,gBACR,uBAAuB,gBAAgB;EACzC,KAAK,SAAS,KAAK;EAEnB,KAAK,eACH,QAAQ,eAAe,gBACvB,uBAAuB,qBAAqB;EAE9C,KAAK,QAAQ,QAAQ,SAAS,QAAQ,aAAa,KAAK;EACxD,KACG,KAAK,OAAO,WAAW,eAAe,KACrC,KAAK,OAAO,WAAW,OAAO,KAC9B,KAAK,OAAO,WAAW,IAAI,MAC7B,CAAC,KAAK,OAAO,S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SAGA;EACA,MAAM,iBAAiB,KAAK,kBAAkB,OAAO;EACrD,OAAO,KAAK,OAAO,KAAK,YAAY;GAClC,IAAI;IAKF,OAAO,MAJW,KAAK,OAAO,YAAY,OACxC,SACA,cACF;GAEF,SAAS,GAAG;IAEV,MADc,sBAAsB,CAC1B;GACZ;EACF,CAAC;CACH;;;;;;;CAQA,kBACE,SAC0B;EAC1B,IAAI,CAAC,KAAK,QAAQ;GAKhB,MAAM,WAAW,YAAY,EAH3B,SAAS,KAAK,aAAa,QAGmB,CAAC;GAEjD,MAAM,SAAS;IACb,GAAG,KAAK;IACR,SAAS;IACT,SAAS,KAAK;IACd,YAAY;GACd;GAEA,IAAI,CAAC,OAAO,SACV,OAAO,OAAO;GAGhB,OAAO,iBAAiB,wBAAwB,OAAO,cAAc;GAErE,KAAK,SAAS,IAAIC,OAAa,MAAM;EACvC;EAKA,OAAO;GAHL,GAAG,KAAK;GACR,GAAG;EAEe;CACtB;CAEA,WAAW;EACT,OAAO;CACT;AACF"}
@@ -109,6 +109,10 @@ function applyPatch(options) {
109
109
  return patchTool;
110
110
  }
111
111
  //#endregion
112
+ exports.ApplyPatchCreateFileOperationSchema = ApplyPatchCreateFileOperationSchema;
113
+ exports.ApplyPatchDeleteFileOperationSchema = ApplyPatchDeleteFileOperationSchema;
114
+ exports.ApplyPatchOperationSchema = ApplyPatchOperationSchema;
115
+ exports.ApplyPatchUpdateFileOperationSchema = ApplyPatchUpdateFileOperationSchema;
112
116
  exports.applyPatch = applyPatch;
113
117
 
114
118
  //# sourceMappingURL=applyPatch.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"applyPatch.cjs","names":["z"],"sources":["../../src/tools/applyPatch.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { tool, type DynamicStructuredTool } from \"@langchain/core/tools\";\n\n/**\n * Re-export operation types from OpenAI SDK for convenience.\n */\nexport type ApplyPatchCreateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.CreateFile;\nexport type ApplyPatchUpdateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.UpdateFile;\nexport type ApplyPatchDeleteFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.DeleteFile;\n\n/**\n * Union type of all apply patch operations from OpenAI SDK.\n */\nexport type ApplyPatchOperation = NonNullable<\n OpenAIClient.Responses.ResponseApplyPatchToolCall[\"operation\"]\n>;\n\n// Zod schemas for apply patch operations\nexport const ApplyPatchCreateFileOperationSchema = z.object({\n type: z.literal(\"create_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchUpdateFileOperationSchema = z.object({\n type: z.literal(\"update_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchDeleteFileOperationSchema = z.object({\n type: z.literal(\"delete_file\"),\n path: z.string(),\n});\n\n// Union schema for all apply patch operations\nexport const ApplyPatchOperationSchema = z.union([\n ApplyPatchCreateFileOperationSchema,\n ApplyPatchUpdateFileOperationSchema,\n ApplyPatchDeleteFileOperationSchema,\n]);\n\n/**\n * Options for the Apply Patch tool.\n */\nexport interface ApplyPatchOptions {\n /**\n * Execute function that handles patch operations.\n * This function receives the operation input and should return a string\n * describing the result (success or failure message).\n *\n * The operation types are:\n * - `create_file`: Create a new file at the specified path with the diff content\n * - `update_file`: Modify an existing file using V4A diff format\n * - `delete_file`: Remove a file at the specified path\n *\n * @example\n * ```typescript\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * }\n * ```\n */\n execute: (operation: ApplyPatchOperation) => string | Promise<string>;\n}\n\n/**\n * OpenAI Apply Patch tool type for the Responses API.\n */\nexport type ApplyPatchTool = OpenAIClient.Responses.ApplyPatchTool;\n\nconst TOOL_NAME = \"apply_patch\";\n\n/**\n * Creates an Apply Patch tool that allows models to propose structured diffs\n * that your integration applies. This enables iterative, multi-step code\n * editing workflows.\n *\n * **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase\n * using structured diffs. Instead of just suggesting edits, the model emits\n * patch operations that your application applies and then reports back on.\n *\n * **When to use**:\n * - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules\n * - **Bug fixes** – Have the model both diagnose issues and emit precise patches\n * - **Tests & docs generation** – Create new test files, fixtures, and documentation\n * - **Migrations & mechanical edits** – Apply repetitive, structured updates\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends patch operations (`apply_patch_call` with operation type)\n * 2. Your code applies the patch to your working directory or repo\n * 3. You return success/failure status and optional output\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Applying patches can modify files in your codebase.\n * Always validate paths, implement backups, and consider sandboxing.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation}\n *\n * @param options - Configuration options for the Apply Patch tool\n * @returns An Apply Patch tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { applyDiff } from \"@openai/agents\";\n * import * as fs from \"fs/promises\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-5.1\" });\n *\n * // With execute callback for automatic patch handling\n * const patchTool = tools.applyPatch({\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * },\n * });\n *\n * const llmWithPatch = model.bindTools([patchTool]);\n * const response = await llmWithPatch.invoke(\n * \"Rename the fib() function to fibonacci() in lib/fib.py\"\n * );\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Designed for use with `gpt-5.1` model\n * - Operations include: `create_file`, `update_file`, `delete_file`\n * - Patches use V4A diff format for updates\n * - Always validate paths to prevent directory traversal attacks\n * - Consider backing up files before applying patches\n * - Implement \"all-or-nothing\" semantics if atomicity is required\n */\nexport function applyPatch(options: ApplyPatchOptions) {\n const patchTool = tool(options.execute, {\n name: TOOL_NAME,\n description:\n \"Apply structured diffs to create, update, or delete files in the codebase.\",\n schema: ApplyPatchOperationSchema,\n });\n\n patchTool.extras = {\n ...(patchTool.extras ?? {}),\n providerToolDefinition: {\n type: \"apply_patch\",\n } satisfies ApplyPatchTool,\n };\n\n return patchTool as DynamicStructuredTool<\n typeof ApplyPatchOperationSchema,\n ApplyPatchOperation,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAsBA,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,cAAc;CAC9B,MAAMA,OAAAA,EAAE,QAAQ;CAChB,MAAMA,OAAAA,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,cAAc;CAC9B,MAAMA,OAAAA,EAAE,QAAQ;CAChB,MAAMA,OAAAA,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,cAAc;CAC9B,MAAMA,OAAAA,EAAE,QAAQ;CACjB,CAAC;AAGF,MAAa,4BAA4BA,OAAAA,EAAE,MAAM;CAC/C;CACA;CACA;CACD,CAAC;AA8CF,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ElB,SAAgB,WAAW,SAA4B;CACrD,MAAM,aAAA,GAAA,sBAAA,MAAiB,QAAQ,SAAS;EACtC,MAAM;EACN,aACE;EACF,QAAQ;EACT,CAAC;AAEF,WAAU,SAAS;EACjB,GAAI,UAAU,UAAU,EAAE;EAC1B,wBAAwB,EACtB,MAAM,eACP;EACF;AAED,QAAO"}
1
+ {"version":3,"file":"applyPatch.cjs","names":["z"],"sources":["../../src/tools/applyPatch.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { tool, type DynamicStructuredTool } from \"@langchain/core/tools\";\n\n/**\n * Re-export operation types from OpenAI SDK for convenience.\n */\nexport type ApplyPatchCreateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.CreateFile;\nexport type ApplyPatchUpdateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.UpdateFile;\nexport type ApplyPatchDeleteFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.DeleteFile;\n\n/**\n * Union type of all apply patch operations from OpenAI SDK.\n */\nexport type ApplyPatchOperation = NonNullable<\n OpenAIClient.Responses.ResponseApplyPatchToolCall[\"operation\"]\n>;\n\n// Zod schemas for apply patch operations\nexport const ApplyPatchCreateFileOperationSchema = z.object({\n type: z.literal(\"create_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchUpdateFileOperationSchema = z.object({\n type: z.literal(\"update_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchDeleteFileOperationSchema = z.object({\n type: z.literal(\"delete_file\"),\n path: z.string(),\n});\n\n// Union schema for all apply patch operations\nexport const ApplyPatchOperationSchema = z.union([\n ApplyPatchCreateFileOperationSchema,\n ApplyPatchUpdateFileOperationSchema,\n ApplyPatchDeleteFileOperationSchema,\n]);\n\n/**\n * Options for the Apply Patch tool.\n */\nexport interface ApplyPatchOptions {\n /**\n * Execute function that handles patch operations.\n * This function receives the operation input and should return a string\n * describing the result (success or failure message).\n *\n * The operation types are:\n * - `create_file`: Create a new file at the specified path with the diff content\n * - `update_file`: Modify an existing file using V4A diff format\n * - `delete_file`: Remove a file at the specified path\n *\n * @example\n * ```typescript\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * }\n * ```\n */\n execute: (operation: ApplyPatchOperation) => string | Promise<string>;\n}\n\n/**\n * OpenAI Apply Patch tool type for the Responses API.\n */\nexport type ApplyPatchTool = OpenAIClient.Responses.ApplyPatchTool;\n\nconst TOOL_NAME = \"apply_patch\";\n\n/**\n * Creates an Apply Patch tool that allows models to propose structured diffs\n * that your integration applies. This enables iterative, multi-step code\n * editing workflows.\n *\n * **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase\n * using structured diffs. Instead of just suggesting edits, the model emits\n * patch operations that your application applies and then reports back on.\n *\n * **When to use**:\n * - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules\n * - **Bug fixes** – Have the model both diagnose issues and emit precise patches\n * - **Tests & docs generation** – Create new test files, fixtures, and documentation\n * - **Migrations & mechanical edits** – Apply repetitive, structured updates\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends patch operations (`apply_patch_call` with operation type)\n * 2. Your code applies the patch to your working directory or repo\n * 3. You return success/failure status and optional output\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Applying patches can modify files in your codebase.\n * Always validate paths, implement backups, and consider sandboxing.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation}\n *\n * @param options - Configuration options for the Apply Patch tool\n * @returns An Apply Patch tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { applyDiff } from \"@openai/agents\";\n * import * as fs from \"fs/promises\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-5.1\" });\n *\n * // With execute callback for automatic patch handling\n * const patchTool = tools.applyPatch({\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * },\n * });\n *\n * const llmWithPatch = model.bindTools([patchTool]);\n * const response = await llmWithPatch.invoke(\n * \"Rename the fib() function to fibonacci() in lib/fib.py\"\n * );\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Designed for use with `gpt-5.1` model\n * - Operations include: `create_file`, `update_file`, `delete_file`\n * - Patches use V4A diff format for updates\n * - Always validate paths to prevent directory traversal attacks\n * - Consider backing up files before applying patches\n * - Implement \"all-or-nothing\" semantics if atomicity is required\n */\nexport function applyPatch(options: ApplyPatchOptions) {\n const patchTool = tool(options.execute, {\n name: TOOL_NAME,\n description:\n \"Apply structured diffs to create, update, or delete files in the codebase.\",\n schema: ApplyPatchOperationSchema,\n });\n\n patchTool.extras = {\n ...(patchTool.extras ?? {}),\n providerToolDefinition: {\n type: \"apply_patch\",\n } satisfies ApplyPatchTool,\n };\n\n return patchTool as DynamicStructuredTool<\n typeof ApplyPatchOperationSchema,\n ApplyPatchOperation,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAsBA,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,aAAa;CAC7B,MAAMA,OAAAA,EAAE,OAAO;CACf,MAAMA,OAAAA,EAAE,OAAO;AACjB,CAAC;AAED,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,aAAa;CAC7B,MAAMA,OAAAA,EAAE,OAAO;CACf,MAAMA,OAAAA,EAAE,OAAO;AACjB,CAAC;AAED,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,aAAa;CAC7B,MAAMA,OAAAA,EAAE,OAAO;AACjB,CAAC;AAGD,MAAa,4BAA4BA,OAAAA,EAAE,MAAM;CAC/C;CACA;CACA;AACF,CAAC;AA8CD,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ElB,SAAgB,WAAW,SAA4B;CACrD,MAAM,aAAA,GAAA,sBAAA,KAAA,CAAiB,QAAQ,SAAS;EACtC,MAAM;EACN,aACE;EACF,QAAQ;CACV,CAAC;CAED,UAAU,SAAS;EACjB,GAAI,UAAU,UAAU,CAAC;EACzB,wBAAwB,EACtB,MAAM,cACR;CACF;CAEA,OAAO;AAMT"}
@@ -1,7 +1,6 @@
1
1
  import { OpenAI } from "openai";
2
2
  import { DynamicStructuredTool } from "@langchain/core/tools";
3
3
  import { z } from "zod/v4";
4
-
5
4
  //#region src/tools/applyPatch.d.ts
6
5
  /**
7
6
  * Re-export operation types from OpenAI SDK for convenience.
@@ -144,5 +143,5 @@ type ApplyPatchTool = OpenAI.Responses.ApplyPatchTool;
144
143
  */
145
144
  declare function applyPatch(options: ApplyPatchOptions): DynamicStructuredTool<typeof ApplyPatchOperationSchema, ApplyPatchOperation, unknown, string>;
146
145
  //#endregion
147
- export { ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchOperation, ApplyPatchOptions, ApplyPatchTool, ApplyPatchUpdateFileOperation, applyPatch };
146
+ export { ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchOperation, ApplyPatchOperationSchema, ApplyPatchOptions, ApplyPatchTool, ApplyPatchUpdateFileOperation, applyPatch };
148
147
  //# sourceMappingURL=applyPatch.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"applyPatch.d.cts","names":[],"sources":["../../src/tools/applyPatch.ts"],"mappings":";;;;;;;AAOA;KAAY,6BAAA,GACV,MAAA,CAAa,SAAA,CAAU,0BAAA,CAA2B,UAAA;AAAA,KACxC,6BAAA,GACV,MAAA,CAAa,SAAA,CAAU,0BAAA,CAA2B,UAAA;AAAA,KACxC,6BAAA,GACV,MAAA,CAAa,SAAA,CAAU,0BAAA,CAA2B,UAAA;;;;KAKxC,mBAAA,GAAsB,WAAA,CAChC,MAAA,CAAa,SAAA,CAAU,0BAAA;AAAA,cAsBZ,yBAAA,EAAyB,CAAA,CAAA,QAAA,WAAA,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;UASrB,iBAAA;EA/BkC;;AAsBnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA0CE,OAAA,GAAU,SAAA,EAAW,mBAAA,cAAiC,OAAA;AAAA;;;;KAM5C,cAAA,GAAiB,MAAA,CAAa,SAAA,CAAU,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAvCpD;;;;;;;;;;AAuCA;;;;;;;;;AA+EA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,UAAA,CAAW,OAAA,EAAS,iBAAA,GAed,qBAAA,QACX,yBAAA,EACP,mBAAA"}
1
+ {"version":3,"file":"applyPatch.d.cts","names":[],"sources":["../../src/tools/applyPatch.ts"],"mappings":";;;;;;;KAOY,gCACV,OAAa,UAAU,2BAA2B;KACxC,gCACV,OAAa,UAAU,2BAA2B;KACxC,gCACV,OAAa,UAAU,2BAA2B;;;;KAKxC,sBAAsB,YAChC,OAAa,UAAU;cAsBZ,2BAAyB,EAAA,mBAAA,EAAA;;;;;;;;;;;GAIpC,EAAA,KAAA;;;;UAKe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiCf,UAAU,WAAW,iCAAiC;;;;;KAM5C,iBAAiB,OAAa,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+EpC,WAAW,SAAS,oBAed,6BACX,2BACP"}
@@ -1,7 +1,6 @@
1
1
  import { OpenAI } from "openai";
2
2
  import { DynamicStructuredTool } from "@langchain/core/tools";
3
3
  import { z } from "zod/v4";
4
-
5
4
  //#region src/tools/applyPatch.d.ts
6
5
  /**
7
6
  * Re-export operation types from OpenAI SDK for convenience.
@@ -144,5 +143,5 @@ type ApplyPatchTool = OpenAI.Responses.ApplyPatchTool;
144
143
  */
145
144
  declare function applyPatch(options: ApplyPatchOptions): DynamicStructuredTool<typeof ApplyPatchOperationSchema, ApplyPatchOperation, unknown, string>;
146
145
  //#endregion
147
- export { ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchOperation, ApplyPatchOptions, ApplyPatchTool, ApplyPatchUpdateFileOperation, applyPatch };
146
+ export { ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchOperation, ApplyPatchOperationSchema, ApplyPatchOptions, ApplyPatchTool, ApplyPatchUpdateFileOperation, applyPatch };
148
147
  //# sourceMappingURL=applyPatch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"applyPatch.d.ts","names":[],"sources":["../../src/tools/applyPatch.ts"],"mappings":";;;;;;;AAOA;KAAY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"}
@@ -109,6 +109,6 @@ function applyPatch(options) {
109
109
  return patchTool;
110
110
  }
111
111
  //#endregion
112
- export { applyPatch };
112
+ export { ApplyPatchCreateFileOperationSchema, ApplyPatchDeleteFileOperationSchema, ApplyPatchOperationSchema, ApplyPatchUpdateFileOperationSchema, applyPatch };
113
113
 
114
114
  //# sourceMappingURL=applyPatch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"applyPatch.js","names":[],"sources":["../../src/tools/applyPatch.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { tool, type DynamicStructuredTool } from \"@langchain/core/tools\";\n\n/**\n * Re-export operation types from OpenAI SDK for convenience.\n */\nexport type ApplyPatchCreateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.CreateFile;\nexport type ApplyPatchUpdateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.UpdateFile;\nexport type ApplyPatchDeleteFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.DeleteFile;\n\n/**\n * Union type of all apply patch operations from OpenAI SDK.\n */\nexport type ApplyPatchOperation = NonNullable<\n OpenAIClient.Responses.ResponseApplyPatchToolCall[\"operation\"]\n>;\n\n// Zod schemas for apply patch operations\nexport const ApplyPatchCreateFileOperationSchema = z.object({\n type: z.literal(\"create_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchUpdateFileOperationSchema = z.object({\n type: z.literal(\"update_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchDeleteFileOperationSchema = z.object({\n type: z.literal(\"delete_file\"),\n path: z.string(),\n});\n\n// Union schema for all apply patch operations\nexport const ApplyPatchOperationSchema = z.union([\n ApplyPatchCreateFileOperationSchema,\n ApplyPatchUpdateFileOperationSchema,\n ApplyPatchDeleteFileOperationSchema,\n]);\n\n/**\n * Options for the Apply Patch tool.\n */\nexport interface ApplyPatchOptions {\n /**\n * Execute function that handles patch operations.\n * This function receives the operation input and should return a string\n * describing the result (success or failure message).\n *\n * The operation types are:\n * - `create_file`: Create a new file at the specified path with the diff content\n * - `update_file`: Modify an existing file using V4A diff format\n * - `delete_file`: Remove a file at the specified path\n *\n * @example\n * ```typescript\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * }\n * ```\n */\n execute: (operation: ApplyPatchOperation) => string | Promise<string>;\n}\n\n/**\n * OpenAI Apply Patch tool type for the Responses API.\n */\nexport type ApplyPatchTool = OpenAIClient.Responses.ApplyPatchTool;\n\nconst TOOL_NAME = \"apply_patch\";\n\n/**\n * Creates an Apply Patch tool that allows models to propose structured diffs\n * that your integration applies. This enables iterative, multi-step code\n * editing workflows.\n *\n * **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase\n * using structured diffs. Instead of just suggesting edits, the model emits\n * patch operations that your application applies and then reports back on.\n *\n * **When to use**:\n * - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules\n * - **Bug fixes** – Have the model both diagnose issues and emit precise patches\n * - **Tests & docs generation** – Create new test files, fixtures, and documentation\n * - **Migrations & mechanical edits** – Apply repetitive, structured updates\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends patch operations (`apply_patch_call` with operation type)\n * 2. Your code applies the patch to your working directory or repo\n * 3. You return success/failure status and optional output\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Applying patches can modify files in your codebase.\n * Always validate paths, implement backups, and consider sandboxing.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation}\n *\n * @param options - Configuration options for the Apply Patch tool\n * @returns An Apply Patch tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { applyDiff } from \"@openai/agents\";\n * import * as fs from \"fs/promises\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-5.1\" });\n *\n * // With execute callback for automatic patch handling\n * const patchTool = tools.applyPatch({\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * },\n * });\n *\n * const llmWithPatch = model.bindTools([patchTool]);\n * const response = await llmWithPatch.invoke(\n * \"Rename the fib() function to fibonacci() in lib/fib.py\"\n * );\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Designed for use with `gpt-5.1` model\n * - Operations include: `create_file`, `update_file`, `delete_file`\n * - Patches use V4A diff format for updates\n * - Always validate paths to prevent directory traversal attacks\n * - Consider backing up files before applying patches\n * - Implement \"all-or-nothing\" semantics if atomicity is required\n */\nexport function applyPatch(options: ApplyPatchOptions) {\n const patchTool = tool(options.execute, {\n name: TOOL_NAME,\n description:\n \"Apply structured diffs to create, update, or delete files in the codebase.\",\n schema: ApplyPatchOperationSchema,\n });\n\n patchTool.extras = {\n ...(patchTool.extras ?? {}),\n providerToolDefinition: {\n type: \"apply_patch\",\n } satisfies ApplyPatchTool,\n };\n\n return patchTool as DynamicStructuredTool<\n typeof ApplyPatchOperationSchema,\n ApplyPatchOperation,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAsBA,MAAa,sCAAsC,EAAE,OAAO;CAC1D,MAAM,EAAE,QAAQ,cAAc;CAC9B,MAAM,EAAE,QAAQ;CAChB,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAa,sCAAsC,EAAE,OAAO;CAC1D,MAAM,EAAE,QAAQ,cAAc;CAC9B,MAAM,EAAE,QAAQ;CAChB,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAa,sCAAsC,EAAE,OAAO;CAC1D,MAAM,EAAE,QAAQ,cAAc;CAC9B,MAAM,EAAE,QAAQ;CACjB,CAAC;AAGF,MAAa,4BAA4B,EAAE,MAAM;CAC/C;CACA;CACA;CACD,CAAC;AA8CF,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ElB,SAAgB,WAAW,SAA4B;CACrD,MAAM,YAAY,KAAK,QAAQ,SAAS;EACtC,MAAM;EACN,aACE;EACF,QAAQ;EACT,CAAC;AAEF,WAAU,SAAS;EACjB,GAAI,UAAU,UAAU,EAAE;EAC1B,wBAAwB,EACtB,MAAM,eACP;EACF;AAED,QAAO"}
1
+ {"version":3,"file":"applyPatch.js","names":[],"sources":["../../src/tools/applyPatch.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { tool, type DynamicStructuredTool } from \"@langchain/core/tools\";\n\n/**\n * Re-export operation types from OpenAI SDK for convenience.\n */\nexport type ApplyPatchCreateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.CreateFile;\nexport type ApplyPatchUpdateFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.UpdateFile;\nexport type ApplyPatchDeleteFileOperation =\n OpenAIClient.Responses.ResponseApplyPatchToolCall.DeleteFile;\n\n/**\n * Union type of all apply patch operations from OpenAI SDK.\n */\nexport type ApplyPatchOperation = NonNullable<\n OpenAIClient.Responses.ResponseApplyPatchToolCall[\"operation\"]\n>;\n\n// Zod schemas for apply patch operations\nexport const ApplyPatchCreateFileOperationSchema = z.object({\n type: z.literal(\"create_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchUpdateFileOperationSchema = z.object({\n type: z.literal(\"update_file\"),\n path: z.string(),\n diff: z.string(),\n});\n\nexport const ApplyPatchDeleteFileOperationSchema = z.object({\n type: z.literal(\"delete_file\"),\n path: z.string(),\n});\n\n// Union schema for all apply patch operations\nexport const ApplyPatchOperationSchema = z.union([\n ApplyPatchCreateFileOperationSchema,\n ApplyPatchUpdateFileOperationSchema,\n ApplyPatchDeleteFileOperationSchema,\n]);\n\n/**\n * Options for the Apply Patch tool.\n */\nexport interface ApplyPatchOptions {\n /**\n * Execute function that handles patch operations.\n * This function receives the operation input and should return a string\n * describing the result (success or failure message).\n *\n * The operation types are:\n * - `create_file`: Create a new file at the specified path with the diff content\n * - `update_file`: Modify an existing file using V4A diff format\n * - `delete_file`: Remove a file at the specified path\n *\n * @example\n * ```typescript\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * }\n * ```\n */\n execute: (operation: ApplyPatchOperation) => string | Promise<string>;\n}\n\n/**\n * OpenAI Apply Patch tool type for the Responses API.\n */\nexport type ApplyPatchTool = OpenAIClient.Responses.ApplyPatchTool;\n\nconst TOOL_NAME = \"apply_patch\";\n\n/**\n * Creates an Apply Patch tool that allows models to propose structured diffs\n * that your integration applies. This enables iterative, multi-step code\n * editing workflows.\n *\n * **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase\n * using structured diffs. Instead of just suggesting edits, the model emits\n * patch operations that your application applies and then reports back on.\n *\n * **When to use**:\n * - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules\n * - **Bug fixes** – Have the model both diagnose issues and emit precise patches\n * - **Tests & docs generation** – Create new test files, fixtures, and documentation\n * - **Migrations & mechanical edits** – Apply repetitive, structured updates\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends patch operations (`apply_patch_call` with operation type)\n * 2. Your code applies the patch to your working directory or repo\n * 3. You return success/failure status and optional output\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Applying patches can modify files in your codebase.\n * Always validate paths, implement backups, and consider sandboxing.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation}\n *\n * @param options - Configuration options for the Apply Patch tool\n * @returns An Apply Patch tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { applyDiff } from \"@openai/agents\";\n * import * as fs from \"fs/promises\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-5.1\" });\n *\n * // With execute callback for automatic patch handling\n * const patchTool = tools.applyPatch({\n * execute: async (operation) => {\n * if (operation.type === \"create_file\") {\n * const content = applyDiff(\"\", operation.diff, \"create\");\n * await fs.writeFile(operation.path, content);\n * return `Created ${operation.path}`;\n * }\n * if (operation.type === \"update_file\") {\n * const current = await fs.readFile(operation.path, \"utf-8\");\n * const newContent = applyDiff(current, operation.diff);\n * await fs.writeFile(operation.path, newContent);\n * return `Updated ${operation.path}`;\n * }\n * if (operation.type === \"delete_file\") {\n * await fs.unlink(operation.path);\n * return `Deleted ${operation.path}`;\n * }\n * return \"Unknown operation type\";\n * },\n * });\n *\n * const llmWithPatch = model.bindTools([patchTool]);\n * const response = await llmWithPatch.invoke(\n * \"Rename the fib() function to fibonacci() in lib/fib.py\"\n * );\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Designed for use with `gpt-5.1` model\n * - Operations include: `create_file`, `update_file`, `delete_file`\n * - Patches use V4A diff format for updates\n * - Always validate paths to prevent directory traversal attacks\n * - Consider backing up files before applying patches\n * - Implement \"all-or-nothing\" semantics if atomicity is required\n */\nexport function applyPatch(options: ApplyPatchOptions) {\n const patchTool = tool(options.execute, {\n name: TOOL_NAME,\n description:\n \"Apply structured diffs to create, update, or delete files in the codebase.\",\n schema: ApplyPatchOperationSchema,\n });\n\n patchTool.extras = {\n ...(patchTool.extras ?? {}),\n providerToolDefinition: {\n type: \"apply_patch\",\n } satisfies ApplyPatchTool,\n };\n\n return patchTool as DynamicStructuredTool<\n typeof ApplyPatchOperationSchema,\n ApplyPatchOperation,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAsBA,MAAa,sCAAsC,EAAE,OAAO;CAC1D,MAAM,EAAE,QAAQ,aAAa;CAC7B,MAAM,EAAE,OAAO;CACf,MAAM,EAAE,OAAO;AACjB,CAAC;AAED,MAAa,sCAAsC,EAAE,OAAO;CAC1D,MAAM,EAAE,QAAQ,aAAa;CAC7B,MAAM,EAAE,OAAO;CACf,MAAM,EAAE,OAAO;AACjB,CAAC;AAED,MAAa,sCAAsC,EAAE,OAAO;CAC1D,MAAM,EAAE,QAAQ,aAAa;CAC7B,MAAM,EAAE,OAAO;AACjB,CAAC;AAGD,MAAa,4BAA4B,EAAE,MAAM;CAC/C;CACA;CACA;AACF,CAAC;AA8CD,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ElB,SAAgB,WAAW,SAA4B;CACrD,MAAM,YAAY,KAAK,QAAQ,SAAS;EACtC,MAAM;EACN,aACE;EACF,QAAQ;CACV,CAAC;CAED,UAAU,SAAS;EACjB,GAAI,UAAU,UAAU,CAAC;EACzB,wBAAwB,EACtB,MAAM,cACR;CACF;CAEA,OAAO;AAMT"}
@@ -1 +1 @@
1
- {"version":3,"file":"codeInterpreter.cjs","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n\n/**\n * Memory limit options for the Code Interpreter container.\n * Higher tiers offer more RAM and are billed at different rates.\n */\nexport type CodeInterpreterMemoryLimit = \"1g\" | \"4g\" | \"16g\" | \"64g\";\n\n/**\n * Auto container configuration for Code Interpreter.\n * Creates a new container automatically or reuses an active one.\n */\nexport interface CodeInterpreterAutoContainer {\n /**\n * Memory limit for the container.\n * - `\"1g\"` (default): 1 GB RAM\n * - `\"4g\"`: 4 GB RAM\n * - `\"16g\"`: 16 GB RAM\n * - `\"64g\"`: 64 GB RAM\n */\n memoryLimit?: CodeInterpreterMemoryLimit;\n /**\n * Optional list of uploaded file IDs to make available to the code.\n * Files in the model input are automatically uploaded, so this is only\n * needed for additional files.\n */\n fileIds?: string[];\n}\n\n/**\n * Options for the Code Interpreter tool.\n */\nexport interface CodeInterpreterOptions {\n /**\n * The container configuration for the Code Interpreter.\n *\n * Can be either:\n * - A string container ID for explicit mode (created via `/v1/containers` endpoint)\n * - An auto configuration object that creates/reuses containers automatically\n *\n * If not provided, defaults to auto mode with default settings.\n */\n container?: string | CodeInterpreterAutoContainer;\n}\n\n/**\n * OpenAI Code Interpreter tool type for the Responses API.\n */\nexport type CodeInterpreterTool = OpenAIClient.Responses.Tool.CodeInterpreter;\n\n/**\n * Converts container options to the API format.\n */\nfunction convertContainer(\n container: string | CodeInterpreterAutoContainer | undefined\n):\n | string\n | OpenAIClient.Responses.Tool.CodeInterpreter.CodeInterpreterToolAuto {\n // If a string container ID is provided, use it directly\n if (typeof container === \"string\") {\n return container;\n }\n\n // Auto mode configuration\n return {\n type: \"auto\",\n file_ids: container?.fileIds,\n memory_limit: container?.memoryLimit,\n };\n}\n\n/**\n * Creates a Code Interpreter tool that allows models to write and run Python code\n * in a sandboxed environment to solve complex problems.\n *\n * Use Code Interpreter for:\n * - **Data analysis**: Processing files with diverse data and formatting\n * - **File generation**: Creating files with data and images of graphs\n * - **Iterative coding**: Writing and running code iteratively to solve problems\n * - **Visual intelligence**: Cropping, zooming, rotating, and transforming images\n *\n * The tool runs in a container, which is a fully sandboxed virtual machine.\n * Containers can be created automatically (auto mode) or explicitly via the\n * `/v1/containers` endpoint.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation}\n *\n * @param options - Configuration options for the Code Interpreter tool\n * @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4.1\" });\n *\n * // Basic usage with auto container (default 1GB memory)\n * const response = await model.invoke(\n * \"Solve the equation 3x + 11 = 14\",\n * { tools: [tools.codeInterpreter()] }\n * );\n *\n * // With increased memory limit for larger computations\n * const response = await model.invoke(\n * \"Analyze this large dataset and create visualizations\",\n * {\n * tools: [tools.codeInterpreter({\n * container: { memoryLimit: \"4g\" }\n * })]\n * }\n * );\n *\n * // With specific files available to the code\n * const response = await model.invoke(\n * \"Process the uploaded CSV file\",\n * {\n * tools: [tools.codeInterpreter({\n * container: {\n * memoryLimit: \"4g\",\n * fileIds: [\"file-abc123\", \"file-def456\"]\n * }\n * })]\n * }\n * );\n *\n * // Using an explicit container ID (created via /v1/containers)\n * const response = await model.invoke(\n * \"Continue working with the data\",\n * {\n * tools: [tools.codeInterpreter({\n * container: \"cntr_abc123\"\n * })]\n * }\n * );\n * ```\n *\n * @remarks\n * - Containers expire after 20 minutes of inactivity\n * - While called \"Code Interpreter\", the model knows it as the \"python tool\"\n * - For explicit prompting, ask for \"the python tool\" in your prompts\n * - Files in model input are automatically uploaded to the container\n * - Generated files are returned as `container_file_citation` annotations\n */\nexport function codeInterpreter(options?: CodeInterpreterOptions): ServerTool {\n return {\n type: \"code_interpreter\",\n container: convertContainer(options?.container),\n } satisfies CodeInterpreterTool;\n}\n"],"mappings":";;;;AAsDA,SAAS,iBACP,WAGsE;AAEtE,KAAI,OAAO,cAAc,SACvB,QAAO;AAIT,QAAO;EACL,MAAM;EACN,UAAU,WAAW;EACrB,cAAc,WAAW;EAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EH,SAAgB,gBAAgB,SAA8C;AAC5E,QAAO;EACL,MAAM;EACN,WAAW,iBAAiB,SAAS,UAAU;EAChD"}
1
+ {"version":3,"file":"codeInterpreter.cjs","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n\n/**\n * Memory limit options for the Code Interpreter container.\n * Higher tiers offer more RAM and are billed at different rates.\n */\nexport type CodeInterpreterMemoryLimit = \"1g\" | \"4g\" | \"16g\" | \"64g\";\n\n/**\n * Auto container configuration for Code Interpreter.\n * Creates a new container automatically or reuses an active one.\n */\nexport interface CodeInterpreterAutoContainer {\n /**\n * Memory limit for the container.\n * - `\"1g\"` (default): 1 GB RAM\n * - `\"4g\"`: 4 GB RAM\n * - `\"16g\"`: 16 GB RAM\n * - `\"64g\"`: 64 GB RAM\n */\n memoryLimit?: CodeInterpreterMemoryLimit;\n /**\n * Optional list of uploaded file IDs to make available to the code.\n * Files in the model input are automatically uploaded, so this is only\n * needed for additional files.\n */\n fileIds?: string[];\n}\n\n/**\n * Options for the Code Interpreter tool.\n */\nexport interface CodeInterpreterOptions {\n /**\n * The container configuration for the Code Interpreter.\n *\n * Can be either:\n * - A string container ID for explicit mode (created via `/v1/containers` endpoint)\n * - An auto configuration object that creates/reuses containers automatically\n *\n * If not provided, defaults to auto mode with default settings.\n */\n container?: string | CodeInterpreterAutoContainer;\n}\n\n/**\n * OpenAI Code Interpreter tool type for the Responses API.\n */\nexport type CodeInterpreterTool = OpenAIClient.Responses.Tool.CodeInterpreter;\n\n/**\n * Converts container options to the API format.\n */\nfunction convertContainer(\n container: string | CodeInterpreterAutoContainer | undefined\n):\n | string\n | OpenAIClient.Responses.Tool.CodeInterpreter.CodeInterpreterToolAuto {\n // If a string container ID is provided, use it directly\n if (typeof container === \"string\") {\n return container;\n }\n\n // Auto mode configuration\n return {\n type: \"auto\",\n file_ids: container?.fileIds,\n memory_limit: container?.memoryLimit,\n };\n}\n\n/**\n * Creates a Code Interpreter tool that allows models to write and run Python code\n * in a sandboxed environment to solve complex problems.\n *\n * Use Code Interpreter for:\n * - **Data analysis**: Processing files with diverse data and formatting\n * - **File generation**: Creating files with data and images of graphs\n * - **Iterative coding**: Writing and running code iteratively to solve problems\n * - **Visual intelligence**: Cropping, zooming, rotating, and transforming images\n *\n * The tool runs in a container, which is a fully sandboxed virtual machine.\n * Containers can be created automatically (auto mode) or explicitly via the\n * `/v1/containers` endpoint.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation}\n *\n * @param options - Configuration options for the Code Interpreter tool\n * @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4.1\" });\n *\n * // Basic usage with auto container (default 1GB memory)\n * const response = await model.invoke(\n * \"Solve the equation 3x + 11 = 14\",\n * { tools: [tools.codeInterpreter()] }\n * );\n *\n * // With increased memory limit for larger computations\n * const response = await model.invoke(\n * \"Analyze this large dataset and create visualizations\",\n * {\n * tools: [tools.codeInterpreter({\n * container: { memoryLimit: \"4g\" }\n * })]\n * }\n * );\n *\n * // With specific files available to the code\n * const response = await model.invoke(\n * \"Process the uploaded CSV file\",\n * {\n * tools: [tools.codeInterpreter({\n * container: {\n * memoryLimit: \"4g\",\n * fileIds: [\"file-abc123\", \"file-def456\"]\n * }\n * })]\n * }\n * );\n *\n * // Using an explicit container ID (created via /v1/containers)\n * const response = await model.invoke(\n * \"Continue working with the data\",\n * {\n * tools: [tools.codeInterpreter({\n * container: \"cntr_abc123\"\n * })]\n * }\n * );\n * ```\n *\n * @remarks\n * - Containers expire after 20 minutes of inactivity\n * - While called \"Code Interpreter\", the model knows it as the \"python tool\"\n * - For explicit prompting, ask for \"the python tool\" in your prompts\n * - Files in model input are automatically uploaded to the container\n * - Generated files are returned as `container_file_citation` annotations\n */\nexport function codeInterpreter(options?: CodeInterpreterOptions): ServerTool {\n return {\n type: \"code_interpreter\",\n container: convertContainer(options?.container),\n } satisfies CodeInterpreterTool;\n}\n"],"mappings":";;;;AAsDA,SAAS,iBACP,WAGsE;CAEtE,IAAI,OAAO,cAAc,UACvB,OAAO;CAIT,OAAO;EACL,MAAM;EACN,UAAU,WAAW;EACrB,cAAc,WAAW;CAC3B;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,gBAAgB,SAA8C;CAC5E,OAAO;EACL,MAAM;EACN,WAAW,iBAAiB,SAAS,SAAS;CAChD;AACF"}
@@ -1,6 +1,5 @@
1
1
  import { OpenAI } from "openai";
2
2
  import { ServerTool } from "@langchain/core/tools";
3
-
4
3
  //#region src/tools/codeInterpreter.d.ts
5
4
  /**
6
5
  * Memory limit options for the Code Interpreter container.
@@ -1 +1 @@
1
- {"version":3,"file":"codeInterpreter.d.cts","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"mappings":";;;;;;AAOA;;KAAY,0BAAA;;;AAMZ;;UAAiB,4BAAA;EAQyB;;;;;;AAY1C;EAZE,WAAA,GAAc,0BAAA;;;;AA4BhB;;EAtBE,OAAA;AAAA;;;;UAMe,sBAAA;EAgB4D;;AA+F7E;;;;;;;EArGE,SAAA,YAAqB,4BAAA;AAAA;;;;KAMX,mBAAA,GAAsB,MAAA,CAAa,SAAA,CAAU,IAAA,CAAK,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+F9C,eAAA,CAAgB,OAAA,GAAU,sBAAA,GAAyB,UAAA"}
1
+ {"version":3,"file":"codeInterpreter.d.cts","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"mappings":";;;;;;;KAOY;;;;;UAMK;;;;;;;;EAQf,cAAc;;;;;;EAMd;;;;;UAMe;;;;;;;;;;EAUf,qBAAqB;;;;;KAMX,sBAAsB,OAAa,UAAU,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+F9C,gBAAgB,UAAU,yBAAyB"}
@@ -1,6 +1,5 @@
1
1
  import { OpenAI } from "openai";
2
2
  import { ServerTool } from "@langchain/core/tools";
3
-
4
3
  //#region src/tools/codeInterpreter.d.ts
5
4
  /**
6
5
  * Memory limit options for the Code Interpreter container.
@@ -1 +1 @@
1
- {"version":3,"file":"codeInterpreter.d.ts","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"mappings":";;;;;;AAOA;;KAAY,0BAAA;;;AAMZ;;UAAiB,4BAAA;EAQyB;;;;;;AAY1C;EAZE,WAAA,GAAc,0BAAA;;;;AA4BhB;;EAtBE,OAAA;AAAA;;;;UAMe,sBAAA;EAgB4D;;AA+F7E;;;;;;;EArGE,SAAA,YAAqB,4BAAA;AAAA;;;;KAMX,mBAAA,GAAsB,MAAA,CAAa,SAAA,CAAU,IAAA,CAAK,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+F9C,eAAA,CAAgB,OAAA,GAAU,sBAAA,GAAyB,UAAA"}
1
+ {"version":3,"file":"codeInterpreter.d.ts","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"mappings":";;;;;;;KAOY;;;;;UAMK;;;;;;;;EAQf,cAAc;;;;;;EAMd;;;;;UAMe;;;;;;;;;;EAUf,qBAAqB;;;;;KAMX,sBAAsB,OAAa,UAAU,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+F9C,gBAAgB,UAAU,yBAAyB"}
@@ -1 +1 @@
1
- {"version":3,"file":"codeInterpreter.js","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n\n/**\n * Memory limit options for the Code Interpreter container.\n * Higher tiers offer more RAM and are billed at different rates.\n */\nexport type CodeInterpreterMemoryLimit = \"1g\" | \"4g\" | \"16g\" | \"64g\";\n\n/**\n * Auto container configuration for Code Interpreter.\n * Creates a new container automatically or reuses an active one.\n */\nexport interface CodeInterpreterAutoContainer {\n /**\n * Memory limit for the container.\n * - `\"1g\"` (default): 1 GB RAM\n * - `\"4g\"`: 4 GB RAM\n * - `\"16g\"`: 16 GB RAM\n * - `\"64g\"`: 64 GB RAM\n */\n memoryLimit?: CodeInterpreterMemoryLimit;\n /**\n * Optional list of uploaded file IDs to make available to the code.\n * Files in the model input are automatically uploaded, so this is only\n * needed for additional files.\n */\n fileIds?: string[];\n}\n\n/**\n * Options for the Code Interpreter tool.\n */\nexport interface CodeInterpreterOptions {\n /**\n * The container configuration for the Code Interpreter.\n *\n * Can be either:\n * - A string container ID for explicit mode (created via `/v1/containers` endpoint)\n * - An auto configuration object that creates/reuses containers automatically\n *\n * If not provided, defaults to auto mode with default settings.\n */\n container?: string | CodeInterpreterAutoContainer;\n}\n\n/**\n * OpenAI Code Interpreter tool type for the Responses API.\n */\nexport type CodeInterpreterTool = OpenAIClient.Responses.Tool.CodeInterpreter;\n\n/**\n * Converts container options to the API format.\n */\nfunction convertContainer(\n container: string | CodeInterpreterAutoContainer | undefined\n):\n | string\n | OpenAIClient.Responses.Tool.CodeInterpreter.CodeInterpreterToolAuto {\n // If a string container ID is provided, use it directly\n if (typeof container === \"string\") {\n return container;\n }\n\n // Auto mode configuration\n return {\n type: \"auto\",\n file_ids: container?.fileIds,\n memory_limit: container?.memoryLimit,\n };\n}\n\n/**\n * Creates a Code Interpreter tool that allows models to write and run Python code\n * in a sandboxed environment to solve complex problems.\n *\n * Use Code Interpreter for:\n * - **Data analysis**: Processing files with diverse data and formatting\n * - **File generation**: Creating files with data and images of graphs\n * - **Iterative coding**: Writing and running code iteratively to solve problems\n * - **Visual intelligence**: Cropping, zooming, rotating, and transforming images\n *\n * The tool runs in a container, which is a fully sandboxed virtual machine.\n * Containers can be created automatically (auto mode) or explicitly via the\n * `/v1/containers` endpoint.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation}\n *\n * @param options - Configuration options for the Code Interpreter tool\n * @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4.1\" });\n *\n * // Basic usage with auto container (default 1GB memory)\n * const response = await model.invoke(\n * \"Solve the equation 3x + 11 = 14\",\n * { tools: [tools.codeInterpreter()] }\n * );\n *\n * // With increased memory limit for larger computations\n * const response = await model.invoke(\n * \"Analyze this large dataset and create visualizations\",\n * {\n * tools: [tools.codeInterpreter({\n * container: { memoryLimit: \"4g\" }\n * })]\n * }\n * );\n *\n * // With specific files available to the code\n * const response = await model.invoke(\n * \"Process the uploaded CSV file\",\n * {\n * tools: [tools.codeInterpreter({\n * container: {\n * memoryLimit: \"4g\",\n * fileIds: [\"file-abc123\", \"file-def456\"]\n * }\n * })]\n * }\n * );\n *\n * // Using an explicit container ID (created via /v1/containers)\n * const response = await model.invoke(\n * \"Continue working with the data\",\n * {\n * tools: [tools.codeInterpreter({\n * container: \"cntr_abc123\"\n * })]\n * }\n * );\n * ```\n *\n * @remarks\n * - Containers expire after 20 minutes of inactivity\n * - While called \"Code Interpreter\", the model knows it as the \"python tool\"\n * - For explicit prompting, ask for \"the python tool\" in your prompts\n * - Files in model input are automatically uploaded to the container\n * - Generated files are returned as `container_file_citation` annotations\n */\nexport function codeInterpreter(options?: CodeInterpreterOptions): ServerTool {\n return {\n type: \"code_interpreter\",\n container: convertContainer(options?.container),\n } satisfies CodeInterpreterTool;\n}\n"],"mappings":";;;;AAsDA,SAAS,iBACP,WAGsE;AAEtE,KAAI,OAAO,cAAc,SACvB,QAAO;AAIT,QAAO;EACL,MAAM;EACN,UAAU,WAAW;EACrB,cAAc,WAAW;EAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EH,SAAgB,gBAAgB,SAA8C;AAC5E,QAAO;EACL,MAAM;EACN,WAAW,iBAAiB,SAAS,UAAU;EAChD"}
1
+ {"version":3,"file":"codeInterpreter.js","names":[],"sources":["../../src/tools/codeInterpreter.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n\n/**\n * Memory limit options for the Code Interpreter container.\n * Higher tiers offer more RAM and are billed at different rates.\n */\nexport type CodeInterpreterMemoryLimit = \"1g\" | \"4g\" | \"16g\" | \"64g\";\n\n/**\n * Auto container configuration for Code Interpreter.\n * Creates a new container automatically or reuses an active one.\n */\nexport interface CodeInterpreterAutoContainer {\n /**\n * Memory limit for the container.\n * - `\"1g\"` (default): 1 GB RAM\n * - `\"4g\"`: 4 GB RAM\n * - `\"16g\"`: 16 GB RAM\n * - `\"64g\"`: 64 GB RAM\n */\n memoryLimit?: CodeInterpreterMemoryLimit;\n /**\n * Optional list of uploaded file IDs to make available to the code.\n * Files in the model input are automatically uploaded, so this is only\n * needed for additional files.\n */\n fileIds?: string[];\n}\n\n/**\n * Options for the Code Interpreter tool.\n */\nexport interface CodeInterpreterOptions {\n /**\n * The container configuration for the Code Interpreter.\n *\n * Can be either:\n * - A string container ID for explicit mode (created via `/v1/containers` endpoint)\n * - An auto configuration object that creates/reuses containers automatically\n *\n * If not provided, defaults to auto mode with default settings.\n */\n container?: string | CodeInterpreterAutoContainer;\n}\n\n/**\n * OpenAI Code Interpreter tool type for the Responses API.\n */\nexport type CodeInterpreterTool = OpenAIClient.Responses.Tool.CodeInterpreter;\n\n/**\n * Converts container options to the API format.\n */\nfunction convertContainer(\n container: string | CodeInterpreterAutoContainer | undefined\n):\n | string\n | OpenAIClient.Responses.Tool.CodeInterpreter.CodeInterpreterToolAuto {\n // If a string container ID is provided, use it directly\n if (typeof container === \"string\") {\n return container;\n }\n\n // Auto mode configuration\n return {\n type: \"auto\",\n file_ids: container?.fileIds,\n memory_limit: container?.memoryLimit,\n };\n}\n\n/**\n * Creates a Code Interpreter tool that allows models to write and run Python code\n * in a sandboxed environment to solve complex problems.\n *\n * Use Code Interpreter for:\n * - **Data analysis**: Processing files with diverse data and formatting\n * - **File generation**: Creating files with data and images of graphs\n * - **Iterative coding**: Writing and running code iteratively to solve problems\n * - **Visual intelligence**: Cropping, zooming, rotating, and transforming images\n *\n * The tool runs in a container, which is a fully sandboxed virtual machine.\n * Containers can be created automatically (auto mode) or explicitly via the\n * `/v1/containers` endpoint.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation}\n *\n * @param options - Configuration options for the Code Interpreter tool\n * @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4.1\" });\n *\n * // Basic usage with auto container (default 1GB memory)\n * const response = await model.invoke(\n * \"Solve the equation 3x + 11 = 14\",\n * { tools: [tools.codeInterpreter()] }\n * );\n *\n * // With increased memory limit for larger computations\n * const response = await model.invoke(\n * \"Analyze this large dataset and create visualizations\",\n * {\n * tools: [tools.codeInterpreter({\n * container: { memoryLimit: \"4g\" }\n * })]\n * }\n * );\n *\n * // With specific files available to the code\n * const response = await model.invoke(\n * \"Process the uploaded CSV file\",\n * {\n * tools: [tools.codeInterpreter({\n * container: {\n * memoryLimit: \"4g\",\n * fileIds: [\"file-abc123\", \"file-def456\"]\n * }\n * })]\n * }\n * );\n *\n * // Using an explicit container ID (created via /v1/containers)\n * const response = await model.invoke(\n * \"Continue working with the data\",\n * {\n * tools: [tools.codeInterpreter({\n * container: \"cntr_abc123\"\n * })]\n * }\n * );\n * ```\n *\n * @remarks\n * - Containers expire after 20 minutes of inactivity\n * - While called \"Code Interpreter\", the model knows it as the \"python tool\"\n * - For explicit prompting, ask for \"the python tool\" in your prompts\n * - Files in model input are automatically uploaded to the container\n * - Generated files are returned as `container_file_citation` annotations\n */\nexport function codeInterpreter(options?: CodeInterpreterOptions): ServerTool {\n return {\n type: \"code_interpreter\",\n container: convertContainer(options?.container),\n } satisfies CodeInterpreterTool;\n}\n"],"mappings":";;;;AAsDA,SAAS,iBACP,WAGsE;CAEtE,IAAI,OAAO,cAAc,UACvB,OAAO;CAIT,OAAO;EACL,MAAM;EACN,UAAU,WAAW;EACrB,cAAc,WAAW;CAC3B;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,gBAAgB,SAA8C;CAC5E,OAAO;EACL,MAAM;EACN,WAAW,iBAAiB,SAAS,SAAS;CAChD;AACF"}
@@ -228,6 +228,7 @@ function computerUse(options) {
228
228
  return computerTool;
229
229
  }
230
230
  //#endregion
231
+ exports.ComputerUseActionSchema = ComputerUseActionSchema;
231
232
  exports.computerUse = computerUse;
232
233
 
233
234
  //# sourceMappingURL=computerUse.cjs.map