|
1 | | -import { Result, error } from "./result"; |
| 1 | +import { Result, success, error } from "./result"; |
2 | 2 | import { TypeChatLanguageModel } from "./model"; |
3 | 3 | import { TypeChatJsonValidator, createJsonValidator } from "./validate"; |
4 | 4 |
|
@@ -42,6 +42,15 @@ export interface TypeChatJsonTranslator<T extends object> { |
42 | 42 | * @returns A repair prompt constructed from the error message. |
43 | 43 | */ |
44 | 44 | createRepairPrompt(validationError: string): string; |
| 45 | + /** |
| 46 | + * Optionally implements additional validation logic beyond what is expressed in the schema. This function is |
| 47 | + * called following successful schema validation of an instance. By default the function just returns a |
| 48 | + * `Success<T>` for the given instance, but an application can assign a new function that implements any |
| 49 | + * additional validation. |
| 50 | + * @param instance The instance to validate. |
| 51 | + * @returns A `Success<T>` with the final validated instance, or an `Error` explaning the validation failure. |
| 52 | + */ |
| 53 | + validateInstance(instance: T): Result<T>; |
45 | 54 | /** |
46 | 55 | * Translates a natural language request into an object of type `T`. If the JSON object returned by |
47 | 56 | * the language model fails to validate and the `attemptRepair` property is `true`, a second |
@@ -71,6 +80,7 @@ export function createJsonTranslator<T extends object>(model: TypeChatLanguageMo |
71 | 80 | stripNulls: false, |
72 | 81 | createRequestPrompt, |
73 | 82 | createRepairPrompt, |
| 83 | + validateInstance: success, |
74 | 84 | translate |
75 | 85 | }; |
76 | 86 | return typeChat; |
@@ -104,7 +114,8 @@ export function createJsonTranslator<T extends object>(model: TypeChatLanguageMo |
104 | 114 | return error(`Response is not JSON:\n${responseText}`); |
105 | 115 | } |
106 | 116 | const jsonText = responseText.slice(startIndex, endIndex + 1); |
107 | | - const validation = validator.validate(jsonText); |
| 117 | + const schemaValidation = validator.validate(jsonText); |
| 118 | + const validation = schemaValidation.success ? typeChat.validateInstance(schemaValidation.data) : schemaValidation; |
108 | 119 | if (validation.success) { |
109 | 120 | return validation; |
110 | 121 | } |
|
0 commit comments