MCPcopy
hub / github.com/wavetermdev/waveterm / CombineConsecutiveSameRoleMessages

Function CombineConsecutiveSameRoleMessages

pkg/aiusechat/usechat-utils.go:13–64  ·  view source on GitHub ↗

CombineConsecutiveSameRoleMessages combines consecutive UIMessages with the same role by appending their Parts together. This is useful for APIs like OpenAI that may split assistant messages into separate messages (e.g., one for text and one for tool calls).

(uiChat *uctypes.UIChat)

Source from the content-addressed store, hash-verified

11// by appending their Parts together. This is useful for APIs like OpenAI that may split
12// assistant messages into separate messages (e.g., one for text and one for tool calls).
13func CombineConsecutiveSameRoleMessages(uiChat *uctypes.UIChat) *uctypes.UIChat {
14 if uiChat == nil || len(uiChat.Messages) == 0 {
15 return uiChat
16 }
17
18 combined := make([]uctypes.UIMessage, 0, len(uiChat.Messages))
19 var current *uctypes.UIMessage
20
21 for i := range uiChat.Messages {
22 msg := &uiChat.Messages[i]
23
24 if current == nil {
25 // First message - start a new combined message
26 current = &uctypes.UIMessage{
27 ID: msg.ID,
28 Role: msg.Role,
29 Metadata: msg.Metadata,
30 Parts: make([]uctypes.UIMessagePart, len(msg.Parts)),
31 }
32 copy(current.Parts, msg.Parts)
33 continue
34 }
35
36 if current.Role == msg.Role {
37 // Same role - append parts to current message
38 current.Parts = append(current.Parts, msg.Parts...)
39 } else {
40 // Different role - save current and start new
41 combined = append(combined, *current)
42 current = &uctypes.UIMessage{
43 ID: msg.ID,
44 Role: msg.Role,
45 Metadata: msg.Metadata,
46 Parts: make([]uctypes.UIMessagePart, len(msg.Parts)),
47 }
48 copy(current.Parts, msg.Parts)
49 }
50 }
51
52 // Don't forget the last message
53 if current != nil {
54 combined = append(combined, *current)
55 }
56
57 return &uctypes.UIChat{
58 ChatId: uiChat.ChatId,
59 APIType: uiChat.APIType,
60 Model: uiChat.Model,
61 APIVersion: uiChat.APIVersion,
62 Messages: combined,
63 }
64}
65
66
67// ConvertAIChatToUIChat converts an AIChat to a UIChat by routing to the appropriate

Callers 1

ConvertAIChatToUIChatFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected