UNPKG

typia

Version:

Superfast runtime validators with only one line

1 lines 17.5 kB
{"version":3,"file":"llm.mjs","names":[],"sources":["../src/llm.ts"],"sourcesContent":["import {\n IJsonParseResult,\n ILlmApplication,\n ILlmController,\n ILlmSchema,\n ILlmStructuredOutput,\n} from \"@typia/interface\";\n\nimport { NoTransformConfigurationError } from \"./transformers/NoTransformConfigurationError\";\n\n/* -----------------------------------------------------------\n FUNCTION CALLING\n----------------------------------------------------------- */\n/**\n * Creates LLM function calling controller.\n *\n * @danger You must configure the generic argument `Class`\n */\nexport function controller(\n name: string,\n execute: object,\n config?: Partial<Pick<ILlmApplication.IConfig<any>, \"validate\">>,\n): never;\n\n/**\n * Creates LLM function calling controller from class/interface.\n *\n * Generates {@link ILlmController} from a TypeScript class or interface,\n * containing both function calling schemas ({@link ILlmFunction}) and an\n * executor ({@link ILlmController.execute}).\n *\n * Each {@link ILlmFunction} includes a built-in {@link ILlmFunction.validate}\n * function that validates LLM-generated arguments before execution. When\n * validation fails, use `LlmJson.stringify()` from `@typia/utils` to format\n * errors for LLM feedback, enabling auto-correction.\n *\n * When passed to LLM providers (ChatGPT, Claude, Gemini, etc.), the LLM\n * automatically selects functions and fills arguments from conversation.\n * Execute the selected function via {@link ILlmController.execute}.\n *\n * Related functions:\n *\n * - {@link application} — Schemas only, without executor\n * - {@link parameters} — Single parameters schema for structured output\n * - {@link schema} — Single type schema\n *\n * @template Class Target class or interface type\n * @template Config LLM schema configuration\n * @param name Controller identifier name\n * @param execute Executor instance\n * @param config LLM application options\n * @returns LLM function calling controller\n */\nexport function controller<\n Class extends Record<string, any>,\n Config extends Partial<\n ILlmSchema.IConfig & {\n /**\n * Whether to disallow superfluous properties or not.\n *\n * If configure as `true`, {@link validateEquals} function would be used\n * for validation feedback, which is more strict than {@link validate}\n * function.\n *\n * @default false\n */\n equals: boolean;\n }\n > = {},\n>(\n name: string,\n execute: Class,\n config?: Partial<Pick<ILlmApplication.IConfig<Class>, \"validate\">>,\n): ILlmController<Class>;\n\n/** @internal */\nexport function controller(..._args: any[]): never {\n NoTransformConfigurationError(\"llm.controller\");\n}\n\n/**\n * Creates LLM function calling application.\n *\n * @danger You must configure the generic argument `Class`\n */\nexport function application(\n config?: Partial<Pick<ILlmApplication.IConfig<any>, \"validate\">>,\n): never;\n\n/**\n * Creates LLM function calling application from class/interface.\n *\n * Generates {@link ILlmApplication} from a TypeScript class or interface,\n * containing function calling schemas ({@link ILlmFunction}). Does not include\n * an executor—use {@link controller} if you need execution capability.\n *\n * Each {@link ILlmFunction} includes a built-in {@link ILlmFunction.validate}\n * function that validates LLM-generated arguments before execution. When\n * validation fails, use `LlmJson.stringify()` from `@typia/utils` to format\n * errors for LLM feedback, enabling auto-correction.\n *\n * When passed to LLM providers (ChatGPT, Claude, Gemini, etc.), the LLM\n * automatically selects functions and fills arguments from conversation. You\n * execute the function manually with the LLM-prepared arguments.\n *\n * Related functions:\n *\n * - {@link controller} — Includes executor alongside schemas\n * - {@link parameters} — Single parameters schema for structured output\n * - {@link schema} — Single type schema\n *\n * @template Class Target class or interface type\n * @template Config LLM schema configuration\n * @param config LLM application options\n * @returns LLM function calling application\n */\nexport function application<\n Class extends Record<string, any>,\n Config extends Partial<\n ILlmSchema.IConfig & {\n /**\n * Whether to disallow superfluous properties or not.\n *\n * If configure as `true`, {@link validateEquals} function would be used\n * for validation feedback, which is more strict than {@link validate}\n * function.\n *\n * @default false\n */\n equals: boolean;\n }\n > = {},\n>(\n config?: Partial<Pick<ILlmApplication.IConfig<Class>, \"validate\">>,\n): ILlmApplication<Class>;\n\n/** @internal */\nexport function application(): never {\n NoTransformConfigurationError(\"llm.application\");\n}\n\n/**\n * Creates LLM structured output interface.\n *\n * @danger You must configure the generic argument `T`\n */\nexport function structuredOutput(): never;\n\n/**\n * Creates LLM structured output interface from TypeScript object type.\n *\n * Generates {@link ILlmStructuredOutput} containing everything needed for\n * handling LLM structured outputs: the JSON schema for prompting, and functions\n * for parsing, coercing, and validating responses.\n *\n * Structured outputs allow LLMs to generate data conforming to a predefined\n * schema instead of free-form text. This is useful for:\n *\n * - Extracting structured data from conversations\n * - Generating typed responses for downstream processing\n * - Ensuring consistent output formats across LLM calls\n *\n * Workflow:\n *\n * 1. Pass {@link ILlmStructuredOutput.parameters} schema to LLM provider\n * 2. Receive LLM response (JSON string or pre-parsed object)\n * 3. Use {@link ILlmStructuredOutput.parse} for raw strings or\n * {@link ILlmStructuredOutput.coerce} for pre-parsed objects\n * 4. Use {@link ILlmStructuredOutput.validate} to check the result\n *\n * Related functions:\n *\n * - {@link parameters} — Schema only, without parse/coerce/validate\n * - {@link application} — Multiple function schemas from class/interface\n * - {@link controller} — Application with executor\n *\n * @template T Target output type (object with static properties)\n * @template Config LLM schema configuration\n * @returns LLM structured output interface\n */\nexport function structuredOutput<\n T extends Record<string, any>,\n Config extends Partial<\n ILlmSchema.IConfig & {\n /**\n * Whether to disallow superfluous properties or not.\n *\n * If configure as `true`, {@link validateEquals} function would be used\n * for validation feedback, which is more strict than {@link validate}\n * function.\n *\n * @default false\n */\n equals: boolean;\n }\n > = {},\n>(): ILlmStructuredOutput<T>;\n\n/** @internal */\nexport function structuredOutput(): never {\n NoTransformConfigurationError(\"llm.structuredOutput\");\n}\n\n/* -----------------------------------------------------------\n RAW SCHEMAS\n----------------------------------------------------------- */\n/**\n * Creates LLM parameters schema.\n *\n * @danger You must configure the generic argument `Parameters`\n */\nexport function parameters(): never;\n\n/**\n * Creates LLM parameters schema from TypeScript object type.\n *\n * Generates {@link ILlmSchema.IParameters} for LLM function calling or\n * structured outputs. LLMs use keyworded arguments only, so the type must be an\n * object with static properties (no dynamic properties allowed).\n *\n * Use cases:\n *\n * - Function calling: LLM fills parameters from conversation\n * - Structured outputs: LLM generates structured data, not plain text\n *\n * Related functions:\n *\n * - {@link application} — Multiple function schemas from class/interface\n * - {@link controller} — Application with executor\n * - {@link schema} — Single type schema (not parameters-specific)\n *\n * @template Parameters Target parameters type (object with static properties)\n * @template Config LLM schema configuration\n * @returns LLM parameters schema\n */\nexport function parameters<\n Parameters extends Record<string, any>,\n Config extends Partial<ILlmSchema.IConfig> = {},\n>(): ILlmSchema.IParameters;\n\n/** @internal */\nexport function parameters(): never {\n NoTransformConfigurationError(\"llm.parameters\");\n}\n\n/**\n * Creates LLM type schema.\n *\n * @danger You must configure the generic argument `T`\n */\nexport function schema(): never;\n\n/**\n * Creates LLM type schema from TypeScript type.\n *\n * Generates {@link ILlmSchema} for use in LLM function calling. For actual\n * function calling with TypeScript functions, use {@link application}. For\n * structured output generation, use {@link parameters}.\n *\n * LLM function calling flow:\n *\n * 1. LLM selects function and fills arguments from conversation\n * 2. You execute the function with LLM-prepared arguments\n * 3. Return value is passed back to LLM via system prompt\n * 4. LLM continues conversation based on return value\n *\n * Related functions:\n *\n * - {@link application} — Multiple function schemas from class/interface\n * - {@link controller} — Application with executor\n * - {@link parameters} — Parameters schema for structured output\n *\n * @template T Target type\n * @template Config LLM schema configuration\n * @param $defs Shared schema definitions for `$ref` referencing\n * @returns LLM type schema\n */\nexport function schema<T, Config = {}>(\n $defs: Record<string, ILlmSchema>,\n): ILlmSchema;\n\n/** @internal */\nexport function schema(): never {\n NoTransformConfigurationError(\"llm.schema\");\n}\n\n/* -----------------------------------------------------------\n UTILITY FUNCTIONS\n----------------------------------------------------------- */\n/**\n * Parse LLM response JSON with type coercion.\n *\n * @danger You must configure the generic argument `Parameters`\n */\nexport function parse(input: string): never;\n\n/**\n * Parse lenient JSON with schema-based type coercion.\n *\n * Handles incomplete or malformed JSON commonly produced by LLMs:\n *\n * - Unclosed brackets, strings, trailing commas\n * - JavaScript-style comments (`//` and multi-line)\n * - Unquoted object keys, incomplete keywords (`tru`, `fal`, `nul`)\n * - Markdown code block extraction, junk prefix skipping\n *\n * Also coerces double-stringified values based on the `Parameters` schema:\n *\n * - `\"42\"` → `42` (when schema expects number)\n * - `\"true\"` → `true` (when schema expects boolean)\n * - `\"null\"` → `null` (when schema expects null)\n * - `\"{...}\"` → `{...}` (when schema expects object)\n * - `\"[...]\"` → `[...]` (when schema expects array)\n *\n * Type validation is NOT performed—use {@link ILlmFunction.validate} or\n * `typia.validate()` for that.\n *\n * For repeated parsing, use {@link createParse} to avoid regenerating the schema\n * each time.\n *\n * Related functions:\n *\n * - {@link createParse} — Create reusable parser function\n * - {@link coerce} — Type coercion for already-parsed objects\n * - {@link parameters} — Generate parameters schema from type\n *\n * @template Parameters Target parameters type (object with static properties)\n * @template Config LLM schema configuration\n * @param input Raw JSON string (potentially incomplete or malformed)\n * @returns Parse result with typed data on success, or partial data with errors\n */\nexport function parse<\n Parameters extends Record<string, any>,\n Config extends Partial<ILlmSchema.IConfig> = {},\n>(input: string): IJsonParseResult<Parameters>;\n\n/** @internal */\nexport function parse(): never {\n NoTransformConfigurationError(\"llm.parse\");\n}\n\n/**\n * Coerce LLM arguments to match expected schema types.\n *\n * LLMs often return values with incorrect types (e.g., numbers as strings).\n * This function recursively coerces values based on the `Parameters` schema:\n *\n * - `\"42\"` → `42` (when schema expects number)\n * - `\"true\"` → `true` (when schema expects boolean)\n * - `\"null\"` → `null` (when schema expects null)\n * - `\"{...}\"` → `{...}` (when schema expects object)\n * - `\"[...]\"` → `[...]` (when schema expects array)\n *\n * Use this when your SDK provides already-parsed objects but values may have\n * wrong types. For raw JSON strings, use {@link parse} instead.\n *\n * For repeated coercion, use {@link createCoerce} to avoid regenerating the\n * schema each time.\n *\n * Type validation is NOT performed—use {@link ILlmFunction.validate} or\n * `typia.validate()` for that.\n *\n * Related functions:\n *\n * - {@link createCoerce} — Create reusable coercer function\n * - {@link parse} — Parse and coerce raw JSON strings\n * - {@link parameters} — Generate parameters schema from type\n *\n * @template Parameters Target parameters type (object with static properties)\n * @template Config LLM schema configuration\n * @param input Parsed arguments object from LLM (with potentially wrong types)\n * @returns Coerced arguments with corrected types\n */\nexport function coerce<\n Parameters extends Record<string, any>,\n Config extends Partial<ILlmSchema.IConfig> = {},\n>(input: Parameters): Parameters;\n\n/** @internal */\nexport function coerce(): never {\n NoTransformConfigurationError(\"llm.coerce\");\n}\n\n/**\n * Create reusable LLM JSON parser with type coercion.\n *\n * @danger You must configure the generic argument `Parameters`\n */\nexport function createParse(): never;\n\n/**\n * Create reusable lenient JSON parser with schema-based type coercion.\n *\n * Returns a parser function that handles incomplete or malformed JSON commonly\n * produced by LLMs:\n *\n * - Unclosed brackets, strings, trailing commas\n * - JavaScript-style comments (`//` and multi-line)\n * - Unquoted object keys, incomplete keywords (`tru`, `fal`, `nul`)\n * - Markdown code block extraction, junk prefix skipping\n *\n * Also coerces double-stringified values based on the `Parameters` schema:\n *\n * - `\"42\"` → `42` (when schema expects number)\n * - `\"true\"` → `true` (when schema expects boolean)\n * - `\"null\"` → `null` (when schema expects null)\n * - `\"{...}\"` → `{...}` (when schema expects object)\n * - `\"[...]\"` → `[...]` (when schema expects array)\n *\n * Use this instead of {@link parse} when parsing multiple inputs to avoid\n * regenerating the schema each time.\n *\n * Type validation is NOT performed—use {@link ILlmFunction.validate} or\n * `typia.validate()` for that.\n *\n * Related functions:\n *\n * - {@link parse} — One-shot parsing (regenerates schema each call)\n * - {@link createCoerce} — Create reusable coercer function\n * - {@link parameters} — Generate parameters schema from type\n *\n * @template Parameters Target parameters type (object with static properties)\n * @template Config LLM schema configuration\n * @returns Reusable parser function\n */\nexport function createParse<\n Parameters extends Record<string, any>,\n Config extends Partial<ILlmSchema.IConfig> = {},\n>(): (input: string) => IJsonParseResult<Parameters>;\n\n/** @internal */\nexport function createParse(): never {\n NoTransformConfigurationError(\"llm.createParse\");\n}\n\n/**\n * Create reusable LLM arguments coercer.\n *\n * @danger You must configure the generic argument `Parameters`\n */\nexport function createCoerce(): never;\n\n/**\n * Create reusable coercer for LLM arguments.\n *\n * Returns a coercer function that fixes incorrect types commonly returned by\n * LLMs (e.g., numbers as strings). Coerces values based on the `Parameters`\n * schema:\n *\n * - `\"42\"` → `42` (when schema expects number)\n * - `\"true\"` → `true` (when schema expects boolean)\n * - `\"null\"` → `null` (when schema expects null)\n * - `\"{...}\"` → `{...}` (when schema expects object)\n * - `\"[...]\"` → `[...]` (when schema expects array)\n *\n * Use this instead of {@link coerce} when coercing multiple inputs to avoid\n * regenerating the schema each time.\n *\n * Type validation is NOT performed—use {@link ILlmFunction.validate} or\n * `typia.validate()` for that.\n *\n * Related functions:\n *\n * - {@link coerce} — One-shot coercion (regenerates schema each call)\n * - {@link createParse} — Create reusable parser function\n * - {@link parameters} — Generate parameters schema from type\n *\n * @template Parameters Target parameters type (object with static properties)\n * @template Config LLM schema configuration\n * @returns Reusable coercer function\n */\nexport function createCoerce<\n Parameters extends Record<string, any>,\n Config extends Partial<ILlmSchema.IConfig> = {},\n>(): (input: Parameters) => Parameters;\n\n/** @internal */\nexport function createCoerce(): never {\n NoTransformConfigurationError(\"llm.createCoerce\");\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4EA,SAAgB,WAAW,GAAG,OAAqB;CACjD,8BAA8B,gBAAgB;AAChD;;AA2DA,SAAgB,cAAqB;CACnC,8BAA8B,iBAAiB;AACjD;;AA4DA,SAAgB,mBAA0B;CACxC,8BAA8B,sBAAsB;AACtD;;AAwCA,SAAgB,aAAoB;CAClC,8BAA8B,gBAAgB;AAChD;;AAuCA,SAAgB,SAAgB;CAC9B,8BAA8B,YAAY;AAC5C;;AAqDA,SAAgB,QAAe;CAC7B,8BAA8B,WAAW;AAC3C;;AAwCA,SAAgB,SAAgB;CAC9B,8BAA8B,YAAY;AAC5C;;AAkDA,SAAgB,cAAqB;CACnC,8BAA8B,iBAAiB;AACjD;;AA4CA,SAAgB,eAAsB;CACpC,8BAA8B,kBAAkB;AAClD"}