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 🙏

© 2024 – Pkg Stats / Ryan Hefner

function-json-schema

v1.0.1

Published

Function json schema for function calling.

Downloads

77

Readme

Function JSON Schema

Function JSON Schema types are nonstandard but used in OpenAI's function calling and assistants APIs. This library exists to create the types and validation for JSON schema objects that can be passed to LLMs.

The types and validation are created from Zod types.

Installation

npm install function-json-schema
# or
yarn add function-json-schema
# or
pnpm add function-json-schema

Schema

OpenAI slightly modified JSON schema because the original JSON schema specification does not include functions because functions are not serializable into JSON. Our function JSON schema codies roughly what OpenAI uses in their examples but includes additional restrictions and flexibility for better LLM results.

export const functionJsonSchema = z.object({
  name: z.string(),
  description: z.string(),
  parameters: z.union([
    z.object({
      type: z.literal('object'),
      properties: z.record(valueJsonSchema),
      description: z.string().optional(),
      required: z.array(z.string()).optional(),
    }),
    z.array(valueJsonSchema),
  ]),
  returns: valueJsonSchema,
  usageExample: z.string().optional(),
  returnsExample: z.string().optional(),
});

Keen eyes will notice the inclusion a few extra type changes:

  • description is mandatory.

  • parameters can be an array value to represent functions with argument lists rather than just a single object.

  • returns is mandatory and represents the return value of the function.

  • usageExample and returnsExample for additional documentation.

We encourage filling these out as best practice for your functions. However, the loose type can still be extracted with the coerceFunctionJsonSchema validator.

Additionally, we have added some new types:

  • For unknown types
const unknownJsonSchema = z.object({
  type: z.literal('unknown'),
  description: z.string().optional(),
});
  • For union types
/**
 * This is not the real way to represent union types in JSON Schema.
 * The real way sucks.
 */
const unionJsonSchema = z.object({
  type: z.array(z.string()),
  description: z.string().optional(),
});
/**
 * The real way to represent unions
 */
const realUnionJsonSchema: z.ZodType<RealUnionJsonSchema>  = z.object({
  anyOf: z.array(z.lazy(() => valueJsonSchema)),
  description: z.string().optional(),
});

Usage

Basic compilation time example

import { FunctionJson } from 'function-json-schema';

const schema: FunctionJson = {
  name: 'getCurrentWeather',
  description: 'Gets the current weather',
  parameters: {
    type: 'object',
    properties: {
      location: {
        type: 'string',
        description: 'The location to get the weather for',
      },
      unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
    },
    required: ['location'],
  },
  returns: {
    type: 'object',
    properties: {
      temperature: {
        description: 'The temperature value.',
        type: 'number',
      },
      temperatureUnit: {
        description: 'The temperature unit.',
        type: 'number',
      },
      windSpeed: {
        description: 'The wind speed in miles per hour.',
        type: 'number',
      },
      shortForecast: {
        description: 'A short description of the forecast.',
        type: 'string',
      },
    },
  },
};

Basic run time example

import { functionJsonSchema, coerceFunctionJsonSchema } from 'function-json-schema';

const schema: any = {
  name: 'getCurrentWeather',
  description: 'Gets the current weather',
  parameters: {
    type: 'object',
    properties: {
      location: {
        type: 'string',
        description: 12345,
      },
      unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
    },
    required: ['location'],
  },
},

const jsonSchema = functionJsonSchema.safeParse(schema);
// Strict parse result: false
console.log('Strict parse result:', jsonSchema.success);

const coercedJsonSchema = coerceFunctionJsonSchema.safeParse(schema);
// Loose parse result: true
console.log('Loose parse result:', coercedJsonSchema.success);