@typia/langchain 12.0.0-dev.20260225

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 ADDED
@@ -0,0 +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.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # `@typia/langchain`
2
+
3
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/samchon/typia/blob/master/LICENSE)
4
+ [![NPM Version](https://img.shields.io/npm/v/typia.svg)](https://www.npmjs.com/package/typia)
5
+ [![NPM Downloads](https://img.shields.io/npm/dm/typia.svg)](https://www.npmjs.com/package/typia)
6
+
7
+ [LangChain.js](https://github.com/langchain-ai/langchainjs) integration for [`typia`](https://github.com/samchon/typia).
8
+
9
+ Converts typia controllers to LangChain `DynamicStructuredTool[]` with automatic validation.
10
+
11
+ ## Setup
12
+
13
+ ```bash
14
+ npm install @typia/langchain @langchain/core
15
+ npm install typia
16
+ npx typia setup
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### From TypeScript class
22
+
23
+ ```typescript
24
+ import { ChainValues, Runnable } from "@langchain/core";
25
+ import { ChatPromptTemplate } from "@langchain/core/prompts";
26
+ import { DynamicStructuredTool } from "@langchain/core/tools";
27
+ import { ChatOpenAI } from "@langchain/openai";
28
+ import { toLangChainTools } from "@typia/langchain";
29
+ import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
30
+ import typia from "typia";
31
+
32
+ const tools: DynamicStructuredTool[] = toLangChainTools({
33
+ controllers: [
34
+ typia.llm.controller<Calculator>("Calculator", new Calculator()),
35
+ ],
36
+ });
37
+
38
+ const agent: Runnable = createToolCallingAgent({
39
+ llm: new ChatOpenAI({ model: "gpt-4o" }),
40
+ tools,
41
+ prompt: ChatPromptTemplate.fromMessages([
42
+ ["system", "You are a helpful assistant."],
43
+ ["human", "{input}"],
44
+ ["placeholder", "{agent_scratchpad}"],
45
+ ]),
46
+ });
47
+ const executor: AgentExecutor = new AgentExecutor({ agent, tools });
48
+ const result: ChainValues = await executor.invoke({ input: "What is 10 + 5?" });
49
+ ```
50
+
51
+ ### From OpenAPI document
52
+
53
+ ```typescript
54
+ import { DynamicStructuredTool } from "@langchain/core/tools";
55
+ import { toLangChainTools } from "@typia/langchain";
56
+ import { HttpLlm } from "@typia/utils";
57
+
58
+ const tools: DynamicStructuredTool[] = toLangChainTools({
59
+ controllers: [
60
+ HttpLlm.controller({
61
+ name: "petStore",
62
+ document: yourOpenApiDocument,
63
+ connection: { host: "https://api.example.com" },
64
+ }),
65
+ ],
66
+ });
67
+ ```
68
+
69
+ ## Features
70
+
71
+ - No manual schema definition — generates everything from TypeScript types or OpenAPI
72
+ - Automatic argument validation with LLM-friendly error feedback
73
+ - Supports both class-based (`typia.llm.controller`) and HTTP-based (`HttpLlm.controller`) controllers
package/lib/index.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { DynamicStructuredTool } from "@langchain/core/tools";
2
+ import { IHttpLlmController, ILlmController } from "@typia/interface";
3
+ /**
4
+ * Convert typia controllers to LangChain tools.
5
+ *
6
+ * Converts TypeScript class methods via `typia.llm.controller<Class>()` or
7
+ * OpenAPI operations via `HttpLlm.controller()` to LangChain tools.
8
+ *
9
+ * Every tool call is validated by typia. If LLM provides invalid arguments,
10
+ * returns validation error formatted by {@link stringifyValidationFailure}
11
+ * so that LLM can correct them automatically.
12
+ *
13
+ * @param props Conversion properties
14
+ * @returns Array of LangChain DynamicStructuredTool
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { ChatOpenAI } from "@langchain/openai";
19
+ * import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
20
+ * import typia from "typia";
21
+ * import { toLangChainTools } from "@typia/langchain";
22
+ *
23
+ * class Calculator {
24
+ * add(input: { a: number; b: number }): number {
25
+ * return input.a + input.b;
26
+ * }
27
+ * }
28
+ *
29
+ * const tools = toLangChainTools({
30
+ * controllers: [
31
+ * typia.llm.controller<Calculator>("calculator", new Calculator()),
32
+ * ],
33
+ * });
34
+ *
35
+ * const llm = new ChatOpenAI({ model: "gpt-4" });
36
+ * const agent = createToolCallingAgent({ llm, tools, prompt });
37
+ * const executor = new AgentExecutor({ agent, tools });
38
+ * await executor.invoke({ input: "What is 10 + 5?" });
39
+ * ```
40
+ */
41
+ export declare function toLangChainTools(props: {
42
+ /**
43
+ * List of controllers to convert to LangChain tools.
44
+ *
45
+ * - {@link ILlmController}: from `typia.llm.controller<Class>()`, converts
46
+ * all methods of the class to tools
47
+ * - {@link IHttpLlmController}: from `HttpLlm.controller()`, converts all
48
+ * operations from OpenAPI document to tools
49
+ */
50
+ controllers: Array<ILlmController | IHttpLlmController>;
51
+ /**
52
+ * Whether to add controller name as prefix to tool names.
53
+ *
54
+ * If `true`, tool names become `{controllerName}_{methodName}`.
55
+ * If `false`, tool names are just `{methodName}`.
56
+ *
57
+ * @default true
58
+ */
59
+ prefix?: boolean | undefined;
60
+ }): DynamicStructuredTool[];
package/lib/index.js ADDED
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toLangChainTools = toLangChainTools;
4
+ const LangChainToolsRegistrar_1 = require("./internal/LangChainToolsRegistrar");
5
+ /**
6
+ * Convert typia controllers to LangChain tools.
7
+ *
8
+ * Converts TypeScript class methods via `typia.llm.controller<Class>()` or
9
+ * OpenAPI operations via `HttpLlm.controller()` to LangChain tools.
10
+ *
11
+ * Every tool call is validated by typia. If LLM provides invalid arguments,
12
+ * returns validation error formatted by {@link stringifyValidationFailure}
13
+ * so that LLM can correct them automatically.
14
+ *
15
+ * @param props Conversion properties
16
+ * @returns Array of LangChain DynamicStructuredTool
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { ChatOpenAI } from "@langchain/openai";
21
+ * import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
22
+ * import typia from "typia";
23
+ * import { toLangChainTools } from "@typia/langchain";
24
+ *
25
+ * class Calculator {
26
+ * add(input: { a: number; b: number }): number {
27
+ * return input.a + input.b;
28
+ * }
29
+ * }
30
+ *
31
+ * const tools = toLangChainTools({
32
+ * controllers: [
33
+ * typia.llm.controller<Calculator>("calculator", new Calculator()),
34
+ * ],
35
+ * });
36
+ *
37
+ * const llm = new ChatOpenAI({ model: "gpt-4" });
38
+ * const agent = createToolCallingAgent({ llm, tools, prompt });
39
+ * const executor = new AgentExecutor({ agent, tools });
40
+ * await executor.invoke({ input: "What is 10 + 5?" });
41
+ * ```
42
+ */
43
+ function toLangChainTools(props) {
44
+ return LangChainToolsRegistrar_1.LangChainToolsRegistrar.convert(props);
45
+ }
46
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AA2CA,4CAsBC;AA9DD,gFAA6E;AAE7E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,SAAgB,gBAAgB,CAAC,KAoBhC;IACC,OAAO,iDAAuB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAChD,CAAC"}
package/lib/index.mjs ADDED
@@ -0,0 +1,46 @@
1
+ import { LangChainToolsRegistrar } from './internal/LangChainToolsRegistrar.mjs';
2
+
3
+ /**
4
+ * Convert typia controllers to LangChain tools.
5
+ *
6
+ * Converts TypeScript class methods via `typia.llm.controller<Class>()` or
7
+ * OpenAPI operations via `HttpLlm.controller()` to LangChain tools.
8
+ *
9
+ * Every tool call is validated by typia. If LLM provides invalid arguments,
10
+ * returns validation error formatted by {@link stringifyValidationFailure}
11
+ * so that LLM can correct them automatically.
12
+ *
13
+ * @param props Conversion properties
14
+ * @returns Array of LangChain DynamicStructuredTool
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { ChatOpenAI } from "@langchain/openai";
19
+ * import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
20
+ * import typia from "typia";
21
+ * import { toLangChainTools } from "@typia/langchain";
22
+ *
23
+ * class Calculator {
24
+ * add(input: { a: number; b: number }): number {
25
+ * return input.a + input.b;
26
+ * }
27
+ * }
28
+ *
29
+ * const tools = toLangChainTools({
30
+ * controllers: [
31
+ * typia.llm.controller<Calculator>("calculator", new Calculator()),
32
+ * ],
33
+ * });
34
+ *
35
+ * const llm = new ChatOpenAI({ model: "gpt-4" });
36
+ * const agent = createToolCallingAgent({ llm, tools, prompt });
37
+ * const executor = new AgentExecutor({ agent, tools });
38
+ * await executor.invoke({ input: "What is 10 + 5?" });
39
+ * ```
40
+ */
41
+ function toLangChainTools(props) {
42
+ return LangChainToolsRegistrar.convert(props);
43
+ }
44
+
45
+ export { toLangChainTools };
46
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":[null],"names":[],"mappings":";;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCG;AACG,SAAU,gBAAgB,CAAC,KAoBhC,EAAA;AACC,IAAA,OAAO,uBAAuB,CAAC,OAAO,CAAC,KAAK,CAAC;AAC/C;;;;"}
@@ -0,0 +1,8 @@
1
+ import { DynamicStructuredTool } from "@langchain/core/tools";
2
+ import { IHttpLlmController, ILlmController } from "@typia/interface";
3
+ export declare namespace LangChainToolsRegistrar {
4
+ const convert: (props: {
5
+ controllers: Array<ILlmController | IHttpLlmController>;
6
+ prefix?: boolean | undefined;
7
+ }) => DynamicStructuredTool[];
8
+ }
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.LangChainToolsRegistrar = void 0;
13
+ const tools_1 = require("@langchain/core/tools");
14
+ const utils_1 = require("@typia/utils");
15
+ const zod_1 = require("zod");
16
+ var LangChainToolsRegistrar;
17
+ (function (LangChainToolsRegistrar) {
18
+ LangChainToolsRegistrar.convert = (props) => {
19
+ var _a;
20
+ const prefix = (_a = props.prefix) !== null && _a !== void 0 ? _a : true;
21
+ const tools = [];
22
+ for (const controller of props.controllers) {
23
+ if (controller.protocol === "class") {
24
+ convertClassController(tools, controller, prefix);
25
+ }
26
+ else {
27
+ convertHttpController(tools, controller, prefix);
28
+ }
29
+ }
30
+ return tools;
31
+ };
32
+ const convertClassController = (tools, controller, prefix) => {
33
+ const execute = controller.execute;
34
+ for (const func of controller.application.functions) {
35
+ const method = execute[func.name];
36
+ if (typeof method !== "function") {
37
+ throw new Error(`Method "${func.name}" not found on controller "${controller.name}"`);
38
+ }
39
+ const toolName = prefix
40
+ ? `${controller.name}_${func.name}`
41
+ : func.name;
42
+ tools.push(createTool({
43
+ name: toolName,
44
+ function: func,
45
+ execute: (args) => __awaiter(this, void 0, void 0, function* () { return method.call(execute, args); }),
46
+ }));
47
+ }
48
+ };
49
+ const convertHttpController = (tools, controller, prefix) => {
50
+ const application = controller.application;
51
+ const connection = controller.connection;
52
+ for (const func of application.functions) {
53
+ const toolName = prefix
54
+ ? `${controller.name}_${func.name}`
55
+ : func.name;
56
+ tools.push(createTool({
57
+ name: toolName,
58
+ function: func,
59
+ execute: (args) => __awaiter(this, void 0, void 0, function* () {
60
+ if (controller.execute !== undefined) {
61
+ const response = yield controller.execute({
62
+ connection,
63
+ application,
64
+ function: func,
65
+ arguments: args,
66
+ });
67
+ return response.body;
68
+ }
69
+ return utils_1.HttpLlm.execute({
70
+ application,
71
+ function: func,
72
+ connection,
73
+ input: args,
74
+ });
75
+ }),
76
+ }));
77
+ }
78
+ };
79
+ // Schema that accepts any object - bypasses LangChain's validation
80
+ // so typia can handle all validation with proper error messages.
81
+ // LangChain validates JSON Schema using @cfworker/json-schema which
82
+ // throws ToolInputParsingException before reaching our func.
83
+ const passthroughSchema = zod_1.z.record(zod_1.z.unknown());
84
+ const createTool = (entry) => {
85
+ var _a;
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
+ return new tools_1.DynamicStructuredTool({
88
+ name: entry.name,
89
+ description: (_a = entry.function.description) !== null && _a !== void 0 ? _a : "",
90
+ schema: passthroughSchema,
91
+ func: (args) => __awaiter(this, void 0, void 0, function* () {
92
+ const validation = entry.function.validate(args);
93
+ if (!validation.success) {
94
+ return (0, utils_1.stringifyValidationFailure)(validation);
95
+ }
96
+ try {
97
+ const result = yield entry.execute(validation.data);
98
+ return result === undefined
99
+ ? "Success"
100
+ : JSON.stringify(result, null, 2);
101
+ }
102
+ catch (error) {
103
+ return error instanceof Error
104
+ ? `${error.name}: ${error.message}`
105
+ : String(error);
106
+ }
107
+ }),
108
+ });
109
+ };
110
+ })(LangChainToolsRegistrar || (exports.LangChainToolsRegistrar = LangChainToolsRegistrar = {}));
111
+ //# sourceMappingURL=LangChainToolsRegistrar.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LangChainToolsRegistrar.js","sourceRoot":"","sources":["../../src/internal/LangChainToolsRegistrar.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iDAA8D;AAQ9D,wCAAmE;AACnE,6BAAwB;AAExB,IAAiB,uBAAuB,CA2HvC;AA3HD,WAAiB,uBAAuB;IACzB,+BAAO,GAAG,CAAC,KAGvB,EAA2B,EAAE;;QAC5B,MAAM,MAAM,GAAY,MAAA,KAAK,CAAC,MAAM,mCAAI,IAAI,CAAC;QAC7C,MAAM,KAAK,GAA4B,EAAE,CAAC;QAE1C,KAAK,MAAM,UAAU,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;YAC3C,IAAI,UAAU,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;gBACpC,sBAAsB,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC;YACpD,CAAC;iBAAM,CAAC;gBACN,qBAAqB,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC;YACnD,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IAEF,MAAM,sBAAsB,GAAG,CAC7B,KAA8B,EAC9B,UAA0B,EAC1B,MAAe,EACT,EAAE;QACR,MAAM,OAAO,GAA4B,UAAU,CAAC,OAAO,CAAC;QAE5D,KAAK,MAAM,IAAI,IAAI,UAAU,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC;YACpD,MAAM,MAAM,GAAY,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC3C,IAAI,OAAO,MAAM,KAAK,UAA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AC,GAAG,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE;wBACnC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACpB,CAAC;YACH,CAAC,CAAA;SACF,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC,EA3HgB,uBAAuB,uCAAvB,uBAAuB,QA2HvC"}
@@ -0,0 +1,100 @@
1
+ import { DynamicStructuredTool } from '@langchain/core/tools';
2
+ import { stringifyValidationFailure, HttpLlm } from '@typia/utils';
3
+ import { z } from 'zod';
4
+
5
+ var LangChainToolsRegistrar;
6
+ (function (LangChainToolsRegistrar) {
7
+ LangChainToolsRegistrar.convert = (props) => {
8
+ const prefix = props.prefix ?? true;
9
+ const tools = [];
10
+ for (const controller of props.controllers) {
11
+ if (controller.protocol === "class") {
12
+ convertClassController(tools, controller, prefix);
13
+ }
14
+ else {
15
+ convertHttpController(tools, controller, prefix);
16
+ }
17
+ }
18
+ return tools;
19
+ };
20
+ const convertClassController = (tools, controller, prefix) => {
21
+ const execute = controller.execute;
22
+ for (const func of controller.application.functions) {
23
+ const method = execute[func.name];
24
+ if (typeof method !== "function") {
25
+ throw new Error(`Method "${func.name}" not found on controller "${controller.name}"`);
26
+ }
27
+ const toolName = prefix
28
+ ? `${controller.name}_${func.name}`
29
+ : func.name;
30
+ tools.push(createTool({
31
+ name: toolName,
32
+ function: func,
33
+ execute: async (args) => method.call(execute, args),
34
+ }));
35
+ }
36
+ };
37
+ const convertHttpController = (tools, controller, prefix) => {
38
+ const application = controller.application;
39
+ const connection = controller.connection;
40
+ for (const func of application.functions) {
41
+ const toolName = prefix
42
+ ? `${controller.name}_${func.name}`
43
+ : func.name;
44
+ tools.push(createTool({
45
+ name: toolName,
46
+ function: func,
47
+ execute: async (args) => {
48
+ if (controller.execute !== undefined) {
49
+ const response = await controller.execute({
50
+ connection,
51
+ application,
52
+ function: func,
53
+ arguments: args,
54
+ });
55
+ return response.body;
56
+ }
57
+ return HttpLlm.execute({
58
+ application,
59
+ function: func,
60
+ connection,
61
+ input: args,
62
+ });
63
+ },
64
+ }));
65
+ }
66
+ };
67
+ // Schema that accepts any object - bypasses LangChain's validation
68
+ // so typia can handle all validation with proper error messages.
69
+ // LangChain validates JSON Schema using @cfworker/json-schema which
70
+ // throws ToolInputParsingException before reaching our func.
71
+ const passthroughSchema = z.record(z.unknown());
72
+ const createTool = (entry) => {
73
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
+ return new DynamicStructuredTool({
75
+ name: entry.name,
76
+ description: entry.function.description ?? "",
77
+ schema: passthroughSchema,
78
+ func: async (args) => {
79
+ const validation = entry.function.validate(args);
80
+ if (!validation.success) {
81
+ return stringifyValidationFailure(validation);
82
+ }
83
+ try {
84
+ const result = await entry.execute(validation.data);
85
+ return result === undefined
86
+ ? "Success"
87
+ : JSON.stringify(result, null, 2);
88
+ }
89
+ catch (error) {
90
+ return error instanceof Error
91
+ ? `${error.name}: ${error.message}`
92
+ : String(error);
93
+ }
94
+ },
95
+ });
96
+ };
97
+ })(LangChainToolsRegistrar || (LangChainToolsRegistrar = {}));
98
+
99
+ export { LangChainToolsRegistrar };
100
+ //# sourceMappingURL=LangChainToolsRegistrar.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LangChainToolsRegistrar.mjs","sources":["../../src/internal/LangChainToolsRegistrar.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAWM,IAAW;AAAjB,CAAA,UAAiB,uBAAuB,EAAA;AACzB,IAAA,uBAAA,CAAA,OAAO,GAAG,CAAC,KAGvB,KAA6B;AAC5B,QAAA,MAAM,MAAM,GAAY,KAAK,CAAC,MAAM,IAAI,IAAI;QAC5C,MAAM,KAAK,GAA4B,EAAE;AAEzC,QAAA,KAAK,MAAM,UAAU,IAAI,KAAK,CAAC,WAAW,EAAE;AAC1C,YAAA,IAAI,UAAU,CAAC,QAAQ,KAAK,OAAO,EAAE;AACnC,gBAAA,sBAAsB,CAAC,KAAK,EAAE,UAA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;AAEA,gBAAA,IAAI;oBACF,MAAM,MAAM,GAAY,MAAM,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC;oBAC5D,OAAO,MAAM,KAAK;AAChB,0BAAE;0BACA,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;gBACrC;gBAAE,OAAO,KAAK,EAAE;oBACd,OAAO,KAAK,YAAY;0BACpB,GAAG,KAAK,CAAC,IAAI,CAAA,EAAA,EAAK,KAAK,CAAC,OAAO,CAAA;AACjC,0BAAE,MAAM,CAAC,KAAK,CAAC;gBACnB;YACF,CAAC;AACF,SAAA,CAAC;AACJ,IAAA,CAAC;AACH,CAAC,EA3HgB,uBAAuB,KAAvB,uBAAuB,GAAA,EAAA,CAAA,CAAA;;;;"}
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@typia/langchain",
3
+ "version": "12.0.0-dev.20260225",
4
+ "description": "LangChain.js integration for typia",
5
+ "main": "lib/index.js",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./lib/index.d.ts",
9
+ "import": "./lib/index.mjs",
10
+ "default": "./lib/index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/samchon/typia"
17
+ },
18
+ "author": "Jeongho Nam",
19
+ "license": "MIT",
20
+ "bugs": {
21
+ "url": "https://github.com/samchon/typia/issues"
22
+ },
23
+ "homepage": "https://typia.io",
24
+ "dependencies": {
25
+ "zod": "^3.25.0",
26
+ "@typia/interface": "^12.0.0-dev.20260225",
27
+ "@typia/utils": "^12.0.0-dev.20260225"
28
+ },
29
+ "peerDependencies": {
30
+ "@langchain/core": ">=0.3.0"
31
+ },
32
+ "devDependencies": {
33
+ "@langchain/core": "^0.3.44",
34
+ "@rollup/plugin-commonjs": "^29.0.0",
35
+ "@rollup/plugin-node-resolve": "^16.0.3",
36
+ "@rollup/plugin-typescript": "^12.3.0",
37
+ "rimraf": "^6.1.2",
38
+ "rollup": "^4.56.0",
39
+ "rollup-plugin-auto-external": "^2.0.0",
40
+ "rollup-plugin-node-externals": "^8.1.2",
41
+ "tinyglobby": "^0.2.12",
42
+ "typescript": "~5.9.3"
43
+ },
44
+ "sideEffects": false,
45
+ "files": [
46
+ "LICENSE",
47
+ "README.md",
48
+ "package.json",
49
+ "lib",
50
+ "src"
51
+ ],
52
+ "keywords": [
53
+ "langchain",
54
+ "typia",
55
+ "llm",
56
+ "llm-function-calling",
57
+ "ai",
58
+ "claude",
59
+ "openai",
60
+ "chatgpt",
61
+ "gemini",
62
+ "validation",
63
+ "json-schema",
64
+ "typescript"
65
+ ],
66
+ "publishConfig": {
67
+ "access": "public"
68
+ },
69
+ "scripts": {
70
+ "build": "rimraf lib && tsc && rollup -c",
71
+ "dev": "rimraf lib && tsc --watch"
72
+ },
73
+ "module": "lib/index.mjs",
74
+ "types": "lib/index.d.ts"
75
+ }
package/src/index.ts ADDED
@@ -0,0 +1,66 @@
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 stringifyValidationFailure}
14
+ * so that LLM can correct them automatically.
15
+ *
16
+ * @param props Conversion properties
17
+ * @returns Array of LangChain DynamicStructuredTool
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { ChatOpenAI } from "@langchain/openai";
22
+ * import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
23
+ * import typia from "typia";
24
+ * import { toLangChainTools } from "@typia/langchain";
25
+ *
26
+ * class Calculator {
27
+ * add(input: { a: number; b: number }): number {
28
+ * return input.a + input.b;
29
+ * }
30
+ * }
31
+ *
32
+ * const tools = toLangChainTools({
33
+ * controllers: [
34
+ * typia.llm.controller<Calculator>("calculator", new Calculator()),
35
+ * ],
36
+ * });
37
+ *
38
+ * const llm = new ChatOpenAI({ model: "gpt-4" });
39
+ * const agent = createToolCallingAgent({ llm, tools, prompt });
40
+ * const executor = new AgentExecutor({ agent, tools });
41
+ * await executor.invoke({ input: "What is 10 + 5?" });
42
+ * ```
43
+ */
44
+ export function toLangChainTools(props: {
45
+ /**
46
+ * List of controllers to convert to LangChain tools.
47
+ *
48
+ * - {@link ILlmController}: from `typia.llm.controller<Class>()`, converts
49
+ * all methods of the class to tools
50
+ * - {@link IHttpLlmController}: from `HttpLlm.controller()`, converts all
51
+ * operations from OpenAPI document to tools
52
+ */
53
+ controllers: Array<ILlmController | IHttpLlmController>;
54
+
55
+ /**
56
+ * Whether to add controller name as prefix to tool names.
57
+ *
58
+ * If `true`, tool names become `{controllerName}_{methodName}`.
59
+ * If `false`, tool names are just `{methodName}`.
60
+ *
61
+ * @default true
62
+ */
63
+ prefix?: boolean | undefined;
64
+ }): DynamicStructuredTool[] {
65
+ return LangChainToolsRegistrar.convert(props);
66
+ }
@@ -0,0 +1,135 @@
1
+ import { DynamicStructuredTool } from "@langchain/core/tools";
2
+ import {
3
+ IHttpLlmController,
4
+ IHttpLlmFunction,
5
+ ILlmController,
6
+ ILlmFunction,
7
+ IValidation,
8
+ } from "@typia/interface";
9
+ import { HttpLlm, stringifyValidationFailure } from "@typia/utils";
10
+ import { z } from "zod";
11
+
12
+ export namespace LangChainToolsRegistrar {
13
+ export const convert = (props: {
14
+ controllers: Array<ILlmController | IHttpLlmController>;
15
+ prefix?: boolean | undefined;
16
+ }): DynamicStructuredTool[] => {
17
+ const prefix: boolean = props.prefix ?? true;
18
+ const tools: DynamicStructuredTool[] = [];
19
+
20
+ for (const controller of props.controllers) {
21
+ if (controller.protocol === "class") {
22
+ convertClassController(tools, controller, prefix);
23
+ } else {
24
+ convertHttpController(tools, controller, prefix);
25
+ }
26
+ }
27
+
28
+ return tools;
29
+ };
30
+
31
+ const convertClassController = (
32
+ tools: DynamicStructuredTool[],
33
+ controller: ILlmController,
34
+ prefix: boolean,
35
+ ): void => {
36
+ const execute: Record<string, unknown> = controller.execute;
37
+
38
+ for (const func of controller.application.functions) {
39
+ const method: unknown = execute[func.name];
40
+ if (typeof method !== "function") {
41
+ throw new Error(
42
+ `Method "${func.name}" not found on controller "${controller.name}"`,
43
+ );
44
+ }
45
+
46
+ const toolName: string = prefix
47
+ ? `${controller.name}_${func.name}`
48
+ : func.name;
49
+
50
+ tools.push(
51
+ createTool({
52
+ name: toolName,
53
+ function: func,
54
+ execute: async (args: unknown) => method.call(execute, args),
55
+ }),
56
+ );
57
+ }
58
+ };
59
+
60
+ const convertHttpController = (
61
+ tools: DynamicStructuredTool[],
62
+ controller: IHttpLlmController,
63
+ prefix: boolean,
64
+ ): void => {
65
+ const application = controller.application;
66
+ const connection = controller.connection;
67
+
68
+ for (const func of application.functions) {
69
+ const toolName: string = prefix
70
+ ? `${controller.name}_${func.name}`
71
+ : func.name;
72
+
73
+ tools.push(
74
+ createTool({
75
+ name: toolName,
76
+ function: func,
77
+ execute: async (args: unknown) => {
78
+ if (controller.execute !== undefined) {
79
+ const response = await controller.execute({
80
+ connection,
81
+ application,
82
+ function: func,
83
+ arguments: args as object,
84
+ });
85
+ return response.body;
86
+ }
87
+ return HttpLlm.execute({
88
+ application,
89
+ function: func,
90
+ connection,
91
+ input: args as object,
92
+ });
93
+ },
94
+ }),
95
+ );
96
+ }
97
+ };
98
+
99
+ // Schema that accepts any object - bypasses LangChain's validation
100
+ // so typia can handle all validation with proper error messages.
101
+ // LangChain validates JSON Schema using @cfworker/json-schema which
102
+ // throws ToolInputParsingException before reaching our func.
103
+ const passthroughSchema = z.record(z.unknown());
104
+
105
+ const createTool = (entry: {
106
+ name: string;
107
+ function: ILlmFunction | IHttpLlmFunction;
108
+ execute: (args: unknown) => Promise<unknown>;
109
+ }): DynamicStructuredTool => {
110
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
111
+ return new DynamicStructuredTool<any>({
112
+ name: entry.name,
113
+ description: entry.function.description ?? "",
114
+ schema: passthroughSchema,
115
+ func: async (args: unknown): Promise<string> => {
116
+ const validation: IValidation<unknown> =
117
+ entry.function.validate(args);
118
+ if (!validation.success) {
119
+ return stringifyValidationFailure(validation);
120
+ }
121
+
122
+ try {
123
+ const result: unknown = await entry.execute(validation.data);
124
+ return result === undefined
125
+ ? "Success"
126
+ : JSON.stringify(result, null, 2);
127
+ } catch (error) {
128
+ return error instanceof Error
129
+ ? `${error.name}: ${error.message}`
130
+ : String(error);
131
+ }
132
+ },
133
+ });
134
+ };
135
+ }