Skip to content

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

fix(prompts): parse chat prompts references correctly (#12421)

Nimarcb6a28a6da5b
diff --git a/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx b/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx
index f8b33b7c23..4e6b626f4b 100644
--- a/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx
+++ b/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx
@@ -32,7 +32,6 @@ export interface ChatMessageProps {
shouldRenderMarkdown: boolean;
currentView: ViewMode;
toolCallNumbers?: number[];
- projectIdForPromptButtons?: string;
isOutputMessage?: boolean;
}
@@ -50,7 +49,6 @@ export function ChatMessage({
shouldRenderMarkdown,
currentView,
toolCallNumbers,
- projectIdForPromptButtons,
isOutputMessage,
}: ChatMessageProps) {
const [showTableView, setShowTableView] = useState(false);
@@ -93,7 +91,6 @@ export function ChatMessage({
<PrettyJsonView
title="Placeholder"
json={message.name || "Unnamed placeholder"}
- projectIdForPromptButtons={projectIdForPromptButtons}
currentView={currentView}
/>
</div>
@@ -108,7 +105,6 @@ export function ChatMessage({
<PrettyJsonView
title={title || (isOutputMessage ? "Output" : "Input")}
json={message.json}
- projectIdForPromptButtons={projectIdForPromptButtons}
currentView={currentView}
/>
</div>
@@ -122,7 +118,6 @@ export function ChatMessage({
<PrettyJsonView
title={title}
json={message.json}
- projectIdForPromptButtons={projectIdForPromptButtons}
currentView="pretty"
controlButtons={passthroughToggleButton}
/>
@@ -210,7 +205,6 @@ export function ChatMessage({
<PrettyJsonView
title={title}
json={message.content}
- projectIdForPromptButtons={projectIdForPromptButtons}
currentView={currentView}
controlButtons={passthroughToggleButton}
afterHeader={thinkingBlocks}
@@ -235,7 +229,6 @@ export function ChatMessage({
<PrettyJsonView
title={title || (isOutputMessage ? "Output" : "Input")}
json={message}
- projectIdForPromptButtons={projectIdForPromptButtons}
currentView={currentView}
/>
</div>
diff --git a/web/src/components/trace2/components/IOPreview/components/ChatMessageList.tsx b/web/src/components/trace2/components/IOPreview/components/ChatMessageList.tsx
index 36f11571ba..3cca9d327e 100644
--- a/web/src/components/trace2/components/IOPreview/components/ChatMessageList.tsx
+++ b/web/src/components/trace2/components/IOPreview/components/ChatMessageList.tsx
@@ -17,7 +17,6 @@ export interface ChatMessageListProps {
currentView: ViewMode;
messageToToolCallNumbers: Map<number, number[]>;
collapseLongHistory?: boolean;
- projectIdForPromptButtons?: string;
inputMessageCount?: number;
}
@@ -38,7 +37,6 @@ export function ChatMessageList({
currentView,
messageToToolCallNumbers,
collapseLongHistory = true,
- projectIdForPromptButtons,
inputMessageCount,
}: ChatMessageListProps) {
// Filter messages to only those with renderable content
@@ -75,7 +73,6 @@ export function ChatMessageList({
shouldRenderMarkdown={shouldRenderMarkdown}
currentView={currentView}
toolCallNumbers={messageToToolCallNumbers.get(originalIndex)}
- projectIdForPromptButtons={projectIdForPromptButtons}
isOutputMessage={originalIndex >= (inputMessageCount ?? 0)}
/>
{/* Show collapse/expand button after first message */}
@@ -100,7 +97,6 @@ export function ChatMessageList({
<PrettyJsonView
title="Additional Input"
json={additionalInput}
- projectIdForPromptButtons={projectIdForPromptButtons}
currentView={shouldRenderMarkdown ? "pretty" : "json"}
/>
)}
diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsx
index 5c93a14768..c3f1b89502 100644
--- a/web/src/components/ui/CodeJsonViewer.tsx
+++ b/web/src/components/ui/CodeJsonViewer.tsx
@@ -19,7 +19,10 @@ import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";
import { type MediaReturnType } from "@/src/features/media/validation";
import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
import { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";
-import { renderRichPromptContent } from "@/src/features/prompts/components/prompt-content-utils";
+import {
+ renderRichPromptContent,
+ usePromptReferenceProjectId,
+} from "@/src/components/ui/PromptReferences";
import { copyTextToClipboard } from "@/src/utils/clipboard";
export const IO_TABLE_CHAR_LIMIT = 10000;
@@ -36,7 +39,6 @@ export function JSONView(props: {
media?: MediaReturnType[];
scrollable?: boolean;
borderless?: boolean;
- projectIdForPromptButtons?: string;
controlButtons?: React.ReactNode;
externalJsonCollapsed?: boolean;
onToggleCollapse?: () => void;
@@ -46,6 +48,7 @@ export function JSONView(props: {
const { resolvedTheme } = useTheme();
const { setIsMarkdownEnabled } = useMarkdownContext();
const capture = usePostHogClientCapture();
+ const promptReferenceProjectId = usePromptReferenceProjectId();
const [internalCollapsed, setInternalCollapsed] = useState(false);
const collapseStringsAfterLength =
@@ -101,16 +104,13 @@ export function JSONView(props: {
>
{props.isLoading ? (
<Skeleton className="h-3 w-3/4" />
- ) : props.projectIdForPromptButtons ? (
+ ) : promptReferenceProjectId && typeof parsedJson === "string" ? (
<code
className="whitespace-pre-wrap break-words"
dir="auto"
style={{ unicodeBidi: "plaintext" }}
>
- {renderRichPromptContent(
- props.projectIdForPromptButtons,
- String(parsedJson),
- )}
+ {renderRichPromptContent(parsedJson)}
</code>
) : (
<div
diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsx
index 53507062a1..b53e29d14c 100644
--- a/web/src/components/ui/MarkdownJsonView.tsx
+++ b/web/src/components/ui/MarkdownJsonView.tsx
@@ -2,7 +2,6 @@ import {
OpenAIContentSchema,
type OpenAIOutputAudioType,
} from "@langfuse/shared";
-import { StringOrMarkdownSchema } from "@/src/components/schemas/MarkdownSchema";
import { Button } from "@/src/components/ui/button";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
import { MarkdownView } from "@/src/components/ui/MarkdownViewer";
@@ -101,10 +100,6 @@ export function MarkdownJsonView({
/** Content to render between header and main content (e.g., thinking blocks) */
afterHeader?: React.ReactNode;
}) {
- const stringOrValidatedMarkdown = useMemo(
- () => StringOrMarkdownSchema.safeParse(content),
- [content],
- );
const validatedOpenAIContent = useMemo(
() => OpenAIContentSchema.safeParse(content),
[content],
@@ -119,7 +114,9 @@ export function MarkdownJsonView({
<>
{canEnableMarkdown ? (
<MarkdownView
- markdown={stringOrValidatedMarkdown.data ?? content}
+ markdown={
+ validatedOpenAIContent.success ? validatedOpenAIContent.data : null
+ }
title={title}
titleIcon={titleIcon}
customCodeHeaderClassName={customCodeHeaderClassName}
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index 3e6af7f4fd..5e51ccb28f 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -21,6 +21,7 @@ import { type ExtraProps as ReactMarkdownExtraProps } from "react-markdown";
import {
OpenAIUrlImageUrl,
MediaReferenceStringSchema,
+ PromptDependencyRegex,
type OpenAIContentParts,
type OpenAIContentSchema,
type OpenAIOutputAudioType,
@@ -38,6 +39,14 @@ import DOMPurify from "dompurify";
import { MENTION_USER_PREFIX } from "@/src/features/comments/lib/mentionParser";
import { useCollapsibleSystemPrompt } from "@/src/hooks/useCollapsibleSystemPrompt";
import { Button } from "@/src/components/ui/button";
+import {
+ getPromptReferenceMarkdownHref,
+ getPromptReferenceMarkdownLabel,
+ parsePromptDependencyInnerContent,
+ parsePromptReferenceMarkdownHref,
+ PromptReferenceButton,
+ usePromptReferenceProjectId,
+} from "@/src/components/ui/PromptReferences";
type ReactMarkdownNode = ReactMarkdownExtraProps["node"];
type ReactMarkdownNodeChildren = Exclude<
@@ -109,6 +118,108 @@ const isImageNode = (node?: ReactMarkdownNode): boolean =>
"tagName" in child && child.tagName === "img",
);
+const getNodeTextContent = (node: ReactNode): string => {
+ if (typeof node === "string" || typeof node === "number") {
+ return String(node);
+ }
+
+ if (Array.isArray(node)) {
+ return node.map(getNodeTextContent).join("");
+ }
+
+ if (isValidElement<{ children?: ReactNode }>(node)) {
+ return getNodeTextContent(node.props.children);
+ }
+
+ return "";
+};
+
+type MarkdownAstNode = {
+ type: string;
+ value?: string;
+ url?: string;
+ children?: MarkdownAstNode[];
+};
+
+const splitTextNodeWithPromptReferences = (
+ node: MarkdownAstNode,
+): MarkdownAstNode[] => {
+ const value = node.value;
+ if (!value) return [node];
+
+ const promptRegex = new RegExp(PromptDependencyRegex.source, "g");
+ const parts: MarkdownAstNode[] = [];
+ let lastIndex = 0;
+ let match: RegExpExecArray | null;
+
+ while ((match = promptRegex.exec(value)) !== null) {
+ const index = match.index ?? 0;
+ const fullMatch = match[0];
+ const innerContent = match[1];
+
+ if (typeof innerContent !== "string") continue;
+
+ const tag = parsePromptDependencyInnerContent(innerContent, index);
+ if (!tag) continue;
+
+ if (index > lastIndex) {
+ parts.push({
+ type: "text",
+ value: value.slice(lastIndex, index),
+ });
+ }
+
+ parts.push({
+ type: "link",
+ url: getPromptReferenceMarkdownHref(tag),
+ children: [
+ {
+ type: "text",
+ value: getPromptReferenceMarkdownLabel(tag),
+ },
+ ],
+ });
+
+ lastIndex = index + fullMatch.length;
+ }
+
+ if (parts.length === 0) return [node];
+
+ if (lastIndex < value.length) {
+ parts.push({
+ type: "text",
+ value: value.slice(lastIndex),
+ });
+ }
+
+ return parts;
+};
+
+const transformPromptReferenceNodes = (node: MarkdownAstNode): void => {
+ if (!Array.isArray(node.children)) return;
+ if (
+ node.type === "code" ||
+ node.type === "inlineCode" ||
+ node.type === "link" ||
+ node.type === "linkReference"
+ ) {
+ return;
+ }
+
+ node.children = node.children.flatMap((child) => {
+ if (child.type === "text") {
+ return splitTextNodeWithPromptReferences(child);
+ }
+
+ transformPromptReferenceNodes(child);
+ return [child];
+ });
+};
+
+const remarkPromptReferences = () => (tree: MarkdownAstNode) => {
+ transformPromptReferenceNodes(tree);
+};
+
function MarkdownRenderer({
markdown,
theme,
@@ -120,6 +231,8 @@ function MarkdownRenderer({
className?: string;
customCodeHeaderClassName?: string;
}) {
+ const promptReferenceProjectId = usePromptReferenceProjectId();
+
// Try to parse markdown content
try {
@@ -132,7 +245,11 @@ function MarkdownRenderer({
)}
>
<MemoizedReactMarkdown
- remarkPlugins={[remarkGfm]}
+ remarkPlugins={
+ promptReferenceProjectId
+ ? [remarkGfm, remarkPromptReferences]
+ : [remarkGfm]
+ }
components={{
p({ children, node }) {
if (isImageNode(node)) {
@@ -143,6 +260,16 @@ function MarkdownRenderer({
);
},
a({ children, href }) {
+ const promptReference = parsePromptReferenceMarkdownHref(href);
+ if (promptReference) {
+ return (
+ <PromptReferenceButton
+ promptRef={promptReference}
+ fallbackText={getNodeTextContent(children)}
+ />
+ );
+ }
+
// Handle mention links
if (href?.startsWith(MENTION_USER_PREFIX)) {
const userId = href.replace(MENTION_USER_PREFIX, "");
diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsx
index d07eaec1c0..0802300a1d 100644
--- a/web/src/components/ui/PrettyJsonView.tsx
+++ b/web/src/components/ui/PrettyJsonView.tsx
@@ -751,7 +751,6 @@ export function PrettyJsonView(props: {
collapseStringsAfterLength?: number | null;
media?: MediaReturnType[];
scrollable?: boolean;
- projectIdForPromptButtons?: string;
controlButtons?: React.ReactNode;
currentView?: "pretty" | "json";
externalExpansionState?: Record<string, boolean> | boolean;
@@ -1274,7 +1273,6 @@ export function PrettyJsonView(props: {
collapseStringsAfterLength={props.collapseStringsAfterLength}
media={props.media}
scrollable={props.scrollable}
- projectIdForPromptButtons={props.projectIdForPromptButtons}
externalJsonCollapsed={jsonIsCollapsed}
onToggleCollapse={handleJsonToggleCollapse}
/>
diff --git a/web/src/components/ui/PromptReferences.tsx b/web/src/components/ui/PromptReferences.tsx
new file mode 100644
index 0000000000..d8a19a0355
--- /dev/null
+++ b/web/src/components/ui/PromptReferences.tsx
@@ -0,0 +1,272 @@
+import React, { createContext, useContext, type ReactNode } from "react";
+import {
+ MUSTACHE_REGEX,
+ PromptDependencyRegex,
+ isValidVariableName,
+ type ParsedPromptDependencyTag,
+} from "@langfuse/shared";
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import { cn } from "@/src/utils/tailwind";
+import { FileCode } from "lucide-react";
+
+const PROMPT_REFERENCE_MARKDOWN_PREFIX = "/__langfuse_prompt_reference__?";
+const PromptReferenceContext = createContext<string | undefined>(undefined);
+
+export const PromptReferenceProvider = ({
+ projectId,
+ children,
+}: {
+ projectId?: string;
+ children: ReactNode;
+}) => (
+ <PromptReferenceContext.Provider value={projectId}>
+ {children}
+ </PromptReferenceContext.Provider>
+);
+
+export const usePromptReferenceProjectId = () =>
+ useContext(PromptReferenceContext);
+
+export type PromptReferenceWithPosition = ParsedPromptDependencyTag & {
+ position: number;
+};
+
+export const parsePromptDependencyInnerContent = (
+ innerContent: string,
+ position: number,
+): PromptReferenceWithPosition | null => {
+ const params: Record<string, string> = {};
+
+ innerContent.split("|").forEach((part) => {
+ const separatorIndex = part.indexOf("=");
+ if (separatorIndex === -1) return;
+
+ const key = part.slice(0, separatorIndex);
+ const value = part.slice(separatorIndex + 1);
+
+ if (key && value) {
+ params[key] = value;
+ }
+ });
+
+ if (!params.name) return null;
+
+ if (params.version) {
+ const version = Number(params.version);
+ if (!Number.isFinite(version)) return null;
+
+ return {
+ name: params.name,
+ type: "version",
+ version,
+ position,
+ };
+ }
+
+ return {
+ name: params.name,
+ type: "label",
+ label: params.label || "",
+ position,
+ };
+};
+
+export const getPromptReferenceUrl = (
+ projectId: string,
+ tag: ParsedPromptDependencyTag,
+) => {
+ const baseUrl = `/project/${projectId}/prompts/`;
+ if (tag.type === "version") {
+ return `${baseUrl}${encodeURIComponent(tag.name)}?version=${tag.version}`;
+ }
+
+ return `${baseUrl}${encodeURIComponent(tag.name)}?label=${encodeURIComponent(tag.label)}`;
+};
+
+export const getPromptReferenceMarkdownLabel = (
+ tag: ParsedPromptDependencyTag,
+) =>
+ tag.type === "version"
+ ? `${tag.name} v${tag.version}`
+ : `${tag.name} ${tag.label}`.trimEnd();
+
+export const getPromptReferenceMarkdownHref = (
+ tag: ParsedPromptDependencyTag,
+) => {
+ const params = new URLSearchParams({
+ name: tag.name,
+ type: tag.type,
+ });
+
+ if (tag.type === "version") {
+ params.set("version", String(tag.version));
+ } else {
+ params.set("label", tag.label);
+ }
+
+ return `${PROMPT_REFERENCE_MARKDOWN_PREFIX}${params.toString()}`;
+};
+
+export const parsePromptReferenceMarkdownHref = (
+ href: string | undefined,
+): ParsedPromptDependencyTag | null => {
+ if (!href?.startsWith(PROMPT_REFERENCE_MARKDOWN_PREFIX)) return null;
+
+ const params = new URLSearchParams(
+ href.slice(PROMPT_REFERENCE_MARKDOWN_PREFIX.length),
+ );
+ const name = params.get("name");
+ const type = params.get("type");
+
+ if (!name || !type) return null;
+
+ if (type === "version") {
+ const version = Number(params.get("version"));
+ if (!Number.isFinite(version)) return null;
+
+ return {
+ name,
+ type,
+ version,
+ };
+ }
+
+ if (type !== "label") return null;
+
+ return {
+ name,
+ type,
+ label: params.get("label") ?? "",
+ };
+};
+
+export const PromptReferenceButton = ({
+ promptRef,
+ fallbackText,
+}: {
+ promptRef: ParsedPromptDependencyTag;
+ fallbackText: string;
+}) => {
+ const projectId = usePromptReferenceProjectId();
+
+ if (!projectId) {
+ return (
+ <span
+ dir="auto"
+ style={{ unicodeBidi: "plaintext" }}
+ className="whitespace-pre-wrap break-words"
+ >
+ {fallbackText}
+ </span>
+ );
+ }
+
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ className="inline-flex items-center gap-1.5 rounded-sm border-dashed bg-muted/50 px-2 py-0.5 align-[-3px] text-xs font-medium transition-colors hover:bg-muted"
+ dir="ltr"
+ onClick={() =>
+ window.open(getPromptReferenceUrl(projectId, promptRef), "_blank")
+ }
+ title={`Open prompt: ${promptRef.name}${promptRef.type === "version" ? ` (v${promptRef.version})` : promptRef.label ? ` (${promptRef.label})` : ""}`}
+ >
+ <FileCode className="h-3 w-3 flex-shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">
+ {promptRef.name}
+ {promptRef.type === "version" ? (
+ <Badge variant="outline" className="ml-1 px-1 py-0 text-[10px]">
+ v{promptRef.version}
+ </Badge>
+ ) : promptRef.label ? (
+ <Badge variant="outline" className="ml-1 px-1 py-0 text-[10px]">
+ {promptRef.label}
+ </Badge>
+ ) : (
+ ""
+ )}
+ </span>
+ </Button>
+ );
+};
+
+const PromptVar = ({ name, isValid }: { name: string; isValid: boolean }) => (
+ <span
+ dir="ltr"
+ style={{ unicodeBidi: "isolate" }}
+ className={cn(
+ isValid ? "text-primary-accent" : "text-destructive",
+ "whitespace-nowrap",
+ )}
+ >
+ {`{{${name}}}`}
+ </span>
+);
+
+export const renderRichPromptContent = (content: string): React.ReactNode[] => {
+ if (!content) return [];
+
+ const createTextNode = (text: string, key: string) => (
+ <span
+ key={key}
+ dir="auto"
+ style={{ unicodeBidi: "plaintext" }}
+ className="whitespace-pre-wrap break-words"
+ >
+ {text}
+ </span>
+ );
+
+ const parts: React.ReactNode[] = [];
+ let lastIndex = 0;
+ const combinedRegex = new RegExp(
+ `${PromptDependencyRegex.source}|${MUSTACHE_REGEX.source}`,
+ "g",
+ );
+
+ let match;
+ while ((match = combinedRegex.exec(content)) !== null) {
+ const index = match.index ?? 0;
+ const fullMatch = match[0];
+
+ if (index > lastIndex) {
+ const textBefore = content.substring(lastIndex, index);
+ if (textBefore) {
+ parts.push(createTextNode(textBefore, `text-${lastIndex}-${index}`));
+ }
+ }
+
+ if (match[1] !== undefined) {
+ const tag = parsePromptDependencyInnerContent(match[1], index);
+ parts.push(
+ tag ? (
+ <React.Fragment key={`prompt-${index}`}>
+ <PromptReferenceButton promptRef={tag} fallbackText={fullMatch} />
+ </React.Fragment>
+ ) : (
+ createTextNode(fullMatch, `raw-${index}`)
+ ),
+ );
+ } else if (match[2] !== undefined) {
+ const variable = match[2];
+ parts.push(
+ <React.Fragment key={`var-${index}-${variable}`}>
+ <PromptVar name={variable} isValid={isValidVariableName(variable)} />
+ </React.Fragment>,
+ );
+ }
+
+ lastIndex = index + fullMatch.length;
+ }
+
+ if (lastIndex < content.length) {
+ const remainingText = content.substring(lastIndex);
+ if (remainingText) {
+ parts.push(createTextNode(remainingText, `text-${lastIndex}-end`));
+ }
+ }
+
+ return parts;
+};
diff --git a/web/src/features/prompts/components/prompt-content-utils.tsx b/web/src/features/prompts/components/prompt-content-utils.tsx
deleted file mode 100644
index a1b880b37d..0000000000
--- a/web/src/features/prompts/components/prompt-content-utils.tsx
+++ /dev/null
@@ -1,175 +0,0 @@
-import React from "react";
-import { cn } from "@/src/utils/tailwind";
-import {
- MUSTACHE_REGEX,
- isValidVariableName,
- PromptDependencyRegex,
- type ParsedPromptDependencyTag,
-} from "@langfuse/shared";
-import { Badge } from "@/src/components/ui/badge";
-import { Button } from "@/src/components/ui/button";
-import { FileCode } from "lucide-react";
-
-const PromptVar = ({ name, isValid }: { name: string; isValid: boolean }) => (
- <span
- dir="ltr"
- style={{ unicodeBidi: "isolate" }}
- className={cn(
- isValid ? "text-primary-accent" : "text-destructive",
- "whitespace-nowrap",
- )}
- >
- {`{{${name}}}`}
- </span>
-);
-
-type PromptReference = ParsedPromptDependencyTag & {
- position: number;
-};
-
-const PromptReference = ({
- promptRef,
- projectId,
-}: {
- promptRef: PromptReference;
- projectId: string;
-}) => {
- const getPromptUrl = (projectId: string, tag: PromptReference) => {
- const baseUrl = `/project/${projectId}/prompts/`;
- if (tag.type === "version") {
- return `${baseUrl}${encodeURIComponent(tag.name)}?version=${tag.version}`;
- } else {
- return `${baseUrl}${encodeURIComponent(tag.name)}?label=${encodeURIComponent(tag.label)}`;
- }
- };
-
- return (
- <Button
- variant="outline"
- size="sm"
- className="inline-flex items-center gap-1.5 rounded-sm border-dashed bg-muted/50 px-2 py-0.5 align-[-3px] text-xs font-medium transition-colors hover:bg-muted"
- dir="ltr"
- onClick={() => window.open(getPromptUrl(projectId, promptRef), "_blank")}
- title={`Open prompt: ${promptRef.name}${promptRef.type === "version" ? ` (v${promptRef.version})` : promptRef.label ? ` (${promptRef.label})` : ""}`}
- >
- <FileCode className="h-3 w-3 flex-shrink-0 text-muted-foreground" />
- <span className="truncate font-medium">
- {promptRef.name}
- {promptRef.type === "version" ? (
- <Badge variant="outline" className="ml-1 px-1 py-0 text-[10px]">
- v{promptRef.version}
- </Badge>
- ) : promptRef.label ? (
- <Badge variant="outline" className="ml-1 px-1 py-0 text-[10px]">
- {promptRef.label}
- </Badge>
- ) : (
- ""
- )}
- </span>
- </Button>
- );
-};
-
-// Higher-level function that renders prompt content with all the rich formatting
-export const renderRichPromptContent = (
- projectId: string,
- content: string,
-): React.ReactNode[] => {
- if (!content) return [];
-
- const createTextNode = (text: string, key: string) => (
- <span
- key={key}
- dir="auto"
- style={{ unicodeBidi: "plaintext" }}
- className="whitespace-pre-wrap break-words"
- >
- {text}
- </span>
- );
-
- const parts: React.ReactNode[] = [];
- let lastIndex = 0;
-
- // Create combined regex that captures both patterns in a single pass
- // Group 1: prompt dependency inner content, Group 2: variable name
- const combinedRegex = new RegExp(
- `${PromptDependencyRegex.source}|${MUSTACHE_REGEX.source}`,
- "g",
- );
-
- let match;
- while ((match = combinedRegex.exec(content)) !== null) {
- const index = match.index ?? 0;
- const fullMatch = match[0];
-
- // Add any text before this match
- if (index > lastIndex) {
- const textBefore = content.substring(lastIndex, index);
- if (textBefore) {
- parts.push(createTextNode(textBefore, `text-${lastIndex}-${index}`));
- }
- }
-
- // Determine type based on which capture group matched and process directly
- if (match[1] !== undefined) {
- // First capture group = prompt dependency
- const innerContent = match[1];
- const tagParts = innerContent.split("|");
- const params: Record<string, string> = {};
-
- tagParts.forEach((part) => {
- const [key, value] = part.split("=");
- if (key && value) {
- params[key] = value;
- }
- });
-
- if (params.name) {
- const tag: PromptReference = params.version
- ? {
- name: params.name,
- type: "version",
- version: Number(params.version),
- position: index,
- }
- : {
- name: params.name,
- type: "label",
- label: params.label || "",
- position: index,
- };
-
- parts.push(
- <React.Fragment key={`prompt-${index}`}>
- <PromptReference promptRef={tag} projectId={projectId} />
- </React.Fragment>,
- );
- } else {
- parts.push(createTextNode(fullMatch, `raw-${index}`));
- }
- } else if (match[2] !== undefined) {
- // Second capture group = variable
- const variable = match[2];
- const isValid = isValidVariableName(variable);
- parts.push(
- <React.Fragment key={`var-${index}-${variable}`}>
- <PromptVar name={variable} isValid={isValid} />
- </React.Fragment>,
- );
- }
-
- lastIndex = index + fullMatch.length;
- }
-
- // Add any remaining text
- if (lastIndex < content.length) {
- const remainingText = content.substring(lastIndex);
- if (remainingText) {
- parts.push(createTextNode(remainingText, `text-${lastIndex}-end`));
- }
- }
-
- return parts;
-};
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index dfe2b90076..2fc3d00677 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -59,7 +59,10 @@ import { TagPromptDetailsPopover } from "@/src/features/tag/components/TagPrompt
import { SetPromptVersionLabels } from "@/src/features/prompts/components/SetPromptVersionLabels";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { Command, CommandInput } from "@/src/components/ui/command";
-import { renderRichPromptContent } from "@/src/features/prompts/components/prompt-content-utils";
+import {
+ PromptReferenceProvider,
+ renderRichPromptContent,
+} from "@/src/components/ui/PromptReferences";
import { PromptVariableListPreview } from "@/src/features/prompts/components/PromptVariableListPreview";
import { createBreadcrumbItems } from "@/src/features/folders/utils";
@@ -533,37 +536,35 @@ export const PromptDetail = ({
</Tabs>
</div>
)}
- {prompt.type === PromptType.Chat && chatMessages ? (
- <div className="w-full">
- <OpenAiMessageView
- messages={chatMessages}
- shouldRenderMarkdown={true}
- currentView="pretty"
- messageToToolCallNumbers={new Map()}
- collapseLongHistory={false}
- projectIdForPromptButtons={projectId}
- />
- </div>
- ) : typeof prompt.prompt === "string" ? (
- resolutionMode === "resolved" &&
- promptGraph.data?.resolvedPrompt ? (
- <CodeView
- content={String(promptGraph.data.resolvedPrompt)}
- title="Text Prompt (resolved)"
- />
+ <PromptReferenceProvider projectId={projectId}>
+ {prompt.type === PromptType.Chat && chatMessages ? (
+ <div className="w-full">
+ <OpenAiMessageView
+ messages={chatMessages}
+ shouldRenderMarkdown={true}
+ currentView="pretty"
+ messageToToolCallNumbers={new Map()}
+ collapseLongHistory={false}
+ />
+ </div>
+ ) : typeof prompt.prompt === "string" ? (
+ resolutionMode === "resolved" &&
+ promptGraph.data?.resolvedPrompt ? (
+ <CodeView
+ content={String(promptGraph.data.resolvedPrompt)}
+ title="Text Prompt (resolved)"
+ />
+ ) : (
+ <CodeView
+ content={renderRichPromptContent(prompt.prompt)}
+ originalContent={prompt.prompt}
+ title="Text Prompt"
+ />
+ )
) : (
- <CodeView
- content={renderRichPromptContent(
- projectId as string,
- prompt.prompt,
- )}
- originalContent={prompt.prompt}
- title="Text Prompt"
- />
- )
- ) : (
- <JSONView json={prompt.prompt} title="Prompt" />
- )}
+ <JSONView json={prompt.prompt} title="Prompt" />
+ )}
+ </PromptReferenceProvider>
<PromptVariableListPreview variables={extractedVariables} />
</div>
</TabsBarContent>