Typesafe API for chat


The Chat and ChatBuilder classes are designed to help you create and manage a conversation with the ChatGPT model. The Chat class represents a conversation with multiple messages, while the ChatBuilder class helps you create a Chat instance by adding messages step by step. Both classes support input validation, allowing you to ensure that the input data matches the expected format.

Basic Usage

To create a conversation using the Chat and ChatBuilder classes, follow these steps:

// 1: Import the necessary classes
import { ChatBuilder } from "@/lib/ChatBuilder";
import { system } from "@/lib/Util";
// 2: Create a new ChatBuilder instance:
const builder = new ChatBuilder([
    // 3: Messages can be passed in the constructor as an array
    system("You are an assistant that can answer questions.")
// 4: Additional methods can be added on by chaining
    .user("What's the capital of France?");
// 5: Build the Chat instance using the build method:
const chat ={});

In this example, we create a new ChatBuilder instance, add a system message and a user message to the conversation, and then build a Chat instance from the builder.

Input Validation

You can apply input validation to the Chat and ChatBuilder classes using TypeScript's type-checking capabilities.

const chatBuilder = new ChatBuilder([
  // ^?
  system(`You are a joke generator you only tell {{jokeType}} jokes`),
  user(`Tell {{me}} {{num}} Jokes.`),
  assistant(`Probably a bad joke a about atoms`),
  jokeType: "funny" | "silly";
  me: "Brett" | "Liana";
  num: number;

const chat ={
  // ^? [
  //        { role: "system"; content: "You are a joke generator you only tell funny jokes" },
  //        { role: "user"; content: "Tell Brett 1 Jokes." },
  //        { role: "assistant"; content: "Probably a bad joke a about atoms" }
  //    ]
  jokeType: "funny",
  num: 1,
  me: "Brett",

addInputValidation only validates at compile time. To check values at runtime use addZodInputValidation

Advanced Usage with Zod

You can also use the Zod library for input validation when working with the Chat and ChatBuilder classes.

import { ChatBuilder } from "@/lib/ChatBuilder";
import { ChatCompletionRequestMessage } from "openai";
import { z } from "zod";

const chatBuilder = new ChatBuilder([])
    .user(`Tell me a {{jokeType}} joke`)
        // Will throw type error if jokeType not included in zodSchema
        jokeType: z.union([z.literal("funny"), z.literal("bad")]),

const chat ={
  //   ^?   Tell me a funny joke
  jokeType: "funny",
  // @ts-expect-error
  jokeType: "asdf",

By using Zod validation, you can ensure that the input data matches the expected format when adding messages to the conversation. If the input data does not match the Zod schema, a validation error will be thrown at runtime.

Last updated