langchain 1.2.1 → 1.2.3-dev-1766726832377
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 +11 -0
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/index.cjs +11 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/tools/browser.cjs +81 -0
- package/dist/tools/browser.cjs.map +1 -0
- package/dist/tools/browser.d.cts +96 -0
- package/dist/tools/browser.d.cts.map +1 -0
- package/dist/tools/browser.d.ts +96 -0
- package/dist/tools/browser.d.ts.map +1 -0
- package/dist/tools/browser.js +80 -0
- package/dist/tools/browser.js.map +1 -0
- package/package.json +5 -5
- package/chat_models/universal.cjs +0 -1
- package/chat_models/universal.d.cts +0 -1
- package/chat_models/universal.d.ts +0 -1
- package/chat_models/universal.js +0 -1
- package/hub/node.cjs +0 -1
- package/hub/node.d.cts +0 -1
- package/hub/node.d.ts +0 -1
- package/hub/node.js +0 -1
- package/hub.cjs +0 -1
- package/hub.d.cts +0 -1
- package/hub.d.ts +0 -1
- package/hub.js +0 -1
- package/load/serializable.cjs +0 -1
- package/load/serializable.d.cts +0 -1
- package/load/serializable.d.ts +0 -1
- package/load/serializable.js +0 -1
- package/load.cjs +0 -1
- package/load.d.cts +0 -1
- package/load.d.ts +0 -1
- package/load.js +0 -1
- package/storage/encoder_backed.cjs +0 -1
- package/storage/encoder_backed.d.cts +0 -1
- package/storage/encoder_backed.d.ts +0 -1
- package/storage/encoder_backed.js +0 -1
- package/storage/file_system.cjs +0 -1
- package/storage/file_system.d.cts +0 -1
- package/storage/file_system.d.ts +0 -1
- package/storage/file_system.js +0 -1
- package/storage/in_memory.cjs +0 -1
- package/storage/in_memory.d.cts +0 -1
- package/storage/in_memory.d.ts +0 -1
- package/storage/in_memory.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","LanguageModelLike","BaseMessage","SystemMessage","BaseCheckpointSaver","BaseStore","Messages","ClientTool","ServerTool","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","JumpToTarget","N","Interrupt","TValue","BuiltInState","UserInput","TStateSchema","ToolCall","Record","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","StateSchema","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","T","Rest","A","WithStateGraphNodes","K","Graph","SD","S","U","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage, SystemMessage } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput } from \"./middleware/types.js\";\nimport type { JumpToTarget } from \"./constants.js\";\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState {\n messages: BaseMessage[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent 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 * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n *\n * **Use a `string`** for simple, static system prompts. This is the most common use case\n * and works well with template literals for dynamic content. When a string is provided,\n * it's converted to a single text block internally.\n *\n * **Use a `SystemMessage`** when you need advanced features that require structured content:\n * - **Anthropic cache control**: Use `SystemMessage` with array content to enable per-block\n * cache control settings (e.g., `cache_control: { type: \"ephemeral\" }`). This allows you\n * to have different cache settings for different parts of your system prompt.\n * - **Multiple content blocks**: When you need multiple text blocks with different metadata\n * or formatting requirements.\n * - **Integration with existing code**: When working with code that already produces\n * `SystemMessage` instances.\n *\n * @example Using a string (recommended for most cases)\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant.\",\n * // ...\n * });\n * ```\n *\n * @example Using a string with template literals\n * ```ts\n * const userRole = \"premium\";\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a helpful assistant for ${userRole} users.`,\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage with cache control (Anthropic)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage({\n * content: [\n * {\n * type: \"text\",\n * text: \"You are a helpful assistant.\",\n * },\n * {\n * type: \"text\",\n * text: \"Today's date is 2024-06-01.\",\n * cache_control: { type: \"ephemeral\" },\n * },\n * ],\n * }),\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage (simple)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage(\"You are a helpful assistant.\"),\n * // ...\n * });\n * ```\n */\n systemPrompt?: string | SystemMessage;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware<any, any, any>[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;;KAUYuB,CAAAA,UAAWrB;;AAAvB;AAIA;AAUiBwB,UAVAF,SAUY,CAAA,SAAA,OAAA,CAAA,CAAA;EACflB;;;EAUW,EAAA,EAAA,MAAA;EAKbqB;;;EAAgHC,KAAAA,EAlBjHH,MAkBiHG;;AAC9GlB,UAjBGgB,YAAAA,CAiBHhB;EAAQ,QAAA,EAhBRJ,WAgBQ,EAAA;EAKLuB,aAAQ,CAAA,EApBLL,SAoBK,EAYfM;EAaOC;AAiBjB;AAIA;AAkBA;;;;;EAAgNX,MAAAA,CAAAA,EA3EnME,YA2EmMF;;;;;AAAwHnB,KAtE5T0B,SAsE4T1B,CAAAA,qBAtE7RmB,iBAsE6RnB,GAtEzQD,gBAsEyQC,GAAAA,SAAAA,GAAAA,SAAAA,CAAAA,GAtE7NoB,gBAsE6NpB,CAtE5M2B,YAsE4M3B,CAAAA,GAAAA;EAA4BgB,QAAAA,EArEtVP,QAqEsVO;CAAmBA;;;;AAA+FkB,UAhErcN,UAAAA,CAgEqcM;EAAbrB;;;EAAkFI,EAAAA,EAAAA,MAAAA;EAwBvgBb;;;EA4FQE,IAAAA,EAAAA,MAAAA;EA6CV6B;;;EA4CN3B,IAAAA,EAjQFqB,MAiQErB,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA;EAsDS6B;;;EA2BG,MAAA,CAAA,EAAA,OAAA;EAiBZE;;;EAAqFvC,KAAAA,CAAAA,EAAAA,MAAAA;;;;;AAA4FuC,UAtV5KT,UAAAA,CAsV4KS;EAA6BG;AAAC;AAC3N;EAA2DG,EAAAA,EAAAA,MAAAA;EAAc1C;;;EAA+F6C,MAAAA,EAAAA,GAAAA;EAAG1B;;;EAAU4B,KAAAA,CAAAA,EAAAA,MAAAA;;;AAArB;;KAtUpJnB,MAAAA,sCAA4C7B;;;;UAIvC8B,gBAAAA;;;;;;;;QAQPH;;;;;;;;;;KAUEI,iDAAiDJ,sBAAsBA,yCAAyCV,oBAAoBpB,gEAAgEoB,oBAAoBpB,mBAAmBoB,wCAAwCnB,eAAekC,0BAA0BlC,4BAA4BgB,mBAAmBA,qBAAqBJ,iBAAiBE,kBAAkBoB,0BAA0BrB,aAAaqB,0BAA0BnB,iBAAiBmB,0BAA0BjB;;;;;;;;;;;;;;;;;;;;;;;;kBAwBvgBb;;;;;;;;;;;;;;;;;;;;;;WAsBPO,aAAaD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0BAsEEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gBA6CV6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;;;;iBAKD7B;;;;;UAKPC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS6B;;;;;;;wBAOKnB;;;;;;;;;;;;;;;;;;;;WAoBboB;;;;;;;;;;;;;;;;;KAiBDC,wCAAwCvC,yBAAyBwC,oBAAoBxC,0CAA0CyC,sBAAsBzC,wBAAwB0C,IAAIH,qBAAqBE,QAAQC;KAC9MC,+CAA+CE,cAAc1C,6EAA6EA,WAAW2C,IAAIC,GAAGC,GAAG1B,IAAIsB,GAAGK,GAAGC,GAAGC"}
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","LanguageModelLike","BaseMessage","SystemMessage","BaseCheckpointSaver","BaseStore","Messages","ClientTool","ServerTool","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","JumpToTarget","N","Interrupt","TValue","BuiltInState","UserInput","TStateSchema","ToolCall","Record","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","StateSchema","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","T","Rest","A","WithStateGraphNodes","K","Graph","SD","S","U","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage, SystemMessage } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput } from \"./middleware/types.js\";\nimport type { JumpToTarget } from \"./constants.js\";\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState {\n messages: BaseMessage[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent 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 * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n *\n * **Use a `string`** for simple, static system prompts. This is the most common use case\n * and works well with template literals for dynamic content. When a string is provided,\n * it's converted to a single text block internally.\n *\n * **Use a `SystemMessage`** when you need advanced features that require structured content:\n * - **Anthropic cache control**: Use `SystemMessage` with array content to enable per-block\n * cache control settings (e.g., `cache_control: { type: \"ephemeral\" }`). This allows you\n * to have different cache settings for different parts of your system prompt.\n * - **Multiple content blocks**: When you need multiple text blocks with different metadata\n * or formatting requirements.\n * - **Integration with existing code**: When working with code that already produces\n * `SystemMessage` instances.\n *\n * @example Using a string (recommended for most cases)\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant.\",\n * // ...\n * });\n * ```\n *\n * @example Using a string with template literals\n * ```ts\n * const userRole = \"premium\";\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a helpful assistant for ${userRole} users.`,\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage with cache control (Anthropic)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage({\n * content: [\n * {\n * type: \"text\",\n * text: \"You are a helpful assistant.\",\n * },\n * {\n * type: \"text\",\n * text: \"Today's date is 2024-06-01.\",\n * cache_control: { type: \"ephemeral\" },\n * },\n * ],\n * }),\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage (simple)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage(\"You are a helpful assistant.\"),\n * // ...\n * });\n * ```\n */\n systemPrompt?: string | SystemMessage;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware<any, any, any>[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;;KAUYuB,CAAAA,UAAWrB;;AAAvB;AAIA;AAUiBwB,UAVAF,SAUY,CAAA,SAAA,OAAA,CAAA,CAAA;EACflB;;;EAUW,EAAA,EAAA,MAAA;EAKbqB;;;EAAgHC,KAAAA,EAlBjHH,MAkBiHG;;AAC9GlB,UAjBGgB,YAAAA,CAiBHhB;EAAQ,QAAA,EAhBRJ,WAgBQ,EAAA;EAKLuB,aAAQ,CAAA,EApBLL,SAgCVM,EAAAA;EAaOC;AAiBjB;AAIA;AAkBA;;;;;EAAgNX,MAAAA,CAAAA,EA3EnME,YA2EmMF;;;;;AAAwHnB,KAtE5T0B,SAsE4T1B,CAAAA,qBAtE7RmB,iBAsE6RnB,GAtEzQD,gBAsEyQC,GAAAA,SAAAA,GAAAA,SAAAA,CAAAA,GAtE7NoB,gBAsE6NpB,CAtE5M2B,YAsE4M3B,CAAAA,GAAAA;EAA4BgB,QAAAA,EArEtVP,QAqEsVO;CAAmBA;;;;AAA+FkB,UAhErcN,UAAAA,CAgEqcM;EAAbrB;;;EAAkFI,EAAAA,EAAAA,MAAAA;EAwBvgBb;;;EA4FQE,IAAAA,EAAAA,MAAAA;EA6CV6B;;;EA4CN3B,IAAAA,EAjQFqB,MAiQErB,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA;EAsDS6B;;;EA2BG,MAAA,CAAA,EAAA,OAAA;EAiBZE;;;EAAqFvC,KAAAA,CAAAA,EAAAA,MAAAA;;;;;AAA4FuC,UAtV5KT,UAAAA,CAsV4KS;EAA6BG;AAAC;AAC3N;EAA2DG,EAAAA,EAAAA,MAAAA;EAAc1C;;;EAA+F6C,MAAAA,EAAAA,GAAAA;EAAG1B;;;EAAU4B,KAAAA,CAAAA,EAAAA,MAAAA;;;AAArB;;KAtUpJnB,MAAAA,sCAA4C7B;;;;UAIvC8B,gBAAAA;;;;;;;;QAQPH;;;;;;;;;;KAUEI,iDAAiDJ,sBAAsBA,yCAAyCV,oBAAoBpB,gEAAgEoB,oBAAoBpB,mBAAmBoB,wCAAwCnB,eAAekC,0BAA0BlC,4BAA4BgB,mBAAmBA,qBAAqBJ,iBAAiBE,kBAAkBoB,0BAA0BrB,aAAaqB,0BAA0BnB,iBAAiBmB,0BAA0BjB;;;;;;;;;;;;;;;;;;;;;;;;kBAwBvgBb;;;;;;;;;;;;;;;;;;;;;;WAsBPO,aAAaD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0BAsEEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gBA6CV6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;;;;iBAKD7B;;;;;UAKPC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS6B;;;;;;;wBAOKnB;;;;;;;;;;;;;;;;;;;;WAoBboB;;;;;;;;;;;;;;;;;KAiBDC,wCAAwCvC,yBAAyBwC,oBAAoBxC,0CAA0CyC,sBAAsBzC,wBAAwB0C,IAAIH,qBAAqBE,QAAQC;KAC9MC,+CAA+CE,cAAc1C,6EAA6EA,WAAW2C,IAAIC,GAAGC,GAAG1B,IAAIsB,GAAGK,GAAGC,GAAGC"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_chat_models_universal = require('./chat_models/universal.cjs');
|
|
3
|
+
const require_browser = require('./tools/browser.cjs');
|
|
3
4
|
const require_errors = require('./agents/errors.cjs');
|
|
4
5
|
const require_responses = require('./agents/responses.cjs');
|
|
5
6
|
const require_utils = require('./agents/middleware/utils.cjs');
|
|
@@ -26,6 +27,7 @@ const require_promptCaching = require('./agents/middleware/provider/anthropic/pr
|
|
|
26
27
|
require('./agents/middleware/index.cjs');
|
|
27
28
|
const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
|
|
28
29
|
const __langchain_core_tools = require_rolldown_runtime.__toESM(require("@langchain/core/tools"));
|
|
30
|
+
const __langchain_core_utils_context = require_rolldown_runtime.__toESM(require("@langchain/core/utils/context"));
|
|
29
31
|
const __langchain_core_stores = require_rolldown_runtime.__toESM(require("@langchain/core/stores"));
|
|
30
32
|
const __langchain_core_documents = require_rolldown_runtime.__toESM(require("@langchain/core/documents"));
|
|
31
33
|
|
|
@@ -62,6 +64,8 @@ require_rolldown_runtime.__export(src_exports, {
|
|
|
62
64
|
ToolStrategy: () => require_responses.ToolStrategy,
|
|
63
65
|
anthropicPromptCachingMiddleware: () => require_promptCaching.anthropicPromptCachingMiddleware,
|
|
64
66
|
applyStrategy: () => require_pii.applyStrategy,
|
|
67
|
+
browserTool: () => require_browser.browserTool,
|
|
68
|
+
context: () => __langchain_core_utils_context.context,
|
|
65
69
|
contextEditingMiddleware: () => require_contextEditing.contextEditingMiddleware,
|
|
66
70
|
countTokensApproximately: () => require_utils.countTokensApproximately,
|
|
67
71
|
createAgent: () => require_index.createAgent,
|
|
@@ -205,6 +209,13 @@ Object.defineProperty(exports, 'ToolMessageChunk', {
|
|
|
205
209
|
exports.ToolStrategy = require_responses.ToolStrategy;
|
|
206
210
|
exports.anthropicPromptCachingMiddleware = require_promptCaching.anthropicPromptCachingMiddleware;
|
|
207
211
|
exports.applyStrategy = require_pii.applyStrategy;
|
|
212
|
+
exports.browserTool = require_browser.browserTool;
|
|
213
|
+
Object.defineProperty(exports, 'context', {
|
|
214
|
+
enumerable: true,
|
|
215
|
+
get: function () {
|
|
216
|
+
return __langchain_core_utils_context.context;
|
|
217
|
+
}
|
|
218
|
+
});
|
|
208
219
|
exports.contextEditingMiddleware = require_contextEditing.contextEditingMiddleware;
|
|
209
220
|
exports.countTokensApproximately = require_utils.countTokensApproximately;
|
|
210
221
|
exports.createAgent = require_index.createAgent;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n type ToolRuntime,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n type ToolRuntime,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * Browser Tools\n */\nexport {\n browserTool,\n type BrowserTool,\n type BrowserToolParams,\n} from \"./tools/browser.js\";\n\n/**\n * LangChain utilities\n */\nexport { context } from \"@langchain/core/utils/context\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { initChatModel } from "./chat_models/universal.cjs";
|
|
2
|
+
import { BrowserTool, BrowserToolParams, browserTool } from "./tools/browser.cjs";
|
|
2
3
|
import { MultipleStructuredOutputsError, MultipleToolsBoundError, StructuredOutputParsingError, ToolInvocationError } from "./agents/errors.cjs";
|
|
3
4
|
import { ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, providerStrategy, toolStrategy } from "./agents/responses.cjs";
|
|
4
5
|
import { JumpToTarget } from "./agents/constants.cjs";
|
|
@@ -28,6 +29,7 @@ import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from
|
|
|
28
29
|
import { countTokensApproximately } from "./agents/middleware/utils.cjs";
|
|
29
30
|
import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ContentBlock, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
|
|
30
31
|
import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolRuntime, tool } from "@langchain/core/tools";
|
|
32
|
+
import { context } from "@langchain/core/utils/context";
|
|
31
33
|
import { InMemoryStore } from "@langchain/core/stores";
|
|
32
34
|
import { Document, DocumentInput } from "@langchain/core/documents";
|
|
33
|
-
export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, MIDDLEWARE_BRAND, MiddlewareResult, ModelCallLimitMiddlewareConfig, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
35
|
+
export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, type BrowserTool, type BrowserToolParams, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, MIDDLEWARE_BRAND, MiddlewareResult, ModelCallLimitMiddlewareConfig, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, browserTool, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { initChatModel } from "./chat_models/universal.js";
|
|
2
|
+
import { BrowserTool, BrowserToolParams, browserTool } from "./tools/browser.js";
|
|
2
3
|
import { MultipleStructuredOutputsError, MultipleToolsBoundError, StructuredOutputParsingError, ToolInvocationError } from "./agents/errors.js";
|
|
3
4
|
import { ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, providerStrategy, toolStrategy } from "./agents/responses.js";
|
|
4
5
|
import { JumpToTarget } from "./agents/constants.js";
|
|
@@ -29,6 +30,7 @@ import { countTokensApproximately } from "./agents/middleware/utils.js";
|
|
|
29
30
|
import "./agents/middleware/index.js";
|
|
30
31
|
import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ContentBlock, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
|
|
31
32
|
import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolRuntime, tool } from "@langchain/core/tools";
|
|
33
|
+
import { context } from "@langchain/core/utils/context";
|
|
32
34
|
import { InMemoryStore } from "@langchain/core/stores";
|
|
33
35
|
import { Document, DocumentInput } from "@langchain/core/documents";
|
|
34
|
-
export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, MIDDLEWARE_BRAND, MiddlewareResult, ModelCallLimitMiddlewareConfig, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
36
|
+
export { AIMessage, AIMessageChunk, Action, ActionRequest, AfterAgentHook, AfterModelHook, AgentMiddleware, AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, BeforeAgentHook, BeforeModelHook, type BrowserTool, type BrowserToolParams, BuiltInPIIType, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferChannelType, InferContextInput, InferMergedInputState, InferMergedState, InferMiddlewareContext, InferMiddlewareContextInput, InferMiddlewareContextInputs, InferMiddlewareContexts, InferMiddlewareInputState, InferMiddlewareInputStates, InferMiddlewareState, InferMiddlewareStates, InferSchemaInput, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, MIDDLEWARE_BRAND, MiddlewareResult, ModelCallLimitMiddlewareConfig, ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, NormalizedSchemaInput, OpenAIModerationMiddlewareOptions, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIRedactionMiddlewareConfig, PIIStrategy, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RedactionRuleConfig, RejectDecision, ResolvedRedactionRule, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, ToAnnotationRoot, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolEmulatorOptions, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, UserInput, WithStateGraphNodes, WrapModelCallHandler, WrapModelCallHook, WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, browserTool, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { __export } from "./_virtual/rolldown_runtime.js";
|
|
2
2
|
import { initChatModel } from "./chat_models/universal.js";
|
|
3
|
+
import { browserTool } from "./tools/browser.js";
|
|
3
4
|
import { MultipleStructuredOutputsError, MultipleToolsBoundError, StructuredOutputParsingError, ToolInvocationError } from "./agents/errors.js";
|
|
4
5
|
import { ProviderStrategy, ToolStrategy, providerStrategy, toolStrategy } from "./agents/responses.js";
|
|
5
6
|
import { countTokensApproximately } from "./agents/middleware/utils.js";
|
|
@@ -26,6 +27,7 @@ import { anthropicPromptCachingMiddleware } from "./agents/middleware/provider/a
|
|
|
26
27
|
import "./agents/middleware/index.js";
|
|
27
28
|
import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
|
|
28
29
|
import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, tool } from "@langchain/core/tools";
|
|
30
|
+
import { context } from "@langchain/core/utils/context";
|
|
29
31
|
import { InMemoryStore } from "@langchain/core/stores";
|
|
30
32
|
import { Document } from "@langchain/core/documents";
|
|
31
33
|
|
|
@@ -62,6 +64,8 @@ __export(src_exports, {
|
|
|
62
64
|
ToolStrategy: () => ToolStrategy,
|
|
63
65
|
anthropicPromptCachingMiddleware: () => anthropicPromptCachingMiddleware,
|
|
64
66
|
applyStrategy: () => applyStrategy,
|
|
67
|
+
browserTool: () => browserTool,
|
|
68
|
+
context: () => context,
|
|
65
69
|
contextEditingMiddleware: () => contextEditingMiddleware,
|
|
66
70
|
countTokensApproximately: () => countTokensApproximately,
|
|
67
71
|
createAgent: () => createAgent,
|
|
@@ -95,5 +99,5 @@ __export(src_exports, {
|
|
|
95
99
|
});
|
|
96
100
|
|
|
97
101
|
//#endregion
|
|
98
|
-
export { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ClearToolUsesEdit, Document, DynamicStructuredTool, DynamicTool, FakeToolCallingModel, HumanMessage, HumanMessageChunk, InMemoryStore, MIDDLEWARE_BRAND, MultipleStructuredOutputsError, MultipleToolsBoundError, PIIDetectionError, ProviderStrategy, StructuredOutputParsingError, StructuredTool, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, Tool, ToolCallLimitExceededError, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolStrategy, anthropicPromptCachingMiddleware, applyStrategy, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, src_exports, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
102
|
+
export { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ClearToolUsesEdit, Document, DynamicStructuredTool, DynamicTool, FakeToolCallingModel, HumanMessage, HumanMessageChunk, InMemoryStore, MIDDLEWARE_BRAND, MultipleStructuredOutputsError, MultipleToolsBoundError, PIIDetectionError, ProviderStrategy, StructuredOutputParsingError, StructuredTool, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, Tool, ToolCallLimitExceededError, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolStrategy, anthropicPromptCachingMiddleware, applyStrategy, browserTool, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, resolveRedactionRule, src_exports, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
99
103
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n type ToolRuntime,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n type ToolRuntime,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * Browser Tools\n */\nexport {\n browserTool,\n type BrowserTool,\n type BrowserToolParams,\n} from \"./tools/browser.js\";\n\n/**\n * LangChain utilities\n */\nexport { context } from \"@langchain/core/utils/context\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const __langchain_core_tools = require_rolldown_runtime.__toESM(require("@langchain/core/tools"));
|
|
3
|
+
const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
|
|
4
|
+
|
|
5
|
+
//#region src/tools/browser.ts
|
|
6
|
+
/**
|
|
7
|
+
* Check if we're running in a browser environment.
|
|
8
|
+
*/
|
|
9
|
+
const isBrowserEnvironment = () => typeof window !== "undefined" && typeof navigator !== "undefined" && typeof document !== "undefined";
|
|
10
|
+
/**
|
|
11
|
+
* Creates a browser tool that interrupts on the server and executes on the client.
|
|
12
|
+
*
|
|
13
|
+
* Browser tools are defined once and work in both environments:
|
|
14
|
+
* - **Server**: Returns a `Command` that interrupts with the tool call details
|
|
15
|
+
* - **Browser**: Executes the tool directly using browser APIs
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* import { browserTool } from "langchain/tools/browser";
|
|
20
|
+
* import { z } from "zod";
|
|
21
|
+
*
|
|
22
|
+
* export const getLocation = browserTool({
|
|
23
|
+
* name: "get_location",
|
|
24
|
+
* description: "Get the user's current GPS location",
|
|
25
|
+
* schema: z.object({
|
|
26
|
+
* highAccuracy: z.boolean().optional().describe("Request high accuracy GPS"),
|
|
27
|
+
* }),
|
|
28
|
+
* execute: async ({ highAccuracy }) => {
|
|
29
|
+
* return new Promise((resolve, reject) => {
|
|
30
|
+
* navigator.geolocation.getCurrentPosition(
|
|
31
|
+
* (pos) => resolve({
|
|
32
|
+
* latitude: pos.coords.latitude,
|
|
33
|
+
* longitude: pos.coords.longitude,
|
|
34
|
+
* }),
|
|
35
|
+
* (err) => reject(new Error(err.message)),
|
|
36
|
+
* { enableHighAccuracy: highAccuracy }
|
|
37
|
+
* );
|
|
38
|
+
* });
|
|
39
|
+
* },
|
|
40
|
+
* });
|
|
41
|
+
*
|
|
42
|
+
* // Use in createAgent (server)
|
|
43
|
+
* const agent = createAgent({
|
|
44
|
+
* model: "openai:gpt-4o",
|
|
45
|
+
* tools: [getLocation],
|
|
46
|
+
* });
|
|
47
|
+
*
|
|
48
|
+
* // Use in useStream (client)
|
|
49
|
+
* const stream = useStream({
|
|
50
|
+
* assistantId: "agent",
|
|
51
|
+
* browserTools: [getLocation],
|
|
52
|
+
* });
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* @param params - The browser tool configuration
|
|
56
|
+
* @returns A browser tool that can be used in both environments
|
|
57
|
+
*/
|
|
58
|
+
function browserTool(params) {
|
|
59
|
+
const { execute, name, description, schema } = params;
|
|
60
|
+
const wrappedTool = (0, __langchain_core_tools.tool)(async (args, config) => {
|
|
61
|
+
if (isBrowserEnvironment()) return execute(args);
|
|
62
|
+
return (0, __langchain_langgraph.interrupt)({
|
|
63
|
+
type: "browser_tool",
|
|
64
|
+
toolCall: {
|
|
65
|
+
id: config?.toolCall?.id,
|
|
66
|
+
name,
|
|
67
|
+
args
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}, {
|
|
71
|
+
name,
|
|
72
|
+
description,
|
|
73
|
+
schema,
|
|
74
|
+
metadata: { browserTool: true }
|
|
75
|
+
});
|
|
76
|
+
return Object.assign(wrappedTool, { execute });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
//#endregion
|
|
80
|
+
exports.browserTool = browserTool;
|
|
81
|
+
//# sourceMappingURL=browser.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.cjs","names":["params: BrowserToolParams<SchemaT, OutputT>","args: InferInteropZodOutput<SchemaT>","config?: ToolRunnableConfig"],"sources":["../../src/tools/browser.ts"],"sourcesContent":["/**\n * Browser Tools for LangChain Agents\n *\n * This module provides the `browserTool` primitive for creating tools that\n * execute in the browser while the agent runs on the server.\n *\n * @module\n */\n\nimport {\n tool as coreTool,\n DynamicStructuredTool,\n type ToolRunnableConfig,\n} from \"@langchain/core/tools\";\nimport type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport { interrupt } from \"@langchain/langgraph\";\n\n/**\n * Check if we're running in a browser environment.\n */\nconst isBrowserEnvironment = (): boolean =>\n typeof window !== \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n typeof document !== \"undefined\";\n\n/**\n * Parameters for creating a browser tool.\n */\nexport interface BrowserToolParams<\n SchemaT extends InteropZodObject,\n OutputT = unknown\n> {\n /**\n * The name of the tool. Must be unique across all tools.\n */\n name: string;\n\n /**\n * A description of what the tool does. This is shown to the LLM\n * to help it decide when to use the tool.\n */\n description: string;\n\n /**\n * The Zod schema defining the input parameters for the tool.\n */\n schema: SchemaT;\n\n /**\n * The function that executes the tool in the browser.\n * This function only runs in browser environments.\n *\n * @param args - The parsed input arguments matching the schema\n * @returns The tool output\n */\n execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;\n}\n\n/**\n * A browser tool that can be used in both server and client environments.\n *\n * On the server, it returns a Command that interrupts execution.\n * On the client, it executes the tool directly.\n */\nexport type BrowserTool<\n SchemaT extends InteropZodObject = InteropZodObject,\n OutputT = unknown\n> = DynamicStructuredTool<SchemaT> & {\n /**\n * The execute function for client-side use.\n * Called by `useStream` when the interrupt is received.\n */\n execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;\n};\n\n/**\n * Creates a browser tool that interrupts on the server and executes on the client.\n *\n * Browser tools are defined once and work in both environments:\n * - **Server**: Returns a `Command` that interrupts with the tool call details\n * - **Browser**: Executes the tool directly using browser APIs\n *\n * @example\n * ```typescript\n * import { browserTool } from \"langchain/tools/browser\";\n * import { z } from \"zod\";\n *\n * export const getLocation = browserTool({\n * name: \"get_location\",\n * description: \"Get the user's current GPS location\",\n * schema: z.object({\n * highAccuracy: z.boolean().optional().describe(\"Request high accuracy GPS\"),\n * }),\n * execute: async ({ highAccuracy }) => {\n * return new Promise((resolve, reject) => {\n * navigator.geolocation.getCurrentPosition(\n * (pos) => resolve({\n * latitude: pos.coords.latitude,\n * longitude: pos.coords.longitude,\n * }),\n * (err) => reject(new Error(err.message)),\n * { enableHighAccuracy: highAccuracy }\n * );\n * });\n * },\n * });\n *\n * // Use in createAgent (server)\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getLocation],\n * });\n *\n * // Use in useStream (client)\n * const stream = useStream({\n * assistantId: \"agent\",\n * browserTools: [getLocation],\n * });\n * ```\n *\n * @param params - The browser tool configuration\n * @returns A browser tool that can be used in both environments\n */\nexport function browserTool<\n SchemaT extends InteropZodObject,\n OutputT = unknown\n>(params: BrowserToolParams<SchemaT, OutputT>): BrowserTool<SchemaT, OutputT> {\n const { execute, name, description, schema } = params;\n\n // Create the underlying tool using @langchain/core's tool function\n const wrappedTool = coreTool(\n async (\n args: InferInteropZodOutput<SchemaT>,\n config?: ToolRunnableConfig\n ) => {\n // In browser: execute the tool directly\n if (isBrowserEnvironment()) {\n return execute(args);\n }\n\n // On server: interrupt and wait for client to execute\n // The interrupt value contains the tool call details for the client\n return interrupt({\n type: \"browser_tool\",\n toolCall: {\n id: config?.toolCall?.id,\n name,\n args,\n },\n });\n },\n {\n name,\n description,\n schema,\n // Mark as browser tool in metadata for detection\n metadata: {\n browserTool: true,\n },\n }\n );\n\n // Attach the execute function for explicit client-side use (e.g., in useStream)\n return Object.assign(wrappedTool, { execute }) as BrowserTool<\n SchemaT,\n OutputT\n >;\n}\n"],"mappings":";;;;;;;;AAuBA,MAAM,uBAAuB,MAC3B,OAAO,WAAW,eAClB,OAAO,cAAc,eACrB,OAAO,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGtB,SAAgB,YAGdA,QAA4E;CAC5E,MAAM,EAAE,SAAS,MAAM,aAAa,QAAQ,GAAG;CAG/C,MAAM,+CACJ,OACEC,MACAC,WACG;AAEH,MAAI,sBAAsB,CACxB,QAAO,QAAQ,KAAK;AAKtB,8CAAiB;GACf,MAAM;GACN,UAAU;IACR,IAAI,QAAQ,UAAU;IACtB;IACA;GACD;EACF,EAAC;CACH,GACD;EACE;EACA;EACA;EAEA,UAAU,EACR,aAAa,KACd;CACF,EACF;AAGD,QAAO,OAAO,OAAO,aAAa,EAAE,QAAS,EAAC;AAI/C"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
2
|
+
import { InferInteropZodOutput, InteropZodObject } from "@langchain/core/utils/types";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/browser.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parameters for creating a browser tool.
|
|
8
|
+
*/
|
|
9
|
+
interface BrowserToolParams<SchemaT extends InteropZodObject, OutputT = unknown> {
|
|
10
|
+
/**
|
|
11
|
+
* The name of the tool. Must be unique across all tools.
|
|
12
|
+
*/
|
|
13
|
+
name: string;
|
|
14
|
+
/**
|
|
15
|
+
* A description of what the tool does. This is shown to the LLM
|
|
16
|
+
* to help it decide when to use the tool.
|
|
17
|
+
*/
|
|
18
|
+
description: string;
|
|
19
|
+
/**
|
|
20
|
+
* The Zod schema defining the input parameters for the tool.
|
|
21
|
+
*/
|
|
22
|
+
schema: SchemaT;
|
|
23
|
+
/**
|
|
24
|
+
* The function that executes the tool in the browser.
|
|
25
|
+
* This function only runs in browser environments.
|
|
26
|
+
*
|
|
27
|
+
* @param args - The parsed input arguments matching the schema
|
|
28
|
+
* @returns The tool output
|
|
29
|
+
*/
|
|
30
|
+
execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A browser tool that can be used in both server and client environments.
|
|
34
|
+
*
|
|
35
|
+
* On the server, it returns a Command that interrupts execution.
|
|
36
|
+
* On the client, it executes the tool directly.
|
|
37
|
+
*/
|
|
38
|
+
type BrowserTool<SchemaT extends InteropZodObject = InteropZodObject, OutputT = unknown> = DynamicStructuredTool<SchemaT> & {
|
|
39
|
+
/**
|
|
40
|
+
* The execute function for client-side use.
|
|
41
|
+
* Called by `useStream` when the interrupt is received.
|
|
42
|
+
*/
|
|
43
|
+
execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Creates a browser tool that interrupts on the server and executes on the client.
|
|
47
|
+
*
|
|
48
|
+
* Browser tools are defined once and work in both environments:
|
|
49
|
+
* - **Server**: Returns a `Command` that interrupts with the tool call details
|
|
50
|
+
* - **Browser**: Executes the tool directly using browser APIs
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* import { browserTool } from "langchain/tools/browser";
|
|
55
|
+
* import { z } from "zod";
|
|
56
|
+
*
|
|
57
|
+
* export const getLocation = browserTool({
|
|
58
|
+
* name: "get_location",
|
|
59
|
+
* description: "Get the user's current GPS location",
|
|
60
|
+
* schema: z.object({
|
|
61
|
+
* highAccuracy: z.boolean().optional().describe("Request high accuracy GPS"),
|
|
62
|
+
* }),
|
|
63
|
+
* execute: async ({ highAccuracy }) => {
|
|
64
|
+
* return new Promise((resolve, reject) => {
|
|
65
|
+
* navigator.geolocation.getCurrentPosition(
|
|
66
|
+
* (pos) => resolve({
|
|
67
|
+
* latitude: pos.coords.latitude,
|
|
68
|
+
* longitude: pos.coords.longitude,
|
|
69
|
+
* }),
|
|
70
|
+
* (err) => reject(new Error(err.message)),
|
|
71
|
+
* { enableHighAccuracy: highAccuracy }
|
|
72
|
+
* );
|
|
73
|
+
* });
|
|
74
|
+
* },
|
|
75
|
+
* });
|
|
76
|
+
*
|
|
77
|
+
* // Use in createAgent (server)
|
|
78
|
+
* const agent = createAgent({
|
|
79
|
+
* model: "openai:gpt-4o",
|
|
80
|
+
* tools: [getLocation],
|
|
81
|
+
* });
|
|
82
|
+
*
|
|
83
|
+
* // Use in useStream (client)
|
|
84
|
+
* const stream = useStream({
|
|
85
|
+
* assistantId: "agent",
|
|
86
|
+
* browserTools: [getLocation],
|
|
87
|
+
* });
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* @param params - The browser tool configuration
|
|
91
|
+
* @returns A browser tool that can be used in both environments
|
|
92
|
+
*/
|
|
93
|
+
declare function browserTool<SchemaT extends InteropZodObject, OutputT = unknown>(params: BrowserToolParams<SchemaT, OutputT>): BrowserTool<SchemaT, OutputT>;
|
|
94
|
+
//#endregion
|
|
95
|
+
export { BrowserTool, BrowserToolParams, browserTool };
|
|
96
|
+
//# sourceMappingURL=browser.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.d.cts","names":["DynamicStructuredTool","InteropZodObject","InferInteropZodOutput","BrowserToolParams","SchemaT","OutputT","Promise","BrowserTool","browserTool"],"sources":["../../src/tools/browser.d.ts"],"sourcesContent":["/**\n * Browser Tools for LangChain Agents\n *\n * This module provides the `browserTool` primitive for creating tools that\n * execute in the browser while the agent runs on the server.\n *\n * @module\n */\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport type { InteropZodObject, InferInteropZodOutput } from \"@langchain/core/utils/types\";\n/**\n * Parameters for creating a browser tool.\n */\nexport interface BrowserToolParams<SchemaT extends InteropZodObject, OutputT = unknown> {\n /**\n * The name of the tool. Must be unique across all tools.\n */\n name: string;\n /**\n * A description of what the tool does. This is shown to the LLM\n * to help it decide when to use the tool.\n */\n description: string;\n /**\n * The Zod schema defining the input parameters for the tool.\n */\n schema: SchemaT;\n /**\n * The function that executes the tool in the browser.\n * This function only runs in browser environments.\n *\n * @param args - The parsed input arguments matching the schema\n * @returns The tool output\n */\n execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;\n}\n/**\n * A browser tool that can be used in both server and client environments.\n *\n * On the server, it returns a Command that interrupts execution.\n * On the client, it executes the tool directly.\n */\nexport type BrowserTool<SchemaT extends InteropZodObject = InteropZodObject, OutputT = unknown> = DynamicStructuredTool<SchemaT> & {\n /**\n * The execute function for client-side use.\n * Called by `useStream` when the interrupt is received.\n */\n execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;\n};\n/**\n * Creates a browser tool that interrupts on the server and executes on the client.\n *\n * Browser tools are defined once and work in both environments:\n * - **Server**: Returns a `Command` that interrupts with the tool call details\n * - **Browser**: Executes the tool directly using browser APIs\n *\n * @example\n * ```typescript\n * import { browserTool } from \"langchain/tools/browser\";\n * import { z } from \"zod\";\n *\n * export const getLocation = browserTool({\n * name: \"get_location\",\n * description: \"Get the user's current GPS location\",\n * schema: z.object({\n * highAccuracy: z.boolean().optional().describe(\"Request high accuracy GPS\"),\n * }),\n * execute: async ({ highAccuracy }) => {\n * return new Promise((resolve, reject) => {\n * navigator.geolocation.getCurrentPosition(\n * (pos) => resolve({\n * latitude: pos.coords.latitude,\n * longitude: pos.coords.longitude,\n * }),\n * (err) => reject(new Error(err.message)),\n * { enableHighAccuracy: highAccuracy }\n * );\n * });\n * },\n * });\n *\n * // Use in createAgent (server)\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getLocation],\n * });\n *\n * // Use in useStream (client)\n * const stream = useStream({\n * assistantId: \"agent\",\n * browserTools: [getLocation],\n * });\n * ```\n *\n * @param params - The browser tool configuration\n * @returns A browser tool that can be used in both environments\n */\nexport declare function browserTool<SchemaT extends InteropZodObject, OutputT = unknown>(params: BrowserToolParams<SchemaT, OutputT>): BrowserTool<SchemaT, OutputT>;\n//# sourceMappingURL=browser.d.ts.map"],"mappings":";;;;;;AAkC8D;AAQ9D;AAAwCC,UA7BvBE,iBA6BuBF,CAAAA,gBA7BWA,gBA6BXA,EAAAA,UAAAA,OAAAA,CAAAA,CAAAA;EAAmBA;;;EAKjBG,IAAAA,EAAAA,MAAAA;EAAtBF;;;AAA0C;EAkDtCM,WAAAA,EAAAA,MAAW;EAAiBP;;;EAA6CE,MAAAA,EAvErFC,OAuEqFD;EAAkDC;;;AAAD;;;;kBA/D9HF,sBAAsBE,aAAaE,QAAQD;;;;;;;;KAQnDE,4BAA4BN,mBAAmBA,uCAAuCD,sBAAsBI;;;;;kBAKpGF,sBAAsBE,aAAaE,QAAQD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkDvCG,4BAA4BP,6CAA6CE,kBAAkBC,SAASC,WAAWE,YAAYH,SAASC"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
2
|
+
import { InferInteropZodOutput, InteropZodObject } from "@langchain/core/utils/types";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/browser.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parameters for creating a browser tool.
|
|
8
|
+
*/
|
|
9
|
+
interface BrowserToolParams<SchemaT extends InteropZodObject, OutputT = unknown> {
|
|
10
|
+
/**
|
|
11
|
+
* The name of the tool. Must be unique across all tools.
|
|
12
|
+
*/
|
|
13
|
+
name: string;
|
|
14
|
+
/**
|
|
15
|
+
* A description of what the tool does. This is shown to the LLM
|
|
16
|
+
* to help it decide when to use the tool.
|
|
17
|
+
*/
|
|
18
|
+
description: string;
|
|
19
|
+
/**
|
|
20
|
+
* The Zod schema defining the input parameters for the tool.
|
|
21
|
+
*/
|
|
22
|
+
schema: SchemaT;
|
|
23
|
+
/**
|
|
24
|
+
* The function that executes the tool in the browser.
|
|
25
|
+
* This function only runs in browser environments.
|
|
26
|
+
*
|
|
27
|
+
* @param args - The parsed input arguments matching the schema
|
|
28
|
+
* @returns The tool output
|
|
29
|
+
*/
|
|
30
|
+
execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A browser tool that can be used in both server and client environments.
|
|
34
|
+
*
|
|
35
|
+
* On the server, it returns a Command that interrupts execution.
|
|
36
|
+
* On the client, it executes the tool directly.
|
|
37
|
+
*/
|
|
38
|
+
type BrowserTool<SchemaT extends InteropZodObject = InteropZodObject, OutputT = unknown> = DynamicStructuredTool<SchemaT> & {
|
|
39
|
+
/**
|
|
40
|
+
* The execute function for client-side use.
|
|
41
|
+
* Called by `useStream` when the interrupt is received.
|
|
42
|
+
*/
|
|
43
|
+
execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Creates a browser tool that interrupts on the server and executes on the client.
|
|
47
|
+
*
|
|
48
|
+
* Browser tools are defined once and work in both environments:
|
|
49
|
+
* - **Server**: Returns a `Command` that interrupts with the tool call details
|
|
50
|
+
* - **Browser**: Executes the tool directly using browser APIs
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* import { browserTool } from "langchain/tools/browser";
|
|
55
|
+
* import { z } from "zod";
|
|
56
|
+
*
|
|
57
|
+
* export const getLocation = browserTool({
|
|
58
|
+
* name: "get_location",
|
|
59
|
+
* description: "Get the user's current GPS location",
|
|
60
|
+
* schema: z.object({
|
|
61
|
+
* highAccuracy: z.boolean().optional().describe("Request high accuracy GPS"),
|
|
62
|
+
* }),
|
|
63
|
+
* execute: async ({ highAccuracy }) => {
|
|
64
|
+
* return new Promise((resolve, reject) => {
|
|
65
|
+
* navigator.geolocation.getCurrentPosition(
|
|
66
|
+
* (pos) => resolve({
|
|
67
|
+
* latitude: pos.coords.latitude,
|
|
68
|
+
* longitude: pos.coords.longitude,
|
|
69
|
+
* }),
|
|
70
|
+
* (err) => reject(new Error(err.message)),
|
|
71
|
+
* { enableHighAccuracy: highAccuracy }
|
|
72
|
+
* );
|
|
73
|
+
* });
|
|
74
|
+
* },
|
|
75
|
+
* });
|
|
76
|
+
*
|
|
77
|
+
* // Use in createAgent (server)
|
|
78
|
+
* const agent = createAgent({
|
|
79
|
+
* model: "openai:gpt-4o",
|
|
80
|
+
* tools: [getLocation],
|
|
81
|
+
* });
|
|
82
|
+
*
|
|
83
|
+
* // Use in useStream (client)
|
|
84
|
+
* const stream = useStream({
|
|
85
|
+
* assistantId: "agent",
|
|
86
|
+
* browserTools: [getLocation],
|
|
87
|
+
* });
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* @param params - The browser tool configuration
|
|
91
|
+
* @returns A browser tool that can be used in both environments
|
|
92
|
+
*/
|
|
93
|
+
declare function browserTool<SchemaT extends InteropZodObject, OutputT = unknown>(params: BrowserToolParams<SchemaT, OutputT>): BrowserTool<SchemaT, OutputT>;
|
|
94
|
+
//#endregion
|
|
95
|
+
export { BrowserTool, BrowserToolParams, browserTool };
|
|
96
|
+
//# sourceMappingURL=browser.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.d.ts","names":["DynamicStructuredTool","InteropZodObject","InferInteropZodOutput","BrowserToolParams","SchemaT","OutputT","Promise","BrowserTool","browserTool"],"sources":["../../src/tools/browser.d.ts"],"sourcesContent":["/**\n * Browser Tools for LangChain Agents\n *\n * This module provides the `browserTool` primitive for creating tools that\n * execute in the browser while the agent runs on the server.\n *\n * @module\n */\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport type { InteropZodObject, InferInteropZodOutput } from \"@langchain/core/utils/types\";\n/**\n * Parameters for creating a browser tool.\n */\nexport interface BrowserToolParams<SchemaT extends InteropZodObject, OutputT = unknown> {\n /**\n * The name of the tool. Must be unique across all tools.\n */\n name: string;\n /**\n * A description of what the tool does. This is shown to the LLM\n * to help it decide when to use the tool.\n */\n description: string;\n /**\n * The Zod schema defining the input parameters for the tool.\n */\n schema: SchemaT;\n /**\n * The function that executes the tool in the browser.\n * This function only runs in browser environments.\n *\n * @param args - The parsed input arguments matching the schema\n * @returns The tool output\n */\n execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;\n}\n/**\n * A browser tool that can be used in both server and client environments.\n *\n * On the server, it returns a Command that interrupts execution.\n * On the client, it executes the tool directly.\n */\nexport type BrowserTool<SchemaT extends InteropZodObject = InteropZodObject, OutputT = unknown> = DynamicStructuredTool<SchemaT> & {\n /**\n * The execute function for client-side use.\n * Called by `useStream` when the interrupt is received.\n */\n execute: (args: InferInteropZodOutput<SchemaT>) => Promise<OutputT>;\n};\n/**\n * Creates a browser tool that interrupts on the server and executes on the client.\n *\n * Browser tools are defined once and work in both environments:\n * - **Server**: Returns a `Command` that interrupts with the tool call details\n * - **Browser**: Executes the tool directly using browser APIs\n *\n * @example\n * ```typescript\n * import { browserTool } from \"langchain/tools/browser\";\n * import { z } from \"zod\";\n *\n * export const getLocation = browserTool({\n * name: \"get_location\",\n * description: \"Get the user's current GPS location\",\n * schema: z.object({\n * highAccuracy: z.boolean().optional().describe(\"Request high accuracy GPS\"),\n * }),\n * execute: async ({ highAccuracy }) => {\n * return new Promise((resolve, reject) => {\n * navigator.geolocation.getCurrentPosition(\n * (pos) => resolve({\n * latitude: pos.coords.latitude,\n * longitude: pos.coords.longitude,\n * }),\n * (err) => reject(new Error(err.message)),\n * { enableHighAccuracy: highAccuracy }\n * );\n * });\n * },\n * });\n *\n * // Use in createAgent (server)\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getLocation],\n * });\n *\n * // Use in useStream (client)\n * const stream = useStream({\n * assistantId: \"agent\",\n * browserTools: [getLocation],\n * });\n * ```\n *\n * @param params - The browser tool configuration\n * @returns A browser tool that can be used in both environments\n */\nexport declare function browserTool<SchemaT extends InteropZodObject, OutputT = unknown>(params: BrowserToolParams<SchemaT, OutputT>): BrowserTool<SchemaT, OutputT>;\n//# sourceMappingURL=browser.d.ts.map"],"mappings":";;;;;;AAkC8D;AAQ9D;AAAwCC,UA7BvBE,iBA6BuBF,CAAAA,gBA7BWA,gBA6BXA,EAAAA,UAAAA,OAAAA,CAAAA,CAAAA;EAAmBA;;;EAKjBG,IAAAA,EAAAA,MAAAA;EAAtBF;;;AAA0C;EAkDtCM,WAAAA,EAAAA,MAAW;EAAiBP;;;EAA6CE,MAAAA,EAvErFC,OAuEqFD;EAAkDC;;;AAAD;;;;kBA/D9HF,sBAAsBE,aAAaE,QAAQD;;;;;;;;KAQnDE,4BAA4BN,mBAAmBA,uCAAuCD,sBAAsBI;;;;;kBAKpGF,sBAAsBE,aAAaE,QAAQD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkDvCG,4BAA4BP,6CAA6CE,kBAAkBC,SAASC,WAAWE,YAAYH,SAASC"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { tool } from "@langchain/core/tools";
|
|
2
|
+
import { interrupt } from "@langchain/langgraph";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/browser.ts
|
|
5
|
+
/**
|
|
6
|
+
* Check if we're running in a browser environment.
|
|
7
|
+
*/
|
|
8
|
+
const isBrowserEnvironment = () => typeof window !== "undefined" && typeof navigator !== "undefined" && typeof document !== "undefined";
|
|
9
|
+
/**
|
|
10
|
+
* Creates a browser tool that interrupts on the server and executes on the client.
|
|
11
|
+
*
|
|
12
|
+
* Browser tools are defined once and work in both environments:
|
|
13
|
+
* - **Server**: Returns a `Command` that interrupts with the tool call details
|
|
14
|
+
* - **Browser**: Executes the tool directly using browser APIs
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* import { browserTool } from "langchain/tools/browser";
|
|
19
|
+
* import { z } from "zod";
|
|
20
|
+
*
|
|
21
|
+
* export const getLocation = browserTool({
|
|
22
|
+
* name: "get_location",
|
|
23
|
+
* description: "Get the user's current GPS location",
|
|
24
|
+
* schema: z.object({
|
|
25
|
+
* highAccuracy: z.boolean().optional().describe("Request high accuracy GPS"),
|
|
26
|
+
* }),
|
|
27
|
+
* execute: async ({ highAccuracy }) => {
|
|
28
|
+
* return new Promise((resolve, reject) => {
|
|
29
|
+
* navigator.geolocation.getCurrentPosition(
|
|
30
|
+
* (pos) => resolve({
|
|
31
|
+
* latitude: pos.coords.latitude,
|
|
32
|
+
* longitude: pos.coords.longitude,
|
|
33
|
+
* }),
|
|
34
|
+
* (err) => reject(new Error(err.message)),
|
|
35
|
+
* { enableHighAccuracy: highAccuracy }
|
|
36
|
+
* );
|
|
37
|
+
* });
|
|
38
|
+
* },
|
|
39
|
+
* });
|
|
40
|
+
*
|
|
41
|
+
* // Use in createAgent (server)
|
|
42
|
+
* const agent = createAgent({
|
|
43
|
+
* model: "openai:gpt-4o",
|
|
44
|
+
* tools: [getLocation],
|
|
45
|
+
* });
|
|
46
|
+
*
|
|
47
|
+
* // Use in useStream (client)
|
|
48
|
+
* const stream = useStream({
|
|
49
|
+
* assistantId: "agent",
|
|
50
|
+
* browserTools: [getLocation],
|
|
51
|
+
* });
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* @param params - The browser tool configuration
|
|
55
|
+
* @returns A browser tool that can be used in both environments
|
|
56
|
+
*/
|
|
57
|
+
function browserTool(params) {
|
|
58
|
+
const { execute, name, description, schema } = params;
|
|
59
|
+
const wrappedTool = tool(async (args, config) => {
|
|
60
|
+
if (isBrowserEnvironment()) return execute(args);
|
|
61
|
+
return interrupt({
|
|
62
|
+
type: "browser_tool",
|
|
63
|
+
toolCall: {
|
|
64
|
+
id: config?.toolCall?.id,
|
|
65
|
+
name,
|
|
66
|
+
args
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}, {
|
|
70
|
+
name,
|
|
71
|
+
description,
|
|
72
|
+
schema,
|
|
73
|
+
metadata: { browserTool: true }
|
|
74
|
+
});
|
|
75
|
+
return Object.assign(wrappedTool, { execute });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
export { browserTool };
|
|
80
|
+
//# sourceMappingURL=browser.js.map
|