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

48 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-02-27 14:08:24 -08:00
import React, { createContext, useContext, ReactNode } from "react";
import { useStream } from "@langchain/langgraph-sdk/react";
import type { Message } from "@langchain/langgraph-sdk";
import type {
UIMessage,
RemoveUIMessage,
} from "@langchain/langgraph-sdk/react-ui/types";
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
};
CustomType: UIMessage | RemoveUIMessage;
}
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-02 20:22:36 +01:00
const streamValue = useTypedStream({
2025-02-27 14:08:24 -08:00
apiUrl: "http://localhost:2024",
assistantId: "agent",
});
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;