-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathutils.ts
More file actions
227 lines (207 loc) · 8.05 KB
/
utils.ts
File metadata and controls
227 lines (207 loc) · 8.05 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import type { TraceContext } from '../../types-hoist/context';
import type { Span, SpanAttributes, SpanJSON } from '../../types-hoist/span';
import {
GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE,
GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE,
GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE,
GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE,
GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE,
GEN_AI_INPUT_MESSAGES_ATTRIBUTE,
GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,
GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE,
GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE,
GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE,
GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,
GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,
GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,
} from '../ai/gen-ai-attributes';
import { extractSystemInstructions, getTruncatedJsonString } from '../ai/utils';
import { toolCallSpanMap } from './constants';
import type { TokenSummary } from './types';
import { AI_PROMPT_ATTRIBUTE, AI_PROMPT_MESSAGES_ATTRIBUTE } from './vercel-ai-attributes';
/**
* Accumulates token data from a span to its parent in the token accumulator map.
* This function extracts token usage from the current span and adds it to the
* accumulated totals for its parent span.
*/
export function accumulateTokensForParent(span: SpanJSON, tokenAccumulator: Map<string, TokenSummary>): void {
const parentSpanId = span.parent_span_id;
if (!parentSpanId) {
return;
}
const inputTokens = span.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE];
const outputTokens = span.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE];
if (typeof inputTokens === 'number' || typeof outputTokens === 'number') {
const existing = tokenAccumulator.get(parentSpanId) || { inputTokens: 0, outputTokens: 0 };
if (typeof inputTokens === 'number') {
existing.inputTokens += inputTokens;
}
if (typeof outputTokens === 'number') {
existing.outputTokens += outputTokens;
}
tokenAccumulator.set(parentSpanId, existing);
}
}
/**
* Applies accumulated token data to the `gen_ai.invoke_agent` span.
* Only immediate children of the `gen_ai.invoke_agent` span are considered,
* since aggregation will automatically occur for each parent span.
*/
export function applyAccumulatedTokens(
spanOrTrace: SpanJSON | TraceContext,
tokenAccumulator: Map<string, TokenSummary>,
): void {
const accumulated = tokenAccumulator.get(spanOrTrace.span_id);
if (!accumulated || !spanOrTrace.data) {
return;
}
if (accumulated.inputTokens > 0) {
spanOrTrace.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = accumulated.inputTokens;
}
if (accumulated.outputTokens > 0) {
spanOrTrace.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = accumulated.outputTokens;
}
if (accumulated.inputTokens > 0 || accumulated.outputTokens > 0) {
spanOrTrace.data['gen_ai.usage.total_tokens'] = accumulated.inputTokens + accumulated.outputTokens;
}
}
/**
* Get the span associated with a tool call ID
*/
export function _INTERNAL_getSpanForToolCallId(toolCallId: string): Span | undefined {
return toolCallSpanMap.get(toolCallId);
}
/**
* Clean up the span mapping for a tool call ID
*/
export function _INTERNAL_cleanupToolCallSpan(toolCallId: string): void {
toolCallSpanMap.delete(toolCallId);
}
/**
* Convert an array of tool strings to a JSON string
*/
export function convertAvailableToolsToJsonString(tools: unknown[]): string {
const toolObjects = tools.map(tool => {
if (typeof tool === 'string') {
try {
return JSON.parse(tool);
} catch {
return tool;
}
}
return tool;
});
return JSON.stringify(toolObjects);
}
/**
* Convert the prompt string to messages array
*/
export function convertPromptToMessages(prompt: string): { role: string; content: string }[] {
try {
const p = JSON.parse(prompt);
if (!!p && typeof p === 'object') {
// Handle messages array format: { messages: [...] }
const { messages } = p as { messages?: unknown };
if (Array.isArray(messages)) {
return messages.filter(
(m: unknown): m is { role: string; content: string } =>
!!m && typeof m === 'object' && 'role' in m && 'content' in m,
);
}
// Handle prompt/system string format: { prompt: "...", system: "..." }
const { prompt, system } = p;
if (typeof prompt === 'string' || typeof system === 'string') {
const messages: { role: string; content: string }[] = [];
if (typeof system === 'string') {
messages.push({ role: 'system', content: system });
}
if (typeof prompt === 'string') {
messages.push({ role: 'user', content: prompt });
}
return messages;
}
}
// eslint-disable-next-line no-empty
} catch {}
return [];
}
/**
* Generate a request.messages JSON array from the prompt field in the
* invoke_agent op
*/
export function requestMessagesFromPrompt(span: Span, attributes: SpanAttributes): void {
if (
typeof attributes[AI_PROMPT_ATTRIBUTE] === 'string' &&
!attributes[GEN_AI_INPUT_MESSAGES_ATTRIBUTE] &&
!attributes[AI_PROMPT_MESSAGES_ATTRIBUTE]
) {
// No messages array is present, so we need to convert the prompt to the proper messages format
const prompt = attributes[AI_PROMPT_ATTRIBUTE];
const messages = convertPromptToMessages(prompt);
if (messages.length) {
const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);
if (systemInstructions) {
span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);
}
const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;
const truncatedMessages = getTruncatedJsonString(filteredMessages);
span.setAttributes({
[AI_PROMPT_ATTRIBUTE]: truncatedMessages,
[GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: truncatedMessages,
[GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,
});
}
} else if (typeof attributes[AI_PROMPT_MESSAGES_ATTRIBUTE] === 'string') {
// In this case we already get a properly formatted messages array, this is the preferred way to get the messages
try {
const messages = JSON.parse(attributes[AI_PROMPT_MESSAGES_ATTRIBUTE]);
if (Array.isArray(messages)) {
const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);
if (systemInstructions) {
span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);
}
const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;
const truncatedMessages = getTruncatedJsonString(filteredMessages);
span.setAttributes({
[AI_PROMPT_MESSAGES_ATTRIBUTE]: truncatedMessages,
[GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: truncatedMessages,
[GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,
});
}
// eslint-disable-next-line no-empty
} catch {}
}
}
/**
* Maps a Vercel AI span name to the corresponding Sentry op.
*/
export function getSpanOpFromName(name: string): string | undefined {
switch (name) {
case 'ai.generateText':
case 'ai.streamText':
case 'ai.generateObject':
case 'ai.streamObject':
case 'ai.embed':
case 'ai.embedMany':
return GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE;
case 'ai.generateText.doGenerate':
return GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE;
case 'ai.streamText.doStream':
return GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE;
case 'ai.generateObject.doGenerate':
return GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE;
case 'ai.streamObject.doStream':
return GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE;
case 'ai.embed.doEmbed':
return GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE;
case 'ai.embedMany.doEmbed':
return GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE;
case 'ai.toolCall':
return GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE;
default:
if (name.startsWith('ai.stream')) {
return 'ai.run';
}
return undefined;
}
}