UNPKG

@langgraph-js/sdk

Version:

The UI SDK for LangGraph - seamlessly integrate your AI agents with frontend interfaces

81 lines (80 loc) 2.93 kB
import { createContext, useContext, createMemo, onMount, createComponent } from "solid-js"; import { createChatStore } from "../ui-store/index.js"; import { useStore } from "@nanostores/solid"; const ChatContext = createContext(undefined); export const useChat = () => { const context = useContext(ChatContext); if (!context) { throw new Error("useChat must be used within a ChatProvider"); } return context; }; /** * @zh useUnionStore Hook 用于将 nanostores 的 store 结构转换为更易于在 UI 组件中使用的扁平结构。 * @en The useUnionStore Hook is used to transform the nanostores store structure into a flatter structure that is easier to use in UI components. */ export const useUnionStoreSolid = (store, useStore) => { const data = Object.fromEntries(Object.entries(store.data).map(([key, value]) => { return [key, useStore(value)]; })); return { ...data, ...store.mutations, }; }; export const ChatProvider = (props) => { // 使用 createMemo 稳定 defaultHeaders 的引用 const stableHeaders = createMemo(() => props.defaultHeaders || {}); // 使用 createMemo 创建 fetch 函数 const F = createMemo(() => { const baseFetch = props.fetch || globalThis.fetch; return props.withCredentials ? (url, options) => { options.credentials = "include"; return baseFetch(url, options); } : baseFetch; }); const store = createMemo(() => { const config = { apiUrl: props.apiUrl || "http://localhost:8123", defaultHeaders: stableHeaders(), callerOptions: { fetch: F(), maxRetries: 1, }, legacyMode: props.legacyMode || false, }; /** @ts-ignore */ if (props.client) config.client = props.client; return createChatStore(props.defaultAgent || "", config, { showHistory: props.showHistory || false, showGraph: props.showGraph || false, fallbackToAvailableAssistants: props.fallbackToAvailableAssistants || false, autoRestoreLastSession: props.autoRestoreLastSession || false, }); }); const unionStore = useUnionStoreSolid(store(), useStore); // 初始化标志 let initialized = false; onMount(() => { if (initialized) { return; } initialized = true; unionStore.initClient().catch((err) => { console.error(err); if (props.onInitError) { props.onInitError(err, unionStore.currentAgent()); } }); }); // 使用 createComponent 创建 Provider 组件 return createComponent(ChatContext.Provider, { value: unionStore, get children() { return props.children; }, }); };