@typia/utils 12.0.0 → 12.1.0-dev.20260325

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.
@@ -1,173 +1,173 @@
1
- import {
2
- IJsonParseResult,
3
- ILlmSchema,
4
- ILlmStructuredOutput,
5
- IValidation,
6
- OpenApi,
7
- } from "@typia/interface";
8
-
9
- import { LlmSchemaConverter } from "../converters";
10
- import { OpenApiValidator } from "../validators";
11
- import { coerceLlmArguments } from "./internal/coerceLlmArguments";
12
- import { parseLenientJson } from "./internal/parseLenientJson";
13
- import { stringifyValidationFailure } from "./internal/stringifyValidationFailure";
14
-
15
- /**
16
- * JSON utilities for LLM function calling.
17
- *
18
- * - {@link LlmJson.parse}: Lenient JSON parser for incomplete/malformed JSON
19
- * - {@link LlmJson.stringify}: Format validation errors for LLM feedback
20
- * - {@link LlmJson.validate}: Create a reusable validator from schema
21
- *
22
- * @author Jeongho Nam - https://github.com/samchon
23
- */
24
- export namespace LlmJson {
25
- /**
26
- * Coerce LLM arguments to match expected schema types.
27
- *
28
- * LLMs often return values with incorrect types (e.g., numbers as strings).
29
- * This function recursively coerces values based on the schema:
30
- *
31
- * - `"42"` → `42` (when schema expects number)
32
- * - `"true"` → `true` (when schema expects boolean)
33
- * - `"null"` → `null` (when schema expects null)
34
- * - `"{...}"` → `{...}` (when schema expects object)
35
- * - `"[...]"` → `[...]` (when schema expects array)
36
- *
37
- * Use this when SDK provides already-parsed objects but values may have wrong
38
- * types. For raw JSON strings, use {@link parse} instead.
39
- *
40
- * @param input Parsed arguments object from LLM
41
- * @param parameters LLM function parameters schema for type coercion
42
- * @returns Coerced arguments with corrected types
43
- */
44
- export function coerce<T = unknown>(
45
- input: unknown,
46
- parameters: ILlmSchema.IParameters,
47
- ): T {
48
- return coerceLlmArguments(input, parameters);
49
- }
50
-
51
- /**
52
- * Parse lenient JSON with optional schema-based coercion.
53
- *
54
- * Handles incomplete/malformed JSON commonly produced by LLMs:
55
- *
56
- * - Unclosed brackets, strings, trailing commas
57
- * - JavaScript-style comments (`//` and multi-line)
58
- * - Unquoted object keys, incomplete keywords (`tru`, `fal`, `nul`)
59
- * - Markdown code block extraction, junk prefix skipping
60
- *
61
- * When `parameters` schema is provided, also coerces double-stringified
62
- * values: `"42"` → `42`, `"true"` → `true`, `"{...}"` → `{...}` based on
63
- * expected types.
64
- *
65
- * Type validation is NOT performed - use {@link ILlmFunction.validate}.
66
- *
67
- * @param input Raw JSON string (potentially incomplete or malformed)
68
- * @param parameters Optional LLM parameters schema for type coercion
69
- * @returns Parse result with data on success, or partial data with errors
70
- */
71
- export function parse<T = unknown>(
72
- input: string,
73
- parameters?: ILlmSchema.IParameters,
74
- ): IJsonParseResult<T> {
75
- const result: IJsonParseResult<T> = parseLenientJson<T>(input);
76
-
77
- // Apply schema-based coercion if parameters provided and parsing succeeded
78
- if (parameters !== undefined && result.success) {
79
- return {
80
- success: true,
81
- data: coerceLlmArguments(result.data, parameters) as T,
82
- };
83
- }
84
- return result;
85
- }
86
-
87
- /**
88
- * Format validation failure for LLM auto-correction feedback.
89
- *
90
- * When LLM generates invalid function call arguments, this produces annotated
91
- * JSON with inline `// ❌` error comments at each invalid property. The output
92
- * is wrapped in a markdown code block so that LLM can understand and correct
93
- * its mistakes in the next turn.
94
- *
95
- * Below is an example of the output format:
96
- *
97
- * ```json
98
- * {
99
- * "name": "John",
100
- * "age": "twenty", // ❌ [{"path":"$input.age","expected":"number & Type<\"uint32\">"}]
101
- * "email": "not-an-email", // ❌ [{"path":"$input.email","expected":"string & Format<\"email\">"}]
102
- * "hobbies": "reading" // ❌ [{"path":"$input.hobbies","expected":"Array<string>"}]
103
- * }
104
- * ```
105
- *
106
- * @param failure Validation failure from {@link ILlmFunction.validate}
107
- */
108
- export function stringify(failure: IValidation.IFailure): string {
109
- return stringifyValidationFailure(failure);
110
- }
111
-
112
- /**
113
- * Create a reusable validator from LLM parameters schema.
114
- *
115
- * When validation fails, format the failure with {@link stringify} for LLM
116
- * auto-correction feedback.
117
- *
118
- * @param parameters LLM function parameters schema
119
- * @param equals If `true`, reject extraneous properties not defined in the
120
- * schema. Otherwise, extra properties are ignored.
121
- * @returns Validator function that checks data against the schema
122
- */
123
- export function validate(
124
- parameters: ILlmSchema.IParameters,
125
- equals?: boolean | undefined,
126
- ) {
127
- const components: OpenApi.IComponents = {
128
- schemas: {},
129
- };
130
- const schema: OpenApi.IJsonSchema = LlmSchemaConverter.invert({
131
- components,
132
- schema: parameters,
133
- $defs: parameters.$defs,
134
- });
135
- return OpenApiValidator.create({
136
- components,
137
- schema,
138
- required: true,
139
- equals,
140
- });
141
- }
142
-
143
- /**
144
- * Convert LLM parameters schema to structured output interface.
145
- *
146
- * Creates an {@link ILlmStructuredOutput} containing everything needed for
147
- * handling LLM structured outputs: the parameters schema for prompting, and
148
- * functions for parsing, coercing, and validating responses.
149
- *
150
- * This is useful when you have a parameters schema (e.g., from
151
- * `typia.llm.parameters()`) and need the full structured output interface
152
- * with all utility functions.
153
- *
154
- * @template T The expected output type
155
- * @param parameters LLM parameters schema
156
- * @param equals If `true`, reject extraneous properties not defined in the
157
- * schema during validation. Otherwise, extra properties are ignored.
158
- * @returns Structured output interface with parse, coerce, and validate
159
- */
160
- export function structuredOutput<T>(
161
- parameters: ILlmSchema.IParameters,
162
- equals?: boolean | undefined,
163
- ): ILlmStructuredOutput<T> {
164
- const validator = validate(parameters, equals);
165
- return {
166
- parameters,
167
- parse: (str: string): IJsonParseResult<T> => parse(str, parameters),
168
- coerce: (input: unknown): T => coerce(input, parameters),
169
- validate: (input: unknown): IValidation<T> =>
170
- validator(input) as IValidation<T>,
171
- };
172
- }
173
- }
1
+ import {
2
+ IJsonParseResult,
3
+ ILlmSchema,
4
+ ILlmStructuredOutput,
5
+ IValidation,
6
+ OpenApi,
7
+ } from "@typia/interface";
8
+
9
+ import { LlmSchemaConverter } from "../converters";
10
+ import { OpenApiValidator } from "../validators";
11
+ import { coerceLlmArguments } from "./internal/coerceLlmArguments";
12
+ import { parseLenientJson } from "./internal/parseLenientJson";
13
+ import { stringifyValidationFailure } from "./internal/stringifyValidationFailure";
14
+
15
+ /**
16
+ * JSON utilities for LLM function calling.
17
+ *
18
+ * - {@link LlmJson.parse}: Lenient JSON parser for incomplete/malformed JSON
19
+ * - {@link LlmJson.stringify}: Format validation errors for LLM feedback
20
+ * - {@link LlmJson.validate}: Create a reusable validator from schema
21
+ *
22
+ * @author Jeongho Nam - https://github.com/samchon
23
+ */
24
+ export namespace LlmJson {
25
+ /**
26
+ * Coerce LLM arguments to match expected schema types.
27
+ *
28
+ * LLMs often return values with incorrect types (e.g., numbers as strings).
29
+ * This function recursively coerces values based on the schema:
30
+ *
31
+ * - `"42"` → `42` (when schema expects number)
32
+ * - `"true"` → `true` (when schema expects boolean)
33
+ * - `"null"` → `null` (when schema expects null)
34
+ * - `"{...}"` → `{...}` (when schema expects object)
35
+ * - `"[...]"` → `[...]` (when schema expects array)
36
+ *
37
+ * Use this when SDK provides already-parsed objects but values may have wrong
38
+ * types. For raw JSON strings, use {@link parse} instead.
39
+ *
40
+ * @param input Parsed arguments object from LLM
41
+ * @param parameters LLM function parameters schema for type coercion
42
+ * @returns Coerced arguments with corrected types
43
+ */
44
+ export function coerce<T = unknown>(
45
+ input: unknown,
46
+ parameters: ILlmSchema.IParameters,
47
+ ): T {
48
+ return coerceLlmArguments(input, parameters);
49
+ }
50
+
51
+ /**
52
+ * Parse lenient JSON with optional schema-based coercion.
53
+ *
54
+ * Handles incomplete/malformed JSON commonly produced by LLMs:
55
+ *
56
+ * - Unclosed brackets, strings, trailing commas
57
+ * - JavaScript-style comments (`//` and multi-line)
58
+ * - Unquoted object keys, incomplete keywords (`tru`, `fal`, `nul`)
59
+ * - Markdown code block extraction, junk prefix skipping
60
+ *
61
+ * When `parameters` schema is provided, also coerces double-stringified
62
+ * values: `"42"` → `42`, `"true"` → `true`, `"{...}"` → `{...}` based on
63
+ * expected types.
64
+ *
65
+ * Type validation is NOT performed - use {@link ILlmFunction.validate}.
66
+ *
67
+ * @param input Raw JSON string (potentially incomplete or malformed)
68
+ * @param parameters Optional LLM parameters schema for type coercion
69
+ * @returns Parse result with data on success, or partial data with errors
70
+ */
71
+ export function parse<T = unknown>(
72
+ input: string,
73
+ parameters?: ILlmSchema.IParameters,
74
+ ): IJsonParseResult<T> {
75
+ const result: IJsonParseResult<T> = parseLenientJson<T>(input);
76
+
77
+ // Apply schema-based coercion if parameters provided and parsing succeeded
78
+ if (parameters !== undefined && result.success) {
79
+ return {
80
+ success: true,
81
+ data: coerceLlmArguments(result.data, parameters) as T,
82
+ };
83
+ }
84
+ return result;
85
+ }
86
+
87
+ /**
88
+ * Format validation failure for LLM auto-correction feedback.
89
+ *
90
+ * When LLM generates invalid function call arguments, this produces annotated
91
+ * JSON with inline `// ❌` error comments at each invalid property. The output
92
+ * is wrapped in a markdown code block so that LLM can understand and correct
93
+ * its mistakes in the next turn.
94
+ *
95
+ * Below is an example of the output format:
96
+ *
97
+ * ```json
98
+ * {
99
+ * "name": "John",
100
+ * "age": "twenty", // ❌ [{"path":"$input.age","expected":"number & Type<\"uint32\">"}]
101
+ * "email": "not-an-email", // ❌ [{"path":"$input.email","expected":"string & Format<\"email\">"}]
102
+ * "hobbies": "reading" // ❌ [{"path":"$input.hobbies","expected":"Array<string>"}]
103
+ * }
104
+ * ```
105
+ *
106
+ * @param failure Validation failure from {@link ILlmFunction.validate}
107
+ */
108
+ export function stringify(failure: IValidation.IFailure): string {
109
+ return stringifyValidationFailure(failure);
110
+ }
111
+
112
+ /**
113
+ * Create a reusable validator from LLM parameters schema.
114
+ *
115
+ * When validation fails, format the failure with {@link stringify} for LLM
116
+ * auto-correction feedback.
117
+ *
118
+ * @param parameters LLM function parameters schema
119
+ * @param equals If `true`, reject extraneous properties not defined in the
120
+ * schema. Otherwise, extra properties are ignored.
121
+ * @returns Validator function that checks data against the schema
122
+ */
123
+ export function validate(
124
+ parameters: ILlmSchema.IParameters,
125
+ equals?: boolean | undefined,
126
+ ) {
127
+ const components: OpenApi.IComponents = {
128
+ schemas: {},
129
+ };
130
+ const schema: OpenApi.IJsonSchema = LlmSchemaConverter.invert({
131
+ components,
132
+ schema: parameters,
133
+ $defs: parameters.$defs,
134
+ });
135
+ return OpenApiValidator.create({
136
+ components,
137
+ schema,
138
+ required: true,
139
+ equals,
140
+ });
141
+ }
142
+
143
+ /**
144
+ * Convert LLM parameters schema to structured output interface.
145
+ *
146
+ * Creates an {@link ILlmStructuredOutput} containing everything needed for
147
+ * handling LLM structured outputs: the parameters schema for prompting, and
148
+ * functions for parsing, coercing, and validating responses.
149
+ *
150
+ * This is useful when you have a parameters schema (e.g., from
151
+ * `typia.llm.parameters()`) and need the full structured output interface
152
+ * with all utility functions.
153
+ *
154
+ * @template T The expected output type
155
+ * @param parameters LLM parameters schema
156
+ * @param equals If `true`, reject extraneous properties not defined in the
157
+ * schema during validation. Otherwise, extra properties are ignored.
158
+ * @returns Structured output interface with parse, coerce, and validate
159
+ */
160
+ export function structuredOutput<T>(
161
+ parameters: ILlmSchema.IParameters,
162
+ equals?: boolean | undefined,
163
+ ): ILlmStructuredOutput<T> {
164
+ const validator = validate(parameters, equals);
165
+ return {
166
+ parameters,
167
+ parse: (str: string): IJsonParseResult<T> => parse(str, parameters),
168
+ coerce: (input: unknown): T => coerce(input, parameters),
169
+ validate: (input: unknown): IValidation<T> =>
170
+ validator(input) as IValidation<T>,
171
+ };
172
+ }
173
+ }