Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,22 @@ public void PrepareChatHistoryToRequestAsyncAddsDeveloperWhenSystemExists()
Assert.Equal("Hello", chatHistory[2].Content);
}

[Fact]
public void ItCanSerializeResponseFormatAsType()
{
// Arrange
var settings = new OpenAIPromptExecutionSettings
{
ResponseFormat = typeof(MyTestClass)
};

// Act & Assert
var json = JsonSerializer.Serialize(settings);

Assert.NotNull(json);
Assert.Contains("response_format", json);
}

/// <summary>
/// Test implementation of OpenAIPromptExecutionSettings that exposes the protected PrepareChatHistoryToRequestAsync method.
/// </summary>
Expand Down Expand Up @@ -851,4 +867,9 @@ private static void AssertExecutionSettings(OpenAIPromptExecutionSettings execut
Assert.Equal("""{"format":"mp3","voice":"alloy"}""", JsonSerializer.Serialize(executionSettings.Audio));
Assert.Equal("""["audio","text"]""", JsonSerializer.Serialize(executionSettings.Modalities));
}

private sealed class MyTestClass
{
public int MyProperty { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ public long? Seed
/// </remarks>
[JsonPropertyName("response_format")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[JsonConverter(typeof(TypeOrFunctionResponseFormatConverter))]
public object? ResponseFormat
{
get => this._responseFormat;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Microsoft.SemanticKernel.Connectors.OpenAI;

internal sealed class TypeOrFunctionResponseFormatConverter : JsonConverter<object>
{
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert == typeof(object);
}

public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}

public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
if (value is Type type)
{
var responseFormat = OpenAIChatResponseFormatBuilder.GetJsonSchemaResponseFormat(type);
JsonSerializer.Serialize(writer, responseFormat, options);
}
else
{
JsonSerializer.Serialize(writer, value, value.GetType(), options);
}
}
}