Team Ai
Datasetpublic

Brunobkr/llama.cpp_AlgMor24_github

ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes3.1kdownloads
README.md391 linesDownload Raw Back to zod-to-json-schema
1# Zod to Json Schema2 3[![NPM Version](https://img.shields.io/npm/v/zod-to-json-schema.svg)](https://npmjs.org/package/zod-to-json-schema)4[![NPM Downloads](https://img.shields.io/npm/dw/zod-to-json-schema.svg)](https://npmjs.org/package/zod-to-json-schema)5 6## Notice of deprecation7 8As of November 2025, this project will no longer be actively maintained. [Zod v4 natively supports generating JSON schemas](https://zod.dev/json-schema#ztojsonschema), so I recommend you switch to the new major.9 10Thank you to all the contributors and sponsors throughout the years! So long, and thanks for all the fish.11 12## Summary13 14Does what it says on the tin; converts [Zod schemas](https://github.com/colinhacks/zod) into [JSON schemas](https://json-schema.org/)!15 16- Supports all relevant schema types, basic string, number and array length validations and string patterns.17- Resolves recursive and recurring schemas with internal `$ref`s.18- Supports targeting legacy Open API 3.0 specification (3.1 supports regular Json Schema).19- Supports Open AI strict mode schemas (Optional object properties are replaced with required but nullable ones).20- As of v3.25 you can use Zod v4 as a peer-dependency, so long as you still provide v3-schemas.21 22_Looking for the exact opposite? Check out [json-schema-to-zod](https://npmjs.org/package/json-schema-to-zod)_23 24## Sponsors25 26As this project will no longer be receiving updates I am no longer accepting new partnerships. Huge shout-out to CodeRabbit for keeping it real to the end <327 28<table align="center" style="justify-content: center;align-items: center;display: flex;">29  <tr>30    <td align="center">31      <p></p>32      <p>33      <div style="background-color: white; padding: 4px; padding-bottom: 8px;" alt="stainless">34        <a href="https://www.coderabbit.ai/">35          <picture height="45px">36             <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/eea24edb-ff20-4532-b57c-e8719f455d6d">37          <img alt="CodeRabbit logo" height="45px" src="https://github.com/user-attachments/assets/d791bc7d-dc60-4d55-9c31-97779839cb74">38          </picture>39        </a>40      </div>41      <br  />   42      Cut code review time & bugs in half43      <br/>44      <a href="https://www.coderabbit.ai/" style="text-decoration:none;">coderabbit.ai</a>45      </p>46      <p></p>47    </td>48  </tr>49</table>50 51## Usage52 53### Basic example54 55```typescript56import { z } from "zod"; // Or, using v3.25 or v4, "zod/v3"57import { zodToJsonSchema } from "zod-to-json-schema";58 59const mySchema = z60  .object({61    myString: z.string().min(5),62    myUnion: z.union([z.number(), z.boolean()]),63  })64  .describe("My neat object schema");65 66const jsonSchema = zodToJsonSchema(mySchema, "mySchema");67```68 69#### Expected output70 71```json72{73  "$schema": "http://json-schema.org/draft-07/schema#",74  "$ref": "#/definitions/mySchema",75  "definitions": {76    "mySchema": {77      "description": "My neat object schema",78      "type": "object",79      "properties": {80        "myString": {81          "type": "string",82          "minLength": 583        },84        "myUnion": {85          "type": ["number", "boolean"]86        }87      },88      "additionalProperties": false,89      "required": ["myString", "myUnion"]90    }91  }92}93```94 95## Options96 97### Schema name98 99You can pass a string as the second parameter of the main zodToJsonSchema function. If you do, your schema will end up inside a definitions object property on the root and referenced from there. Alternatively, you can pass the name as the `name` property of the options object (see below).100 101### Options object102 103Instead of the schema name (or nothing), you can pass an options object as the second parameter. The following options are available:104 105| Option                                                                             | Effect                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |106| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |107| **name**?: _string_                                                                | As described above.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |108| **nameStrategy**?: "ref" \| "title"                                                | Adds name as "title" meta instead of as a ref as described above                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |109| **basePath**?: string[]                                                            | The base path of the root reference builder. Defaults to ["#"].                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |110| **$refStrategy**?: "root" \| "relative" \| "seen" \| "none"                        | The reference builder strategy; <ul><li>**"root"** resolves $refs from the root up, ie: "#/definitions/mySchema".</li><li>**"relative"** uses [relative JSON pointers](https://tools.ietf.org/id/draft-handrews-relative-json-pointer-00.html). _See known issues!_</li><li>**"seen"** reuses the output of any "seen" Zod schema. In theory it's a more performant version of "none", but in practice this behaviour can cause issues with nested schemas and has now gotten its own option.</li> <li>**"none"** ignores referencing all together, creating a new schema branch even on "seen" schemas. Recursive references defaults to "any", ie `{}`.</li></ul> Defaults to "root". |111| **effectStrategy**?: "input" \| "any"                                              | The effects output strategy. Defaults to "input". _See known issues!_                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |112| **dateStrategy**?: "format:date" \| "format:date-time" \| "string" \| "integer"    | Date strategy, integer allow to specify in unix-time min and max values. "format:date" creates a string schema with format: "date". "format:date-time" creates a string schema with format: "date-time". "string" is intepreted as "format:date-time". "integer" creates an integer schema with format "unix-time" (unless target "openApi3" is used min max checks are also respected)                                                                                                                                                                                                                                                                                                 |113|                                                                                    |114| **emailStrategy**?: "format:email" \| "format:idn-email" \| "pattern:zod"          | Choose how to handle the email string check. Defaults to "format:email".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |115| **base64Strategy**?: "format:binary" \| "contentEnconding:base64" \| "pattern:zod" | Choose how to handle the base64 string check. Defaults to "contentEncoding:base64" as described [here](https://json-schema.org/understanding-json-schema/reference/non_json_data#contentencoding). Note that "format:binary" is not represented in the output type as it's not part of the JSON Schema spec and only intended to be used when targeting OpenAPI 3.0. Later versions of OpenAPI support contentEncoding.                                                                                                                                                                                                                                                                 |116| **definitionPath**?: "definitions" \| "$defs"                                      | The name of the definitions property when name is passed. Defaults to "definitions".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |117| **target**?: "jsonSchema7" \| "jsonSchema2019-09" \| "openApi3" \| "openAi"        | Which spec to target. Defaults to "jsonSchema7"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |118| **strictUnions**?: boolean                                                         | Scrubs unions of any-like json schemas, like `{}` or `true`. Multiple zod types may result in these out of necessity, such as z.instanceof()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |119| **definitions**?: Record<string, ZodSchema>                                        | See separate section below                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |120| **errorMessages**?: boolean                                                        | Include custom error messages created via chained function checks for supported zod types. See section below                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |121| **markdownDescription**?: boolean                                                  | Copies the `description` meta to `markdownDescription`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |122| **patternStrategy**?: "escape" \| "preserve"                                       | The Zod string validations `.includes()`, `.startsWith()`, and `.endsWith()` must be converted to regex to be compatible with JSON Schema's `pattern`. For safety, all non-alphanumeric characters are `escape`d by default (consider `z.string().includes(".")`), but this can occasionally cause problems with Unicode-flagged regex parsers. Use `preserve` to prevent this escaping behaviour and preserve the exact string written, even if it results in an inaccurate regex.                                                                                                                                                                                                     |123| **applyRegexFlags**?: boolean                                                      | JSON Schema's `pattern` doesn't support RegExp flags, but Zod's `z.string().regex()` does. When this option is true (default false), a best-effort is made to transform regexes into a flag-independent form (e.g. `/x/i => /[xX]/` ). Supported flags: `i` (basic Latin only), `m`, `s`.                                                                                                                                                                                                                                                                                                                                                                                               |124| **pipeStrategy**?: "all" \| "input" \| "output"                                    | Decide which types should be included when using `z.pipe`, for example `z.string().pipe(z.number())` would return both `string` and `number` by default, only `string` for "input" and only `number` for "output".                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |125| **removeAdditionalStrategy**?: "passthrough" \| "strict"                           | Decide when `additionalProperties` should be allowed. See the section on additional properties for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |126| **allowedAdditionalProperties**?: `true` \| `undefined`                            | What value to give `additionalProperties` when allowed. See the section on additional properties for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |127| **rejectedAdditionalProperties**?: `false` \| `undefined`                          | What value to give `additionalProperties` when rejected. See the section on additional properties for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |128| **override**?: callback                                                            | See section                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |129| **postProcess**?: callback                                                         | See section                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |130| **openAiAnyTypeName**?: string                                                     | Decides the name of a Json schema used to allow semi-arbitrary values in Open AI structured output. If any value in the Zod-schema resolves to any "any"-type schema it will reference a definition of this name. If no such definition is provided a default Json schema will be used. Defaults to "OpenAiAnyType"                                                                                                                                                                                                                                                                                                                                                                     |131 132### Definitions133 134The definitions option lets you manually add recurring schemas into definitions for cleaner outputs. It's fully compatible with named schemas, changed definitions path and base path. Here's a simple example:135 136```typescript137const myRecurringSchema = z.string();138const myObjectSchema = z.object({ a: myRecurringSchema, b: myRecurringSchema });139 140const myJsonSchema = zodToJsonSchema(myObjectSchema, {141  definitions: { myRecurringSchema },142});143```144 145#### Result146 147```json148{149  "type": "object",150  "properties": {151    "a": {152      "$ref": "#/definitions/myRecurringSchema"153    },154    "b": {155      "$ref": "#/definitions/myRecurringSchema"156    }157  },158  "definitions": {159    "myRecurringSchema": {160      "type": "string"161    }162  }163}164```165 166### Error Messages167 168This feature allows optionally including error messages created via chained function calls for supported zod types:169 170```ts171// string schema with additional chained function call checks172const EmailSchema = z.string().email("Invalid email").min(5, "Too short");173 174const jsonSchema = zodToJsonSchema(EmailSchema, { errorMessages: true });175```176 177#### Result178 179```json180{181  "$schema": "http://json-schema.org/draft-07/schema#",182  "type": "string",183  "format": "email",184  "minLength": 5,185  "errorMessage": {186    "format": "Invalid email",187    "minLength": "Too short"188  }189}190```191 192This allows for field specific, validation step specific error messages which can be useful for building forms and such. This format is accepted by `react-hook-form`'s ajv resolver (and therefor `ajv-errors` which it uses under the hood). Note that if using AJV with this format will require [enabling `ajv-errors`](https://ajv.js.org/packages/ajv-errors.html#usage) as vanilla AJV does not accept this format by default.193 194#### Custom Error Message Support195 196- ZodString197  - regex198  - min, max199  - email, cuid, uuid, url200  - endsWith, startsWith201- ZodNumber202  - min, max, lt, lte, gt, gte,203  - int204  - multipleOf205- ZodSet206  - min, max207- ZodArray208  - min, max209 210### Additional properties211 212By default, Zod removes undeclared properties when parsing object schemas. In order to replicate the expected output of this behaviour, the default for behaviour of zodToJsonSchema is to set `"additionalProperties"` to `false` (although the correctness of this can be debated). If you wish to allow undeclared properties you can either:213 214- Set `removeAdditionalStrategy` to `"strict"`. This will allow additional properties for any object schema that is not declared with `.strict()`.215- Leave `removeAdditionalStrategy` set to its default value of `"passthrough"`, and add `.passtrough()` to your object schema.216 217#### Removing the `additionalProperties` keyword using the `allowedAdditionalProperties` and/or `rejectedAdditionalProperties` options.218 219Some schema definitions (like Googles Gen AI API for instance) does not allow the `additionalProperties` keyword at all. Luckily the JSON Schema spec allows for this: leaving the keyword undefined _should_ have the same effect as setting it to true (as per usual YMMV). To enable this behaviour, set the option `allowedAdditionalProperties` to `undefined`.220 221To exclude the keyword even when additional properties are _not_ allowed, set the `rejectedAdditionalProperties` to `undefined` as well.222 223_Heads up ⚠️: Both of these options will be ignored if your schema is declared with `.catchall(...)` as the provided schema will be used instead (if valid)._224 225#### Expected outputs226 227| `z.object({})` + option   | `"additionalProperties"` value                              |228| ------------------------- | ----------------------------------------------------------- |229| `.strip()` (default)      | `false` if strategy is `"passtrough"`, `true` if `"strict"` |230| `.passtrough()`           | `true`                                                      |231| `.strict()`               | `false`                                                     |232| `.catchall(z.string())`   | `{ "type": "string" }`                                      |233| `.catchall(z.function())` | `undefined` (function schemas are not currently parseable)  |234 235Substitute `true` and `false` for `undefined` according to `allowedAdditionalProperties` and/or `rejectedAdditionalProperties` respectively.236 237### `override`238 239This options takes a callback receiving a Zod schema definition, the current reference object (containing the current ref path and other options), an argument containing inforation about wether or not the schema has been encountered before, and a forceResolution argument.240 241Important: if you don't want to override the current item you have to return the `ignoreOverride` symbol exported from the index. This is because `undefined` is a valid option to return when you want the property to be excluded from the resulting JSON schema.242 243```typescript244import zodToJsonSchema, { ignoreOverride } from "zod-to-json-schema";245 246zodToJsonSchema(247  z.object({248    ignoreThis: z.string(),249    overrideThis: z.string(),250    removeThis: z.string(),251  }),252  {253    override: (def, refs) => {254      const path = refs.currentPath.join("/");255 256      if (path === "#/properties/overrideThis") {257        return {258          type: "integer",259        };260      }261 262      if (path === "#/properties/removeThis") {263        return undefined;264      }265 266      // Important! Do not return `undefined` or void unless you want to remove the property from the resulting schema completely.267      return ignoreOverride;268    },269  },270);271```272 273Expected output:274 275```json276{277  "type": "object",278  "required": ["ignoreThis", "overrideThis"],279  "properties": {280    "ignoreThis": {281      "type": "string"282    },283    "overrideThis": {284      "type": "integer"285    }286  },287  "additionalProperties": false288}289```290 291### `postProcess`292 293Besided receiving all arguments of the `override` callback, the `postProcess` callback also receives the generated schema. It should always return a JSON Schema, or `undefined` if you wish to filter it out. Unlike the `override` callback you do not have to return `ignoreOverride` if you are happy with the produced schema; simply return it unchanged.294 295```typescript296import zodToJsonSchema, { PostProcessCallback } from "zod-to-json-schema";297 298// Define the callback to be used to process the output using the PostProcessCallback type:299const postProcess: PostProcessCallback = (300  // The original output produced by the package itself:301  jsonSchema,302  // The ZodSchema def used to produce the original schema:303  def,304  // The refs object containing the current path, passed options, etc.305  refs,306) => {307  if (!jsonSchema) {308    return jsonSchema;309  }310 311  // Try to expand description as JSON meta:312  if (jsonSchema.description) {313    try {314      jsonSchema = {315        ...jsonSchema,316        ...JSON.parse(jsonSchema.description),317      };318    } catch {}319  }320 321  // Make all numbers nullable:322  if ("type" in jsonSchema! && jsonSchema.type === "number") {323    jsonSchema.type = ["number", "null"];324  }325 326  // Add the refs path, just because327  (jsonSchema as any).path = refs.currentPath;328 329  return jsonSchema;330};331 332const jsonSchema = zodToJsonSchema(zodSchema, { postProcess });333```334 335#### Using `postProcess` for including examples and other meta336 337Adding support for examples and other JSON Schema meta keys are among the most commonly requested features for this project. Unfortunately the current Zod major (3) has pretty anemic support for this, so some userland hacking is required. Since this is such a common usecase I've included a helper function that simply tries to parse any description as JSON and expand it into the resulting schema.338 339Simply stringify whatever you want added to the output schema as the description, then import and use `jsonDescription` as the postProcess option:340 341```typescript342import zodToJsonSchema, { jsonDescription } from "zod-to-json-schema";343 344const zodSchema = z.string().describe(345  JSON.stringify({346    title: "My string",347    description: "My description",348    examples: ["Foo", "Bar"],349    whatever: 123,350  }),351);352 353const jsonSchema = zodToJsonSchema(zodSchema, {354  postProcess: jsonDescription,355});356```357 358Expected output:359 360```json361{362  "$schema": "http://json-schema.org/draft-07/schema#",363  "type": "string",364  "title": "My string",365  "description": "My description",366  "examples": ["Foo", "Bar"],367  "whatever": 123368}369```370 371## Known issues372 373- The OpenAI target should be considered experimental for now, as some combination of options may break the compatibility.374- When using `.transform`, the return type is inferred from the supplied function. In other words, there is no schema for the return type, and there is no way to convert it in runtime. Currently the JSON schema will therefore reflect the input side of the Zod schema and not necessarily the output (the latter aka. `z.infer`). If this causes problems with your schema, consider using the effectStrategy "any", which will allow any type of output.375- JSON Schemas does not support any other key type than strings for objects. When using `z.record` with any other key type, this will be ignored. An exception to this rule is `z.enum` as is supported since 3.11.3376- Relative JSON pointers, while published alongside [JSON schema draft 2020-12](https://json-schema.org/specification.html), is not technically a part of it. Currently, most resolvers do not handle them at all.377- Since v3, the Object parser uses `.isOptional()` to check if a property should be included in `required` or not. This has the potentially dangerous behavior of calling `.safeParse` with `undefined`. To work around this, make sure your `preprocess` and other effects callbacks are pure and not liable to throw errors. An issue has been logged in the Zod repo and can be [tracked here](https://github.com/colinhacks/zod/issues/1460).378- JSON Schema version 2020-12 is not yet officially supported. However, you should be able to use this library to obtain a compatible schema for the 2020-12 format just by changing the returned schema's `$schema` field to: "https://json-schema.org/draft/2020-12/schema#"379 380## Versioning381 382This package _does not_ follow semantic versioning. The major and minor versions of this package instead reflects feature parity with the [Zod package](http://npmjs.com/package/zod).383 384I will do my best to keep API-breaking changes to an absolute minimum, but new features may appear as "patches", such as introducing the options pattern in 3.9.1.385 386While v3.25 supports Zod v4 as a peer-dependency, it does _not_ mean it supports v4 schemas. Use `import { z } from "zod/v3"` and refer to the Zod documentation.387 388## Changelog389 390https://github.com/StefanTerdell/zod-to-json-schema/blob/master/changelog.md391 
Brunobkr/llama.cpp_AlgMor24_github · Team Ai