-
Notifications
You must be signed in to change notification settings - Fork 338
Expand file tree
/
Copy pathutils.ts
More file actions
193 lines (173 loc) · 6.17 KB
/
Copy pathutils.ts
File metadata and controls
193 lines (173 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0
import { log } from '../../log.js';
import type {
ChatContext,
ChatItem,
ChatMessage,
FunctionCall,
FunctionCallOutput,
} from '../chat_context.js';
class ChatItemGroup {
message?: ChatMessage;
toolCalls: FunctionCall[];
toolOutputs: FunctionCallOutput[];
logger = log();
constructor(params: {
message?: ChatMessage;
toolCalls: FunctionCall[];
toolOutputs: FunctionCallOutput[];
}) {
this.message = params.message;
this.toolCalls = params.toolCalls;
this.toolOutputs = params.toolOutputs;
}
static create(params?: {
message?: ChatMessage;
toolCalls?: FunctionCall[];
toolOutputs?: FunctionCallOutput[];
}) {
const { message, toolCalls = [], toolOutputs = [] } = params ?? {};
return new ChatItemGroup({ message, toolCalls, toolOutputs });
}
get isEmpty() {
return (
this.message === undefined && this.toolCalls.length === 0 && this.toolOutputs.length === 0
);
}
add(item: ChatItem) {
if (item.type === 'message') {
if (this.message) {
throw new Error('only one message is allowed in a group');
}
this.message = item;
} else if (item.type === 'function_call') {
this.toolCalls.push(item);
} else if (item.type === 'function_call_output') {
this.toolOutputs.push(item);
} else if (item.type === 'agent_handoff') {
// provider formatters don't serialize handoff records into model input.
}
return this;
}
removeInvalidToolCalls() {
const toolCallIds = new Set(this.toolCalls.map((call) => call.callId));
const toolOutputIds = new Set(this.toolOutputs.map((output) => output.callId));
const sameIds =
toolCallIds.size === toolOutputIds.size &&
[...toolCallIds].every((id) => toolOutputIds.has(id));
if (this.toolCalls.length === this.toolOutputs.length && sameIds) {
return;
}
// intersection of tool call ids and tool output ids
const validCallIds = intersection(toolCallIds, toolOutputIds);
// filter out tool calls that don't have a corresponding tool output
this.toolCalls = this.toolCalls.filter((call) => {
if (validCallIds.has(call.callId)) return true;
this.logger.warn(
{
callId: call.callId,
toolName: call.name,
},
'function call missing the corresponding function output, ignoring',
);
return false;
});
// filter out tool outputs that don't have a corresponding tool call
this.toolOutputs = this.toolOutputs.filter((output) => {
if (validCallIds.has(output.callId)) return true;
this.logger.warn(
{
callId: output.callId,
toolName: output.name,
},
'function output missing the corresponding function call, ignoring',
);
return false;
});
}
flatten() {
const items: ChatItem[] = [];
if (this.message) items.push(this.message);
items.push(...this.toolCalls, ...this.toolOutputs);
return items;
}
}
function intersection<T>(set1: Set<T>, set2: Set<T>): Set<T> {
return new Set([...set1].filter((item) => set2.has(item)));
}
/**
* Group chat items (messages, function calls, and function outputs)
* into coherent groups based on their item IDs and call IDs.
*
* Each group will contain:
* - Zero or one assistant message
* - Zero or more function/tool calls
* - The corresponding function/tool outputs matched by call_id
*
* User and system messages are placed in their own individual groups.
*
* @param chatCtx - The chat context containing all conversation items
* @returns A list of ChatItemGroup objects representing the grouped conversation
*/
export function groupToolCalls(chatCtx: ChatContext) {
const itemGroups: Record<string, ChatItemGroup> = {};
const insertionOrder: Record<string, number> = {};
const toolOutputs: FunctionCallOutput[] = [];
const logger = log();
let insertionIndex = 0;
for (const item of chatCtx.items) {
const isAssistantMessage = item.type === 'message' && item.role === 'assistant';
const isFunctionCall = item.type === 'function_call';
const isFunctionCallOutput = item.type === 'function_call_output';
if (isAssistantMessage || isFunctionCall) {
// only assistant messages and function calls can be grouped
// For function calls, use group_id if available (for parallel function calls),
// otherwise fall back to id-based grouping for backwards compatibility
const groupId =
item.type === 'function_call' && item.groupId ? item.groupId : item.id.split('/')[0]!;
if (itemGroups[groupId] === undefined) {
itemGroups[groupId] = ChatItemGroup.create();
// we use insertion order to sort the groups as they are added to the context
// simulating the OrderedDict in python
insertionOrder[groupId] = insertionIndex;
insertionIndex++;
}
itemGroups[groupId]!.add(item);
} else if (isFunctionCallOutput) {
toolOutputs.push(item);
} else {
itemGroups[item.id] = ChatItemGroup.create().add(item);
// User/system messages and agent_handoff items also need stable insertion indices.
insertionOrder[item.id] = insertionIndex++;
}
}
// add tool outputs to their corresponding groups
const callIdToGroup: Record<string, ChatItemGroup> = {};
for (const group of Object.values(itemGroups)) {
for (const toolCall of group.toolCalls) {
callIdToGroup[toolCall.callId] = group;
}
}
for (const toolOutput of toolOutputs) {
const group = callIdToGroup[toolOutput.callId];
if (group === undefined) {
logger.warn(
{ callId: toolOutput.callId, toolName: toolOutput.name },
'function output missing the corresponding function call, ignoring',
);
continue;
}
group.add(toolOutput);
}
// validate that each group and remove invalid tool calls and tool outputs
for (const group of Object.values(itemGroups)) {
group.removeInvalidToolCalls();
}
// sort groups by their item id
const orderedGroups = Object.entries(itemGroups)
.sort((a, b) => insertionOrder[a[0]]! - insertionOrder[b[0]]!)
.map(([, group]) => group);
return orderedGroups;
}