TypeChat allows you to turn user intent into structured, type-safe JSON by combining a human prompt with a TypeScript schema.
To implement this:
- Define a TypeScript interface for your expected response.
- Create a language model using
createLanguageModel. - Create a translator using
createJsonTranslator, passing the model, the schema file content, and the name of the interface. - Use the translator's
.translate() method to process requests. The result contains either the typed data or a message describing the failure.
import * as fs from "fs";
import * as path from "path";
import dotenv from "dotenv";
import * as typechat from "typechat";
import { SentimentResponse } from "./sentimentSchema";
// Load environment variables.
dotenv.config({ path: path.join(__dirname, "../.env") });
// Create a language model based on the environment variables.
const model = typechat.createLanguageModel(process.env);
// Load up the contents of our "Response" schema.
const schema = fs.readFileSync(path.join(__dirname, "sentimentSchema.ts"), "utf8");
const translator = typechat.createJsonTranslator<SentimentResponse>(model, schema, "SentimentResponse");
// Process requests interactively.
typechat.processRequests("😀> ", /*inputFile*/ undefined, async (request) => {
const response = await translator.translate(request);
if (!response.success) {
console.log(response.message);
return;
}
console.log(`The sentiment is ${response.data.sentiment}`);
});