Skip to content

Support JSON response: CreateChatCompletionRequest class supports response_format field #116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Runtime/DataTypes.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace OpenAI
{
Expand Down Expand Up @@ -83,6 +84,13 @@ public class OpenAIModelResponse : OpenAIModel, IResponse
#endregion

#region Chat API Data Types

public enum ResponseFormat
{
Text,
JsonObject
}

public sealed class CreateChatCompletionRequest
{
public string Model { get; set; }
Expand All @@ -97,6 +105,40 @@ public sealed class CreateChatCompletionRequest
public Dictionary<string, string> LogitBias { get; set; }
public string User { get; set; }
public string SystemFingerprint { get; set; }

[JsonConverter(typeof(ResponseFormatJsonConverter))]
public ResponseFormat? ResponseFormat { get; set; }
}

public class ResponseFormatJsonConverter : JsonConverter<ResponseFormat>
{
public override void WriteJson(JsonWriter writer, ResponseFormat value, JsonSerializer serializer)
{
if (value == ResponseFormat.JsonObject)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteValue("json_object");
writer.WriteEndObject();
} else
{
writer.WriteNull();
}
}

public override ResponseFormat ReadJson(JsonReader reader, System.Type objectType, ResponseFormat existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject)
{
JObject obj = JObject.Load(reader);
if (obj.TryGetValue("type", out JToken typeToken) && typeToken.ToString() == "json_object")
{
return ResponseFormat.JsonObject;
}
}

return ResponseFormat.Text;
}
}

public struct CreateChatCompletionResponse : IResponse
Expand Down