AI Chat
A complete AI workspace: chat with streaming Markdown, voice in and out, image generation, and a managed document
library that grounds answers in your own files. This is the pack-ai-chat pack. It is the largest pack in the catalog,
and the one the Aether template is built on.
What you need
- An OpenAI API key. It covers text, transcription, speech, realtime voice, and embeddings out of the box.
- Optionally Anthropic or Google keys, to route the text model elsewhere.
- A billing pack. Usage is metered against the organization's plan, so this pack depends on the
pack-billingfamily and refuses to install without one. - Postgres, Valkey, and RustFS (uploads and generated images land in a private bucket).
What it depends on
- A starter pack, for auth, organizations, and permissions.
- A billing pack: Stripe, Lemon Squeezy, or Polar.
What you get
/chat: conversation history, streaming responses, dictation, read-aloud, and image generation, on web and in the Expo app./knowledge: upload documents, watch them index, and have answers cite them. Versioned, with per-organization limits.- Durable execution. Every run and tool call is a row, so a run that dies mid-stream is recovered by a job, and cancellation is a state change, not a dropped socket.
- Usage accounting per organization: tokens, operations, voice minutes, and storage, reserved before a run and settled after, against caps from the plan.
- In the admin app: an AI usage dashboard with 30-day charts, a workspace leaderboard against plan caps, and an AI usage tab on every organization for its allowance and model mix.
Background work
Document indexing runs on the template's task queue. Every upload becomes one
knowledge-indexing task, written in the same transaction as the upload, so a file is never "queued" with nothing
behind it. Each backend instance indexes KNOWLEDGE_INDEXING_CONCURRENCY documents at a time (2 by default), so one
slow PDF does not hold up everyone else. A failed run retries with backoff and resumes from the last embedded batch.
After 5 retries the file shows as failed with a Try again button. A file no retry can fix (no text, too many pages)
fails right away with the reason.
Two cron jobs register with the template's scheduler on install:
| Job | Schedule | What it does |
|---|---|---|
ai-chat-recovery | every 30 seconds | Finishes or fails runs whose process died |
knowledge-sweep | every minute | Purges deleted documents, closes out dead uploads, re-queues stranded files |
Everything starts with the API, so nothing extra runs in production. If indexing starts competing with requests, lower
KNOWLEDGE_INDEXING_CONCURRENCY or add a backend replica: every instance indexes.
Needs template v1.7.0 or newer for the task queue.
Add your own tool
The assistant ships with generateImage, searchWeb, and searchKnowledge. A tool of your own, say one that looks up
invoices, is three files that share one contract. The contract is the tool's name, the description the model reads,
and zod schemas for input and output. Both the backend and the clients import it, so the model's arguments, your
handler, and the chat UI agree on one shape.
1. The contract, in the enums package so clients can import it:
// packages/enums/src/features/ai-chat/tools/find-invoices.ts
import { defineToolContract } from "@enums/libs/ai-tools/contract";
import { z } from "zod";
export const findInvoicesContract = defineToolContract({
name: "findInvoices",
description: "Find the organization's invoices by customer name or status.",
inputSchema: z.strictObject({
customer: z.string().max(200).optional(),
status: z.enum(["open", "overdue"]).optional(),
}),
outputSchema: z.strictObject({
invoices: z
.array(z.strictObject({ id: z.string(), number: z.string(), total: z.number(), status: z.string() }))
.max(50),
}),
});Export it from features/ai-chat/tools/index.ts and add it to aiChatToolContracts.
2. The backend tool, next to the built-in ones:
// apps/backend/src/features/ai-chat/tools/find-invoices/index.ts
import { defineChatTool } from "../utils/define-chat-tool";
import { ToolExecutionError } from "@backend/libs/ai-tools/define-tool";
import { buildAbilityFromPermissions } from "@backend/libs/permissions";
import { resolvePermissionsForMembership } from "@backend/features/permissions/modules/resolve-permissions";
import { findInvoicesContract } from "@<your-app>/enums";
export const findInvoices = defineChatTool({
contract: findInvoicesContract,
authorize: async ({ userId, organizationId }) => {
const { permissions } = await resolvePermissionsForMembership({ userId, organizationId });
if (!buildAbilityFromPermissions(permissions ?? []).can("read", "invoice")) {
throw new ToolExecutionError("forbidden", "You cannot read invoices.");
}
},
execute: async (input, { organizationId }) => ({
invoices: await searchInvoices({ organizationId, ...input }),
}),
});Add it to aiChatTools in features/ai-chat/tools/index.ts. The key has to equal the contract's name, or the backend
refuses to start.
3. The renderers, one for web and one for mobile, in features/ai-chat/tools/find-invoices/index.tsx:
function FindInvoicesTool({ state }: ToolRendererProps<typeof findInvoicesContract>) {
if (state.status === "failed") return <p role="alert">{state.error.message}</p>;
if (state.status !== "complete") return <p role="status">Looking up invoices…</p>;
return <InvoiceList invoices={state.output.invoices} />;
}
export const findInvoicesRenderer = defineToolRenderer(findInvoicesContract, FindInvoicesTool);Add it to aiChatToolRenderers. There is no fallback renderer: the registry is typed over every contract, so a missing
renderer is a type error rather than a blank bubble. state.status is pending, running, complete, or failed.
If the model should know when to reach for the tool, add a sentence to assistantInstructions in
features/ai-chat/modules/stream-response/helpers/model-response.ts.
What a tool gets and what it must check
| On the context | What it is |
|---|---|
organizationId | The active workspace, from the session. Never from the model's arguments |
userId | Who is chatting |
conversationId, runId | The current chat and run |
signal | Aborted when the user cancels. Pass it to anything slow |
capabilities | Which built-in features are on for this turn (images, webSearch, knowledge) |
- Permissions are yours to check. The context carries no CASL ability and the chat routes have no
hasAccess, so any member can chat. If a tool reads or changes something role-gated, check it inauthorize, as above.authorizealso runs when a stored result is replayed, so revoked access is not bypassed by history. - Scope every query by
organizationId. The model picks the arguments, so treat them like untrusted user input. - Writes run once. Each call is journaled on
(runId, callId). A replay returns the stored output instead of running again, and the same call with different input fails. There is no "ask the user to approve" step yet, so a tool that deletes or sends things runs as soon as the model calls it. - Errors: throw
ToolExecutionErrorwithforbidden,unavailable,cancelled, orconflictand the model sees your message. Any other error reaches the model as "This operation could not be completed." - Paid APIs: wrap the call in
executeWithUsage({ usage, amounts, signal, perform })with a usage context fromcreateUsageContext, so it counts against the workspace's plan.searchWebshows the pattern.
Who can see what
- Every member of an organization can chat, upload to the knowledge library, and see the workspace's usage. There is no role check on the AI routes.
- Conversations are scoped to the active organization.
- Platform admins see aggregate usage and per-organization allowances in the admin app, not conversation content.
Plan limits
The allowance is per organization per billing period, shared by its members, and lives in
features/billing/modules/ai-allowance/limits.ts:
| Plan | Models | Tokens | Images | Transcription | Speech characters |
|---|---|---|---|---|---|
free | standard | 0 | 0 | 0 | 0 |
pro | standard, pro | 1,000,000 | 10 | 1 hour | 100,000 |
premier | standard, pro, frontier | 5,000,000 | 50 | 5 hours | 500,000 |
Edit AI_TIER_LIMITS to change them. The plan and period come from the billing pack's getSubscriptionStatus, so a
free workspace cannot chat until it subscribes. GET /ai-chat/usage returns the allowance with consumed, reserved, and
remaining amounts per metric.
Environment variables
| Variable | Purpose |
|---|---|
OPENAI_API_KEY | Required |
ANTHROPIC_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY | Optional, for other text providers |
AI_TEXT_MODEL | provider:model, default openai:gpt-5.4-mini |
AI_TRANSCRIPTION_MODEL, AI_SPEECH_MODEL, AI_REALTIME_MODEL | Voice models |
AI_STORAGE_BUCKET | Private bucket for uploads and images, default ai-private |
AI_MAX_OUTPUT_TOKENS, AI_MAX_RUN_SECONDS, AI_MAX_VOICE_SECONDS | Hard caps per run |
AI_USER_STORAGE_BYTES | Storage cap per user |
KNOWLEDGE_EMBEDDING_MODEL | Embedding model for the document library |
KNOWLEDGE_MAX_FILE_BYTES, KNOWLEDGE_MAX_PAGES, KNOWLEDGE_MAX_TEXT_CHARACTERS | Upload limits |
KNOWLEDGE_INDEXING_CONCURRENCY | Documents indexed at once per backend instance, default 2 |
Every cap has a sensible default. You only need OPENAI_API_KEY to start.
After installing
The pack adds eleven Prisma models (conversations, messages, runs, tool calls, assets, voice sessions, usage accounts
and reservations, knowledge documents, versions, and chunks). Say yes when the CLI offers to run the migration, or run
pnpm --filter @hype-stack/backend migration:create afterwards.
Related
- Aether, the template built on this pack
- Billing (Stripe) for the plan caps usage is metered against
- Storage for the private bucket