Brainlaq
Brainlaq20h ago

transfer class instances

The AI SDK uses the Chat class as the abstraction that one is supposed to share: https://ai-sdk.dev/cookbook/next/use-shared-chat-context the useChat hook needs the same reference in order to not rerender: https://github.com/vercel/ai/blob/e15b5458f1aaced8ea854823044ea3d125dcaac8/packages/react/src/use-chat.ts#L67 My current soultion is to wrap trpc with a "normal" useQuery
export function useChatInstanceQuery(chatId?: string) {
const trpc = useTRPC();
const getToken = useGetToken();
const queryClient = useQueryClient();

const query = useQuery({
queryKey: ["chats", chatId],
staleTime: Infinity,
queryFn: chatId
? async () => {
const messages = await queryClient.fetchQuery(
trpc.getChatHistory.queryOptions({ chatId }),
);

const chat = createChat({ chatId, getToken, messages });
return chat;
}
: skipToken,
});
return query;
}
export function useChatInstanceQuery(chatId?: string) {
const trpc = useTRPC();
const getToken = useGetToken();
const queryClient = useQueryClient();

const query = useQuery({
queryKey: ["chats", chatId],
staleTime: Infinity,
queryFn: chatId
? async () => {
const messages = await queryClient.fetchQuery(
trpc.getChatHistory.queryOptions({ chatId }),
);

const chat = createChat({ chatId, getToken, messages });
return chat;
}
: skipToken,
});
return query;
}
Is there another (better?) way? i thought about adding conditional logic in the transformer that checks for
`instanceof Chat
`instanceof Chat
on the backend I am unsure how to do this client side and if this a good approach in generel.
Share useChat State Across Components
Learn how to share a chat instance across multiple components with useChat and easily reset the chat.
GitHub
ai/packages/react/src/use-chat.ts at e15b5458f1aaced8ea854823044ea3...
The AI Toolkit for TypeScript. From the creators of Next.js, the AI SDK is a free open-source library for building AI-powered applications and agents - vercel/ai
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?