@langchain/openai 1.5.9 → 1.5.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/azure/chat_models/common.cjs.map +1 -1
- package/dist/azure/embeddings.cjs.map +1 -1
- package/dist/azure/llms.cjs.map +1 -1
- package/dist/chat_models/base.cjs +3 -2
- package/dist/chat_models/base.cjs.map +1 -1
- package/dist/chat_models/base.js +3 -2
- package/dist/chat_models/base.js.map +1 -1
- package/dist/chat_models/completions.cjs.map +1 -1
- package/dist/chat_models/responses.cjs.map +1 -1
- package/dist/chat_models/responses.js.map +1 -1
- package/dist/converters/completions.cjs +3 -1
- package/dist/converters/completions.cjs.map +1 -1
- package/dist/converters/completions.d.cts.map +1 -1
- package/dist/converters/completions.d.ts.map +1 -1
- package/dist/converters/completions.js +3 -1
- package/dist/converters/completions.js.map +1 -1
- package/dist/converters/responses.cjs +6 -4
- package/dist/converters/responses.cjs.map +1 -1
- package/dist/converters/responses.d.cts.map +1 -1
- package/dist/converters/responses.d.ts.map +1 -1
- package/dist/converters/responses.js +6 -4
- package/dist/converters/responses.js.map +1 -1
- package/dist/embeddings.cjs +2 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.js +2 -1
- package/dist/embeddings.js.map +1 -1
- package/dist/llms.cjs +3 -2
- package/dist/llms.cjs.map +1 -1
- package/dist/llms.js +3 -2
- package/dist/llms.js.map +1 -1
- package/dist/tools/applyPatch.cjs.map +1 -1
- package/dist/tools/computerUse.cjs.map +1 -1
- package/dist/tools/custom.cjs.map +1 -1
- package/dist/tools/dalle.cjs.map +1 -1
- package/dist/tools/localShell.cjs.map +1 -1
- package/dist/tools/shell.cjs.map +1 -1
- package/dist/utils/azure.cjs.map +1 -1
- package/dist/utils/client.cjs.map +1 -1
- package/dist/utils/output.cjs.map +1 -1
- package/dist/utils/prompts.cjs +2 -1
- package/dist/utils/prompts.cjs.map +1 -1
- package/dist/utils/prompts.js +2 -1
- package/dist/utils/prompts.js.map +1 -1
- package/dist/utils/responses_stream_events.cjs.map +1 -1
- package/dist/utils/tools.cjs.map +1 -1
- package/package.json +4 -4
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 maxRetries: options.maxRetries,\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 // The SDK has its own `maxRetries`; take it for our caller instead so\n // the two retry loops don't multiply.\n const { maxRetries, ...sdkOptions } = options ?? {};\n const requestOptions = this._getClientOptions(sdkOptions);\n return this.caller.callWithOptions({ maxRetries }, 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,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,iBAAA,GAAA,0BAAA,uBAAA,CACe,gBAAgB;EACzC,KAAK,SAAS,KAAK;EAEnB,KAAK,eACH,QAAQ,eAAe,iBAAA,GAAA,0BAAA,uBAAA,CACA,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,SAAS,WAAW,GAEjC,MAAM,IAAI,MACR;GACE,8BAA8B,KAAK,MAAM;GACzC;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A,MAAM,oBACJ,SAGA,SAGA;EAGA,MAAM,EAAE,YAAY,GAAG,eAAe,WAAW,CAAC;EAClD,MAAM,iBAAiB,KAAK,kBAAkB,UAAU;EACxD,OAAO,KAAK,OAAO,gBAAgB,EAAE,WAAW,GAAG,YAAY;GAC7D,IAAI;IAKF,OAAO,MAJW,KAAK,OAAO,YAAY,OACxC,SACA,cACF;GAEF,SAAS,GAAG;IAEV,MADcC,eAAAA,sBAAsB,CAC1B;GACZ;EACF,CAAC;CACH;;;;;;;CAQA,kBACE,SAC0B;EAC1B,IAAI,CAAC,KAAK,QAAQ;GAKhB,MAAM,WAAWC,cAAAA,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,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"}
|
|
1
|
+
{"version":3,"file":"llms.cjs","names":["BaseLLM","getEnvironmentVariable","chunkArray","calculateMaxTokens","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 maxRetries: options.maxRetries,\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 // The SDK has its own `maxRetries`; take it for our caller instead so\n // the two retry loops don't multiply.\n const { maxRetries, ...sdkOptions } = options ?? {};\n const requestOptions = this._getClientOptions(sdkOptions);\n return this.caller.callWithOptions({ maxRetries }, 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,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;CAE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B,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.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.
|
|
85
|
+
this._addVersion("@langchain/openai", "1.5.11");
|
|
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");
|
|
@@ -285,7 +285,8 @@ var OpenAI$2 = class extends BaseLLM {
|
|
|
285
285
|
*/
|
|
286
286
|
_getClientOptions(options) {
|
|
287
287
|
if (!this.client) {
|
|
288
|
-
const
|
|
288
|
+
const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL };
|
|
289
|
+
const endpoint = getEndpoint(openAIEndpointConfig);
|
|
289
290
|
const params = {
|
|
290
291
|
...this.clientConfig,
|
|
291
292
|
baseURL: endpoint,
|
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 maxRetries: options.maxRetries,\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 // The SDK has its own `maxRetries`; take it for our caller instead so\n // the two retry loops don't multiply.\n const { maxRetries, ...sdkOptions } = options ?? {};\n const requestOptions = this._getClientOptions(sdkOptions);\n return this.caller.callWithOptions({ maxRetries }, 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,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AO;GAHL,GAAG,KAAK;GACR,GAAG;EAEe;CACtB;CAEA,WAAW;EACT,OAAO;CACT;AACF"}
|
|
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 maxRetries: options.maxRetries,\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 // The SDK has its own `maxRetries`; take it for our caller instead so\n // the two retry loops don't multiply.\n const { maxRetries, ...sdkOptions } = options ?? {};\n const requestOptions = this._getClientOptions(sdkOptions);\n return this.caller.callWithOptions({ maxRetries }, 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,QAAoC;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,SAAS,WAAW,GAEjC,MAAM,IAAI,MACR;GACE,8BAA8B,KAAK,MAAM;GACzC;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,IAAI,CACb;EAEF,KAAK,YAAY,KAAK;EACtB,KAAK,cAAc,QAAQ,eAAe,CAAC;EAC3C,KAAK,YAAY,QAAQ,aAAa,KAAK;EAC3C,KAAK,UAAU,QA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S,GAAG;IAEV,MADc,sBAAsB,CAC1B;GACZ;EACF,CAAC;CACH;;;;;;;CAQA,kBACE,SAC0B;EAC1B,IAAI,CAAC,KAAK,QAAQ;GAChB,MAAM,uBAA6C,EACjD,SAAS,KAAK,aAAa,QAC7B;GAEA,MAAM,WAAW,YAAY,oBAAoB;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"}
|
|
@@ -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,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,
|
|
1
|
+
{"version":3,"file":"applyPatch.cjs","names":["z","tool"],"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,GAAYC,sBAAAA,KAAAA,CAAK,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":"computerUse.cjs","names":["z","ToolMessage"],"sources":["../../src/tools/computerUse.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v4\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { tool, type DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { type ToolRuntime } from \"@langchain/core/tools\";\nimport {\n ToolMessage,\n type AIMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\n\n/**\n * The type of computer environment to control.\n */\nexport type ComputerUseEnvironment =\n | \"browser\"\n | \"mac\"\n | \"windows\"\n | \"linux\"\n | \"ubuntu\";\n\n/**\n * Re-export action types from OpenAI SDK for convenience.\n */\nexport type ComputerUseClickAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Click;\nexport type ComputerUseDoubleClickAction =\n OpenAIClient.Responses.ResponseComputerToolCall.DoubleClick;\nexport type ComputerUseDragAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Drag;\nexport type ComputerUseKeypressAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Keypress;\nexport type ComputerUseMoveAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Move;\nexport type ComputerUseScreenshotAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Screenshot;\nexport type ComputerUseScrollAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Scroll;\nexport type ComputerUseTypeAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Type;\nexport type ComputerUseWaitAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Wait;\n\n/**\n * Union type of all computer use actions from OpenAI SDK.\n */\nexport type ComputerUseAction =\n OpenAIClient.Responses.ResponseComputerToolCall[\"action\"];\n\n// Zod schemas for computer use actions\nconst ComputerUseScreenshotActionSchema = z.object({\n type: z.literal(\"screenshot\"),\n});\n\nconst ComputerUseClickActionSchema = z.object({\n type: z.literal(\"click\"),\n x: z.number(),\n y: z.number(),\n button: z.enum([\"left\", \"right\", \"wheel\", \"back\", \"forward\"]).default(\"left\"),\n});\n\nconst ComputerUseDoubleClickActionSchema = z.object({\n type: z.literal(\"double_click\"),\n x: z.number(),\n y: z.number(),\n button: z.enum([\"left\", \"right\", \"wheel\", \"back\", \"forward\"]).default(\"left\"),\n});\n\nconst ComputerUseDragActionSchema = z.object({\n type: z.literal(\"drag\"),\n path: z.array(z.object({ x: z.number(), y: z.number() })),\n});\n\nconst ComputerUseKeypressActionSchema = z.object({\n type: z.literal(\"keypress\"),\n keys: z.array(z.string()),\n});\n\nconst ComputerUseMoveActionSchema = z.object({\n type: z.literal(\"move\"),\n x: z.number(),\n y: z.number(),\n});\n\nconst ComputerUseScrollActionSchema = z.object({\n type: z.literal(\"scroll\"),\n x: z.number(),\n y: z.number(),\n scroll_x: z.number(),\n scroll_y: z.number(),\n});\n\nconst ComputerUseTypeActionSchema = z.object({\n type: z.literal(\"type\"),\n text: z.string(),\n});\n\nconst ComputerUseWaitActionSchema = z.object({\n type: z.literal(\"wait\"),\n duration: z.number().optional(),\n});\n\n// Union schema for individual action types\nconst ComputerUseActionUnionSchema = z.union([\n ComputerUseScreenshotActionSchema,\n ComputerUseClickActionSchema,\n ComputerUseDoubleClickActionSchema,\n ComputerUseDragActionSchema,\n ComputerUseKeypressActionSchema,\n ComputerUseMoveActionSchema,\n ComputerUseScrollActionSchema,\n ComputerUseTypeActionSchema,\n ComputerUseWaitActionSchema,\n]);\n\n// Schema for the input structure received from parseComputerCall\n// The action is wrapped in an `action` property: { action: { type: 'screenshot' } }\nexport const ComputerUseActionSchema = z.object({\n action: ComputerUseActionUnionSchema,\n});\n\n// TypeScript types derived from Zod schemas\nexport type ComputerUseScreenshotActionType = z.infer<\n typeof ComputerUseScreenshotActionSchema\n>;\nexport type ComputerUseClickActionType = z.infer<\n typeof ComputerUseClickActionSchema\n>;\nexport type ComputerUseDoubleClickActionType = z.infer<\n typeof ComputerUseDoubleClickActionSchema\n>;\nexport type ComputerUseDragActionType = z.infer<\n typeof ComputerUseDragActionSchema\n>;\nexport type ComputerUseKeypressActionType = z.infer<\n typeof ComputerUseKeypressActionSchema\n>;\nexport type ComputerUseMoveActionType = z.infer<\n typeof ComputerUseMoveActionSchema\n>;\nexport type ComputerUseScrollActionType = z.infer<\n typeof ComputerUseScrollActionSchema\n>;\nexport type ComputerUseTypeActionType = z.infer<\n typeof ComputerUseTypeActionSchema\n>;\nexport type ComputerUseWaitActionType = z.infer<\n typeof ComputerUseWaitActionSchema\n>;\n\n/**\n * Input structure for the Computer Use tool.\n * The action is wrapped in an `action` property.\n */\nexport interface ComputerUseInput {\n action: ComputerUseAction;\n}\n\nexport type ComputerUseReturnType =\n | string\n | Promise<string>\n | ToolMessage<any>\n | Promise<ToolMessage<any>>;\n\n/**\n * Options for the Computer Use tool.\n */\nexport interface ComputerUseOptions {\n /**\n * The width of the computer display in pixels.\n */\n displayWidth: number;\n\n /**\n * The height of the computer display in pixels.\n */\n displayHeight: number;\n\n /**\n * The type of computer environment to control.\n * - `browser`: Browser automation (recommended for most use cases)\n * - `mac`: macOS environment\n * - `windows`: Windows environment\n * - `linux`: Linux environment\n * - `ubuntu`: Ubuntu environment\n */\n environment: ComputerUseEnvironment;\n\n /**\n * Execute function that handles computer action execution.\n * This function receives the action input and should return a base64-encoded\n * screenshot of the result.\n */\n execute: (\n action: ComputerUseAction,\n runtime: ToolRuntime<any, any>\n ) => ComputerUseReturnType;\n}\n\n/**\n * OpenAI Computer Use tool type for the Responses API.\n */\nexport type ComputerUseTool = OpenAIClient.Responses.ComputerUsePreviewTool;\n\nconst TOOL_NAME = \"computer_use\";\n\n/**\n * Creates a Computer Use tool that allows models to control computer interfaces\n * and perform tasks by simulating mouse clicks, keyboard input, scrolling, and more.\n *\n * **Computer Use** is a practical application of OpenAI's Computer-Using Agent (CUA)\n * model (`computer-use-preview`), which combines vision capabilities with advanced\n * reasoning to simulate controlling computer interfaces.\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends computer actions (click, type, scroll, etc.)\n * 2. Your code executes these actions in a controlled environment\n * 3. You capture a screenshot of the result\n * 4. Send the screenshot back to the model\n * 5. Repeat until the task is complete\n *\n * **Important**: Computer use is in beta and requires careful consideration:\n * - Use in sandboxed environments only\n * - Do not use for high-stakes or authenticated tasks\n * - Always implement human-in-the-loop for important decisions\n * - Handle safety checks appropriately\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-computer-use | OpenAI Computer Use Documentation}\n *\n * @param options - Configuration options for the Computer Use tool\n * @returns A Computer Use tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"computer-use-preview\" });\n *\n * // With execute callback for automatic action handling\n * const computer = tools.computerUse({\n * displayWidth: 1024,\n * displayHeight: 768,\n * environment: \"browser\",\n * execute: async (action) => {\n * if (action.type === \"screenshot\") {\n * return captureScreenshot();\n * }\n * if (action.type === \"click\") {\n * await page.mouse.click(action.x, action.y, { button: action.button });\n * return captureScreenshot();\n * }\n * if (action.type === \"type\") {\n * await page.keyboard.type(action.text);\n * return captureScreenshot();\n * }\n * // Handle other actions...\n * return captureScreenshot();\n * },\n * });\n *\n * const llmWithComputer = model.bindTools([computer]);\n * const response = await llmWithComputer.invoke(\n * \"Check the latest news on bing.com\"\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Without execute callback (manual action handling)\n * const computer = tools.computerUse({\n * displayWidth: 1024,\n * displayHeight: 768,\n * environment: \"browser\",\n * });\n *\n * const response = await model.invoke(\"Check the news\", {\n * tools: [computer],\n * });\n *\n * // Access the computer call from the response\n * const computerCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"computer_call\"\n * );\n * if (computerCall) {\n * console.log(\"Action to execute:\", computerCall.action);\n * // Execute the action manually, then send back a screenshot\n * }\n * ```\n *\n * @example\n * ```typescript\n * // For macOS desktop automation with Docker\n * const computer = tools.computerUse({\n * displayWidth: 1920,\n * displayHeight: 1080,\n * environment: \"mac\",\n * execute: async (action) => {\n * if (action.type === \"click\") {\n * await dockerExec(\n * `DISPLAY=:99 xdotool mousemove ${action.x} ${action.y} click 1`,\n * containerName\n * );\n * }\n * // Capture screenshot from container\n * return await getDockerScreenshot(containerName);\n * },\n * });\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Requires `computer-use-preview` model\n * - Actions include: click, double_click, drag, keypress, move, screenshot, scroll, type, wait\n * - Safety checks may be returned that require acknowledgment before proceeding\n * - Use `truncation: \"auto\"` parameter when making requests\n * - Recommended to use with `reasoning.summary` for debugging\n */\nexport function computerUse(options: ComputerUseOptions) {\n const computerTool = tool(\n async (\n input: ComputerUseInput,\n runtime: ToolRuntime<{ messages: BaseMessage[] }>\n ) => {\n /**\n * get computer_use call id from runtime\n */\n const aiMessage = runtime.state?.messages.at(-1) as AIMessage | undefined;\n const computerToolCall = aiMessage?.tool_calls?.find(\n (tc) => tc.name === \"computer_use\"\n );\n const computerToolCallId = computerToolCall?.id;\n if (!computerToolCallId) {\n throw new Error(\"Computer use call id not found\");\n }\n\n const result = await options.execute(input.action, runtime);\n\n /**\n * make sure {@link ToolMessage} is returned with the correct additional kwargs\n */\n if (typeof result === \"string\") {\n return new ToolMessage({\n content: result,\n tool_call_id: computerToolCallId,\n additional_kwargs: {\n type: \"computer_call_output\",\n },\n });\n }\n\n /**\n * make sure {@link ToolMessage} is returned with the correct additional kwargs\n */\n return new ToolMessage({\n ...result,\n tool_call_id: computerToolCallId,\n additional_kwargs: {\n type: \"computer_call_output\",\n ...result.additional_kwargs,\n },\n });\n },\n {\n name: TOOL_NAME,\n description:\n \"Control a computer interface by executing mouse clicks, keyboard input, scrolling, and other actions.\",\n schema: ComputerUseActionSchema,\n }\n );\n\n computerTool.extras = {\n ...(computerTool.extras ?? {}),\n providerToolDefinition: {\n type: \"computer_use_preview\",\n display_width: options.displayWidth,\n display_height: options.displayHeight,\n environment: options.environment,\n } satisfies ComputerUseTool,\n };\n\n /**\n * return as typed {@link DynamicStructuredTool} so we don't get any type\n * errors like \"can't export tool without reference\"\n */\n return computerTool as DynamicStructuredTool<\n typeof ComputerUseActionSchema,\n ComputerUseInput,\n unknown,\n ComputerUseReturnType\n >;\n}\n"],"mappings":";;;;AAkDA,MAAM,oCAAoCA,OAAAA,EAAE,OAAO,EACjD,MAAMA,OAAAA,EAAE,QAAQ,YAAY,EAC9B,CAAC;AAED,MAAM,+BAA+BA,OAAAA,EAAE,OAAO;CAC5C,MAAMA,OAAAA,EAAE,QAAQ,OAAO;CACvB,GAAGA,OAAAA,EAAE,OAAO;CACZ,GAAGA,OAAAA,EAAE,OAAO;CACZ,QAAQA,OAAAA,EAAE,KAAK;EAAC;EAAQ;EAAS;EAAS;EAAQ;CAAS,CAAC,CAAC,CAAC,QAAQ,MAAM;AAC9E,CAAC;AAED,MAAM,qCAAqCA,OAAAA,EAAE,OAAO;CAClD,MAAMA,OAAAA,EAAE,QAAQ,cAAc;CAC9B,GAAGA,OAAAA,EAAE,OAAO;CACZ,GAAGA,OAAAA,EAAE,OAAO;CACZ,QAAQA,OAAAA,EAAE,KAAK;EAAC;EAAQ;EAAS;EAAS;EAAQ;CAAS,CAAC,CAAC,CAAC,QAAQ,MAAM;AAC9E,CAAC;AAED,MAAM,8BAA8BA,OAAAA,EAAE,OAAO;CAC3C,MAAMA,OAAAA,EAAE,QAAQ,MAA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHlB,SAAgB,YAAY,SAA6B;CACvD,MAAM,gBAAA,GAAA,sBAAA,KAAA,CACJ,OACE,OACA,YACG;EAQH,MAAM,uBAJY,QAAQ,OAAO,SAAS,GAAG,EAAE,EAAA,EACX,YAAY,MAC7C,OAAO,GAAG,SAAS,cACtB,EAAA,EAC6C;EAC7C,IAAI,CAAC,oBACH,MAAM,IAAI,MAAM,gCAAgC;EAGlD,MAAM,SAAS,MAAM,QAAQ,QAAQ,MAAM,QAAQ,OAAO;;;;EAK1D,IAAI,OAAO,WAAW,UACpB,OAAO,IAAIC,yBAAAA,YAAY;GACrB,SAAS;GACT,cAAc;GACd,mBAAmB,EACjB,MAAM,uBACR;EACF,CAAC;;;;EAMH,OAAO,IAAIA,yBAAAA,YAAY;GACrB,GAAG;GACH,cAAc;GACd,mBAAmB;IACjB,MAAM;IACN,GAAG,OAAO;GACZ;EACF,CAAC;CACH,GACA;EACE,MAAM;EACN,aACE;EACF,QAAQ;CACV,CACF;CAEA,aAAa,SAAS;EACpB,GAAI,aAAa,UAAU,CAAC;EAC5B,wBAAwB;GACtB,MAAM;GACN,eAAe,QAAQ;GACvB,gBAAgB,QAAQ;GACxB,aAAa,QAAQ;EACvB;CACF;;;;;CAMA,OAAO;AAMT"}
|
|
1
|
+
{"version":3,"file":"computerUse.cjs","names":["z","tool","ToolMessage"],"sources":["../../src/tools/computerUse.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v4\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { tool, type DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { type ToolRuntime } from \"@langchain/core/tools\";\nimport {\n ToolMessage,\n type AIMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\n\n/**\n * The type of computer environment to control.\n */\nexport type ComputerUseEnvironment =\n | \"browser\"\n | \"mac\"\n | \"windows\"\n | \"linux\"\n | \"ubuntu\";\n\n/**\n * Re-export action types from OpenAI SDK for convenience.\n */\nexport type ComputerUseClickAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Click;\nexport type ComputerUseDoubleClickAction =\n OpenAIClient.Responses.ResponseComputerToolCall.DoubleClick;\nexport type ComputerUseDragAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Drag;\nexport type ComputerUseKeypressAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Keypress;\nexport type ComputerUseMoveAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Move;\nexport type ComputerUseScreenshotAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Screenshot;\nexport type ComputerUseScrollAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Scroll;\nexport type ComputerUseTypeAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Type;\nexport type ComputerUseWaitAction =\n OpenAIClient.Responses.ResponseComputerToolCall.Wait;\n\n/**\n * Union type of all computer use actions from OpenAI SDK.\n */\nexport type ComputerUseAction =\n OpenAIClient.Responses.ResponseComputerToolCall[\"action\"];\n\n// Zod schemas for computer use actions\nconst ComputerUseScreenshotActionSchema = z.object({\n type: z.literal(\"screenshot\"),\n});\n\nconst ComputerUseClickActionSchema = z.object({\n type: z.literal(\"click\"),\n x: z.number(),\n y: z.number(),\n button: z.enum([\"left\", \"right\", \"wheel\", \"back\", \"forward\"]).default(\"left\"),\n});\n\nconst ComputerUseDoubleClickActionSchema = z.object({\n type: z.literal(\"double_click\"),\n x: z.number(),\n y: z.number(),\n button: z.enum([\"left\", \"right\", \"wheel\", \"back\", \"forward\"]).default(\"left\"),\n});\n\nconst ComputerUseDragActionSchema = z.object({\n type: z.literal(\"drag\"),\n path: z.array(z.object({ x: z.number(), y: z.number() })),\n});\n\nconst ComputerUseKeypressActionSchema = z.object({\n type: z.literal(\"keypress\"),\n keys: z.array(z.string()),\n});\n\nconst ComputerUseMoveActionSchema = z.object({\n type: z.literal(\"move\"),\n x: z.number(),\n y: z.number(),\n});\n\nconst ComputerUseScrollActionSchema = z.object({\n type: z.literal(\"scroll\"),\n x: z.number(),\n y: z.number(),\n scroll_x: z.number(),\n scroll_y: z.number(),\n});\n\nconst ComputerUseTypeActionSchema = z.object({\n type: z.literal(\"type\"),\n text: z.string(),\n});\n\nconst ComputerUseWaitActionSchema = z.object({\n type: z.literal(\"wait\"),\n duration: z.number().optional(),\n});\n\n// Union schema for individual action types\nconst ComputerUseActionUnionSchema = z.union([\n ComputerUseScreenshotActionSchema,\n ComputerUseClickActionSchema,\n ComputerUseDoubleClickActionSchema,\n ComputerUseDragActionSchema,\n ComputerUseKeypressActionSchema,\n ComputerUseMoveActionSchema,\n ComputerUseScrollActionSchema,\n ComputerUseTypeActionSchema,\n ComputerUseWaitActionSchema,\n]);\n\n// Schema for the input structure received from parseComputerCall\n// The action is wrapped in an `action` property: { action: { type: 'screenshot' } }\nexport const ComputerUseActionSchema = z.object({\n action: ComputerUseActionUnionSchema,\n});\n\n// TypeScript types derived from Zod schemas\nexport type ComputerUseScreenshotActionType = z.infer<\n typeof ComputerUseScreenshotActionSchema\n>;\nexport type ComputerUseClickActionType = z.infer<\n typeof ComputerUseClickActionSchema\n>;\nexport type ComputerUseDoubleClickActionType = z.infer<\n typeof ComputerUseDoubleClickActionSchema\n>;\nexport type ComputerUseDragActionType = z.infer<\n typeof ComputerUseDragActionSchema\n>;\nexport type ComputerUseKeypressActionType = z.infer<\n typeof ComputerUseKeypressActionSchema\n>;\nexport type ComputerUseMoveActionType = z.infer<\n typeof ComputerUseMoveActionSchema\n>;\nexport type ComputerUseScrollActionType = z.infer<\n typeof ComputerUseScrollActionSchema\n>;\nexport type ComputerUseTypeActionType = z.infer<\n typeof ComputerUseTypeActionSchema\n>;\nexport type ComputerUseWaitActionType = z.infer<\n typeof ComputerUseWaitActionSchema\n>;\n\n/**\n * Input structure for the Computer Use tool.\n * The action is wrapped in an `action` property.\n */\nexport interface ComputerUseInput {\n action: ComputerUseAction;\n}\n\nexport type ComputerUseReturnType =\n | string\n | Promise<string>\n | ToolMessage<any>\n | Promise<ToolMessage<any>>;\n\n/**\n * Options for the Computer Use tool.\n */\nexport interface ComputerUseOptions {\n /**\n * The width of the computer display in pixels.\n */\n displayWidth: number;\n\n /**\n * The height of the computer display in pixels.\n */\n displayHeight: number;\n\n /**\n * The type of computer environment to control.\n * - `browser`: Browser automation (recommended for most use cases)\n * - `mac`: macOS environment\n * - `windows`: Windows environment\n * - `linux`: Linux environment\n * - `ubuntu`: Ubuntu environment\n */\n environment: ComputerUseEnvironment;\n\n /**\n * Execute function that handles computer action execution.\n * This function receives the action input and should return a base64-encoded\n * screenshot of the result.\n */\n execute: (\n action: ComputerUseAction,\n runtime: ToolRuntime<any, any>\n ) => ComputerUseReturnType;\n}\n\n/**\n * OpenAI Computer Use tool type for the Responses API.\n */\nexport type ComputerUseTool = OpenAIClient.Responses.ComputerUsePreviewTool;\n\nconst TOOL_NAME = \"computer_use\";\n\n/**\n * Creates a Computer Use tool that allows models to control computer interfaces\n * and perform tasks by simulating mouse clicks, keyboard input, scrolling, and more.\n *\n * **Computer Use** is a practical application of OpenAI's Computer-Using Agent (CUA)\n * model (`computer-use-preview`), which combines vision capabilities with advanced\n * reasoning to simulate controlling computer interfaces.\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends computer actions (click, type, scroll, etc.)\n * 2. Your code executes these actions in a controlled environment\n * 3. You capture a screenshot of the result\n * 4. Send the screenshot back to the model\n * 5. Repeat until the task is complete\n *\n * **Important**: Computer use is in beta and requires careful consideration:\n * - Use in sandboxed environments only\n * - Do not use for high-stakes or authenticated tasks\n * - Always implement human-in-the-loop for important decisions\n * - Handle safety checks appropriately\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-computer-use | OpenAI Computer Use Documentation}\n *\n * @param options - Configuration options for the Computer Use tool\n * @returns A Computer Use tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"computer-use-preview\" });\n *\n * // With execute callback for automatic action handling\n * const computer = tools.computerUse({\n * displayWidth: 1024,\n * displayHeight: 768,\n * environment: \"browser\",\n * execute: async (action) => {\n * if (action.type === \"screenshot\") {\n * return captureScreenshot();\n * }\n * if (action.type === \"click\") {\n * await page.mouse.click(action.x, action.y, { button: action.button });\n * return captureScreenshot();\n * }\n * if (action.type === \"type\") {\n * await page.keyboard.type(action.text);\n * return captureScreenshot();\n * }\n * // Handle other actions...\n * return captureScreenshot();\n * },\n * });\n *\n * const llmWithComputer = model.bindTools([computer]);\n * const response = await llmWithComputer.invoke(\n * \"Check the latest news on bing.com\"\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Without execute callback (manual action handling)\n * const computer = tools.computerUse({\n * displayWidth: 1024,\n * displayHeight: 768,\n * environment: \"browser\",\n * });\n *\n * const response = await model.invoke(\"Check the news\", {\n * tools: [computer],\n * });\n *\n * // Access the computer call from the response\n * const computerCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"computer_call\"\n * );\n * if (computerCall) {\n * console.log(\"Action to execute:\", computerCall.action);\n * // Execute the action manually, then send back a screenshot\n * }\n * ```\n *\n * @example\n * ```typescript\n * // For macOS desktop automation with Docker\n * const computer = tools.computerUse({\n * displayWidth: 1920,\n * displayHeight: 1080,\n * environment: \"mac\",\n * execute: async (action) => {\n * if (action.type === \"click\") {\n * await dockerExec(\n * `DISPLAY=:99 xdotool mousemove ${action.x} ${action.y} click 1`,\n * containerName\n * );\n * }\n * // Capture screenshot from container\n * return await getDockerScreenshot(containerName);\n * },\n * });\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Requires `computer-use-preview` model\n * - Actions include: click, double_click, drag, keypress, move, screenshot, scroll, type, wait\n * - Safety checks may be returned that require acknowledgment before proceeding\n * - Use `truncation: \"auto\"` parameter when making requests\n * - Recommended to use with `reasoning.summary` for debugging\n */\nexport function computerUse(options: ComputerUseOptions) {\n const computerTool = tool(\n async (\n input: ComputerUseInput,\n runtime: ToolRuntime<{ messages: BaseMessage[] }>\n ) => {\n /**\n * get computer_use call id from runtime\n */\n const aiMessage = runtime.state?.messages.at(-1) as AIMessage | undefined;\n const computerToolCall = aiMessage?.tool_calls?.find(\n (tc) => tc.name === \"computer_use\"\n );\n const computerToolCallId = computerToolCall?.id;\n if (!computerToolCallId) {\n throw new Error(\"Computer use call id not found\");\n }\n\n const result = await options.execute(input.action, runtime);\n\n /**\n * make sure {@link ToolMessage} is returned with the correct additional kwargs\n */\n if (typeof result === \"string\") {\n return new ToolMessage({\n content: result,\n tool_call_id: computerToolCallId,\n additional_kwargs: {\n type: \"computer_call_output\",\n },\n });\n }\n\n /**\n * make sure {@link ToolMessage} is returned with the correct additional kwargs\n */\n return new ToolMessage({\n ...result,\n tool_call_id: computerToolCallId,\n additional_kwargs: {\n type: \"computer_call_output\",\n ...result.additional_kwargs,\n },\n });\n },\n {\n name: TOOL_NAME,\n description:\n \"Control a computer interface by executing mouse clicks, keyboard input, scrolling, and other actions.\",\n schema: ComputerUseActionSchema,\n }\n );\n\n computerTool.extras = {\n ...(computerTool.extras ?? {}),\n providerToolDefinition: {\n type: \"computer_use_preview\",\n display_width: options.displayWidth,\n display_height: options.displayHeight,\n environment: options.environment,\n } satisfies ComputerUseTool,\n };\n\n /**\n * return as typed {@link DynamicStructuredTool} so we don't get any type\n * errors like \"can't export tool without reference\"\n */\n return computerTool as DynamicStructuredTool<\n typeof ComputerUseActionSchema,\n ComputerUseInput,\n unknown,\n ComputerUseReturnType\n >;\n}\n"],"mappings":";;;;AAkDA,MAAM,oCAAoCA,OAAAA,EAAE,OAAO,EACjD,MAAMA,OAAAA,EAAE,QAAQ,YAAY,EAC9B,CAAC;AAED,MAAM,+BAA+BA,OAAAA,EAAE,OAAO;CAC5C,MAAMA,OAAAA,EAAE,QAAQ,OAAO;CACvB,GAAGA,OAAAA,EAAE,OAAO;CACZ,GAAGA,OAAAA,EAAE,OAAO;CACZ,QAAQA,OAAAA,E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;;;CAMA,OAAO;AAMT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.cjs","names":["DynamicTool","AsyncLocalStorageProviderSingleton"],"sources":["../../src/tools/custom.ts"],"sourcesContent":["import {\n patchConfig,\n pickRunnableConfigKeys,\n RunnableFunc,\n} from \"@langchain/core/runnables\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { DynamicTool, ToolRunnableConfig } from \"@langchain/core/tools\";\nimport OpenAI from \"openai\";\n\nexport type CustomToolFields = Omit<OpenAI.Responses.CustomTool, \"type\">;\n\nexport function customTool(\n func: RunnableFunc<string, string, ToolRunnableConfig>,\n fields: CustomToolFields\n): DynamicTool<string> {\n return new DynamicTool({\n ...fields,\n description: \"\",\n metadata: {\n customTool: fields,\n },\n func: async (input, runManager, config) =>\n new Promise<string>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n resolve(func(input, childConfig));\n } catch (e) {\n reject(e);\n }\n }\n );\n }),\n });\n}\n"],"mappings":";;;;AAWA,SAAgB,WACd,MACA,QACqB;CACrB,OAAO,IAAIA,sBAAAA,YAAY;EACrB,GAAG;EACH,aAAa;EACb,UAAU,EACR,YAAY,OACd;EACA,MAAM,OAAO,OAAO,YAAY,WAC9B,IAAI,SAAiB,SAAS,WAAW;GACvC,MAAM,eAAA,
|
|
1
|
+
{"version":3,"file":"custom.cjs","names":["DynamicTool","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys"],"sources":["../../src/tools/custom.ts"],"sourcesContent":["import {\n patchConfig,\n pickRunnableConfigKeys,\n RunnableFunc,\n} from \"@langchain/core/runnables\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { DynamicTool, ToolRunnableConfig } from \"@langchain/core/tools\";\nimport OpenAI from \"openai\";\n\nexport type CustomToolFields = Omit<OpenAI.Responses.CustomTool, \"type\">;\n\nexport function customTool(\n func: RunnableFunc<string, string, ToolRunnableConfig>,\n fields: CustomToolFields\n): DynamicTool<string> {\n return new DynamicTool({\n ...fields,\n description: \"\",\n metadata: {\n customTool: fields,\n },\n func: async (input, runManager, config) =>\n new Promise<string>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n resolve(func(input, childConfig));\n } catch (e) {\n reject(e);\n }\n }\n );\n }),\n });\n}\n"],"mappings":";;;;AAWA,SAAgB,WACd,MACA,QACqB;CACrB,OAAO,IAAIA,sBAAAA,YAAY;EACrB,GAAG;EACH,aAAa;EACb,UAAU,EACR,YAAY,OACd;EACA,MAAM,OAAO,OAAO,YAAY,WAC9B,IAAI,SAAiB,SAAS,WAAW;GACvC,MAAM,eAAA,GAAcC,0BAAAA,YAAAA,CAAY,QAAQ,EACtC,WAAW,YAAY,SAAS,EAClC,CAAC;GAED,2BAAKC,mCAAmC,eAAA,GACtCC,0BAAAA,uBAAAA,CAAuB,WAAW,GAClC,YAAY;IACV,IAAI;KACF,QAAQ,KAAK,OAAO,WAAW,CAAC;IAClC,SAAS,GAAG;KACV,OAAO,CAAC;IACV;GACF,CACF;EACF,CAAC;CACL,CAAC;AACH"}
|
package/dist/tools/dalle.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dalle.cjs","names":["Tool","OpenAIClient"],"sources":["../../src/tools/dalle.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { Tool, ToolParams } from \"@langchain/core/tools\";\nimport {\n MessageContentComplex,\n MessageContentImageUrl,\n} from \"@langchain/core/messages\";\n\n/**\n * @see https://platform.openai.com/docs/api-reference/images/create\n */\nexport type OpenAIImageModelId =\n | OpenAIClient.ImageModel\n | (string & NonNullable<unknown>);\n\n/**\n * An interface for the Dall-E API Wrapper.\n */\nexport interface DallEAPIWrapperParams extends ToolParams {\n /**\n * The OpenAI API key\n * Alias for `apiKey`\n */\n openAIApiKey?: string;\n /**\n * The OpenAI API key\n */\n apiKey?: string;\n /**\n * The model to use.\n * Alias for `model`\n * @params \"dall-e-2\" | \"dall-e-3\"\n * @default \"dall-e-3\"\n * @deprecated Use `model` instead.\n */\n modelName?: OpenAIImageModelId;\n /**\n * The model to use.\n * @params \"dall-e-2\" | \"dall-e-3\"\n * @default \"dall-e-3\"\n */\n model?: OpenAIImageModelId;\n /**\n * The style of the generated images. Must be one of vivid or natural.\n * Vivid causes the model to lean towards generating hyper-real and dramatic images.\n * Natural causes the model to produce more natural, less hyper-real looking images.\n * @default \"vivid\"\n */\n style?: \"natural\" | \"vivid\";\n /**\n * The quality of the image that will be generated. ‘hd’ creates images with finer\n * details and greater consistency across the image.\n * @default \"standard\"\n */\n quality?: \"standard\" | \"hd\";\n /**\n * The number of images to generate.\n * Must be between 1 and 10.\n * For dall-e-3, only `n: 1` is supported.\n * @default 1\n */\n n?: number;\n /**\n * The size of the generated images.\n * Must be one of 256x256, 512x512, or 1024x1024 for DALL·E-2 models.\n * Must be one of 1024x1024, 1792x1024, or 1024x1792 for DALL·E-3 models.\n * @default \"1024x1024\"\n */\n size?: \"256x256\" | \"512x512\" | \"1024x1024\" | \"1792x1024\" | \"1024x1792\";\n /**\n * The format in which the generated images are returned.\n * Must be one of \"url\" or \"b64_json\".\n * @default \"url\"\n */\n dallEResponseFormat?: \"url\" | \"b64_json\";\n /**\n * @deprecated Use dallEResponseFormat instead for the Dall-E response type.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n responseFormat?: any;\n /**\n * A unique identifier representing your end-user, which will help\n * OpenAI to monitor and detect abuse.\n */\n user?: string;\n /**\n * The organization to use\n */\n organization?: string;\n /**\n * The base URL of the OpenAI API.\n */\n baseUrl?: string;\n}\n\n/**\n * A tool for generating images with Open AIs Dall-E 2 or 3 API.\n */\nexport class DallEAPIWrapper extends Tool {\n static lc_name() {\n return \"DallEAPIWrapper\";\n }\n\n name = \"dalle_api_wrapper\";\n\n description =\n \"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.\";\n\n protected client: OpenAIClient;\n\n static readonly toolName = \"dalle_api_wrapper\";\n\n private model = \"dall-e-3\";\n\n private style: \"natural\" | \"vivid\" = \"vivid\";\n\n private quality: \"standard\" | \"hd\" = \"standard\";\n\n private n = 1;\n\n private size:\n | \"256x256\"\n | \"512x512\"\n | \"1024x1024\"\n | \"1792x1024\"\n | \"1024x1792\" = \"1024x1024\";\n\n private dallEResponseFormat: \"url\" | \"b64_json\" = \"url\";\n\n private user?: string;\n\n constructor(fields?: DallEAPIWrapperParams) {\n // Shim for new base tool param name\n if (\n fields?.responseFormat !== undefined &&\n [\"url\", \"b64_json\"].includes(fields.responseFormat)\n ) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n fields.dallEResponseFormat = fields.responseFormat as any;\n fields.responseFormat = \"content\";\n }\n super(fields);\n const openAIApiKey =\n fields?.apiKey ??\n fields?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n\n const organization =\n fields?.organization ?? getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n const clientConfig = {\n apiKey: openAIApiKey,\n organization,\n dangerouslyAllowBrowser: true,\n baseURL: fields?.baseUrl,\n };\n this.client = new OpenAIClient(clientConfig);\n this.model = fields?.model ?? fields?.modelName ?? this.model;\n this.style = fields?.style ?? this.style;\n this.quality = fields?.quality ?? this.quality;\n this.n = fields?.n ?? this.n;\n this.size = fields?.size ?? this.size;\n this.dallEResponseFormat =\n fields?.dallEResponseFormat ?? this.dallEResponseFormat;\n this.user = fields?.user;\n }\n\n /**\n * Processes the API response if multiple images are generated.\n * Returns a list of MessageContentImageUrl objects. If the response\n * format is `url`, then the `image_url` field will contain the URL.\n * If it is `b64_json`, then the `image_url` field will contain an object\n * with a `url` field with the base64 encoded image.\n *\n * @param {OpenAIClient.Images.ImagesResponse[]} response The API response\n * @returns {MessageContentImageUrl[]}\n */\n private processMultipleGeneratedUrls(\n response: OpenAIClient.Images.ImagesResponse[]\n ): MessageContentImageUrl[] {\n if (this.dallEResponseFormat === \"url\") {\n return response.flatMap((res) => {\n const imageUrlContent =\n res.data\n ?.flatMap((item) => {\n if (!item.url) return [];\n return {\n type: \"image_url\" as const,\n image_url: item.url,\n };\n })\n .filter(\n (item) =>\n item !== undefined &&\n item.type === \"image_url\" &&\n typeof item.image_url === \"string\" &&\n item.image_url !== undefined\n ) ?? [];\n return imageUrlContent;\n });\n } else {\n return response.flatMap((res) => {\n const b64Content =\n res.data\n ?.flatMap((item) => {\n if (!item.b64_json) return [];\n return {\n type: \"image_url\" as const,\n image_url: {\n url: item.b64_json,\n },\n };\n })\n .filter(\n (item) =>\n item !== undefined &&\n item.type === \"image_url\" &&\n typeof item.image_url === \"object\" &&\n \"url\" in item.image_url &&\n typeof item.image_url.url === \"string\" &&\n item.image_url.url !== undefined\n ) ?? [];\n return b64Content;\n });\n }\n }\n\n /** @ignore */\n async _call(input: string): Promise<string | MessageContentComplex[]> {\n const generateImageFields = {\n model: this.model,\n prompt: input,\n n: 1,\n size: this.size,\n response_format: this.dallEResponseFormat,\n style: this.style,\n quality: this.quality,\n user: this.user,\n };\n\n if (this.n > 1) {\n const results = await Promise.all(\n Array.from({ length: this.n }).map(() =>\n this.client.images.generate(generateImageFields)\n )\n );\n\n return this.processMultipleGeneratedUrls(results);\n }\n\n const response = await this.client.images.generate(generateImageFields);\n\n let data = \"\";\n if (this.dallEResponseFormat === \"url\") {\n [data] =\n response.data\n ?.map((item) => item.url)\n .filter((url): url is string => url !== \"undefined\") ?? [];\n } else {\n [data] =\n response.data\n ?.map((item) => item.b64_json)\n .filter((b64_json): b64_json is string => b64_json !== \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["Tool","getEnvironmentVariable","OpenAIClient"],"sources":["../../src/tools/dalle.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { Tool, ToolParams } from \"@langchain/core/tools\";\nimport {\n MessageContentComplex,\n MessageContentImageUrl,\n} from \"@langchain/core/messages\";\n\n/**\n * @see https://platform.openai.com/docs/api-reference/images/create\n */\nexport type OpenAIImageModelId =\n | OpenAIClient.ImageModel\n | (string & NonNullable<unknown>);\n\n/**\n * An interface for the Dall-E API Wrapper.\n */\nexport interface DallEAPIWrapperParams extends ToolParams {\n /**\n * The OpenAI API key\n * Alias for `apiKey`\n */\n openAIApiKey?: string;\n /**\n * The OpenAI API key\n */\n apiKey?: string;\n /**\n * The model to use.\n * Alias for `model`\n * @params \"dall-e-2\" | \"dall-e-3\"\n * @default \"dall-e-3\"\n * @deprecated Use `model` instead.\n */\n modelName?: OpenAIImageModelId;\n /**\n * The model to use.\n * @params \"dall-e-2\" | \"dall-e-3\"\n * @default \"dall-e-3\"\n */\n model?: OpenAIImageModelId;\n /**\n * The style of the generated images. Must be one of vivid or natural.\n * Vivid causes the model to lean towards generating hyper-real and dramatic images.\n * Natural causes the model to produce more natural, less hyper-real looking images.\n * @default \"vivid\"\n */\n style?: \"natural\" | \"vivid\";\n /**\n * The quality of the image that will be generated. ‘hd’ creates images with finer\n * details and greater consistency across the image.\n * @default \"standard\"\n */\n quality?: \"standard\" | \"hd\";\n /**\n * The number of images to generate.\n * Must be between 1 and 10.\n * For dall-e-3, only `n: 1` is supported.\n * @default 1\n */\n n?: number;\n /**\n * The size of the generated images.\n * Must be one of 256x256, 512x512, or 1024x1024 for DALL·E-2 models.\n * Must be one of 1024x1024, 1792x1024, or 1024x1792 for DALL·E-3 models.\n * @default \"1024x1024\"\n */\n size?: \"256x256\" | \"512x512\" | \"1024x1024\" | \"1792x1024\" | \"1024x1792\";\n /**\n * The format in which the generated images are returned.\n * Must be one of \"url\" or \"b64_json\".\n * @default \"url\"\n */\n dallEResponseFormat?: \"url\" | \"b64_json\";\n /**\n * @deprecated Use dallEResponseFormat instead for the Dall-E response type.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n responseFormat?: any;\n /**\n * A unique identifier representing your end-user, which will help\n * OpenAI to monitor and detect abuse.\n */\n user?: string;\n /**\n * The organization to use\n */\n organization?: string;\n /**\n * The base URL of the OpenAI API.\n */\n baseUrl?: string;\n}\n\n/**\n * A tool for generating images with Open AIs Dall-E 2 or 3 API.\n */\nexport class DallEAPIWrapper extends Tool {\n static lc_name() {\n return \"DallEAPIWrapper\";\n }\n\n name = \"dalle_api_wrapper\";\n\n description =\n \"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.\";\n\n protected client: OpenAIClient;\n\n static readonly toolName = \"dalle_api_wrapper\";\n\n private model = \"dall-e-3\";\n\n private style: \"natural\" | \"vivid\" = \"vivid\";\n\n private quality: \"standard\" | \"hd\" = \"standard\";\n\n private n = 1;\n\n private size:\n | \"256x256\"\n | \"512x512\"\n | \"1024x1024\"\n | \"1792x1024\"\n | \"1024x1792\" = \"1024x1024\";\n\n private dallEResponseFormat: \"url\" | \"b64_json\" = \"url\";\n\n private user?: string;\n\n constructor(fields?: DallEAPIWrapperParams) {\n // Shim for new base tool param name\n if (\n fields?.responseFormat !== undefined &&\n [\"url\", \"b64_json\"].includes(fields.responseFormat)\n ) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n fields.dallEResponseFormat = fields.responseFormat as any;\n fields.responseFormat = \"content\";\n }\n super(fields);\n const openAIApiKey =\n fields?.apiKey ??\n fields?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n\n const organization =\n fields?.organization ?? getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n const clientConfig = {\n apiKey: openAIApiKey,\n organization,\n dangerouslyAllowBrowser: true,\n baseURL: fields?.baseUrl,\n };\n this.client = new OpenAIClient(clientConfig);\n this.model = fields?.model ?? fields?.modelName ?? this.model;\n this.style = fields?.style ?? this.style;\n this.quality = fields?.quality ?? this.quality;\n this.n = fields?.n ?? this.n;\n this.size = fields?.size ?? this.size;\n this.dallEResponseFormat =\n fields?.dallEResponseFormat ?? this.dallEResponseFormat;\n this.user = fields?.user;\n }\n\n /**\n * Processes the API response if multiple images are generated.\n * Returns a list of MessageContentImageUrl objects. If the response\n * format is `url`, then the `image_url` field will contain the URL.\n * If it is `b64_json`, then the `image_url` field will contain an object\n * with a `url` field with the base64 encoded image.\n *\n * @param {OpenAIClient.Images.ImagesResponse[]} response The API response\n * @returns {MessageContentImageUrl[]}\n */\n private processMultipleGeneratedUrls(\n response: OpenAIClient.Images.ImagesResponse[]\n ): MessageContentImageUrl[] {\n if (this.dallEResponseFormat === \"url\") {\n return response.flatMap((res) => {\n const imageUrlContent =\n res.data\n ?.flatMap((item) => {\n if (!item.url) return [];\n return {\n type: \"image_url\" as const,\n image_url: item.url,\n };\n })\n .filter(\n (item) =>\n item !== undefined &&\n item.type === \"image_url\" &&\n typeof item.image_url === \"string\" &&\n item.image_url !== undefined\n ) ?? [];\n return imageUrlContent;\n });\n } else {\n return response.flatMap((res) => {\n const b64Content =\n res.data\n ?.flatMap((item) => {\n if (!item.b64_json) return [];\n return {\n type: \"image_url\" as const,\n image_url: {\n url: item.b64_json,\n },\n };\n })\n .filter(\n (item) =>\n item !== undefined &&\n item.type === \"image_url\" &&\n typeof item.image_url === \"object\" &&\n \"url\" in item.image_url &&\n typeof item.image_url.url === \"string\" &&\n item.image_url.url !== undefined\n ) ?? [];\n return b64Content;\n });\n }\n }\n\n /** @ignore */\n async _call(input: string): Promise<string | MessageContentComplex[]> {\n const generateImageFields = {\n model: this.model,\n prompt: input,\n n: 1,\n size: this.size,\n response_format: this.dallEResponseFormat,\n style: this.style,\n quality: this.quality,\n user: this.user,\n };\n\n if (this.n > 1) {\n const results = await Promise.all(\n Array.from({ length: this.n }).map(() =>\n this.client.images.generate(generateImageFields)\n )\n );\n\n return this.processMultipleGeneratedUrls(results);\n }\n\n const response = await this.client.images.generate(generateImageFields);\n\n let data = \"\";\n if (this.dallEResponseFormat === \"url\") {\n [data] =\n response.data\n ?.map((item) => item.url)\n .filter((url): url is string => url !== \"undefined\") ?? [];\n } else {\n [data] =\n response.data\n ?.map((item) => item.b64_json)\n .filter((b64_json): b64_json is string => b64_json !== \"undefined\") ??\n [];\n }\n return data;\n }\n}\n"],"mappings":";;;;;;;AAkGA,IAAa,kBAAb,cAAqCA,sBAAAA,KAAK;CACxC,OAAO,UAAU;EACf,OAAO;CACT;CAEA,OAAO;CAEP,cACE;CAEF;CAEA,OAAgB,WAAW;CAE3B,QAAgB;CAEhB,QAAqC;CAErC,UAAqC;CAErC,IAAY;CAEZ,OAKkB;CAElB,sBAAkD;CAElD;CAEA,YAAY,QAAgC;EAE1C,IACE,QAAQ,mBAAmB,KAAA,KAC3B,CAAC,OAAO,UAAU,CAAC,CAAC,SAAS,OAAO,cAAc,GAClD;GAEA,OAAO,sBAAsB,OAAO;GACpC,OAAO,iBAAiB;EAC1B;EACA,MAAM,MAAM;EASZ,MAAM,eAAe;GACnB,QARA,QAAQ,UACR,QAAQ,iBAAA,GACRC,0BAAAA,uBAAAA,CAAuB,gBAAgB;GAOvC,cAJA,QAAQ,iBAAA,GAAgBA,0BAAAA,uBAAAA,CAAuB,qBAAqB;GAKpE,yBAAyB;GACzB,SAAS,QAAQ;EACnB;EACA,KAAK,SAAS,IAAIC,OAAAA,OAAa,YAAY;EAC3C,KAAK,QAAQ,QAAQ,SAAS,QAAQ,aAAa,KAAK;EACxD,KAAK,QAAQ,QAAQ,SAAS,KAAK;EACnC,KAAK,UAAU,QAAQ,WAAW,KAAK;EACvC,KAAK,IAAI,QAAQ,KAAK,KAAK;EAC3B,KAAK,OAAO,QAAQ,QAAQ,KAAK;EACjC,KAAK,sBACH,QAAQ,uBAAuB,KAAK;EACtC,KAAK,OAAO,QAAQ;CACtB;;;;;;;;;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,QACC,SAAS,MACL,KAAK,SAAS,KAAK,GAAG,CAAC,CACxB,QAAQ,QAAuB,QAAQ,WAAW,KAAK,CAAC;OAE7D,CAAC,QACC,SAAS,MACL,KAAK,SAAS,KAAK,QAAQ,CAAC,CAC7B,QAAQ,aAAiC,aAAa,WAAW,KACpE,CAAC;EAEL,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localShell.cjs","names":["z"],"sources":["../../src/tools/localShell.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 action type from OpenAI SDK for convenience.\n * The action contains command details like argv tokens, environment variables,\n * working directory, timeout, and user.\n */\nexport type LocalShellAction =\n OpenAIClient.Responses.ResponseOutputItem.LocalShellCall.Action;\n\n// Zod schema for local shell exec action\nexport const LocalShellExecActionSchema = z.object({\n type: z.literal(\"exec\"),\n command: z.array(z.string()),\n env: z.record(z.string(), z.string()).optional(),\n working_directory: z.string().optional(),\n timeout_ms: z.number().optional(),\n user: z.string().optional(),\n});\n\n// Schema for all local shell actions (currently only exec)\nexport const LocalShellActionSchema = z.union([LocalShellExecActionSchema]);\n\n/**\n * Options for the Local Shell tool.\n */\nexport interface LocalShellOptions {\n /**\n * Optional execute function that handles shell command execution.\n * This function receives the action input and should return the command output\n * (stdout + stderr combined).\n *\n * If not provided, you'll need to handle action execution manually by\n * checking `local_shell_call` outputs in the response.\n *\n * @example\n * ```typescript\n * execute: async (action) => {\n * const result = await exec(action.command.join(' '), {\n * cwd: action.working_directory,\n * env: { ...process.env, ...action.env },\n * timeout: action.timeout_ms,\n * });\n * return result.stdout + result.stderr;\n * }\n * ```\n */\n execute: (action: LocalShellAction) => string | Promise<string>;\n}\n\n/**\n * OpenAI Local Shell tool type for the Responses API.\n */\nexport type LocalShellTool = OpenAIClient.Responses.Tool.LocalShell;\n\nconst TOOL_NAME = \"local_shell\";\n\n/**\n * Creates a Local Shell tool that allows models to run shell commands locally\n * on a machine you provide. Commands are executed inside your own runtime—\n * the API only returns the instructions, but does not execute them on OpenAI infrastructure.\n *\n * **Important**: The local shell tool is designed to work with\n * [Codex CLI](https://github.com/openai/codex) and the `codex-mini-latest` model.\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends shell commands (`local_shell_call` with `exec` action)\n * 2. Your code executes the command locally\n * 3. You return the output back to the model\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Running arbitrary shell commands can be dangerous.\n * Always sandbox execution or add strict allow/deny-lists before forwarding\n * a command to the system shell.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-local-shell | OpenAI Local Shell Documentation}\n *\n * @param options - Optional configuration for the Local Shell tool\n * @returns A Local Shell tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { exec } from \"child_process\";\n * import { promisify } from \"util\";\n *\n * const execAsync = promisify(exec);\n * const model = new ChatOpenAI({ model: \"codex-mini-latest\" });\n *\n * // With execute callback for automatic command handling\n * const shell = tools.localShell({\n * execute: async (action) => {\n * const { command, env, working_directory, timeout_ms } = action;\n * const result = await execAsync(command.join(' '), {\n * cwd: working_directory ?? process.cwd(),\n * env: { ...process.env, ...env },\n * timeout: timeout_ms ?? undefined,\n * });\n * return result.stdout + result.stderr;\n * },\n * });\n *\n * const llmWithShell = model.bindTools([shell]);\n * const response = await llmWithShell.invoke(\n * \"List files in the current directory\"\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Without execute callback (manual handling)\n * const shell = tools.localShell();\n *\n * const response = await model.invoke(\"List files\", {\n * tools: [shell],\n * });\n *\n * // Access the shell call from the response\n * const shellCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"local_shell_call\"\n * );\n * if (shellCall) {\n * console.log(\"Command to execute:\", shellCall.action.command);\n * // Execute the command manually, then send back the output\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Full shell loop example\n * async function shellLoop(model, task) {\n * let response = await model.invoke(task, {\n * tools: [tools.localShell()],\n * });\n *\n * while (true) {\n * const shellCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"local_shell_call\"\n * );\n *\n * if (!shellCall) break;\n *\n * // Execute command (with proper sandboxing!)\n * const output = await executeCommand(shellCall.action);\n *\n * // Send output back to model\n * response = await model.invoke([\n * response,\n * {\n * type: \"local_shell_call_output\",\n * id: shellCall.call_id,\n * output: output,\n * },\n * ], {\n * tools: [tools.localShell()],\n * });\n * }\n *\n * return response;\n * }\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Designed for use with `codex-mini-latest` model\n * - Commands are provided as argv tokens in `action.command`\n * - Action includes: `command`, `env`, `working_directory`, `timeout_ms`, `user`\n * - Always sandbox or validate commands before execution\n * - The `timeout_ms` from the model is only a hint—enforce your own limits\n */\nexport function localShell(options: LocalShellOptions) {\n const shellTool = tool(options.execute, {\n name: TOOL_NAME,\n description:\n \"Execute shell commands locally on the machine. Commands are provided as argv tokens.\",\n schema: LocalShellActionSchema,\n });\n\n shellTool.extras = {\n ...(shellTool.extras ?? {}),\n providerToolDefinition: {\n type: \"local_shell\",\n } satisfies LocalShellTool,\n };\n\n return shellTool as DynamicStructuredTool<\n typeof LocalShellActionSchema,\n LocalShellAction,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAaA,MAAa,6BAA6BA,OAAAA,EAAE,OAAO;CACjD,MAAMA,OAAAA,EAAE,QAAQ,MAAM;CACtB,SAASA,OAAAA,EAAE,MAAMA,OAAAA,EAAE,OAAO,CAAC;CAC3B,KAAKA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CAC/C,mBAAmBA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CACvC,YAAYA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;AAC5B,CAAC;AAGD,MAAa,yBAAyBA,OAAAA,EAAE,MAAM,CAAC,0BAA0B,CAAC;AAkC1E,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoHlB,SAAgB,WAAW,SAA4B;CACrD,MAAM,aAAA,
|
|
1
|
+
{"version":3,"file":"localShell.cjs","names":["z","tool"],"sources":["../../src/tools/localShell.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 action type from OpenAI SDK for convenience.\n * The action contains command details like argv tokens, environment variables,\n * working directory, timeout, and user.\n */\nexport type LocalShellAction =\n OpenAIClient.Responses.ResponseOutputItem.LocalShellCall.Action;\n\n// Zod schema for local shell exec action\nexport const LocalShellExecActionSchema = z.object({\n type: z.literal(\"exec\"),\n command: z.array(z.string()),\n env: z.record(z.string(), z.string()).optional(),\n working_directory: z.string().optional(),\n timeout_ms: z.number().optional(),\n user: z.string().optional(),\n});\n\n// Schema for all local shell actions (currently only exec)\nexport const LocalShellActionSchema = z.union([LocalShellExecActionSchema]);\n\n/**\n * Options for the Local Shell tool.\n */\nexport interface LocalShellOptions {\n /**\n * Optional execute function that handles shell command execution.\n * This function receives the action input and should return the command output\n * (stdout + stderr combined).\n *\n * If not provided, you'll need to handle action execution manually by\n * checking `local_shell_call` outputs in the response.\n *\n * @example\n * ```typescript\n * execute: async (action) => {\n * const result = await exec(action.command.join(' '), {\n * cwd: action.working_directory,\n * env: { ...process.env, ...action.env },\n * timeout: action.timeout_ms,\n * });\n * return result.stdout + result.stderr;\n * }\n * ```\n */\n execute: (action: LocalShellAction) => string | Promise<string>;\n}\n\n/**\n * OpenAI Local Shell tool type for the Responses API.\n */\nexport type LocalShellTool = OpenAIClient.Responses.Tool.LocalShell;\n\nconst TOOL_NAME = \"local_shell\";\n\n/**\n * Creates a Local Shell tool that allows models to run shell commands locally\n * on a machine you provide. Commands are executed inside your own runtime—\n * the API only returns the instructions, but does not execute them on OpenAI infrastructure.\n *\n * **Important**: The local shell tool is designed to work with\n * [Codex CLI](https://github.com/openai/codex) and the `codex-mini-latest` model.\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends shell commands (`local_shell_call` with `exec` action)\n * 2. Your code executes the command locally\n * 3. You return the output back to the model\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Running arbitrary shell commands can be dangerous.\n * Always sandbox execution or add strict allow/deny-lists before forwarding\n * a command to the system shell.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-local-shell | OpenAI Local Shell Documentation}\n *\n * @param options - Optional configuration for the Local Shell tool\n * @returns A Local Shell tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { exec } from \"child_process\";\n * import { promisify } from \"util\";\n *\n * const execAsync = promisify(exec);\n * const model = new ChatOpenAI({ model: \"codex-mini-latest\" });\n *\n * // With execute callback for automatic command handling\n * const shell = tools.localShell({\n * execute: async (action) => {\n * const { command, env, working_directory, timeout_ms } = action;\n * const result = await execAsync(command.join(' '), {\n * cwd: working_directory ?? process.cwd(),\n * env: { ...process.env, ...env },\n * timeout: timeout_ms ?? undefined,\n * });\n * return result.stdout + result.stderr;\n * },\n * });\n *\n * const llmWithShell = model.bindTools([shell]);\n * const response = await llmWithShell.invoke(\n * \"List files in the current directory\"\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Without execute callback (manual handling)\n * const shell = tools.localShell();\n *\n * const response = await model.invoke(\"List files\", {\n * tools: [shell],\n * });\n *\n * // Access the shell call from the response\n * const shellCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"local_shell_call\"\n * );\n * if (shellCall) {\n * console.log(\"Command to execute:\", shellCall.action.command);\n * // Execute the command manually, then send back the output\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Full shell loop example\n * async function shellLoop(model, task) {\n * let response = await model.invoke(task, {\n * tools: [tools.localShell()],\n * });\n *\n * while (true) {\n * const shellCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"local_shell_call\"\n * );\n *\n * if (!shellCall) break;\n *\n * // Execute command (with proper sandboxing!)\n * const output = await executeCommand(shellCall.action);\n *\n * // Send output back to model\n * response = await model.invoke([\n * response,\n * {\n * type: \"local_shell_call_output\",\n * id: shellCall.call_id,\n * output: output,\n * },\n * ], {\n * tools: [tools.localShell()],\n * });\n * }\n *\n * return response;\n * }\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Designed for use with `codex-mini-latest` model\n * - Commands are provided as argv tokens in `action.command`\n * - Action includes: `command`, `env`, `working_directory`, `timeout_ms`, `user`\n * - Always sandbox or validate commands before execution\n * - The `timeout_ms` from the model is only a hint—enforce your own limits\n */\nexport function localShell(options: LocalShellOptions) {\n const shellTool = tool(options.execute, {\n name: TOOL_NAME,\n description:\n \"Execute shell commands locally on the machine. Commands are provided as argv tokens.\",\n schema: LocalShellActionSchema,\n });\n\n shellTool.extras = {\n ...(shellTool.extras ?? {}),\n providerToolDefinition: {\n type: \"local_shell\",\n } satisfies LocalShellTool,\n };\n\n return shellTool as DynamicStructuredTool<\n typeof LocalShellActionSchema,\n LocalShellAction,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAaA,MAAa,6BAA6BA,OAAAA,EAAE,OAAO;CACjD,MAAMA,OAAAA,EAAE,QAAQ,MAAM;CACtB,SAASA,OAAAA,EAAE,MAAMA,OAAAA,EAAE,OAAO,CAAC;CAC3B,KAAKA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CAC/C,mBAAmBA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CACvC,YAAYA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;AAC5B,CAAC;AAGD,MAAa,yBAAyBA,OAAAA,EAAE,MAAM,CAAC,0BAA0B,CAAC;AAkC1E,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoHlB,SAAgB,WAAW,SAA4B;CACrD,MAAM,aAAA,GAAYC,sBAAAA,KAAAA,CAAK,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"}
|
package/dist/tools/shell.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell.cjs","names":["z"],"sources":["../../src/tools/shell.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 action type from OpenAI SDK for convenience.\n * The action contains command details like commands array, timeout, and max output length.\n */\nexport type ShellAction =\n OpenAIClient.Responses.ResponseFunctionShellToolCall.Action;\n\n// Zod schema for shell action\nexport const ShellActionSchema = z.object({\n commands: z.array(z.string()).describe(\"Array of shell commands to execute\"),\n timeout_ms: z\n .number()\n .optional()\n .describe(\"Optional timeout in milliseconds for the commands\"),\n max_output_length: z\n .number()\n .optional()\n .describe(\n \"Optional maximum number of characters to return from each command\"\n ),\n});\n\n/**\n * Result of a single shell command execution.\n * Contains stdout, stderr, and the outcome (exit code or timeout).\n */\nexport type ShellCommandOutput =\n OpenAIClient.Responses.ResponseFunctionShellCallOutputContent;\n\n/**\n * Outcome type for shell command execution - either exit with code or timeout.\n */\nexport type ShellCallOutcome = ShellCommandOutput[\"outcome\"];\n\n/**\n * Result of executing shell commands.\n * Contains an array of outputs (one per command) and the max_output_length parameter.\n */\nexport interface ShellResult {\n /**\n * Array of command outputs. Each entry corresponds to a command from the action.\n * The order should match the order of commands in the action.\n */\n output: ShellCommandOutput[];\n /**\n * The max_output_length from the action, which must be passed back to the API.\n * If not provided in the action, can be omitted.\n */\n maxOutputLength?: number | null;\n}\n\n/**\n * Options for the Shell tool.\n */\nexport interface ShellOptions {\n /**\n * Execute function that handles shell command execution.\n * This function receives the action input containing the commands and limits,\n * and should return a ShellResult with stdout, stderr, and outcome for each command.\n *\n * @example\n * ```typescript\n * execute: async (action) => {\n * const outputs = await Promise.all(\n * action.commands.map(async (cmd) => {\n * try {\n * const { stdout, stderr } = await exec(cmd, {\n * timeout: action.timeout_ms ?? undefined,\n * });\n * return {\n * stdout,\n * stderr,\n * outcome: { type: \"exit\" as const, exit_code: 0 },\n * };\n * } catch (error) {\n * const timedOut = error.killed && error.signal === \"SIGTERM\";\n * return {\n * stdout: error.stdout ?? \"\",\n * stderr: error.stderr ?? String(error),\n * outcome: timedOut\n * ? { type: \"timeout\" as const }\n * : { type: \"exit\" as const, exit_code: error.code ?? 1 },\n * };\n * }\n * })\n * );\n * return {\n * output: outputs,\n * maxOutputLength: action.max_output_length,\n * };\n * }\n * ```\n */\n execute: (action: ShellAction) => ShellResult | Promise<ShellResult>;\n}\n\n/**\n * OpenAI Shell tool type for the Responses API.\n */\nexport type ShellTool = OpenAIClient.Responses.FunctionShellTool;\n\nconst TOOL_NAME = \"shell\";\n\n/**\n * Creates a Shell tool that allows models to run shell commands through your integration.\n *\n * The shell tool allows the model to interact with your local computer through a controlled\n * command-line interface. The model proposes shell commands; your integration executes them\n * and returns the outputs. This creates a simple plan-execute loop that lets models inspect\n * the system, run utilities, and gather data until they can finish the task.\n *\n * **Important**: The shell tool is available through the Responses API for use with `GPT-5.1`.\n * It is not available on other models, or via the Chat Completions API.\n *\n * **When to use**:\n * - **Automating filesystem or process diagnostics** – For example, \"find the largest PDF\n * under ~/Documents\" or \"show running gunicorn processes.\"\n * - **Extending the model's capabilities** – Using built-in UNIX utilities, python runtime\n * and other CLIs in your environment.\n * - **Running multi-step build and test flows** – Chaining commands like `pip install` and `pytest`.\n * - **Complex agentic coding workflows** – Using other tools like `apply_patch` to complete\n * workflows that involve complex file operations.\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends shell commands (`shell_call` with `commands` array)\n * 2. Your code executes the commands (can be concurrent)\n * 3. You return stdout, stderr, and outcome for each command\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Running arbitrary shell commands can be dangerous.\n * Always sandbox execution or add strict allow/deny-lists before forwarding\n * a command to the system shell.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-shell | OpenAI Shell Documentation}\n * @see {@link https://github.com/openai/codex | Codex CLI} for reference implementation.\n *\n * @param options - Configuration for the Shell tool\n * @returns A Shell tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { exec } from \"child_process/promises\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-5.1\" });\n *\n * // With execute callback for automatic command handling\n * const shellTool = tools.shell({\n * execute: async (action) => {\n * const outputs = await Promise.all(\n * action.commands.map(async (cmd) => {\n * try {\n * const { stdout, stderr } = await exec(cmd, {\n * timeout: action.timeout_ms ?? undefined,\n * });\n * return {\n * stdout,\n * stderr,\n * outcome: { type: \"exit\" as const, exit_code: 0 },\n * };\n * } catch (error) {\n * const timedOut = error.killed && error.signal === \"SIGTERM\";\n * return {\n * stdout: error.stdout ?? \"\",\n * stderr: error.stderr ?? String(error),\n * outcome: timedOut\n * ? { type: \"timeout\" as const }\n * : { type: \"exit\" as const, exit_code: error.code ?? 1 },\n * };\n * }\n * })\n * );\n * return {\n * output: outputs,\n * maxOutputLength: action.max_output_length,\n * };\n * },\n * });\n *\n * const llmWithShell = model.bindTools([shellTool]);\n * const response = await llmWithShell.invoke(\n * \"Find the largest PDF file in ~/Documents\"\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Full shell loop example\n * async function shellLoop(model, task) {\n * let response = await model.invoke(task, {\n * tools: [tools.shell({ execute: myExecutor })],\n * });\n *\n * while (true) {\n * const shellCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"shell_call\"\n * );\n *\n * if (!shellCall) break;\n *\n * // Execute commands (with proper sandboxing!)\n * const result = await executeCommands(shellCall.action);\n *\n * // Send output back to model\n * response = await model.invoke([\n * response,\n * {\n * type: \"shell_call_output\",\n * call_id: shellCall.call_id,\n * output: result.output,\n * max_output_length: result.maxOutputLength,\n * },\n * ], {\n * tools: [tools.shell({ execute: myExecutor })],\n * });\n * }\n *\n * return response;\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 * - Commands are provided as an array of strings that can be executed concurrently\n * - Action includes: `commands`, `timeout_ms`, `max_output_length`\n * - Always sandbox or validate commands before execution\n * - The `timeout_ms` from the model is only a hint—enforce your own limits\n * - If `max_output_length` exists in the action, always pass it back in the output\n * - Many CLI tools return non-zero exit codes for warnings; still capture stdout/stderr\n */\nexport function shell(options: ShellOptions) {\n // Wrapper that converts ShellResult to string for LangChain tool compatibility\n const executeWrapper = async (action: ShellAction): Promise<string> => {\n const result = await options.execute(action);\n // Return a JSON string representation for the tool result\n return JSON.stringify({\n output: result.output,\n max_output_length: result.maxOutputLength,\n });\n };\n\n const shellTool = tool(executeWrapper, {\n name: TOOL_NAME,\n description:\n \"Execute shell commands in a managed environment. Commands can be run concurrently.\",\n schema: ShellActionSchema,\n });\n\n shellTool.extras = {\n ...(shellTool.extras ?? {}),\n providerToolDefinition: {\n type: \"shell\",\n } satisfies ShellTool,\n };\n\n return shellTool as DynamicStructuredTool<\n typeof ShellActionSchema,\n ShellAction,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAYA,MAAa,oBAAoBA,OAAAA,EAAE,OAAO;CACxC,UAAUA,OAAAA,EAAE,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,oCAAoC;CAC3E,YAAYA,OAAAA,EACT,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,mDAAmD;CAC/D,mBAAmBA,OAAAA,EAChB,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SACC,mEACF;AACJ,CAAC;AAiFD,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIlB,SAAgB,MAAM,SAAuB;CAE3C,MAAM,iBAAiB,OAAO,WAAyC;EACrE,MAAM,SAAS,MAAM,QAAQ,QAAQ,MAAM;EAE3C,OAAO,KAAK,UAAU;GACpB,QAAQ,OAAO;GACf,mBAAmB,OAAO;EAC5B,CAAC;CACH;CAEA,MAAM,aAAA,GAAA,sBAAA,KAAA,CAAiB,gBAAgB;EACrC,MAAM;EACN,aACE;EACF,QAAQ;CACV,CAAC;CAED,UAAU,SAAS;EACjB,GAAI,UAAU,UAAU,CAAC;EACzB,wBAAwB,EACtB,MAAM,QACR;CACF;CAEA,OAAO;AAMT"}
|
|
1
|
+
{"version":3,"file":"shell.cjs","names":["z","tool"],"sources":["../../src/tools/shell.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 action type from OpenAI SDK for convenience.\n * The action contains command details like commands array, timeout, and max output length.\n */\nexport type ShellAction =\n OpenAIClient.Responses.ResponseFunctionShellToolCall.Action;\n\n// Zod schema for shell action\nexport const ShellActionSchema = z.object({\n commands: z.array(z.string()).describe(\"Array of shell commands to execute\"),\n timeout_ms: z\n .number()\n .optional()\n .describe(\"Optional timeout in milliseconds for the commands\"),\n max_output_length: z\n .number()\n .optional()\n .describe(\n \"Optional maximum number of characters to return from each command\"\n ),\n});\n\n/**\n * Result of a single shell command execution.\n * Contains stdout, stderr, and the outcome (exit code or timeout).\n */\nexport type ShellCommandOutput =\n OpenAIClient.Responses.ResponseFunctionShellCallOutputContent;\n\n/**\n * Outcome type for shell command execution - either exit with code or timeout.\n */\nexport type ShellCallOutcome = ShellCommandOutput[\"outcome\"];\n\n/**\n * Result of executing shell commands.\n * Contains an array of outputs (one per command) and the max_output_length parameter.\n */\nexport interface ShellResult {\n /**\n * Array of command outputs. Each entry corresponds to a command from the action.\n * The order should match the order of commands in the action.\n */\n output: ShellCommandOutput[];\n /**\n * The max_output_length from the action, which must be passed back to the API.\n * If not provided in the action, can be omitted.\n */\n maxOutputLength?: number | null;\n}\n\n/**\n * Options for the Shell tool.\n */\nexport interface ShellOptions {\n /**\n * Execute function that handles shell command execution.\n * This function receives the action input containing the commands and limits,\n * and should return a ShellResult with stdout, stderr, and outcome for each command.\n *\n * @example\n * ```typescript\n * execute: async (action) => {\n * const outputs = await Promise.all(\n * action.commands.map(async (cmd) => {\n * try {\n * const { stdout, stderr } = await exec(cmd, {\n * timeout: action.timeout_ms ?? undefined,\n * });\n * return {\n * stdout,\n * stderr,\n * outcome: { type: \"exit\" as const, exit_code: 0 },\n * };\n * } catch (error) {\n * const timedOut = error.killed && error.signal === \"SIGTERM\";\n * return {\n * stdout: error.stdout ?? \"\",\n * stderr: error.stderr ?? String(error),\n * outcome: timedOut\n * ? { type: \"timeout\" as const }\n * : { type: \"exit\" as const, exit_code: error.code ?? 1 },\n * };\n * }\n * })\n * );\n * return {\n * output: outputs,\n * maxOutputLength: action.max_output_length,\n * };\n * }\n * ```\n */\n execute: (action: ShellAction) => ShellResult | Promise<ShellResult>;\n}\n\n/**\n * OpenAI Shell tool type for the Responses API.\n */\nexport type ShellTool = OpenAIClient.Responses.FunctionShellTool;\n\nconst TOOL_NAME = \"shell\";\n\n/**\n * Creates a Shell tool that allows models to run shell commands through your integration.\n *\n * The shell tool allows the model to interact with your local computer through a controlled\n * command-line interface. The model proposes shell commands; your integration executes them\n * and returns the outputs. This creates a simple plan-execute loop that lets models inspect\n * the system, run utilities, and gather data until they can finish the task.\n *\n * **Important**: The shell tool is available through the Responses API for use with `GPT-5.1`.\n * It is not available on other models, or via the Chat Completions API.\n *\n * **When to use**:\n * - **Automating filesystem or process diagnostics** – For example, \"find the largest PDF\n * under ~/Documents\" or \"show running gunicorn processes.\"\n * - **Extending the model's capabilities** – Using built-in UNIX utilities, python runtime\n * and other CLIs in your environment.\n * - **Running multi-step build and test flows** – Chaining commands like `pip install` and `pytest`.\n * - **Complex agentic coding workflows** – Using other tools like `apply_patch` to complete\n * workflows that involve complex file operations.\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends shell commands (`shell_call` with `commands` array)\n * 2. Your code executes the commands (can be concurrent)\n * 3. You return stdout, stderr, and outcome for each command\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Running arbitrary shell commands can be dangerous.\n * Always sandbox execution or add strict allow/deny-lists before forwarding\n * a command to the system shell.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-shell | OpenAI Shell Documentation}\n * @see {@link https://github.com/openai/codex | Codex CLI} for reference implementation.\n *\n * @param options - Configuration for the Shell tool\n * @returns A Shell tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { exec } from \"child_process/promises\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-5.1\" });\n *\n * // With execute callback for automatic command handling\n * const shellTool = tools.shell({\n * execute: async (action) => {\n * const outputs = await Promise.all(\n * action.commands.map(async (cmd) => {\n * try {\n * const { stdout, stderr } = await exec(cmd, {\n * timeout: action.timeout_ms ?? undefined,\n * });\n * return {\n * stdout,\n * stderr,\n * outcome: { type: \"exit\" as const, exit_code: 0 },\n * };\n * } catch (error) {\n * const timedOut = error.killed && error.signal === \"SIGTERM\";\n * return {\n * stdout: error.stdout ?? \"\",\n * stderr: error.stderr ?? String(error),\n * outcome: timedOut\n * ? { type: \"timeout\" as const }\n * : { type: \"exit\" as const, exit_code: error.code ?? 1 },\n * };\n * }\n * })\n * );\n * return {\n * output: outputs,\n * maxOutputLength: action.max_output_length,\n * };\n * },\n * });\n *\n * const llmWithShell = model.bindTools([shellTool]);\n * const response = await llmWithShell.invoke(\n * \"Find the largest PDF file in ~/Documents\"\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Full shell loop example\n * async function shellLoop(model, task) {\n * let response = await model.invoke(task, {\n * tools: [tools.shell({ execute: myExecutor })],\n * });\n *\n * while (true) {\n * const shellCall = response.additional_kwargs.tool_outputs?.find(\n * (output) => output.type === \"shell_call\"\n * );\n *\n * if (!shellCall) break;\n *\n * // Execute commands (with proper sandboxing!)\n * const result = await executeCommands(shellCall.action);\n *\n * // Send output back to model\n * response = await model.invoke([\n * response,\n * {\n * type: \"shell_call_output\",\n * call_id: shellCall.call_id,\n * output: result.output,\n * max_output_length: result.maxOutputLength,\n * },\n * ], {\n * tools: [tools.shell({ execute: myExecutor })],\n * });\n * }\n *\n * return response;\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 * - Commands are provided as an array of strings that can be executed concurrently\n * - Action includes: `commands`, `timeout_ms`, `max_output_length`\n * - Always sandbox or validate commands before execution\n * - The `timeout_ms` from the model is only a hint—enforce your own limits\n * - If `max_output_length` exists in the action, always pass it back in the output\n * - Many CLI tools return non-zero exit codes for warnings; still capture stdout/stderr\n */\nexport function shell(options: ShellOptions) {\n // Wrapper that converts ShellResult to string for LangChain tool compatibility\n const executeWrapper = async (action: ShellAction): Promise<string> => {\n const result = await options.execute(action);\n // Return a JSON string representation for the tool result\n return JSON.stringify({\n output: result.output,\n max_output_length: result.maxOutputLength,\n });\n };\n\n const shellTool = tool(executeWrapper, {\n name: TOOL_NAME,\n description:\n \"Execute shell commands in a managed environment. Commands can be run concurrently.\",\n schema: ShellActionSchema,\n });\n\n shellTool.extras = {\n ...(shellTool.extras ?? {}),\n providerToolDefinition: {\n type: \"shell\",\n } satisfies ShellTool,\n };\n\n return shellTool as DynamicStructuredTool<\n typeof ShellActionSchema,\n ShellAction,\n unknown,\n string\n >;\n}\n"],"mappings":";;;AAYA,MAAa,oBAAoBA,OAAAA,EAAE,OAAO;CACxC,UAAUA,OAAAA,EAAE,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,oCAAoC;CAC3E,YAAYA,OAAAA,EACT,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,mDAAmD;CAC/D,mBAAmBA,OAAAA,EAChB,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SACC,mEACF;AACJ,CAAC;AAiFD,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIlB,SAAgB,MAAM,SAAuB;CAE3C,MAAM,iBAAiB,OAAO,WAAyC;EACrE,MAAM,SAAS,MAAM,QAAQ,QAAQ,MAAM;EAE3C,OAAO,KAAK,UAAU;GACpB,QAAQ,OAAO;GACf,mBAAmB,OAAO;EAC5B,CAAC;CACH;CAEA,MAAM,aAAA,GAAYC,sBAAAA,KAAAA,CAAK,gBAAgB;EACrC,MAAM;EACN,aACE;EACF,QAAQ;CACV,CAAC;CAED,UAAU,SAAS;EACjB,GAAI,UAAU,UAAU,CAAC;EACzB,wBAAwB,EACtB,MAAM,QACR;CACF;CAEA,OAAO;AAMT"}
|
package/dist/utils/azure.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"azure.cjs","names":["iife"],"sources":["../../src/utils/azure.ts"],"sourcesContent":["import { getEnv } from \"@langchain/core/utils/env\";\nimport { iife } from \"./misc.js\";\n\nexport interface OpenAIEndpointConfig {\n azureOpenAIApiDeploymentName?: string;\n azureOpenAIApiInstanceName?: string;\n azureOpenAIApiKey?: string;\n azureADTokenProvider?: () => Promise<string>;\n azureOpenAIBasePath?: string;\n baseURL?: string | null;\n azureOpenAIEndpoint?: string;\n}\n\n/**\n * This function generates an endpoint URL for (Azure) OpenAI\n * based on the configuration parameters provided.\n *\n * @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint.\n *\n * @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI.\n * @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI, e.g. `example-resource`.\n * @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI.\n * @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI, e.g. `https://example-resource.azure.openai.com/openai/deployments/`.\n * @property {string} config.baseURL - Some other custom base path URL.\n * @property {string} config.azureOpenAIEndpoint - The endpoint for the Azure OpenAI instance, e.g. `https://example-resource.azure.openai.com/`.\n *\n * The function operates as follows:\n * - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`).\n * - If both `azureOpenAIEndpoint` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`).\n * - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters.\n * - If none of the above conditions are met, return any custom `baseURL`.\n * - The function returns the generated URL as a string, or undefined if no custom paths are specified.\n *\n * @throws Will throw an error if the necessary parameters for generating the URL are missing.\n *\n * @returns {string | undefined} The generated (Azure) OpenAI endpoint URL.\n */\nexport function getEndpoint(config: OpenAIEndpointConfig) {\n const {\n azureOpenAIApiDeploymentName,\n azureOpenAIApiInstanceName,\n azureOpenAIApiKey,\n azureOpenAIBasePath,\n baseURL,\n azureADTokenProvider,\n azureOpenAIEndpoint,\n } = config;\n\n if (\n (azureOpenAIApiKey || azureADTokenProvider) &&\n azureOpenAIBasePath &&\n azureOpenAIApiDeploymentName\n ) {\n return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`;\n }\n if (\n (azureOpenAIApiKey || azureADTokenProvider) &&\n azureOpenAIEndpoint &&\n azureOpenAIApiDeploymentName\n ) {\n return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`;\n }\n\n if (azureOpenAIApiKey || azureADTokenProvider) {\n if (!azureOpenAIApiInstanceName) {\n throw new Error(\n \"azureOpenAIApiInstanceName is required when using azureOpenAIApiKey\"\n );\n }\n if (!azureOpenAIApiDeploymentName) {\n throw new Error(\n \"azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey\"\n );\n }\n return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`;\n }\n\n return baseURL;\n}\n\ntype HeaderValue = string | undefined | null;\nexport type HeadersLike =\n | Headers\n | readonly HeaderValue[][]\n | Record<string, HeaderValue | readonly HeaderValue[]>\n | undefined\n | null\n // NullableHeaders\n | { values: Headers; [key: string]: unknown };\n\nexport function isHeaders(headers: unknown): headers is Headers {\n return (\n typeof Headers !== \"undefined\" &&\n headers !== null &&\n typeof headers === \"object\" &&\n Object.prototype.toString.call(headers) === \"[object Headers]\"\n );\n}\n\n/**\n * Normalizes various header formats into a consistent Record format.\n *\n * This function accepts headers in multiple formats and converts them to a\n * Record<string, HeaderValue | readonly HeaderValue[]> for consistent handling.\n *\n * @param headers - The headers to normalize. Can be:\n * - A Headers instance\n * - An array of [key, value] pairs\n * - A plain object with string keys\n * - A NullableHeaders-like object with a 'values' property containing Headers\n * - null or undefined\n * @returns A normalized Record containing the header key-value pairs\n *\n * @example\n * ```ts\n * // With Headers instance\n * const headers1 = new Headers([['content-type', 'application/json']]);\n * const normalized1 = normalizeHeaders(headers1);\n *\n * // With plain object\n * const headers2 = { 'content-type': 'application/json' };\n * const normalized2 = normalizeHeaders(headers2);\n *\n * // With array of pairs\n * const headers3 = [['content-type', 'application/json']];\n * const normalized3 = normalizeHeaders(headers3);\n * ```\n */\nexport function normalizeHeaders(\n headers: HeadersLike\n): Record<string, HeaderValue | readonly HeaderValue[]> {\n const output = iife(() => {\n // If headers is a Headers instance\n if (isHeaders(headers)) {\n return headers;\n }\n // If headers is an array of [key, value] pairs\n else if (Array.isArray(headers)) {\n return new Headers(headers);\n }\n // If headers is a NullableHeaders-like object (has 'values' property that is a Headers)\n else if (\n typeof headers === \"object\" &&\n headers !== null &&\n \"values\" in headers &&\n isHeaders(headers.values)\n ) {\n return headers.values;\n }\n // If headers is a plain object\n else if (typeof headers === \"object\" && headers !== null) {\n const entries: [string, string][] = Object.entries(headers)\n .filter(([, v]) => typeof v === \"string\")\n .map(([k, v]) => [k, v as string]);\n return new Headers(entries);\n }\n return new Headers();\n });\n\n return Object.fromEntries(output.entries());\n}\n\nexport function getFormattedEnv() {\n let env = getEnv();\n if (env === \"node\" || env === \"deno\") {\n env = `(${env}/${process.version}; ${process.platform}; ${process.arch})`;\n }\n return env;\n}\n\n// Note: ideally version would be imported from package.json, but there's\n// currently no good way to do that for all supported environments (Node, Deno, Browser).\nexport function getHeadersWithUserAgent(\n headers: HeadersLike,\n isAzure = false,\n version = \"1.0.0\"\n): Record<string, string> {\n const normalizedHeaders = normalizeHeaders(headers);\n const env = getFormattedEnv();\n const library = `langchainjs${isAzure ? \"-azure\" : \"\"}-openai`;\n return {\n ...normalizedHeaders,\n \"User-Agent\": normalizedHeaders[\"User-Agent\"]\n ? `${library}/${version} (${env})${normalizedHeaders[\"User-Agent\"]}`\n : `${library}/${version} (${env})`,\n };\n}\n"],"mappings":";;;;;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ure.cjs","names":["iife","getEnv"],"sources":["../../src/utils/azure.ts"],"sourcesContent":["import { getEnv } from \"@langchain/core/utils/env\";\nimport { iife } from \"./misc.js\";\n\nexport interface OpenAIEndpointConfig {\n azureOpenAIApiDeploymentName?: string;\n azureOpenAIApiInstanceName?: string;\n azureOpenAIApiKey?: string;\n azureADTokenProvider?: () => Promise<string>;\n azureOpenAIBasePath?: string;\n baseURL?: string | null;\n azureOpenAIEndpoint?: string;\n}\n\n/**\n * This function generates an endpoint URL for (Azure) OpenAI\n * based on the configuration parameters provided.\n *\n * @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint.\n *\n * @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI.\n * @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI, e.g. `example-resource`.\n * @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI.\n * @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI, e.g. `https://example-resource.azure.openai.com/openai/deployments/`.\n * @property {string} config.baseURL - Some other custom base path URL.\n * @property {string} config.azureOpenAIEndpoint - The endpoint for the Azure OpenAI instance, e.g. `https://example-resource.azure.openai.com/`.\n *\n * The function operates as follows:\n * - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`).\n * - If both `azureOpenAIEndpoint` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`).\n * - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters.\n * - If none of the above conditions are met, return any custom `baseURL`.\n * - The function returns the generated URL as a string, or undefined if no custom paths are specified.\n *\n * @throws Will throw an error if the necessary parameters for generating the URL are missing.\n *\n * @returns {string | undefined} The generated (Azure) OpenAI endpoint URL.\n */\nexport function getEndpoint(config: OpenAIEndpointConfig) {\n const {\n azureOpenAIApiDeploymentName,\n azureOpenAIApiInstanceName,\n azureOpenAIApiKey,\n azureOpenAIBasePath,\n baseURL,\n azureADTokenProvider,\n azureOpenAIEndpoint,\n } = config;\n\n if (\n (azureOpenAIApiKey || azureADTokenProvider) &&\n azureOpenAIBasePath &&\n azureOpenAIApiDeploymentName\n ) {\n return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`;\n }\n if (\n (azureOpenAIApiKey || azureADTokenProvider) &&\n azureOpenAIEndpoint &&\n azureOpenAIApiDeploymentName\n ) {\n return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`;\n }\n\n if (azureOpenAIApiKey || azureADTokenProvider) {\n if (!azureOpenAIApiInstanceName) {\n throw new Error(\n \"azureOpenAIApiInstanceName is required when using azureOpenAIApiKey\"\n );\n }\n if (!azureOpenAIApiDeploymentName) {\n throw new Error(\n \"azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey\"\n );\n }\n return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`;\n }\n\n return baseURL;\n}\n\ntype HeaderValue = string | undefined | null;\nexport type HeadersLike =\n | Headers\n | readonly HeaderValue[][]\n | Record<string, HeaderValue | readonly HeaderValue[]>\n | undefined\n | null\n // NullableHeaders\n | { values: Headers; [key: string]: unknown };\n\nexport function isHeaders(headers: unknown): headers is Headers {\n return (\n typeof Headers !== \"undefined\" &&\n headers !== null &&\n typeof headers === \"object\" &&\n Object.prototype.toString.call(headers) === \"[object Headers]\"\n );\n}\n\n/**\n * Normalizes various header formats into a consistent Record format.\n *\n * This function accepts headers in multiple formats and converts them to a\n * Record<string, HeaderValue | readonly HeaderValue[]> for consistent handling.\n *\n * @param headers - The headers to normalize. Can be:\n * - A Headers instance\n * - An array of [key, value] pairs\n * - A plain object with string keys\n * - A NullableHeaders-like object with a 'values' property containing Headers\n * - null or undefined\n * @returns A normalized Record containing the header key-value pairs\n *\n * @example\n * ```ts\n * // With Headers instance\n * const headers1 = new Headers([['content-type', 'application/json']]);\n * const normalized1 = normalizeHeaders(headers1);\n *\n * // With plain object\n * const headers2 = { 'content-type': 'application/json' };\n * const normalized2 = normalizeHeaders(headers2);\n *\n * // With array of pairs\n * const headers3 = [['content-type', 'application/json']];\n * const normalized3 = normalizeHeaders(headers3);\n * ```\n */\nexport function normalizeHeaders(\n headers: HeadersLike\n): Record<string, HeaderValue | readonly HeaderValue[]> {\n const output = iife(() => {\n // If headers is a Headers instance\n if (isHeaders(headers)) {\n return headers;\n }\n // If headers is an array of [key, value] pairs\n else if (Array.isArray(headers)) {\n return new Headers(headers);\n }\n // If headers is a NullableHeaders-like object (has 'values' property that is a Headers)\n else if (\n typeof headers === \"object\" &&\n headers !== null &&\n \"values\" in headers &&\n isHeaders(headers.values)\n ) {\n return headers.values;\n }\n // If headers is a plain object\n else if (typeof headers === \"object\" && headers !== null) {\n const entries: [string, string][] = Object.entries(headers)\n .filter(([, v]) => typeof v === \"string\")\n .map(([k, v]) => [k, v as string]);\n return new Headers(entries);\n }\n return new Headers();\n });\n\n return Object.fromEntries(output.entries());\n}\n\nexport function getFormattedEnv() {\n let env = getEnv();\n if (env === \"node\" || env === \"deno\") {\n env = `(${env}/${process.version}; ${process.platform}; ${process.arch})`;\n }\n return env;\n}\n\n// Note: ideally version would be imported from package.json, but there's\n// currently no good way to do that for all supported environments (Node, Deno, Browser).\nexport function getHeadersWithUserAgent(\n headers: HeadersLike,\n isAzure = false,\n version = \"1.0.0\"\n): Record<string, string> {\n const normalizedHeaders = normalizeHeaders(headers);\n const env = getFormattedEnv();\n const library = `langchainjs${isAzure ? \"-azure\" : \"\"}-openai`;\n return {\n ...normalizedHeaders,\n \"User-Agent\": normalizedHeaders[\"User-Agent\"]\n ? `${library}/${version} (${env})${normalizedHeaders[\"User-Agent\"]}`\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AChC,IAAI,OAAA,GAAMC,0BAAAA,OAAAA,CAAO;CACjB,IAAI,QAAQ,UAAU,QAAQ,QAC5B,MAAM,IAAI,IAAI,GAAG,QAAQ,QAAQ,IAAI,QAAQ,SAAS,IAAI,QAAQ,KAAK;CAEzE,OAAO;AACT;AAIA,SAAgB,wBACd,SACA,UAAU,OACV,UAAU,SACc;CACxB,MAAM,oBAAoB,iBAAiB,OAAO;CAClD,MAAM,MAAM,gBAAgB;CAC5B,MAAM,UAAU,cAAc,UAAU,WAAW,GAAG;CACtD,OAAO;EACL,GAAG;EACH,cAAc,kBAAkB,gBAC5B,GAAG,QAAQ,GAAG,QAAQ,IAAI,IAAI,GAAG,kBAAkB,kBACnD,GAAG,QAAQ,GAAG,QAAQ,IAAI,IAAI;CACpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["APIConnectionTimeoutError","APIUserAbortError","ContextOverflowError","addLangChainErrorFields"],"sources":["../../src/utils/client.ts"],"sourcesContent":["import { APIConnectionTimeoutError, APIUserAbortError } from \"openai\";\nimport { ContextOverflowError, stampRetryable } from \"@langchain/core/errors\";\nimport { addLangChainErrorFields } from \"./errors.js\";\n\nfunction _isOpenAIContextOverflowError(e: object): boolean {\n const errorStr = String(e);\n if (errorStr.includes(\"context_length_exceeded\")) {\n return true;\n }\n if (\n \"message\" in e &&\n typeof e.message === \"string\" &&\n (e.message.includes(\"Input tokens exceed the configured limit\") ||\n e.message.includes(\"exceeds the context window\") ||\n e.message.includes(\"maximum context length\"))\n ) {\n return true;\n }\n return false;\n}\n\nexport function wrapOpenAIClientError(e: unknown) {\n if (!e || typeof e !== \"object\") {\n return e;\n }\n\n let error;\n if (\n e.constructor.name === APIConnectionTimeoutError.name &&\n \"message\" in e &&\n typeof e.message === \"string\"\n ) {\n error = new Error(e.message);\n error.name = \"TimeoutError\";\n // This branch discards the original status, so AsyncCaller can't classify it.\n stampRetryable(error, true);\n } else if (\n e.constructor.name === APIUserAbortError.name &&\n \"message\" in e &&\n typeof e.message === \"string\"\n ) {\n error = new Error(e.message);\n error.name = \"AbortError\";\n stampRetryable(error, false);\n } else if (_isOpenAIContextOverflowError(e)) {\n // ContextOverflowError marks itself non-retryable at construction.\n error = ContextOverflowError.fromError(e as Error);\n } else if (\n \"status\" in e &&\n e.status === 400 &&\n \"message\" in e &&\n typeof e.message === \"string\" &&\n e.message.includes(\"tool_calls\")\n ) {\n error = stampRetryable(\n addLangChainErrorFields(e, \"INVALID_TOOL_RESULTS\"),\n false\n );\n } else if (\"status\" in e && e.status === 401) {\n error = stampRetryable(\n addLangChainErrorFields(e, \"MODEL_AUTHENTICATION\"),\n false\n );\n } else if (\"status\" in e && e.status === 429) {\n // AsyncCaller runs after this and re-marks false if it's quota exhaustion.\n error = stampRetryable(\n addLangChainErrorFields(e, \"MODEL_RATE_LIMIT\"),\n true\n );\n } else if (\"status\" in e && e.status === 404) {\n error = stampRetryable(\n addLangChainErrorFields(e, \"MODEL_NOT_FOUND\"),\n false\n );\n } else {\n error = e;\n }\n return error;\n}\n"],"mappings":";;;;AAIA,SAAS,8BAA8B,GAAoB;CAEzD,IADiB,OAAO,CACb,CAAC,CAAC,SAAS,yBAAyB,GAC7C,OAAO;CAET,IACE,aAAa,KACb,OAAO,EAAE,YAAY,aACpB,EAAE,QAAQ,SAAS,0CAA0C,KAC5D,EAAE,QAAQ,SAAS,4BAA4B,KAC/C,EAAE,QAAQ,SAAS,wBAAwB,IAE7C,OAAO;CAET,OAAO;AACT;AAEA,SAAgB,sBAAsB,GAAY;CAChD,IAAI,CAAC,KAAK,OAAO,MAAM,UACrB,OAAO;CAGT,IAAI;CACJ,IACE,EAAE,YAAY,SAASA,OAAAA,0BAA0B,QACjD,aAAa,KACb,OAAO,EAAE,YAAY,UACrB;EACA,QAAQ,IAAI,MAAM,EAAE,OAAO;EAC3B,MAAM,OAAO;EAEb,CAAA,GAAA,uBAAA,eAAA,CAAe,OAAO,IAAI;CAC5B,OAAO,IACL,EAAE,YAAY,SAASC,OAAAA,kBAAkB,QACzC,aAAa,KACb,OAAO,EAAE,YAAY,UACrB;EACA,QAAQ,IAAI,MAAM,EAAE,OAAO;EAC3B,MAAM,OAAO;EACb,CAAA,GAAA,uBAAA,eAAA,CAAe,OAAO,KAAK;CAC7B,OAAO,IAAI,8BAA8B,CAAC,GAExC,QAAQC,uBAAAA,qBAAqB,UAAU,CAAU;MAC5C,IACL,YAAY,KACZ,EAAE,WAAW,OACb,aAAa,KACb,OAAO,EAAE,YAAY,YACrB,EAAE,QAAQ,SAAS,YAAY,GAE/B,SAAA,
|
|
1
|
+
{"version":3,"file":"client.cjs","names":["APIConnectionTimeoutError","APIUserAbortError","ContextOverflowError","stampRetryable","addLangChainErrorFields"],"sources":["../../src/utils/client.ts"],"sourcesContent":["import { APIConnectionTimeoutError, APIUserAbortError } from \"openai\";\nimport { ContextOverflowError, stampRetryable } from \"@langchain/core/errors\";\nimport { addLangChainErrorFields } from \"./errors.js\";\n\nfunction _isOpenAIContextOverflowError(e: object): boolean {\n const errorStr = String(e);\n if (errorStr.includes(\"context_length_exceeded\")) {\n return true;\n }\n if (\n \"message\" in e &&\n typeof e.message === \"string\" &&\n (e.message.includes(\"Input tokens exceed the configured limit\") ||\n e.message.includes(\"exceeds the context window\") ||\n e.message.includes(\"maximum context length\"))\n ) {\n return true;\n }\n return false;\n}\n\nexport function wrapOpenAIClientError(e: unknown) {\n if (!e || typeof e !== \"object\") {\n return e;\n }\n\n let error;\n if (\n e.constructor.name === APIConnectionTimeoutError.name &&\n \"message\" in e &&\n typeof e.message === \"string\"\n ) {\n error = new Error(e.message);\n error.name = \"TimeoutError\";\n // This branch discards the original status, so AsyncCaller can't classify it.\n stampRetryable(error, true);\n } else if (\n e.constructor.name === APIUserAbortError.name &&\n \"message\" in e &&\n typeof e.message === \"string\"\n ) {\n error = new Error(e.message);\n error.name = \"AbortError\";\n stampRetryable(error, false);\n } else if (_isOpenAIContextOverflowError(e)) {\n // ContextOverflowError marks itself non-retryable at construction.\n error = ContextOverflowError.fromError(e as Error);\n } else if (\n \"status\" in e &&\n e.status === 400 &&\n \"message\" in e &&\n typeof e.message === \"string\" &&\n e.message.includes(\"tool_calls\")\n ) {\n error = stampRetryable(\n addLangChainErrorFields(e, \"INVALID_TOOL_RESULTS\"),\n false\n );\n } else if (\"status\" in e && e.status === 401) {\n error = stampRetryable(\n addLangChainErrorFields(e, \"MODEL_AUTHENTICATION\"),\n false\n );\n } else if (\"status\" in e && e.status === 429) {\n // AsyncCaller runs after this and re-marks false if it's quota exhaustion.\n error = stampRetryable(\n addLangChainErrorFields(e, \"MODEL_RATE_LIMIT\"),\n true\n );\n } else if (\"status\" in e && e.status === 404) {\n error = stampRetryable(\n addLangChainErrorFields(e, \"MODEL_NOT_FOUND\"),\n false\n );\n } else {\n error = e;\n }\n return error;\n}\n"],"mappings":";;;;AAIA,SAAS,8BAA8B,GAAoB;CAEzD,IADiB,OAAO,CACb,CAAC,CAAC,SAAS,yBAAyB,GAC7C,OAAO;CAET,IACE,aAAa,KACb,OAAO,EAAE,YAAY,aACpB,EAAE,QAAQ,SAAS,0CAA0C,KAC5D,EAAE,QAAQ,SAAS,4BAA4B,KAC/C,EAAE,QAAQ,SAAS,wBAAwB,IAE7C,OAAO;CAET,OAAO;AACT;AAEA,SAAgB,sBAAsB,GAAY;CAChD,IAAI,CAAC,KAAK,OAAO,MAAM,UACrB,OAAO;CAGT,IAAI;CACJ,IACE,EAAE,YAAY,SAASA,OAAAA,0BAA0B,QACjD,aAAa,KACb,OAAO,EAAE,YAAY,UACrB;EACA,QAAQ,IAAI,MAAM,EAAE,OAAO;EAC3B,MAAM,OAAO;EAEb,CAAA,GAAA,uBAAA,eAAA,CAAe,OAAO,IAAI;CAC5B,OAAO,IACL,EAAE,YAAY,SAASC,OAAAA,kBAAkB,QACzC,aAAa,KACb,OAAO,EAAE,YAAY,UACrB;EACA,QAAQ,IAAI,MAAM,EAAE,OAAO;EAC3B,MAAM,OAAO;EAC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