Skip to content

harrysolovay/structured-outputs

Repository files navigation

Structured Outputs TypeScript

A library for working with OpenAI's structured outputs.

Installation

Node

npm i structured-outputs

Deno

deno add jsr:@crosshatch/[email protected]

Note: replace "X" with the latest beta version number. Version specificity will be unnecessary upon the first stable release of structured-outputs.

Example Usage

Declare a Type

import { T } from "structured-outputs"

const Character = T.object({
  name: T.string,
  age: T.number`Ensure between 1 and 110.`,
  home: T.string`The name of a fictional realm of magic and wonder.`,
  disposition: T.constantUnion("Optimistic", "Reserved", "Inquisitive"),
})

Create a ResponseFormat

// ...

import { ResponseFormat } from "structured-outputs"

const response_format = ResponseFormat("create_character", Character)`
  Create a character to be the protagonist of a children's story.
`

Create Chat Completions

// ...

const character = await openai.chat.completions
  .create({
    model: "gpt-4o-mini",
    messages: [...yourMessages],
    response_format,
  })
  .then(response_format.into)

Utilize The Typed, Unwrapped Data

// ...

character satisfies {
  name: string
  age: number
  home: string
  disposition: "Optimistic" | "Reserved" | "Inquisitive"
}

License

Structured Outputs TypeScript is Apache licensed.