Files
agent-chat-ui/src/providers/Stream.tsx

274 lines
8.4 KiB
TypeScript
Raw Normal View History

2025-03-11 10:21:21 -07:00
import React, {
createContext,
useContext,
ReactNode,
useState,
useEffect,
} from "react";
2025-02-27 14:08:24 -08:00
import { useStream } from "@langchain/langgraph-sdk/react";
2025-03-03 13:51:41 -08:00
import { type Message } from "@langchain/langgraph-sdk";
2025-03-10 18:11:53 +01:00
import {
uiMessageReducer,
type UIMessage,
type RemoveUIMessage,
2025-03-05 17:58:51 +01:00
} from "@langchain/langgraph-sdk/react-ui";
import { useQueryState } from "nuqs";
2025-03-04 17:38:33 +01:00
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { LangGraphLogoSVG } from "@/components/icons/langgraph";
import { Label } from "@/components/ui/label";
import { ArrowRight } from "lucide-react";
2025-03-04 17:58:46 +01:00
import { PasswordInput } from "@/components/ui/password-input";
2025-03-04 10:34:52 -08:00
import { getApiKey } from "@/lib/api-key";
import { useThreads } from "./Thread";
2025-03-11 10:21:21 -07:00
import { toast } from "sonner";
2025-02-27 14:08:24 -08:00
export type StateType = { messages: Message[]; ui?: UIMessage[] };
2025-03-02 20:22:36 +01:00
const useTypedStream = useStream<
StateType,
2025-03-02 20:22:36 +01:00
{
UpdateType: {
2025-02-27 14:08:24 -08:00
messages?: Message[] | Message | string;
ui?: (UIMessage | RemoveUIMessage)[] | UIMessage | RemoveUIMessage;
2025-03-02 20:22:36 +01:00
};
2025-03-10 18:11:53 +01:00
CustomEventType: UIMessage | RemoveUIMessage;
2025-03-02 20:22:36 +01:00
}
2025-02-27 14:08:24 -08:00
>;
2025-03-02 20:22:36 +01:00
type StreamContextType = ReturnType<typeof useTypedStream>;
2025-02-27 14:08:24 -08:00
const StreamContext = createContext<StreamContextType | undefined>(undefined);
async function sleep(ms = 4000) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
2025-03-11 10:21:21 -07:00
async function checkGraphStatus(
apiUrl: string,
apiKey: string | null,
): Promise<boolean> {
try {
2025-03-11 10:30:43 -07:00
const res = await fetch(`${apiUrl}/info`, {
2025-03-11 10:21:21 -07:00
...(apiKey && {
headers: {
"X-Api-Key": apiKey,
},
}),
});
return res.ok;
} catch (e) {
console.error(e);
return false;
}
}
2025-03-04 17:38:33 +01:00
const StreamSession = ({
2025-02-27 14:08:24 -08:00
children,
2025-03-04 17:58:46 +01:00
apiKey,
2025-03-04 17:38:33 +01:00
apiUrl,
assistantId,
}: {
children: ReactNode;
2025-03-04 17:58:46 +01:00
apiKey: string | null;
2025-03-04 17:38:33 +01:00
apiUrl: string;
assistantId: string;
2025-02-27 14:08:24 -08:00
}) => {
const [threadId, setThreadId] = useQueryState("threadId");
const { getThreads, setThreads } = useThreads();
2025-03-02 20:22:36 +01:00
const streamValue = useTypedStream({
2025-03-04 17:38:33 +01:00
apiUrl,
2025-03-04 17:58:46 +01:00
apiKey: apiKey ?? undefined,
2025-03-04 17:38:33 +01:00
assistantId,
2025-03-04 13:55:37 +01:00
threadId: threadId ?? null,
2025-03-10 18:11:53 +01:00
onCustomEvent: (event, options) => {
options.mutate((prev) => {
const ui = uiMessageReducer(prev.ui ?? [], event);
return { ...prev, ui };
});
},
onThreadId: (id) => {
setThreadId(id);
// Refetch threads list when thread ID changes.
// Wait for some seconds before fetching so we're able to get the new thread that was created.
sleep().then(() => getThreads().then(setThreads).catch(console.error));
},
2025-02-27 14:08:24 -08:00
});
2025-03-11 10:21:21 -07:00
useEffect(() => {
checkGraphStatus(apiUrl, apiKey).then((ok) => {
if (!ok) {
toast.error("Failed to connect to LangGraph server", {
description: () => (
<p>
Please ensure your graph is running at <code>{apiUrl}</code> and
your API key is correctly set (if connecting to a deployed graph).
</p>
),
duration: 10000,
richColors: true,
closeButton: true,
});
}
});
}, [apiKey, apiUrl]);
2025-02-27 14:08:24 -08:00
return (
<StreamContext.Provider value={streamValue}>
{children}
</StreamContext.Provider>
);
};
// Default values for the form
const DEFAULT_API_URL = "http://localhost:2024";
const DEFAULT_ASSISTANT_ID = "agent";
2025-03-04 17:38:33 +01:00
export const StreamProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
// Get environment variables
2025-04-10 11:47:43 -07:00
const envApiUrl: string | undefined = process.env.NEXT_PUBLIC_API_URL;
const envAssistantId: string | undefined =
process.env.NEXT_PUBLIC_ASSISTANT_ID;
// Use URL params with env var fallbacks
2025-04-02 13:46:41 -07:00
const [apiUrl, setApiUrl] = useQueryState("apiUrl", {
defaultValue: envApiUrl || "",
});
const [assistantId, setAssistantId] = useQueryState("assistantId", {
defaultValue: envAssistantId || "",
});
// For API key, use localStorage with env var fallback
2025-03-04 17:58:46 +01:00
const [apiKey, _setApiKey] = useState(() => {
const storedKey = getApiKey();
return storedKey || "";
2025-03-04 17:58:46 +01:00
});
const setApiKey = (key: string) => {
window.localStorage.setItem("lg:chat:apiKey", key);
_setApiKey(key);
};
// Determine final values to use, prioritizing URL params then env vars
const finalApiUrl = apiUrl || envApiUrl;
const finalAssistantId = assistantId || envAssistantId;
2025-04-02 13:46:41 -07:00
// Show the form if we: don't have an API URL, or don't have an assistant ID
if (!finalApiUrl || !finalAssistantId) {
2025-03-04 17:38:33 +01:00
return (
2025-03-04 17:58:46 +01:00
<div className="flex items-center justify-center min-h-screen w-full p-4">
2025-03-07 15:32:03 +01:00
<div className="animate-in fade-in-0 zoom-in-95 flex flex-col border bg-background shadow-lg rounded-lg max-w-3xl">
2025-03-04 17:38:33 +01:00
<div className="flex flex-col gap-2 mt-14 p-6 border-b">
<div className="flex items-start flex-col gap-2">
<LangGraphLogoSVG className="h-7" />
<h1 className="text-xl font-semibold tracking-tight">
2025-03-10 16:30:10 -07:00
Agent Chat
2025-03-04 17:38:33 +01:00
</h1>
</div>
<p className="text-muted-foreground">
2025-03-10 16:30:19 -07:00
Welcome to Agent Chat! Before you get started, you need to enter
the URL of the deployment and the assistant / graph ID.
2025-03-04 17:38:33 +01:00
</p>
</div>
<form
onSubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const formData = new FormData(form);
const apiUrl = formData.get("apiUrl") as string;
const assistantId = formData.get("assistantId") as string;
2025-03-04 17:58:46 +01:00
const apiKey = formData.get("apiKey") as string;
2025-03-04 17:38:33 +01:00
setApiUrl(apiUrl);
2025-03-04 17:58:46 +01:00
setApiKey(apiKey);
2025-03-04 17:38:33 +01:00
setAssistantId(assistantId);
form.reset();
}}
className="flex flex-col gap-6 p-6 bg-muted/50"
>
<div className="flex flex-col gap-2">
2025-03-05 12:17:42 -08:00
<Label htmlFor="apiUrl">
Deployment URL<span className="text-rose-500">*</span>
</Label>
2025-03-04 17:38:33 +01:00
<p className="text-muted-foreground text-sm">
This is the URL of your LangGraph deployment. Can be a local, or
production deployment.
</p>
<Input
id="apiUrl"
name="apiUrl"
className="bg-background"
defaultValue={apiUrl || DEFAULT_API_URL}
2025-03-05 12:17:42 -08:00
required
2025-03-04 17:38:33 +01:00
/>
</div>
<div className="flex flex-col gap-2">
2025-03-05 12:17:42 -08:00
<Label htmlFor="assistantId">
Assistant / Graph ID<span className="text-rose-500">*</span>
</Label>
2025-03-04 17:38:33 +01:00
<p className="text-muted-foreground text-sm">
This is the ID of the graph (can be the graph name), or
assistant to fetch threads from, and invoke when actions are
taken.
</p>
<Input
id="assistantId"
name="assistantId"
className="bg-background"
defaultValue={assistantId || DEFAULT_ASSISTANT_ID}
2025-03-05 12:17:42 -08:00
required
2025-03-04 17:58:46 +01:00
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="apiKey">LangSmith API Key</Label>
<p className="text-muted-foreground text-sm">
2025-03-05 12:17:42 -08:00
This is <strong>NOT</strong> required if using a local LangGraph
server. This value is stored in your browser's local storage and
is only used to authenticate requests sent to your LangGraph
server.
2025-03-04 17:58:46 +01:00
</p>
<PasswordInput
id="apiKey"
name="apiKey"
defaultValue={apiKey ?? ""}
className="bg-background"
placeholder="lsv2_pt_..."
2025-03-04 17:38:33 +01:00
/>
</div>
<div className="flex justify-end mt-2">
<Button type="submit" size="lg">
Continue
<ArrowRight className="size-5" />
</Button>
</div>
</form>
</div>
</div>
);
}
return (
2025-03-04 17:58:46 +01:00
<StreamSession apiKey={apiKey} apiUrl={apiUrl} assistantId={assistantId}>
2025-03-04 17:38:33 +01:00
{children}
</StreamSession>
);
};
2025-02-27 14:08:24 -08:00
// Create a custom hook to use the context
export const useStreamContext = (): StreamContextType => {
const context = useContext(StreamContext);
if (context === undefined) {
throw new Error("useStreamContext must be used within a StreamProvider");
}
return context;
};
export default StreamContext;