npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@proposit/typebox-to-openai

v2.0.2

Published

Convert Typebox schema to OpenAI API schema for structured output

Readme

typebox-to-openai

Convert TypeBox schemas into OpenAI Structured Output schemas. The converter lifts $defs to the root, normalizes $ref paths, and keeps schemas compatible with the OpenAI API's JSON Schema expectations.

Install

pnpm add typebox-to-openai
# or
npm install typebox-to-openai

Usage

import { Type } from "typebox"
import { ConvertToOpenAISchema } from "typebox-to-openai"

const User = Type.Object(
    {
        id: Type.String({ format: "uuid" }),
        name: Type.String(),
        tags: Type.Array(Type.String()),
    },
    { additionalProperties: false }
)

const promptSchema = ConvertToOpenAISchema(User, "User")

promptSchema is shaped like:

{
    "name": "User",
    "strict": true,
    "schema": {
        "type": "object",
        "properties": {
            "id": { "type": "string", "format": "uuid" },
            "name": { "type": "string" },
            "tags": { "type": "array", "items": { "type": "string" } }
        },
        "required": ["id", "name", "tags"],
        "additionalProperties": false
    }
}

Using with OpenAI

Pass the converted schema directly to the OpenAI API as a response_format:

import OpenAI from "openai"
import { Type } from "typebox"
import { ConvertToOpenAISchema } from "typebox-to-openai"

const schema = Type.Object(
    {
        title: Type.String(),
        count: Type.Number(),
        isActive: Type.Boolean(),
    },
    { additionalProperties: false }
)

const promptSchema = ConvertToOpenAISchema(schema, "MySchema")

const client = new OpenAI()
const response = await client.responses.create({
    model: "gpt-4o",
    input: "Return a JSON object that matches the provided schema.",
    text: {
        format: {
            type: "json_schema",
            name: promptSchema.name,
            strict: true,
            schema: promptSchema.schema,
        },
    },
})

Nullable unions

A Type.Union([Type.Object(...), Type.Null()]) with exactly one object branch and one null branch is merged into a single schema with a nullable type array:

const NullableObject = Type.Object(
    {
        maybe: Type.Union([
            Type.Object({ id: Type.Number() }, { additionalProperties: false }),
            Type.Null(),
        ]),
    },
    { additionalProperties: false }
)

const result = ConvertToOpenAISchema(NullableObject, "NullableObject")
// result.schema.properties.maybe.type === ["object", "null"]

Unions with multiple object branches, non-object types, or no null branch are preserved as anyOf arrays.

Cyclic and recursive schemas

TypeBox Type.Cyclic and Type.Ref schemas are supported. Nested $defs are lifted to the root level and bare $ref values are rewritten to #/$defs/... paths:

const TreeNode = Type.Cyclic(
    {
        TreeNode: Type.Object(
            {
                value: Type.String(),
                children: Type.Array(Type.Ref("TreeNode")),
            },
            { additionalProperties: false }
        ),
    },
    "TreeNode"
)

const result = ConvertToOpenAISchema(TreeNode, "TreeNode")
// result.schema.$defs.TreeNode exists
// children.items.$ref === "#/$defs/TreeNode"

API

ConvertToOpenAISchema(inputSchema, schemaName, options?)

Returns an object containing:

| Property | Type | Description | | -------- | -------- | ----------------------------------------------- | | name | string | The schema name passed in | | strict | true | Always true | | schema | object | OpenAI Structured Output-compatible JSON schema |

Options

The optional third argument accepts:

| Option | Type | Description | | -------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | debug | boolean | When true, logs to the console via console.debug, console.info, console.warn, console.error | | logger | TLogger ({ debug?, info?, warn?, error? }) | Custom logger object — each method is optional and receives (...args: unknown[]) |

If both logger and debug are provided, logger takes precedence.

Schema transformations

The converter applies these transformations recursively:

  • $defs lifting — nested $defs blocks are collected and moved to the root-level $defs of the output schema.
  • $ref normalization — bare ref values like "Child" are rewritten to "#/$defs/Child". External refs (https://...), absolute refs (/...), and JSON pointer refs (#/...) are left unchanged.
  • $id removal$id fields are removed at all levels to avoid OpenAI API validation errors.
  • Nullable object merginganyOf unions with exactly one object branch and one null branch are merged into { type: ["object", "null"], ... }.
  • Single-entry allOf flattening{ allOf: [schema] } is unwrapped to just schema, with any sibling keywords (e.g., description) merged onto the result. This is common in Pydantic-generated schemas.
  • Immutability — the input schema is never mutated; a new object is always returned.

Supported schema types

The following JSON Schema constructs are supported and compatible with OpenAI's strict mode:

| Construct | Example | Notes | | -------------------- | ------------------------------------ | ----------------------------------------------------------------- | | string | Type.String() | Supports format (e.g., "uuid") | | number | Type.Number() | | | integer | Type.Integer() | | | boolean | Type.Boolean() | | | null | Type.Null() | | | object | Type.Object(...) | Must include additionalProperties: false for OpenAI strict mode | | array | Type.Array(...) | Must include items | | anyOf | Type.Union([...]) | Nullable object unions are merged automatically | | $ref / $defs | Type.Ref(...) / Type.Cyclic(...) | Bare refs rewritten to #/$defs/... | | const | Type.Literal(...) | | | enum | Type.Enum(...) | TypeBox emits { enum: [...] } directly | | Single-entry allOf | Common in Pydantic output | Automatically flattened |

Unsupported schema types

The following constructs will cause ConvertToOpenAISchema to throw an error, since they are not supported by OpenAI's structured output strict mode:

| Construct | Error | | -------------------------------------------- | ------------------------------------------------- | | Multi-entry allOf | Unsupported schema type "allOf" | | oneOf | Unsupported schema type "oneOf" | | not | Unsupported schema type "not" | | Array without items | Unsupported schema: array type requires "items" | | Missing type/$ref/anyOf/const/enum | Unsupported schema: missing "type", "$ref", ... | | Duplicate $defs keys | Duplicate $defs key "..." | | anyOf with only null branches | Unsupported anyOf union with only null branches |

Development

pnpm install          # install dependencies
pnpm build            # compile TypeScript
pnpm test             # run unit tests
pnpm lint             # lint with ESLint
pnpm prettify         # format with Prettier

Integration tests

The integration test suite (src/__tests__/openai.integration.test.ts) makes real API calls to OpenAI and is skipped by default. To run it:

OPENAI_API_KEY=sk-... pnpm test

Optional env vars:

| Variable | Default | Description | | ----------------- | --------------------------- | ---------------------------------- | | OPENAI_API_KEY | — | Required to run integration tests | | OPENAI_BASE_URL | https://api.openai.com/v1 | API base URL | | OPENAI_MODEL | gpt-5.2 | Model to use for structured output |

License

MIT. See LICENSE.