-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathconversationId.ts
More file actions
46 lines (39 loc) · 1.87 KB
/
conversationId.ts
File metadata and controls
46 lines (39 loc) · 1.87 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 { getCurrentScope, getIsolationScope } from '../currentScopes';
import { defineIntegration } from '../integration';
import { GEN_AI_CONVERSATION_ID_ATTRIBUTE } from '../semanticAttributes';
import type { IntegrationFn } from '../types-hoist/integration';
import type { Span } from '../types-hoist/span';
import { spanToJSON } from '../utils/spanUtils';
const INTEGRATION_NAME = 'ConversationId';
const _conversationIdIntegration = (() => {
return {
name: INTEGRATION_NAME,
setup(client: Client) {
client.on('spanStart', (span: Span) => {
const scopeData = getCurrentScope().getScopeData();
const isolationScopeData = getIsolationScope().getScopeData();
const conversationId = scopeData.conversationId || isolationScopeData.conversationId;
if (conversationId) {
const { op, data: attributes, description: name } = spanToJSON(span);
// Only apply conversation ID to gen_ai spans.
// We also check for Vercel AI spans (ai.operationId attribute or ai.* span name)
// because the Vercel AI integration sets the gen_ai.* op in its own spanStart handler
// which fires after this, so the op is not yet available at this point.
if (!op?.startsWith('gen_ai.') && !attributes['ai.operationId'] && !name?.startsWith('ai.')) {
return;
}
span.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE, conversationId);
}
});
},
};
}) satisfies IntegrationFn;
/**
* Automatically applies conversation ID from scope to spans.
*
* This integration reads the conversation ID from the current or isolation scope
* and applies it to spans when they start. This ensures the conversation ID is
* available for all AI-related operations.
*/
export const conversationIdIntegration = defineIntegration(_conversationIdIntegration);