Skip to content

Commit 8216ce1

Browse files
authored
Fix handling of empty messages in AzureAIInferenceChatClient (#6072)
ChatRequestUserMessage's ctor doesn't like it when it's constructed from an empty list.
1 parent 44fd1c1 commit 8216ce1

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/Libraries/Microsoft.Extensions.AI.AzureAIInference/AzureAIInferenceChatClient.cs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -449,9 +449,20 @@ private IEnumerable<ChatRequestMessage> ToAzureAIInferenceChatMessages(IEnumerab
449449
}
450450
else if (input.Role == ChatRole.User)
451451
{
452-
yield return input.Contents.All(c => c is TextContent) ?
453-
new ChatRequestUserMessage(string.Concat(input.Contents)) :
454-
new ChatRequestUserMessage(GetContentParts(input.Contents));
452+
if (input.Contents.Count > 0)
453+
{
454+
if (input.Contents.All(c => c is TextContent))
455+
{
456+
if (string.Concat(input.Contents) is { Length: > 0 } text)
457+
{
458+
yield return new ChatRequestUserMessage(text);
459+
}
460+
}
461+
else if (GetContentParts(input.Contents) is { Count: > 0 } parts)
462+
{
463+
yield return new ChatRequestUserMessage(parts);
464+
}
465+
}
455466
}
456467
else if (input.Role == ChatRole.Assistant)
457468
{

test/Libraries/Microsoft.Extensions.AI.Integration.Tests/ChatClientIntegrationTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,20 @@ public virtual async Task GetResponseAsync_MultipleRequestMessages()
7070
Assert.Contains("Asia", response.Text);
7171
}
7272

73+
[ConditionalFact]
74+
public virtual async Task GetResponseAsync_WithEmptyMessage()
75+
{
76+
SkipIfNotEnabled();
77+
78+
var response = await _chatClient.GetResponseAsync(
79+
[
80+
new(ChatRole.User, []),
81+
new(ChatRole.User, "What is 1 + 2? Reply with a single number."),
82+
]);
83+
84+
Assert.Contains("3", response.Text);
85+
}
86+
7387
[ConditionalFact]
7488
public virtual async Task GetStreamingResponseAsync()
7589
{

0 commit comments

Comments
 (0)