fix(chatflow): support assistant role and fix message ordering for additional_messages #2539
+21
−27
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What type of PR is this?
fix
Check the PR title.
(Optional) Translate the PR title into Chinese.
fix(chatflow): additional_messages支持 assistant 角色并修复消息顺序问题
(Optional) More detailed description for this PR(en: English/zh: Chinese).
en: This PR fixes several issues in chatflow related to additional_messages handling:
Support Multiple Roles: Previously, roles in additional_messages were hardcoded to user. This PR enables proper mapping to support roles like assistant.
Fix Message Duplication: Adjusted the creation sequence so that history messages (from additional_messages) are created before the current run and user message. This ensures their CreatedAt timestamps are earlier, allowing prefetchChatHistory to correctly skip existing messages and preventing duplication.
Guaranteed Sequential Order: Implemented manual timestamp management for history messages and switched to BatchCreate to ensure strict chronological order when stored in the database.
zh: 此 PR 修复了 chatflow 处理 additional_messages 时的几个关键问题:
支持多种角色:修复了之前 additional_messages 中角色被硬编码为 user 的问题,现在能正确识别并支持 assistant 等角色。
修复消息重复:调整了创建顺序,确保 additional_messages 中的历史消息在当前最新轮次user 的 Run Record 和消息之前创建。这保证了历史消息的 CreatedAt 时间戳更早,从而让 prefetchChatHistory 的跳过逻辑能正常工作,避免了取回历史消息时出现的重复问题。
保证消息顺序:为历史消息引入了手动的时间戳增量逻辑,并从并发创建改为 BatchCreate(批量创建),确保消息在数据库中严格按序排列,防止获取最新消息时顺序错乱。
代码变更要点回顾:
角色映射:在 toConversationMessage 中将 Role: schema.User 修改为 Role: schema.RoleType(msg.Role)。
创建时序:将 makeChatFlowHistoryMessages 和 BatchCreate 的调用移到了 OpenAPIChatFlowRun 的最开始部分。
时间戳管理:在 makeChatFlowHistoryMessages 中通过 baseTimestamp + int64(i*100) 为每条历史消息分配了递增的时间戳。
性能优化:移除了 taskgroup 的并发创建,改用一次 BatchCreate 提交,既保证了顺序又提高了效率。
(Optional) Which issue(s) this PR fixes: