-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseMultiAgentResponse.ts
More file actions
60 lines (50 loc) · 1.94 KB
/
parseMultiAgentResponse.ts
File metadata and controls
60 lines (50 loc) · 1.94 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
/**
* Parses multi-agent LLM responses where multiple agents reply in a single stream.
* Format: **AgentDisplayName:** message text
*
* Returns segments for each detected agent (excluding the originating agent).
* System messages like **Party Mode encerrado.** (no colon) are ignored.
*/
export interface ParsedAgentSegment {
agentId: string;
displayName: string;
message: string;
}
/**
* Matches **DisplayName:** at start of line or after newline.
* Requires colon after the bold name (excludes **Party Mode encerrado.**).
*/
const AGENT_PATTERN = /(?:\n|^)\*\*([^*]+)\*\*:\s*/g;
export function parseMultiAgentResponse(
fullText: string,
displayNameToId: Map<string, string>,
originatingAgentId: string
): ParsedAgentSegment[] {
const segments: ParsedAgentSegment[] = [];
const knownIds = new Set(displayNameToId.values());
let lastIndex = 0;
let lastDisplayName: string | null = null;
let lastAgentId: string | null = null;
let match: RegExpExecArray | null;
AGENT_PATTERN.lastIndex = 0;
while ((match = AGENT_PATTERN.exec(fullText)) !== null) {
const displayName = match[1].trim();
const agentId = displayNameToId.get(displayName.toLowerCase());
if (lastDisplayName !== null && lastAgentId !== null && lastAgentId !== originatingAgentId && knownIds.has(lastAgentId)) {
const message = fullText.slice(lastIndex, match.index).trim();
if (message.length > 0) {
segments.push({ agentId: lastAgentId, displayName: lastDisplayName, message });
}
}
lastIndex = match.index + match[0].length;
lastDisplayName = displayName;
lastAgentId = agentId ?? null;
}
if (lastDisplayName !== null && lastAgentId !== null && lastAgentId !== originatingAgentId && knownIds.has(lastAgentId)) {
const message = fullText.slice(lastIndex).trim();
if (message.length > 0) {
segments.push({ agentId: lastAgentId, displayName: lastDisplayName, message });
}
}
return segments;
}