Skip to content

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

chore(markdown): introduce type guards for markdown rendering (#6631)

marliessophied39b0214b8d1
diff --git a/web/src/components/schemas/ChatMlSchema.ts b/web/src/components/schemas/ChatMlSchema.ts
index 33b20b9215..c9f11e30a1 100644
--- a/web/src/components/schemas/ChatMlSchema.ts
+++ b/web/src/components/schemas/ChatMlSchema.ts
@@ -9,6 +9,7 @@ const OpenAITextContentPart = z.object({
]),
text: z.string(),
});
+export type OpenAITextContentPartType = z.infer<typeof OpenAITextContentPart>;
export const OpenAIUrlImageUrl = z.string().regex(/^https?:/);
@@ -75,6 +76,7 @@ const OpenAIImageContentPart = z.object({
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 type OpenAIImageContentPartType = z.infer<typeof OpenAIImageContentPart>;
const OpenAIInputAudioContentPart = z.object({
type: z.literal("input_audio"),
@@ -134,3 +136,16 @@ export type ChatMlMessageSchema = z.infer<typeof ChatMlMessageSchema>;
export const ChatMlArraySchema = z.array(ChatMlMessageSchema).min(1);
export type ChatMlArraySchema = z.infer<typeof ChatMlArraySchema>;
+
+// Typeguards to help with type inference in components
+export const isOpenAITextContentPart = (
+ content: any,
+): content is z.infer<typeof OpenAITextContentPart> => {
+ return OpenAITextContentPart.safeParse(content).success;
+};
+
+export const isOpenAIImageContentPart = (
+ content: any,
+): content is z.infer<typeof OpenAIImageContentPart> => {
+ return OpenAIImageContentPart.safeParse(content).success;
+};
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index ae45361fce..f67405ef75 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -26,6 +26,8 @@ import {
type OpenAIContentParts,
type OpenAIContentSchema,
type OpenAIOutputAudioType,
+ isOpenAITextContentPart,
+ isOpenAIImageContentPart,
} from "@/src/components/schemas/ChatMlSchema";
import { type z } from "zod";
import { ResizableImage } from "@/src/components/ui/resizable-image";
@@ -320,14 +322,14 @@ export function MarkdownView({
) : (
// content parts (multi-modal)
(markdown ?? []).map((content, index) =>
- content.type === "text" ? (
+ isOpenAITextContentPart(content) ? (
<MarkdownRenderer
key={index}
markdown={content.text}
theme={theme}
customCodeHeaderClassName={customCodeHeaderClassName}
/>
- ) : content.type === "image_url" ? (
+ ) : isOpenAIImageContentPart(content) ? (
OpenAIUrlImageUrl.safeParse(content.image_url.url).success ? (
<div key={index}>
<ResizableImage src={content.image_url.url.toString()} />