@typia/langchain 12.0.0-dev.20260316 → 12.0.0

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Jeongho Nam
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Jeongho Nam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,115 +1,115 @@
1
- # `@typia/langchain`
2
-
3
- ![Typia Logo](https://typia.io/logo.png)
4
-
5
- [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/samchon/typia/blob/master/LICENSE)
6
- [![NPM Version](https://img.shields.io/npm/v/typia.svg)](https://www.npmjs.com/package/typia)
7
- [![NPM Downloads](https://img.shields.io/npm/dm/typia.svg)](https://www.npmjs.com/package/typia)
8
- [![Build Status](https://github.com/samchon/typia/workflows/test/badge.svg)](https://github.com/samchon/typia/actions?query=workflow%3Atest)
9
- [![Guide Documents](https://img.shields.io/badge/Guide-Documents-forestgreen)](https://typia.io/docs/)
10
- [![Gurubase](https://img.shields.io/badge/Gurubase-Document%20Chatbot-006BFF)](https://gurubase.io/g/typia)
11
- [![Discord Badge](https://img.shields.io/badge/discord-samchon-d91965?style=flat&labelColor=5866f2&logo=discord&logoColor=white&link=https://discord.gg/E94XhzrUCZ)](https://discord.gg/E94XhzrUCZ)
12
-
13
- [LangChain.js](https://github.com/langchain-ai/langchainjs) integration for [`typia`](https://github.com/samchon/typia).
14
-
15
- Converts typia controllers to LangChain `DynamicStructuredTool[]` with automatic validation.
16
-
17
- ## Setup
18
-
19
- ```bash
20
- npm install @typia/langchain @langchain/core
21
- npm install typia
22
- npx typia setup
23
- ```
24
-
25
- ## Usage
26
-
27
- ### From TypeScript class
28
-
29
- ```typescript
30
- import { ChainValues, Runnable } from "@langchain/core";
31
- import { ChatPromptTemplate } from "@langchain/core/prompts";
32
- import { DynamicStructuredTool } from "@langchain/core/tools";
33
- import { ChatOpenAI } from "@langchain/openai";
34
- import { toLangChainTools } from "@typia/langchain";
35
- import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
36
- import typia from "typia";
37
-
38
- const tools: DynamicStructuredTool[] = toLangChainTools({
39
- controllers: [
40
- typia.llm.controller<Calculator>("Calculator", new Calculator()),
41
- ],
42
- });
43
-
44
- const agent: Runnable = createToolCallingAgent({
45
- llm: new ChatOpenAI({ model: "gpt-4o" }),
46
- tools,
47
- prompt: ChatPromptTemplate.fromMessages([
48
- ["system", "You are a helpful assistant."],
49
- ["human", "{input}"],
50
- ["placeholder", "{agent_scratchpad}"],
51
- ]),
52
- });
53
- const executor: AgentExecutor = new AgentExecutor({ agent, tools });
54
- const result: ChainValues = await executor.invoke({ input: "What is 10 + 5?" });
55
- ```
56
-
57
- ### From OpenAPI document
58
-
59
- ```typescript
60
- import { DynamicStructuredTool } from "@langchain/core/tools";
61
- import { toLangChainTools } from "@typia/langchain";
62
- import { HttpLlm } from "@typia/utils";
63
-
64
- const tools: DynamicStructuredTool[] = toLangChainTools({
65
- controllers: [
66
- HttpLlm.controller({
67
- name: "petStore",
68
- document: yourOpenApiDocument,
69
- connection: { host: "https://api.example.com" },
70
- }),
71
- ],
72
- });
73
- ```
74
-
75
- ### Structured Output
76
-
77
- Use `typia.llm.parameters<T>()` with LangChain's `withStructuredOutput()` to generate structured output with validation:
78
-
79
- ```typescript
80
- import { ChatOpenAI } from "@langchain/openai";
81
- import { dedent, LlmJson } from "@typia/utils";
82
- import typia, { tags } from "typia";
83
-
84
- interface IMember {
85
- email: string & tags.Format<"email">;
86
- name: string;
87
- age: number & tags.Minimum<0> & tags.Maximum<100>;
88
- hobbies: string[];
89
- joined_at: string & tags.Format<"date">;
90
- }
91
-
92
- const model = new ChatOpenAI({ model: "gpt-4o" }).withStructuredOutput(
93
- typia.llm.parameters<IMember>(),
94
- );
95
-
96
- const member: IMember = await model.invoke(dedent`
97
- I am a new member of the community.
98
-
99
- My name is John Doe, and I am 25 years old.
100
- I like playing basketball and reading books,
101
- and joined to this community at 2022-01-01.
102
- `);
103
-
104
- // Validate the result
105
- const result = typia.validate<IMember>(member);
106
- if (!result.success) {
107
- console.error(LlmJson.stringify(result));
108
- }
109
- ```
110
-
111
- ## Features
112
-
113
- - No manual schema definition — generates everything from TypeScript types or OpenAPI
114
- - Automatic argument validation with LLM-friendly error feedback
115
- - Supports both class-based (`typia.llm.controller`) and HTTP-based (`HttpLlm.controller`) controllers
1
+ # `@typia/langchain`
2
+
3
+ ![Typia Logo](https://typia.io/logo.png)
4
+
5
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/samchon/typia/blob/master/LICENSE)
6
+ [![NPM Version](https://img.shields.io/npm/v/typia.svg)](https://www.npmjs.com/package/typia)
7
+ [![NPM Downloads](https://img.shields.io/npm/dm/typia.svg)](https://www.npmjs.com/package/typia)
8
+ [![Build Status](https://github.com/samchon/typia/workflows/test/badge.svg)](https://github.com/samchon/typia/actions?query=workflow%3Atest)
9
+ [![Guide Documents](https://img.shields.io/badge/Guide-Documents-forestgreen)](https://typia.io/docs/)
10
+ [![Gurubase](https://img.shields.io/badge/Gurubase-Document%20Chatbot-006BFF)](https://gurubase.io/g/typia)
11
+ [![Discord Badge](https://img.shields.io/badge/discord-samchon-d91965?style=flat&labelColor=5866f2&logo=discord&logoColor=white&link=https://discord.gg/E94XhzrUCZ)](https://discord.gg/E94XhzrUCZ)
12
+
13
+ [LangChain.js](https://github.com/langchain-ai/langchainjs) integration for [`typia`](https://github.com/samchon/typia).
14
+
15
+ Converts typia controllers to LangChain `DynamicStructuredTool[]` with automatic validation.
16
+
17
+ ## Setup
18
+
19
+ ```bash
20
+ npm install @typia/langchain @langchain/core
21
+ npm install typia
22
+ npx typia setup
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### From TypeScript class
28
+
29
+ ```typescript
30
+ import { ChainValues, Runnable } from "@langchain/core";
31
+ import { ChatPromptTemplate } from "@langchain/core/prompts";
32
+ import { DynamicStructuredTool } from "@langchain/core/tools";
33
+ import { ChatOpenAI } from "@langchain/openai";
34
+ import { toLangChainTools } from "@typia/langchain";
35
+ import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
36
+ import typia from "typia";
37
+
38
+ const tools: DynamicStructuredTool[] = toLangChainTools({
39
+ controllers: [
40
+ typia.llm.controller<Calculator>("Calculator", new Calculator()),
41
+ ],
42
+ });
43
+
44
+ const agent: Runnable = createToolCallingAgent({
45
+ llm: new ChatOpenAI({ model: "gpt-4o" }),
46
+ tools,
47
+ prompt: ChatPromptTemplate.fromMessages([
48
+ ["system", "You are a helpful assistant."],
49
+ ["human", "{input}"],
50
+ ["placeholder", "{agent_scratchpad}"],
51
+ ]),
52
+ });
53
+ const executor: AgentExecutor = new AgentExecutor({ agent, tools });
54
+ const result: ChainValues = await executor.invoke({ input: "What is 10 + 5?" });
55
+ ```
56
+
57
+ ### From OpenAPI document
58
+
59
+ ```typescript
60
+ import { DynamicStructuredTool } from "@langchain/core/tools";
61
+ import { toLangChainTools } from "@typia/langchain";
62
+ import { HttpLlm } from "@typia/utils";
63
+
64
+ const tools: DynamicStructuredTool[] = toLangChainTools({
65
+ controllers: [
66
+ HttpLlm.controller({
67
+ name: "petStore",
68
+ document: yourOpenApiDocument,
69
+ connection: { host: "https://api.example.com" },
70
+ }),
71
+ ],
72
+ });
73
+ ```
74
+
75
+ ### Structured Output
76
+
77
+ Use `typia.llm.parameters<T>()` with LangChain's `withStructuredOutput()` to generate structured output with validation:
78
+
79
+ ```typescript
80
+ import { ChatOpenAI } from "@langchain/openai";
81
+ import { dedent, LlmJson } from "@typia/utils";
82
+ import typia, { tags } from "typia";
83
+
84
+ interface IMember {
85
+ email: string & tags.Format<"email">;
86
+ name: string;
87
+ age: number & tags.Minimum<0> & tags.Maximum<100>;
88
+ hobbies: string[];
89
+ joined_at: string & tags.Format<"date">;
90
+ }
91
+
92
+ const model = new ChatOpenAI({ model: "gpt-4o" }).withStructuredOutput(
93
+ typia.llm.parameters<IMember>(),
94
+ );
95
+
96
+ const member: IMember = await model.invoke(dedent`
97
+ I am a new member of the community.
98
+
99
+ My name is John Doe, and I am 25 years old.
100
+ I like playing basketball and reading books,
101
+ and joined to this community at 2022-01-01.
102
+ `);
103
+
104
+ // Validate the result
105
+ const result = typia.validate<IMember>(member);
106
+ if (!result.success) {
107
+ console.error(LlmJson.stringify(result));
108
+ }
109
+ ```
110
+
111
+ ## Features
112
+
113
+ - No manual schema definition — generates everything from TypeScript types or OpenAPI
114
+ - Automatic argument validation with LLM-friendly error feedback
115
+ - Supports both class-based (`typia.llm.controller`) and HTTP-based (`HttpLlm.controller`) controllers
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typia/langchain",
3
- "version": "12.0.0-dev.20260316",
3
+ "version": "12.0.0",
4
4
  "description": "LangChain.js integration for typia",
5
5
  "main": "lib/index.js",
6
6
  "exports": {
@@ -22,8 +22,8 @@
22
22
  },
23
23
  "homepage": "https://typia.io",
24
24
  "dependencies": {
25
- "@typia/interface": "^12.0.0-dev.20260316",
26
- "@typia/utils": "^12.0.0-dev.20260316"
25
+ "@typia/interface": "^12.0.0",
26
+ "@typia/utils": "^12.0.0"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@langchain/core": ">=1.0.0"
package/src/index.ts CHANGED
@@ -1,64 +1,64 @@
1
- import type { DynamicStructuredTool } from "@langchain/core/tools";
2
- import { IHttpLlmController, ILlmController } from "@typia/interface";
3
-
4
- import { LangChainToolsRegistrar } from "./internal/LangChainToolsRegistrar";
5
-
6
- /**
7
- * Convert typia controllers to LangChain tools.
8
- *
9
- * Converts TypeScript class methods via `typia.llm.controller<Class>()` or
10
- * OpenAPI operations via `HttpLlm.controller()` to LangChain tools.
11
- *
12
- * Every tool call is validated by typia. If LLM provides invalid arguments,
13
- * returns validation error formatted by {@link LlmJson.stringify} so that LLM
14
- * can correct them automatically.
15
- *
16
- * @example
17
- * ```typescript
18
- * import { initChatModel } from "langchain/chat_models/universal";
19
- * import typia from "typia";
20
- * import { toLangChainTools } from "@typia/langchain";
21
- *
22
- * class Calculator {
23
- * add(input: { a: number; b: number }): { value: number } {
24
- * return { value: input.a + input.b };
25
- * }
26
- * }
27
- *
28
- * const tools = toLangChainTools({
29
- * controllers: [
30
- * typia.llm.controller<Calculator>("calculator", new Calculator()),
31
- * ],
32
- * });
33
- *
34
- * const llm = await initChatModel();
35
- * const modelWithTools = llm.bindTools(tools);
36
- * const result = await modelWithTools.invoke("What is 10 + 5?");
37
- * ```;
38
- *
39
- * @param props Conversion properties
40
- * @returns Array of LangChain DynamicStructuredTool
41
- */
42
- export function toLangChainTools(props: {
43
- /**
44
- * List of controllers to convert to LangChain tools.
45
- *
46
- * - {@link ILlmController}: from `typia.llm.controller<Class>()`, converts all
47
- * methods of the class to tools
48
- * - {@link IHttpLlmController}: from `HttpLlm.controller()`, converts all
49
- * operations from OpenAPI document to tools
50
- */
51
- controllers: Array<ILlmController | IHttpLlmController>;
52
-
53
- /**
54
- * Whether to add controller name as prefix to tool names.
55
- *
56
- * If `true`, tool names become `{controllerName}_{methodName}`. If `false`,
57
- * tool names are just `{methodName}`.
58
- *
59
- * @default false
60
- */
61
- prefix?: boolean | undefined;
62
- }): DynamicStructuredTool[] {
63
- return LangChainToolsRegistrar.convert(props);
64
- }
1
+ import type { DynamicStructuredTool } from "@langchain/core/tools";
2
+ import { IHttpLlmController, ILlmController } from "@typia/interface";
3
+
4
+ import { LangChainToolsRegistrar } from "./internal/LangChainToolsRegistrar";
5
+
6
+ /**
7
+ * Convert typia controllers to LangChain tools.
8
+ *
9
+ * Converts TypeScript class methods via `typia.llm.controller<Class>()` or
10
+ * OpenAPI operations via `HttpLlm.controller()` to LangChain tools.
11
+ *
12
+ * Every tool call is validated by typia. If LLM provides invalid arguments,
13
+ * returns validation error formatted by {@link LlmJson.stringify} so that LLM
14
+ * can correct them automatically.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { initChatModel } from "langchain/chat_models/universal";
19
+ * import typia from "typia";
20
+ * import { toLangChainTools } from "@typia/langchain";
21
+ *
22
+ * class Calculator {
23
+ * add(input: { a: number; b: number }): { value: number } {
24
+ * return { value: input.a + input.b };
25
+ * }
26
+ * }
27
+ *
28
+ * const tools = toLangChainTools({
29
+ * controllers: [
30
+ * typia.llm.controller<Calculator>("calculator", new Calculator()),
31
+ * ],
32
+ * });
33
+ *
34
+ * const llm = await initChatModel();
35
+ * const modelWithTools = llm.bindTools(tools);
36
+ * const result = await modelWithTools.invoke("What is 10 + 5?");
37
+ * ```;
38
+ *
39
+ * @param props Conversion properties
40
+ * @returns Array of LangChain DynamicStructuredTool
41
+ */
42
+ export function toLangChainTools(props: {
43
+ /**
44
+ * List of controllers to convert to LangChain tools.
45
+ *
46
+ * - {@link ILlmController}: from `typia.llm.controller<Class>()`, converts all
47
+ * methods of the class to tools
48
+ * - {@link IHttpLlmController}: from `HttpLlm.controller()`, converts all
49
+ * operations from OpenAPI document to tools
50
+ */
51
+ controllers: Array<ILlmController | IHttpLlmController>;
52
+
53
+ /**
54
+ * Whether to add controller name as prefix to tool names.
55
+ *
56
+ * If `true`, tool names become `{controllerName}_{methodName}`. If `false`,
57
+ * tool names are just `{methodName}`.
58
+ *
59
+ * @default false
60
+ */
61
+ prefix?: boolean | undefined;
62
+ }): DynamicStructuredTool[] {
63
+ return LangChainToolsRegistrar.convert(props);
64
+ }
@@ -1,149 +1,149 @@
1
- import {
2
- DynamicStructuredTool,
3
- ToolInputParsingException,
4
- } from "@langchain/core/tools";
5
- import {
6
- IHttpLlmController,
7
- IHttpLlmFunction,
8
- ILlmController,
9
- ILlmFunction,
10
- IValidation,
11
- } from "@typia/interface";
12
- import { HttpLlm, LlmJson } from "@typia/utils";
13
-
14
- export namespace LangChainToolsRegistrar {
15
- export const convert = (props: {
16
- controllers: Array<ILlmController | IHttpLlmController>;
17
- prefix?: boolean | undefined;
18
- }): DynamicStructuredTool[] => {
19
- const prefix: boolean = props.prefix ?? false;
20
- const tools: DynamicStructuredTool[] = [];
21
-
22
- // check duplicate tool names
23
- if (prefix === false && props.controllers.length >= 2) {
24
- const names: Map<string, string> = new Map();
25
- const duplicates: string[] = [];
26
- for (const controller of props.controllers) {
27
- for (const func of controller.application.functions) {
28
- const existing: string | undefined = names.get(func.name);
29
- if (existing !== undefined)
30
- duplicates.push(
31
- `"${func.name}" in "${controller.name}" (conflicts with "${existing}")`,
32
- );
33
- else names.set(func.name, controller.name);
34
- }
35
- }
36
- if (duplicates.length > 0)
37
- throw new Error(
38
- `Duplicate tool names found:\n - ${duplicates.join("\n - ")}`,
39
- );
40
- }
41
-
42
- // convert controllers to tools
43
- for (const controller of props.controllers) {
44
- if (controller.protocol === "class") {
45
- convertClassController(tools, controller, prefix);
46
- } else {
47
- convertHttpController(tools, controller, prefix);
48
- }
49
- }
50
-
51
- return tools;
52
- };
53
-
54
- const convertClassController = (
55
- tools: DynamicStructuredTool[],
56
- controller: ILlmController,
57
- prefix: boolean,
58
- ): void => {
59
- const execute: Record<string, unknown> = controller.execute;
60
-
61
- for (const func of controller.application.functions) {
62
- const toolName: string = prefix
63
- ? `${controller.name}_${func.name}`
64
- : func.name;
65
-
66
- const method: unknown = execute[func.name];
67
- if (typeof method !== "function") {
68
- throw new Error(
69
- `Method "${func.name}" not found on controller "${controller.name}"`,
70
- );
71
- }
72
-
73
- tools.push(
74
- createTool({
75
- name: toolName,
76
- function: func,
77
- execute: async (args: unknown) => method.call(execute, args),
78
- }),
79
- );
80
- }
81
- };
82
-
83
- const convertHttpController = (
84
- tools: DynamicStructuredTool[],
85
- controller: IHttpLlmController,
86
- prefix: boolean,
87
- ): void => {
88
- const application = controller.application;
89
- const connection = controller.connection;
90
-
91
- for (const func of application.functions) {
92
- const toolName: string = prefix
93
- ? `${controller.name}_${func.name}`
94
- : func.name;
95
-
96
- tools.push(
97
- createTool({
98
- name: toolName,
99
- function: func,
100
- execute: async (args: unknown) => {
101
- if (controller.execute !== undefined) {
102
- const response = await controller.execute({
103
- connection,
104
- application,
105
- function: func,
106
- arguments: args as object,
107
- });
108
- return response.body;
109
- }
110
- return HttpLlm.execute({
111
- application,
112
- function: func,
113
- connection,
114
- input: args as object,
115
- });
116
- },
117
- }),
118
- );
119
- }
120
- };
121
-
122
- const createTool = (entry: {
123
- name: string;
124
- function: ILlmFunction | IHttpLlmFunction;
125
- execute: (args: unknown) => Promise<unknown>;
126
- }): DynamicStructuredTool =>
127
- new DynamicStructuredTool<any>({
128
- name: entry.name,
129
- description: entry.function.description ?? "",
130
- schema: entry.function.parameters,
131
- func: async (args: unknown): Promise<unknown> => {
132
- const coerced: unknown = LlmJson.coerce(
133
- args,
134
- entry.function.parameters,
135
- );
136
- const valid: IValidation<unknown> = entry.function.validate(coerced);
137
- if (valid.success === false)
138
- throw new ToolInputParsingException(
139
- `Type errors in "${entry.name}" arguments:\n\n` +
140
- `\`\`\`json\n${LlmJson.stringify(valid)}\n\`\`\``,
141
- JSON.stringify(coerced),
142
- );
143
- const result: unknown = await entry.execute(valid.data);
144
- return result === undefined
145
- ? { success: true }
146
- : { success: true, data: result };
147
- },
148
- });
149
- }
1
+ import {
2
+ DynamicStructuredTool,
3
+ ToolInputParsingException,
4
+ } from "@langchain/core/tools";
5
+ import {
6
+ IHttpLlmController,
7
+ IHttpLlmFunction,
8
+ ILlmController,
9
+ ILlmFunction,
10
+ IValidation,
11
+ } from "@typia/interface";
12
+ import { HttpLlm, LlmJson } from "@typia/utils";
13
+
14
+ export namespace LangChainToolsRegistrar {
15
+ export const convert = (props: {
16
+ controllers: Array<ILlmController | IHttpLlmController>;
17
+ prefix?: boolean | undefined;
18
+ }): DynamicStructuredTool[] => {
19
+ const prefix: boolean = props.prefix ?? false;
20
+ const tools: DynamicStructuredTool[] = [];
21
+
22
+ // check duplicate tool names
23
+ if (prefix === false && props.controllers.length >= 2) {
24
+ const names: Map<string, string> = new Map();
25
+ const duplicates: string[] = [];
26
+ for (const controller of props.controllers) {
27
+ for (const func of controller.application.functions) {
28
+ const existing: string | undefined = names.get(func.name);
29
+ if (existing !== undefined)
30
+ duplicates.push(
31
+ `"${func.name}" in "${controller.name}" (conflicts with "${existing}")`,
32
+ );
33
+ else names.set(func.name, controller.name);
34
+ }
35
+ }
36
+ if (duplicates.length > 0)
37
+ throw new Error(
38
+ `Duplicate tool names found:\n - ${duplicates.join("\n - ")}`,
39
+ );
40
+ }
41
+
42
+ // convert controllers to tools
43
+ for (const controller of props.controllers) {
44
+ if (controller.protocol === "class") {
45
+ convertClassController(tools, controller, prefix);
46
+ } else {
47
+ convertHttpController(tools, controller, prefix);
48
+ }
49
+ }
50
+
51
+ return tools;
52
+ };
53
+
54
+ const convertClassController = (
55
+ tools: DynamicStructuredTool[],
56
+ controller: ILlmController,
57
+ prefix: boolean,
58
+ ): void => {
59
+ const execute: Record<string, unknown> = controller.execute;
60
+
61
+ for (const func of controller.application.functions) {
62
+ const toolName: string = prefix
63
+ ? `${controller.name}_${func.name}`
64
+ : func.name;
65
+
66
+ const method: unknown = execute[func.name];
67
+ if (typeof method !== "function") {
68
+ throw new Error(
69
+ `Method "${func.name}" not found on controller "${controller.name}"`,
70
+ );
71
+ }
72
+
73
+ tools.push(
74
+ createTool({
75
+ name: toolName,
76
+ function: func,
77
+ execute: async (args: unknown) => method.call(execute, args),
78
+ }),
79
+ );
80
+ }
81
+ };
82
+
83
+ const convertHttpController = (
84
+ tools: DynamicStructuredTool[],
85
+ controller: IHttpLlmController,
86
+ prefix: boolean,
87
+ ): void => {
88
+ const application = controller.application;
89
+ const connection = controller.connection;
90
+
91
+ for (const func of application.functions) {
92
+ const toolName: string = prefix
93
+ ? `${controller.name}_${func.name}`
94
+ : func.name;
95
+
96
+ tools.push(
97
+ createTool({
98
+ name: toolName,
99
+ function: func,
100
+ execute: async (args: unknown) => {
101
+ if (controller.execute !== undefined) {
102
+ const response = await controller.execute({
103
+ connection,
104
+ application,
105
+ function: func,
106
+ arguments: args as object,
107
+ });
108
+ return response.body;
109
+ }
110
+ return HttpLlm.execute({
111
+ application,
112
+ function: func,
113
+ connection,
114
+ input: args as object,
115
+ });
116
+ },
117
+ }),
118
+ );
119
+ }
120
+ };
121
+
122
+ const createTool = (entry: {
123
+ name: string;
124
+ function: ILlmFunction | IHttpLlmFunction;
125
+ execute: (args: unknown) => Promise<unknown>;
126
+ }): DynamicStructuredTool =>
127
+ new DynamicStructuredTool<any>({
128
+ name: entry.name,
129
+ description: entry.function.description ?? "",
130
+ schema: entry.function.parameters,
131
+ func: async (args: unknown): Promise<unknown> => {
132
+ const coerced: unknown = LlmJson.coerce(
133
+ args,
134
+ entry.function.parameters,
135
+ );
136
+ const valid: IValidation<unknown> = entry.function.validate(coerced);
137
+ if (valid.success === false)
138
+ throw new ToolInputParsingException(
139
+ `Type errors in "${entry.name}" arguments:\n\n` +
140
+ `\`\`\`json\n${LlmJson.stringify(valid)}\n\`\`\``,
141
+ JSON.stringify(coerced),
142
+ );
143
+ const result: unknown = await entry.execute(valid.data);
144
+ return result === undefined
145
+ ? { success: true }
146
+ : { success: true, data: result };
147
+ },
148
+ });
149
+ }