{"id":15764447,"url":"https://github.com/r-larch/openai.jsonschema","last_synced_at":"2026-01-21T08:39:28.004Z","repository":{"id":257808478,"uuid":"867143606","full_name":"r-Larch/OpenAi.JsonSchema","owner":"r-Larch","description":"OpenAi.JsonSchema is a lightweight library for generating valid JSON Schema for OpenAI models' Structured Outputs feature. It supports a wide range of types, ensures compatibility with OpenAI's JSON Schema format, and leverages C# descriptions and attributes for schema generation.","archived":false,"fork":false,"pushed_at":"2024-10-03T17:34:01.000Z","size":37,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-10-11T12:09:26.219Z","etag":null,"topics":["ai","json-schema","openai","schema-generation","structured-outputs"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/r-Larch.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-03T14:24:00.000Z","updated_at":"2024-10-08T03:40:16.000Z","dependencies_parsed_at":null,"dependency_job_id":"01f702a0-6310-4d5b-987c-c3fa0435cdf7","html_url":"https://github.com/r-Larch/OpenAi.JsonSchema","commit_stats":{"total_commits":9,"total_committers":1,"mean_commits":9.0,"dds":0.0,"last_synced_commit":"ae1f8eec110f752f64cecd216e53799d43166380"},"previous_names":["r-larch/openai.jsonschema"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/r-Larch%2FOpenAi.JsonSchema","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/r-Larch%2FOpenAi.JsonSchema/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/r-Larch%2FOpenAi.JsonSchema/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/r-Larch%2FOpenAi.JsonSchema/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/r-Larch","download_url":"https://codeload.github.com/r-Larch/OpenAi.JsonSchema/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249996085,"owners_count":21358058,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","json-schema","openai","schema-generation","structured-outputs"],"created_at":"2024-10-04T12:03:38.441Z","updated_at":"2026-01-21T08:39:27.977Z","avatar_url":"https://github.com/r-Larch.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# OpenAi JsonSchema\n\n![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/r-Larch/OpenAi.JsonSchema/ci.yml) [![NuGet Version](https://img.shields.io/nuget/v/LarchSys.OpenAi.JsonSchema)](https://www.nuget.org/packages/LarchSys.OpenAi.JsonSchema)\n\n**OpenAi-JsonSchema** is a lightweight library for generating valid JSON Schema for OpenAI's Structured Outputs feature, ensuring compatibility with OpenAI's JSON Schema subset. It simplifies the creation of structured outputs for OpenAI models, following the schema generation guidelines provided by OpenAI.\n\n## Features\n- Supports `System.ComponentModel.DescriptionAttribute` for generating descriptions in the JSON Schema.\n- Handles `Nullable\u003cT\u003e` types (e.g., `int?`) and nullable reference types (e.g., `string?`).\n- Supports a wide range of types, including primitives such as `bool`, `int`, `double`, and `DateTime`.\n- Automatically manages `$defs` and `$ref` in the schema (e.g., `\"$ref\": \"#/$defs/MyType\"`).\n- Ensures compatibility with OpenAI's JSON Schema format for structured outputs.\n- **Polymorphism support** using `JsonPolymorphicAttribute` and `JsonDerivedTypeAttribute` to generate schemas for polymorphic types.\n- Supports `JsonIgnoreAttribute` and all other `System.Text.Json` attributes for flexible schema customization.\n\n### Static Schema Generation\n\nIt supports generating a schema from a `class`, `record`, `struct`:\n\n```csharp\nvar resolver = new DefaultSchemaGenerator();\nvar schema = resolver.Generate\u003cMyModel\u003e(options);\n```\n\n### Fluent Schema Generation\n\nIt supports generating a dynamic custom schema:\n- Enables dynamic descriptions for properties.\n- Allows picking properties form a type without including all properties in schema.\n- Allows defining a schema for `JsonElement`, `JsonNode` or `object` typed properties.\n- And much more..\n\n```csharp\nvar generator = new DefaultSchemaGenerator();\nvar schema1 = generator.Build(new JsonSchemaOptions(SchemaDefaults.OpenAi, Helper.JsonOptionsSnakeCase), _ =\u003e _\n    .Object(\"A person\", _ =\u003e _\n        .Property\u003cstring\u003e(\"fullName\", \"Firstname and Lastname\")\n        .Property(\"metaData\", \"Some Metadata\", _ =\u003e _\n            .Object(_ =\u003e _\n                .Property(\"type\", _ =\u003e _.Const(\"meta\"))\n                .Property\u003cstring\u003e(\"author\", \"Author of the document\")\n                .Property\u003cDateTime\u003e(\"published\", \"published date\")\n            )\n        )\n        .Property(\"extra\", \"Some Extra\", _ =\u003e _\n            .AnyOf(\n                _ =\u003e _.Object\u003cPerson\u003e(),\n                _ =\u003e _.Object\u003cOrganization\u003e()\n            )\n        )\n    )\n);\n\nvar schema2 = generator.Build(new JsonSchemaOptions(SchemaDefaults.OpenAi, Helper.JsonOptions), _ =\u003e _\n    .Object\u003cDocument\u003e(\"A document\", _ =\u003e _\n        .Property(_ =\u003e _.Id, \"Id of the document\")\n        .Property(_ =\u003e _.Name, \"Document Name\")\n        // Metadata is of type JsonElement:\n        .Property(_ =\u003e _.Metadata, \"Some Metadata\", _ =\u003e _\n            .AnyOf(\n                _ =\u003e _.Object(_ =\u003e _\n                    .Property(\"type\", _ =\u003e _.Const(\"version-1\"))\n                    .Property\u003cstring\u003e(\"author\", \"Author of the document\")\n                    .Property\u003cDateTime\u003e(\"published\", \"published date\")\n                ),\n                _ =\u003e _.Object(_ =\u003e _\n                    .Property(\"type\", _ =\u003e _.Const(\"version-2\"))\n                    .Property\u003cstring\u003e(\"publisher\", \"Author of the document\")\n                    .Property\u003cDateTime\u003e(\"created\", \"created date\")\n                ),\n            )\n        )\n    )\n);\n```\n\n## Installation\n\nInstall via [NuGet](https://www.nuget.org/packages/LarchSys.OpenAi.JsonSchema):\n\n```bash\nInstall-Package LarchSys.OpenAi.JsonSchema\n```\n\n## Quick Start\n\nThe following example demonstrates how to generate a JSON Schema using the **LarchSys.OpenAi.JsonSchema** library.\n\n```csharp\n// use Json Options to control PropertyName and Enum serialization:\nvar jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) {\n    PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,\n    Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }\n};\n\n// use SchemaDefaults.OpenAi to enforce OpenAi rule set:\nvar options = new JsonSchemaOptions(SchemaDefaults.OpenAi, jsonOptions);\n\nvar resolver = new DefaultSchemaGenerator();\nvar schema = resolver.Generate\u003cDocument\u003e(options);\n\nvar json = schema.ToJsonNode().ToJsonString(new JsonSerializerOptions() { WriteIndented = true });\noutput.WriteLine(json);\nAssert.NotNull(json);\n\nstring response = ChatCompletionWithStructuredOutput(messages: [...], model: \"...\", schema: schema.ToJsonNode());\nAssert.StartsWith(\"\"\"{\"id\":\"\"\", response);\n\n// deserialize with JsonOptions used for schema generation:\nvar result = JsonSerializer.Deserialize\u003cDocument\u003e(response, jsonOptions);\nAssert.NotNull(result);\nAssert.NotNull(result.Name);\n\n// Model definition with descriptions to include in schema:\n\n[Description(\"A document\")]\npublic record Document(\n    [property: Description(\"Id of the document\")] int Id,\n    [property: Description(\"Document name\")] string Name,\n    [property: Description(\"Text lines of the document\")] Line[] Lines,\n    [property: Description(\"Next document in order\")] Document? Next,\n    [property: Description(\"Prev document in order\")] Document? Prev\n);\n\n[Description(\"A line of text in a document\")]\npublic record Line(\n    [property: Description(\"Line number\")] int Number,\n    [property: Description(\"Line text\")] string Text\n);\n```\n\n### Example Output\n\n```json\n{\n  \"type\": \"object\",\n  \"description\": \"A document\",\n  \"properties\": {\n    \"id\": {\n      \"type\": \"integer\",\n      \"description\": \"Id of the document\"\n    },\n    \"name\": {\n      \"type\": \"string\",\n      \"description\": \"Document name\"\n    },\n    \"lines\": {\n      \"type\": \"array\",\n      \"description\": \"Text lines of the document\",\n      \"items\": {\n        \"type\": \"object\",\n        \"description\": \"A line of text in a document\",\n        \"properties\": {\n          \"number\": {\n            \"type\": \"integer\",\n            \"description\": \"Line number\"\n          },\n          \"text\": {\n            \"type\": \"string\",\n            \"description\": \"Line text\"\n          }\n        },\n        \"required\": [\n          \"number\",\n          \"text\"\n        ],\n        \"additionalProperties\": false\n      }\n    },\n    \"next\": {\n      \"description\": \"Next document in order\",\n      \"anyOf\": [\n        { \"type\": \"null\" },\n        { \"$ref\": \"#\" }\n      ]\n    },\n    \"prev\": {\n      \"description\": \"Prev document in order\",\n      \"anyOf\": [\n        { \"type\": \"null\" },\n        { \"$ref\": \"#\" }\n      ]\n    }\n  },\n  \"required\": [\n    \"id\",\n    \"name\",\n    \"lines\",\n    \"next\",\n    \"prev\"\n  ],\n  \"additionalProperties\": false\n}\n\n```\n\n## How It Works\n\nOpenAi JsonSchema simplifies the generation of JSON Schema for structured outputs using C# classes and attributes. It leverages the `System.ComponentModel.DescriptionAttribute` for field descriptions and supports nullable reference types, ensuring full compatibility with the JSON Schema language supported by OpenAI models.\n\nFor more details on the OpenAI Structured Outputs feature, check out:\n- [Introducing Structured Outputs in the OpenAI API](https://openai.com/index/introducing-structured-outputs-in-the-api/)\n- [OpenAI Structured Outputs Guide](https://platform.openai.com/docs/guides/structured-outputs/introduction)\n\n## Contributing\n\nContributions are welcome! Please fork this repository and submit a pull request with any improvements or feature additions. All contributions should follow the repository's guidelines.\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE.txt) file for more information.\n\n## Contact\n\nFor any questions or issues, feel free to reach out via GitHub or email.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fr-larch%2Fopenai.jsonschema","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fr-larch%2Fopenai.jsonschema","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fr-larch%2Fopenai.jsonschema/lists"}