Share via

Custom Semantic Kernel Agent Stuck in GroupChatOrchestration After Yield Return

abbas hammoud 0 Reputation points
2025-09-12T09:02:13.4666667+00:00

Environment:

  • Language: C#
  • Library: Microsoft Semantic Kernel
  • Using Azure OpenAI models
  • .NET 8

Problem: A custom agent FastRagAgent has been implemented to call a SemanticSearchAgent.RagSearch function. The agent operates correctly on its own, but when integrated into a GroupChatOrchestration, the process hangs after the yield return statement, preventing the manager from proceeding to the next agent.

Code Snippet:

Implementation of the FastRagAgent class that inherits from Agent:

public override async IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> InvokeAsync(
    ICollection<ChatMessageContent> messages,
    AgentThread? thread = null,
    AgentInvokeOptions? options = null,
    [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    var lastUserMessage = messages?.LastOrDefault(m => m.Role == AuthorRole.User)?.Content ?? string.Empty;
    if (string.IsNullOrEmpty(lastUserMessage)) yield break;

    var result = await _semanticSearchAgent.RagSearch(lastUserMessage);
    var message = new ChatMessageContent
    {
        AuthorName = "SemanticSearchAgent",
        Role = AuthorRole.Assistant,
        Items = new ChatMessageContentItemCollection
        {
            new TextContent { Text = result }
        },
        Metadata = new Dictionary<string, object>
        {
            ["FinishReason"] = "Stop",
            ["CreatedAt"] = DateTime.UtcNow,
            ["Id"] = Guid.NewGuid().ToString()
        }
    };

    // Reached here but stuck afterward (the chat manager should call the next agent, but it does not)
    yield return new AgentResponseItem<ChatMessageContent>(message, thread);
    yield break;
}

GroupChat:

ChatHistory history = [];
ValueTask responseCallback(ChatMessageContent message)
{
    history.Add(message);
    return ValueTask.CompletedTask;
}
var customManager = new CustomGroupChatManager { MaximumInvocationCount = 5 };
GroupChatOrchestration orchestration = new GroupChatOrchestration(
    customManager,
    _fastRagAgent,
    other agents...)
{
    ResponseCallback = responseCallback,
};

InProcessRuntime runtime = new InProcessRuntime();
await runtime.StartAsync();

The setup works when agents are wrapped with chatCompletionAgent, but this increases latency. What can be done to address this issue?

Azure OpenAI in Foundry Models
0 comments No comments

1 answer

Sort by: Most helpful
  1. Divyesh Govaerdhanan 10,905 Reputation points MVP Volunteer Moderator
    2025-09-16T21:38:01.16+00:00

    Hello,

    Welcome to Microsoft Q&A,

    In GroupChatOrchestration, a few small contract details determine whether the manager advances to the next agent. The symptoms you described (hang right after yield return) usually come from one of these:

    1. Message attribution doesn’t match the speaking agent
      1. The group-chat manager relies on the message role + author name to know which agent just spoke. If you return a ChatMessageContent whose AuthorName doesn’t match the agent that was selected to speak, the orchestration history won’t advance correctly. Fix: set AuthorName = this.Name (or the exact name the manager used when it picked this agent).
      2. https://learn.microsoft.com/en-us/semantic-kernel/frameworks/agent/agent-orchestration/group-chat?pivots=programming-language-csharp
    2. Missing/incorrect finish metadata
      1. The manager looks at the finish reason of the last chunk to know that the agent has finished talking. In current SK builds, the value is "Stop" (capital S). Lower-case "stop" from older SDKs won’t be recognized. Fix: message.Metadata["FinishReason"] = "Stop"; (exact casing).
      2. https://learn.microsoft.com/en-us/semantic-kernel/support/migration/v2-openai-migration-guide
    3. Thread association is null or wrong
      1. Each response must be associated with the same AgentThread the orchestration passed in; that’s how the runtime adds your message to the shared chat history. Fix: Return new AgentResponseItem(message, thread) and ensure thread is not null. If the framework ever calls you with thread == null, create a ChatHistoryAgentThread and reuse it for subsequent turns.
    4. Custom manager is pausing for input / not selecting the next agent
      1. If CustomGroupChatManager.ShouldRequestUserInput(..) returns true, the orchestration pauses, which looks like a hang. Likewise, a selection strategy that repeatedly picks the same agent or never picks anyone after your turn will stall progress. Test: Swap in the stock RoundRobinGroupChatManager and try again. If that runs, the issue is in your manager’s selection/termination logic.
      2. https://learn.microsoft.com/en-us/semantic-kernel/frameworks/agent/agent-orchestration/group-chat?pivots=programming-language-csharp

    Please Upvote and accept the answer if it helps!!

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.