Skip to content

Commit ec3a37c

Browse files
authored
Add validateInstance method to TypeChatJsonTranslator (#115)
1 parent d9f0458 commit ec3a37c

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/typechat.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Result, error } from "./result";
1+
import { Result, success, error } from "./result";
22
import { TypeChatLanguageModel } from "./model";
33
import { TypeChatJsonValidator, createJsonValidator } from "./validate";
44

@@ -42,6 +42,15 @@ export interface TypeChatJsonTranslator<T extends object> {
4242
* @returns A repair prompt constructed from the error message.
4343
*/
4444
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>;
4554
/**
4655
* Translates a natural language request into an object of type `T`. If the JSON object returned by
4756
* 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
7180
stripNulls: false,
7281
createRequestPrompt,
7382
createRepairPrompt,
83+
validateInstance: success,
7484
translate
7585
};
7686
return typeChat;
@@ -104,7 +114,8 @@ export function createJsonTranslator<T extends object>(model: TypeChatLanguageMo
104114
return error(`Response is not JSON:\n${responseText}`);
105115
}
106116
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;
108119
if (validation.success) {
109120
return validation;
110121
}

0 commit comments

Comments
 (0)