Skip to content

Commit

Permalink
chore: fixes nits
Browse files Browse the repository at this point in the history
Signed-off-by: Vincent Biret <vibiret@microsoft.com>
  • Loading branch information
baywet committed Dec 10, 2024
1 parent 56baeb3 commit c5c92d7
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions dotnet/src/Connectors/Connectors.OpenAI/Core/OpenAIFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,13 +221,21 @@ private static KernelJsonSchema GetOptionalStringSchemaWithDescription(string de
};
return KernelJsonSchema.Parse(jObject.ToString());
}

private static bool ShouldPropertiesBeRemoved(string[] names) => names.Length > 0;

private static bool DoesNullTypeNeedToBeAdded(bool shouldInsertNullType, KernelJsonSchema schema)
=> shouldInsertNullType && schema.RootElement.TryGetProperty(TypeKey, out var typeElement) &&
// multiple types, but not null entry
(typeElement.ValueKind == JsonValueKind.Array && !typeElement.EnumerateArray().Any(static t => NullType.Equals(t.GetString(), StringComparison.OrdinalIgnoreCase)) ||
// single type which is not null
typeElement.ValueKind == JsonValueKind.String && typeElement.GetString() != NullType);

private static KernelJsonSchema GetSanitizedSchemaForStrictMode(KernelJsonSchema schema, bool insertNullType)
{
var forbiddenPropertyNames = s_forbiddenKeywords.Where(k => schema.RootElement.TryGetProperty(k, out _)).ToArray();

if (forbiddenPropertyNames.Length > 0 || insertNullType && schema.RootElement.TryGetProperty(TypeKey, out var typeElement) &&
(typeElement.ValueKind == JsonValueKind.Array && !typeElement.EnumerateArray().Any(static t => NullType.Equals(t.GetString(), StringComparison.OrdinalIgnoreCase)) ||
typeElement.ValueKind == JsonValueKind.String && typeElement.GetString() != NullType))
if (ShouldPropertiesBeRemoved(forbiddenPropertyNames) || DoesNullTypeNeedToBeAdded(insertNullType, schema))
{
var originalSchema = JsonSerializer.Serialize(schema.RootElement);
var parsedJson = JsonNode.Parse(originalSchema);
Expand All @@ -249,6 +257,7 @@ private static KernelJsonSchema GetSanitizedSchemaForStrictMode(KernelJsonSchema
}
return schema;
}

// https://platform.openai.com/docs/guides/structured-outputs#some-type-specific-keywords-are-not-yet-supported
private static void InsertNullTypeIfRequired(bool insertNullType, JsonObject jsonObject)
{
Expand All @@ -264,8 +273,11 @@ private static void InsertNullTypeIfRequired(bool insertNullType, JsonObject jso
}
}
}

private const string NullType = "null";

private const string TypeKey = "type";

// https://platform.openai.com/docs/guides/structured-outputs#some-type-specific-keywords-are-not-yet-supported
private static readonly string[] s_forbiddenKeywords = [
"contains",
Expand Down

0 comments on commit c5c92d7

Please sign in to comment.