Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(otel): decode Python bytes media (#15347)

Hassieb Pakzad9752449ca054
diff --git a/packages/shared/src/server/media/MediaPayloadProcessor.test.ts b/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
index 161ecf43fc..9f4a85d454 100644
--- a/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
+++ b/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
@@ -87,7 +87,8 @@ describe("transformMediaPayload", () => {
expect(transformed.value).toBe(`file: ${MEDIA_REFERENCE}`);
expect(processCandidate).toHaveBeenCalledWith({
- base64Data: textBase64,
+ encodedData: textBase64,
+ encoding: "base64",
contentType: "text/plain",
kind: "data_uri",
source: "base64_data_uri",
diff --git a/packages/shared/src/server/media/MediaPayloadProcessor.ts b/packages/shared/src/server/media/MediaPayloadProcessor.ts
index 493a71fd00..9126ba9230 100644
--- a/packages/shared/src/server/media/MediaPayloadProcessor.ts
+++ b/packages/shared/src/server/media/MediaPayloadProcessor.ts
@@ -17,7 +17,8 @@ export type MediaPayloadKind =
| "ai_sdk_v7";
export type MediaPayloadCandidate = {
- base64Data: string;
+ encodedData: string;
+ encoding: "base64" | "python_bytes_literal";
contentType: MediaContentType;
kind: MediaPayloadKind;
source: "base64_data_uri" | "bytes";
@@ -278,7 +279,8 @@ function findDataUris(value: string): DataUriOccurrence[] {
base64Data.length % 4 !== 1 &&
isMediaContentType(contentType)
? {
- base64Data,
+ encodedData: base64Data,
+ encoding: "base64",
contentType,
kind: "data_uri",
source: "base64_data_uri",
@@ -470,7 +472,7 @@ async function replaceStructuredMedia(
): Promise<number | undefined> {
if (isMediaReference(media.content) || isRemoteUrl(media.content)) return;
- const candidate = parseRawBase64(media);
+ const candidate = parseStructuredMediaCandidate(media);
if (!candidate) {
params.onInvalidCandidate(media.kind);
return;
@@ -487,7 +489,7 @@ async function replaceStructuredMedia(
}
}
-function parseRawBase64(
+function parseStructuredMediaCandidate(
media: StructuredMedia,
): MediaPayloadCandidate | undefined {
if (!isMediaContentType(media.contentType)) return;
@@ -510,9 +512,20 @@ function parseRawBase64(
: undefined;
}
+ if (isPythonBytesLiteral(media.content)) {
+ return {
+ encodedData: media.content,
+ encoding: "python_bytes_literal",
+ contentType: media.contentType,
+ kind: media.kind,
+ source: "bytes",
+ };
+ }
+
return isValidBase64(media.content)
? {
- base64Data: media.content,
+ encodedData: media.content,
+ encoding: "base64",
contentType: media.contentType,
kind: media.kind,
source: "bytes",
@@ -520,6 +533,16 @@ function parseRawBase64(
: undefined;
}
+function isPythonBytesLiteral(value: string): boolean {
+ const quote = value[1];
+ return (
+ value.length >= 3 &&
+ value[0] === "b" &&
+ (quote === "'" || quote === '"') &&
+ value.at(-1) === quote
+ );
+}
+
/**
* Cheaply requires a complete provider-specific key combination before the
* more expensive JSON.parse and structured traversal. A common `data` key by
diff --git a/packages/shared/src/server/otel/OtelMediaProcessor.test.ts b/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
index 70b3675804..4913b44bff 100644
--- a/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
+++ b/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
@@ -21,6 +21,16 @@ const SPAN_ID = "0123456789abcdef";
const MEDIA_ID = "test-media-id";
const PNG_BYTES = Buffer.from("test-image");
const PNG_BASE64 = PNG_BYTES.toString("base64");
+const PYTHON_BYTES = Buffer.from([
+ 0xff,
+ 0xd8,
+ 0xff,
+ 0xe0,
+ ...Buffer.from("test\nquote'slash\\"),
+ 0x00,
+]);
+const PYTHON_BYTES_LITERAL =
+ "b'\\xff\\xd8\\xff\\xe0test\\nquote\\'slash\\\\\\x00'";
const MEDIA_REFERENCE = `@@@langfuseMedia:type=image/png|id=${MEDIA_ID}|source=base64_data_uri@@@`;
function createEvent(params: { value: unknown; field?: MediaField }): {
@@ -204,6 +214,54 @@ describe("processOtelMedia", () => {
expect(result.detectionChecks.stringified_json).toBe(1);
});
+ it("processes Gemini media serialized as a Python bytes literal", async () => {
+ const { event, body } = createEvent({
+ value: JSON.stringify({
+ inline_data: {
+ mime_type: "image/jpeg",
+ data: PYTHON_BYTES_LITERAL,
+ },
+ }),
+ });
+ const uploadMedia = createUploadMock();
+
+ const result = await processEvents([event], uploadMedia);
+
+ expect(uploadMedia).toHaveBeenCalledWith(
+ expect.objectContaining({
+ contentType: "image/jpeg",
+ contentBytes: PYTHON_BYTES,
+ }),
+ );
+ expect(JSON.parse(body.input as string).inline_data.data).toBe(
+ `@@@langfuseMedia:type=image/jpeg|id=${MEDIA_ID}|source=bytes@@@`,
+ );
+ expect(result).toMatchObject({
+ uploaded: 1,
+ invalid: 0,
+ candidates: 1,
+ bytesProcessed: PYTHON_BYTES.length,
+ });
+ });
+
+ it("leaves malformed Python bytes literals unchanged", async () => {
+ const value = {
+ inline_data: {
+ mime_type: "image/jpeg",
+ data: "b'\\xff\\x0g'",
+ },
+ };
+ const { event, body } = createEvent({ value });
+ const uploadMedia = createUploadMock();
+
+ const result = await processEvents([event], uploadMedia);
+
+ expect(uploadMedia).not.toHaveBeenCalled();
+ expect(body.input).toBe(value);
+ expect(value.inline_data.data).toBe("b'\\xff\\x0g'");
+ expect(result.invalid).toBe(1);
+ });
+
it("leaves normalized values unchanged when upload fails", async () => {
const dataUri = `data:image/png;base64,${PNG_BASE64}`;
const { event, body } = createEvent({ value: dataUri });
diff --git a/packages/shared/src/server/otel/OtelMediaProcessor.ts b/packages/shared/src/server/otel/OtelMediaProcessor.ts
index 6605d37d89..0fc1cd30dd 100644
--- a/packages/shared/src/server/otel/OtelMediaProcessor.ts
+++ b/packages/shared/src/server/otel/OtelMediaProcessor.ts
@@ -159,7 +159,10 @@ async function processCandidate(
let contentBytes: Buffer;
try {
- contentBytes = Buffer.from(candidate.base64Data, "base64");
+ contentBytes =
+ candidate.encoding === "base64"
+ ? Buffer.from(candidate.encodedData, "base64")
+ : decodePythonBytesLiteral(candidate.encodedData);
if (contentBytes.length === 0) {
recordInvalidCandidate(candidate.kind, context);
return;
@@ -217,6 +220,84 @@ async function processCandidate(
}
}
+/**
+ * Strictly decodes the subset of Python bytes-literal syntax emitted by
+ * `bytes.__repr__`. Returns an exact-size Buffer and rejects malformed escapes
+ * instead of interpreting arbitrary Python expressions.
+ */
+function decodePythonBytesLiteral(value: string): Buffer {
+ const decodedLength = scanPythonBytesLiteral(value);
+ if (decodedLength === undefined) {
+ throw new Error("Invalid Python bytes literal");
+ }
+
+ const output = Buffer.alloc(decodedLength);
+ const written = scanPythonBytesLiteral(value, output);
+ if (written !== decodedLength) {
+ throw new Error("Invalid Python bytes literal");
+ }
+ return output;
+}
+
+function scanPythonBytesLiteral(
+ value: string,
+ output?: Buffer,
+): number | undefined {
+ const quote = value.charCodeAt(1);
+ const end = value.length - 1;
+ if (
+ value.length < 3 ||
+ value.charCodeAt(0) !== 98 ||
+ (quote !== 34 && quote !== 39) ||
+ value.charCodeAt(end) !== quote
+ ) {
+ return;
+ }
+
+ let offset = 0;
+ for (let index = 2; index < end; index += 1) {
+ let byte = value.charCodeAt(index);
+ if (byte !== 92) {
+ if (byte < 32 || byte > 126 || byte === quote) return;
+ } else {
+ index += 1;
+ if (index >= end) return;
+
+ const escape = value.charCodeAt(index);
+ if (escape === 120) {
+ if (index + 2 >= end) return;
+ const high = hexValue(value.charCodeAt(index + 1));
+ const low = hexValue(value.charCodeAt(index + 2));
+ if (high === undefined || low === undefined) return;
+ byte = high * 16 + low;
+ index += 2;
+ } else {
+ const escapedByte = escapedByteValue(escape);
+ if (escapedByte === undefined) return;
+ byte = escapedByte;
+ }
+ }
+
+ if (output) output[offset] = byte;
+ offset += 1;
+ }
+
+ return offset;
+}
+
+function escapedByteValue(code: number): number | undefined {
+ if (code === 34 || code === 39 || code === 92) return code;
+ if (code === 110) return 10;
+ if (code === 114) return 13;
+ if (code === 116) return 9;
+}
+
+function hexValue(code: number): number | undefined {
+ if (code >= 48 && code <= 57) return code - 48;
+ if (code >= 65 && code <= 70) return code - 55;
+ if (code >= 97 && code <= 102) return code - 87;
+}
+
function recordDetectionCheck(
path: MediaDetectionPath,
checkedBytes: number,