Skip to content

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

feat(ui): support OpenAI's image content part format via markdown on trace/observation preview (#2984)

marliessophie5d81505d8465
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index 8485f40c7e..4192536492 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -832,6 +832,8 @@ function createObjects(
)
];
+ const { input, output } = getGenerationInputOutput();
+
const generation = {
type: ObservationType.GENERATION,
id: `generation-${v4()}`,
@@ -843,35 +845,8 @@ function createObjects(
name: `generation-${i}-${j}-${k}`,
projectId: trace.projectId,
promptId: promptId,
- input:
- Math.random() > 0.5
- ? [
- {
- role: "system",
- content: "Be a helpful assistant",
- },
- {
- role: "user",
- content: "How can i create a *React* component?",
- },
- ]
- : {
- input: "How can i create a React component?",
- retrievedDocuments: [
- {
- title: "How to create a React component",
- url: "https://www.google.com",
- description: "A guide to creating React components",
- },
- {
- title: "React component creation",
- url: "https://www.google.com",
- description: "A guide to creating React components",
- },
- ],
- },
- output:
- "Creating a React component can be done in two ways: as a functional component or as a class component. Let's start with a basic example of both.\n\n**Image**\n\n![Languse Example Image](https://static.langfuse.com/langfuse-dev/langfuse-example-image.jpeg)\n\n1. **Functional Component**:\n\nA functional component is just a plain JavaScript function that accepts props as an argument, and returns a React element. Here's how you can create one:\n\n```javascript\nimport React from 'react';\nfunction Greeting(props) {\n return <h1>Hello, {props.name}</h1>;\n}\nexport default Greeting;\n```\n\nTo use this component in another file, you can do:\n\n```javascript\nimport Greeting from './Greeting';\nfunction App() {\n return (\n <div>\n <Greeting name=\"John\" />\n </div>\n );\n}\nexport default App;\n```\n\n2. **Class Component**:\n\nYou can also define components as classes in React. These have some additional features compared to functional components:\n\n```javascript\nimport React, { Component } from 'react';\nclass Greeting extends Component {\n render() {\n return <h1>Hello, {this.props.name}</h1>;\n }\n}\nexport default Greeting;\n```\n\nAnd here's how to use this component:\n\n```javascript\nimport Greeting from './Greeting';\nclass App extends Component {\n render() {\n return (\n <div>\n <Greeting name=\"John\" />\n </div>\n );\n }\n}\nexport default App;\n```\n\nWith the advent of hooks in React, functional components can do everything that class components can do and hence, the community has been favoring functional components over class components.\n\nRemember to import React at the top of your file whenever you're creating a component, because JSX transpiles to `React.createElement` calls under the hood.",
+ input,
+ output,
model: model,
internalModel: model,
modelParameters: {
@@ -1243,3 +1218,63 @@ async function generateConfigs(project: Project) {
return configNameAndId;
}
+function getGenerationInputOutput(): {
+ input: Prisma.InputJsonValue;
+ output: Prisma.InputJsonValue;
+} {
+ if (Math.random() > 0.9) {
+ const input = [
+ {
+ role: "user",
+ content: [
+ { text: "What’s depicted in this image?", type: "text" },
+ {
+ type: "image_url",
+ image_url: {
+ url: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
+ },
+ },
+ { text: "Describe the scene in detail.", type: "text" },
+ ],
+ },
+ ];
+
+ const output =
+ "The image depicts a serene landscape featuring a wooden pathway or boardwalk that winds through a lush green field. The field is filled with tall grass and surrounded by trees and shrubs. Above, the sky is bright with scattered clouds, suggesting a clear and pleasant day. The scene conveys a sense of tranquility and natural beauty.";
+
+ return { input, output };
+ }
+
+ const input =
+ Math.random() > 0.5
+ ? [
+ {
+ role: "system",
+ content: "Be a helpful assistant",
+ },
+ {
+ role: "user",
+ content: "How can i create a *React* component?",
+ },
+ ]
+ : {
+ input: "How can i create a React component?",
+ retrievedDocuments: [
+ {
+ title: "How to create a React component",
+ url: "https://www.google.com",
+ description: "A guide to creating React components",
+ },
+ {
+ title: "React component creation",
+ url: "https://www.google.com",
+ description: "A guide to creating React components",
+ },
+ ],
+ };
+
+ const output =
+ "Creating a React component can be done in two ways: as a functional component or as a class component. Let's start with a basic example of both.\n\n**Image**\n\n![Languse Example Image](https://static.langfuse.com/langfuse-dev/langfuse-example-image.jpeg)\n\n1. **Functional Component**:\n\nA functional component is just a plain JavaScript function that accepts props as an argument, and returns a React element. Here's how you can create one:\n\n```javascript\nimport React from 'react';\nfunction Greeting(props) {\n return <h1>Hello, {props.name}</h1>;\n}\nexport default Greeting;\n```\n\nTo use this component in another file, you can do:\n\n```javascript\nimport Greeting from './Greeting';\nfunction App() {\n return (\n <div>\n <Greeting name=\"John\" />\n </div>\n );\n}\nexport default App;\n```\n\n2. **Class Component**:\n\nYou can also define components as classes in React. These have some additional features compared to functional components:\n\n```javascript\nimport React, { Component } from 'react';\nclass Greeting extends Component {\n render() {\n return <h1>Hello, {this.props.name}</h1>;\n }\n}\nexport default Greeting;\n```\n\nAnd here's how to use this component:\n\n```javascript\nimport Greeting from './Greeting';\nclass App extends Component {\n render() {\n return (\n <div>\n <Greeting name=\"John\" />\n </div>\n );\n }\n}\nexport default App;\n```\n\nWith the advent of hooks in React, functional components can do everything that class components can do and hence, the community has been favoring functional components over class components.\n\nRemember to import React at the top of your file whenever you're creating a component, because JSX transpiles to `React.createElement` calls under the hood.";
+
+ return { input, output };
+}
diff --git a/web/src/components/schemas/ChatMlSchema.ts b/web/src/components/schemas/ChatMlSchema.ts
index bdbd6d071a..5875eeb3ca 100644
--- a/web/src/components/schemas/ChatMlSchema.ts
+++ b/web/src/components/schemas/ChatMlSchema.ts
@@ -1,11 +1,42 @@
import { z } from "zod";
+// OpenAI API Content Schema defined as per https://platform.openai.com/docs/api-reference/chat/create#chat-create-messages, 20.08.2024
+const OpenAITextContentPart = z.object({
+ type: z.literal("text"),
+ text: z.string(),
+});
+
+export const OpenAIUrlImageUrl = z.string().regex(/^https?:/);
+
+const OpenAIBase64ImageUrl = z
+ .string()
+ .regex(/^data:image\/(png|jpeg|jpg|gif|webp);base64,/);
+
+const OpenAIImageContentPart = z.object({
+ type: z.literal("image_url"),
+ image_url: z.object({
+ url: z.union([OpenAIUrlImageUrl, 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]
+ }),
+});
+
+export const OpenAIContentParts = z.array(
+ z.union([OpenAITextContentPart, OpenAIImageContentPart]),
+);
+
+export const OpenAIContentSchema = z.union([z.string(), OpenAIContentParts]);
+
export const ChatMlMessageSchema = z
.object({
role: z.string().optional(),
name: z.string().optional(),
content: z
- .union([z.record(z.any()), z.string(), z.array(z.any())])
+ .union([
+ z.record(z.any()),
+ z.string(),
+ z.array(z.any()),
+ OpenAIContentSchema,
+ ])
.nullish(),
additional_kwargs: z.record(z.any()).optional(),
})
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index f3d2bb3214..55de9cbecc 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -12,9 +12,18 @@ import { MarkdownSchema } from "@/src/components/schemas/MarkdownSchema";
import {
ChatMlArraySchema,
ChatMlMessageSchema,
+ OpenAIContentSchema,
} from "@/src/components/schemas/ChatMlSchema";
import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";
+const isSupportedMarkdownFormat = (
+ content: unknown,
+ contentValidation: z.SafeParseReturnType<
+ string,
+ z.infer<typeof OpenAIContentSchema>
+ >,
+): content is z.infer<typeof OpenAIContentSchema> => contentValidation.success;
+
// MarkdownOrJsonView will render markdown if `isMarkdownEnabled` (global context) is true and the content is valid markdown
// otherwise, if content is valid markdown will render JSON with switch to enable markdown globally
function MarkdownOrJsonView({
@@ -32,12 +41,20 @@ function MarkdownOrJsonView({
() => MarkdownSchema.safeParse(content),
[content],
);
+ const validatedOpenAIContent = useMemo(
+ () => OpenAIContentSchema.safeParse(content),
+ [content],
+ );
const { isMarkdownEnabled } = useMarkdownContext();
+ const canEnableMarkdown = isSupportedMarkdownFormat(
+ content,
+ validatedOpenAIContent,
+ );
- return validatedMarkdown.success && isMarkdownEnabled ? (
+ return isMarkdownEnabled && canEnableMarkdown ? (
<MarkdownView
- markdown={validatedMarkdown.data}
+ markdown={validatedMarkdown.data ?? content}
title={title}
className={className}
customCodeHeaderClassName={customCodeHeaderClassName}
@@ -45,7 +62,7 @@ function MarkdownOrJsonView({
) : (
<JSONView
json={content}
- canEnableMarkdown={validatedMarkdown.success}
+ canEnableMarkdown={canEnableMarkdown}
title={title}
className={className}
/>
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index 669f481631..7e5b199ac7 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -9,31 +9,25 @@ import {
Children,
createElement,
} from "react";
-import ReactMarkdown, { type Components, type Options } from "react-markdown";
+import ReactMarkdown, { type Options } from "react-markdown";
import Link from "next/link";
-import Image from "next/image";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { CodeBlock } from "@/src/components/ui/Codeblock";
import { useTheme } from "next-themes";
import { Button } from "@/src/components/ui/button";
-import {
- Check,
- Copy,
- Image as ImageIcon,
- ImageOff,
- Maximize2,
- Minimize2,
-} from "lucide-react";
-import { api } from "@/src/utils/api";
-import { isPresent } from "@langfuse/shared";
+import { Check, Copy, ImageOff } from "lucide-react";
import { BsMarkdown } from "react-icons/bs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { Skeleton } from "@/src/components/ui/skeleton";
import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";
-import { captureException } from "@sentry/nextjs";
-import { useSession } from "next-auth/react";
import { type ExtraProps as ReactMarkdownExtraProps } from "react-markdown";
+import {
+ OpenAIUrlImageUrl,
+ type OpenAIContentParts,
+ type OpenAIContentSchema,
+} from "@/src/components/schemas/ChatMlSchema";
+import { type z } from "zod";
+import { ResizableImage } from "@/src/components/ui/resizable-image";
type ReactMarkdownNode = ReactMarkdownExtraProps["node"];
type ReactMarkdownNodeChildren = Exclude<
@@ -50,147 +44,6 @@ const MemoizedReactMarkdown: FC<Options> = memo(
prevProps.className === nextProps.className,
);
-/**
- * Implemented customLoader as we cannot whitelist user provided image domains
- * Security risks are taken care of by a validation in api.utilities.validateImgUrl
- * Fetching image will fail if SSL/TLS certificate is invalid or expired, will be handled by onError
- * Do not use this customLoader in production if you are not using the above mentioned security measures */
-const customLoader = ({
- src,
- width,
- quality,
-}: {
- src: string;
- width: number;
- quality?: number;
-}) => {
- return `${src}?w=${width}&q=${quality || 75}`;
-};
-
-const ImageErrorDisplay = ({
- src,
- displayError,
-}: {
- src: string;
- displayError: string;
-}) => (
- <div className="flex flex-row items-center gap-2">
- <span title={displayError} className="h-4 w-4">
- <ImageOff className="h-4 w-4" />
- </span>
- <Link href={src} className="underline" target="_blank">
- {src}
- </Link>
- </div>
-);
-
-const MarkdownImage: Components["img"] = ({ src, alt }) => {
- const [isZoomedIn, setIsZoomedIn] = useState(true);
- const [hasFetchError, setHasFetchError] = useState(false);
- const [isImageVisible, setIsImageVisible] = useState(false);
- const session = useSession();
-
- if (!isPresent(src)) return null;
-
- const isValidImage = api.utilities.validateImgUrl.useQuery(src, {
- enabled: session.status === "authenticated",
- });
-
- if (session.status !== "authenticated") {
- return (
- <ImageErrorDisplay
- src={src}
- displayError="Images not rendered on public traces and observations"
- />
- );
- }
-
- if (isValidImage.isLoading) {
- return (
- <Skeleton className="h-8 w-1/2 items-center p-2 text-xs">
- <span className="opacity-80">Loading image...</span>
- </Skeleton>
- );
- }
-
- const displayError = `Cannot load image. ${src.includes("http") ? "Http images are not rendered in Langfuse for security reasons" : "Invalid image URL"}`;
-
- if (isValidImage.data?.isValid) {
- return (
- <div>
- {hasFetchError ? (
- <ImageErrorDisplay src={src} displayError={displayError} />
- ) : (
- <div
- className={cn(
- "group relative w-full overflow-hidden",
- isZoomedIn ? "h-1/2 w-1/2" : "h-full w-full",
- )}
- >
- {isImageVisible ? (
- <Image
- loader={customLoader}
- src={src}
- alt={alt ?? `Markdown Image-${Math.random()}`}
- loading="lazy"
- width={0}
- height={0}
- title={src}
- className="h-full w-full rounded border object-contain"
- onError={(error) => {
- setHasFetchError(true);
- captureException(error);
- }}
- />
- ) : (
- <div className="grid h-14 w-full grid-cols-[auto,1fr] items-center gap-2 rounded border border-dashed bg-muted/30 p-2 text-xs text-muted-foreground/60">
- <Button
- title="Render image"
- type="button"
- size="icon"
- variant="ghost"
- onClick={() => setIsImageVisible(!isImageVisible)}
- >
- <ImageIcon className="h-4 w-4" />
- </Button>
- <div className="flex items-center overflow-hidden">
- <Link
- href={src}
- title={src}
- className="overflow-hidden underline"
- target="_blank"
- >
- <div className="h-8 overflow-hidden overflow-ellipsis">
- {src}
- </div>
- </Link>
- </div>
- </div>
- )}
- {isImageVisible && (
- <Button
- type="button"
- className="absolute right-0 top-0 mr-1 mt-1 h-8 w-8 opacity-0 group-hover:!bg-accent/30 group-hover:opacity-100"
- variant="ghost"
- size="icon"
- onClick={() => setIsZoomedIn(!isZoomedIn)}
- >
- {isZoomedIn ? (
- <Maximize2 className="h-4 w-4"></Maximize2>
- ) : (
- <Minimize2 className="h-4 w-4"></Minimize2>
- )}
- </Button>
- )}
- </div>
- )}
- </div>
- );
- }
-
- return <ImageErrorDisplay src={src} displayError={displayError} />;
-};
-
const isTextElement = (child: ReactNode): child is ReactElement =>
isValidElement(child) &&
typeof child.type !== "string" &&
@@ -219,25 +72,179 @@ const isImageNode = (node?: ReactMarkdownNode): boolean =>
"tagName" in child && child.tagName === "img",
);
+function MarkdownRenderer({
+ markdown,
+ theme,
+ className,
+ customCodeHeaderClassName,
+}: {
+ markdown: string;
+ theme?: string;
+ className?: string;
+ customCodeHeaderClassName?: string;
+}) {
+ return (
+ <MemoizedReactMarkdown
+ className={cn("space-y-2 overflow-x-auto break-words text-sm", className)}
+ remarkPlugins={[remarkGfm, remarkMath]}
+ components={{
+ p({ children, node }) {
+ if (isImageNode(node)) {
+ return <>{children}</>;
+ }
+ return (
+ <p className="mb-2 whitespace-pre-wrap last:mb-0">{children}</p>
+ );
+ },
+ a({ children, href }) {
+ if (href)
+ return (
+ <Link href={href} className="underline" target="_blank">
+ {children}
+ </Link>
+ );
+ },
+ ul({ children }) {
+ if (isChecklist(children))
+ return <ul className="list-none">{children}</ul>;
+
+ return <ul className="list-outside list-disc pl-4">{children}</ul>;
+ },
+ ol({ children }) {
+ return <ol className="list-outside list-decimal pl-4">{children}</ol>;
+ },
+ li({ children }) {
+ return (
+ <li className="mb-1 list-item">
+ {transformListItemChildren(children)}
+ </li>
+ );
+ },
+ pre({ children }) {
+ return <pre className="rounded p-2">{children}</pre>;
+ },
+ h1({ children }) {
+ return <h1 className="text-2xl font-bold">{children}</h1>;
+ },
+ h2({ children }) {
+ return <h2 className="text-xl font-bold">{children}</h2>;
+ },
+ h3({ children }) {
+ return <h3 className="text-lg font-bold">{children}</h3>;
+ },
+ h4({ children }) {
+ return <h4 className="text-base font-bold">{children}</h4>;
+ },
+ h5({ children }) {
+ return <h5 className="text-sm font-bold">{children}</h5>;
+ },
+ h6({ children }) {
+ return <h6 className="text-xs font-bold">{children}</h6>;
+ },
+ code({ children, className }) {
+ const languageMatch = /language-(\w+)/.exec(className || "");
+ const language = languageMatch ? languageMatch[1] : "";
+ const codeContent = String(children).replace(/\n$/, "");
+ const isMultiLine = codeContent.includes("\n");
+
+ return language || isMultiLine ? (
+ // code block
+ <CodeBlock
+ key={Math.random()}
+ language={language}
+ value={codeContent}
+ theme={theme}
+ className={customCodeHeaderClassName}
+ />
+ ) : (
+ // inline code
+ <code className="rounded border bg-secondary px-0.5">
+ {codeContent}
+ </code>
+ );
+ },
+ blockquote({ children }) {
+ return (
+ <blockquote className="border-l-4 pl-4 italic">
+ {children}
+ </blockquote>
+ );
+ },
+ img({ src, alt }) {
+ return <ResizableImage src={src} alt={alt} />;
+ },
+ hr() {
+ return <hr className="my-4" />;
+ },
+ table({ children }) {
+ return (
+ <div className="overflow-x-auto rounded border text-xs">
+ <table className="min-w-full divide-y">{children}</table>
+ </div>
+ );
+ },
+ thead({ children }) {
+ return <thead>{children}</thead>;
+ },
+ tbody({ children }) {
+ return <tbody className="divide-y divide-border">{children}</tbody>;
+ },
+ tr({ children }) {
+ return <tr>{children}</tr>;
+ },
+ th({ children }) {
+ return (
+ <th className="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider">
+ {children}
+ </th>
+ );
+ },
+ td({ children }) {
+ return <td className="whitespace-nowrap px-4 py-2">{children}</td>;
+ },
+ }}
+ >
+ {markdown}
+ </MemoizedReactMarkdown>
+ );
+}
+const parseOpenAIContentParts = (
+ content: z.infer<typeof OpenAIContentParts>,
+): string => {
+ return content
+ .map((item) => {
+ if (item.type === "text") {
+ return item.text;
+ } else {
+ return `![image](${item.image_url.url})`;
+ }
+ })
+ .join("\n");
+};
+
export function MarkdownView({
markdown,
title,
className,
customCodeHeaderClassName,
}: {
- markdown: string;
+ markdown: string | z.infer<typeof OpenAIContentSchema>;
title?: string;
className?: string;
customCodeHeaderClassName?: string;
}) {
const [isCopied, setIsCopied] = useState(false);
- const { resolvedTheme: theme } = useTheme();
const capture = usePostHogClientCapture();
+ const { resolvedTheme: theme } = useTheme();
const { setIsMarkdownEnabled } = useMarkdownContext();
const handleCopy = () => {
setIsCopied(true);
- void navigator.clipboard.writeText(markdown);
+ const rawText =
+ typeof markdown === "string"
+ ? markdown
+ : parseOpenAIContentParts(markdown);
+ void navigator.clipboard.writeText(rawText);
setTimeout(() => setIsCopied(false), 1000);
};
@@ -288,132 +295,44 @@ export function MarkdownView({
</Button>
</div>
</div>
- ) : undefined}
- <MemoizedReactMarkdown
- className={cn(
- "space-y-4 overflow-x-auto break-words p-3 text-sm",
- className,
- )}
- remarkPlugins={[remarkGfm, remarkMath]}
- components={{
- p({ children, node }) {
- if (isImageNode(node)) {
- return <>{children}</>;
- }
- return (
- <p className="mb-2 whitespace-pre-wrap last:mb-0">{children}</p>
- );
- },
- a({ children, href }) {
- if (href)
- return (
- <Link href={href} className="underline" target="_blank">
- {children}
- </Link>
- );
- },
- ul({ children }) {
- if (isChecklist(children))
- return <ul className="list-none">{children}</ul>;
-
- return <ul className="list-outside list-disc pl-4">{children}</ul>;
- },
- ol({ children }) {
- return (
- <ol className="list-outside list-decimal pl-4">{children}</ol>
- );
- },
- li({ children }) {
- return (
- <li className="mb-1 list-item">
- {transformListItemChildren(children)}
- </li>
- );
- },
- pre({ children }) {
- return <pre className="rounded p-2">{children}</pre>;
- },
- h1({ children }) {
- return <h1 className="text-2xl font-bold">{children}</h1>;
- },
- h2({ children }) {
- return <h2 className="text-xl font-bold">{children}</h2>;
- },
- h3({ children }) {
- return <h3 className="text-lg font-bold">{children}</h3>;
- },
- h4({ children }) {
- return <h4 className="text-base font-bold">{children}</h4>;
- },
- h5({ children }) {
- return <h5 className="text-sm font-bold">{children}</h5>;
- },
- h6({ children }) {
- return <h6 className="text-xs font-bold">{children}</h6>;
- },
- code({ children, className }) {
- const languageMatch = /language-(\w+)/.exec(className || "");
- const language = languageMatch ? languageMatch[1] : "";
- const codeContent = String(children).replace(/\n$/, "");
- const isMultiLine = codeContent.includes("\n");
-
- return language || isMultiLine ? (
- // code block
- <CodeBlock
- key={Math.random()}
- language={language}
- value={codeContent}
+ ) : null}
+ <div className="grid grid-flow-row gap-2 p-3">
+ {typeof markdown === "string" ? (
+ // plain string
+ <MarkdownRenderer
+ markdown={markdown}
+ theme={theme}
+ className={className}
+ customCodeHeaderClassName={customCodeHeaderClassName}
+ />
+ ) : (
+ // content parts (multi-modal)
+ markdown.map((content, index) =>
+ content.type === "text" ? (
+ <MarkdownRenderer
+ key={index}
+ markdown={content.text}
theme={theme}
- className={customCodeHeaderClassName}
+ className={className}
+ customCodeHeaderClassName={customCodeHeaderClassName}
/>
+ ) : OpenAIUrlImageUrl.safeParse(content.image_url.url).success ? (
+ <div key={index}>
+ <ResizableImage src={content.image_url.url} />
+ </div>
) : (
- // inline code
- <code className="rounded border bg-secondary px-0.5">
- {codeContent}
- </code>
- );
- },
- blockquote({ children }) {
- return (
- <blockquote className="border-l-4 pl-4 italic">
- {children}
- </blockquote>
- );
- },
- img: MarkdownImage,
- hr() {
- return <hr className="my-4" />;
- },
- table({ children }) {
- return (
- <div className="overflow-x-auto rounded border text-xs">
- <table className="min-w-full divide-y">{children}</table>
+ <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>
- );
- },
- thead({ children }) {
- return <thead>{children}</thead>;
- },
- tbody({ children }) {
- return <tbody className="divide-y divide-border">{children}</tbody>;
- },
- tr({ children }) {
- return <tr>{children}</tr>;
- },
- th({ children }) {
- return (
- <th className="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider">
- {children}
- </th>
- );
- },
- td({ children }) {
- return <td className="whitespace-nowrap px-4 py-2">{children}</td>;
- },
- }}
- >
- {markdown}
- </MemoizedReactMarkdown>
+ ),
+ )
+ )}
+ </div>
</div>
);
}
diff --git a/web/src/components/ui/resizable-image.tsx b/web/src/components/ui/resizable-image.tsx
new file mode 100644
index 0000000000..c577969c04
--- /dev/null
+++ b/web/src/components/ui/resizable-image.tsx
@@ -0,0 +1,159 @@
+import { cn } from "@/src/utils/tailwind";
+import { useState } from "react";
+import Link from "next/link";
+import Image from "next/image";
+import { Button } from "@/src/components/ui/button";
+import {
+ Image as ImageIcon,
+ ImageOff,
+ Maximize2,
+ 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";
+
+/**
+ * Implemented customLoader as we cannot whitelist user provided image domains
+ * Security risks are taken care of by a validation in api.utilities.validateImgUrl
+ * Fetching image will fail if SSL/TLS certificate is invalid or expired, will be handled by onError
+ * Do not use this customLoader in production if you are not using the above mentioned security measures */
+const customLoader = ({
+ src,
+ width,
+ quality,
+}: {
+ src: string;
+ width: number;
+ quality?: number;
+}) => {
+ return `${src}?w=${width}&q=${quality || 75}`;
+};
+
+const ImageErrorDisplay = ({
+ src,
+ displayError,
+}: {
+ src: string;
+ displayError: string;
+}) => (
+ <div className="grid grid-cols-[auto,1fr] items-center gap-2">
+ <span title={displayError} className="h-4 w-4">
+ <ImageOff className="h-4 w-4" />
+ </span>
+ <Link href={src} className="truncate text-sm underline" target="_blank">
+ {src}
+ </Link>
+ </div>
+);
+
+export const ResizableImage = ({
+ src,
+ alt,
+}: {
+ src?: string;
+ alt?: string;
+}) => {
+ const [isZoomedIn, setIsZoomedIn] = useState(true);
+ const [hasFetchError, setHasFetchError] = useState(false);
+ const [isImageVisible, setIsImageVisible] = useState(false);
+ const session = useSession();
+
+ if (!isPresent(src)) return null;
+
+ const isValidImage = api.utilities.validateImgUrl.useQuery(src, {
+ enabled: session.status === "authenticated" && isImageVisible,
+ });
+
+ if (session.status !== "authenticated") {
+ return (
+ <ImageErrorDisplay
+ src={src}
+ displayError="Images not rendered on public traces and observations"
+ />
+ );
+ }
+
+ if (isValidImage.isLoading && isImageVisible) {
+ return (
+ <Skeleton className="h-8 w-1/2 items-center p-2 text-xs">
+ <span className="opacity-80">Loading image...</span>
+ </Skeleton>
+ );
+ }
+
+ const displayError = `Cannot load image. ${src.includes("http") ? "Http images are not rendered in Langfuse for security reasons" : "Invalid image URL"}`;
+
+ return (
+ <div>
+ {hasFetchError ? (
+ <ImageErrorDisplay src={src} displayError={displayError} />
+ ) : (
+ <div
+ className={cn(
+ "group relative w-full overflow-hidden",
+ isZoomedIn ? "h-1/2 w-1/2" : "h-full w-full",
+ )}
+ >
+ {isImageVisible && isValidImage.data?.isValid ? (
+ <>
+ <Image
+ loader={customLoader}
+ src={src}
+ alt={alt ?? `Markdown Image-${Math.random()}`}
+ loading="lazy"
+ width={0}
+ height={0}
+ title={src}
+ className="h-full w-full rounded border object-contain"
+ onError={(error) => {
+ setHasFetchError(true);
+ captureException(error);
+ }}
+ />
+ <Button
+ type="button"
+ className="absolute right-0 top-0 mr-1 mt-1 h-8 w-8 opacity-0 group-hover:!bg-accent/30 group-hover:opacity-100"
+ variant="ghost"
+ size="icon"
+ onClick={() => setIsZoomedIn(!isZoomedIn)}
+ >
+ {isZoomedIn ? (
+ <Maximize2 className="h-4 w-4"></Maximize2>
+ ) : (
+ <Minimize2 className="h-4 w-4"></Minimize2>
+ )}
+ </Button>
+ </>
+ ) : (
+ <div className="grid h-14 w-full grid-cols-[auto,1fr] items-center gap-2 rounded border border-dashed bg-muted/30 p-2 text-xs text-muted-foreground/60">
+ <Button
+ title="Render image"
+ type="button"
+ size="icon"
+ variant="ghost"
+ onClick={() => setIsImageVisible(!isImageVisible)}
+ >
+ <ImageIcon className="h-4 w-4" />
+ </Button>
+ <div className="flex items-center overflow-hidden">
+ <Link
+ href={src}
+ title={src}
+ className="overflow-hidden underline"
+ target="_blank"
+ >
+ <div className="h-8 overflow-hidden overflow-ellipsis">
+ {src}
+ </div>
+ </Link>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/server/api/routers/utilities.ts b/web/src/server/api/routers/utilities.ts
index bb288a3a6a..79c68c4a68 100644
--- a/web/src/server/api/routers/utilities.ts
+++ b/web/src/server/api/routers/utilities.ts
@@ -80,12 +80,6 @@ const isValidImageUrl = async (url: string): Promise<boolean> => {
}
const contentType = response.headers.get("content-type");
- const contentLength = response.headers.get("content-length");
-
- // ensure image is not larger than 1MB in size
- if (!contentLength || parseInt(contentLength, 10) > 1 * 1024 * 1024) {
- return false;
- }
return !!contentType && contentType.startsWith("image/");
} catch (error) {