Skip to content

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

feat(mcp): Make media available via MCP (#13798)

Ben Bachemb5f4356e3982
diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.ts
index 946ac7f476..d0bf13fd50 100644
--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts
@@ -19,8 +19,14 @@ vi.mock("@langfuse/shared/src/server", async () => {
};
});
+vi.mock("@/src/features/media/server/getMediaStorageClient", () => ({
+ getMediaStorageServiceClient: () => ({
+ getSignedUrl: vi.fn().mockResolvedValue("https://media.example/download"),
+ }),
+}));
+
import { nanoid } from "nanoid";
-import { randomUUID } from "crypto";
+import { createHash, randomUUID } from "crypto";
import { prisma } from "@langfuse/shared/src/db";
import {
createEvent,
@@ -117,6 +123,10 @@ import {
updateScoreConfigTool,
handleUpdateScoreConfig,
} from "@/src/features/mcp/features/scores/tools/updateScoreConfig";
+import {
+ getMediaTool,
+ handleGetMedia,
+} from "@/src/features/mcp/features/media/tools/getMedia";
const maybeEventsTable =
env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"
@@ -209,6 +219,50 @@ const containsPropertyName = (value: unknown, expected: string): boolean => {
};
describe("MCP Read Tools", () => {
+ describe("getMedia tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getMediaTool, { readOnlyHint: true });
+ });
+
+ it("should return media metadata and a signed download URL", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const mediaId = `mcp-media-${nanoid()}`;
+ const uploadedAt = new Date("2026-01-01T00:00:00.000Z");
+
+ await prisma.media.create({
+ data: {
+ id: mediaId,
+ projectId,
+ sha256Hash: createHash("sha256").update(mediaId).digest("base64"),
+ bucketPath: `${projectId}/${mediaId}.png`,
+ bucketName: "media-test-bucket",
+ contentType: "image/png",
+ contentLength: 123n,
+ uploadedAt,
+ uploadHttpStatus: 200,
+ },
+ });
+
+ const result = (await handleGetMedia({ mediaId }, context)) as {
+ mediaId: string;
+ contentType: string;
+ contentLength: number;
+ uploadedAt: Date;
+ url: string;
+ urlExpiry: string;
+ };
+
+ expect(result).toMatchObject({
+ mediaId,
+ contentType: "image/png",
+ contentLength: 123,
+ url: "https://media.example/download",
+ });
+ expect(result.uploadedAt).toEqual(uploadedAt);
+ expect(new Date(result.urlExpiry).getTime()).toBeGreaterThan(Date.now());
+ });
+ });
+
describe("getObservationFieldSchema tool", () => {
it("should have readOnlyHint annotation", () => {
verifyToolAnnotations(getObservationFieldSchemaTool, {
diff --git a/web/src/features/mcp/features/media/index.ts b/web/src/features/mcp/features/media/index.ts
new file mode 100644
index 0000000000..37ad45bdb7
--- /dev/null
+++ b/web/src/features/mcp/features/media/index.ts
@@ -0,0 +1,14 @@
+import type { McpFeatureModule } from "../../server/registry";
+import { getMediaTool, handleGetMedia } from "./tools/getMedia";
+
+export const mediaFeature: McpFeatureModule = {
+ name: "media",
+ description:
+ "Retrieve files, images, audio, video, text, and other media assets in the current Langfuse project",
+ tools: [
+ {
+ definition: getMediaTool,
+ handler: handleGetMedia,
+ },
+ ],
+};
diff --git a/web/src/features/mcp/features/media/tools/getMedia.ts b/web/src/features/mcp/features/media/tools/getMedia.ts
new file mode 100644
index 0000000000..6ed1ba2980
--- /dev/null
+++ b/web/src/features/mcp/features/media/tools/getMedia.ts
@@ -0,0 +1,33 @@
+import { SpanKind } from "@opentelemetry/api";
+
+import { getMedia } from "@/src/features/media/server/mediaService";
+import { GetMediaQuerySchema } from "@/src/features/media/validation";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { defineTool } from "../../../core/define-tool";
+
+export const [getMediaTool, handleGetMedia] = defineTool({
+ name: "getMedia",
+ description:
+ "Fetch metadata and a signed download URL for one media asset in the current Langfuse project.",
+ baseSchema: GetMediaQuerySchema,
+ inputSchema: GetMediaQuerySchema,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.media.get", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.media_id": input.mediaId,
+ });
+
+ return await getMedia({
+ projectId: context.projectId,
+ mediaId: input.mediaId,
+ });
+ },
+ );
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.ts
index 056fba641e..eafebba3f2 100644
--- a/web/src/features/mcp/server/bootstrap.ts
+++ b/web/src/features/mcp/server/bootstrap.ts
@@ -20,6 +20,7 @@ import { healthFeature } from "../features/health";
import { scoresFeature } from "../features/scores";
import { metricsFeature } from "../features/metrics";
import { modelsFeature } from "../features/models";
+import { mediaFeature } from "../features/media";
// Import future features as they're added:
// import { tracesFeature } from "../features/traces";
// import { evalsFeature } from "../features/evals";
@@ -41,6 +42,7 @@ export function bootstrapMcpFeatures(): void {
toolRegistry.register(scoresFeature);
toolRegistry.register(metricsFeature);
toolRegistry.register(modelsFeature);
+ toolRegistry.register(mediaFeature);
// Add future features here:
// toolRegistry.register(tracesFeature);
diff --git a/web/src/features/media/server/mediaService.ts b/web/src/features/media/server/mediaService.ts
new file mode 100644
index 0000000000..df8ff7a315
--- /dev/null
+++ b/web/src/features/media/server/mediaService.ts
@@ -0,0 +1,305 @@
+import { randomUUID } from "crypto";
+
+import { env } from "@/src/env.mjs";
+import { getFileExtensionFromContentType } from "@/src/features/media/server/getFileExtensionFromContentType";
+import { getMediaStorageServiceClient } from "@/src/features/media/server/getMediaStorageClient";
+import {
+ GetMediaResponseSchema,
+ type GetMediaUploadUrlQuery,
+ GetMediaUploadUrlResponseSchema,
+ type MediaContentType,
+ type PatchMediaBody,
+} from "@/src/features/media/validation";
+import { InternalServerError, LangfuseNotFoundError } from "@langfuse/shared";
+import { Prisma, prisma } from "@langfuse/shared/src/db";
+import {
+ getCurrentSpan,
+ logger,
+ recordHistogram,
+ recordIncrement,
+} from "@langfuse/shared/src/server";
+
+export async function createMediaUploadUrl(params: {
+ projectId: string;
+ body: GetMediaUploadUrlQuery;
+}) {
+ const { projectId, body } = params;
+ const {
+ contentType,
+ contentLength,
+ sha256Hash,
+ traceId,
+ observationId,
+ field,
+ } = body;
+
+ try {
+ const existingMedia = await prisma.media.findUnique({
+ where: {
+ projectId_sha256Hash: {
+ projectId,
+ sha256Hash,
+ },
+ },
+ });
+
+ const mediaId = existingMedia?.id ?? getMediaId(sha256Hash);
+ getCurrentSpan()?.setAttribute("mediaId", mediaId);
+
+ if (
+ existingMedia &&
+ existingMedia.uploadHttpStatus === 200 &&
+ existingMedia.contentType === contentType
+ ) {
+ await linkMediaToTraceOrObservation({
+ projectId,
+ traceId,
+ observationId,
+ mediaId,
+ field,
+ });
+
+ return GetMediaUploadUrlResponseSchema.parse({
+ mediaId,
+ uploadUrl: null,
+ });
+ }
+
+ const uploadBucket = env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET;
+
+ if (!uploadBucket) {
+ throw new InternalServerError(
+ "Media upload to blob storage not enabled or no bucket configured",
+ );
+ }
+
+ const bucketPath = getBucketPath({ projectId, mediaId, contentType });
+ const uploadUrl = await getMediaStorageServiceClient(
+ uploadBucket,
+ ).getSignedUploadUrl({
+ path: bucketPath,
+ ttlSeconds: 60 * 60,
+ sha256Hash,
+ contentType,
+ contentLength,
+ });
+
+ await upsertMediaRecord({
+ mediaId,
+ projectId,
+ sha256Hash,
+ bucketPath,
+ uploadBucket,
+ contentType,
+ contentLength,
+ });
+
+ await linkMediaToTraceOrObservation({
+ projectId,
+ traceId,
+ observationId,
+ mediaId,
+ field,
+ });
+
+ return GetMediaUploadUrlResponseSchema.parse({ mediaId, uploadUrl });
+ } catch (error) {
+ if (error instanceof InternalServerError) throw error;
+
+ logger.error(
+ `Failed to get media upload URL for trace ${traceId} and observation ${observationId}.`,
+ );
+ throw new InternalServerError("Failed to get media upload URL");
+ }
+}
+
+export async function getMedia(params: { projectId: string; mediaId: string }) {
+ const { projectId, mediaId } = params;
+ const media = await prisma.media.findUnique({
+ where: {
+ projectId_id: {
+ projectId,
+ id: mediaId,
+ },
+ },
+ });
+
+ if (!media) throw new LangfuseNotFoundError("Media asset not found");
+ if (!media.uploadHttpStatus) {
+ throw new LangfuseNotFoundError("Media not yet uploaded");
+ }
+ if (!(media.uploadHttpStatus === 200 || media.uploadHttpStatus === 201)) {
+ throw new LangfuseNotFoundError(
+ `Media upload failed with status ${media.uploadHttpStatus}: \n ${media.uploadHttpError}`,
+ );
+ }
+
+ const ttlSeconds = env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS;
+ const url = await getMediaStorageServiceClient(media.bucketName).getSignedUrl(
+ media.bucketPath,
+ ttlSeconds,
+ false,
+ );
+
+ return GetMediaResponseSchema.parse({
+ mediaId,
+ contentType: media.contentType,
+ contentLength: Number(media.contentLength),
+ uploadedAt: media.uploadedAt,
+ url,
+ urlExpiry: new Date(Date.now() + ttlSeconds * 1000).toISOString(),
+ });
+}
+
+export async function updateMediaUploadStatus(params: {
+ projectId: string;
+ mediaId: string;
+ body: PatchMediaBody;
+}) {
+ const { projectId, mediaId, body } = params;
+ const { uploadedAt, uploadHttpStatus, uploadHttpError, uploadTimeMs } = body;
+
+ try {
+ await prisma.media.update({
+ where: {
+ projectId_id: {
+ projectId,
+ id: mediaId,
+ },
+ },
+ data: {
+ uploadedAt,
+ uploadHttpStatus,
+ uploadHttpError: uploadHttpStatus === 200 ? null : uploadHttpError,
+ },
+ });
+
+ recordIncrement("langfuse.media.upload_http_status", 1, {
+ status_code: uploadHttpStatus,
+ });
+
+ if (uploadTimeMs) {
+ recordHistogram("langfuse.media.upload_time_ms", uploadTimeMs, {
+ status_code: uploadHttpStatus,
+ });
+ }
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2025"
+ ) {
+ throw new LangfuseNotFoundError(
+ `Media asset ${mediaId} not found in project ${projectId}`,
+ );
+ }
+
+ const message = error instanceof Error ? error.message : "";
+ throw new InternalServerError(
+ `Error updating uploadedAt on media ID ${mediaId}: ${message}`,
+ );
+ }
+}
+
+async function upsertMediaRecord(params: {
+ mediaId: string;
+ projectId: string;
+ sha256Hash: string;
+ bucketPath: string;
+ uploadBucket: string;
+ contentType: MediaContentType;
+ contentLength: number;
+}) {
+ const {
+ mediaId,
+ projectId,
+ sha256Hash,
+ bucketPath,
+ uploadBucket,
+ contentType,
+ contentLength,
+ } = params;
+ const maxRetries = 3;
+ const delayMs = 100;
+
+ for (let retryCount = 0; retryCount < maxRetries; retryCount += 1) {
+ try {
+ await prisma.$queryRaw`
+ INSERT INTO "media" (
+ "id",
+ "project_id",
+ "sha_256_hash",
+ "bucket_path",
+ "bucket_name",
+ "content_type",
+ "content_length"
+ )
+ VALUES (
+ ${mediaId},
+ ${projectId},
+ ${sha256Hash},
+ ${bucketPath},
+ ${uploadBucket},
+ ${contentType},
+ ${contentLength}
+ )
+ ON CONFLICT ("project_id", "sha_256_hash")
+ DO UPDATE SET
+ "bucket_name" = ${uploadBucket},
+ "bucket_path" = ${bucketPath},
+ "content_type" = ${contentType},
+ "content_length" = ${contentLength}
+ `;
+ return;
+ } catch (error) {
+ if (retryCount === maxRetries - 1) throw error;
+
+ logger.debug(
+ `Failed to create media record. Retrying (${retryCount + 1}/${maxRetries})...`,
+ );
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ }
+ }
+}
+
+async function linkMediaToTraceOrObservation(params: {
+ projectId: string;
+ traceId: string;
+ observationId?: string | null;
+ mediaId: string;
+ field: string;
+}) {
+ const { projectId, traceId, observationId, mediaId, field } = params;
+
+ if (observationId) {
+ await prisma.$queryRaw`
+ INSERT INTO "observation_media" ("id", "project_id", "trace_id", "observation_id", "media_id", "field")
+ VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${observationId}, ${mediaId}, ${field})
+ ON CONFLICT DO NOTHING;
+ `;
+ return;
+ }
+
+ await prisma.$queryRaw`
+ INSERT INTO "trace_media" ("id", "project_id", "trace_id", "media_id", "field")
+ VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${mediaId}, ${field})
+ ON CONFLICT DO NOTHING;
+ `;
+}
+
+function getBucketPath(params: {
+ projectId: string;
+ mediaId: string;
+ contentType: MediaContentType;
+}) {
+ const { projectId, mediaId, contentType } = params;
+ const prefix = env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX ?? "";
+ const fileExtension = getFileExtensionFromContentType(contentType);
+
+ return `${prefix}${projectId}/${mediaId}.${fileExtension}`;
+}
+
+function getMediaId(sha256Hash: string) {
+ const urlSafeHash = sha256Hash.replaceAll("+", "-").replaceAll("/", "_");
+
+ return urlSafeHash.slice(0, 22);
+}
diff --git a/web/src/pages/api/public/media/[mediaId].ts b/web/src/pages/api/public/media/[mediaId].ts
index 4b42f71c73..b0f262df64 100644
--- a/web/src/pages/api/public/media/[mediaId].ts
+++ b/web/src/pages/api/public/media/[mediaId].ts
@@ -1,7 +1,9 @@
import { z } from "zod";
-import { env } from "@/src/env.mjs";
-import { getMediaStorageServiceClient } from "@/src/features/media/server/getMediaStorageClient";
+import {
+ getMedia,
+ updateMediaUploadStatus,
+} from "@/src/features/media/server/mediaService";
import {
GetMediaQuerySchema,
GetMediaResponseSchema,
@@ -9,13 +11,7 @@ import {
} from "@/src/features/media/validation";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
-import {
- ForbiddenError,
- InternalServerError,
- LangfuseNotFoundError,
-} from "@langfuse/shared";
-import { Prisma, prisma } from "@langfuse/shared/src/db";
-import { recordIncrement, recordHistogram } from "@langfuse/shared/src/server";
+import { ForbiddenError } from "@langfuse/shared";
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
@@ -28,43 +24,7 @@ export default withMiddlewares({
const { projectId } = auth.scope;
const { mediaId } = query;
- const media = await prisma.media.findUnique({
- where: {
- projectId_id: {
- projectId,
- id: mediaId,
- },
- },
- });
-
- if (!media) throw new LangfuseNotFoundError("Media asset not found");
- if (!media.uploadHttpStatus)
- throw new LangfuseNotFoundError("Media not yet uploaded");
- if (!(media.uploadHttpStatus === 200 || media.uploadHttpStatus === 201))
- throw new LangfuseNotFoundError(
- `Media upload failed with status ${media.uploadHttpStatus}: \n ${media.uploadHttpError}`,
- );
-
- const mediaStorageClient = getMediaStorageServiceClient(media.bucketName);
- const ttlSeconds = env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS;
- const urlExpiry = new Date(Date.now() + ttlSeconds * 1000).toISOString();
-
- const url = await mediaStorageClient.getSignedUrl(
- media.bucketPath,
- ttlSeconds,
- false,
- );
-
- const { contentType, contentLength, uploadedAt } = media;
-
- return {
- mediaId,
- contentType,
- contentLength: Number(contentLength),
- url,
- urlExpiry,
- uploadedAt,
- };
+ return await getMedia({ projectId, mediaId });
},
}),
@@ -81,53 +41,8 @@ export default withMiddlewares({
const { projectId } = auth.scope;
const { mediaId } = query;
- const { uploadedAt, uploadHttpStatus, uploadHttpError, uploadTimeMs } =
- body;
-
- try {
- await prisma.media.update({
- where: {
- projectId_id: {
- projectId,
- id: mediaId,
- },
- },
- data: {
- uploadedAt,
- uploadHttpStatus,
- uploadHttpError: uploadHttpStatus === 200 ? null : uploadHttpError,
- },
- });
-
- recordIncrement("langfuse.media.upload_http_status", 1, {
- status_code: uploadHttpStatus,
- });
-
- if (uploadTimeMs) {
- recordHistogram("langfuse.media.upload_time_ms", uploadTimeMs, {
- status_code: uploadHttpStatus,
- });
- }
- } catch (e) {
- if (
- e instanceof Prisma.PrismaClientKnownRequestError &&
- e.code === "P2025"
- ) {
- /* https://www.prisma.io/docs/orm/reference/error-reference#p2025
- * An operation failed because it depends on one or more records that were required but not found.
- */
- throw new LangfuseNotFoundError(
- `Media asset ${mediaId} not found in project ${projectId}`,
- );
- }
- throw new InternalServerError(
- `Error updating uploadedAt on media ID ${mediaId}` +
- (e instanceof Error ? e.message : "")
- ? (e as Error).message
- : "",
- );
- }
+ await updateMediaUploadStatus({ projectId, mediaId, body });
},
}),
});
diff --git a/web/src/pages/api/public/media/index.ts b/web/src/pages/api/public/media/index.ts
index 3167c5f9f7..41af1a5a18 100644
--- a/web/src/pages/api/public/media/index.ts
+++ b/web/src/pages/api/public/media/index.ts
@@ -1,22 +1,13 @@
-import { randomUUID } from "crypto";
-
import { env } from "@/src/env.mjs";
-import { getFileExtensionFromContentType } from "@/src/features/media/server/getFileExtensionFromContentType";
-import { getMediaStorageServiceClient } from "@/src/features/media/server/getMediaStorageClient";
+import { createMediaUploadUrl } from "@/src/features/media/server/mediaService";
import {
GetMediaUploadUrlQuerySchema,
GetMediaUploadUrlResponseSchema,
- type MediaContentType,
} from "@/src/features/media/validation";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
-import {
- ForbiddenError,
- InternalServerError,
- InvalidRequestError,
-} from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
-import { logger, instrumentAsync } from "@langfuse/shared/src/server";
+import { ForbiddenError, InvalidRequestError } from "@langfuse/shared";
+import { instrumentAsync } from "@langfuse/shared/src/server";
export default withMiddlewares({
POST: createAuthedProjectAPIRoute({
@@ -36,14 +27,7 @@ export default withMiddlewares({
if (auth.scope.accessLevel !== "project") throw new ForbiddenError();
const { projectId } = auth.scope;
- const {
- contentType,
- contentLength,
- sha256Hash,
- traceId,
- observationId,
- field,
- } = body;
+ const { contentLength, sha256Hash, traceId, observationId, field } = body;
if (contentLength > env.LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH)
throw new InvalidRequestError(
@@ -59,173 +43,12 @@ export default withMiddlewares({
span.setAttribute("field", field);
span.setAttribute("sha256Hash", sha256Hash);
- try {
- const existingMedia = await prisma.media.findUnique({
- where: {
- projectId_sha256Hash: {
- projectId,
- sha256Hash,
- },
- },
- });
-
- if (
- existingMedia &&
- existingMedia.uploadHttpStatus === 200 &&
- existingMedia.contentType === contentType
- ) {
- span.setAttribute("mediaId", existingMedia.id);
-
- if (observationId) {
- // Use raw upserts to avoid deadlocks
- await prisma.$queryRaw`
- INSERT INTO "observation_media" ("id", "project_id", "trace_id", "observation_id", "media_id", "field")
- VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${observationId}, ${existingMedia.id}, ${field})
- ON CONFLICT DO NOTHING;
- `;
- } else {
- // Use raw upserts to avoid deadlocks
- await prisma.$queryRaw`
- INSERT INTO "trace_media" ("id", "project_id", "trace_id", "media_id", "field")
- VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${existingMedia.id}, ${field})
- ON CONFLICT DO NOTHING;
- `;
- }
-
- return {
- mediaId: existingMedia.id,
- uploadUrl: null,
- };
- }
-
- const mediaId = existingMedia?.id ?? getMediaId({ sha256Hash });
-
- span.setAttribute("mediaId", mediaId);
-
- if (!env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET)
- throw new InternalServerError(
- "Media upload to blob storage not enabled or no bucket configured",
- );
-
- const s3Client = getMediaStorageServiceClient(
- env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
- );
-
- const bucketPath = getBucketPath({
- projectId,
- mediaId,
- contentType,
- });
-
- const uploadUrl = await s3Client.getSignedUploadUrl({
- path: bucketPath,
- ttlSeconds: 60 * 60, // 1 hour
- sha256Hash,
- contentType,
- contentLength,
- });
-
- // Create media record first to ensure fkey constraint is met on next queries
- // Under high concurrency, the upsert might fail due to the multiple uniqueness constraints
- // (id and (project_id ad sha_256))
- // See also: https://stackoverflow.com/questions/73164161/insert-on-conflict-do-update-set-an-upsert-statement-with-a-unique-constraint
- const maxRetries = 3;
- const delayMs = 100;
- let retryCount = 0;
+ const result = await createMediaUploadUrl({ projectId, body });
+ span.setAttribute("mediaId", result.mediaId);
- while (retryCount < maxRetries) {
- try {
- await prisma.$queryRaw`
- INSERT INTO "media" (
- "id",
- "project_id",
- "sha_256_hash",
- "bucket_path",
- "bucket_name",
- "content_type",
- "content_length"
- )
- VALUES (
- ${mediaId},
- ${projectId},
- ${sha256Hash},
- ${bucketPath},
- ${env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET},
- ${contentType},
- ${contentLength}
- )
- ON CONFLICT ("project_id", "sha_256_hash")
- DO UPDATE SET
- "bucket_name" = ${env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET},
- "bucket_path" = ${bucketPath},
- "content_type" = ${contentType},
- "content_length" = ${contentLength}
- `;
- break;
- } catch (e) {
- retryCount += 1;
-
- if (retryCount >= maxRetries) throw e;
-
- logger.debug(
- `Failed to create media record. Retrying (${retryCount}/${maxRetries})...`,
- );
-
- await new Promise((resolve) => setTimeout(resolve, delayMs));
- }
- }
-
- if (observationId) {
- await prisma.$queryRaw`
- INSERT INTO "observation_media" ("id", "project_id", "trace_id", "observation_id", "media_id", "field")
- VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${observationId}, ${mediaId}, ${field})
- ON CONFLICT DO NOTHING;
- `;
- } else {
- await prisma.$queryRaw`
- INSERT INTO "trace_media" ("id", "project_id", "trace_id", "media_id", "field")
- VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${mediaId}, ${field})
- ON CONFLICT DO NOTHING;
- `;
- }
-
- return {
- mediaId,
- uploadUrl,
- };
- } catch {
- logger.error(
- `Failed to get media upload URL for trace ${traceId} and observation ${observationId}.`,
- );
- throw new InternalServerError("Failed to get media upload URL");
- }
+ return result;
},
);
},
}),
});
-
-function getBucketPath(params: {
- projectId: string;
- mediaId: string;
- contentType: MediaContentType;
-}): string {
- const { projectId, mediaId, contentType } = params;
- const fileExtension = getFileExtensionFromContentType(contentType);
-
- const prefix = env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX
- ? `${env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX}`
- : "";
-
- return `${prefix}${projectId}/${mediaId}.${fileExtension}`;
-}
-
-function getMediaId(params: { sha256Hash: string }) {
- const { sha256Hash } = params;
-
- // Make hash URL safe
- const urlSafeHash = sha256Hash.replaceAll("+", "-").replaceAll("/", "_");
-
- // Get first 132 bits, i.e. first 22 base64Url chars
- return urlSafeHash.slice(0, 22);
-}