-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathextractGenAiSpans.ts
More file actions
46 lines (39 loc) · 1.56 KB
/
extractGenAiSpans.ts
File metadata and controls
46 lines (39 loc) · 1.56 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
import type { Client } from '../../client';
import type { SpanContainerItem } from '../../types-hoist/envelope';
import type { Event } from '../../types-hoist/event';
import { hasSpanStreamingEnabled } from './hasSpanStreamingEnabled';
import { spanJsonToSerializedStreamedSpan } from './spanJsonToStreamedSpan';
/**
* Extracts gen_ai spans from a transaction event, converts them to span v2 format,
* and returns them as a SpanContainerItem.
*
* Only applies to static mode (non-streaming) transactions.
*
* WARNING: This function mutates `event.spans` by removing the extracted gen_ai spans
* from the array. Call this before creating the event envelope so the transaction
* item does not include the extracted spans.
*/
export function extractGenAiSpansFromEvent(event: Event, client: Client): SpanContainerItem | undefined {
if (event.type !== 'transaction' || !event.spans?.length || hasSpanStreamingEnabled(client)) {
return undefined;
}
const genAiSpans = [];
const remainingSpans = [];
for (const span of event.spans) {
if (span.op?.startsWith('gen_ai.')) {
genAiSpans.push(span);
} else {
remainingSpans.push(span);
}
}
if (genAiSpans.length === 0) {
return undefined;
}
const serializedSpans = genAiSpans.map(span => spanJsonToSerializedStreamedSpan(span, event, client));
// Remove gen_ai spans from the legacy transaction
event.spans = remainingSpans;
return [
{ type: 'span', item_count: serializedSpans.length, content_type: 'application/vnd.sentry.items.span.v2+json' },
{ items: serializedSpans },
];
}