🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ui): support image rendering in markdown view when image url provided (#2636)
marliessophiee93c06c938ec
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex 47e7ec5053..c0998971c4 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -729,7 +729,7 @@ function createObjects(],},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\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.",+ "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\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.",model: model,internalModel: model,modelParameters: {diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsxindex aeaab91237..02162767dd 100644--- a/web/src/components/ui/MarkdownViewer.tsx+++ b/web/src/components/ui/MarkdownViewer.tsx@@ -9,16 +9,20 @@ import {Children,createElement,} from "react";-import ReactMarkdown, { type Options } from "react-markdown";+import ReactMarkdown, { type Components, 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 } from "lucide-react";+import { Check, Copy, Maximize2, Minimize2 } from "lucide-react";+import { api } from "@/src/utils/api";+import { isPresent } from "@/src/utils/typeChecks";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";// ReactMarkdown does not render raw HTML by default for security reasons, to prevent XSS (Cross-Site Scripting) attacks.@@ -34,6 +38,70 @@ const isChecklist = (children: ReactNode) =>Array.isArray(children) &&children.some((child: any) => child?.props?.className === "task-list-item");+// Implemented customLoader as we cannot whitelist user provided image domains.+// Security risks are taken care of by a validation in api.public.validateImgUrl.+// Do not use this customLoader in production if you are not using the above mentioned security measures.+const customLoader = ({ src }: { src: string }) => {+ return src;+};++const MarkdownImage: Components["img"] = ({ src, alt }) => {+ const [isZoomedIn, setIsZoomedIn] = useState(true);++ if (!isPresent(src)) return null;++ const isValidImage = api.public.validateImgUrl.useQuery(src);+ 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>+ );+ }++ if (isValidImage.data?.isValid) {+ return (+ <div>+ <div+ className={cn(+ "group relative w-full overflow-hidden rounded border",+ isZoomedIn ? "h-1/2 w-1/2" : "h-full w-full",+ )}+ >+ <Image+ loader={customLoader}+ src={src}+ alt={alt ?? `Markdown Image-${Math.random()}`}+ loading="lazy"+ width={0}+ height={0}+ className="h-full w-full object-contain"+ />+ <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 (+ <Link href={src} className="underline" target="_blank">+ {src}+ </Link>+ );+};+const isTextElement = (child: ReactNode): child is ReactElement =>isValidElement(child) &&typeof child.type !== "string" &&@@ -208,13 +276,7 @@ export function MarkdownView({</blockquote>);},- img({ src }) {- return (- <Link href={src ?? ""} className="underline" target="_blank">- {src ?? ""}- </Link>- );- },+ img: MarkdownImage,hr() {return <hr className="my-4" />;},diff --git a/web/src/server/api/routers/public.ts b/web/src/server/api/routers/public.tsindex 5d9f3dd5e3..2500d558e9 100644--- a/web/src/server/api/routers/public.ts+++ b/web/src/server/api/routers/public.ts@@ -46,6 +46,38 @@ const ReleaseApiRes = z.array(}),);+const isValidURL = (urlString: string): boolean => {+ try {+ const url = new URL(urlString);+ return url.protocol === "https:";+ } catch (error) {+ console.log(error);+ return false;+ }+};++const isValidImageUrl = async (url: string): Promise<boolean> => {+ try {+ const response = await fetch(url, { method: "HEAD" });+ if (!response.ok) {+ return false;+ }++ 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) {+ console.log(error);+ return false;+ }+};+export const publicRouter = createTRPCRouter({checkUpdate: publicProcedure.query(async () => {// Skip update check on Langfuse Cloud@@ -91,4 +123,14 @@ export const publicRouter = createTRPCRouter({url: langfuseRelease.url,};}),+ validateImgUrl: publicProcedure+ .input(z.string().url())+ .query(async ({ input: url }) => {+ if (!isValidURL(url)) {+ return { isValid: false };+ }++ const isValidImage = await isValidImageUrl(url);+ return { isValid: isValidImage };+ }),});