UNPKG

@langchain/community

Version:
1 lines 11.3 kB
{"version":3,"file":"connery.cjs","names":["StructuredTool","z","AsyncCaller"],"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,sBAAAA,eAAe;CAChD;CAEA;CAEA;;;;;;;CAQA,YACE,SACA,UACA;AACA,SAAO;AAHG,OAAA,UAAA;AACA,OAAA,WAAA;AAIV,OAAK,OAAO,KAAK,QAAQ;AACzB,OAAK,cACH,KAAK,QAAQ,SACZ,KAAK,QAAQ,cAAc,KAAK,KAAK,QAAQ,gBAAgB;AAChE,OAAK,SAAS,KAAK,mBAAmB;;;;;;;CAQxC,MACE,KACiB;AACjB,SAAO,KAAK,SAAS,UAAU,KAAK,QAAQ,IAAI,IAAI;;;;;;CAOtD,oBAEE;EACA,MAAM,qBAGF,EAAE;AAEN,OAAK,QAAQ,gBAAgB,SAAS,UAAU;GAC9C,MAAM,aAAa,MAAM,YAAY,YAAY;GACjD,IAAI,cAAwDC,OAAAA,EAAE,QAAQ;AACtE,iBAAc,aAAa,cAAc,YAAY,UAAU;GAE/D,MAAM,mBACJ,M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