feat: Add default tool call renderer, and error toasts

This commit is contained in:
bracesproul
2025-03-04 13:37:42 -08:00
parent a796f7612d
commit 3f9c85b106
10 changed files with 168 additions and 7 deletions

View File

@@ -21,7 +21,7 @@ function ThreadList({
const [threadId, setThreadId] = useQueryParam("threadId", StringParam);
return (
<div className="h-full overflow-y-scroll flex flex-col gap-2 items-start justify-start [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-gray-300 [&::-webkit-scrollbar-track]:bg-transparent">
<div className="h-full flex flex-col gap-2 items-start justify-start overflow-y-scroll [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-gray-300 [&::-webkit-scrollbar-track]:bg-transparent">
{threads.map((t) => {
let itemText = t.thread_id;
if (

View File

@@ -23,6 +23,7 @@ import {
import { BooleanParam, StringParam, useQueryParam } from "use-query-params";
import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
import ThreadHistory from "./history";
import { toast } from "sonner";
function StickyToBottomContent(props: {
content: ReactNode;
@@ -75,6 +76,36 @@ export function Thread() {
const messages = stream.messages;
const isLoading = stream.isLoading;
const lastError = useRef<string | undefined>(undefined);
useEffect(() => {
if (!stream.error) {
lastError.current = undefined;
return;
}
try {
const message = (stream.error as any).message;
if (!message || lastError.current === message) {
// Message has already been logged. do not modify ref, return early.
return;
}
// Message is defined, and it has not been logged yet. Save it, and send the error
lastError.current = message;
toast.error("An error occurred. Please try again.", {
description: (
<p>
<strong>Error:</strong> <code>{message}</code>
</p>
),
richColors: true,
closeButton: true,
});
} catch {
// no-op
}
}, [stream.error]);
// TODO: this should be part of the useStream hook
const prevMessageLength = useRef(0);
useEffect(() => {
@@ -178,7 +209,7 @@ export function Thread() {
<StickToBottom className="relative flex-1 overflow-hidden">
<StickyToBottomContent
className={cn(
"absolute inset-0 overflow-auto",
"absolute inset-0 overflow-y-scroll [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-gray-300 [&::-webkit-scrollbar-track]:bg-transparent",
!threadId && "flex flex-col items-stretch mt-[25vh]",
threadId && "grid grid-rows-[1fr_auto]",
)}

View File

@@ -205,10 +205,7 @@ const defaultComponents = memoizeMarkdownComponents({
const isCodeBlock = useIsMarkdownCodeBlock();
return (
<code
className={cn(
!isCodeBlock && "bg-muted rounded border font-semibold",
className,
)}
className={cn(!isCodeBlock && "rounded font-semibold", className)}
{...props}
/>
);

View File

@@ -6,6 +6,7 @@ import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { MarkdownText } from "../markdown-text";
import { LoadExternalComponent } from "@langchain/langgraph-sdk/react-ui/client";
import { cn } from "@/lib/utils";
import { ToolCalls } from "./tool-calls";
function CustomComponent({
message,
@@ -56,12 +57,18 @@ export function AssistantMessage({
const meta = thread.getMessagesMetadata(message);
const parentCheckpoint = meta?.firstSeenState?.parent_checkpoint;
const hasToolCalls =
"tool_calls" in message &&
message.tool_calls &&
message.tool_calls.length > 0;
return (
<div className="flex items-start mr-auto gap-2 group">
<Avatar>
<AvatarFallback>A</AvatarFallback>
</Avatar>
<div className="flex flex-col gap-2">
{hasToolCalls && <ToolCalls toolCalls={message.tool_calls} />}
<CustomComponent message={message} thread={thread} />
{contentString.length > 0 && (
<div className="rounded-2xl bg-muted px-4 py-2">

View File

@@ -0,0 +1,53 @@
import { AIMessage } from "@langchain/langgraph-sdk";
function isComplexValue(value: any): boolean {
return Array.isArray(value) || (typeof value === "object" && value !== null);
}
export function ToolCalls({
toolCalls,
}: {
toolCalls: AIMessage["tool_calls"];
}) {
if (!toolCalls || toolCalls.length === 0) return null;
return (
<div className="space-y-4">
{toolCalls.map((tc, idx) => {
const args = tc.args as Record<string, any>;
if (!tc.args || Object.keys(args).length === 0) return null;
return (
<div
key={idx}
className="border border-gray-200 rounded-lg overflow-hidden"
>
<div className="bg-gray-50 px-4 py-2 border-b border-gray-200">
<h3 className="text-lg font-medium text-gray-900">{tc.name}</h3>
</div>
<table className="min-w-full divide-y divide-gray-200">
<tbody className="divide-y divide-gray-200">
{Object.entries(args).map(([key, value], argIdx) => (
<tr key={argIdx}>
<td className="px-4 py-2 text-sm font-medium text-gray-900 whitespace-nowrap">
{key}
</td>
<td className="px-4 py-2 text-sm text-gray-500">
{isComplexValue(value) ? (
<code className="bg-gray-50 rounded px-2 py-1 font-mono text-sm">
{JSON.stringify(value, null, 2)}
</code>
) : (
String(value)
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,27 @@
import { useTheme } from "next-themes";
import { Toaster as Sonner, ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground font-medium",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground font-medium",
},
}}
{...props}
/>
);
};
export { Toaster };

View File

@@ -5,6 +5,7 @@ import { StreamProvider } from "./providers/Stream.tsx";
import { QueryParamProvider } from "use-query-params";
import { ReactRouter6Adapter } from "use-query-params/adapters/react-router-6";
import { BrowserRouter } from "react-router-dom";
import { Toaster } from "@/components/ui/sonner";
createRoot(document.getElementById("root")!).render(
<BrowserRouter>
@@ -13,5 +14,6 @@ createRoot(document.getElementById("root")!).render(
<App />
</StreamProvider>
</QueryParamProvider>
<Toaster />
</BrowserRouter>,
);

View File

@@ -14,8 +14,10 @@ import { ArrowRight } from "lucide-react";
import { PasswordInput } from "@/components/ui/password-input";
import { getApiKey } from "@/lib/api-key";
export type StateType = { messages: Message[]; ui?: UIMessage[] };
const useTypedStream = useStream<
{ messages: Message[]; ui?: UIMessage[] },
StateType,
{
UpdateType: {
messages?: Message[] | Message | string;
@@ -48,6 +50,12 @@ const StreamSession = ({
onThreadId: setThreadId,
});
if (streamValue.error) {
if (typeof streamValue.error === "object") {
console.log((streamValue.error as any)?.["message"]);
}
}
return (
<StreamContext.Provider value={streamValue}>
{children}