Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,13 @@ describe.runIf(supports({ min: 22 }))('Google GenAI integration (v3)', () => {
]);

expect(JSON.parse(imageSpan!.attributes[GEN_AI_INPUT_MESSAGES]!.value as string)[0].state).toEqual([
{ type: 'text', text: 'Is the package damaged?' },
{ type: 'image', mime_type: 'image/png', data: 'iVBORw0KGgoAAAANSUhEUg==' },
{
role: 'user',
parts: [
{ type: 'text', content: 'Is the package damaged?' },
{ type: 'blob', modality: 'image', mime_type: 'image/png' },
],
},
]);

const errorSpan = spans.find(span => span.name === 'decide models/error-model');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ describe.runIf(supports({ min: 22 }))('OpenAI integration (V7)', () => {
// Both successful spans are named `decide gpt-6-luna` and may arrive in any order, so match on the input.
const inputOf = (span: (typeof spans)[number]): string => String(span.attributes[GEN_AI_INPUT_MESSAGES]?.value);
const textSpan = spans.find(span => inputOf(span).includes('charged twice'));
const imageSpan = spans.find(span => inputOf(span).includes('input_image'));
const imageSpan = spans.find(span => inputOf(span).includes('package damaged'));
expect(textSpan!.name).toBe('decide gpt-6-luna');
expect(textSpan!.attributes).toMatchObject({
[SENTRY_ORIGIN]: { value: 'auto.ai.openai' },
Expand Down Expand Up @@ -246,9 +246,9 @@ describe.runIf(supports({ min: 22 }))('OpenAI integration (V7)', () => {
expect(JSON.parse(imageSpan!.attributes[GEN_AI_INPUT_MESSAGES]!.value as string)[0].state).toEqual([
{
role: 'user',
content: [
{ type: 'input_text', text: 'Is the package damaged?' },
{ type: 'input_image', image_url: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg==' },
parts: [
{ type: 'text', content: 'Is the package damaged?' },
{ type: 'blob', modality: 'image', mime_type: 'image/png' },
],
},
]);
Expand Down
27 changes: 25 additions & 2 deletions packages/server-utils/src/ai/google-genai/decisions.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,38 @@
// Google's questions and answers already use Jev's layout, so only the evaluated input is renamed.
// Google's questions and answers already use Jev's layout, so only the evaluated input is mapped.
import { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import { isObjectLike } from '@sentry/core';
import { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from '../core/utils';
import type { GenAiMessage, GenAiMessagePart } from '../types';

/**
* Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`
* so both render the same.
*/
export function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {
return getEvaluationInputMessages({ state: params.input, questions: params.questions });
return getEvaluationInputMessages({ state: toStateMessages(params.input), questions: params.questions });
}

/**
* Multimodal evidence is one part or a list of parts, recorded as one user message so it renders like OpenAI's.
* Inline media is reported by modality and media type only: its `data` is base64, which the conventions require
* to be dropped.
*/
function toStateMessages(input: unknown): unknown {
if (typeof input === 'string') {
return input;
}

const parts = (Array.isArray(input) ? input : [input]).filter(isObjectLike).map((part): GenAiMessagePart => {
if (part.type === 'text') {
return { type: 'text', content: part.text };
}
if (typeof part.uri === 'string') {
return { type: 'uri', modality: part.type, mime_type: part.mime_type, uri: part.uri };
}
return { type: 'blob', modality: part.type, mime_type: part.mime_type };
});
return [{ role: 'user', parts } satisfies GenAiMessage];
Comment thread
andreiborza marked this conversation as resolved.
Resolved
}

export function addDecisionResponseAttributes(span: Span, response: unknown, recordOutputs: boolean): void {
Expand Down
46 changes: 45 additions & 1 deletion packages/server-utils/src/ai/openai/mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,58 @@
*/
import { isObjectLike } from '@sentry/core';
import { getEvaluationInputMessages, getEvaluationOutputMessages } from '../core/utils';
import type { GenAiMessage, GenAiMessagePart } from '../types';

/**
* Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`
* so both render the same.
*/
export function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {
const questions = Array.isArray(params.questions) ? params.questions.map(toJevQuestionFormat) : params.questions;
return getEvaluationInputMessages({ state: params.input, questions: keyByName(questions) });
return getEvaluationInputMessages({ state: toStateMessages(params.input), questions: keyByName(questions) });
}

/**
* Lay out evidence messages as gen_ai messages, so they render like Google's. Other input items (tool calls and
* their outputs) keep their layout, with output parts mapped like message parts.
*/
function toStateMessages(input: unknown): unknown {
if (!Array.isArray(input)) {
return input;
}

return input.map(item => {
if (!isObjectLike(item)) {
return item;
}
if (typeof item.role === 'string') {
return {
// The gen_ai conventions have no `developer` role.
role: (item.role === 'developer' ? 'system' : item.role) as GenAiMessage['role'],
parts: Array.isArray(item.content)
? item.content.filter(isObjectLike).map(toMessagePart)
: [{ type: 'text', content: item.content }],
} satisfies GenAiMessage;
}
return Array.isArray(item.output) ? { ...item, output: item.output.filter(isObjectLike).map(toMessagePart) } : item;
});
}

/**
* An image in a data URL is reported by its media type only: the URL holds base64, which the conventions require to be
* dropped.
*/
function toMessagePart(part: Record<PropertyKey, unknown>): GenAiMessagePart {
if (part.type === 'input_image' && typeof part.image_url === 'string') {
const dataUrlMimeType = /^data:([^;,]+)/.exec(part.image_url)?.[1];
return part.image_url.startsWith('data:')
? { type: 'blob', modality: 'image', mime_type: dataUrlMimeType }
: { type: 'uri', modality: 'image', uri: part.image_url };
}
if (part.type === 'input_json') {
return { type: 'object', content: part.data };
}
return { type: 'text', content: part.text ?? part.refusal };
}

/** Serialize the answers of a decisions response, laid out and keyed like Jev answers. */
Expand Down
2 changes: 1 addition & 1 deletion packages/server-utils/src/ai/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ export interface GenAiMessage {
}

export type GenAiMessagePart = Record<string, unknown> & {
type: 'blob' | 'object' | 'reasoning' | 'text' | 'tool_call' | 'tool_call_response';
type: 'blob' | 'object' | 'reasoning' | 'text' | 'tool_call' | 'tool_call_response' | 'uri';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

super-l: Wouldn't this count as feat when we support uri now?

};
15 changes: 15 additions & 0 deletions packages/server-utils/test/ai/lib/tracing/google-genai.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,21 @@ describe('instrumentGoogleGenAIClient decisions.create', () => {
]);
});

it('records a single media part given by URI as a user message', async () => {
const endedSpans = setupClient('stream');
const instrumented = instrumentGoogleGenAIClient(fakeDecisionsClient());

await instrumented.decisions.create({
...DECISION_REQUEST,
input: { type: 'image', mime_type: 'image/png', uri: 'gs://bucket/box.png' },
});

const input = JSON.parse(spanToStaticSpanJSON(endedSpans[0]!).data[GEN_AI_INPUT_MESSAGES] as string);
expect(input[0].state).toEqual([
{ role: 'user', parts: [{ type: 'uri', modality: 'image', mime_type: 'image/png', uri: 'gs://bucket/box.png' }] },
]);
});

it('records a decide span with its answers and token usage', async () => {
const endedSpans = setupClient('stream');
const instrumented = instrumentGoogleGenAIClient(fakeDecisionsClient());
Expand Down
49 changes: 48 additions & 1 deletion packages/server-utils/test/ai/lib/tracing/openai.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';
import { GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';
import { GEN_AI_DECIDE } from '@sentry/conventions/op';
import { getMainCarrier, setCurrentClient, spanToStaticSpanJSON } from '@sentry/core';
import type { Span } from '@sentry/core';
Expand Down Expand Up @@ -156,4 +156,51 @@ describe('instrumentOpenAiClient span names', () => {
},
]);
});

it('keeps message roles, image URLs, JSON parts and tool items in the decision input, without image data', async () => {
const endedSpans = setupClient('stream');
const instrumented = instrumentOpenAiClient({
decisions: { create: vi.fn().mockResolvedValue({ model: 'gpt-6-luna', answers: [] }) },
});
const toolCall = { type: 'function_call', call_id: 'call_1', name: 'lookup_order', arguments: '{}' };

await instrumented.decisions.create({
model: 'gpt-6-luna',
input: [
{ role: 'developer', content: 'Judge the ticket.' },
toolCall,
{
type: 'function_call_output',
call_id: 'call_1',
output: [{ type: 'input_image', image_url: 'data:image/png;base64,iVBORw0KGgo=' }],
},
{
role: 'user',
content: [
{ type: 'input_image', image_url: 'https://example.com/box.png' },
{ type: 'input_json', data: { order_id: 42 } },
],
},
],
questions: [{ type: 'predicate', name: 'damaged', instructions: 'Is the box damaged?' }],
});

const input = JSON.parse(spanToStaticSpanJSON(endedSpans[0]!).data[GEN_AI_INPUT_MESSAGES] as string);
expect(input[0].state).toEqual([
{ role: 'system', parts: [{ type: 'text', content: 'Judge the ticket.' }] },
toolCall,
{
type: 'function_call_output',
call_id: 'call_1',
output: [{ type: 'blob', modality: 'image', mime_type: 'image/png' }],
},
{
role: 'user',
parts: [
{ type: 'uri', modality: 'image', uri: 'https://example.com/box.png' },
{ type: 'object', content: { order_id: 42 } },
],
},
]);
});
});
Loading