https://github.com/r-larch/openai.jsonschema
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.
https://github.com/r-larch/openai.jsonschema
ai json-schema openai schema-generation structured-outputs
Last synced: about 1 month ago
JSON representation
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.
- Host: GitHub
- URL: https://github.com/r-larch/openai.jsonschema
- Owner: r-Larch
- License: mit
- Created: 2024-10-03T14:24:00.000Z (8 months ago)
- Default Branch: master
- Last Pushed: 2024-10-03T17:34:01.000Z (8 months ago)
- Last Synced: 2024-10-11T12:09:26.219Z (7 months ago)
- Topics: ai, json-schema, openai, schema-generation, structured-outputs
- Language: C#
- Homepage:
- Size: 36.1 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# OpenAi JsonSchema
 [](https://www.nuget.org/packages/LarchSys.OpenAi.JsonSchema)
**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.
## Features
- Supports `System.ComponentModel.DescriptionAttribute` for generating descriptions in the JSON Schema.
- Handles `Nullable` types (e.g., `int?`) and nullable reference types (e.g., `string?`).
- Supports a wide range of types, including primitives such as `bool`, `int`, `double`, and `DateTime`.
- Automatically manages `$defs` and `$ref` in the schema (e.g., `"$ref": "#/$defs/MyType"`).
- Ensures compatibility with OpenAI's JSON Schema format for structured outputs.
- **Polymorphism support** using `JsonPolymorphicAttribute` and `JsonDerivedTypeAttribute` to generate schemas for polymorphic types.
- Supports `JsonIgnoreAttribute` and all other `System.Text.Json` attributes for flexible schema customization.### Static Schema Generation
It supports generating a schema from a `class`, `record`, `struct`:
```csharp
var resolver = new DefaultSchemaGenerator();
var schema = resolver.Generate(options);
```### Fluent Schema Generation
It supports generating a dynamic custom schema:
- Enables dynamic descriptions for properties.
- Allows picking properties form a type without including all properties in schema.
- Allows defining a schema for `JsonElement`, `JsonNode` or `object` typed properties.
- And much more..```csharp
var generator = new DefaultSchemaGenerator();
var schema1 = generator.Build(new JsonSchemaOptions(SchemaDefaults.OpenAi, Helper.JsonOptionsSnakeCase), _ => _
.Object("A person", _ => _
.Property("fullName", "Firstname and Lastname")
.Property("metaData", "Some Metadata", _ => _
.Object(_ => _
.Property("type", _ => _.Const("meta"))
.Property("author", "Author of the document")
.Property("published", "published date")
)
)
.Property("extra", "Some Extra", _ => _
.AnyOf(
_ => _.Object(),
_ => _.Object()
)
)
)
);var schema2 = generator.Build(new JsonSchemaOptions(SchemaDefaults.OpenAi, Helper.JsonOptions), _ => _
.Object("A document", _ => _
.Property(_ => _.Id, "Id of the document")
.Property(_ => _.Name, "Document Name")
// Metadata is of type JsonElement:
.Property(_ => _.Metadata, "Some Metadata", _ => _
.AnyOf(
_ => _.Object(_ => _
.Property("type", _ => _.Const("version-1"))
.Property("author", "Author of the document")
.Property("published", "published date")
),
_ => _.Object(_ => _
.Property("type", _ => _.Const("version-2"))
.Property("publisher", "Author of the document")
.Property("created", "created date")
),
)
)
)
);
```## Installation
Install via [NuGet](https://www.nuget.org/packages/LarchSys.OpenAi.JsonSchema):
```bash
Install-Package LarchSys.OpenAi.JsonSchema
```## Quick Start
The following example demonstrates how to generate a JSON Schema using the **LarchSys.OpenAi.JsonSchema** library.
```csharp
// use Json Options to control PropertyName and Enum serialization:
var jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) {
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }
};// use SchemaDefaults.OpenAi to enforce OpenAi rule set:
var options = new JsonSchemaOptions(SchemaDefaults.OpenAi, jsonOptions);var resolver = new DefaultSchemaGenerator();
var schema = resolver.Generate(options);var json = schema.ToJsonNode().ToJsonString(new JsonSerializerOptions() { WriteIndented = true });
output.WriteLine(json);
Assert.NotNull(json);string response = ChatCompletionWithStructuredOutput(messages: [...], model: "...", schema: schema.ToJsonNode());
Assert.StartsWith("""{"id":""", response);// deserialize with JsonOptions used for schema generation:
var result = JsonSerializer.Deserialize(response, jsonOptions);
Assert.NotNull(result);
Assert.NotNull(result.Name);// Model definition with descriptions to include in schema:
[Description("A document")]
public record Document(
[property: Description("Id of the document")] int Id,
[property: Description("Document name")] string Name,
[property: Description("Text lines of the document")] Line[] Lines,
[property: Description("Next document in order")] Document? Next,
[property: Description("Prev document in order")] Document? Prev
);[Description("A line of text in a document")]
public record Line(
[property: Description("Line number")] int Number,
[property: Description("Line text")] string Text
);
```### Example Output
```json
{
"type": "object",
"description": "A document",
"properties": {
"id": {
"type": "integer",
"description": "Id of the document"
},
"name": {
"type": "string",
"description": "Document name"
},
"lines": {
"type": "array",
"description": "Text lines of the document",
"items": {
"type": "object",
"description": "A line of text in a document",
"properties": {
"number": {
"type": "integer",
"description": "Line number"
},
"text": {
"type": "string",
"description": "Line text"
}
},
"required": [
"number",
"text"
],
"additionalProperties": false
}
},
"next": {
"description": "Next document in order",
"anyOf": [
{ "type": "null" },
{ "$ref": "#" }
]
},
"prev": {
"description": "Prev document in order",
"anyOf": [
{ "type": "null" },
{ "$ref": "#" }
]
}
},
"required": [
"id",
"name",
"lines",
"next",
"prev"
],
"additionalProperties": false
}```
## How It Works
OpenAi 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.
For more details on the OpenAI Structured Outputs feature, check out:
- [Introducing Structured Outputs in the OpenAI API](https://openai.com/index/introducing-structured-outputs-in-the-api/)
- [OpenAI Structured Outputs Guide](https://platform.openai.com/docs/guides/structured-outputs/introduction)## Contributing
Contributions 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.
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE.txt) file for more information.
## Contact
For any questions or issues, feel free to reach out via GitHub or email.