2025-02-27 14:08:24 -08:00
|
|
|
import React, { createContext, useContext, ReactNode } from "react";
|
|
|
|
|
import { useStream } from "@langchain/langgraph-sdk/react";
|
2025-03-03 13:51:41 -08:00
|
|
|
import { type Message } from "@langchain/langgraph-sdk";
|
2025-02-27 14:08:24 -08:00
|
|
|
import type {
|
|
|
|
|
UIMessage,
|
|
|
|
|
RemoveUIMessage,
|
|
|
|
|
} from "@langchain/langgraph-sdk/react-ui/types";
|
2025-03-03 13:51:41 -08:00
|
|
|
import { useQueryParam, StringParam } from "use-query-params";
|
2025-02-27 14:08:24 -08:00
|
|
|
|
2025-03-02 20:22:36 +01:00
|
|
|
const useTypedStream = useStream<
|
|
|
|
|
{ messages: Message[]; ui: UIMessage[] },
|
|
|
|
|
{
|
|
|
|
|
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-03 12:31:27 -08:00
|
|
|
CustomUpdateType: 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);
|
|
|
|
|
|
|
|
|
|
export const StreamProvider: React.FC<{ children: ReactNode }> = ({
|
|
|
|
|
children,
|
|
|
|
|
}) => {
|
2025-03-03 13:51:41 -08:00
|
|
|
const [threadId, setThreadId] = useQueryParam("threadId", StringParam);
|
2025-03-03 13:13:57 -08:00
|
|
|
|
2025-03-02 20:22:36 +01:00
|
|
|
const streamValue = useTypedStream({
|
2025-02-27 14:08:24 -08:00
|
|
|
apiUrl: "http://localhost:2024",
|
|
|
|
|
assistantId: "agent",
|
2025-03-03 13:51:41 -08:00
|
|
|
threadId,
|
2025-03-03 13:13:57 -08:00
|
|
|
onThreadId: setThreadId,
|
2025-02-27 14:08:24 -08:00
|
|
|
});
|
|
|
|
|
|
2025-03-03 13:51:41 -08:00
|
|
|
console.log("threadId", threadId);
|
|
|
|
|
console.log("streamValue", streamValue.values);
|
|
|
|
|
|
2025-02-27 14:08:24 -08:00
|
|
|
return (
|
|
|
|
|
<StreamContext.Provider value={streamValue}>
|
|
|
|
|
{children}
|
|
|
|
|
</StreamContext.Provider>
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// 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;
|