langchain 1.2.17 → 1.2.19
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 +17 -0
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +8 -8
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +9 -0
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +9 -0
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js.map +1 -1
- package/dist/chat_models/universal.cjs +12 -6
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.d.cts +4 -2
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts +4 -2
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/chat_models/universal.js +12 -6
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/hub/base.cjs +6 -3
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.d.cts +2 -0
- package/dist/hub/base.d.cts.map +1 -1
- package/dist/hub/base.d.ts +2 -0
- package/dist/hub/base.d.ts.map +1 -1
- package/dist/hub/base.js +6 -3
- package/dist/hub/base.js.map +1 -1
- package/dist/hub/index.cjs +2 -0
- package/dist/hub/index.cjs.map +1 -1
- package/dist/hub/index.d.cts +5 -0
- package/dist/hub/index.d.cts.map +1 -1
- package/dist/hub/index.d.ts +5 -0
- package/dist/hub/index.d.ts.map +1 -1
- package/dist/hub/index.js +2 -0
- package/dist/hub/index.js.map +1 -1
- package/dist/hub/node.cjs +29 -1
- package/dist/hub/node.cjs.map +1 -1
- package/dist/hub/node.d.cts +15 -1
- package/dist/hub/node.d.cts.map +1 -1
- package/dist/hub/node.d.ts +15 -1
- package/dist/hub/node.d.ts.map +1 -1
- package/dist/hub/node.js +29 -2
- package/dist/hub/node.js.map +1 -1
- package/package.json +7 -7
|
@@ -91,14 +91,20 @@ const MODEL_PROVIDER_CONFIG = {
|
|
|
91
91
|
};
|
|
92
92
|
const SUPPORTED_PROVIDERS = Object.keys(MODEL_PROVIDER_CONFIG);
|
|
93
93
|
/**
|
|
94
|
-
* Helper function to get a chat model class by its class name
|
|
94
|
+
* Helper function to get a chat model class by its class name or model provider.
|
|
95
95
|
* @param className The class name (e.g., "ChatOpenAI", "ChatAnthropic")
|
|
96
|
+
* @param modelProvider Optional model provider key for direct lookup (e.g., "google-vertexai-web").
|
|
97
|
+
* When provided, uses direct lookup to avoid className collision issues.
|
|
96
98
|
* @returns The imported model class or undefined if not found
|
|
97
99
|
*/
|
|
98
|
-
async function getChatModelByClassName(className) {
|
|
99
|
-
|
|
100
|
-
if (
|
|
101
|
-
|
|
100
|
+
async function getChatModelByClassName(className, modelProvider) {
|
|
101
|
+
let config;
|
|
102
|
+
if (modelProvider) config = MODEL_PROVIDER_CONFIG[modelProvider];
|
|
103
|
+
else {
|
|
104
|
+
const providerEntry = Object.entries(MODEL_PROVIDER_CONFIG).find(([, c]) => c.className === className);
|
|
105
|
+
config = providerEntry ? providerEntry[1] : void 0;
|
|
106
|
+
}
|
|
107
|
+
if (!config) return void 0;
|
|
102
108
|
try {
|
|
103
109
|
const module = await import(config.package);
|
|
104
110
|
return module[config.className];
|
|
@@ -121,7 +127,7 @@ async function _initChatModelHelper(model, modelProvider, params = {}) {
|
|
|
121
127
|
throw new Error(`Unsupported { modelProvider: ${modelProviderCopy} }.\n\nSupported model providers are: ${supported}`);
|
|
122
128
|
}
|
|
123
129
|
const { modelProvider: _unused,...passedParams } = params;
|
|
124
|
-
const ProviderClass = await getChatModelByClassName(config.className);
|
|
130
|
+
const ProviderClass = await getChatModelByClassName(config.className, modelProviderCopy);
|
|
125
131
|
return new ProviderClass({
|
|
126
132
|
model,
|
|
127
133
|
...passedParams
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"universal.js","names":["className: string","config","e: unknown","model: string","modelProvider?: string","params: Record<string, any>","modelName: string","fields: ConfigurableModelFields","config?: RunnableConfig","messages: BaseMessage[]","options?: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","tools: BindToolsInput[]","params?: Record<string, any>","modelParams: Record<string, any>","str: string","prefix: string","mergedConfig: RunnableConfig","remainingConfig: RunnableConfig","input: RunInput","options?: CallOptions","inputs: RunInput[]","options?: Partial<CallOptions> | Partial<CallOptions>[]","batchOptions?: RunnableBatchOptions","generator: AsyncGenerator<RunInput>","options: CallOptions","options?: Partial<CallOptions>","streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">","options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding?: \"text/event-stream\" | undefined;\n }","streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">","filtered: Record<string, unknown>","model?: string","fields?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: string[] | \"any\";\n configPrefix?: string;\n profile?: ModelProfile;\n }","paramsCopy: Record<string, any>","configurableModel: ConfigurableModel<RunInput, CallOptions>"],"sources":["../../src/chat_models/universal.ts"],"sourcesContent":["import {\n BaseLanguageModelInput,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport {\n BaseChatModel,\n BaseChatModelParams,\n BindToolsInput,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n BaseMessage,\n type AIMessageChunk,\n MessageStructure,\n} from \"@langchain/core/messages\";\nimport {\n type RunnableBatchOptions,\n RunnableBinding,\n type RunnableConfig,\n type RunnableToolLike,\n ensureConfig,\n} from \"@langchain/core/runnables\";\nimport {\n AsyncGeneratorWithSetup,\n IterableReadableStream,\n} from \"@langchain/core/utils/stream\";\nimport {\n type LogStreamCallbackHandlerInput,\n type RunLogPatch,\n type StreamEvent,\n} from \"@langchain/core/tracers/log_stream\";\nimport { type StructuredToolInterface } from \"@langchain/core/tools\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nimport { ModelProfile } from \"@langchain/core/language_models/profile\";\n\n// TODO: remove once `EventStreamCallbackHandlerInput` is exposed in core\ninterface EventStreamCallbackHandlerInput\n extends Omit<LogStreamCallbackHandlerInput, \"_schemaFormat\"> {}\n\nexport interface ConfigurableChatModelCallOptions\n extends BaseChatModelCallOptions {\n tools?: (\n | StructuredToolInterface\n | Record<string, unknown>\n | ToolDefinition\n | RunnableToolLike\n )[];\n}\n\n// Configuration map for model providers\nexport const MODEL_PROVIDER_CONFIG = {\n openai: {\n package: \"@langchain/openai\",\n className: \"ChatOpenAI\",\n },\n anthropic: {\n package: \"@langchain/anthropic\",\n className: \"ChatAnthropic\",\n },\n azure_openai: {\n package: \"@langchain/openai\",\n className: \"AzureChatOpenAI\",\n },\n cohere: {\n package: \"@langchain/cohere\",\n className: \"ChatCohere\",\n },\n \"google-vertexai\": {\n package: \"@langchain/google-vertexai\",\n className: \"ChatVertexAI\",\n },\n \"google-vertexai-web\": {\n package: \"@langchain/google-vertexai-web\",\n className: \"ChatVertexAI\",\n },\n \"google-genai\": {\n package: \"@langchain/google-genai\",\n className: \"ChatGoogleGenerativeAI\",\n },\n ollama: {\n package: \"@langchain/ollama\",\n className: \"ChatOllama\",\n },\n mistralai: {\n package: \"@langchain/mistralai\",\n className: \"ChatMistralAI\",\n },\n mistral: {\n package: \"@langchain/mistralai\",\n className: \"ChatMistralAI\",\n },\n groq: {\n package: \"@langchain/groq\",\n className: \"ChatGroq\",\n },\n cerebras: {\n package: \"@langchain/cerebras\",\n className: \"ChatCerebras\",\n },\n bedrock: {\n package: \"@langchain/aws\",\n className: \"ChatBedrockConverse\",\n },\n deepseek: {\n package: \"@langchain/deepseek\",\n className: \"ChatDeepSeek\",\n },\n xai: {\n package: \"@langchain/xai\",\n className: \"ChatXAI\",\n },\n fireworks: {\n package: \"@langchain/community/chat_models/fireworks\",\n className: \"ChatFireworks\",\n hasCircularDependency: true,\n },\n together: {\n package: \"@langchain/community/chat_models/togetherai\",\n className: \"ChatTogetherAI\",\n hasCircularDependency: true,\n },\n perplexity: {\n package: \"@langchain/community/chat_models/perplexity\",\n className: \"ChatPerplexity\",\n hasCircularDependency: true,\n },\n} as const;\n\nconst SUPPORTED_PROVIDERS = Object.keys(\n MODEL_PROVIDER_CONFIG\n) as (keyof typeof MODEL_PROVIDER_CONFIG)[];\nexport type ChatModelProvider = keyof typeof MODEL_PROVIDER_CONFIG;\ntype ModelProviderConfig = {\n package: string;\n className: string;\n hasCircularDependency?: boolean;\n};\n\n/**\n * Helper function to get a chat model class by its class name\n * @param className The class name (e.g., \"ChatOpenAI\", \"ChatAnthropic\")\n * @returns The imported model class or undefined if not found\n */\nexport async function getChatModelByClassName(className: string) {\n // Find the provider config that matches the class name\n const providerEntry = Object.entries(MODEL_PROVIDER_CONFIG).find(\n ([, config]) => config.className === className\n );\n\n if (!providerEntry) {\n return undefined;\n }\n\n const [, config] = providerEntry;\n try {\n const module = await import(config.package);\n return module[config.className];\n } catch (e: unknown) {\n const err = e as Error;\n if (\n \"code\" in err &&\n err.code?.toString().includes(\"ERR_MODULE_NOT_FOUND\") &&\n \"message\" in err &&\n typeof err.message === \"string\"\n ) {\n const msg = err.message.startsWith(\"Error: \")\n ? err.message.slice(\"Error: \".length)\n : err.message;\n const attemptedPackage = msg\n .split(\"Cannot find package '\")[1]\n .split(\"'\")[0];\n throw new Error(\n `Unable to import ${attemptedPackage}. Please install with ` +\n `\\`npm install ${attemptedPackage}\\` or \\`pnpm install ${attemptedPackage}\\``\n );\n }\n throw e;\n }\n}\n\nasync function _initChatModelHelper(\n model: string,\n modelProvider?: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params: Record<string, any> = {}\n): Promise<BaseChatModel> {\n const modelProviderCopy = modelProvider || _inferModelProvider(model);\n if (!modelProviderCopy) {\n throw new Error(\n `Unable to infer model provider for { model: ${model} }, please specify modelProvider directly.`\n );\n }\n\n const config = MODEL_PROVIDER_CONFIG[\n modelProviderCopy as keyof typeof MODEL_PROVIDER_CONFIG\n ] as ModelProviderConfig;\n if (!config) {\n const supported = SUPPORTED_PROVIDERS.join(\", \");\n throw new Error(\n `Unsupported { modelProvider: ${modelProviderCopy} }.\\n\\nSupported model providers are: ${supported}`\n );\n }\n\n const { modelProvider: _unused, ...passedParams } = params;\n const ProviderClass = await getChatModelByClassName(config.className);\n return new ProviderClass({ model, ...passedParams });\n}\n\n/**\n * Attempts to infer the model provider based on the given model name.\n *\n * @param {string} modelName - The name of the model to infer the provider for.\n * @returns {string | undefined} The inferred model provider name, or undefined if unable to infer.\n *\n * @example\n * _inferModelProvider(\"gpt-4\"); // returns \"openai\"\n * _inferModelProvider(\"claude-2\"); // returns \"anthropic\"\n * _inferModelProvider(\"unknown-model\"); // returns undefined\n */\nexport function _inferModelProvider(modelName: string): string | undefined {\n if (\n modelName.startsWith(\"gpt-3\") ||\n modelName.startsWith(\"gpt-4\") ||\n modelName.startsWith(\"gpt-5\") ||\n modelName.startsWith(\"o1\") ||\n modelName.startsWith(\"o3\") ||\n modelName.startsWith(\"o4\")\n ) {\n return \"openai\";\n } else if (modelName.startsWith(\"claude\")) {\n return \"anthropic\";\n } else if (modelName.startsWith(\"command\")) {\n return \"cohere\";\n } else if (modelName.startsWith(\"accounts/fireworks\")) {\n return \"fireworks\";\n } else if (modelName.startsWith(\"gemini\")) {\n return \"google-vertexai\";\n } else if (modelName.startsWith(\"amazon.\")) {\n return \"bedrock\";\n } else if (modelName.startsWith(\"mistral\")) {\n return \"mistralai\";\n } else if (modelName.startsWith(\"sonar\") || modelName.startsWith(\"pplx\")) {\n return \"perplexity\";\n } else {\n return undefined;\n }\n}\n\ninterface ConfigurableModelFields extends BaseChatModelParams {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n defaultConfig?: Record<string, any>;\n /**\n * @default \"any\"\n */\n configurableFields?: string[] | \"any\";\n /**\n * @default \"\"\n */\n configPrefix?: string;\n /**\n * Methods which should be called after the model is initialized.\n * The key will be the method name, and the value will be the arguments.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n queuedMethodOperations?: Record<string, any>;\n /**\n * Overrides the profiling information for the model. If not provided,\n * the profile will be inferred from the inner model instance.\n */\n profile?: ModelProfile;\n}\n\n/**\n * Internal class used to create chat models.\n *\n * @internal\n */\nexport class ConfigurableModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends\n ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions,\n> extends BaseChatModel<CallOptions, AIMessageChunk> {\n _llmType(): string {\n return \"chat_model\";\n }\n\n lc_namespace = [\"langchain\", \"chat_models\"];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _defaultConfig?: Record<string, any> = {};\n\n /**\n * @default \"any\"\n */\n _configurableFields: string[] | \"any\" = \"any\";\n\n /**\n * @default \"\"\n */\n _configPrefix: string;\n\n /**\n * Methods which should be called after the model is initialized.\n * The key will be the method name, and the value will be the arguments.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _queuedMethodOperations: Record<string, any> = {};\n\n /** @internal */\n private _modelInstanceCache = new Map<\n string,\n BaseChatModel<BaseChatModelCallOptions, AIMessageChunk<MessageStructure>>\n >();\n\n /** @internal */\n private _profile?: ModelProfile;\n\n constructor(fields: ConfigurableModelFields) {\n super(fields);\n this._defaultConfig = fields.defaultConfig ?? {};\n\n if (fields.configurableFields === \"any\") {\n this._configurableFields = \"any\";\n } else {\n this._configurableFields = fields.configurableFields ?? [\n \"model\",\n \"modelProvider\",\n ];\n }\n\n if (fields.configPrefix) {\n this._configPrefix = fields.configPrefix.endsWith(\"_\")\n ? fields.configPrefix\n : `${fields.configPrefix}_`;\n } else {\n this._configPrefix = \"\";\n }\n\n this._queuedMethodOperations =\n fields.queuedMethodOperations ?? this._queuedMethodOperations;\n\n this._profile = fields.profile ?? undefined;\n }\n\n async _getModelInstance(\n config?: RunnableConfig\n ): Promise<\n BaseChatModel<BaseChatModelCallOptions, AIMessageChunk<MessageStructure>>\n > {\n // Check cache first\n const cacheKey = this._getCacheKey(config);\n const cachedModel = this._modelInstanceCache.get(cacheKey);\n if (cachedModel) {\n return cachedModel;\n }\n\n // Initialize model with merged params\n const params = { ...this._defaultConfig, ...this._modelParams(config) };\n let initializedModel = await _initChatModelHelper(\n params.model,\n params.modelProvider,\n params\n );\n\n // Apply queued method operations in sequence\n for (const [method, args] of Object.entries(this._queuedMethodOperations)) {\n if (\n method in initializedModel &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (initializedModel as any)[method] === \"function\"\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initializedModel = await (initializedModel as any)[method](...args);\n }\n }\n\n // Cache and return the initialized model\n this._modelInstanceCache.set(cacheKey, initializedModel);\n return initializedModel;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const model = await this._getModelInstance(options);\n return model._generate(messages, options ?? {}, runManager);\n }\n\n override bindTools(\n tools: BindToolsInput[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params?: Record<string, any>\n ): ConfigurableModel<RunInput, CallOptions> {\n const newQueuedOperations = { ...this._queuedMethodOperations };\n newQueuedOperations.bindTools = [tools, params];\n return new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: this._defaultConfig,\n configurableFields: this._configurableFields,\n configPrefix: this._configPrefix,\n queuedMethodOperations: newQueuedOperations,\n });\n }\n\n // Extract the input types from the `BaseModel` class.\n withStructuredOutput: BaseChatModel[\"withStructuredOutput\"] = (\n schema,\n ...args\n ): ReturnType<BaseChatModel[\"withStructuredOutput\"]> => {\n const newQueuedOperations = { ...this._queuedMethodOperations };\n newQueuedOperations.withStructuredOutput = [schema, ...args];\n return new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: this._defaultConfig,\n configurableFields: this._configurableFields,\n configPrefix: this._configPrefix,\n queuedMethodOperations: newQueuedOperations,\n }) as unknown as ReturnType<BaseChatModel[\"withStructuredOutput\"]>;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _modelParams(config?: RunnableConfig): Record<string, any> {\n const configurable = config?.configurable ?? {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let modelParams: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(configurable)) {\n if (key.startsWith(this._configPrefix)) {\n const strippedKey = this._removePrefix(key, this._configPrefix);\n modelParams[strippedKey] = value;\n }\n }\n\n if (this._configurableFields !== \"any\") {\n modelParams = Object.fromEntries(\n Object.entries(modelParams).filter(([key]) =>\n this._configurableFields.includes(key)\n )\n );\n }\n\n return modelParams;\n }\n\n _removePrefix(str: string, prefix: string): string {\n return str.startsWith(prefix) ? str.slice(prefix.length) : str;\n }\n\n /**\n * Bind config to a Runnable, returning a new Runnable.\n * @param {RunnableConfig | undefined} [config] - The config to bind.\n * @returns {RunnableBinding<RunInput, RunOutput, CallOptions>} A new RunnableBinding with the bound config.\n */\n withConfig(\n config?: RunnableConfig\n ): RunnableBinding<RunInput, AIMessageChunk, CallOptions> {\n const mergedConfig: RunnableConfig = { ...(config || {}) };\n const modelParams = this._modelParams(mergedConfig);\n\n const remainingConfig: RunnableConfig = Object.fromEntries(\n Object.entries(mergedConfig).filter(([k]) => k !== \"configurable\")\n );\n\n remainingConfig.configurable = Object.fromEntries(\n Object.entries(mergedConfig.configurable || {}).filter(\n ([k]) =>\n this._configPrefix &&\n !Object.keys(modelParams).includes(\n this._removePrefix(k, this._configPrefix)\n )\n )\n );\n\n const newConfigurableModel = new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: { ...this._defaultConfig, ...modelParams },\n configurableFields: Array.isArray(this._configurableFields)\n ? [...this._configurableFields]\n : this._configurableFields,\n configPrefix: this._configPrefix,\n queuedMethodOperations: this._queuedMethodOperations,\n });\n\n return new RunnableBinding<RunInput, AIMessageChunk, CallOptions>({\n config: mergedConfig,\n bound: newConfigurableModel,\n });\n }\n\n async invoke(\n input: RunInput,\n options?: CallOptions\n ): Promise<AIMessageChunk> {\n const model = await this._getModelInstance(options);\n const config = ensureConfig(options);\n return model.invoke(input, config);\n }\n\n async stream(\n input: RunInput,\n options?: CallOptions\n ): Promise<IterableReadableStream<AIMessageChunk>> {\n const model = await this._getModelInstance(options);\n const wrappedGenerator = new AsyncGeneratorWithSetup({\n generator: await model.stream(input, options),\n config: options,\n });\n await wrappedGenerator.setup;\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions?: false }\n ): Promise<AIMessageChunk[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions: true }\n ): Promise<(AIMessageChunk | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(AIMessageChunk | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(AIMessageChunk | Error)[]> {\n // We can super this since the base runnable implementation of\n // `.batch` will call `.invoke` on each input.\n return super.batch(inputs, options, batchOptions);\n }\n\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options: CallOptions\n ): AsyncGenerator<AIMessageChunk> {\n const model = await this._getModelInstance(options);\n const config = ensureConfig(options);\n\n yield* model.transform(generator, config);\n }\n\n async *streamLog(\n input: RunInput,\n options?: Partial<CallOptions>,\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): AsyncGenerator<RunLogPatch> {\n const model = await this._getModelInstance(options);\n const config = ensureConfig(options);\n\n yield* model.streamLog(input, config, {\n ...streamOptions,\n _schemaFormat: \"original\",\n includeNames: streamOptions?.includeNames,\n includeTypes: streamOptions?.includeTypes,\n includeTags: streamOptions?.includeTags,\n excludeNames: streamOptions?.excludeNames,\n excludeTypes: streamOptions?.excludeTypes,\n excludeTags: streamOptions?.excludeTags,\n });\n }\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" | \"v2\" },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding?: \"text/event-stream\" | undefined;\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent | Uint8Array> {\n const outerThis = this;\n async function* wrappedGenerator() {\n const model = await outerThis._getModelInstance(options);\n const config = ensureConfig(options);\n const eventStream = model.streamEvents(input, config, streamOptions);\n\n for await (const chunk of eventStream) {\n yield chunk;\n }\n }\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator());\n }\n\n /**\n * Return profiling information for the model.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n if (this._profile) {\n return this._profile;\n }\n const cacheKey = this._getCacheKey({});\n const instance = this._modelInstanceCache.get(cacheKey);\n return instance?.profile ?? {};\n }\n\n /** @internal */\n _getCacheKey(config?: RunnableConfig): string {\n let toStringify = config ?? {};\n if (toStringify.configurable) {\n const { configurable } = toStringify;\n const filtered: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(configurable)) {\n if (!k.startsWith(\"__pregel_\")) {\n filtered[k] = v;\n }\n }\n toStringify = { ...toStringify, configurable: filtered };\n }\n return JSON.stringify(toStringify);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface InitChatModelFields extends Partial<Record<string, any>> {\n modelProvider?: string;\n configurableFields?: string[] | \"any\";\n configPrefix?: string;\n}\n\nexport type ConfigurableFields = \"any\" | string[];\n\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends\n ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions,\n>(\n model: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fields?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: never;\n configPrefix?: string;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>>;\n\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends\n ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions,\n>(\n model: never,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: never;\n configPrefix?: string;\n profile?: ModelProfile;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>>;\n\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends\n ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions,\n>(\n model?: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: ConfigurableFields;\n configPrefix?: string;\n profile?: ModelProfile;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>>;\n\n// ################################# FOR CONTRIBUTORS #################################\n//\n// If adding support for a new provider, please append the provider\n// name to the supported list in the docstring below.\n//\n// ####################################################################################\n\n/**\n * Initialize a ChatModel from the model name and provider.\n * Must have the integration package corresponding to the model provider installed.\n *\n * @template {extends BaseLanguageModelInput = BaseLanguageModelInput} RunInput - The input type for the model.\n * @template {extends ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions} CallOptions - Call options for the model.\n *\n * @param {string | ChatModelProvider} [model] - The name of the model, e.g. \"gpt-4\", \"claude-3-opus-20240229\".\n * Can be prefixed with the model provider, e.g. \"openai:gpt-4\", \"anthropic:claude-3-opus-20240229\".\n * @param {Object} [fields] - Additional configuration options.\n * @param {string} [fields.modelProvider] - The model provider. Supported values include:\n * - openai (@langchain/openai)\n * - anthropic (@langchain/anthropic)\n * - azure_openai (@langchain/openai)\n * - google-vertexai (@langchain/google-vertexai)\n * - google-vertexai-web (@langchain/google-vertexai-web)\n * - google-genai (@langchain/google-genai)\n * - bedrock (@langchain/aws)\n * - cohere (@langchain/cohere)\n * - fireworks (@langchain/community/chat_models/fireworks)\n * - together (@langchain/community/chat_models/togetherai)\n * - mistralai (@langchain/mistralai)\n * - groq (@langchain/groq)\n * - ollama (@langchain/ollama)\n * - perplexity (@langchain/community/chat_models/perplexity)\n * - cerebras (@langchain/cerebras)\n * - deepseek (@langchain/deepseek)\n * - xai (@langchain/xai)\n * @param {string[] | \"any\"} [fields.configurableFields] - Which model parameters are configurable:\n * - undefined: No configurable fields.\n * - \"any\": All fields are configurable. (See Security Note in description)\n * - string[]: Specified fields are configurable.\n * @param {string} [fields.configPrefix] - Prefix for configurable fields at runtime.\n * @param {ModelProfile} [fields.profile] - Overrides the profiling information for the model. If not provided,\n * the profile will be inferred from the inner model instance.\n * @param {Record<string, any>} [fields.params] - Additional keyword args to pass to the ChatModel constructor.\n * @returns {Promise<ConfigurableModel<RunInput, CallOptions>>} A class which extends BaseChatModel.\n * @throws {Error} If modelProvider cannot be inferred or isn't supported.\n * @throws {Error} If the model provider integration package is not installed.\n *\n * @example Initialize non-configurable models\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const gpt4 = await initChatModel(\"openai:gpt-4\", {\n * temperature: 0.25,\n * });\n * const gpt4Result = await gpt4.invoke(\"what's your name\");\n *\n * const claude = await initChatModel(\"anthropic:claude-3-opus-20240229\", {\n * temperature: 0.25,\n * });\n * const claudeResult = await claude.invoke(\"what's your name\");\n *\n * const gemini = await initChatModel(\"gemini-1.5-pro\", {\n * modelProvider: \"google-vertexai\",\n * temperature: 0.25,\n * });\n * const geminiResult = await gemini.invoke(\"what's your name\");\n * ```\n *\n * @example Create a partially configurable model with no default model\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const configurableModel = await initChatModel(undefined, {\n * temperature: 0,\n * configurableFields: [\"model\", \"apiKey\"],\n * });\n *\n * const gpt4Result = await configurableModel.invoke(\"what's your name\", {\n * configurable: {\n * model: \"gpt-4\",\n * },\n * });\n *\n * const claudeResult = await configurableModel.invoke(\"what's your name\", {\n * configurable: {\n * model: \"claude-3-5-sonnet-20240620\",\n * },\n * });\n * ```\n *\n * @example Create a fully configurable model with a default model and a config prefix\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const configurableModelWithDefault = await initChatModel(\"gpt-4\", {\n * modelProvider: \"openai\",\n * configurableFields: \"any\",\n * configPrefix: \"foo\",\n * temperature: 0,\n * });\n *\n * const openaiResult = await configurableModelWithDefault.invoke(\n * \"what's your name\",\n * {\n * configurable: {\n * foo_apiKey: process.env.OPENAI_API_KEY,\n * },\n * }\n * );\n *\n * const claudeResult = await configurableModelWithDefault.invoke(\n * \"what's your name\",\n * {\n * configurable: {\n * foo_model: \"claude-3-5-sonnet-20240620\",\n * foo_modelProvider: \"anthropic\",\n * foo_temperature: 0.6,\n * foo_apiKey: process.env.ANTHROPIC_API_KEY,\n * },\n * }\n * );\n * ```\n *\n * @example Bind tools to a configurable model:\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n * import { z } from \"zod/v3\";\n * import { tool } from \"@langchain/core/tools\";\n *\n * const getWeatherTool = tool(\n * (input) => {\n * // Do something with the input\n * return JSON.stringify(input);\n * },\n * {\n * schema: z\n * .object({\n * location: z\n * .string()\n * .describe(\"The city and state, e.g. San Francisco, CA\"),\n * })\n * .describe(\"Get the current weather in a given location\"),\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * }\n * );\n *\n * const getPopulationTool = tool(\n * (input) => {\n * // Do something with the input\n * return JSON.stringify(input);\n * },\n * {\n * schema: z\n * .object({\n * location: z\n * .string()\n * .describe(\"The city and state, e.g. San Francisco, CA\"),\n * })\n * .describe(\"Get the current population in a given location\"),\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * }\n * );\n *\n * const configurableModel = await initChatModel(\"gpt-4\", {\n * configurableFields: [\"model\", \"modelProvider\", \"apiKey\"],\n * temperature: 0,\n * });\n *\n * const configurableModelWithTools = configurableModel.bindTools([\n * getWeatherTool,\n * getPopulationTool,\n * ]);\n *\n * const configurableToolResult = await configurableModelWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\",\n * {\n * configurable: {\n * apiKey: process.env.OPENAI_API_KEY,\n * },\n * }\n * );\n *\n * const configurableToolResult2 = await configurableModelWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\",\n * {\n * configurable: {\n * model: \"claude-3-5-sonnet-20240620\",\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * },\n * }\n * );\n * ```\n *\n * @example Initialize a model with a custom profile\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const model = await initChatModel(\"gpt-4o-mini\", {\n * profile: {\n * maxInputTokens: 100000,\n * },\n * });\n *\n * @description\n * This function initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * Security Note: Setting `configurableFields` to \"any\" means fields like apiKey, baseUrl, etc.\n * can be altered at runtime, potentially redirecting model requests to a different service/user.\n * Make sure that if you're accepting untrusted configurations, you enumerate the\n * `configurableFields` explicitly.\n *\n * The function will attempt to infer the model provider from the model name if not specified.\n * Certain model name prefixes are associated with specific providers:\n * - gpt-3... or gpt-4... -> openai\n * - claude... -> anthropic\n * - amazon.... -> bedrock\n * - gemini... -> google-vertexai\n * - command... -> cohere\n * - accounts/fireworks... -> fireworks\n *\n * @since 0.2.11\n * @version 0.2.11\n */\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends\n ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions,\n>(\n model?: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fields?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: string[] | \"any\";\n configPrefix?: string;\n profile?: ModelProfile;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>> {\n // eslint-disable-next-line prefer-const\n let { configurableFields, configPrefix, modelProvider, profile, ...params } =\n {\n configPrefix: \"\",\n ...(fields ?? {}),\n };\n if (modelProvider === undefined && model?.includes(\":\")) {\n const [provider, ...remainingParts] = model.split(\":\");\n const modelComponents =\n remainingParts.length === 0\n ? [provider]\n : [provider, remainingParts.join(\":\")];\n if (SUPPORTED_PROVIDERS.includes(modelComponents[0] as ChatModelProvider)) {\n // eslint-disable-next-line no-param-reassign\n [modelProvider, model] = modelComponents;\n }\n }\n let configurableFieldsCopy = Array.isArray(configurableFields)\n ? [...configurableFields]\n : configurableFields;\n\n if (!model && configurableFieldsCopy === undefined) {\n configurableFieldsCopy = [\"model\", \"modelProvider\"];\n }\n if (configPrefix && configurableFieldsCopy === undefined) {\n console.warn(\n `{ configPrefix: ${configPrefix} } has been set but no fields are configurable. Set ` +\n `{ configurableFields: [...] } to specify the model params that are ` +\n `configurable.`\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const paramsCopy: Record<string, any> = { ...params };\n\n let configurableModel: ConfigurableModel<RunInput, CallOptions>;\n\n if (configurableFieldsCopy === undefined) {\n configurableModel = new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: {\n ...paramsCopy,\n model,\n modelProvider,\n },\n configPrefix,\n profile,\n });\n } else {\n if (model) {\n paramsCopy.model = model;\n }\n if (modelProvider) {\n paramsCopy.modelProvider = modelProvider;\n }\n configurableModel = new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: paramsCopy,\n configPrefix,\n configurableFields: configurableFieldsCopy,\n profile,\n });\n }\n\n // Initialize the model instance to make sure a profile is available\n await configurableModel._getModelInstance();\n return configurableModel;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmDA,MAAa,wBAAwB;CACnC,QAAQ;EACN,SAAS;EACT,WAAW;CACZ;CACD,WAAW;EACT,SAAS;EACT,WAAW;CACZ;CACD,cAAc;EACZ,SAAS;EACT,WAAW;CACZ;CACD,QAAQ;EACN,SAAS;EACT,WAAW;CACZ;CACD,mBAAmB;EACjB,SAAS;EACT,WAAW;CACZ;CACD,uBAAuB;EACrB,SAAS;EACT,WAAW;CACZ;CACD,gBAAgB;EACd,SAAS;EACT,WAAW;CACZ;CACD,QAAQ;EACN,SAAS;EACT,WAAW;CACZ;CACD,WAAW;EACT,SAAS;EACT,WAAW;CACZ;CACD,SAAS;EACP,SAAS;EACT,WAAW;CACZ;CACD,MAAM;EACJ,SAAS;EACT,WAAW;CACZ;CACD,UAAU;EACR,SAAS;EACT,WAAW;CACZ;CACD,SAAS;EACP,SAAS;EACT,WAAW;CACZ;CACD,UAAU;EACR,SAAS;EACT,WAAW;CACZ;CACD,KAAK;EACH,SAAS;EACT,WAAW;CACZ;CACD,WAAW;EACT,SAAS;EACT,WAAW;EACX,uBAAuB;CACxB;CACD,UAAU;EACR,SAAS;EACT,WAAW;EACX,uBAAuB;CACxB;CACD,YAAY;EACV,SAAS;EACT,WAAW;EACX,uBAAuB;CACxB;AACF;AAED,MAAM,sBAAsB,OAAO,KACjC,sBACD;;;;;;AAaD,eAAsB,wBAAwBA,WAAmB;CAE/D,MAAM,g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ACH;GACA;EACD;EACD;EACA;CACD;MACI;AACL,MAAI,OACF,WAAW,QAAQ;AAErB,MAAI,eACF,WAAW,gBAAgB;EAE7B,oBAAoB,IAAI,kBAAyC;GAC/D,eAAe;GACf;GACA,oBAAoB;GACpB;EACD;CACF;CAGD,MAAM,kBAAkB,mBAAmB;AAC3C,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"universal.js","names":["className: string","modelProvider?: string","config: ModelProviderConfig | undefined","e: unknown","model: string","params: Record<string, any>","modelName: string","fields: ConfigurableModelFields","config?: RunnableConfig","messages: BaseMessage[]","options?: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","tools: BindToolsInput[]","params?: Record<string, any>","modelParams: Record<string, any>","str: string","prefix: string","mergedConfig: RunnableConfig","remainingConfig: RunnableConfig","input: RunInput","options?: CallOptions","inputs: RunInput[]","options?: Partial<CallOptions> | Partial<CallOptions>[]","batchOptions?: RunnableBatchOptions","generator: AsyncGenerator<RunInput>","options: CallOptions","options?: Partial<CallOptions>","streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">","options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding?: \"text/event-stream\" | undefined;\n }","streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">","filtered: Record<string, unknown>","model?: string","fields?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: string[] | \"any\";\n configPrefix?: string;\n profile?: ModelProfile;\n }","paramsCopy: Record<string, any>","configurableModel: ConfigurableModel<RunInput, CallOptions>"],"sources":["../../src/chat_models/universal.ts"],"sourcesContent":["import {\n BaseLanguageModelInput,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport {\n BaseChatModel,\n BaseChatModelParams,\n BindToolsInput,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n BaseMessage,\n type AIMessageChunk,\n MessageStructure,\n} from \"@langchain/core/messages\";\nimport {\n type RunnableBatchOptions,\n RunnableBinding,\n type RunnableConfig,\n type RunnableToolLike,\n ensureConfig,\n} from \"@langchain/core/runnables\";\nimport {\n AsyncGeneratorWithSetup,\n IterableReadableStream,\n} from \"@langchain/core/utils/stream\";\nimport {\n type LogStreamCallbackHandlerInput,\n type RunLogPatch,\n type StreamEvent,\n} from \"@langchain/core/tracers/log_stream\";\nimport { type StructuredToolInterface } from \"@langchain/core/tools\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nimport { ModelProfile } from \"@langchain/core/language_models/profile\";\n\n// TODO: remove once `EventStreamCallbackHandlerInput` is exposed in core\ninterface EventStreamCallbackHandlerInput extends Omit<\n LogStreamCallbackHandlerInput,\n \"_schemaFormat\"\n> {}\n\nexport interface ConfigurableChatModelCallOptions extends BaseChatModelCallOptions {\n tools?: (\n | StructuredToolInterface\n | Record<string, unknown>\n | ToolDefinition\n | RunnableToolLike\n )[];\n}\n\n// Configuration map for model providers\nexport const MODEL_PROVIDER_CONFIG = {\n openai: {\n package: \"@langchain/openai\",\n className: \"ChatOpenAI\",\n },\n anthropic: {\n package: \"@langchain/anthropic\",\n className: \"ChatAnthropic\",\n },\n azure_openai: {\n package: \"@langchain/openai\",\n className: \"AzureChatOpenAI\",\n },\n cohere: {\n package: \"@langchain/cohere\",\n className: \"ChatCohere\",\n },\n \"google-vertexai\": {\n package: \"@langchain/google-vertexai\",\n className: \"ChatVertexAI\",\n },\n \"google-vertexai-web\": {\n package: \"@langchain/google-vertexai-web\",\n className: \"ChatVertexAI\",\n },\n \"google-genai\": {\n package: \"@langchain/google-genai\",\n className: \"ChatGoogleGenerativeAI\",\n },\n ollama: {\n package: \"@langchain/ollama\",\n className: \"ChatOllama\",\n },\n mistralai: {\n package: \"@langchain/mistralai\",\n className: \"ChatMistralAI\",\n },\n mistral: {\n package: \"@langchain/mistralai\",\n className: \"ChatMistralAI\",\n },\n groq: {\n package: \"@langchain/groq\",\n className: \"ChatGroq\",\n },\n cerebras: {\n package: \"@langchain/cerebras\",\n className: \"ChatCerebras\",\n },\n bedrock: {\n package: \"@langchain/aws\",\n className: \"ChatBedrockConverse\",\n },\n deepseek: {\n package: \"@langchain/deepseek\",\n className: \"ChatDeepSeek\",\n },\n xai: {\n package: \"@langchain/xai\",\n className: \"ChatXAI\",\n },\n fireworks: {\n package: \"@langchain/community/chat_models/fireworks\",\n className: \"ChatFireworks\",\n hasCircularDependency: true,\n },\n together: {\n package: \"@langchain/community/chat_models/togetherai\",\n className: \"ChatTogetherAI\",\n hasCircularDependency: true,\n },\n perplexity: {\n package: \"@langchain/community/chat_models/perplexity\",\n className: \"ChatPerplexity\",\n hasCircularDependency: true,\n },\n} as const;\n\nconst SUPPORTED_PROVIDERS = Object.keys(\n MODEL_PROVIDER_CONFIG\n) as (keyof typeof MODEL_PROVIDER_CONFIG)[];\nexport type ChatModelProvider = keyof typeof MODEL_PROVIDER_CONFIG;\ntype ModelProviderConfig = {\n package: string;\n className: string;\n hasCircularDependency?: boolean;\n};\n\n/**\n * Helper function to get a chat model class by its class name or model provider.\n * @param className The class name (e.g., \"ChatOpenAI\", \"ChatAnthropic\")\n * @param modelProvider Optional model provider key for direct lookup (e.g., \"google-vertexai-web\").\n * When provided, uses direct lookup to avoid className collision issues.\n * @returns The imported model class or undefined if not found\n */\nexport async function getChatModelByClassName(\n className: string,\n modelProvider?: string\n) {\n let config: ModelProviderConfig | undefined;\n\n if (modelProvider) {\n // Direct lookup by modelProvider key - avoids className collision\n // (e.g., google-vertexai and google-vertexai-web both use \"ChatVertexAI\")\n config = MODEL_PROVIDER_CONFIG[\n modelProvider as keyof typeof MODEL_PROVIDER_CONFIG\n ] as ModelProviderConfig | undefined;\n } else {\n // Fallback to className lookup for backward compatibility\n const providerEntry = Object.entries(MODEL_PROVIDER_CONFIG).find(\n ([, c]) => c.className === className\n );\n config = providerEntry\n ? (providerEntry[1] as ModelProviderConfig)\n : undefined;\n }\n\n if (!config) {\n return undefined;\n }\n\n try {\n const module = await import(config.package);\n return module[config.className];\n } catch (e: unknown) {\n const err = e as Error;\n if (\n \"code\" in err &&\n err.code?.toString().includes(\"ERR_MODULE_NOT_FOUND\") &&\n \"message\" in err &&\n typeof err.message === \"string\"\n ) {\n const msg = err.message.startsWith(\"Error: \")\n ? err.message.slice(\"Error: \".length)\n : err.message;\n const attemptedPackage = msg\n .split(\"Cannot find package '\")[1]\n .split(\"'\")[0];\n throw new Error(\n `Unable to import ${attemptedPackage}. Please install with ` +\n `\\`npm install ${attemptedPackage}\\` or \\`pnpm install ${attemptedPackage}\\``\n );\n }\n throw e;\n }\n}\n\nasync function _initChatModelHelper(\n model: string,\n modelProvider?: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params: Record<string, any> = {}\n): Promise<BaseChatModel> {\n const modelProviderCopy = modelProvider || _inferModelProvider(model);\n if (!modelProviderCopy) {\n throw new Error(\n `Unable to infer model provider for { model: ${model} }, please specify modelProvider directly.`\n );\n }\n\n const config = MODEL_PROVIDER_CONFIG[\n modelProviderCopy as keyof typeof MODEL_PROVIDER_CONFIG\n ] as ModelProviderConfig;\n if (!config) {\n const supported = SUPPORTED_PROVIDERS.join(\", \");\n throw new Error(\n `Unsupported { modelProvider: ${modelProviderCopy} }.\\n\\nSupported model providers are: ${supported}`\n );\n }\n\n const { modelProvider: _unused, ...passedParams } = params;\n // Pass modelProviderCopy to use direct lookup and avoid className collision\n const ProviderClass = await getChatModelByClassName(\n config.className,\n modelProviderCopy\n );\n return new ProviderClass({ model, ...passedParams });\n}\n\n/**\n * Attempts to infer the model provider based on the given model name.\n *\n * @param {string} modelName - The name of the model to infer the provider for.\n * @returns {string | undefined} The inferred model provider name, or undefined if unable to infer.\n *\n * @example\n * _inferModelProvider(\"gpt-4\"); // returns \"openai\"\n * _inferModelProvider(\"claude-2\"); // returns \"anthropic\"\n * _inferModelProvider(\"unknown-model\"); // returns undefined\n */\nexport function _inferModelProvider(modelName: string): string | undefined {\n if (\n modelName.startsWith(\"gpt-3\") ||\n modelName.startsWith(\"gpt-4\") ||\n modelName.startsWith(\"gpt-5\") ||\n modelName.startsWith(\"o1\") ||\n modelName.startsWith(\"o3\") ||\n modelName.startsWith(\"o4\")\n ) {\n return \"openai\";\n } else if (modelName.startsWith(\"claude\")) {\n return \"anthropic\";\n } else if (modelName.startsWith(\"command\")) {\n return \"cohere\";\n } else if (modelName.startsWith(\"accounts/fireworks\")) {\n return \"fireworks\";\n } else if (modelName.startsWith(\"gemini\")) {\n return \"google-vertexai\";\n } else if (modelName.startsWith(\"amazon.\")) {\n return \"bedrock\";\n } else if (modelName.startsWith(\"mistral\")) {\n return \"mistralai\";\n } else if (modelName.startsWith(\"sonar\") || modelName.startsWith(\"pplx\")) {\n return \"perplexity\";\n } else {\n return undefined;\n }\n}\n\ninterface ConfigurableModelFields extends BaseChatModelParams {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n defaultConfig?: Record<string, any>;\n /**\n * @default \"any\"\n */\n configurableFields?: string[] | \"any\";\n /**\n * @default \"\"\n */\n configPrefix?: string;\n /**\n * Methods which should be called after the model is initialized.\n * The key will be the method name, and the value will be the arguments.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n queuedMethodOperations?: Record<string, any>;\n /**\n * Overrides the profiling information for the model. If not provided,\n * the profile will be inferred from the inner model instance.\n */\n profile?: ModelProfile;\n}\n\n/**\n * Internal class used to create chat models.\n *\n * @internal\n */\nexport class ConfigurableModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends ConfigurableChatModelCallOptions =\n ConfigurableChatModelCallOptions,\n> extends BaseChatModel<CallOptions, AIMessageChunk> {\n _llmType(): string {\n return \"chat_model\";\n }\n\n lc_namespace = [\"langchain\", \"chat_models\"];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _defaultConfig?: Record<string, any> = {};\n\n /**\n * @default \"any\"\n */\n _configurableFields: string[] | \"any\" = \"any\";\n\n /**\n * @default \"\"\n */\n _configPrefix: string;\n\n /**\n * Methods which should be called after the model is initialized.\n * The key will be the method name, and the value will be the arguments.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _queuedMethodOperations: Record<string, any> = {};\n\n /** @internal */\n private _modelInstanceCache = new Map<\n string,\n BaseChatModel<BaseChatModelCallOptions, AIMessageChunk<MessageStructure>>\n >();\n\n /** @internal */\n private _profile?: ModelProfile;\n\n constructor(fields: ConfigurableModelFields) {\n super(fields);\n this._defaultConfig = fields.defaultConfig ?? {};\n\n if (fields.configurableFields === \"any\") {\n this._configurableFields = \"any\";\n } else {\n this._configurableFields = fields.configurableFields ?? [\n \"model\",\n \"modelProvider\",\n ];\n }\n\n if (fields.configPrefix) {\n this._configPrefix = fields.configPrefix.endsWith(\"_\")\n ? fields.configPrefix\n : `${fields.configPrefix}_`;\n } else {\n this._configPrefix = \"\";\n }\n\n this._queuedMethodOperations =\n fields.queuedMethodOperations ?? this._queuedMethodOperations;\n\n this._profile = fields.profile ?? undefined;\n }\n\n async _getModelInstance(\n config?: RunnableConfig\n ): Promise<\n BaseChatModel<BaseChatModelCallOptions, AIMessageChunk<MessageStructure>>\n > {\n // Check cache first\n const cacheKey = this._getCacheKey(config);\n const cachedModel = this._modelInstanceCache.get(cacheKey);\n if (cachedModel) {\n return cachedModel;\n }\n\n // Initialize model with merged params\n const params = { ...this._defaultConfig, ...this._modelParams(config) };\n let initializedModel = await _initChatModelHelper(\n params.model,\n params.modelProvider,\n params\n );\n\n // Apply queued method operations in sequence\n for (const [method, args] of Object.entries(this._queuedMethodOperations)) {\n if (\n method in initializedModel &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (initializedModel as any)[method] === \"function\"\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initializedModel = await (initializedModel as any)[method](...args);\n }\n }\n\n // Cache and return the initialized model\n this._modelInstanceCache.set(cacheKey, initializedModel);\n return initializedModel;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const model = await this._getModelInstance(options);\n return model._generate(messages, options ?? {}, runManager);\n }\n\n override bindTools(\n tools: BindToolsInput[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params?: Record<string, any>\n ): ConfigurableModel<RunInput, CallOptions> {\n const newQueuedOperations = { ...this._queuedMethodOperations };\n newQueuedOperations.bindTools = [tools, params];\n return new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: this._defaultConfig,\n configurableFields: this._configurableFields,\n configPrefix: this._configPrefix,\n queuedMethodOperations: newQueuedOperations,\n });\n }\n\n // Extract the input types from the `BaseModel` class.\n withStructuredOutput: BaseChatModel[\"withStructuredOutput\"] = (\n schema,\n ...args\n ): ReturnType<BaseChatModel[\"withStructuredOutput\"]> => {\n const newQueuedOperations = { ...this._queuedMethodOperations };\n newQueuedOperations.withStructuredOutput = [schema, ...args];\n return new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: this._defaultConfig,\n configurableFields: this._configurableFields,\n configPrefix: this._configPrefix,\n queuedMethodOperations: newQueuedOperations,\n }) as unknown as ReturnType<BaseChatModel[\"withStructuredOutput\"]>;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _modelParams(config?: RunnableConfig): Record<string, any> {\n const configurable = config?.configurable ?? {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let modelParams: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(configurable)) {\n if (key.startsWith(this._configPrefix)) {\n const strippedKey = this._removePrefix(key, this._configPrefix);\n modelParams[strippedKey] = value;\n }\n }\n\n if (this._configurableFields !== \"any\") {\n modelParams = Object.fromEntries(\n Object.entries(modelParams).filter(([key]) =>\n this._configurableFields.includes(key)\n )\n );\n }\n\n return modelParams;\n }\n\n _removePrefix(str: string, prefix: string): string {\n return str.startsWith(prefix) ? str.slice(prefix.length) : str;\n }\n\n /**\n * Bind config to a Runnable, returning a new Runnable.\n * @param {RunnableConfig | undefined} [config] - The config to bind.\n * @returns {RunnableBinding<RunInput, RunOutput, CallOptions>} A new RunnableBinding with the bound config.\n */\n withConfig(\n config?: RunnableConfig\n ): RunnableBinding<RunInput, AIMessageChunk, CallOptions> {\n const mergedConfig: RunnableConfig = { ...(config || {}) };\n const modelParams = this._modelParams(mergedConfig);\n\n const remainingConfig: RunnableConfig = Object.fromEntries(\n Object.entries(mergedConfig).filter(([k]) => k !== \"configurable\")\n );\n\n remainingConfig.configurable = Object.fromEntries(\n Object.entries(mergedConfig.configurable || {}).filter(\n ([k]) =>\n this._configPrefix &&\n !Object.keys(modelParams).includes(\n this._removePrefix(k, this._configPrefix)\n )\n )\n );\n\n const newConfigurableModel = new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: { ...this._defaultConfig, ...modelParams },\n configurableFields: Array.isArray(this._configurableFields)\n ? [...this._configurableFields]\n : this._configurableFields,\n configPrefix: this._configPrefix,\n queuedMethodOperations: this._queuedMethodOperations,\n });\n\n return new RunnableBinding<RunInput, AIMessageChunk, CallOptions>({\n config: mergedConfig,\n bound: newConfigurableModel,\n });\n }\n\n async invoke(\n input: RunInput,\n options?: CallOptions\n ): Promise<AIMessageChunk> {\n const model = await this._getModelInstance(options);\n const config = ensureConfig(options);\n return model.invoke(input, config);\n }\n\n async stream(\n input: RunInput,\n options?: CallOptions\n ): Promise<IterableReadableStream<AIMessageChunk>> {\n const model = await this._getModelInstance(options);\n const wrappedGenerator = new AsyncGeneratorWithSetup({\n generator: await model.stream(input, options),\n config: options,\n });\n await wrappedGenerator.setup;\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions?: false }\n ): Promise<AIMessageChunk[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions: true }\n ): Promise<(AIMessageChunk | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(AIMessageChunk | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(AIMessageChunk | Error)[]> {\n // We can super this since the base runnable implementation of\n // `.batch` will call `.invoke` on each input.\n return super.batch(inputs, options, batchOptions);\n }\n\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options: CallOptions\n ): AsyncGenerator<AIMessageChunk> {\n const model = await this._getModelInstance(options);\n const config = ensureConfig(options);\n\n yield* model.transform(generator, config);\n }\n\n async *streamLog(\n input: RunInput,\n options?: Partial<CallOptions>,\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): AsyncGenerator<RunLogPatch> {\n const model = await this._getModelInstance(options);\n const config = ensureConfig(options);\n\n yield* model.streamLog(input, config, {\n ...streamOptions,\n _schemaFormat: \"original\",\n includeNames: streamOptions?.includeNames,\n includeTypes: streamOptions?.includeTypes,\n includeTags: streamOptions?.includeTags,\n excludeNames: streamOptions?.excludeNames,\n excludeTypes: streamOptions?.excludeTypes,\n excludeTags: streamOptions?.excludeTags,\n });\n }\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" | \"v2\" },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding?: \"text/event-stream\" | undefined;\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent | Uint8Array> {\n const outerThis = this;\n async function* wrappedGenerator() {\n const model = await outerThis._getModelInstance(options);\n const config = ensureConfig(options);\n const eventStream = model.streamEvents(input, config, streamOptions);\n\n for await (const chunk of eventStream) {\n yield chunk;\n }\n }\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator());\n }\n\n /**\n * Return profiling information for the model.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n if (this._profile) {\n return this._profile;\n }\n const cacheKey = this._getCacheKey({});\n const instance = this._modelInstanceCache.get(cacheKey);\n return instance?.profile ?? {};\n }\n\n /** @internal */\n _getCacheKey(config?: RunnableConfig): string {\n let toStringify = config ?? {};\n if (toStringify.configurable) {\n const { configurable } = toStringify;\n const filtered: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(configurable)) {\n if (!k.startsWith(\"__pregel_\")) {\n filtered[k] = v;\n }\n }\n toStringify = { ...toStringify, configurable: filtered };\n }\n return JSON.stringify(toStringify);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface InitChatModelFields extends Partial<Record<string, any>> {\n modelProvider?: string;\n configurableFields?: string[] | \"any\";\n configPrefix?: string;\n}\n\nexport type ConfigurableFields = \"any\" | string[];\n\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends ConfigurableChatModelCallOptions =\n ConfigurableChatModelCallOptions,\n>(\n model: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fields?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: never;\n configPrefix?: string;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>>;\n\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends ConfigurableChatModelCallOptions =\n ConfigurableChatModelCallOptions,\n>(\n model: never,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: never;\n configPrefix?: string;\n profile?: ModelProfile;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>>;\n\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends ConfigurableChatModelCallOptions =\n ConfigurableChatModelCallOptions,\n>(\n model?: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: ConfigurableFields;\n configPrefix?: string;\n profile?: ModelProfile;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>>;\n\n// ################################# FOR CONTRIBUTORS #################################\n//\n// If adding support for a new provider, please append the provider\n// name to the supported list in the docstring below.\n//\n// ####################################################################################\n\n/**\n * Initialize a ChatModel from the model name and provider.\n * Must have the integration package corresponding to the model provider installed.\n *\n * @template {extends BaseLanguageModelInput = BaseLanguageModelInput} RunInput - The input type for the model.\n * @template {extends ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions} CallOptions - Call options for the model.\n *\n * @param {string | ChatModelProvider} [model] - The name of the model, e.g. \"gpt-4\", \"claude-3-opus-20240229\".\n * Can be prefixed with the model provider, e.g. \"openai:gpt-4\", \"anthropic:claude-3-opus-20240229\".\n * @param {Object} [fields] - Additional configuration options.\n * @param {string} [fields.modelProvider] - The model provider. Supported values include:\n * - openai (@langchain/openai)\n * - anthropic (@langchain/anthropic)\n * - azure_openai (@langchain/openai)\n * - google-vertexai (@langchain/google-vertexai)\n * - google-vertexai-web (@langchain/google-vertexai-web)\n * - google-genai (@langchain/google-genai)\n * - bedrock (@langchain/aws)\n * - cohere (@langchain/cohere)\n * - fireworks (@langchain/community/chat_models/fireworks)\n * - together (@langchain/community/chat_models/togetherai)\n * - mistralai (@langchain/mistralai)\n * - groq (@langchain/groq)\n * - ollama (@langchain/ollama)\n * - perplexity (@langchain/community/chat_models/perplexity)\n * - cerebras (@langchain/cerebras)\n * - deepseek (@langchain/deepseek)\n * - xai (@langchain/xai)\n * @param {string[] | \"any\"} [fields.configurableFields] - Which model parameters are configurable:\n * - undefined: No configurable fields.\n * - \"any\": All fields are configurable. (See Security Note in description)\n * - string[]: Specified fields are configurable.\n * @param {string} [fields.configPrefix] - Prefix for configurable fields at runtime.\n * @param {ModelProfile} [fields.profile] - Overrides the profiling information for the model. If not provided,\n * the profile will be inferred from the inner model instance.\n * @param {Record<string, any>} [fields.params] - Additional keyword args to pass to the ChatModel constructor.\n * @returns {Promise<ConfigurableModel<RunInput, CallOptions>>} A class which extends BaseChatModel.\n * @throws {Error} If modelProvider cannot be inferred or isn't supported.\n * @throws {Error} If the model provider integration package is not installed.\n *\n * @example Initialize non-configurable models\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const gpt4 = await initChatModel(\"openai:gpt-4\", {\n * temperature: 0.25,\n * });\n * const gpt4Result = await gpt4.invoke(\"what's your name\");\n *\n * const claude = await initChatModel(\"anthropic:claude-3-opus-20240229\", {\n * temperature: 0.25,\n * });\n * const claudeResult = await claude.invoke(\"what's your name\");\n *\n * const gemini = await initChatModel(\"gemini-1.5-pro\", {\n * modelProvider: \"google-vertexai\",\n * temperature: 0.25,\n * });\n * const geminiResult = await gemini.invoke(\"what's your name\");\n * ```\n *\n * @example Create a partially configurable model with no default model\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const configurableModel = await initChatModel(undefined, {\n * temperature: 0,\n * configurableFields: [\"model\", \"apiKey\"],\n * });\n *\n * const gpt4Result = await configurableModel.invoke(\"what's your name\", {\n * configurable: {\n * model: \"gpt-4\",\n * },\n * });\n *\n * const claudeResult = await configurableModel.invoke(\"what's your name\", {\n * configurable: {\n * model: \"claude-3-5-sonnet-20240620\",\n * },\n * });\n * ```\n *\n * @example Create a fully configurable model with a default model and a config prefix\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const configurableModelWithDefault = await initChatModel(\"gpt-4\", {\n * modelProvider: \"openai\",\n * configurableFields: \"any\",\n * configPrefix: \"foo\",\n * temperature: 0,\n * });\n *\n * const openaiResult = await configurableModelWithDefault.invoke(\n * \"what's your name\",\n * {\n * configurable: {\n * foo_apiKey: process.env.OPENAI_API_KEY,\n * },\n * }\n * );\n *\n * const claudeResult = await configurableModelWithDefault.invoke(\n * \"what's your name\",\n * {\n * configurable: {\n * foo_model: \"claude-3-5-sonnet-20240620\",\n * foo_modelProvider: \"anthropic\",\n * foo_temperature: 0.6,\n * foo_apiKey: process.env.ANTHROPIC_API_KEY,\n * },\n * }\n * );\n * ```\n *\n * @example Bind tools to a configurable model:\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n * import { z } from \"zod/v3\";\n * import { tool } from \"@langchain/core/tools\";\n *\n * const getWeatherTool = tool(\n * (input) => {\n * // Do something with the input\n * return JSON.stringify(input);\n * },\n * {\n * schema: z\n * .object({\n * location: z\n * .string()\n * .describe(\"The city and state, e.g. San Francisco, CA\"),\n * })\n * .describe(\"Get the current weather in a given location\"),\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * }\n * );\n *\n * const getPopulationTool = tool(\n * (input) => {\n * // Do something with the input\n * return JSON.stringify(input);\n * },\n * {\n * schema: z\n * .object({\n * location: z\n * .string()\n * .describe(\"The city and state, e.g. San Francisco, CA\"),\n * })\n * .describe(\"Get the current population in a given location\"),\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * }\n * );\n *\n * const configurableModel = await initChatModel(\"gpt-4\", {\n * configurableFields: [\"model\", \"modelProvider\", \"apiKey\"],\n * temperature: 0,\n * });\n *\n * const configurableModelWithTools = configurableModel.bindTools([\n * getWeatherTool,\n * getPopulationTool,\n * ]);\n *\n * const configurableToolResult = await configurableModelWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\",\n * {\n * configurable: {\n * apiKey: process.env.OPENAI_API_KEY,\n * },\n * }\n * );\n *\n * const configurableToolResult2 = await configurableModelWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\",\n * {\n * configurable: {\n * model: \"claude-3-5-sonnet-20240620\",\n * apiKey: process.env.ANTHROPIC_API_KEY,\n * },\n * }\n * );\n * ```\n *\n * @example Initialize a model with a custom profile\n * ```typescript\n * import { initChatModel } from \"langchain/chat_models/universal\";\n *\n * const model = await initChatModel(\"gpt-4o-mini\", {\n * profile: {\n * maxInputTokens: 100000,\n * },\n * });\n *\n * @description\n * This function initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * Security Note: Setting `configurableFields` to \"any\" means fields like apiKey, baseUrl, etc.\n * can be altered at runtime, potentially redirecting model requests to a different service/user.\n * Make sure that if you're accepting untrusted configurations, you enumerate the\n * `configurableFields` explicitly.\n *\n * The function will attempt to infer the model provider from the model name if not specified.\n * Certain model name prefixes are associated with specific providers:\n * - gpt-3... or gpt-4... -> openai\n * - claude... -> anthropic\n * - amazon.... -> bedrock\n * - gemini... -> google-vertexai\n * - command... -> cohere\n * - accounts/fireworks... -> fireworks\n *\n * @since 0.2.11\n * @version 0.2.11\n */\nexport async function initChatModel<\n RunInput extends BaseLanguageModelInput = BaseLanguageModelInput,\n CallOptions extends ConfigurableChatModelCallOptions =\n ConfigurableChatModelCallOptions,\n>(\n model?: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fields?: Partial<Record<string, any>> & {\n modelProvider?: string;\n configurableFields?: string[] | \"any\";\n configPrefix?: string;\n profile?: ModelProfile;\n }\n): Promise<ConfigurableModel<RunInput, CallOptions>> {\n // eslint-disable-next-line prefer-const\n let { configurableFields, configPrefix, modelProvider, profile, ...params } =\n {\n configPrefix: \"\",\n ...(fields ?? {}),\n };\n if (modelProvider === undefined && model?.includes(\":\")) {\n const [provider, ...remainingParts] = model.split(\":\");\n const modelComponents =\n remainingParts.length === 0\n ? [provider]\n : [provider, remainingParts.join(\":\")];\n if (SUPPORTED_PROVIDERS.includes(modelComponents[0] as ChatModelProvider)) {\n // eslint-disable-next-line no-param-reassign\n [modelProvider, model] = modelComponents;\n }\n }\n let configurableFieldsCopy = Array.isArray(configurableFields)\n ? [...configurableFields]\n : configurableFields;\n\n if (!model && configurableFieldsCopy === undefined) {\n configurableFieldsCopy = [\"model\", \"modelProvider\"];\n }\n if (configPrefix && configurableFieldsCopy === undefined) {\n console.warn(\n `{ configPrefix: ${configPrefix} } has been set but no fields are configurable. Set ` +\n `{ configurableFields: [...] } to specify the model params that are ` +\n `configurable.`\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const paramsCopy: Record<string, any> = { ...params };\n\n let configurableModel: ConfigurableModel<RunInput, CallOptions>;\n\n if (configurableFieldsCopy === undefined) {\n configurableModel = new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: {\n ...paramsCopy,\n model,\n modelProvider,\n },\n configPrefix,\n profile,\n });\n } else {\n if (model) {\n paramsCopy.model = model;\n }\n if (modelProvider) {\n paramsCopy.modelProvider = modelProvider;\n }\n configurableModel = new ConfigurableModel<RunInput, CallOptions>({\n defaultConfig: paramsCopy,\n configPrefix,\n configurableFields: configurableFieldsCopy,\n profile,\n });\n }\n\n // Initialize the model instance to make sure a profile is available\n await configurableModel._getModelInstance();\n return configurableModel;\n}\n"],"mappings":";;;;;;;;;;;;;;AAoDA,MAAa,wBAAwB;CACnC,QAAQ;EACN,SAAS;EACT,WAAW;CACZ;CACD,WAAW;EACT,SAAS;EACT,WAAW;CACZ;CACD,cAAc;EACZ,SAAS;EACT,WAAW;CACZ;CACD,QAAQ;EACN,SAAS;EACT,WAAW;CACZ;CACD,mBAAmB;EACjB,SAAS;EACT,WAAW;CACZ;CACD,uBAAuB;EACrB,SAAS;EACT,WAAW;CACZ;CACD,gBAAgB;EACd,SAAS;EACT,WAAW;CACZ;CACD,QAAQ;EACN,SAAS;EACT,WAAW;CACZ;CACD,WAAW;EACT,SAAS;EACT,WAAW;CACZ;CACD,SAAS;EACP,SAAS;EACT,WAAW;CACZ;CACD,MAAM;EACJ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,CAAC,UAAU,eAAe,KAAK,IAAI,AAAC;AAC1C,MAAI,oBAAoB,SAAS,gBAAgB,GAAwB,EAEvE,CAAC,eAAe,MAAM,GAAG;CAE5B;CACD,IAAI,yBAAyB,MAAM,QAAQ,mBAAmB,GAC1D,CAAC,GAAG,kBAAmB,IACvB;AAEJ,KAAI,CAAC,SAAS,2BAA2B,QACvC,yBAAyB,CAAC,SAAS,eAAgB;AAErD,KAAI,gBAAgB,2BAA2B,QAC7C,QAAQ,KACN,CAAC,gBAAgB,EAAE,aAAa,oIAAoD,CAEnE,CAClB;CAIH,MAAMC,aAAkC,EAAE,GAAG,OAAQ;CAErD,IAAIC;AAEJ,KAAI,2BAA2B,QAC7B,oBAAoB,IAAI,kBAAyC;EAC/D,eAAe;GACb,GAAG;GACH;GACA;EACD;EACD;EACA;CACD;MACI;AACL,MAAI,OACF,WAAW,QAAQ;AAErB,MAAI,eACF,WAAW,gBAAgB;EAE7B,oBAAoB,IAAI,kBAAyC;GAC/D,eAAe;GACf;GACA,oBAAoB;GACpB;EACD;CACF;CAGD,MAAM,kBAAkB,mBAAmB;AAC3C,QAAO;AACR"}
|
package/dist/hub/base.cjs
CHANGED
|
@@ -11,7 +11,7 @@ const langsmith = require_rolldown_runtime.__toESM(require("langsmith"));
|
|
|
11
11
|
* @returns The URL of the newly pushed prompt in the hub.
|
|
12
12
|
*/
|
|
13
13
|
async function basePush(repoFullName, runnable, options) {
|
|
14
|
-
const client = new langsmith.Client(options);
|
|
14
|
+
const client = options?.client ?? new langsmith.Client(options);
|
|
15
15
|
const payloadOptions = {
|
|
16
16
|
object: runnable,
|
|
17
17
|
parentCommitHash: options?.parentCommitHash,
|
|
@@ -23,8 +23,11 @@ async function basePush(repoFullName, runnable, options) {
|
|
|
23
23
|
return client.pushPrompt(repoFullName, payloadOptions);
|
|
24
24
|
}
|
|
25
25
|
async function basePull(ownerRepoCommit, options) {
|
|
26
|
-
const client = new langsmith.Client(options);
|
|
27
|
-
const promptObject = await client.pullPromptCommit(ownerRepoCommit, {
|
|
26
|
+
const client = options?.client ?? new langsmith.Client(options);
|
|
27
|
+
const promptObject = await client.pullPromptCommit(ownerRepoCommit, {
|
|
28
|
+
includeModel: options?.includeModel,
|
|
29
|
+
skipCache: options?.skipCache
|
|
30
|
+
});
|
|
28
31
|
if (promptObject.manifest.kwargs?.metadata === void 0) promptObject.manifest.kwargs = {
|
|
29
32
|
...promptObject.manifest.kwargs,
|
|
30
33
|
metadata: {}
|
package/dist/hub/base.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["repoFullName: string","runnable: Runnable","options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n }","Client","ownerRepoCommit: string","options?: {
|
|
1
|
+
{"version":3,"file":"base.cjs","names":["repoFullName: string","runnable: Runnable","options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n client?: Client;\n }","Client","ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n skipCache?: boolean;\n client?: Client;\n }","varName: string","message: any","modelClass?: new (...args: any[]) => BaseLanguageModel","modelImportMap: Record<string, any>","optionalImportMap: Record<string, any>","loadedSequence: T"],"sources":["../../src/hub/base.ts"],"sourcesContent":["import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\n\nimport { Client } from \"langsmith\";\nimport type { PromptCommit } from \"langsmith/schemas\";\n\n/**\n * Push a prompt to the hub.\n * If the specified repo doesn't already exist, it will be created.\n * @param repoFullName The full name of the repo.\n * @param runnable The prompt to push.\n * @param options\n * @returns The URL of the newly pushed prompt in the hub.\n */\nexport async function basePush(\n repoFullName: string,\n runnable: Runnable,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n client?: Client;\n }\n): Promise<string> {\n const client = options?.client ?? new Client(options);\n const payloadOptions = {\n object: runnable,\n parentCommitHash: options?.parentCommitHash,\n isPublic: options?.isPublic,\n description: options?.description,\n readme: options?.readme,\n tags: options?.tags,\n };\n return client.pushPrompt(repoFullName, payloadOptions);\n}\n\nexport async function basePull(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n skipCache?: boolean;\n client?: Client;\n }\n): Promise<PromptCommit> {\n const client = options?.client ?? new Client(options);\n\n const promptObject = await client.pullPromptCommit(ownerRepoCommit, {\n includeModel: options?.includeModel,\n skipCache: options?.skipCache,\n });\n\n if (promptObject.manifest.kwargs?.metadata === undefined) {\n promptObject.manifest.kwargs = {\n ...promptObject.manifest.kwargs,\n metadata: {},\n };\n }\n\n promptObject.manifest.kwargs.metadata = {\n ...promptObject.manifest.kwargs.metadata,\n lc_hub_owner: promptObject.owner,\n lc_hub_repo: promptObject.repo,\n lc_hub_commit_hash: promptObject.commit_hash,\n };\n\n // Some nested mustache prompts have improperly parsed variables that include a dot.\n if (promptObject.manifest.kwargs.template_format === \"mustache\") {\n const stripDotNotation = (varName: string) => varName.split(\".\")[0];\n\n const { input_variables } = promptObject.manifest.kwargs;\n if (Array.isArray(input_variables)) {\n promptObject.manifest.kwargs.input_variables =\n input_variables.map(stripDotNotation);\n }\n\n const { messages } = promptObject.manifest.kwargs;\n if (Array.isArray(messages)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n promptObject.manifest.kwargs.messages = messages.map((message: any) => {\n const nestedVars = message?.kwargs?.prompt?.kwargs?.input_variables;\n if (Array.isArray(nestedVars)) {\n message.kwargs.prompt.kwargs.input_variables =\n nestedVars.map(stripDotNotation);\n }\n return message;\n });\n }\n }\n return promptObject;\n}\n\nexport function generateModelImportMap(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel\n) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const modelImportMap: Record<string, any> = {};\n if (modelClass !== undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const modelLcName = (modelClass as any)?.lc_name();\n let importMapKey;\n if (modelLcName === \"ChatOpenAI\") {\n importMapKey = \"chat_models__openai\";\n } else if (modelLcName === \"ChatAnthropic\") {\n importMapKey = \"chat_models__anthropic\";\n } else if (modelLcName === \"ChatAzureOpenAI\") {\n importMapKey = \"chat_models__openai\";\n } else if (modelLcName === \"ChatVertexAI\") {\n importMapKey = \"chat_models__vertexai\";\n } else if (modelLcName === \"ChatGoogleGenerativeAI\") {\n importMapKey = \"chat_models__google_genai\";\n } else if (modelLcName === \"ChatBedrockConverse\") {\n importMapKey = \"chat_models__chat_bedrock_converse\";\n } else if (modelLcName === \"ChatMistralAI\") {\n importMapKey = \"chat_models__mistralai\";\n } else if (modelLcName === \"ChatMistral\") {\n importMapKey = \"chat_models__mistralai\";\n } else if (modelLcName === \"ChatFireworks\") {\n importMapKey = \"chat_models__fireworks\";\n } else if (modelLcName === \"ChatGroq\") {\n importMapKey = \"chat_models__groq\";\n } else {\n throw new Error(\"Received unsupported model class when pulling prompt.\");\n }\n modelImportMap[importMapKey] = {\n ...modelImportMap[importMapKey],\n [modelLcName]: modelClass,\n };\n }\n return modelImportMap;\n}\n\nexport function generateOptionalImportMap(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel\n) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const optionalImportMap: Record<string, any> = {};\n if (modelClass !== undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const modelLcName = (modelClass as any)?.lc_name();\n let optionalImportMapKey;\n if (modelLcName === \"ChatGoogleGenerativeAI\") {\n optionalImportMapKey = \"langchain_google_genai/chat_models\";\n } else if (modelLcName === \"ChatBedrockConverse\") {\n optionalImportMapKey = \"langchain_aws/chat_models\";\n } else if (modelLcName === \"ChatGroq\") {\n optionalImportMapKey = \"langchain_groq/chat_models\";\n }\n if (optionalImportMapKey !== undefined) {\n optionalImportMap[optionalImportMapKey] = {\n [modelLcName]: modelClass,\n };\n }\n }\n return optionalImportMap;\n}\n\nexport function bindOutputSchema<T extends Runnable>(loadedSequence: T) {\n if (\n \"first\" in loadedSequence &&\n loadedSequence.first !== null &&\n typeof loadedSequence.first === \"object\" &&\n \"schema\" in loadedSequence.first &&\n \"last\" in loadedSequence &&\n loadedSequence.last !== null &&\n typeof loadedSequence.last === \"object\"\n ) {\n if (\n \"bound\" in loadedSequence.last &&\n loadedSequence.last.bound !== null &&\n typeof loadedSequence.last.bound === \"object\" &&\n \"withStructuredOutput\" in loadedSequence.last.bound &&\n typeof loadedSequence.last.bound.withStructuredOutput === \"function\"\n ) {\n loadedSequence.last.bound =\n loadedSequence.last.bound.withStructuredOutput(\n loadedSequence.first.schema\n );\n } else if (\n \"withStructuredOutput\" in loadedSequence.last &&\n typeof loadedSequence.last.withStructuredOutput === \"function\"\n ) {\n loadedSequence.last = loadedSequence.last.withStructuredOutput(\n loadedSequence.first.schema\n );\n }\n }\n return loadedSequence;\n}\n"],"mappings":";;;;;;;;;;;;AAcA,eAAsB,SACpBA,cACAC,UACAC,SAUiB;CACjB,MAAM,SAAS,SAAS,UAAU,IAAIC,iBAAO;CAC7C,MAAM,iBAAiB;EACrB,QAAQ;EACR,kBAAkB,SAAS;EAC3B,UAAU,SAAS;EACnB,aAAa,SAAS;EACtB,QAAQ,SAAS;EACjB,MAAM,SAAS;CAChB;AACD,QAAO,OAAO,WAAW,cAAc,eAAe;AACvD;AAED,eAAsB,SACpBC,iBACAC,SAOuB;CACvB,MAAM,SAAS,SAAS,UAAU,IAAIF,iBAAO;CAE7C,MAAM,eAAe,MAAM,OAAO,iBAAiB,iBAAiB;EAClE,cAAc,SAAS;EACvB,WAAW,SAAS;CACrB,EAAC;AAEF,KAAI,aAAa,SAAS,QAAQ,aAAa,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AACD,QAAO;AACR;AAED,SAAgB,0BAEdD,YACA;CAEA,MAAME,oBAAyC,CAAE;AACjD,KAAI,eAAe,QAAW;EAE5B,MAAM,cAAe,YAAoB,SAAS;EAClD,IAAI;AACJ,MAAI,gBAAgB,0BAClB,uBAAuB;WACd,gBAAgB,uBACzB,uBAAuB;WACd,gBAAgB,YACzB,uBAAuB;AAEzB,MAAI,yBAAyB,QAC3B,kBAAkB,wBAAwB,GACvC,cAAc,WAChB;CAEJ;AACD,QAAO;AACR;AAED,SAAgB,iBAAqCC,gBAAmB;AACtE,KACE,WAAW,kBACX,eAAe,UAAU,QACzB,OAAO,eAAe,UAAU,YAChC,YAAY,eAAe,SAC3B,UAAU,kBACV,eAAe,SAAS,QACxB,OAAO,eAAe,SAAS,UAE/B;MACE,WAAW,eAAe,QAC1B,eAAe,KAAK,UAAU,QAC9B,OAAO,eAAe,KAAK,UAAU,YACrC,0BAA0B,eAAe,KAAK,SAC9C,OAAO,eAAe,KAAK,MAAM,yBAAyB,YAE1D,eAAe,KAAK,QAClB,eAAe,KAAK,MAAM,qBACxB,eAAe,MAAM,OACtB;WAEH,0BAA0B,eAAe,QACzC,OAAO,eAAe,KAAK,yBAAyB,YAEpD,eAAe,OAAO,eAAe,KAAK,qBACxC,eAAe,MAAM,OACtB;CACF;AAEH,QAAO;AACR"}
|
package/dist/hub/base.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
2
2
|
import { Runnable } from "@langchain/core/runnables";
|
|
3
|
+
import { Client } from "langsmith";
|
|
3
4
|
|
|
4
5
|
//#region src/hub/base.d.ts
|
|
5
6
|
|
|
@@ -19,6 +20,7 @@ declare function basePush(repoFullName: string, runnable: Runnable, options?: {
|
|
|
19
20
|
description?: string;
|
|
20
21
|
readme?: string;
|
|
21
22
|
tags?: string[];
|
|
23
|
+
client?: Client;
|
|
22
24
|
}): Promise<string>;
|
|
23
25
|
//#endregion
|
|
24
26
|
export { basePush };
|
package/dist/hub/base.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.cts","names":["BaseLanguageModel","Runnable","PromptCommit","basePush","Promise","basePull","generateModelImportMap","Record","generateOptionalImportMap","bindOutputSchema","T"],"sources":["../../src/hub/base.d.ts"],"sourcesContent":["import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport type { PromptCommit } from \"langsmith/schemas\";\n/**\n * Push a prompt to the hub.\n * If the specified repo doesn't already exist, it will be created.\n * @param repoFullName The full name of the repo.\n * @param runnable The prompt to push.\n * @param options\n * @returns The URL of the newly pushed prompt in the hub.\n */\nexport declare function basePush(repoFullName: string, runnable: Runnable, options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n}): Promise<string>;\nexport declare function basePull(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n}): Promise<PromptCommit>;\nexport declare function generateModelImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function generateOptionalImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function bindOutputSchema<T extends Runnable>(loadedSequence: T): T;\n//# sourceMappingURL=base.d.ts.map"],"mappings":"
|
|
1
|
+
{"version":3,"file":"base.d.cts","names":["BaseLanguageModel","Runnable","Client","PromptCommit","basePush","Promise","basePull","generateModelImportMap","Record","generateOptionalImportMap","bindOutputSchema","T"],"sources":["../../src/hub/base.d.ts"],"sourcesContent":["import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport { Client } from \"langsmith\";\nimport type { PromptCommit } from \"langsmith/schemas\";\n/**\n * Push a prompt to the hub.\n * If the specified repo doesn't already exist, it will be created.\n * @param repoFullName The full name of the repo.\n * @param runnable The prompt to push.\n * @param options\n * @returns The URL of the newly pushed prompt in the hub.\n */\nexport declare function basePush(repoFullName: string, runnable: Runnable, options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n client?: Client;\n}): Promise<string>;\nexport declare function basePull(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n skipCache?: boolean;\n client?: Client;\n}): Promise<PromptCommit>;\nexport declare function generateModelImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function generateOptionalImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function bindOutputSchema<T extends Runnable>(loadedSequence: T): T;\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;AAYA;;;;AASW;;;iBATaI,QAAAA,iCAAyCH;;;;;;;;WAQpDC;IACTG"}
|
package/dist/hub/base.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Runnable } from "@langchain/core/runnables";
|
|
2
2
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
3
|
+
import { Client } from "langsmith";
|
|
3
4
|
|
|
4
5
|
//#region src/hub/base.d.ts
|
|
5
6
|
|
|
@@ -19,6 +20,7 @@ declare function basePush(repoFullName: string, runnable: Runnable, options?: {
|
|
|
19
20
|
description?: string;
|
|
20
21
|
readme?: string;
|
|
21
22
|
tags?: string[];
|
|
23
|
+
client?: Client;
|
|
22
24
|
}): Promise<string>;
|
|
23
25
|
//#endregion
|
|
24
26
|
export { basePush };
|
package/dist/hub/base.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","names":["BaseLanguageModel","Runnable","PromptCommit","basePush","Promise","basePull","generateModelImportMap","Record","generateOptionalImportMap","bindOutputSchema","T"],"sources":["../../src/hub/base.d.ts"],"sourcesContent":["import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport type { PromptCommit } from \"langsmith/schemas\";\n/**\n * Push a prompt to the hub.\n * If the specified repo doesn't already exist, it will be created.\n * @param repoFullName The full name of the repo.\n * @param runnable The prompt to push.\n * @param options\n * @returns The URL of the newly pushed prompt in the hub.\n */\nexport declare function basePush(repoFullName: string, runnable: Runnable, options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n}): Promise<string>;\nexport declare function basePull(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n}): Promise<PromptCommit>;\nexport declare function generateModelImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function generateOptionalImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function bindOutputSchema<T extends Runnable>(loadedSequence: T): T;\n//# sourceMappingURL=base.d.ts.map"],"mappings":"
|
|
1
|
+
{"version":3,"file":"base.d.ts","names":["BaseLanguageModel","Runnable","Client","PromptCommit","basePush","Promise","basePull","generateModelImportMap","Record","generateOptionalImportMap","bindOutputSchema","T"],"sources":["../../src/hub/base.d.ts"],"sourcesContent":["import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport { Client } from \"langsmith\";\nimport type { PromptCommit } from \"langsmith/schemas\";\n/**\n * Push a prompt to the hub.\n * If the specified repo doesn't already exist, it will be created.\n * @param repoFullName The full name of the repo.\n * @param runnable The prompt to push.\n * @param options\n * @returns The URL of the newly pushed prompt in the hub.\n */\nexport declare function basePush(repoFullName: string, runnable: Runnable, options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n client?: Client;\n}): Promise<string>;\nexport declare function basePull(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n skipCache?: boolean;\n client?: Client;\n}): Promise<PromptCommit>;\nexport declare function generateModelImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function generateOptionalImportMap(modelClass?: new (...args: any[]) => BaseLanguageModel): Record<string, any>;\nexport declare function bindOutputSchema<T extends Runnable>(loadedSequence: T): T;\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;AAYA;;;;AASW;;;iBATaI,QAAAA,iCAAyCH;;;;;;;;WAQpDC;IACTG"}
|
package/dist/hub/base.js
CHANGED
|
@@ -10,7 +10,7 @@ import { Client } from "langsmith";
|
|
|
10
10
|
* @returns The URL of the newly pushed prompt in the hub.
|
|
11
11
|
*/
|
|
12
12
|
async function basePush(repoFullName, runnable, options) {
|
|
13
|
-
const client = new Client(options);
|
|
13
|
+
const client = options?.client ?? new Client(options);
|
|
14
14
|
const payloadOptions = {
|
|
15
15
|
object: runnable,
|
|
16
16
|
parentCommitHash: options?.parentCommitHash,
|
|
@@ -22,8 +22,11 @@ async function basePush(repoFullName, runnable, options) {
|
|
|
22
22
|
return client.pushPrompt(repoFullName, payloadOptions);
|
|
23
23
|
}
|
|
24
24
|
async function basePull(ownerRepoCommit, options) {
|
|
25
|
-
const client = new Client(options);
|
|
26
|
-
const promptObject = await client.pullPromptCommit(ownerRepoCommit, {
|
|
25
|
+
const client = options?.client ?? new Client(options);
|
|
26
|
+
const promptObject = await client.pullPromptCommit(ownerRepoCommit, {
|
|
27
|
+
includeModel: options?.includeModel,
|
|
28
|
+
skipCache: options?.skipCache
|
|
29
|
+
});
|
|
27
30
|
if (promptObject.manifest.kwargs?.metadata === void 0) promptObject.manifest.kwargs = {
|
|
28
31
|
...promptObject.manifest.kwargs,
|
|
29
32
|
metadata: {}
|
package/dist/hub/base.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":["repoFullName: string","runnable: Runnable","options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n }","ownerRepoCommit: string","options?: {
|
|
1
|
+
{"version":3,"file":"base.js","names":["repoFullName: string","runnable: Runnable","options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n client?: Client;\n }","ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n skipCache?: boolean;\n client?: Client;\n }","varName: string","message: any","modelClass?: new (...args: any[]) => BaseLanguageModel","modelImportMap: Record<string, any>","optionalImportMap: Record<string, any>","loadedSequence: T"],"sources":["../../src/hub/base.ts"],"sourcesContent":["import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\n\nimport { Client } from \"langsmith\";\nimport type { PromptCommit } from \"langsmith/schemas\";\n\n/**\n * Push a prompt to the hub.\n * If the specified repo doesn't already exist, it will be created.\n * @param repoFullName The full name of the repo.\n * @param runnable The prompt to push.\n * @param options\n * @returns The URL of the newly pushed prompt in the hub.\n */\nexport async function basePush(\n repoFullName: string,\n runnable: Runnable,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n parentCommitHash?: string;\n isPublic?: boolean;\n description?: string;\n readme?: string;\n tags?: string[];\n client?: Client;\n }\n): Promise<string> {\n const client = options?.client ?? new Client(options);\n const payloadOptions = {\n object: runnable,\n parentCommitHash: options?.parentCommitHash,\n isPublic: options?.isPublic,\n description: options?.description,\n readme: options?.readme,\n tags: options?.tags,\n };\n return client.pushPrompt(repoFullName, payloadOptions);\n}\n\nexport async function basePull(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n skipCache?: boolean;\n client?: Client;\n }\n): Promise<PromptCommit> {\n const client = options?.client ?? new Client(options);\n\n const promptObject = await client.pullPromptCommit(ownerRepoCommit, {\n includeModel: options?.includeModel,\n skipCache: options?.skipCache,\n });\n\n if (promptObject.manifest.kwargs?.metadata === undefined) {\n promptObject.manifest.kwargs = {\n ...promptObject.manifest.kwargs,\n metadata: {},\n };\n }\n\n promptObject.manifest.kwargs.metadata = {\n ...promptObject.manifest.kwargs.metadata,\n lc_hub_owner: promptObject.owner,\n lc_hub_repo: promptObject.repo,\n lc_hub_commit_hash: promptObject.commit_hash,\n };\n\n // Some nested mustache prompts have improperly parsed variables that include a dot.\n if (promptObject.manifest.kwargs.template_format === \"mustache\") {\n const stripDotNotation = (varName: string) => varName.split(\".\")[0];\n\n const { input_variables } = promptObject.manifest.kwargs;\n if (Array.isArray(input_variables)) {\n promptObject.manifest.kwargs.input_variables =\n input_variables.map(stripDotNotation);\n }\n\n const { messages } = promptObject.manifest.kwargs;\n if (Array.isArray(messages)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n promptObject.manifest.kwargs.messages = messages.map((message: any) => {\n const nestedVars = message?.kwargs?.prompt?.kwargs?.input_variables;\n if (Array.isArray(nestedVars)) {\n message.kwargs.prompt.kwargs.input_variables =\n nestedVars.map(stripDotNotation);\n }\n return message;\n });\n }\n }\n return promptObject;\n}\n\nexport function generateModelImportMap(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel\n) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const modelImportMap: Record<string, any> = {};\n if (modelClass !== undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const modelLcName = (modelClass as any)?.lc_name();\n let importMapKey;\n if (modelLcName === \"ChatOpenAI\") {\n importMapKey = \"chat_models__openai\";\n } else if (modelLcName === \"ChatAnthropic\") {\n importMapKey = \"chat_models__anthropic\";\n } else if (modelLcName === \"ChatAzureOpenAI\") {\n importMapKey = \"chat_models__openai\";\n } else if (modelLcName === \"ChatVertexAI\") {\n importMapKey = \"chat_models__vertexai\";\n } else if (modelLcName === \"ChatGoogleGenerativeAI\") {\n importMapKey = \"chat_models__google_genai\";\n } else if (modelLcName === \"ChatBedrockConverse\") {\n importMapKey = \"chat_models__chat_bedrock_converse\";\n } else if (modelLcName === \"ChatMistralAI\") {\n importMapKey = \"chat_models__mistralai\";\n } else if (modelLcName === \"ChatMistral\") {\n importMapKey = \"chat_models__mistralai\";\n } else if (modelLcName === \"ChatFireworks\") {\n importMapKey = \"chat_models__fireworks\";\n } else if (modelLcName === \"ChatGroq\") {\n importMapKey = \"chat_models__groq\";\n } else {\n throw new Error(\"Received unsupported model class when pulling prompt.\");\n }\n modelImportMap[importMapKey] = {\n ...modelImportMap[importMapKey],\n [modelLcName]: modelClass,\n };\n }\n return modelImportMap;\n}\n\nexport function generateOptionalImportMap(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel\n) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const optionalImportMap: Record<string, any> = {};\n if (modelClass !== undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const modelLcName = (modelClass as any)?.lc_name();\n let optionalImportMapKey;\n if (modelLcName === \"ChatGoogleGenerativeAI\") {\n optionalImportMapKey = \"langchain_google_genai/chat_models\";\n } else if (modelLcName === \"ChatBedrockConverse\") {\n optionalImportMapKey = \"langchain_aws/chat_models\";\n } else if (modelLcName === \"ChatGroq\") {\n optionalImportMapKey = \"langchain_groq/chat_models\";\n }\n if (optionalImportMapKey !== undefined) {\n optionalImportMap[optionalImportMapKey] = {\n [modelLcName]: modelClass,\n };\n }\n }\n return optionalImportMap;\n}\n\nexport function bindOutputSchema<T extends Runnable>(loadedSequence: T) {\n if (\n \"first\" in loadedSequence &&\n loadedSequence.first !== null &&\n typeof loadedSequence.first === \"object\" &&\n \"schema\" in loadedSequence.first &&\n \"last\" in loadedSequence &&\n loadedSequence.last !== null &&\n typeof loadedSequence.last === \"object\"\n ) {\n if (\n \"bound\" in loadedSequence.last &&\n loadedSequence.last.bound !== null &&\n typeof loadedSequence.last.bound === \"object\" &&\n \"withStructuredOutput\" in loadedSequence.last.bound &&\n typeof loadedSequence.last.bound.withStructuredOutput === \"function\"\n ) {\n loadedSequence.last.bound =\n loadedSequence.last.bound.withStructuredOutput(\n loadedSequence.first.schema\n );\n } else if (\n \"withStructuredOutput\" in loadedSequence.last &&\n typeof loadedSequence.last.withStructuredOutput === \"function\"\n ) {\n loadedSequence.last = loadedSequence.last.withStructuredOutput(\n loadedSequence.first.schema\n );\n }\n }\n return loadedSequence;\n}\n"],"mappings":";;;;;;;;;;;AAcA,eAAsB,SACpBA,cACAC,UACAC,SAUiB;CACjB,MAAM,SAAS,SAAS,UAAU,IAAI,OAAO;CAC7C,MAAM,iBAAiB;EACrB,QAAQ;EACR,kBAAkB,SAAS;EAC3B,UAAU,SAAS;EACnB,aAAa,SAAS;EACtB,QAAQ,SAAS;EACjB,MAAM,SAAS;CAChB;AACD,QAAO,OAAO,WAAW,cAAc,eAAe;AACvD;AAED,eAAsB,SACpBC,iBACAC,SAOuB;CACvB,MAAM,SAAS,SAAS,UAAU,IAAI,OAAO;CAE7C,MAAM,eAAe,MAAM,OAAO,iBAAiB,iBAAiB;EAClE,cAAc,SAAS;EACvB,WAAW,SAAS;CACrB,EAAC;AAEF,KAAI,aAAa,SAAS,QAAQ,aAAa,QAC7C,aAAa,SAAS,SAAS;EAC7B,GAAG,aAAa,SAAS;EACzB,UAAU,CAAE;CACb;CAGH,aAAa,SAAS,OAAO,WAAW;EACtC,GAAG,aAAa,SAAS,OAAO;EAChC,cAAc,aAAa;EAC3B,aAAa,aAAa;EAC1B,oBAAoB,aAAa;CAClC;AAGD,KAAI,aAAa,SAAS,OAAO,oBAAoB,YAAY;EAC/D,MAAM,mBAAmB,CAACC,YAAoB,QAAQ,MAAM,IAAI,CAAC;EAEjE,MAAM,EAAE,iBAAiB,GAAG,aAAa,SAAS;AAClD,MAAI,MAAM,QAAQ,gBAAgB,EAChC,aAAa,SAAS,OAAO,kBAC3B,gBAAgB,IAAI,iB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AU,kBACV,eAAe,SAAS,QACxB,OAAO,eAAe,SAAS,UAE/B;MACE,WAAW,eAAe,QAC1B,eAAe,KAAK,UAAU,QAC9B,OAAO,eAAe,KAAK,UAAU,YACrC,0BAA0B,eAAe,KAAK,SAC9C,OAAO,eAAe,KAAK,MAAM,yBAAyB,YAE1D,eAAe,KAAK,QAClB,eAAe,KAAK,MAAM,qBACxB,eAAe,MAAM,OACtB;WAEH,0BAA0B,eAAe,QACzC,OAAO,eAAe,KAAK,yBAAyB,YAEpD,eAAe,OAAO,eAAe,KAAK,qBACxC,eAAe,MAAM,OACtB;CACF;AAEH,QAAO;AACR"}
|
package/dist/hub/index.cjs
CHANGED
|
@@ -23,6 +23,8 @@ const require_base = require('./base.cjs');
|
|
|
23
23
|
* `includeModel` is `true`.
|
|
24
24
|
* @param options.secretsFromEnv Whether to load secrets from environment variables.
|
|
25
25
|
* Use with caution and only with trusted prompts.
|
|
26
|
+
* @param options.client LangSmith client to use when pulling the prompt
|
|
27
|
+
* @param options.skipCache Whether to skip the global default cache when pulling the prompt
|
|
26
28
|
* @returns
|
|
27
29
|
*/
|
|
28
30
|
async function pull(ownerRepoCommit, options) {
|
package/dist/hub/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }","basePull","load","generateOptionalImportMap","generateModelImportMap","bindOutputSchema","e: any"],"sources":["../../src/hub/index.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { load } from \"../load/index.js\";\nimport {\n basePush,\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\n\nexport { basePush as push };\n\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n try {\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(options?.modelClass),\n generateModelImportMap(options?.modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (options?.includeModel) {\n throw new Error(\n [\n e.message,\n \"\",\n `To load prompts with an associated non-OpenAI model, you must use the \"langchain/hub/node\" entrypoint, or pass a \"modelClass\" parameter like this:`,\n \"\",\n \"```\",\n `import { pull } from \"langchain/hub\";`,\n `import { ChatAnthropic } from \"@langchain/anthropic\";`,\n \"\",\n `const prompt = await pull(\"my-prompt\", {`,\n ` includeModel: true,`,\n ` modelClass: ChatAnthropic,`,\n `});`,\n \"```\",\n ].join(\"\\n\")\n );\n } else {\n throw e;\n }\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["ownerRepoCommit: string","options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n client?: Client;\n skipCache?: boolean;\n }","basePull","load","generateOptionalImportMap","generateModelImportMap","bindOutputSchema","e: any"],"sources":["../../src/hub/index.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { Client } from \"langsmith\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { load } from \"../load/index.js\";\nimport {\n basePush,\n basePull,\n generateModelImportMap,\n generateOptionalImportMap,\n bindOutputSchema,\n} from \"./base.js\";\n\nexport { basePush as push };\n\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @param options.client LangSmith client to use when pulling the prompt\n * @param options.skipCache Whether to skip the global default cache when pulling the prompt\n * @returns\n */\nexport async function pull<T extends Runnable>(\n ownerRepoCommit: string,\n options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n client?: Client;\n skipCache?: boolean;\n }\n) {\n const promptObject = await basePull(ownerRepoCommit, options);\n try {\n const loadedPrompt = await load<T>(\n JSON.stringify(promptObject.manifest),\n options?.secrets,\n generateOptionalImportMap(options?.modelClass),\n generateModelImportMap(options?.modelClass),\n options?.secretsFromEnv\n );\n return bindOutputSchema(loadedPrompt);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (options?.includeModel) {\n throw new Error(\n [\n e.message,\n \"\",\n `To load prompts with an associated non-OpenAI model, you must use the \"langchain/hub/node\" entrypoint, or pass a \"modelClass\" parameter like this:`,\n \"\",\n \"```\",\n `import { pull } from \"langchain/hub\";`,\n `import { ChatAnthropic } from \"@langchain/anthropic\";`,\n \"\",\n `const prompt = await pull(\"my-prompt\", {`,\n ` includeModel: true,`,\n ` modelClass: ChatAnthropic,`,\n `});`,\n \"```\",\n ].join(\"\\n\")\n );\n } else {\n throw e;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,eAAsB,KACpBA,iBACAC,SAWA;CACA,MAAM,eAAe,MAAMC,sBAAS,iBAAiB,QAAQ;AAC7D,KAAI;EACF,MAAM,eAAe,MAAMC,wBACzB,KAAK,UAAU,aAAa,SAAS,EACrC,SAAS,SACTC,uCAA0B,SAAS,WAAW,EAC9CC,oCAAuB,SAAS,WAAW,EAC3C,SAAS,eACV;AACD,SAAOC,8BAAiB,aAAa;CAEtC,SAAQC,GAAQ;AACf,MAAI,SAAS,aACX,OAAM,IAAI,MACR;GACE,EAAE;GACF;GACA,CAAC,kJAAkJ,CAAC;GACpJ;GACA;GACA,CAAC,qCAAqC,CAAC;GACvC,CAAC,qDAAqD,CAAC;GACvD;GACA,CAAC,wCAAwC,CAAC;GAC1C,CAAC,qBAAqB,CAAC;GACvB,CAAC,4BAA4B,CAAC;GAC9B,CAAC,GAAG,CAAC;GACL;EACD,EAAC,KAAK,KAAK;MAGd,OAAM;CAET;AACF"}
|
package/dist/hub/index.d.cts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { basePush } from "./base.cjs";
|
|
2
2
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
3
3
|
import { Runnable } from "@langchain/core/runnables";
|
|
4
|
+
import { Client } from "langsmith";
|
|
4
5
|
|
|
5
6
|
//#region src/hub/index.d.ts
|
|
6
7
|
|
|
@@ -25,6 +26,8 @@ import { Runnable } from "@langchain/core/runnables";
|
|
|
25
26
|
* `includeModel` is `true`.
|
|
26
27
|
* @param options.secretsFromEnv Whether to load secrets from environment variables.
|
|
27
28
|
* Use with caution and only with trusted prompts.
|
|
29
|
+
* @param options.client LangSmith client to use when pulling the prompt
|
|
30
|
+
* @param options.skipCache Whether to skip the global default cache when pulling the prompt
|
|
28
31
|
* @returns
|
|
29
32
|
*/
|
|
30
33
|
declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {
|
|
@@ -34,6 +37,8 @@ declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {
|
|
|
34
37
|
modelClass?: new (...args: any[]) => BaseLanguageModel;
|
|
35
38
|
secrets?: Record<string, string>;
|
|
36
39
|
secretsFromEnv?: boolean;
|
|
40
|
+
client?: Client;
|
|
41
|
+
skipCache?: boolean;
|
|
37
42
|
}): Promise<T>;
|
|
38
43
|
//#endregion
|
|
39
44
|
export { pull, basePush as push };
|
package/dist/hub/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":["Runnable","BaseLanguageModel","basePush","push","pull","T","Record","Promise"],"sources":["../../src/hub/index.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { basePush } from \"./base.js\";\nexport { basePush as push };\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":["Runnable","Client","BaseLanguageModel","basePush","push","pull","T","Record","Promise"],"sources":["../../src/hub/index.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { Client } from \"langsmith\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { basePush } from \"./base.js\";\nexport { basePush as push };\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @param options.client LangSmith client to use when pulling the prompt\n * @param options.skipCache Whether to skip the global default cache when pulling the prompt\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n client?: Client;\n skipCache?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;AA8BA;;;;;;;AASW;;;;;;;;;;;;;;;;;iBATaK,eAAeL;;;;uCAIEE;YAC3BK;;WAEDN;;IAETO,QAAQF"}
|
package/dist/hub/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { basePush } from "./base.js";
|
|
2
2
|
import { Runnable } from "@langchain/core/runnables";
|
|
3
3
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
4
|
+
import { Client } from "langsmith";
|
|
4
5
|
|
|
5
6
|
//#region src/hub/index.d.ts
|
|
6
7
|
|
|
@@ -25,6 +26,8 @@ import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
|
25
26
|
* `includeModel` is `true`.
|
|
26
27
|
* @param options.secretsFromEnv Whether to load secrets from environment variables.
|
|
27
28
|
* Use with caution and only with trusted prompts.
|
|
29
|
+
* @param options.client LangSmith client to use when pulling the prompt
|
|
30
|
+
* @param options.skipCache Whether to skip the global default cache when pulling the prompt
|
|
28
31
|
* @returns
|
|
29
32
|
*/
|
|
30
33
|
declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {
|
|
@@ -34,6 +37,8 @@ declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {
|
|
|
34
37
|
modelClass?: new (...args: any[]) => BaseLanguageModel;
|
|
35
38
|
secrets?: Record<string, string>;
|
|
36
39
|
secretsFromEnv?: boolean;
|
|
40
|
+
client?: Client;
|
|
41
|
+
skipCache?: boolean;
|
|
37
42
|
}): Promise<T>;
|
|
38
43
|
//#endregion
|
|
39
44
|
export { pull, basePush as push };
|
package/dist/hub/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["Runnable","BaseLanguageModel","basePush","push","pull","T","Record","Promise"],"sources":["../../src/hub/index.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { basePush } from \"./base.js\";\nexport { basePush as push };\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["Runnable","Client","BaseLanguageModel","basePush","push","pull","T","Record","Promise"],"sources":["../../src/hub/index.d.ts"],"sourcesContent":["import { Runnable } from \"@langchain/core/runnables\";\nimport type { Client } from \"langsmith\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { basePush } from \"./base.js\";\nexport { basePush as push };\n/**\n * Pull a prompt from the hub.\n *\n * @param ownerRepoCommit The name of the repo containing the prompt, as well as an optional commit hash separated by a slash.\n * @param options.apiKey LangSmith API key to use when pulling the prompt\n * @param options.apiUrl LangSmith API URL to use when pulling the prompt\n * @param options.includeModel Whether to also instantiate and attach a model instance to the prompt,\n * if the prompt has associated model metadata. If set to true, invoking the resulting pulled prompt will\n * also invoke the instantiated model. For non-OpenAI models, you must also set \"modelClass\" to the\n * correct class of the model.\n * @param options.modelClass If includeModel is true, the class of the model to instantiate. Required\n * for non-OpenAI models. If you are running in Node or another environment that supports dynamic imports,\n * you may instead import this function from \"langchain/hub/node\" and pass \"includeModel: true\" instead\n * of specifying this parameter.\n * @param options.secrets A map of secrets to use when loading, e.g.\n * {'OPENAI_API_KEY': 'sk-...'}`.\n * If a secret is not found in the map, it will be loaded from the\n * environment if `secrets_from_env` is `True`. Should only be needed when\n * `includeModel` is `true`.\n * @param options.secretsFromEnv Whether to load secrets from environment variables.\n * Use with caution and only with trusted prompts.\n * @param options.client LangSmith client to use when pulling the prompt\n * @param options.skipCache Whether to skip the global default cache when pulling the prompt\n * @returns\n */\nexport declare function pull<T extends Runnable>(ownerRepoCommit: string, options?: {\n apiKey?: string;\n apiUrl?: string;\n includeModel?: boolean;\n modelClass?: new (...args: any[]) => BaseLanguageModel;\n secrets?: Record<string, string>;\n secretsFromEnv?: boolean;\n client?: Client;\n skipCache?: boolean;\n}): Promise<T>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;AA8BA;;;;;;;AASW;;;;;;;;;;;;;;;;;iBATaK,eAAeL;;;;uCAIEE;YAC3BK;;WAEDN;;IAETO,QAAQF"}
|
package/dist/hub/index.js
CHANGED
|
@@ -23,6 +23,8 @@ import { basePull, basePush, bindOutputSchema, generateModelImportMap, generateO
|
|
|
23
23
|
* `includeModel` is `true`.
|
|
24
24
|
* @param options.secretsFromEnv Whether to load secrets from environment variables.
|
|
25
25
|
* Use with caution and only with trusted prompts.
|
|
26
|
+
* @param options.client LangSmith client to use when pulling the prompt
|
|
27
|
+
* @param options.skipCache Whether to skip the global default cache when pulling the prompt
|
|
26
28
|
* @returns
|
|
27
29
|
*/
|
|
28
30
|
async function pull(ownerRepoCommit, options) {
|