UNPKG

@kontext.dev/kontext-sdk

Version:

Unified SDK for AI-powered context and personalization

142 lines (104 loc) 4.34 kB
# Kontext SDK Kontext's TypeScript SDK for shipping personalized AI experiences. It bundles a first-class server client, React hooks, UI components, and dataset helpers so you can connect end-user context to any LLM quickly. ## Highlights - **Kontext client** – fetch per-user context with `profile.getProfile`, control privacy, and surface typed errors for consent flows. - **Vault access** – upload, search, and clean user datasets with a lightweight file-first API. - **React toolkit** – hydrate context in the browser with `KontextProvider`, stateful hooks, and drop-in OAuth helpers. - **UI components** – ship polished `KontextConnectButton` and `KontextStatus` widgets that follow the dashboard design system. - **Realtime updates** – subscribe to live context deltas with `useRealtimeContext` or fall back to polling. ## Installation ```bash pnpm add @kontext.dev/kontext-sdk # or npm i / yarn add ``` Set `KONTEXT_API_KEY` on the server. For browser usage, expose `NEXT_PUBLIC_KONTEXT_API_KEY` only when you need client-side connections. ## Server usage ```ts import { Kontext } from '@kontext.dev/kontext-sdk'; const kontext = new Kontext({ apiKey: process.env.KONTEXT_API_KEY!, apiUrl: process.env.KONTEXT_API_URL ?? 'https://api.kontext.dev', }); const context = await kontext.profile.getProfile({ userId: 'user_123', task: 'chat', userQuery: message, // improves retrieval per turn privacyLevel: 'moderate', }); llm.chat({ messages: [ { role: 'system', content: context.systemPrompt }, { role: 'user', content: message }, ], }); ``` Handle consent and auth failures gracefully: ```ts try { await kontext.profile.getProfile({ userId }); } catch (error) { if (error.code === 'UNAUTHORIZED_USER') { // Prompt the user to connect their account first } } ``` Call `kontext.users.purge({ userId })` (or `kontext.disconnect(userId)`) to remove stored context for a user. ## Vault operations `Kontext` ships with a `vault` client for ingesting and querying user-linked data. ```ts const upload = await kontext.vault.upload({ userId: 'user_123', file: new Blob([pdfBuffer]), }); const status = await kontext.vault.getFileStatus({ fileId: upload.fileId }); const answer = await kontext.vault.query({ userId: 'user_123', query: 'latest roadmap', includeAnswer: true, }); ``` Use `deleteFile`, `clearVault`, or `kontext.users.purge` to honor privacy requests. ## React integration ```tsx import { KontextProvider, useKontext, useKontextProfile } from '@kontext.dev/kontext-sdk/react'; import { KontextConnectButton } from '@kontext.dev/kontext-sdk/components'; export function App() { return ( <KontextProvider apiKey={process.env.NEXT_PUBLIC_KONTEXT_API_KEY} apiUrl={process.env.NEXT_PUBLIC_KONTEXT_API_URL} > <Chat /> </KontextProvider> ); } function Chat() { const { isConnected, connectGmail } = useKontext(); const { systemPrompt, refresh } = useKontextProfile(); if (!isConnected) { return <KontextConnectButton onError={(err) => console.error(err)} />; } return <ChatWindow systemPrompt={systemPrompt} onRefresh={refresh} onReconnect={connectGmail} />; } ``` `useKontextProfile` exposes cached profiles with a `refresh()` helper when you need explicit re-hydration. ## UI components ```tsx import { KontextStatus } from '@kontext.dev/kontext-sdk/components'; <KontextStatus variant="badge" showDisconnect />; ``` Components auto-detect light/dark themes and expose minimal props (labels, variants, callbacks) so they blend into existing design systems. ## Realtime context ```ts import { useRealtimeContext } from '@kontext.dev/kontext-sdk/react'; const { isConnected, recentUpdates } = useRealtimeContext({ enabled: true, onUpdate: (event) => console.log('Context change', event), }); ``` Switch to `usePollingContext` for environments where WebSockets are unavailable. ## Troubleshooting - **401 Unauthorized** – ensure the user completed OAuth; `useKontext().connectGmail()` handles the loop. - **High token usage** – send a concise `userQuery` each turn and cap `maxTokens`. - **CORS errors** – add your app origin in the Kontext dashboard; changes propagate within ~60 seconds. For advanced flows (dataset seeding, analytics, batch exports), visit https://docs.kontext.dev.