Skip to content

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

feat(media): add ui support (#4285)

Hassieb Pakzadf71e1aebed9e
diff --git a/fern/apis/server/definition/media.yml b/fern/apis/server/definition/media.yml
index ff53f3d382..c3b7bd83ca 100644
--- a/fern/apis/server/definition/media.yml
+++ b/fern/apis/server/definition/media.yml
@@ -78,9 +78,7 @@ types:
observationId:
type: optional<string>
docs: The observation ID associated with the media record. If the media record is associated directly with a trace, this will be null.
- contentType:
- type: string
- docs: The MIME type of the media record
+ contentType: MediaContentType
contentLength:
type: integer
docs: The size of the media record in bytes
@@ -99,3 +97,7 @@ types:
mediaId:
type: string
docs: The unique langfuse identifier of a media record
+
+ MediaContentType:
+ type: literal<"image/png","image/jpeg","image/jpg","image/webp","audio/mpeg","audio/mp3","audio/wav","text/plain","application/pdf">
+ docs: The MIME type of the media record
diff --git a/web/next.config.mjs b/web/next.config.mjs
index 60c22e46c8..149f35ff01 100644
--- a/web/next.config.mjs
+++ b/web/next.config.mjs
@@ -14,7 +14,7 @@ const cspHeader = `
default-src 'self' https://*.langfuse.com https://*.langfuse.dev https://*.posthog.com https://*.sentry.io wss://*.crisp.chat https://*.crisp.chat;
script-src 'self' 'unsafe-eval' 'unsafe-inline' https://*.langfuse.com https://*.langfuse.dev https://client.crisp.chat https://settings.crisp.chat https://challenges.cloudflare.com https://*.sentry.io https://static.cloudflareinsights.com https://*.stripe.com;
style-src 'self' 'unsafe-inline' https://client.crisp.chat;
- img-src 'self' https: blob: data: https://client.crisp.chat https://image.crisp.chat https://storage.crisp.chat;
+ img-src 'self' https: blob: data: http://localhost:* https://client.crisp.chat https://image.crisp.chat https://storage.crisp.chat;
font-src 'self' https://client.crisp.chat;
frame-src 'self' https://challenges.cloudflare.com https://*.stripe.com https://game.crisp.chat;
worker-src 'self' blob:;
@@ -23,7 +23,7 @@ const cspHeader = `
form-action 'self';
frame-ancestors 'none';
connect-src 'self' https://*.langfuse.com https://*.langfuse.dev https://client.crisp.chat https://storage.crisp.chat wss://client.relay.crisp.chat wss://stream.relay.crisp.chat https://*.ingest.us.sentry.io;
- media-src 'self' https://client.crisp.chat;
+ media-src 'self' https: http://localhost:* https://client.crisp.chat;
${env.LANGFUSE_CSP_ENFORCE_HTTPS === "true" ? "upgrade-insecure-requests; block-all-mixed-content;" : ""}
${env.SENTRY_CSP_REPORT_URI ? `report-uri ${env.SENTRY_CSP_REPORT_URI}; report-to csp-endpoint;` : ""}
`;
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 2311e438a5..697ce37629 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -4021,8 +4021,7 @@ components:
The observation ID associated with the media record. If the media
record is associated directly with a trace, this will be null.
contentType:
- type: string
- description: The MIME type of the media record
+ $ref: '#/components/schemas/MediaContentType'
contentLength:
type: integer
description: The size of the media record in bytes
@@ -4055,6 +4054,13 @@ components:
description: The unique langfuse identifier of a media record
required:
- mediaId
+ MediaContentType:
+ title: MediaContentType
+ type: string
+ enum:
+ - >-
+ image/png","image/jpeg","image/jpg","image/webp","audio/mpeg","audio/mp3","audio/wav","text/plain","application/pdf
+ description: The MIME type of the media record
DailyMetrics:
title: DailyMetrics
type: object
diff --git a/web/src/components/schemas/ChatMlSchema.ts b/web/src/components/schemas/ChatMlSchema.ts
index 756e085445..c181938889 100644
--- a/web/src/components/schemas/ChatMlSchema.ts
+++ b/web/src/components/schemas/ChatMlSchema.ts
@@ -8,6 +8,54 @@ const OpenAITextContentPart = z.object({
export const OpenAIUrlImageUrl = z.string().regex(/^https?:/);
+export const ParsedMediaReferenceSchema = z.object({
+ type: z.string(),
+ id: z.string(),
+ source: z.string(),
+ referenceString: z.string(),
+});
+export type ParsedMediaReferenceType = z.infer<
+ typeof ParsedMediaReferenceSchema
+>;
+
+export const MediaReferenceStringSchema = z
+ .string()
+ .transform((str, ctx) => {
+ // @@@langfuseMedia:type=image/jpeg|id=cc48838a-3da8-4ca4-a007-2cf8df930e69|source=base64@@@
+ const magicStringPattern = /^@@@langfuseMedia:(.*)@@@$/;
+
+ const match = str.match(magicStringPattern);
+ if (!match) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Invalid langfuseMedia magic string format",
+ });
+ return z.NEVER;
+ }
+
+ const content = match[1];
+ const parts = content.split("|").filter(Boolean);
+
+ const metadata: Record<string, string> = {
+ referenceString: str,
+ };
+
+ for (const part of parts) {
+ const [key, value] = part.split("=");
+ if (key && value !== undefined) {
+ metadata[key.trim()] = value.trim();
+ } else {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Invalid key-value pair: ${part}`,
+ });
+ return z.NEVER;
+ }
+ }
+ return metadata;
+ })
+ .pipe(ParsedMediaReferenceSchema);
+
const OpenAIBase64ImageUrl = z
.string()
.regex(/^data:image\/(png|jpeg|jpg|gif|webp);base64,/);
@@ -15,16 +63,39 @@ const OpenAIBase64ImageUrl = z
const OpenAIImageContentPart = z.object({
type: z.literal("image_url"),
image_url: z.object({
- url: z.union([OpenAIUrlImageUrl, OpenAIBase64ImageUrl]),
+ url: z.union([
+ OpenAIUrlImageUrl,
+ MediaReferenceStringSchema,
+ OpenAIBase64ImageUrl,
+ ]),
detail: z.enum(["low", "high", "auto"]).optional(), // Controls how the model processes the image. Defaults to "auto". [https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding]
}),
});
+const OpenAIInputAudioContentPart = z.object({
+ type: z.literal("input_audio"),
+ input_audio: z.object({
+ data: MediaReferenceStringSchema,
+ }),
+});
+
+const OpenAIOutputAudioSchema = z.object({
+ data: MediaReferenceStringSchema,
+ transcript: z.string().optional(),
+});
+export type OpenAIOutputAudioType = z.infer<typeof OpenAIOutputAudioSchema>;
+
export const OpenAIContentParts = z.array(
- z.union([OpenAITextContentPart, OpenAIImageContentPart]),
+ z.union([
+ OpenAITextContentPart,
+ OpenAIImageContentPart,
+ OpenAIInputAudioContentPart,
+ ]),
);
-export const OpenAIContentSchema = z.union([z.string(), OpenAIContentParts]);
+export const OpenAIContentSchema = z
+ .union([z.string(), OpenAIContentParts])
+ .nullable();
export type OpenAIContentSchema = z.infer<typeof OpenAIContentSchema>;
export const ChatMlMessageSchema = z
@@ -39,6 +110,7 @@ export const ChatMlMessageSchema = z
OpenAIContentSchema,
])
.nullish(),
+ audio: OpenAIOutputAudioSchema.optional(),
additional_kwargs: z.record(z.any()).optional(),
})
.passthrough()
@@ -47,10 +119,11 @@ export const ChatMlMessageSchema = z
...other,
...additional_kwargs,
}))
- .transform(({ role, name, content, ...other }) => ({
+ .transform(({ role, name, content, audio, ...other }) => ({
role,
name,
content,
+ audio,
json: Object.keys(other).length === 0 ? undefined : other,
}));
export type ChatMlMessageSchema = z.infer<typeof ChatMlMessageSchema>;
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index 075522bbff..c50b872545 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -13,8 +13,10 @@ import {
ChatMlArraySchema,
type ChatMlMessageSchema,
OpenAIContentSchema,
+ type OpenAIOutputAudioType,
} from "@/src/components/schemas/ChatMlSchema";
import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";
+import { type MediaReturnType } from "@/src/features/media/validation";
const isSupportedMarkdownFormat = (
content: unknown,
@@ -31,11 +33,15 @@ export function MarkdownOrJsonView({
title,
className,
customCodeHeaderClassName,
+ audio,
+ media,
}: {
content?: unknown;
title?: string;
className?: string;
customCodeHeaderClassName?: string;
+ audio?: OpenAIOutputAudioType;
+ media?: MediaReturnType[];
}) {
const stringOrValidatedMarkdown = useMemo(
() => StringOrMarkdownSchema.safeParse(content),
@@ -52,20 +58,26 @@ export function MarkdownOrJsonView({
validatedOpenAIContent,
);
- return isMarkdownEnabled && canEnableMarkdown ? (
- <MarkdownView
- markdown={stringOrValidatedMarkdown.data ?? content}
- title={title}
- className={className}
- customCodeHeaderClassName={customCodeHeaderClassName}
- />
- ) : (
- <JSONView
- json={content}
- canEnableMarkdown={canEnableMarkdown}
- title={title}
- className={className}
- />
+ return (
+ <>
+ {isMarkdownEnabled && canEnableMarkdown ? (
+ <MarkdownView
+ markdown={stringOrValidatedMarkdown.data ?? content}
+ title={title}
+ className={className}
+ customCodeHeaderClassName={customCodeHeaderClassName}
+ audio={audio}
+ />
+ ) : (
+ <JSONView
+ json={content ?? (audio ? { audio } : null)}
+ canEnableMarkdown={canEnableMarkdown}
+ title={title}
+ className={className}
+ media={media}
+ />
+ )}
+ </>
);
}
@@ -74,6 +86,7 @@ export const IOPreview: React.FC<{
output?: Prisma.JsonValue;
isLoading?: boolean;
hideIfNull?: boolean;
+ media?: MediaReturnType[];
hideOutput?: boolean;
hideInput?: boolean;
}> = ({
@@ -81,6 +94,7 @@ export const IOPreview: React.FC<{
hideIfNull = false,
hideOutput = false,
hideInput = false,
+ media,
...props
}) => {
const [currentView, setCurrentView] = useState<"pretty" | "json">("pretty");
@@ -178,7 +192,11 @@ export const IOPreview: React.FC<{
) : (
<>
{!(hideIfNull && !input) && !hideInput ? (
- <MarkdownOrJsonView title="Input" content={input} />
+ <MarkdownOrJsonView
+ title="Input"
+ content={input}
+ media={media?.filter((m) => m.field === "input") ?? []}
+ />
) : null}
{!(hideIfNull && !output) && !hideOutput ? (
<MarkdownOrJsonView
@@ -186,6 +204,7 @@ export const IOPreview: React.FC<{
content={output}
className="bg-accent-light-green dark:border-accent-dark-green"
customCodeHeaderClassName="bg-muted-green dark:bg-secondary"
+ media={media?.filter((m) => m.field === "output") ?? []}
/>
) : null}
</>
@@ -200,6 +219,7 @@ export const IOPreview: React.FC<{
json={input ?? null}
isLoading={isLoading}
className="flex-1"
+ media={media?.filter((m) => m.field === "input") ?? []}
/>
) : null}
{!(hideIfNull && !output) && !hideOutput ? (
@@ -208,6 +228,7 @@ export const IOPreview: React.FC<{
json={outputClean}
isLoading={isLoading}
className="flex-1 bg-accent-light-green dark:border-accent-dark-green"
+ media={media?.filter((m) => m.field === "output") ?? []}
/>
) : null}
</>
@@ -243,7 +264,7 @@ export const OpenAiMessageView: React.FC<{
.map((message, index) => (
<Fragment key={index}>
<div>
- {!!message.content &&
+ {(!!message.content || !!message.audio) &&
(shouldRenderMarkdown ? (
<MarkdownOrJsonView
title={message.name ?? message.role}
@@ -260,6 +281,7 @@ export const OpenAiMessageView: React.FC<{
message.role === "assistant" &&
"bg-muted-green dark:bg-secondary",
)}
+ audio={message.audio}
/>
) : (
<JSONView
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 422439bf1c..e217cc3259 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -76,6 +76,20 @@ export const ObservationPreview = ({
queryClickhouse: useClickhouse(),
});
+ const observationMedia = api.media.getByTraceOrObservationId.useQuery(
+ {
+ traceId: traceId,
+ observationId: currentObservationId,
+ projectId: projectId,
+ },
+ {
+ refetchOnWindowFocus: false,
+ refetchOnMount: false,
+ refetchOnReconnect: false,
+ staleTime: 50 * 60 * 1000, // 50 minutes
+ },
+ );
+
const preloadedObservation = observations.find(
(o) => o.id === currentObservationId,
);
@@ -266,6 +280,7 @@ export const ObservationPreview = ({
input={observationWithInputAndOutput.data?.input ?? undefined}
output={observationWithInputAndOutput.data?.output ?? undefined}
isLoading={observationWithInputAndOutput.isLoading}
+ media={observationMedia.data}
/>
{preloadedObservation.statusMessage ? (
<JSONView
@@ -279,6 +294,9 @@ export const ObservationPreview = ({
key={observationWithInputAndOutput.data.id + "-metadata"}
title="Metadata"
json={observationWithInputAndOutput.data.metadata}
+ media={observationMedia.data?.filter(
+ (m) => m.field === "metadata",
+ )}
/>
) : null}
{viewType === "detailed" && (
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 27463a2143..9b0de5cc7a 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -24,6 +24,7 @@ import { ScoresPreview } from "@/src/components/trace/ScoresPreview";
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import useLocalStorage from "@/src/components/useLocalStorage";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
+import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
import { NewDatasetItemFromTrace } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";
import { CreateNewAnnotationQueueItem } from "@/src/ee/features/annotation-queues/components/CreateNewAnnotationQueueItem";
@@ -73,6 +74,18 @@ export const TracePreview = ({
acc.get(score.source)?.push(score);
return acc;
}, new Map<ScoreSource, APIScore[]>());
+ const traceMedia = api.media.getByTraceOrObservationId.useQuery(
+ {
+ traceId: trace.id,
+ projectId: trace.projectId,
+ },
+ {
+ refetchOnWindowFocus: false,
+ refetchOnMount: false,
+ refetchOnReconnect: false,
+ staleTime: 50 * 60 * 1000, // 50 minutes
+ },
+ );
const totalCost = useMemo(
() =>
@@ -179,11 +192,15 @@ export const TracePreview = ({
key={trace.id + "-io"}
input={trace.input ?? undefined}
output={trace.output ?? undefined}
+ media={traceMedia.data}
/>
<JSONView
key={trace.id + "-metadata"}
title="Metadata"
json={trace.metadata}
+ media={
+ traceMedia.data?.filter((m) => m.field === "metadata") ?? []
+ }
/>
{viewType === "detailed" && (
<ScoresPreview itemScoresBySource={traceScoresBySource} />
diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsx
index f5929def35..9955a58b4b 100644
--- a/web/src/components/ui/CodeJsonViewer.tsx
+++ b/web/src/components/ui/CodeJsonViewer.tsx
@@ -10,6 +10,8 @@ import { useTheme } from "next-themes";
import { BsMarkdown } from "react-icons/bs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";
+import { type MediaReturnType } from "@/src/features/media/validation";
+import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
export function JSONView(props: {
canEnableMarkdown?: boolean;
@@ -19,6 +21,7 @@ export function JSONView(props: {
isLoading?: boolean;
codeClassName?: string;
collapseStringsAfterLength?: number | null;
+ media?: MediaReturnType[];
}) {
// some users ingest stringified json nested in json, parse it
const [isCopied, setIsCopied] = useState(false);
@@ -30,7 +33,7 @@ export function JSONView(props: {
const collapseStringsAfterLength =
props.collapseStringsAfterLength === null
? 100_000_000 // if null, show all (100M chars)
- : props.collapseStringsAfterLength ?? 500;
+ : (props.collapseStringsAfterLength ?? 500);
const handleCopy = () => {
setIsCopied(true);
@@ -115,6 +118,22 @@ export function JSONView(props: {
/>
)}
</div>
+ {props.media && props.media.length > 0 && (
+ <>
+ <div className="mx-3 border-t px-2 py-1 text-xs text-muted-foreground">
+ Media
+ </div>
+ <div className="flex flex-wrap gap-2 p-4 pt-1">
+ {props.media.map((m) => (
+ <LangfuseMediaView
+ mediaAPIReturnValue={m}
+ asFileIcon={true}
+ key={m.mediaId}
+ />
+ ))}
+ </div>
+ </>
+ )}
</div>
);
}
@@ -138,7 +157,7 @@ export function CodeView(props: {
const handleShowAll = () => setCollapsed(!isCollapsed);
return (
- <div className={cn("max-w-full rounded-md border ", props.className)}>
+ <div className={cn("max-w-full rounded-md border", props.className)}>
{props.title ? (
<div className="border-b px-3 py-1 text-xs font-medium">
{props.title}
@@ -210,7 +229,7 @@ export const IOTableCell = ({
<JSONView
json={stringifyJsonNode(data)}
className={cn(
- "h-full w-full self-stretch overflow-y-auto rounded-sm ",
+ "h-full w-full self-stretch overflow-y-auto rounded-sm",
className,
)}
codeClassName="py-1 px-2"
diff --git a/web/src/components/ui/LangfuseMediaView.tsx b/web/src/components/ui/LangfuseMediaView.tsx
new file mode 100644
index 0000000000..22c5ee27ab
--- /dev/null
+++ b/web/src/components/ui/LangfuseMediaView.tsx
@@ -0,0 +1,163 @@
+import { api } from "@/src/utils/api";
+
+import { ImageOff } from "lucide-react";
+import {
+ MediaReferenceStringSchema,
+ type ParsedMediaReferenceType,
+} from "@/src/components/schemas/ChatMlSchema";
+import { ResizableImage } from "@/src/components/ui/resizable-image";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import {
+ MediaContentType,
+ type MediaReturnType,
+} from "@/src/features/media/validation";
+import { FileIcon, ImageIcon, SpeakerLoudIcon } from "@radix-ui/react-icons";
+
+export const LangfuseMediaView = ({
+ mediaReferenceString,
+ mediaAPIReturnValue,
+ asFileIcon = false,
+}: {
+ mediaReferenceString?: string | ParsedMediaReferenceType;
+ mediaAPIReturnValue?: MediaReturnType;
+ asFileIcon?: boolean;
+}) => {
+ let mediaData: { id: string; type: MediaContentType } | null = null;
+
+ const projectId = useProjectIdFromURL();
+
+ if (mediaReferenceString && typeof mediaReferenceString === "string") {
+ const { success, data: parsedTag } =
+ MediaReferenceStringSchema.safeParse(mediaReferenceString);
+ if (success)
+ mediaData = {
+ id: parsedTag.id,
+ type: parsedTag.type as MediaContentType,
+ };
+ } else if (mediaReferenceString && typeof mediaReferenceString !== "string") {
+ mediaData = {
+ id: mediaReferenceString.id,
+ type: mediaReferenceString.type as MediaContentType,
+ };
+ } else if (mediaAPIReturnValue) {
+ mediaData = {
+ id: mediaAPIReturnValue.mediaId,
+ type: mediaAPIReturnValue.contentType,
+ };
+ }
+
+ if (!mediaData)
+ return (
+ <div className="flex items-center gap-2">
+ <span title="Invalid Langfuse Media Tag">
+ <ImageOff className="h-4 w-4" />
+ </span>
+ <span className="truncate text-sm">Invalid Langfuse Media Tag</span>
+ </div>
+ );
+
+ const { data } = api.media.getById.useQuery(
+ {
+ mediaId: mediaData.id,
+ projectId: projectId as string,
+ },
+ {
+ enabled: Boolean(projectId),
+ refetchOnWindowFocus: false,
+ refetchOnMount: false,
+ refetchOnReconnect: false,
+ staleTime: 55 * 60 * 1000, // 55 minutes, s3 links expire after 1 hour
+ },
+ );
+
+ const mediaUrl = data?.url;
+
+ if (!mediaUrl) return null;
+
+ if (asFileIcon) {
+ return <FileViewer src={mediaUrl} contentType={mediaData.type} />;
+ }
+
+ switch (mediaData.type) {
+ case MediaContentType.JPEG:
+ case MediaContentType.PNG:
+ case MediaContentType.WEBP:
+ return (
+ <div>
+ <ResizableImage
+ src={mediaUrl}
+ isDefaultVisible={true}
+ shouldValidateImageSource={false}
+ />
+ </div>
+ );
+ case MediaContentType.MP3:
+ case MediaContentType.MP3_LEGACY:
+ case MediaContentType.WAV:
+ return <AudioPlayer src={mediaUrl} />;
+
+ case MediaContentType.PDF:
+ return <FileViewer src={mediaUrl} contentType={mediaData.type} />;
+
+ case MediaContentType.TXT:
+ return <FileViewer src={mediaUrl} contentType={mediaData.type} />;
+
+ default:
+ return null;
+ }
+};
+
+function FileViewer({
+ src,
+ contentType,
+}: {
+ src?: string;
+ contentType: MediaContentType;
+}) {
+ if (!src) return null;
+
+ const fileName = src.split("/").pop()?.split("?")[0] || "";
+ const fileType = contentType.split("/")[0];
+ const fileExtension = contentType.split("/")[1].toUpperCase();
+
+ const openInNewTab = () => {
+ window.open(src, "_blank", "noopener,noreferrer");
+ };
+
+ return (
+ <button
+ onClick={openInNewTab}
+ aria-label={`Open ${fileName} in new tab`}
+ title={fileName}
+ className="group relative flex h-24 w-24 flex-col items-center justify-center gap-2 rounded-md border bg-gradient-to-br from-accent-light-green/30 to-muted px-2 transition-colors hover:from-accent-light-green/40 hover:to-muted/90 dark:from-accent-dark-green/20 dark:to-muted dark:hover:from-accent-dark-green/30"
+ >
+ <div className="flex flex-col items-center gap-2">
+ {fileType === "image" ? (
+ <ImageIcon className="h-5 w-5 transition-transform group-hover:scale-110" />
+ ) : fileType === "audio" ? (
+ <SpeakerLoudIcon className="h-5 w-5 transition-transform group-hover:scale-110" />
+ ) : (
+ <FileIcon className="h-5 w-5 transition-transform group-hover:scale-110" />
+ )}
+
+ <div className="flex flex-col items-center gap-1">
+ <span className="text-sm font-medium">{fileExtension}</span>
+ <span className="text-xs text-muted-foreground">
+ {fileName.length > 5 ? `${fileName.slice(0, 5)}...` : fileName}
+ </span>
+ </div>
+ </div>
+ </button>
+ );
+}
+
+function AudioPlayer({ src }: { src?: string }) {
+ if (!src) return null;
+
+ return (
+ <audio controls className="w-full" preload="metadata">
+ <source src={src} />
+ Your browser does not support the audio element.
+ </audio>
+ );
+}
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index fbaff73ef6..e7d231cfb1 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -23,11 +23,14 @@ import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";
import { type ExtraProps as ReactMarkdownExtraProps } from "react-markdown";
import {
OpenAIUrlImageUrl,
+ MediaReferenceStringSchema,
type OpenAIContentParts,
type OpenAIContentSchema,
+ type OpenAIOutputAudioType,
} from "@/src/components/schemas/ChatMlSchema";
import { type z } from "zod";
import { ResizableImage } from "@/src/components/ui/resizable-image";
+import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
type ReactMarkdownNode = ReactMarkdownExtraProps["node"];
type ReactMarkdownNodeChildren = Exclude<
@@ -171,7 +174,7 @@ function MarkdownRenderer({
);
},
img({ src, alt }) {
- return <ResizableImage src={src} alt={alt} />;
+ return src ? <ResizableImage src={src} alt={alt} /> : null;
},
hr() {
return <hr className="my-4" />;
@@ -209,14 +212,16 @@ function MarkdownRenderer({
);
}
const parseOpenAIContentParts = (
- content: z.infer<typeof OpenAIContentParts>,
+ content: z.infer<typeof OpenAIContentParts> | null,
): string => {
- return content
+ return (content ?? [])
.map((item) => {
if (item.type === "text") {
return item.text;
- } else {
+ } else if (item.type === "image_url") {
return `![image](${item.image_url.url})`;
+ } else if (item.type === "input_audio") {
+ return `![audio](${item.input_audio.data})`;
}
})
.join("\n");
@@ -227,11 +232,13 @@ export function MarkdownView({
title,
className,
customCodeHeaderClassName,
+ audio,
}: {
markdown: string | z.infer<typeof OpenAIContentSchema>;
title?: string;
className?: string;
customCodeHeaderClassName?: string;
+ audio?: OpenAIOutputAudioType;
}) {
const [isCopied, setIsCopied] = useState(false);
const capture = usePostHogClientCapture();
@@ -307,7 +314,7 @@ export function MarkdownView({
/>
) : (
// content parts (multi-modal)
- markdown.map((content, index) =>
+ (markdown ?? []).map((content, index) =>
content.type === "text" ? (
<MarkdownRenderer
key={index}
@@ -316,22 +323,46 @@ export function MarkdownView({
className={className}
customCodeHeaderClassName={customCodeHeaderClassName}
/>
- ) : OpenAIUrlImageUrl.safeParse(content.image_url.url).success ? (
- <div key={index}>
- <ResizableImage src={content.image_url.url} />
- </div>
- ) : (
- <div className="grid grid-cols-[auto,1fr] items-center gap-2">
- <span title="No Base64 image support yet" className="h-4 w-4">
- <ImageOff className="h-4 w-4" />
- </span>
- <span className="truncate text-sm">
- {content.image_url.url}
- </span>
- </div>
- ),
+ ) : content.type === "image_url" ? (
+ OpenAIUrlImageUrl.safeParse(content.image_url.url).success ? (
+ <div key={index}>
+ <ResizableImage src={content.image_url.url.toString()} />
+ </div>
+ ) : MediaReferenceStringSchema.safeParse(content.image_url.url)
+ .success ? (
+ <LangfuseMediaView
+ mediaReferenceString={content.image_url.url}
+ />
+ ) : (
+ <div className="grid grid-cols-[auto,1fr] items-center gap-2">
+ <span title="<Base64 data URI>" className="h-4 w-4">
+ <ImageOff className="h-4 w-4" />
+ </span>
+ <span className="truncate text-sm">
+ {content.image_url.url.toString()}
+ </span>
+ </div>
+ )
+ ) : content.type === "input_audio" ? (
+ <LangfuseMediaView
+ mediaReferenceString={content.input_audio.data}
+ />
+ ) : null,
)
)}
+ {audio ? (
+ <>
+ <MarkdownRenderer
+ markdown={audio.transcript ? "[Audio] \n" + audio.transcript : ""}
+ theme={theme}
+ className={className}
+ customCodeHeaderClassName={customCodeHeaderClassName}
+ />
+ <LangfuseMediaView
+ mediaReferenceString={audio.data.referenceString}
+ />
+ </>
+ ) : null}
</div>
</div>
);
diff --git a/web/src/components/ui/resizable-image.tsx b/web/src/components/ui/resizable-image.tsx
index c577969c04..a156e1f26e 100644
--- a/web/src/components/ui/resizable-image.tsx
+++ b/web/src/components/ui/resizable-image.tsx
@@ -10,7 +10,6 @@ import {
Minimize2,
} from "lucide-react";
import { api } from "@/src/utils/api";
-import { isPresent } from "@langfuse/shared";
import { Skeleton } from "@/src/components/ui/skeleton";
import { captureException } from "@sentry/nextjs";
import { useSession } from "next-auth/react";
@@ -29,7 +28,7 @@ const customLoader = ({
width: number;
quality?: number;
}) => {
- return `${src}?w=${width}&q=${quality || 75}`;
+ return src + (width && quality ? `?w=${width}&q=${quality || 75}` : "");
};
const ImageErrorDisplay = ({
@@ -52,19 +51,24 @@ const ImageErrorDisplay = ({
export const ResizableImage = ({
src,
alt,
+ isDefaultVisible = false,
+ shouldValidateImageSource = true,
}: {
- src?: string;
+ src: string;
alt?: string;
+ isDefaultVisible?: boolean;
+ shouldValidateImageSource?: boolean;
}) => {
const [isZoomedIn, setIsZoomedIn] = useState(true);
const [hasFetchError, setHasFetchError] = useState(false);
- const [isImageVisible, setIsImageVisible] = useState(false);
+ const [isImageVisible, setIsImageVisible] = useState(isDefaultVisible);
const session = useSession();
-
- if (!isPresent(src)) return null;
-
const isValidImage = api.utilities.validateImgUrl.useQuery(src, {
- enabled: session.status === "authenticated" && isImageVisible,
+ enabled:
+ session.status === "authenticated" &&
+ isImageVisible &&
+ shouldValidateImageSource,
+ initialData: { isValid: true },
});
if (session.status !== "authenticated") {
diff --git a/web/src/features/media/validation.ts b/web/src/features/media/validation.ts
index 8b3f24b951..c3a14fe85e 100644
--- a/web/src/features/media/validation.ts
+++ b/web/src/features/media/validation.ts
@@ -6,6 +6,10 @@ export enum MediaEnabledFields {
Metadata = "metadata",
}
+/*
+ When adding new media content types, also update the supported content types in the server definition
+ in fern/apis/server/definition/media.yml and reflect the changes in the SDKs.
+ */
export enum MediaContentType {
PNG = "image/png",
JPEG = "image/jpeg",
@@ -90,3 +94,14 @@ export const GetMediaResponseSchema = z.object({
});
export type GetMediaResponse = z.infer<typeof GetMediaResponseSchema>;
+
+export const MediaReturnSchema = z.object({
+ mediaId: z.string(),
+ contentType: z.nativeEnum(MediaContentType),
+ contentLength: z.coerce.number(),
+ url: z.string(),
+ urlExpiry: z.string(),
+ field: z.nativeEnum(MediaEnabledFields),
+});
+
+export type MediaReturnType = z.infer<typeof MediaReturnSchema>;
diff --git a/web/src/pages/api/public/media/[mediaId].ts b/web/src/pages/api/public/media/[mediaId].ts
index 68d211a217..905808bea9 100644
--- a/web/src/pages/api/public/media/[mediaId].ts
+++ b/web/src/pages/api/public/media/[mediaId].ts
@@ -53,12 +53,15 @@ export default withMiddlewares({
false,
);
+ const { contentType, contentLength, uploadedAt } = media;
+
return {
mediaId,
- contentType: media.contentType,
- contentLength: Number(media.contentLength),
+ contentType,
+ contentLength: Number(contentLength),
url,
urlExpiry,
+ uploadedAt,
};
},
}),
diff --git a/web/src/pages/api/public/media/index.ts b/web/src/pages/api/public/media/index.ts
index 5894b36ab8..d83428c29b 100644
--- a/web/src/pages/api/public/media/index.ts
+++ b/web/src/pages/api/public/media/index.ts
@@ -14,6 +14,7 @@ import {
ForbiddenError,
InternalServerError,
InvalidRequestError,
+ Prisma,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
@@ -41,177 +42,193 @@ export default withMiddlewares({
`File size must be less than ${env.LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH} bytes`,
);
- const existingMedia = await prisma.media.findUnique({
- where: {
- projectId_sha256Hash: {
- projectId,
- sha256Hash,
- },
- },
- });
-
- if (
- existingMedia &&
- existingMedia.uploadHttpStatus === 200 &&
- existingMedia.contentType === contentType
- ) {
- return await prisma.$transaction<{
- mediaId: string;
- uploadUrl: null;
- }>(async (tx) => {
- if (observationId) {
- await tx.observationMedia.upsert({
- where: {
- projectId_traceId_observationId_mediaId_field: {
- projectId,
- traceId,
- observationId,
- mediaId: existingMedia.id,
- field,
+ // Retry up to 3 times to avoid race conditions for concurrent media uploads
+ // Multiple observations can reference the same media, so we need to make sure no deadlock occurs
+ const MAX_RETRIES = 3;
+ let retries = 0;
+
+ while (retries < MAX_RETRIES) {
+ try {
+ return await prisma.$transaction<{
+ mediaId: string;
+ uploadUrl: string | null;
+ }>(
+ async (tx) => {
+ const existingMedia = await prisma.media.findUnique({
+ where: {
+ projectId_sha256Hash: {
+ projectId,
+ sha256Hash,
+ },
},
- },
- update: {},
- create: {
- projectId,
- traceId,
- observationId,
- mediaId: existingMedia.id,
- field,
- },
- });
- } else {
- await tx.traceMedia.upsert({
- where: {
- projectId_traceId_mediaId_field: {
- projectId,
- traceId,
+ });
+
+ if (
+ existingMedia &&
+ existingMedia.uploadHttpStatus === 200 &&
+ existingMedia.contentType === contentType
+ ) {
+ if (observationId) {
+ await tx.observationMedia.upsert({
+ where: {
+ projectId_traceId_observationId_mediaId_field: {
+ projectId,
+ traceId,
+ observationId,
+ mediaId: existingMedia.id,
+ field,
+ },
+ },
+ update: {},
+ create: {
+ projectId,
+ traceId,
+ observationId,
+ mediaId: existingMedia.id,
+ field,
+ },
+ });
+ } else {
+ await tx.traceMedia.upsert({
+ where: {
+ projectId_traceId_mediaId_field: {
+ projectId,
+ traceId,
+ mediaId: existingMedia.id,
+ field,
+ },
+ },
+ update: {},
+ create: {
+ projectId,
+ traceId,
+ field,
+ mediaId: existingMedia.id,
+ },
+ });
+ }
+
+ return {
mediaId: existingMedia.id,
- field,
- },
- },
- update: {},
- create: {
+ uploadUrl: null,
+ };
+ }
+
+ const mediaId = existingMedia?.id ?? randomUUID();
+
+ if (
+ !(
+ env.LANGFUSE_S3_MEDIA_UPLOAD_ENABLED &&
+ 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,
- traceId,
- field,
- mediaId: existingMedia.id,
- },
- });
- }
-
- return {
- mediaId: existingMedia.id,
- uploadUrl: null,
- };
- });
- }
- const mediaId = existingMedia?.id ?? randomUUID();
-
- if (
- !(
- env.LANGFUSE_S3_MEDIA_UPLOAD_ENABLED &&
- 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,
- });
-
- return await prisma.$transaction<{
- mediaId: string;
- uploadUrl: string;
- }>(async (tx) => {
- if (!env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET)
- throw new InternalServerError(
- "Media upload to bucket not configured",
- );
+ mediaId,
+ contentType,
+ });
- await Promise.all([
- tx.media.upsert({
- where: {
- projectId_sha256Hash: {
- projectId,
+ const uploadUrl = await s3Client.getSignedUploadUrl({
+ path: bucketPath,
+ ttlSeconds: 60 * 60, // 1 hour
sha256Hash,
- },
- },
- update: {
- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
- bucketPath,
- contentType,
- contentLength,
- },
- create: {
- id: mediaId,
- projectId,
- sha256Hash,
- bucketPath,
- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
- contentType,
- contentLength,
- },
- }),
- observationId
- ? tx.observationMedia.upsert({
- where: {
- projectId_traceId_observationId_mediaId_field: {
- projectId,
- traceId,
- observationId,
- mediaId,
- field,
+ contentType,
+ contentLength,
+ });
+
+ await Promise.all([
+ tx.media.upsert({
+ where: {
+ projectId_sha256Hash: {
+ projectId,
+ sha256Hash,
+ },
},
- },
- update: {},
- create: {
- projectId,
- traceId,
- observationId,
- mediaId,
- field,
- },
- })
- : tx.traceMedia.upsert({
- where: {
- projectId_traceId_mediaId_field: {
+ update: {
+ bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ bucketPath,
+ contentType,
+ contentLength,
+ },
+ create: {
+ id: mediaId,
projectId,
- traceId,
- mediaId,
- field,
+ sha256Hash,
+ bucketPath,
+ bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ contentType,
+ contentLength,
},
- },
- update: {},
- create: {
- projectId,
- traceId,
- field,
- mediaId,
- },
- }),
- ]);
-
- return {
- mediaId,
- uploadUrl,
- };
- });
+ }),
+ observationId
+ ? tx.observationMedia.upsert({
+ where: {
+ projectId_traceId_observationId_mediaId_field: {
+ projectId,
+ traceId,
+ observationId,
+ mediaId,
+ field,
+ },
+ },
+ update: {},
+ create: {
+ projectId,
+ traceId,
+ observationId,
+ mediaId,
+ field,
+ },
+ })
+ : tx.traceMedia.upsert({
+ where: {
+ projectId_traceId_mediaId_field: {
+ projectId,
+ traceId,
+ mediaId,
+ field,
+ },
+ },
+ update: {},
+ create: {
+ projectId,
+ traceId,
+ field,
+ mediaId,
+ },
+ }),
+ ]);
+
+ return {
+ mediaId,
+ uploadUrl,
+ };
+ },
+ { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
+ );
+ } catch (error) {
+ if (
+ // See https://www.prisma.io/docs/orm/prisma-client/queries/transactions#transaction-timing-issues
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2034"
+ ) {
+ retries++;
+ continue;
+ }
+
+ throw error;
+ }
+ }
+
+ throw new InternalServerError("Failed to get media upload URL");
},
}),
});
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 016917d464..8ea984c033 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -26,6 +26,7 @@ import { uiCustomizationRouter } from "@/src/ee/features/ui-customization/uiCust
import { commentsRouter } from "@/src/server/api/routers/comments";
import { queueRouter } from "@/src/ee/features/annotation-queues/server/annotationQueues";
import { queueItemRouter } from "@/src/ee/features/annotation-queues/server/annotationQueueItems";
+import { mediaRouter } from "@/src/server/api/routers/media";
/**
* This is the primary router for your server.
@@ -60,6 +61,7 @@ export const appRouter = createTRPCRouter({
utilities: utilsRouter,
uiCustomization: uiCustomizationRouter,
comments: commentsRouter,
+ media: mediaRouter,
});
// export type definition of API
diff --git a/web/src/server/api/routers/media.ts b/web/src/server/api/routers/media.ts
new file mode 100644
index 0000000000..2e3f5285e8
--- /dev/null
+++ b/web/src/server/api/routers/media.ts
@@ -0,0 +1,195 @@
+import { z } from "zod";
+
+import { env } from "@/src/env.mjs";
+import { getMediaStorageServiceClient } from "@/src/features/media/server/getMediaStorageClient";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { logger } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+import {
+ type MediaContentType,
+ type MediaReturnType,
+ type MediaEnabledFields,
+} from "@/src/features/media/validation";
+
+export const mediaRouter = createTRPCRouter({
+ getById: protectedProjectProcedure
+ .input(z.object({ mediaId: z.string(), projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ try {
+ const { projectId, mediaId } = input;
+
+ const media = await ctx.prisma.media.findFirst({
+ where: {
+ projectId,
+ id: mediaId,
+ },
+ });
+
+ if (!media)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Media asset not found",
+ });
+ if (!media.uploadHttpStatus)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Media not yet uploaded",
+ });
+ if (media.uploadHttpStatus !== 200)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: `Media upload failed`,
+ });
+
+ 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,
+ );
+
+ return {
+ mediaId,
+ contentType: media.contentType,
+ contentLength: Number(media.contentLength),
+ url,
+ urlExpiry,
+ };
+ } catch (e) {
+ logger.error(e);
+ if (e instanceof TRPCError) {
+ throw e;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching media failed.",
+ });
+ }
+ }),
+ getByTraceOrObservationId: protectedProjectProcedure
+ .input(
+ z.object({
+ traceId: z.string(),
+ observationId: z.string().nullish(),
+ projectId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ const { projectId, traceId } = input;
+
+ let media: {
+ id: string;
+ field: MediaEnabledFields;
+ bucket_name: string;
+ bucket_path: string;
+ content_type: string;
+ content_length: bigint;
+ }[] = [];
+
+ if (!input.observationId) {
+ // Get all media on the trace IO. This is NOT all media on the observations belonging to the trace.
+ media = await ctx.prisma.$queryRaw<
+ {
+ id: string;
+ field: MediaEnabledFields;
+ bucket_name: string;
+ bucket_path: string;
+ content_type: string;
+ content_length: bigint;
+ }[]
+ >`
+ SELECT
+ tm.field,
+ m.id,
+ m.bucket_name,
+ m.bucket_path,
+ m.content_type,
+ m.content_length
+ FROM
+ trace_media tm
+ LEFT JOIN media m ON tm.media_id = m.id
+ WHERE
+ tm.project_id = ${projectId}
+ AND tm.trace_id = ${traceId}
+ `;
+ } else {
+ media = await ctx.prisma.$queryRaw<
+ {
+ id: string;
+ field: MediaEnabledFields;
+ bucket_name: string;
+ bucket_path: string;
+ content_type: string;
+ content_length: bigint;
+ }[]
+ >`
+ SELECT
+ om.field,
+ m.id,
+ m.bucket_name,
+ m.bucket_path,
+ m.content_type,
+ m.content_length
+ FROM
+ observation_media om
+ LEFT JOIN media m ON om.media_id = m.id
+ WHERE
+ om.project_id = ${projectId}
+ AND om.trace_id = ${traceId}
+ AND om.observation_id = ${input.observationId}
+ `;
+ }
+
+ if (!media.length) {
+ return [];
+ }
+
+ const mediaStorageClient = getMediaStorageServiceClient(
+ media[0].bucket_name,
+ );
+ const ttlSeconds = env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS;
+ const urlExpiry = new Date(
+ Date.now() + ttlSeconds * 1000,
+ ).toISOString();
+
+ // Use Promise.all as better to fail all media requests than one of them only
+ return await Promise.all(
+ media.map<Promise<MediaReturnType>>(async (m) => {
+ const url = await mediaStorageClient.getSignedUrl(
+ m.bucket_path,
+ ttlSeconds,
+ false,
+ );
+ return {
+ mediaId: m.id,
+ contentType: m.content_type as MediaContentType,
+ contentLength: Number(m.content_length),
+ field: m.field,
+ url,
+ urlExpiry,
+ };
+ }),
+ );
+ } catch (e) {
+ logger.error(e);
+ if (e instanceof TRPCError) {
+ throw e;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Fetching media failed.",
+ });
+ }
+ }),
+});