![]() |
VOOZH | about |
dotnet add package LarchSys.OpenAi.JsonSchema --version 0.3.1
NuGet\Install-Package LarchSys.OpenAi.JsonSchema -Version 0.3.1
<PackageReference Include="LarchSys.OpenAi.JsonSchema" Version="0.3.1" />
<PackageVersion Include="LarchSys.OpenAi.JsonSchema" Version="0.3.1" />Directory.Packages.props
<PackageReference Include="LarchSys.OpenAi.JsonSchema" />Project file
paket add LarchSys.OpenAi.JsonSchema --version 0.3.1
#r "nuget: LarchSys.OpenAi.JsonSchema, 0.3.1"
#:package LarchSys.OpenAi.JsonSchema@0.3.1
#addin nuget:?package=LarchSys.OpenAi.JsonSchema&version=0.3.1Install as a Cake Addin
#tool nuget:?package=LarchSys.OpenAi.JsonSchema&version=0.3.1Install as a Cake Tool
👁 GitHub Actions Workflow Status
👁 NuGet Version
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.
System.ComponentModel.DescriptionAttribute for generating descriptions in the JSON Schema.Nullable<T> types (e.g., int?) and nullable reference types (e.g., string?).bool, int, double, and DateTime.$defs and $ref in the schema (e.g., "$ref": "#/$defs/MyType").JsonPolymorphicAttribute and JsonDerivedTypeAttribute to generate schemas for polymorphic types.JsonIgnoreAttribute and all other System.Text.Json attributes for flexible schema customization.It supports generating a schema from a class, record, struct:
var resolver = new DefaultSchemaGenerator();
var schema = resolver.Generate<MyModel>(options);
It supports generating a dynamic custom schema:
JsonElement, JsonNode or object typed properties.var generator = new DefaultSchemaGenerator();
var schema1 = generator.Build(new JsonSchemaOptions(SchemaDefaults.OpenAi, Helper.JsonOptionsSnakeCase), _ => _
.Object("A person", _ => _
.Property<string>("fullName", "Firstname and Lastname")
.Property("metaData", "Some Metadata", _ => _
.Object(_ => _
.Property("type", _ => _.Const("meta"))
.Property<string>("author", "Author of the document")
.Property<DateTime>("published", "published date")
)
)
.Property("extra", "Some Extra", _ => _
.AnyOf(
_ => _.Object<Person>(),
_ => _.Object<Organization>()
)
)
)
);
var schema2 = generator.Build(new JsonSchemaOptions(SchemaDefaults.OpenAi, Helper.JsonOptions), _ => _
.Object<Document>("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<string>("author", "Author of the document")
.Property<DateTime>("published", "published date")
),
_ => _.Object(_ => _
.Property("type", _ => _.Const("version-2"))
.Property<string>("publisher", "Author of the document")
.Property<DateTime>("created", "created date")
),
)
)
)
);
Install via NuGet:
Install-Package LarchSys.OpenAi.JsonSchema
The following example demonstrates how to generate a JSON Schema using the LarchSys.OpenAi.JsonSchema library.
// 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<Document>(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<Document>(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
);
{
"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
}
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:
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.
This project is licensed under the MIT License. See the file for more information.
For any questions or issues, feel free to reach out via GitHub or email.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
Showing the top 1 NuGet packages that depend on LarchSys.OpenAi.JsonSchema:
| Package | Downloads |
|---|---|
|
ScoBro.SemanticKernel
ScoBro Semantic Kernel |
This package is not used by any popular GitHub repositories.