|
| 1 | +import { |
| 2 | + GEN_AI_INPUT_MESSAGES, |
| 3 | + GEN_AI_OPERATION_NAME, |
| 4 | + GEN_AI_PROVIDER_NAME, |
| 5 | + GEN_AI_REQUEST_FREQUENCY_PENALTY, |
| 6 | + GEN_AI_REQUEST_MAX_TOKENS, |
| 7 | + GEN_AI_REQUEST_MODEL, |
| 8 | + GEN_AI_REQUEST_PRESENCE_PENALTY, |
| 9 | + GEN_AI_REQUEST_TEMPERATURE, |
| 10 | + GEN_AI_REQUEST_TOP_K, |
| 11 | + GEN_AI_REQUEST_TOP_P, |
| 12 | + GEN_AI_SYSTEM_INSTRUCTIONS, |
| 13 | + GEN_AI_TOOL_DEFINITIONS, |
| 14 | +} from '@sentry/conventions/attributes'; |
| 15 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
| 16 | +import { getMainCarrier, setCurrentClient, spanToJSON } from '@sentry/core'; |
| 17 | +import type { Span } from '@sentry/core'; |
| 18 | +import { instrumentGoogleGenAIClient } from '../../../../src/ai/google-genai'; |
| 19 | +import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; |
| 20 | + |
| 21 | +const MODEL = 'gemini-1.5-pro'; |
| 22 | + |
| 23 | +const CHAT_CONFIG = { |
| 24 | + temperature: 0.8, |
| 25 | + topP: 0.9, |
| 26 | + topK: 40, |
| 27 | + maxOutputTokens: 150, |
| 28 | + frequencyPenalty: 0.5, |
| 29 | + presencePenalty: 0.3, |
| 30 | + tools: [{ functionDeclarations: [{ name: 'getWeather' }] }], |
| 31 | + systemInstruction: 'You are a friendly robot.', |
| 32 | +}; |
| 33 | + |
| 34 | +const MOCK_RESPONSE = { |
| 35 | + modelVersion: MODEL, |
| 36 | + candidates: [{ content: { parts: [{ text: 'Hi there!' }], role: 'model' } }], |
| 37 | + usageMetadata: { promptTokenCount: 8, candidatesTokenCount: 12, totalTokenCount: 20 }, |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * Minimal stand-in for a `@google/genai` client. `chats.create()` returns a chat object that keeps |
| 42 | + * the model (as the real SDK does) and exposes the two message-sending methods. The config passed to |
| 43 | + * `create()` is stored on the SDK internally and is not repeated on each `sendMessage()` call. |
| 44 | + */ |
| 45 | +function createFakeClient(): { chats: { create: (params: Record<string, unknown>) => unknown } } { |
| 46 | + return { |
| 47 | + chats: { |
| 48 | + create: (params: Record<string, unknown>) => ({ |
| 49 | + model: params.model, |
| 50 | + sendMessage: async (_params: Record<string, unknown>) => MOCK_RESPONSE, |
| 51 | + sendMessageStream: async (_params: Record<string, unknown>) => |
| 52 | + (async function* () { |
| 53 | + yield MOCK_RESPONSE; |
| 54 | + })(), |
| 55 | + }), |
| 56 | + }, |
| 57 | + }; |
| 58 | +} |
| 59 | + |
| 60 | +function setupClient(): Span[] { |
| 61 | + const client = new TestClient( |
| 62 | + getDefaultTestClientOptions({ |
| 63 | + dsn: 'https://public@dsn.ingest.sentry.io/1337', |
| 64 | + tracesSampleRate: 1, |
| 65 | + }), |
| 66 | + ); |
| 67 | + setCurrentClient(client); |
| 68 | + client.init(); |
| 69 | + |
| 70 | + const endedSpans: Span[] = []; |
| 71 | + client.on('spanEnd', span => endedSpans.push(span)); |
| 72 | + return endedSpans; |
| 73 | +} |
| 74 | + |
| 75 | +async function drain(stream: AsyncIterable<unknown>): Promise<void> { |
| 76 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 77 | + for await (const _ of stream) { |
| 78 | + // consume so the streaming span is ended |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +describe('instrumentGoogleGenAIClient chat config propagation (#20086)', () => { |
| 83 | + beforeEach(() => { |
| 84 | + getMainCarrier().__SENTRY__ = undefined; |
| 85 | + }); |
| 86 | + |
| 87 | + afterEach(() => { |
| 88 | + getMainCarrier().__SENTRY__ = undefined; |
| 89 | + }); |
| 90 | + |
| 91 | + it('welds chats.create() config onto chat.sendMessage() spans', async () => { |
| 92 | + const endedSpans = setupClient(); |
| 93 | + const instrumented = instrumentGoogleGenAIClient(createFakeClient()); |
| 94 | + |
| 95 | + const chat = instrumented.chats.create({ model: MODEL, config: CHAT_CONFIG }) as { |
| 96 | + sendMessage: (params: Record<string, unknown>) => Promise<unknown>; |
| 97 | + }; |
| 98 | + await chat.sendMessage({ message: 'Tell me a joke' }); |
| 99 | + |
| 100 | + expect(endedSpans).toHaveLength(1); |
| 101 | + const data = spanToJSON(endedSpans[0]!).data; |
| 102 | + |
| 103 | + expect(data[GEN_AI_OPERATION_NAME]).toBe('chat'); |
| 104 | + expect(data[GEN_AI_PROVIDER_NAME]).toBe('google_genai'); |
| 105 | + expect(data[GEN_AI_REQUEST_MODEL]).toBe(MODEL); |
| 106 | + expect(data[GEN_AI_REQUEST_TEMPERATURE]).toBe(0.8); |
| 107 | + expect(data[GEN_AI_REQUEST_TOP_P]).toBe(0.9); |
| 108 | + expect(data[GEN_AI_REQUEST_TOP_K]).toBe(40); |
| 109 | + expect(data[GEN_AI_REQUEST_MAX_TOKENS]).toBe(150); |
| 110 | + expect(data[GEN_AI_REQUEST_FREQUENCY_PENALTY]).toBe(0.5); |
| 111 | + expect(data[GEN_AI_REQUEST_PRESENCE_PENALTY]).toBe(0.3); |
| 112 | + expect(data[GEN_AI_TOOL_DEFINITIONS]).toBe('[{"name":"getWeather"}]'); |
| 113 | + expect(data[GEN_AI_SYSTEM_INSTRUCTIONS]).toBe('[{"type":"text","content":"You are a friendly robot."}]'); |
| 114 | + // The chat message stays as the only input message; the system instruction is split out above. |
| 115 | + expect(data[GEN_AI_INPUT_MESSAGES]).toBe('[{"role":"user","content":"Tell me a joke"}]'); |
| 116 | + }); |
| 117 | + |
| 118 | + it('welds chats.create() config onto chat.sendMessageStream() spans', async () => { |
| 119 | + const endedSpans = setupClient(); |
| 120 | + const instrumented = instrumentGoogleGenAIClient(createFakeClient()); |
| 121 | + |
| 122 | + const chat = instrumented.chats.create({ model: MODEL, config: CHAT_CONFIG }) as { |
| 123 | + sendMessageStream: (params: Record<string, unknown>) => Promise<AsyncIterable<unknown>>; |
| 124 | + }; |
| 125 | + await drain(await chat.sendMessageStream({ message: 'Tell me a joke' })); |
| 126 | + |
| 127 | + expect(endedSpans).toHaveLength(1); |
| 128 | + const data = spanToJSON(endedSpans[0]!).data; |
| 129 | + |
| 130 | + expect(data[GEN_AI_OPERATION_NAME]).toBe('chat'); |
| 131 | + expect(data[GEN_AI_REQUEST_MODEL]).toBe(MODEL); |
| 132 | + expect(data[GEN_AI_REQUEST_TEMPERATURE]).toBe(0.8); |
| 133 | + expect(data[GEN_AI_REQUEST_TOP_P]).toBe(0.9); |
| 134 | + expect(data[GEN_AI_REQUEST_TOP_K]).toBe(40); |
| 135 | + expect(data[GEN_AI_REQUEST_MAX_TOKENS]).toBe(150); |
| 136 | + expect(data[GEN_AI_REQUEST_FREQUENCY_PENALTY]).toBe(0.5); |
| 137 | + expect(data[GEN_AI_REQUEST_PRESENCE_PENALTY]).toBe(0.3); |
| 138 | + expect(data[GEN_AI_TOOL_DEFINITIONS]).toBe('[{"name":"getWeather"}]'); |
| 139 | + expect(data[GEN_AI_SYSTEM_INSTRUCTIONS]).toBe('[{"type":"text","content":"You are a friendly robot."}]'); |
| 140 | + }); |
| 141 | + |
| 142 | + it('lets a per-message config override the config from chats.create()', async () => { |
| 143 | + const endedSpans = setupClient(); |
| 144 | + const instrumented = instrumentGoogleGenAIClient(createFakeClient()); |
| 145 | + |
| 146 | + const chat = instrumented.chats.create({ model: MODEL, config: CHAT_CONFIG }) as { |
| 147 | + sendMessage: (params: Record<string, unknown>) => Promise<unknown>; |
| 148 | + }; |
| 149 | + await chat.sendMessage({ message: 'Tell me a joke', config: { temperature: 0.1 } }); |
| 150 | + |
| 151 | + const data = spanToJSON(endedSpans[0]!).data; |
| 152 | + // Per-call temperature wins; the untouched create-time values still come through. |
| 153 | + expect(data[GEN_AI_REQUEST_TEMPERATURE]).toBe(0.1); |
| 154 | + expect(data[GEN_AI_REQUEST_TOP_P]).toBe(0.9); |
| 155 | + expect(data[GEN_AI_REQUEST_MAX_TOKENS]).toBe(150); |
| 156 | + }); |
| 157 | + |
| 158 | + it('does not leak chat config onto models.generateContent spans', async () => { |
| 159 | + const endedSpans = setupClient(); |
| 160 | + const client = { |
| 161 | + chats: { create: createFakeClient().chats.create }, |
| 162 | + models: { generateContent: async (_params: Record<string, unknown>) => MOCK_RESPONSE }, |
| 163 | + }; |
| 164 | + const instrumented = instrumentGoogleGenAIClient(client); |
| 165 | + |
| 166 | + // Create a chat (with config) first, then make an unrelated generateContent call. |
| 167 | + instrumented.chats.create({ model: MODEL, config: CHAT_CONFIG }); |
| 168 | + await instrumented.models.generateContent({ model: 'gemini-1.5-flash' }); |
| 169 | + |
| 170 | + const genContentSpan = endedSpans.find(span => spanToJSON(span).data[GEN_AI_OPERATION_NAME] === 'generate_content'); |
| 171 | + const data = spanToJSON(genContentSpan!).data; |
| 172 | + expect(data[GEN_AI_REQUEST_MODEL]).toBe('gemini-1.5-flash'); |
| 173 | + expect(data[GEN_AI_REQUEST_TEMPERATURE]).toBeUndefined(); |
| 174 | + expect(data[GEN_AI_SYSTEM_INSTRUCTIONS]).toBeUndefined(); |
| 175 | + }); |
| 176 | +}); |
0 commit comments