Skip to content

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

feat(agent): Show sources for agent answers (#14218)

Ben Bachem63ec7c7411e8
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index d11d54eeb8..ecbaf45ddf 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -69,7 +69,41 @@ vi.mock("@mastra/mcp", () => ({
listToolsetsWithErrors: vi.fn().mockResolvedValue({
toolsets: {
langfuse: { search: { server: "langfuse" } },
- langfuseDocs: { search: { server: "langfuseDocs" } },
+ langfuseDocs: {
+ search: {
+ server: "langfuseDocs",
+ execute: vi.fn().mockResolvedValue({
+ _meta: {
+ choices: [
+ {
+ message: {
+ content: JSON.stringify({
+ content: [
+ {
+ type: "document",
+ title: "Invite Co-workers",
+ url: "https://langfuse.com/faq/all/inviting-in-langfuse",
+ },
+ {
+ type: "document",
+ title:
+ "SCIM & Organization-Key Scoped API Routes",
+ url: "https://langfuse.com/docs/administration/scim-and-org-api",
+ },
+ {
+ type: "document",
+ title: "Members Router",
+ url: "https://github.com/langfuse/langfuse/blob/main/web/src/features/rbac/server/membersRouter.ts",
+ },
+ ],
+ }),
+ },
+ },
+ ],
+ },
+ }),
+ },
+ },
},
errors: {},
}),
@@ -185,10 +219,20 @@ describe("createAgUiStream", () => {
expect.objectContaining({
tools: {
langfuse_search: { server: "langfuse" },
- langfuseDocs_search: { server: "langfuseDocs" },
+ langfuseDocs_search: expect.objectContaining({
+ server: "langfuseDocs",
+ execute: expect.any(Function),
+ }),
},
}),
);
+ const agentConfig = vi.mocked(Agent).mock.calls[0]?.[0];
+ const docsSearchTool = agentConfig?.tools?.langfuseDocs_search;
+ await expect(docsSearchTool?.execute?.({}, {})).resolves.toMatchObject({
+ _meta: expect.objectContaining({
+ choices: expect.any(Array),
+ }),
+ });
expect(persistedEvents.map((event) => event.type)).toEqual([
EventType.RUN_STARTED,
EventType.MESSAGES_SNAPSHOT,
diff --git a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
index f7580e5d56..d25cbd877e 100644
--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -1,17 +1,9 @@
"use client";
import { useMemo } from "react";
-import { z } from "zod";
-import {
- InAppAgentWindow,
- type InAppAgentWindowMessage,
-} from "./InAppAgentWindow";
-import type { InAppAgentToolCallContent } from "./InAppAgentMessage";
+import { InAppAgentWindow } from "./InAppAgentWindow";
import { useInAppAiAgent } from "./InAppAiAgentProvider";
-import {
- AgUiMessageSchema,
- type AgUiMessage,
-} from "@/src/ee/features/in-app-agent/schema";
+import { getDrawerMessages } from "./utils/utils";
type ControlledInAppAgentWindowBaseProps = {
zIndex?: number;
@@ -52,174 +44,10 @@ export function ControlledInAppAgentWindow(
const isInputDisabled =
isRunning || isSubmitting || isSelectedConversationHydrating;
- const drawerMessages = useMemo(() => {
- const parsedMessages = z.array(AgUiMessageSchema).parse(messages);
- const toolResults = getToolResultsByToolCallId(parsedMessages);
-
- const mappedMessages: InAppAgentWindowMessage[] = [];
- let pendingTools: InAppAgentToolCallContent[] = [];
- let pendingToolGroupId: string | null = null;
- const flushPendingTools = () => {
- if (pendingTools.length === 0) {
- return;
- }
-
- mappedMessages.push({
- id: pendingToolGroupId ?? "tools-pending",
- role: "assistant",
- content: { type: "toolGroup", tools: pendingTools },
- });
- pendingTools = [];
- pendingToolGroupId = null;
- };
-
- parsedMessages.forEach((message, index) => {
- if (
- message.role === "system" ||
- message.role === "developer" ||
- message.role === "tool" ||
- message.role === "activity"
- ) {
- return;
- }
-
- const role = message.role === "user" ? "user" : "assistant";
- const isLoading = message.role === "reasoning";
-
- if (isLoading) {
- flushPendingTools();
-
- const hasLaterAssistantMessage = parsedMessages.some(
- (message, messageIndex) =>
- messageIndex > index && message.role === "assistant",
- );
-
- if (!isRunning || hasLaterAssistantMessage) {
- return;
- }
-
- mappedMessages.push({
- id: message.id,
- role,
- content: { type: "loading" },
- });
- return;
- }
-
- const text =
- typeof message.content === "string"
- ? message.content
- : Array.isArray(message.content)
- ? message.content
- .flatMap((part) => (part.type === "text" ? [part.text] : []))
- .join("")
- : "";
-
- const toolContent =
- message.role === "assistant"
- ? (message.toolCalls?.map((toolCall): InAppAgentToolCallContent => {
- const result = toolResults.get(toolCall.id);
-
- return {
- type: "tool",
- name: toolCall.function.name,
- args: toolCall.function.arguments,
- ...(result?.content !== undefined
- ? { result: result.content }
- : {}),
- ...(result?.error !== undefined ? { error: result.error } : {}),
- };
- }) ?? [])
- : [];
-
- if (role === "assistant" && toolContent.length > 0 && !text.trim()) {
- pendingToolGroupId ??= `tools-${message.id}`;
- pendingTools.push(...toolContent);
- return;
- }
-
- flushPendingTools();
-
- if (role === "assistant" && !text.trim() && toolContent.length === 0) {
- return;
- }
-
- if (text.trim() || role === "user") {
- mappedMessages.push({
- id: message.id,
- ...(message.role === "assistant" && message.runId
- ? { runId: message.runId }
- : {}),
- role,
- content: {
- type: "text",
- text,
- ...(message.role === "assistant" && message.feedback
- ? { feedback: message.feedback }
- : {}),
- },
- });
- }
-
- if (toolContent.length > 0) {
- mappedMessages.push({
- id: `${message.id}-tools`,
- role,
- content: { type: "toolGroup", tools: toolContent },
- });
- }
- });
-
- flushPendingTools();
-
- const latestUserMessageIndex = mappedMessages.findLastIndex(
- (message) => message.role === "user",
- );
- const latestAssistantMessageIndex = mappedMessages.findLastIndex(
- (message, index) =>
- index > latestUserMessageIndex && message.role === "assistant",
- );
- const latestAssistantMessage = mappedMessages[latestAssistantMessageIndex];
-
- // Insert an optimistic loading message
- if (
- isRunning &&
- !error &&
- latestUserMessageIndex >= 0 &&
- latestAssistantMessage?.content.type !== "text" &&
- latestAssistantMessage?.content.type !== "loading"
- ) {
- if (latestAssistantMessage?.content.type === "toolGroup") {
- // Set the tool group message to loading state
- return mappedMessages.map((message, index) =>
- index === latestAssistantMessageIndex
- ? {
- ...message,
- content: { ...latestAssistantMessage.content, isLoading: true },
- }
- : message,
- );
- }
-
- const hasAssistantAnswer = mappedMessages.some(
- (message) =>
- message.role === "assistant" && message.content.type === "text",
- );
-
- return [
- ...mappedMessages,
- {
- id: hasAssistantAnswer ? "loading" : "connecting",
- role: "assistant",
- content: hasAssistantAnswer
- ? { type: "loading" }
- : { type: "loading", label: "Connecting..." },
- } satisfies InAppAgentWindowMessage,
- ];
- }
-
- return mappedMessages;
- }, [error, isRunning, messages]);
+ const drawerMessages = useMemo(
+ () => getDrawerMessages({ error, isRunning, messages }),
+ [error, isRunning, messages],
+ );
const closeButtonProps =
props.showCloseButton === false
@@ -247,15 +75,3 @@ export function ControlledInAppAgentWindow(
/>
);
}
-
-function getToolResultsByToolCallId(messages: readonly AgUiMessage[]) {
- const results = new Map<string, Extract<AgUiMessage, { role: "tool" }>>();
-
- for (const message of messages) {
- if (message.role === "tool") {
- results.set(message.toolCallId, message);
- }
- }
-
- return results;
-}
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx
index 5ed83e8508..d8f19ce30a 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx
@@ -27,6 +27,29 @@ export const AssistantTextWithFeedback = meta.story({
},
});
+export const AssistantTextWithSources = meta.story({
+ args: {
+ role: "assistant" as const,
+ content: {
+ type: "text" as const,
+ text: "Scores are Langfuse's universal data object for storing evaluation results.",
+ sources: [
+ {
+ title: "Scores",
+ url: "https://langfuse.com/docs/evaluation/scores/overview",
+ faviconUrl: "https://langfuse.com/favicon.ico",
+ },
+ {
+ title: "Scores Data Model",
+ url: "https://langfuse.com/docs/evaluation/scores/data-model",
+ faviconUrl: "https://langfuse.com/favicon.ico",
+ },
+ ],
+ },
+ onSubmitFeedback: fn(),
+ },
+});
+
export const ShortAssistantTextWithFeedback = meta.story({
args: {
role: "assistant",
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
index 660f9d148f..1b6e78a7e3 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
@@ -3,6 +3,7 @@
import {
Check,
Copy,
+ BookOpenText,
Loader2,
ThumbsDown,
ThumbsUp,
@@ -22,11 +23,13 @@ import {
import type {
InAppAgentMessageFeedback,
InAppAgentMessageFeedbackValue,
+ InAppAgentMessageSource,
} from "@/src/ee/features/in-app-agent/schema";
import {
Popover,
PopoverAnchor,
PopoverContent,
+ PopoverTrigger,
} from "@/src/components/ui/popover";
import { useElementSize } from "@/src/hooks/useElementSize";
import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";
@@ -37,7 +40,12 @@ export type InAppAgentMessageRole = "assistant" | "user";
export type InAppAgentMessageContent =
| { type: "loading"; label?: string }
- | { type: "text"; text: string; feedback?: InAppAgentMessageFeedback }
+ | {
+ type: "text";
+ text: string;
+ feedback?: InAppAgentMessageFeedback;
+ sources?: InAppAgentMessageSource[];
+ }
| {
type: "toolGroup";
tools: InAppAgentToolCallContent[];
@@ -91,7 +99,7 @@ export function InAppAgentMessage({
);
}
- if (content.type === "text" && role === "assistant" && onSubmitFeedback) {
+ if (content.type === "text" && role === "assistant") {
return (
<AssistantMessageWithFeedback
content={content}
@@ -149,12 +157,15 @@ function AssistantMessageWithFeedback({
isCompact: boolean;
isFeedbackDisabled: boolean;
windowZIndex?: number;
- onSubmitFeedback: (params: {
+ onSubmitFeedback?: (params: {
value: InAppAgentMessageFeedbackValue | null;
comment?: string | null;
}) => Promise<void>;
}) {
const [messageCardRef, messageCardSize] = useElementSize<HTMLDivElement>();
+ const sources = content.sources ?? [];
+ const hasSources = sources.length > 0;
+ const hasActions = Boolean(onSubmitFeedback || hasSources);
return (
<div className="flex max-w-full flex-col items-start">
@@ -164,14 +175,38 @@ function AssistantMessageWithFeedback({
content={content}
isCompact={isCompact}
/>
- <MessageFeedbackControls
- feedback={content.feedback}
- isCompact={isCompact}
- isFeedbackDisabled={isFeedbackDisabled}
- windowZIndex={windowZIndex}
- maxWidth={messageCardSize?.width}
- onSubmitFeedback={onSubmitFeedback}
- />
+ {hasActions ? (
+ <div
+ style={
+ messageCardSize?.width
+ ? { width: messageCardSize.width, maxWidth: "100%" }
+ : undefined
+ }
+ className={cn(
+ "flex max-w-full min-w-50 flex-col items-start overflow-hidden",
+ isCompact ? "mt-1.5" : "mt-2",
+ )}
+ >
+ <div className="flex w-full min-w-0 items-center gap-1">
+ {onSubmitFeedback ? (
+ <MessageFeedbackControls
+ feedback={content.feedback}
+ isCompact={isCompact}
+ isFeedbackDisabled={isFeedbackDisabled}
+ windowZIndex={windowZIndex}
+ onSubmitFeedback={onSubmitFeedback}
+ />
+ ) : null}
+ {hasSources ? (
+ <SourcesPopover
+ sources={sources}
+ isCompact={isCompact}
+ windowZIndex={windowZIndex}
+ />
+ ) : null}
+ </div>
+ </div>
+ ) : null}
</div>
);
}
@@ -181,14 +216,12 @@ function MessageFeedbackControls({
isCompact,
isFeedbackDisabled,
windowZIndex,
- maxWidth,
onSubmitFeedback,
}: {
feedback?: InAppAgentMessageFeedback;
isCompact: boolean;
isFeedbackDisabled: boolean;
windowZIndex?: number;
- maxWidth?: number;
onSubmitFeedback: (params: {
value: InAppAgentMessageFeedbackValue | null;
comment?: string | null;
@@ -265,99 +298,147 @@ function MessageFeedbackControls({
};
return (
- <div
- style={maxWidth ? { width: maxWidth, maxWidth: "100%" } : undefined}
- className={cn(
- "flex max-w-full min-w-50 flex-col items-start overflow-hidden",
- isCompact ? "mt-1.5" : "mt-2",
- )}
+ <Popover
+ open={!isFeedbackDisabled && isCommentPopoverOpen}
+ onOpenChange={(open) => {
+ if (!isFeedbackDisabled) {
+ setIsCommentPopoverOpen(open);
+ }
+ }}
>
- <Popover
- open={!isFeedbackDisabled && isCommentPopoverOpen}
- onOpenChange={(open) => {
- if (!isFeedbackDisabled) {
- setIsCommentPopoverOpen(open);
- }
- }}
+ <PopoverAnchor className="inline-flex">
+ <FeedbackButton
+ label="Good response"
+ isSelected={selectedValue === "thumbs_up"}
+ disabled={isDisabled}
+ onClick={() => handleSelectFeedback("thumbs_up")}
+ >
+ <ThumbsUp
+ className={cn(
+ isCompact ? "size-3" : "size-3.5",
+ selectedValue === "thumbs_up" && "text-foreground",
+ )}
+ />
+ </FeedbackButton>
+ </PopoverAnchor>
+ <FeedbackButton
+ label="Bad response"
+ isSelected={selectedValue === "thumbs_down"}
+ disabled={isDisabled}
+ onClick={() => handleSelectFeedback("thumbs_down")}
>
- <div className="flex w-full min-w-0 items-center gap-1">
- <PopoverAnchor className="inline-flex">
- <FeedbackButton
- label="Good response"
- isSelected={selectedValue === "thumbs_up"}
+ <ThumbsDown
+ className={cn(
+ isCompact ? "size-3" : "size-3.5",
+ selectedValue === "thumbs_down" && "text-foreground",
+ )}
+ />
+ </FeedbackButton>
+ {committedComment ? (
+ <button
+ type="button"
+ className="text-muted-foreground hover:text-foreground ml-1 min-w-0 flex-1 truncate text-left text-xs disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={isDisabled}
+ onClick={() => setIsCommentPopoverOpen(true)}
+ >
+ Comment: {committedComment}
+ </button>
+ ) : null}
+ {selectedValue ? (
+ <PopoverContent
+ align="start"
+ side="top"
+ className="w-72 space-y-1.5 p-2"
+ style={
+ typeof windowZIndex === "number"
+ ? { zIndex: windowZIndex + 1 }
+ : undefined
+ }
+ >
+ <div>
+ <textarea
+ value={comment}
+ onChange={(event) => setComment(event.target.value)}
disabled={isDisabled}
- onClick={() => handleSelectFeedback("thumbs_up")}
- >
- <ThumbsUp
- className={cn(
- isCompact ? "size-3" : "size-3.5",
- selectedValue === "thumbs_up" && "text-foreground",
- )}
- />
- </FeedbackButton>
- </PopoverAnchor>
- <FeedbackButton
- label="Bad response"
- isSelected={selectedValue === "thumbs_down"}
- disabled={isDisabled}
- onClick={() => handleSelectFeedback("thumbs_down")}
- >
- <ThumbsDown
+ placeholder="Optional feedback comment"
+ rows={3}
+ maxLength={500}
className={cn(
- isCompact ? "size-3" : "size-3.5",
- selectedValue === "thumbs_down" && "text-foreground",
+ "border-input bg-background text-foreground placeholder:text-muted-foreground w-full resize-none rounded-md border px-2 py-1",
+ isCompact ? "text-xs" : "text-sm",
)}
/>
- </FeedbackButton>
- {committedComment ? (
- <button
- type="button"
- className="text-muted-foreground hover:text-foreground ml-1 min-w-0 flex-1 truncate text-left text-xs disabled:cursor-not-allowed disabled:opacity-60"
+ <CommentButton
disabled={isDisabled}
- onClick={() => setIsCommentPopoverOpen(true)}
+ className={cn(!isCompact && "px-2 py-1.5 text-sm")}
+ onClick={() => {
+ handleSubmitComment().catch(() => undefined);
+ }}
>
- Comment: {committedComment}
- </button>
- ) : null}
- </div>
- {selectedValue ? (
- <PopoverContent
- align="start"
- side="top"
- className="w-72 space-y-1.5 p-2"
- style={
- typeof windowZIndex === "number"
- ? { zIndex: windowZIndex + 1 }
- : undefined
- }
- >
- <div>
- <textarea
- value={comment}
- onChange={(event) => setComment(event.target.value)}
- disabled={isDisabled}
- placeholder="Optional feedback comment"
- rows={3}
- maxLength={500}
- className={cn(
- "border-input bg-background text-foreground placeholder:text-muted-foreground w-full resize-none rounded-md border px-2 py-1",
- isCompact ? "text-xs" : "text-sm",
- )}
+ {isSubmittingComment ? "Saving..." : "Save comment"}
+ </CommentButton>
+ </div>
+ </PopoverContent>
+ ) : null}
+ </Popover>
+ );
+}
+
+function SourcesPopover({
+ sources,
+ isCompact,
+ windowZIndex,
+}: {
+ sources: InAppAgentMessageSource[];
+ isCompact: boolean;
+ windowZIndex?: number;
+}) {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className={cn(
+ "text-muted-foreground/70 hover:text-muted-foreground inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs font-medium",
+ isCompact && "py-0.5",
+ )}
+ >
+ <BookOpenText className={cn(isCompact ? "size-3" : "size-3.5")} />
+ Sources
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ side="top"
+ className="w-72 p-1.5"
+ style={
+ typeof windowZIndex === "number"
+ ? { zIndex: windowZIndex + 1 }
+ : undefined
+ }
+ >
+ <div className="space-y-0.5">
+ {sources.map((source) => (
+ <a
+ key={source.url}
+ href={source.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="hover:bg-muted flex min-w-0 items-center gap-1.5 rounded-md px-1 py-1 no-underline"
+ >
+ <span
+ aria-hidden="true"
+ className="bg-muted size-3.5 shrink-0 rounded-sm bg-cover bg-center"
+ style={{ backgroundImage: `url("${source.faviconUrl}")` }}
/>
- <CommentButton
- disabled={isDisabled}
- className={cn(!isCompact && "px-2 py-1.5 text-sm")}
- onClick={() => {
- handleSubmitComment().catch(() => undefined);
- }}
- >
- {isSubmittingComment ? "Saving..." : "Save comment"}
- </CommentButton>
- </div>
- </PopoverContent>
- ) : null}
- </Popover>
- </div>
+ <span className="text-foreground min-w-0 flex-1 truncate text-xs">
+ {source.title}
+ </span>
+ </a>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
);
}
diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts
new file mode 100644
index 0000000000..4a36b5e90a
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts
@@ -0,0 +1,225 @@
+import type { AgUiMessage } from "@/src/ee/features/in-app-agent/schema";
+import { extractLangfuseDocsSources, getDrawerMessages } from "./utils";
+
+describe("extractLangfuseDocsSources", () => {
+ it("extracts and deduplicates document sources from docs tool results", () => {
+ const result = JSON.stringify({
+ _meta: {
+ choices: [
+ {
+ message: {
+ content: JSON.stringify({
+ content: [
+ { type: "text", text: "Search result" },
+ {
+ type: "document",
+ title: "Core Concepts",
+ url: "https://langfuse.com/docs/evaluation/core-concepts",
+ },
+ {
+ type: "document",
+ title: "Scores",
+ url: "https://langfuse.com/docs/evaluation/scores/overview",
+ },
+ ],
+ }),
+ },
+ },
+ {
+ message: {
+ content: JSON.stringify({
+ content: [
+ {
+ type: "document",
+ title: "Datasets",
+ url: "https://langfuse.com/docs/datasets/overview",
+ },
+ ],
+ }),
+ },
+ },
+ {
+ message: {
+ content: JSON.stringify({
+ content: [
+ {
+ type: "document",
+ title: "Scores duplicate",
+ url: "https://langfuse.com/docs/evaluation/scores/overview",
+ },
+ ],
+ }),
+ },
+ },
+ ],
+ },
+ });
+
+ expect(
+ extractLangfuseDocsSources([
+ {
+ type: "tool",
+ name: "langfuseDocs_search",
+ args: "{}",
+ result,
+ },
+ {
+ type: "tool",
+ name: "langfuse_queryMetrics",
+ args: "{}",
+ result,
+ },
+ ]),
+ ).toEqual([
+ {
+ title: "Core Concepts",
+ url: "https://langfuse.com/docs/evaluation/core-concepts",
+ faviconUrl: "https://langfuse.com/favicon.ico",
+ },
+ {
+ title: "Scores",
+ url: "https://langfuse.com/docs/evaluation/scores/overview",
+ faviconUrl: "https://langfuse.com/favicon.ico",
+ },
+ {
+ title: "Datasets",
+ url: "https://langfuse.com/docs/datasets/overview",
+ faviconUrl: "https://langfuse.com/favicon.ico",
+ },
+ ]);
+ });
+
+ it("ignores malformed structured sources", () => {
+ const result = JSON.stringify({
+ _meta: {
+ choices: [
+ { message: { content: "not json" } },
+ { message: { content: JSON.stringify({ content: "not array" }) } },
+ {
+ message: {
+ content: JSON.stringify({
+ content: [
+ { type: "document", title: "Missing URL" },
+ { type: "document", title: "Blank URL", url: " " },
+ {
+ type: "document",
+ title: "Unsafe protocol",
+ url: "javascript:alert(1)",
+ },
+ ],
+ }),
+ },
+ },
+ ],
+ },
+ });
+
+ expect(
+ extractLangfuseDocsSources([
+ {
+ type: "tool",
+ name: "langfuseDocs_search",
+ args: "{}",
+ result,
+ },
+ ]),
+ ).toEqual([]);
+ });
+});
+
+describe("getDrawerMessages", () => {
+ it("attaches docs sources to the answer after a search preamble", () => {
+ const docsResult = JSON.stringify({
+ _meta: {
+ choices: [
+ {
+ message: {
+ content: JSON.stringify({
+ content: [
+ {
+ type: "document",
+ url: "https://langfuse.com/docs/audit-logs",
+ title: "Audit Logs",
+ },
+ ],
+ }),
+ },
+ },
+ ],
+ },
+ });
+
+ const mappedMessages = getDrawerMessages({
+ error: null,
+ isRunning: false,
+ messages: [
+ {
+ id: "user-1",
+ role: "user",
+ content: "Does Langfuse have access logging?",
+ },
+ {
+ id: "assistant-1",
+ role: "assistant",
+ content:
+ "I'll search the Langfuse documentation for information about access logging.",
+ toolCalls: [
+ {
+ id: "tool-call-1",
+ type: "function",
+ function: {
+ name: "langfuseDocs_search",
+ arguments: "{}",
+ },
+ },
+ ],
+ },
+ {
+ id: "tool-result-1",
+ role: "tool",
+ toolCallId: "tool-call-1",
+ content: docsResult,
+ },
+ {
+ id: "assistant-2",
+ role: "assistant",
+ content: "Yes, Langfuse has audit logging available.",
+ },
+ ] satisfies AgUiMessage[],
+ });
+
+ expect(mappedMessages).toMatchObject([
+ {
+ id: "user-1",
+ content: { type: "text" },
+ },
+ {
+ id: "assistant-1",
+ content: {
+ type: "text",
+ text: "I'll search the Langfuse documentation for information about access logging.",
+ },
+ },
+ {
+ id: "assistant-1-tools",
+ content: { type: "toolGroup" },
+ },
+ {
+ id: "assistant-2",
+ content: {
+ type: "text",
+ text: "Yes, Langfuse has audit logging available.",
+ sources: [
+ {
+ title: "Audit Logs",
+ url: "https://langfuse.com/docs/audit-logs",
+ faviconUrl: "https://langfuse.com/favicon.ico",
+ },
+ ],
+ },
+ },
+ ]);
+
+ expect(mappedMessages[1]?.content).not.toHaveProperty("sources");
+ });
+});
diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.ts b/web/src/ee/features/in-app-agent/components/utils/utils.ts
new file mode 100644
index 0000000000..475ad2d3b8
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/components/utils/utils.ts
@@ -0,0 +1,327 @@
+import { z } from "zod";
+import type { InAppAgentWindowMessage } from "../InAppAgentWindow";
+import type { InAppAgentToolCallContent } from "../InAppAgentMessage";
+import { deduplicateBy } from "@/src/utils/arrays";
+import {
+ AgUiMessageSchema,
+ type AgUiMessage,
+ type InAppAgentMessageSource,
+ InAppAgentMessageSourceSchema,
+} from "@/src/ee/features/in-app-agent/schema";
+
+const LangfuseDocsDocumentSchema = z.object({
+ type: z.literal("document"),
+ title: z.string().trim().optional(),
+ url: z.string().trim().min(1),
+});
+
+const InkeepChoiceContentSourceSchema = z
+ .object({
+ content: z.array(z.unknown()),
+ })
+ .transform(({ content }): InAppAgentMessageSource[] => {
+ return content.flatMap((entry) => {
+ const parsedDocument = LangfuseDocsDocumentSchema.safeParse(entry);
+
+ if (!parsedDocument.success) {
+ return [];
+ }
+
+ let faviconUrl: string;
+
+ try {
+ faviconUrl = new URL(
+ "/favicon.ico",
+ parsedDocument.data.url,
+ ).toString();
+ } catch {
+ return [];
+ }
+
+ const parsedSource = InAppAgentMessageSourceSchema.safeParse({
+ title: parsedDocument.data.title || parsedDocument.data.url,
+ url: parsedDocument.data.url,
+ faviconUrl,
+ });
+
+ return parsedSource.success ? [parsedSource.data] : [];
+ });
+ });
+
+const InkeepChoiceResultSchema = z.object({
+ _meta: z.object({
+ choices: z.array(
+ z.object({
+ message: z.object({
+ content: z.string(),
+ }),
+ }),
+ ),
+ }),
+});
+
+export function getDrawerMessages({
+ error,
+ isRunning,
+ messages,
+}: {
+ error: unknown;
+ isRunning: boolean;
+ messages: unknown;
+}): InAppAgentWindowMessage[] {
+ const parsedMessages = z.array(AgUiMessageSchema).parse(messages);
+ const toolResults = getToolResultsByToolCallId(parsedMessages);
+
+ const mappedMessages: InAppAgentWindowMessage[] = [];
+ let pendingTools: InAppAgentToolCallContent[] = [];
+ let pendingToolGroupId: string | null = null;
+ let pendingSources: InAppAgentMessageSource[] = [];
+ const flushPendingTools = () => {
+ if (pendingTools.length === 0) {
+ return;
+ }
+
+ mappedMessages.push({
+ id: pendingToolGroupId ?? "tools-pending",
+ role: "assistant",
+ content: { type: "toolGroup", tools: pendingTools },
+ });
+ pendingTools = [];
+ pendingToolGroupId = null;
+ };
+
+ parsedMessages.forEach((message, index) => {
+ if (
+ message.role === "system" ||
+ message.role === "developer" ||
+ message.role === "tool" ||
+ message.role === "activity"
+ ) {
+ return;
+ }
+
+ const role = message.role === "user" ? "user" : "assistant";
+ const isLoading = message.role === "reasoning";
+
+ if (isLoading) {
+ flushPendingTools();
+
+ const hasLaterAssistantMessage = parsedMessages.some(
+ (message, messageIndex) =>
+ messageIndex > index && message.role === "assistant",
+ );
+
+ if (!isRunning || hasLaterAssistantMessage) {
+ return;
+ }
+
+ mappedMessages.push({
+ id: message.id,
+ role,
+ content: { type: "loading" },
+ });
+ return;
+ }
+
+ const text =
+ typeof message.content === "string"
+ ? message.content
+ : Array.isArray(message.content)
+ ? message.content
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
+ .join("")
+ : "";
+
+ const toolContent =
+ message.role === "assistant"
+ ? (message.toolCalls?.map((toolCall): InAppAgentToolCallContent => {
+ const result = toolResults.get(toolCall.id);
+
+ return {
+ type: "tool",
+ name: toolCall.function.name,
+ args: toolCall.function.arguments,
+ ...(result?.content !== undefined
+ ? { result: result.content }
+ : {}),
+ ...(result?.error !== undefined ? { error: result.error } : {}),
+ };
+ }) ?? [])
+ : [];
+ const docsSources = extractLangfuseDocsSources(toolContent);
+
+ if (role === "assistant" && toolContent.length > 0 && !text.trim()) {
+ if (docsSources.length > 0) {
+ pendingSources = mergeSources(pendingSources, docsSources);
+ }
+
+ pendingToolGroupId ??= `tools-${message.id}`;
+ pendingTools.push(...toolContent);
+ return;
+ }
+
+ flushPendingTools();
+
+ if (role === "assistant" && !text.trim() && toolContent.length === 0) {
+ return;
+ }
+
+ if (text.trim() || role === "user") {
+ const sources = role === "assistant" ? pendingSources : [];
+
+ if (role === "user") {
+ pendingSources = [];
+ }
+
+ mappedMessages.push({
+ id: message.id,
+ ...(message.role === "assistant" && message.runId
+ ? { runId: message.runId }
+ : {}),
+ role,
+ content: {
+ type: "text",
+ text,
+ ...(sources.length > 0 ? { sources } : {}),
+ ...(message.role === "assistant" && message.feedback
+ ? { feedback: message.feedback }
+ : {}),
+ },
+ });
+
+ if (role === "assistant") {
+ pendingSources = [];
+
+ if (docsSources.length > 0) {
+ pendingSources = mergeSources(pendingSources, docsSources);
+ }
+ }
+ }
+
+ if (toolContent.length > 0) {
+ mappedMessages.push({
+ id: `${message.id}-tools`,
+ role,
+ content: { type: "toolGroup", tools: toolContent },
+ });
+ }
+ });
+
+ flushPendingTools();
+
+ const latestUserMessageIndex = mappedMessages.findLastIndex(
+ (message) => message.role === "user",
+ );
+ const latestAssistantMessageIndex = mappedMessages.findLastIndex(
+ (message, index) =>
+ index > latestUserMessageIndex && message.role === "assistant",
+ );
+ const latestAssistantMessage = mappedMessages[latestAssistantMessageIndex];
+
+ // Insert an optimistic loading message.
+ if (
+ isRunning &&
+ !error &&
+ latestUserMessageIndex >= 0 &&
+ latestAssistantMessage?.content.type !== "text" &&
+ latestAssistantMessage?.content.type !== "loading"
+ ) {
+ if (latestAssistantMessage?.content.type === "toolGroup") {
+ return mappedMessages.map((message, index) =>
+ index === latestAssistantMessageIndex
+ ? {
+ ...message,
+ content: { ...latestAssistantMessage.content, isLoading: true },
+ }
+ : message,
+ );
+ }
+
+ const hasAssistantAnswer = mappedMessages.some(
+ (message) =>
+ message.role === "assistant" && message.content.type === "text",
+ );
+
+ return [
+ ...mappedMessages,
+ {
+ id: hasAssistantAnswer ? "loading" : "connecting",
+ role: "assistant",
+ content: hasAssistantAnswer
+ ? { type: "loading" }
+ : { type: "loading", label: "Connecting..." },
+ } satisfies InAppAgentWindowMessage,
+ ];
+ }
+
+ return mappedMessages;
+}
+
+function getToolResultsByToolCallId(messages: readonly AgUiMessage[]) {
+ const results = new Map<string, Extract<AgUiMessage, { role: "tool" }>>();
+
+ for (const message of messages) {
+ if (message.role === "tool") {
+ results.set(message.toolCallId, message);
+ }
+ }
+
+ return results;
+}
+
+export function extractLangfuseDocsSources(
+ tools: readonly InAppAgentToolCallContent[],
+): InAppAgentMessageSource[] {
+ return mergeSources(
+ [],
+ tools.flatMap((tool) => {
+ if (!tool.name.startsWith("langfuseDocs_") || !tool.result) {
+ return [];
+ }
+
+ return extractSourcesFromToolResult(tool.result);
+ }),
+ );
+}
+
+function extractSourcesFromToolResult(
+ result: string,
+): InAppAgentMessageSource[] {
+ const parsed = parseJsonString(result);
+ const parsedResult = InkeepChoiceResultSchema.safeParse(parsed);
+
+ if (!parsedResult.success) {
+ return [];
+ }
+
+ return parsedResult.data._meta.choices.flatMap((choice) => {
+ const parsedContent = parseJsonString(choice.message.content);
+ const parsedSource =
+ InkeepChoiceContentSourceSchema.safeParse(parsedContent);
+
+ if (!parsedSource.success) {
+ return [];
+ }
+
+ return parsedSource.data;
+ });
+}
+
+function parseJsonString(value: unknown) {
+ if (typeof value !== "string") {
+ return null;
+ }
+
+ try {
+ return JSON.parse(value) as unknown;
+ } catch {
+ return null;
+ }
+}
+
+function mergeSources(
+ existing: readonly InAppAgentMessageSource[],
+ next: readonly InAppAgentMessageSource[],
+): InAppAgentMessageSource[] {
+ return deduplicateBy([...existing, ...next], (source) => source.url);
+}
diff --git a/web/src/ee/features/in-app-agent/schema.ts b/web/src/ee/features/in-app-agent/schema.ts
index 20d5b9de3b..4f851f043e 100644
--- a/web/src/ee/features/in-app-agent/schema.ts
+++ b/web/src/ee/features/in-app-agent/schema.ts
@@ -1,3 +1,9 @@
+// This module should contained ag-ui base schemas OR shared schemas,
+// do not add any one-off schemas here.
+// This module is shared by browser and server in-app-agent code. Keep it
+// runtime-neutral: Zod schemas and TypeScript types only, with no React,
+// browser-only, server-only, database, or Mastra imports.
+
import type { EventType } from "@ag-ui/core";
import { z } from "zod";
@@ -133,6 +139,40 @@ export const AgUiMessageSchema = z.discriminatedUnion("role", [
export type AgUiMessage = z.infer<typeof AgUiMessageSchema>;
+const AbsoluteHttpUrlSchema = z.string().transform((value, ctx) => {
+ let parsedUrl: URL;
+
+ try {
+ parsedUrl = new URL(value);
+ } catch {
+ ctx.addIssue({
+ code: "custom",
+ message: "URL must be absolute",
+ });
+ return z.NEVER;
+ }
+
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
+ ctx.addIssue({
+ code: "custom",
+ message: "URL protocol must be http or https",
+ });
+ return z.NEVER;
+ }
+
+ return parsedUrl.href;
+});
+
+export const InAppAgentMessageSourceSchema = z.object({
+ title: z.string(),
+ url: AbsoluteHttpUrlSchema,
+ faviconUrl: AbsoluteHttpUrlSchema,
+});
+
+export type InAppAgentMessageSource = z.infer<
+ typeof InAppAgentMessageSourceSchema
+>;
+
const AgUiToolSchema = z.object({
name: z.string(),
description: z.string(),
diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.ts
index db85cbc156..781db521af 100644
--- a/web/src/ee/features/in-app-agent/server/agent.ts
+++ b/web/src/ee/features/in-app-agent/server/agent.ts
@@ -35,6 +35,7 @@ If you cannot provide an answer to the user, spare the user the details of faile
If you think it would be helpful, ask the user for clarification or follow up questions to guide them.
Be concise, factual, and useful. Unless asked for a detailed explanation, keep your answers short and to the point.
Use markdown in your responses when appropriate, especially for tables and lists.
+When you answer using Langfuse documentation tool results, answer normally. The product will attach source links automatically.
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
</behavioral_rules>
diff --git a/web/src/utils/arrays.clienttest.ts b/web/src/utils/arrays.clienttest.ts
new file mode 100644
index 0000000000..8c96d834d7
--- /dev/null
+++ b/web/src/utils/arrays.clienttest.ts
@@ -0,0 +1,19 @@
+import { deduplicateBy } from "@/src/utils/arrays";
+
+describe("deduplicateBy", () => {
+ it("keeps the first item for each key", () => {
+ expect(
+ deduplicateBy(
+ [
+ { id: "a", value: 1 },
+ { id: "b", value: 2 },
+ { id: "a", value: 3 },
+ ],
+ (item) => item.id,
+ ),
+ ).toEqual([
+ { id: "a", value: 1 },
+ { id: "b", value: 2 },
+ ]);
+ });
+});
diff --git a/web/src/utils/arrays.ts b/web/src/utils/arrays.ts
new file mode 100644
index 0000000000..b4898f2545
--- /dev/null
+++ b/web/src/utils/arrays.ts
@@ -0,0 +1,16 @@
+export function deduplicateBy<TItem, TKey>(
+ items: readonly TItem[],
+ getKey: (item: TItem) => TKey,
+): TItem[] {
+ const byKey = new Map<TKey, TItem>();
+
+ for (const item of items) {
+ const key = getKey(item);
+
+ if (!byKey.has(key)) {
+ byKey.set(key, item);
+ }
+ }
+
+ return Array.from(byKey.values());
+}