Skip to main content
userTourKit
@tour-kit/ai

API Reference

Complete API reference for @tour-kit/ai: client hooks, server utilities, chat components, and configuration types

domidex01Published

Complete public API surface for @tour-kit/ai, split by entry point. Server-only utilities live under @tour-kit/ai/server so they don't leak into the browser bundle. Types referenced here are exported from the same entry point unless otherwise noted.

Entry points

Import pathRuns inContains
@tour-kit/aiBrowser + NodeProvider, hooks, components, types, client-side rate limiter
@tour-kit/ai/serverNode / Edge onlycreateChatRouteHandler, RAG pipeline, embedding utilities, server rate limiter
@tour-kit/ai/headlessBrowser + NodeHeadless primitive variants (no styling)

Client Exports (@tour-kit/ai)

Provider

<AiChatProvider config={...}>

Root provider. Must wrap any component that uses useAiChat or useTourAssistant. Connects to the server route specified in config.endpoint.

Config fieldTypeDefaultNotes
endpointstringRequired. URL of the createChatRouteHandler route (e.g. /api/chat).
tourContextbooleanfalseWhen true, includes the active tour's TourAssistantContext in every request. Required for useTourAssistant server-side context.
initialMessagesUIMessage[][]Pre-populate the chat history.
rateLimiterSlidingWindowRateLimiter | nullnullOptional client-side rate limiter. Returns 429 to sendMessage when over budget.

Hooks

useAiChat(): UseAiChatReturn

Core chat hook. Must be used within AiChatProvider.

PropertyTypeDescription
messagesUIMessage[]Chat message history
sendMessage(input: { text: string }) => voidSend a user message
statusChatStatus'ready' | 'submitted' | 'streaming' | 'error'
errorError | nullCurrent error, if any
stop() => voidStop the current generation
reload() => voidRegenerate the last response
setMessages(messages: UIMessage[]) => voidReplace message history (pass [] to clear)
isOpenbooleanWhether the chat panel is open
open() => voidOpen the chat panel
close() => voidClose the chat panel
toggle() => voidToggle the chat panel

Throws if called outside an <AiChatProvider>.

useAiChatContext(): AiChatContextValue

Lower-level escape hatch — returns the raw context value. Use useAiChat instead unless you're building a custom hook.

useTourAssistant()

Tour-aware chat hook. Extends useAiChat with tour context.

Returns UseTourAssistantReturn (extends UseAiChatReturn):

PropertyTypeDescription
tourContextTourAssistantContextCurrent tour state
isLoadingbooleanWhether the assistant is loading
suggestionsstring[]Contextual suggestions based on current step
askAboutStep() => voidAsk the AI about the current tour step
askForHelp(topic?: string) => voidAsk for help, optionally on a topic
...all UseAiChatReturn properties

useSuggestions(): UseSuggestionsReturn

AI-generated follow-up suggestions based on the current conversation. Throws if no provider is mounted.

PropertyTypeDescription
suggestionsstring[]Current suggestions
isLoadingbooleanLoading state

useOptionalSuggestions(): UseSuggestionsReturn | null

Same as useSuggestions but returns null instead of throwing when no provider is mounted. Use in optional/conditional UI.

Components

All components are shadcn/ui-compatible and accept standard className overrides.

ComponentPurpose
<AiChatPanel>Full chat surface — header, message list, input, suggestions
<AiChatToggle>Floating button that toggles the panel
<AiChatHeader>Header bar — title, close button, optional menu
<AiChatMessageList>Renders messages[] with autoscroll
<AiChatMessage>Single message row (user or assistant)
<AiChatInput>Text input + send button + status indicator
<AiChatSuggestions>Renders suggested follow-up chips
<AiChatPortal>Portal wrapper for the panel (used internally by <AiChatPanel>)

See Components for prop tables.

Client utilities

SlidingWindowRateLimiter

Class implementing sliding-window rate limiting. Pass an instance to AiChatProvider.config.rateLimiter to enforce per-user limits before the request leaves the browser.

createRateLimiter(config): SlidingWindowRateLimiter

Factory function. config accepts { maxRequests, windowMs }.

createAnalyticsBridge(config)

Subscribes to AI chat events (message_sent, message_received, error) and forwards them to the @tour-kit/analytics tracker.

Server Exports (@tour-kit/ai/server)

Route handling

createChatRouteHandler(options): { POST }

Returns an object with a Next.js / Edge-compatible POST handler. The handler:

  1. Parses the incoming { messages, tourContext? } payload.
  2. Runs the configured rate limiter (if any).
  3. Builds the system prompt from instructions + retrieved context.
  4. Streams the model response back as Server-Sent Events.
OptionTypeRequiredNotes
modelLanguageModelV1yesAny AI SDK model — openai('gpt-4o-mini'), anthropic('claude-sonnet-4-5'), etc.
context.strategy'context-stuffing' | 'rag'yesPicks CAG or RAG mode.
context.documentsDocument[]yes for CAGAll docs to inject (CAG) or to index (RAG seed).
context.embeddingEmbeddingyes for RAGOutput of createAiSdkEmbedding.
context.vectorStoreVectorStoreAdapteryes for RAGOutput of createInMemoryVectorStore or your own adapter.
context.topKnumberno (RAG only)Chunks to retrieve per query. Default 5.
instructions.productNamestringnoUsed in the default system prompt.
instructions.tone'friendly' | 'professional' | 'concise'noHints to the model.
instructions.boundariesstring[]noHard rules ("only answer X", "never reveal Y").
rateLimiterServerRateLimiternoPre-check before model call. Returns 429 when exceeded.
// app/api/chat/route.ts
import { createChatRouteHandler } from '@tour-kit/ai/server'
import { openai } from '@ai-sdk/openai'

const { POST } = createChatRouteHandler({
  model: openai('gpt-4o-mini'),
  context: {
    strategy: 'context-stuffing',
    documents: [{ id: 'doc-1', content: '...' }],
  },
  instructions: {
    productName: 'My App',
    tone: 'friendly',
    boundaries: ['Only answer questions about My App onboarding.'],
  },
})

export { POST }

RAG pipeline

createInMemoryVectorStore(): VectorStoreAdapter

In-memory vector store. Re-built on every server restart — for dev and prototypes only. Implements the VectorStoreAdapter interface so it's swappable with pgvector, Pinecone, or your own store.

createAiSdkEmbedding(options): Embedding

Embedding adapter wrapping the AI SDK's embedding API. Options:

OptionTypeNotes
modelstringEmbedding model id (e.g. 'text-embedding-3-small'). See the RAG guide for recommendations.
providerEmbeddingProviderOptional explicit provider; defaults to OpenAI.

createRetriever(options): Retriever

Convenience wrapper around { vectorStore, embedding, topK } for use outside createChatRouteHandler (e.g. background jobs that surface "you might be interested in" suggestions).

chunkDocument(doc, options) / chunkDocuments(docs, options)

Splits documents into chunks suitable for embedding. Options: { chunkSize, overlap }. Recommended starting values: chunkSize: 512, overlap: 50.

createRAGMiddleware(options)

Lower-level building block — produces middleware that injects retrieved context into a chat request. Use when you need to compose RAG with custom request handling outside createChatRouteHandler.

Server utilities

createSystemPrompt(config): string

Builds the structured system prompt that createChatRouteHandler uses internally. Export it if you want to log, audit, or modify the final prompt before forwarding to the model.

createServerRateLimiter(config): ServerRateLimiter

Server-side rate limiter. Pass an instance to createChatRouteHandler.rateLimiter. Pairs with createInMemoryRateLimitStore or your own Redis-backed store.

createInMemoryRateLimitStore(): RateLimitStore

In-memory rate-limit store. Scoped to a single Node process — for production use a Redis-backed store across instances.

generateSuggestions(options) / parseSuggestions(text)

Generate and parse AI follow-up suggestion chips. generateSuggestions calls the model with a structured prompt; parseSuggestions extracts the suggestion array from a raw response.

Types

The full type definitions live in packages/ai/src/types. The most commonly imported types:

import type {
  // Provider config
  AiChatConfig,
  // Hook returns
  UseAiChatReturn,
  UseTourAssistantReturn,
  UseSuggestionsReturn,
  // Context shapes
  AiChatContextValue,
  TourAssistantContext,
  // Server
  ChatRouteHandlerOptions,
  VectorStoreAdapter,
  Document,
  Embedding,
  Retriever,
  // Status
  ChatStatus,
} from '@tour-kit/ai'
Free & open source

Ship onboarding, not config.

npm i @tour-kit/core is MIT and free. The Pro packages work unlicensed too — a one-time $99 license removes the production watermark when you ship.

MIT-licensed — no signup, no credit card. Pay once, only when you ship.