New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

function-json-schema

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

function-json-schema

Function json schema for function calling.

  • 1.0.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2
decreased by-98.13%
Maintainers
1
Weekly downloads
 
Created
Source

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 copies 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 of 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 a best practice for your functions. However, the loose type can still be extracted with the coerceFunctionJsonSchema validator to provide sane defaults.

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);

Keywords

FAQs

Package last updated on 11 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc