Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,7 @@ private static AgentSession GetRequiredSession()
}

/// <summary>
/// Drains all pending injected messages from the queue and returns a new list combining
/// the original messages with the drained messages. The original list is never modified.
/// Drains all pending injected messages from the queue and returns the combined messages.
/// </summary>
private static IList<ChatMessage> DrainInjectedMessages(List<ChatMessage> queue, IList<ChatMessage> newMessages)
{
Expand All @@ -275,6 +274,14 @@ private static IList<ChatMessage> DrainInjectedMessages(List<ChatMessage> queue,
return newMessages;
}

if (newMessages is List<ChatMessage> mutableMessages)
{
// Keep the outer function loop's history list in sync with what was sent to the model.
mutableMessages.AddRange(queue);
queue.Clear();
return mutableMessages;
}

var combined = new List<ChatMessage>(newMessages);
combined.AddRange(queue);
queue.Clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,67 @@ public async Task RunAsync_PropagatesConversationId_AcrossInternalLoopIterations
Assert.Equal("conv-123", capturedConversationIds[1]); // Second call: propagated from first response
}

[Fact]
public async Task RunAsync_KeepsInjectedMessagesInFunctionLoopHistoryAsync()
{
// Arrange
int serviceCallCount = 0;
int toolCallCount = 0;
List<List<string>> capturedMessageTexts = [];
MessageInjectingChatClient? injectorRef = null;
ChatClientAgentSession? sessionRef = null;

Mock<IChatClient> mockService = new();
mockService.Setup(
s => s.GetResponseAsync(
It.IsAny<IEnumerable<ChatMessage>>(),
It.IsAny<ChatOptions>(),
It.IsAny<CancellationToken>()))
.Returns((IEnumerable<ChatMessage> msgs, ChatOptions? _, CancellationToken _) =>
{
serviceCallCount++;
capturedMessageTexts.Add(msgs.Select(m => m.Text).ToList());

return Task.FromResult(serviceCallCount switch
{
1 => new ChatResponse([new(ChatRole.Assistant,
[new FunctionCallContent("call1", "myTool", new Dictionary<string, object?>())])]),
2 => new ChatResponse([new(ChatRole.Assistant,
[new FunctionCallContent("call2", "myTool", new Dictionary<string, object?>())])]),
_ => new ChatResponse([new(ChatRole.Assistant, "final")]),
});
});

var tool = AIFunctionFactory.Create(() =>
{
toolCallCount++;
if (toolCallCount == 1)
{
injectorRef!.EnqueueMessages(sessionRef!, [new ChatMessage(ChatRole.User, "injected correction")]);
}

return "tool result";
}, "myTool", "A test tool");

ChatClientAgent agent = new(mockService.Object, options: new()
{
ChatOptions = new() { Tools = [tool] },
EnableMessageInjection = true,
}, services: new ServiceCollection().BuildServiceProvider());

injectorRef = agent.ChatClient.GetService<MessageInjectingChatClient>()!;

// Act
var session = await agent.CreateSessionAsync() as ChatClientAgentSession;
sessionRef = session;
await agent.RunAsync([new(ChatRole.User, "original")], session);

// Assert
Assert.Equal(3, serviceCallCount);
Assert.Contains(capturedMessageTexts[1], text => text == "injected correction");
Assert.Contains(capturedMessageTexts[2], text => text == "injected correction");
}

/// <summary>
/// Verifies that a session with pending injected messages can be serialized and deserialized,
/// and that the deserialized session correctly delivers the injected messages on the next run.
Expand Down