UNPKG

@langchain/community

Version:
1 lines • 12 kB
{"version":3,"file":"connery.cjs","names":["StructuredTool","_action: Action","_service: ConneryService","arg: InferInteropZodOutput<ConneryActionSchema>","dynamicInputFields: Record<\n string,\n z.ZodString | z.ZodOptional<z.ZodString>\n >","fieldSchema: z.ZodString | z.ZodOptional<z.ZodString>","z","params?: ConneryServiceParams","AsyncCaller","actionId: string","input: Input","apiResponse: ApiResponse<Action[]>","apiResponse: ApiResponse<RunActionResult>","response: Response","errorMessage: string","apiErrorResponse: ApiErrorResponse"],"sources":["../../src/tools/connery.ts"],"sourcesContent":["import {\n AsyncCaller,\n AsyncCallerParams,\n} from \"@langchain/core/utils/async_caller\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { StructuredTool } from \"@langchain/core/tools\";\nimport { InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport { z } from \"zod/v3\";\n\n/**\n * An object containing configuration parameters for the ConneryService class.\n * @extends AsyncCallerParams\n */\nexport interface ConneryServiceParams extends AsyncCallerParams {\n runnerUrl: string;\n apiKey: string;\n}\n\ntype ApiResponse<T> = {\n status: \"success\";\n data: T;\n};\n\ntype ApiErrorResponse = {\n status: \"error\";\n error: {\n message: string;\n };\n};\n\ntype Parameter = {\n key: string;\n title: string;\n description: string;\n type: string;\n validation?: {\n required?: boolean;\n };\n};\n\ntype Action = {\n id: string;\n key: string;\n title: string;\n description: string;\n type: string;\n inputParameters: Parameter[];\n outputParameters: Parameter[];\n pluginId: string;\n};\n\ntype Input = Record<string, string | undefined>;\n\ntype Output = Record<string, string>;\n\ntype RunActionResult = {\n output: Output;\n used: {\n actionId: string;\n input: Input;\n };\n};\n\ntype ConneryActionSchema = z.ZodObject<\n Record<string, z.ZodString | z.ZodOptional<z.ZodString>>\n>;\n\n/**\n * A LangChain Tool object wrapping a Connery action.\n * ConneryAction is a structured tool that can be used only in the agents supporting structured tools.\n * @extends StructuredTool\n */\nexport class ConneryAction extends StructuredTool {\n name: string;\n\n description: string;\n\n schema: ConneryActionSchema;\n\n /**\n * Creates a ConneryAction instance based on the provided Connery Action.\n * @param _action The Connery Action.\n * @param _service The ConneryService instance.\n * @returns A ConneryAction instance.\n */\n constructor(\n protected _action: Action,\n protected _service: ConneryService\n ) {\n super();\n\n this.name = this._action.id;\n this.description =\n this._action.title +\n (this._action.description ? `: ${this._action.description}` : \"\");\n this.schema = this.createInputSchema();\n }\n\n /**\n * Runs the Connery Action with the provided input.\n * @param arg The input object expected by the action.\n * @returns A promise that resolves to a JSON string containing the output of the action.\n */\n protected _call(\n arg: InferInteropZodOutput<ConneryActionSchema>\n ): Promise<string> {\n return this._service.runAction(this._action.id, arg);\n }\n\n /**\n * Creates a Zod schema for the input object expected by the Connery action.\n * @returns A Zod schema for the input object expected by the Connery action.\n */\n protected createInputSchema(): z.ZodObject<\n Record<string, z.ZodString | z.ZodOptional<z.ZodString>>\n > {\n const dynamicInputFields: Record<\n string,\n z.ZodString | z.ZodOptional<z.ZodString>\n > = {};\n\n this._action.inputParameters.forEach((param) => {\n const isRequired = param.validation?.required ?? false;\n let fieldSchema: z.ZodString | z.ZodOptional<z.ZodString> = z.string();\n fieldSchema = isRequired ? fieldSchema : fieldSchema.optional();\n\n const fieldDescription =\n param.title + (param.description ? `: ${param.description}` : \"\");\n fieldSchema = fieldSchema.describe(fieldDescription);\n\n dynamicInputFields[param.key] = fieldSchema;\n });\n\n return z.object(dynamicInputFields);\n }\n}\n\n/**\n * A service for working with Connery Actions.\n */\nexport class ConneryService {\n protected runnerUrl: string;\n\n protected apiKey: string;\n\n protected asyncCaller: AsyncCaller;\n\n /**\n * Creates a ConneryService instance.\n * @param params A ConneryServiceParams object.\n * If not provided, the values are retrieved from the CONNERY_RUNNER_URL\n * and CONNERY_RUNNER_API_KEY environment variables.\n * @returns A ConneryService instance.\n */\n constructor(params?: ConneryServiceParams) {\n const runnerUrl =\n params?.runnerUrl ?? getEnvironmentVariable(\"CONNERY_RUNNER_URL\");\n const apiKey =\n params?.apiKey ?? getEnvironmentVariable(\"CONNERY_RUNNER_API_KEY\");\n\n if (!runnerUrl || !apiKey) {\n throw new Error(\n \"CONNERY_RUNNER_URL and CONNERY_RUNNER_API_KEY environment variables must be set.\"\n );\n }\n\n this.runnerUrl = runnerUrl;\n this.apiKey = apiKey;\n\n this.asyncCaller = new AsyncCaller(params ?? {});\n }\n\n /**\n * Returns the list of Connery Actions wrapped as a LangChain StructuredTool objects.\n * @returns A promise that resolves to an array of ConneryAction objects.\n */\n async listActions(): Promise<ConneryAction[]> {\n const actions = await this._listActions();\n return actions.map((action) => new ConneryAction(action, this));\n }\n\n /**\n * Returns the specified Connery action wrapped as a LangChain StructuredTool object.\n * @param actionId The ID of the action to return.\n * @returns A promise that resolves to a ConneryAction object.\n */\n async getAction(actionId: string): Promise<ConneryAction> {\n const action = await this._getAction(actionId);\n return new ConneryAction(action, this);\n }\n\n /**\n * Runs the specified Connery action with the provided input.\n * @param actionId The ID of the action to run.\n * @param input The input object expected by the action.\n * @returns A promise that resolves to a JSON string containing the output of the action.\n */\n async runAction(actionId: string, input: Input = {}): Promise<string> {\n const result = await this._runAction(actionId, input);\n return JSON.stringify(result);\n }\n\n /**\n * Returns the list of actions available in the Connery runner.\n * @returns A promise that resolves to an array of Action objects.\n */\n protected async _listActions(): Promise<Action[]> {\n const response = await this.asyncCaller.call(\n fetch,\n `${this.runnerUrl}/v1/actions`,\n {\n method: \"GET\",\n headers: this._getHeaders(),\n }\n );\n await this._handleError(response, \"Failed to list actions\");\n\n const apiResponse: ApiResponse<Action[]> = await response.json();\n return apiResponse.data;\n }\n\n /**\n * Returns the specified action available in the Connery runner.\n * @param actionId The ID of the action to return.\n * @returns A promise that resolves to an Action object.\n * @throws An error if the action with the specified ID is not found.\n */\n protected async _getAction(actionId: string): Promise<Action> {\n const actions = await this._listActions();\n const action = actions.find((a) => a.id === actionId);\n if (!action) {\n throw new Error(\n `The action with ID \"${actionId}\" was not found in the list of available actions in the Connery runner.`\n );\n }\n return action;\n }\n\n /**\n * Runs the specified Connery action with the provided input.\n * @param actionId The ID of the action to run.\n * @param input The input object expected by the action.\n * @returns A promise that resolves to a RunActionResult object.\n */\n protected async _runAction(\n actionId: string,\n input: Input = {}\n ): Promise<Output> {\n const response = await this.asyncCaller.call(\n fetch,\n `${this.runnerUrl}/v1/actions/${actionId}/run`,\n {\n method: \"POST\",\n headers: this._getHeaders(),\n body: JSON.stringify({\n input,\n }),\n }\n );\n await this._handleError(response, \"Failed to run action\");\n\n const apiResponse: ApiResponse<RunActionResult> = await response.json();\n return apiResponse.data.output;\n }\n\n /**\n * Returns a standard set of HTTP headers to be used in API calls to the Connery runner.\n * @returns An object containing the standard set of HTTP headers.\n */\n protected _getHeaders(): Record<string, string> {\n return {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n }\n\n /**\n * Shared error handler for API calls to the Connery runner.\n * If the response is not ok, an error is thrown containing the error message returned by the Connery runner.\n * Otherwise, the promise resolves to void.\n * @param response The response object returned by the Connery runner.\n * @param errorMessage The error message to be used in the error thrown if the response is not ok.\n * @returns A promise that resolves to void.\n * @throws An error containing the error message returned by the Connery runner.\n */\n protected async _handleError(\n response: Response,\n errorMessage: string\n ): Promise<void> {\n if (response.ok) return;\n\n const apiErrorResponse: ApiErrorResponse = await response.json();\n throw new Error(\n `${errorMessage}. Status code: ${response.status}. Error message: ${apiErrorResponse.error.message}`\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwEA,IAAa,gBAAb,cAAmCA,sCAAe;CAChD;CAEA;CAEA;;;;;;;CAQA,YACYC,SACAC,UACV;EACA,OAAO;EAHG;EACA;EAIV,KAAK,OAAO,KAAK,QAAQ;EACzB,KAAK,cACH,KAAK,QAAQ,SACZ,KAAK,QAAQ,cAAc,CAAC,EAAE,EAAE,KAAK,QAAQ,aAAa,GAAG;EAChE,KAAK,SAAS,KAAK,mBAAmB;CACvC;;;;;;CAOD,AAAU,MACRC,KACiB;AACjB,SAAO,KAAK,SAAS,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