Skip to content

.NET: Fix role assignment in ChatMessage construction#4290

Open
AkiKurisu wants to merge 1 commit intomicrosoft:mainfrom
AkiKurisu:fix/chatcompletions-role-mapping
Open

.NET: Fix role assignment in ChatMessage construction#4290
AkiKurisu wants to merge 1 commit intomicrosoft:mainfrom
AkiKurisu:fix/chatcompletions-role-mapping

Conversation

@AkiKurisu
Copy link

Summary

Fixes #4289

ChatCompletionRequestMessage.ToChatMessage() hardcodes ChatRole.User for all message types, causing multi-turn conversations via the ChatCompletions hosting path to lose role information. The LLM receives every message (including its own previous assistant replies, system messages, developer messages, etc.) as user role, breaking conversation coherence.

Changes

  • ChatCompletionRequestMessage.ToChatMessage() (base class): replaced hardcoded ChatRole.User with new ChatRole(this.Role) so each derived type (UserMessage, AssistantMessage, SystemMessage, DeveloperMessage, ToolMessage) maps to its correct role.
  • FunctionMessage.ToChatMessage() (override): same fix applied.

This aligns the ChatCompletions path with the Responses path, where InputMessage.ToChatMessage() already correctly uses this.Role.

Motivation and Context

Description

Contribution Checklist

  • The code builds clean without any errors or warnings
  • The PR follows the Contribution Guidelines
  • All unit tests pass, and I have added new tests where possible
  • Is this a breaking change? If yes, add "[BREAKING]" prefix to the title of the PR.

Replace hard-coded ChatRole.User with a ChatRole constructed from the message's Role. The change ensures ToChatMessage and FunctionMessage use the original role (new ChatRole(this.Role)) for both text and contents branches, fixing incorrect role assignment when constructing ChatMessage instances.
@github-actions github-actions bot changed the title .Net: Fix role assignment in ChatMessage construction .NET: Fix role assignment in ChatMessage construction Feb 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.NET: [Bug]: ChatCompletionRequestMessage.ToChatMessage() hardcodes ChatRole.User, breaking multi-turn conversations

2 participants