npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

gentiq

v0.16.3

Published

React UI library for the Gentiq AI framework.

Readme

Gentiq React SDK

The core React library for building premium, production-ready AI chatbot interfaces.

gentiq provides a set of highly modular conversational components built on top of Vercel AI SDK and Vite. It offers both a complete, drop-in UI and granular "slots" for building highly customized conversational flows.


📦 Installation

npm install gentiq
# or
pnpm add gentiq

Peer dependencies. gentiq keeps react, react-dom, react-router-dom, ai, @ai-sdk/react, @tanstack/react-query, i18next, react-i18next, next-themes and sonner as peer dependencies — each one holds a React context or a module singleton that silently breaks if two copies end up in the bundle. npm ≥7 installs them for you; pnpm and Yarn users must add them explicitly.

Math. KaTeX's stylesheet is not re-published by this package. If your agent emits LaTeX, add katex (an optional peer dependency) to your own dependencies and import its stylesheet yourself, so your bundler emits its 60 font faces as separate cacheable files instead of ~1.4 MB of inlined base64:

import 'katex/dist/katex.min.css';

🚀 Quick Start

import { GentiqProvider, ChatUI, RequireAuth, UserLoginPage } from 'gentiq';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import 'gentiq/style.css';

export default function App() {
  return (
    <GentiqProvider
      app={{ name: 'My AI', version: '1.2.3', cacheNamespace: 'my_app' }}
    >
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<UserLoginPage />} />
          <Route path="/*" element={
            <RequireAuth>
               <ChatUI />
            </RequireAuth>
          } />
        </Routes>
      </BrowserRouter>
    </GentiqProvider>
  );
}

If you already expose your app version at build time, pass that value here so Gentiq reuses the same source of truth.

Authentication

Nothing to configure: the built-in adapter keeps the JWT in localStorage, namespaced under app.cacheNamespace (default gentiq) so it cannot collide with your host application's own token key. Pass your own adapter only when the token lives somewhere else — a cookie, an external identity provider, your host app's session store:

const cookieAuthAdapter = {
  getToken: () => readCookie('session'),
  setToken: (token: string) => writeCookie('session', token),
  clearToken: () => deleteCookie('session'),
  // Optional — defaults to `Authorization: Bearer <getToken()>`
  getHeaders: () => ({ Authorization: `Bearer ${readCookie('session')}` }),
};

<GentiqProvider api={{ authAdapter: cookieAuthAdapter }}>…</GentiqProvider>

api.basePath (default /api) points the client — including the admin panel — at your backend. In development the templates proxy /api through the Vite dev server, which keeps everything same-origin.

A platform that signs its own users in hands the chat a login code as ?code=, which RequireAuth exchanges for a session. A page loaded again with a code it already used keeps the session it holds for that same user. When there is no usable session, RequireAuth redirects to /login; a deployment whose users only ever arrive that way can show its own screen instead:

<RequireAuth fallback={(reason) => <ReopenFromPortal reason={reason} />}>
  <ChatUI />
</RequireAuth>

reason is handoff_failed (the code or token in the URL could not be used), session_expired or signed_out.


🎨 Extreme Customization (Slots)

Gentiq is designed to be "hacked" at any level. Using the components prop, you can surgically replace internal components with your own implementation.

UI Slot Overrides

Replace message bubbles, input areas, or the entire message list without forking the library.

import type { GentiqComponents, TextPartProps } from 'gentiq';

const MyBrandedTextBubble = ({ part, message }: TextPartProps) => (
  <div className={`p-4 rounded-3xl ${message.role === 'user' ? 'bg-blue-600 text-white' : 'bg-gray-100'}`}>
    <p>{part.text}</p>
  </div>
);

const components: GentiqComponents = {
  TextPart: MyBrandedTextBubble,
  WelcomeScreen: () => <div className="p-20 text-center"><h1>Welcome to My AI</h1></div>,
  // Override the input area entirely
  PromptInput: ({ onSend, status, stop }) => (
    <input
      disabled={status === 'streaming'}
      onKeyDown={(e) => e.key === 'Enter' && onSend(e.currentTarget.value)}
    />
  )
};

<ChatUI components={components} />

The full slot list is MessageList, PromptInput, WelcomeScreen, TextPart, ReasoningPart, ToolPart, FilePart, ReferencePart, ChoiceQuestionPart, ChoiceQuestionDock, ChatError and HeaderActions (plus headerActions, its admin-switchable form). Every slot's props are exported as a type (TextPartProps, PromptInputProps, …), so TypeScript will tell you when you reach for a prop that is not there.

Upgrade Prompts When a Limit Is Reached

When a turn is refused, the chat shows a one-line notice under the transcript. Replace it with ChatError to offer an upgrade instead. The error keeps the server's code and details (for quota_exceeded: meter, limit, used, window, resets_at, plan), and its message is already localized. Render the stock ChatError for everything you don't handle.

import { ChatError, isGentiqError, type ChatErrorProps, type GentiqComponents } from 'gentiq';

const UPGRADE_CODES = ['quota_exceeded', 'credits_exhausted', 'plan_expired'];

function LimitReached(props: ChatErrorProps) {
  const { error, code, chat } = props;
  if (!code || !UPGRADE_CODES.includes(code)) return <ChatError {...props} />;

  const details = isGentiqError(error) ? (error.details as { plan?: { key: string } | null }) : null;
  return (
    <div className="rounded-xl border p-4">
      <p>{error.message}</p>
      <a href={`/billing/upgrade?from=${details?.plan?.key ?? ''}`}>Upgrade your plan</a>
      <button onClick={chat?.clearError}>Dismiss</button>
    </div>
  );
}

const components: GentiqComponents = { ChatError: LimitReached };

useGentiqChat().error carries the same code and details, for apps that build their own chat surface.

Buttons in the Top Bar

HeaderActions adds your own controls to the top bar, before the usage meter, new-chat and settings buttons — an "Upgrade" button, a link to billing, a help menu. It is not rendered on shared-chat pages. It receives isMobile: the logo sits in the middle of the bar, so on a phone keep it to one icon-sized button.

import { useGentiqEntitlement, type GentiqComponents, type HeaderActionsProps } from 'gentiq';

function UpgradeButton({ isMobile }: HeaderActionsProps) {
  const { data: access } = useGentiqEntitlement();
  // Only offer it to users on your free plan.
  if (access?.plan?.key !== 'free') return null;

  return (
    <a href="/billing/upgrade" className="rounded-lg bg-primary px-3 py-1.5 text-sm text-primary-foreground">
      {isMobile ? '⚡' : 'Upgrade'}
    </a>
  );
}

<GentiqProvider components={{ HeaderActions: UpgradeButton }} /* ... */>

Pass it to GentiqProvider so every chat page gets it; <ChatUI components={{ HeaderActions }} /> works too, and takes precedence.

Register the control under headerActions instead and the admin panel gains a switch for it, under Settings › Chat › Top Bar Buttons. Turning it off stops it being rendered, without a deploy and without the component knowing anything about it:

<GentiqProvider
  components={{
    headerActions: [
      {
        id: 'upgrade',
        component: UpgradeButton,
        // Plain text, or an i18n key — both name the admin's switch.
        label: 'chat:upgrade_plan',
        help: 'Links users on the free plan to the billing page.',
        // What applies until an admin first touches the switch.
        defaultEnabled: true,
      },
    ],
  }}
  /* ... */
>

Registered actions render after the HeaderActions slot, in the order given, and the two can be used together. The admin's choice is stored per id, so renaming an id resets it.

Markdown & Tool Customization

You can even intercept markdown rendering or provide custom dashboards for specific AI tool calls.

import { asLoosePart, type GentiqComponents } from 'gentiq';

const components: GentiqComponents = {
  // Custom markdown component overrides (passed through to streamdown)
  textComponents: {
    code: ({ children }) => <pre className="my-custom-code">{children}</pre>,
  },
  // Custom UI for specific tools, keyed by the backend tool's name.
  // `asLoosePart` is the typed view of a message part: the AI SDK's part union
  // does not surface tool `input`/`output`/`state` uniformly.
  toolComponents: {
    get_weather: ({ part }) => {
      const { output } = asLoosePart(part);
      if (!output) return null; // still streaming
      const { city, temperature } = output as { city: string; temperature: number };
      return (
        <div className="weather-card">
          <h3>{city}</h3>
          <p>{temperature}°C</p>
        </div>
      );
    },
  },
  // Inject remark/rehype plugins
  remarkPlugins: [remarkGfm],
};

A tool component renders against a partially-streamed part, so it is the most likely thing in the tree to throw. Gentiq already wraps each one in an ErrorBoundary — let render errors propagate rather than wrapping JSX in a try/catch, which would not catch them anyway.

Markdown links are sanitized down to the schemes GitHub allows. To render a component off a custom scheme, list it in linkProtocols and handle it in textComponents.a.

References for Text, Tools, and Custom Cards

Gentiq includes a built-in reference UX similar to modern AI chat apps. Users can select text in previous messages, click the reference action, and Gentiq will add a compact quote chip to the composer. When the message is sent, the referenced context is sent to the backend/model and shown as a clickable badge in the chat.

For normal text messages, this works automatically. For custom cards, use Referenceable or useChatReferences so Gentiq knows exactly what should be referenced and how it should appear to the user.

Reference a custom card

Use Referenceable when your component has a clear card-like boundary. Gentiq will add a hover reference action, register the source for click-to-highlight, and send the structured reference with the next user message.

import { Referenceable } from 'gentiq';

function CarCard({ car }) {
  return (
    <Referenceable
      reference={{
        kind: 'car',
        sourceId: `car-${car.id}`,
        label: 'Car',
        excerpt: `${car.year} ${car.make} ${car.model} · ${car.price}`,
        data: {
          carId: car.id,
          make: car.make,
          model: car.model,
          year: car.year,
          price: car.price,
        },
      }}
    >
      <div className="car-card">
        <CarImageCarousel images={car.images} />
        <h3>{car.year} {car.make} {car.model}</h3>
        <p>{car.price}</p>
      </div>
    </Referenceable>
  );
}

excerpt is the human-readable text shown in the composer chip and reference badge. data is optional structured context, useful for IDs or machine-readable values like { carId }.

Use your own reference button

If you do not want the built-in hover action, call addReference yourself. Keep the sourceId on the element you want highlighted later.

import { useChatReferences } from 'gentiq';

function CarCard({ car }) {
  const { addReference } = useChatReferences();

  const reference = {
    kind: 'car',
    sourceId: `car-${car.id}`,
    label: 'Car',
    excerpt: `${car.year} ${car.make} ${car.model} · ${car.price}`,
    data: { carId: car.id },
  };

  return (
    <div data-gentiq-reference-source-id={reference.sourceId}>
      <CarImageCarousel images={car.images} />
      <h3>{car.year} {car.make} {car.model}</h3>

      <button type="button" onClick={() => addReference(reference)}>
        Reference this car
      </button>
    </div>
  );
}

Customize tool/card reference text

For tool-rendered cards, use referenceAdapters to control what appears in the composer and sent reference context. This avoids showing raw JSON to users.

const components: GentiqComponents = {
  toolComponents: {
    get_weather: WeatherCard,
  },
  referenceAdapters: {
    get_weather: ({ part }) => ({
      label: 'Weather',
      excerpt: `Weather: ${part.output.city}: ${part.output.condition}`,
      data: {
        city: part.output.city,
        condition: part.output.condition,
      },
    }),
  },
};

<ChatUI components={components} />

For markdown patterns like [CarCard](car_id), render your CarCard from the markdown override, fetch the car data as usual, and wrap the rendered card with Referenceable as shown above.


⚓ Headless Mode

If you need complete control over the UI, use the useGentiqChat hook. It handles all the complex synchronization with the Vercel AI SDK and Gentiq's persistence backend while leaving the rendering to you. It must be called inside GentiqProvider.

import { useState } from 'react';
import { useGentiqChat } from 'gentiq';

export const CustomChat = () => {
  const { messages, sendMessage, stop, status, error } = useGentiqChat();
  const [input, setInput] = useState('');
  const busy = status === 'streaming' || status === 'submitted';

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          {m.parts
            .filter((part) => part.type === 'text')
            .map((part) => part.text)
            .join('')}
        </div>
      ))}

      {error && <p role="alert">{error.message}</p>}

      <input value={input} onChange={(e) => setInput(e.target.value)} />
      <button
        onClick={() => {
          sendMessage(input);
          setInput('');
        }}
        disabled={busy}
      >
        Send
      </button>
      {busy && <button onClick={stop}>Stop</button>}
    </div>
  );
};

Messages are AI SDK v7 UIMessages: the content lives in m.parts, not on a content string. sendMessage(text, files?, references?) is the only send path — it also creates the thread, updates the history sidebar and attaches staged references. status is 'idle' | 'loading-history' | 'ready' | 'submitted' | 'streaming' | 'error' (exported as ChatStatus), and error is already localized. Use clearError() to dismiss it (it clears the AI SDK's error too, which is where network and HTTP failures land).

For error handling that branches on what failed, GentiqError, GentiqErrorCode, isGentiqError and getLocalizedErrorMessage are exported, so you never have to match on message strings.


🔐 Admin & Shared Views

Gentiq includes production-grade views for administration and public sharing.

  • <AdminPanel />: A complete dashboard, customizable with extraPages and disabledPages. Imported from the gentiq/admin subpath so it is not bundled into apps that do not use it.
  • <SharedChatView />: A read-only view for public conversation links.
import { AdminPanel } from 'gentiq/admin';
import { SharedChatView } from 'gentiq';

<Route
  path="/admin/*"
  element={
    <AdminPanel
      extraPages={[{ path: 'metrics', label: 'Metrics', element: <MyMetrics /> }]}
      disabledPages={['chat_history']}
    />
  }
/>
<Route path="/shared/:shareId" element={<SharedChatView />} />

On a fresh database the panel shows a one-time setup screen that creates the first admin and signs you in. That account is granted every permission; admins created after it get only the permissions you assign. Built-in page ids are analytics, chat_history, user_management, admin_management, jobs and settings.


🌍 Advanced Theming & i18n

Support multiple languages (including RTL) and customize your brand's unique look.

<GentiqProvider
  theme={{
    defaultTheme: 'system',
    accent: '#6366f1',
    radius: 20,
    loader: 'orb',
    typography: {
      fontFamily: {
        en: 'Inter, sans-serif',
        fa: 'Vazirmatn, sans-serif' // Built-in RTL support
      }
    }
  }}
  i18n={{
    resources: {
      en: { chat: { input_placeholder: "Ask me anything..." } },
      fa: { chat: { input_placeholder: "هرچیزی میخواهی بپرس..." } }
    }
  }}
>
  <ChatUI />
</GentiqProvider>

loader chooses the indicator shown while the assistant is composing a reply and while a conversation loads: dots (the default), orb, triangle, cross, comet or aurora. Every variant has a still resting state, so a visitor who has asked for reduced motion still sees that something is happening. Admins can change it from the settings page without a redeploy.

defaultTheme accepts system, light, or dark. Appearance preferences are resolved in this order: the user's saved preference, the defaults configured in the admin settings page, the theme values passed to GentiqProvider, and finally Gentiq's built-in defaults.

Gentiq writes --gentiq-primary, --gentiq-radius and --gentiq-font-family onto the document root at runtime, so configure appearance here rather than redeclaring those custom properties in your own stylesheet.

Right-to-left layout switches automatically for Arabic, Persian, Hebrew, Urdu and the rest of the built-in RTL table; extend it with app.rtlLanguages.

Gentiq ships translations for thirteen languages — English, Chinese, Hindi, Spanish, Arabic, French, Bengali, Portuguese, Russian, Urdu, Indonesian, German and Persian — and every language picker offers all of them by default. Narrow that with app.languages when a deployment only serves a few, and set the one new visitors start in with app.language:

<GentiqProvider
  app={{
    language: 'fa',            // what a first-time visitor sees
    languages: ['fa', 'en'],   // what they can switch between
  }}
>

Codes with no bundle behind them are ignored, and the active language always stays selectable. Leave languages unset to offer everything, including any locale you register through i18n.resources. Only the language in use is downloaded — each of the other twelve is a separate chunk fetched on demand — so offering all thirteen costs nothing until someone picks one.


👥 Custom User Metadata Fields

Easily extend user profiles and signup forms with your own fields. Gentiq handles the state, validation, and conditional visibility (branching logic) automatically.

<GentiqProvider
  app={{
    userMetadataFields: [
      {
        key: 'organization',
        label: 'settings:profile.organization',
        type: 'text',
        placeholder: 'Enter your company name',
        showInSignup: true,
        showInProfile: true,
      },
      {
        key: 'role',
        label: 'settings:profile.role',
        type: 'select',
        options: [
          { label: 'Developer', value: 'dev' },
          { label: 'Manager', value: 'manager' },
        ],
        // Field only shown if organization is provided
        condition: { field: 'organization', operator: 'not_equals', value: '' },
        showInSignup: true,
        showInProfile: true,
      }
    ]
  }}
>
  <ChatUI />
</GentiqProvider>

Personalized Greetings

Use a functional greeting to personalize the built-in welcome screen. Gentiq loads and caches the authenticated profile for you:

<GentiqProvider
  welcome={{
    greeting: ({ firstName, t }) =>
      t(firstName ? 'chat:welcome.named' : 'chat:welcome.default', {
        firstName,
      }),
  }}
  i18n={{
    resources: {
      en: {
        chat: {
          welcome: {
            default: 'How can I help you today?',
            named: 'Hi {{firstName}}, how can I help you today?',
          },
        },
      },
    },
  }}
>
  <ChatUI />
</GentiqProvider>

For custom screens or other components, use the same profile data directly:

import { useGentiqUser } from 'gentiq';

function MyWelcomeScreen() {
  const { user, firstName, isLoading, error } = useGentiqUser();

  if (isLoading) return null;
  if (error) return <h1>Welcome!</h1>;

  return <h1>Welcome, {firstName || user?.phone}!</h1>;
}

Typing-Effect Prompts

Rotating example prompts type themselves out in the composer's placeholder on the new-chat screen, cycling through any number of messages. Gentiq ships a default set translated into every supported language, so this works out of the box with nothing configured.

welcome.typingPrompts overrides that list. Set it to a string array, or to a function that receives the authenticated user so the messages can be conditioned on user info. Each entry is passed through t(), so i18n keys work directly. Pass an empty array to turn the effect off and keep the static placeholder. It is independent of the static welcome.subtitle, which keeps rendering under the greeting.

To change the defaults per language rather than replace them wholesale, override the chat:welcome.typing_prompts key for the languages you care about:

<GentiqProvider
  i18n={{
    resources: {
      de: {
        chat: {
          welcome: {
            typing_prompts: ['Fasse ein Dokument zusammen', 'Schreib eine E-Mail'],
          },
        },
      },
    },
  }}
>
// Static list
<GentiqProvider
  welcome={{
    greeting: 'Welcome back',
    typingPrompts: [
      'Ask me anything…',
      'Summarize a document',
      'Draft an email',
    ],
  }}
>
  <ChatUI />
</GentiqProvider>

// Conditioned on the authenticated user
<GentiqProvider
  welcome={{
    greeting: 'Welcome back',
    typingPrompts: ({ firstName }) =>
      firstName
        ? [`Ask me anything, ${firstName}…`, 'Summarize a document', 'Draft an email']
        : ['Ask me anything…', 'Summarize a document', 'Draft an email'],
  }}
>
  <ChatUI />
</GentiqProvider>

The function receives the same context as the personalized greeting ({ user, firstName, isLoading, t }). The typewriter respects the user's prefers-reduced-motion setting, swapping whole messages instead of animating each character when reduced motion is requested.


📄 License

Gentiq is open-source software licensed under the Apache 2.0 License.