Skip to content
Merged
Show file tree
Hide file tree
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
72 changes: 72 additions & 0 deletions src/AzureOpenAIProxy.ApiApp/Converters/EnumMemberConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace AzureOpenAIProxy.ApiApp.Converters;

/// <summary>
/// This represents the converter entity for <see cref="EnumMemberAttribute"/>.
/// </summary>
/// <typeparam name="T">The type of the enum to be converted.</typeparam>
public class EnumMemberConverter<T> : JsonConverter<T> where T : Enum
{
/// <inheritdoc />
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var enumText = reader.GetString();

if (enumText == null)
{
throw new JsonException($"Unable to convert null to Enum \"{typeToConvert}\".");
}

foreach (var field in typeToConvert.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute;

if (attribute != null && attribute.Value == enumText)
{
var value = field.GetValue(null);
if (value != null)
{
return (T)value;
}
}
else if (field.Name == enumText)
{
var value = field.GetValue(null);
if (value != null)
{
return (T)value;
}
}
}

throw new JsonException($"Unable to convert \"{enumText}\" to Enum \"{typeToConvert}\".");
}

/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
var field = value.GetType().GetField(value.ToString());

if (field != null)
{
var attribute = Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute;

if (attribute != null)
{
writer.WriteStringValue(attribute.Value);
}
else
{
writer.WriteStringValue(value.ToString());
}
}
else
{
writer.WriteStringValue(value.ToString());
}
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Text.Json;

using AzureOpenAIProxy.ApiApp.Attributes;
using AzureOpenAIProxy.ApiApp.Models;
using AzureOpenAIProxy.ApiApp.Services;

using Microsoft.AspNetCore.Mvc;
Expand Down Expand Up @@ -54,7 +55,7 @@ public static RouteHandlerBuilder AddChatCompletions(this WebApplication app)
})
// TODO: Check both request/response payloads
.Accepts<ChatCompletionOptions>(contentType: "application/json")
.Produces<ChatCompletion>(statusCode: StatusCodes.Status200OK, contentType: "application/json")
.Produces<CreateChatCompletionResponse>(statusCode: StatusCodes.Status200OK, contentType: "application/json")
// TODO: Check both request/response payloads
.Produces(statusCode: StatusCodes.Status401Unauthorized)
.Produces<string>(statusCode: StatusCodes.Status500InternalServerError, contentType: "text/plain")
Expand Down
Loading
Loading