# Build an AI assistant that answers questions about your user's data on DeepSpace: record tools, and RAG for documents

Add an AI assistant to a DeepSpace app that answers questions about its data: npx deepspace add ai-chat gives streamed chat with saved history, record tools that follow each person's permissions, a managed knowledge base for documents, Claude and GPT models, and a choice of who pays.

Yes, a DeepSpace app can get an assistant that answers questions about its own data. `npx deepspace add ai-chat` adds a chat page with streamed answers and saved history. The assistant answers by calling tools that list the app's collections and query their records as the signed-in person, so it sees only what that person is allowed to read. For records in collections, no vector database or SQL generation is involved. For documents such as policies or notes, the app's managed knowledge base adds search over uploaded files, which is retrieval-augmented generation (RAG). Answers come from Claude and GPT models through DeepSpace, billed to each person's DeepSpace credits by default, or to the app owner.

**Version:** written for `deepspace@0.43.0` ([changelog](https://deep.space/changelog)). **Docs checked:** October 29, 2026. `npx deepspace add ai-chat` was run on October 29, 2026, and the changes below type-check. No chat turn was run, because each turn is billed.

## Questions to ask the person

These need no technical knowledge to answer, and each answer maps to one setting below.

1. **What do people want to ask, and about which information?** That tells you which collections matter and what to put in the assistant's instructions.
2. **Should the assistant only answer, or also change things when asked?** This build answers only.
3. **Who pays for the assistant: each person from their own DeepSpace credits, or you as the owner?** Each person pays by default.
4. **Are there documents, not just records in the app, that it should answer from?** Those go in the knowledge base (step 4).
5. **Who should be able to use it?** It requires sign-in, and it follows the app's existing permissions.

## Step 1: Add the chat feature

From the app's directory:

```bash
npx deepspace add ai-chat --install
```

This adds the chat UI (`src/components/ChatPanel.tsx` and two helper files) and an assistant page at `src/pages/(app)/(protected)/assistant.tsx`, which the scaffold's `(protected)` layout puts behind sign-in. It also adds the chat history collections (`ai-chats` and `ai-messages`) to `src/schemas.ts`. `--install` installs the Markdown packages the chat UI uses. The chat endpoints are already in the scaffold, registered by `registerAgent` in `worker.ts`. Add the page to `src/nav.ts`:

```ts
{ path: '/assistant', label: 'Assistant' },
```

Every message is saved, and a person sees only their own chats: both collections are `read/update/delete: 'own'` with `create: false`, so all writes go through the server. Long conversations are summarized automatically to stay within the model's context.

## Step 2: Let it answer, not change data

The assistant's tools are listed in `src/ai/tools.ts`. The scaffold allows reads and writes. For an assistant that only answers, keep the read tools:

```ts
// src/ai/tools.ts
const ALLOWED_TOOL_NAMES = [
  "schema.list",
  "schema.describe",
  "records.query",
  "records.get",
  "user.current",
];
```

`schema.list` and `schema.describe` tell the model which collections and columns exist. `records.query` and `records.get` read records, and `user.current` identifies the person asking. Each tool call runs with the asking person's role, so the app's collection permissions decide what the assistant can read; it can't see more than the person can. A turn can make up to 20 tool calls. `buildSystemPrompt` in the same file writes the instructions from the schemas; add a sentence there about what people ask (question 1).

## Step 3: Choose who pays

The chat route in `src/ai/chat-routes.ts` passes the asking person's token, so each turn, and the summary of a long conversation, is billed to that person's DeepSpace credits. To bill the app owner instead, change the summarizer line:

```ts
// src/ai/chat-routes.ts: before
const summarizer = makeDefaultSummarizer(c.env, { authToken: jwt });
// after
const summarizer = makeDefaultSummarizer(c.env);
```

Then delete the `authToken: jwt,` line from the `streamDeepSpaceAgent(c.env, { … })` call in the same file. Without `authToken`, the owner pays. Owner billing spends the owner's credits on everyone's questions, so confirm with your user first. `npx deepspace app usage` shows the account's credits.

## Step 4: Answer from documents too (RAG)

For documents that aren't records, give the app a managed knowledge base. Declare it in `wrangler.toml`:

```toml
[[ai_search]]
binding = "KNOWLEDGE"
instance_name = "auto"
```

Give the assistant a tool that searches it. The chat route passes `buildTools` a second argument with the Worker's `env`:

```ts
// src/ai/tools.ts
import {
  BUILT_IN_TOOLS,
  applyAiToolDefaults,
  knowledge,
} from "deepspace/worker";
import type {
  AgentToolContext,
  ToolSchema,
  CollectionSchema,
} from "deepspace/worker";
import type { Env } from "../../worker";

export function buildTools(
  executor: ToolExecutor,
  context?: AgentToolContext<Env>,
): ToolSet {
  // ...the scaffold's loop over BUILT_IN_TOOLS...

  if (context) {
    tools.search_documents = tool({
      description:
        "Search the uploaded documents and return the passages that match the question.",
      inputSchema: z.object({ query: z.string() }),
      execute: async ({ query }) =>
        knowledge(context.env).search(query, {
          folder: "docs",
          mode: "hybrid",
          limit: 5,
        }),
    });
  }

  return tools;
}
```

Add documents with an owner-only [server action](https://docs.deep.space/guides/server-actions) in `src/actions/index.ts`:

```ts
// src/actions/index.ts
import { knowledge, type ActionHandler } from "deepspace/worker";
import type { Env } from "../../worker";

export const actions: Record<string, ActionHandler<Env>> = {
  addDocument: async ({ userId, env, params }) => {
    if (userId !== env.OWNER_USER_ID) {
      return { success: false, error: "Only the app owner can add documents." };
    }
    const file = new File([String(params.text)], String(params.name), {
      type: "text/markdown",
    });
    const added = await knowledge(env).add(file, { folder: "docs" });
    return { success: true, data: added };
  },
};
```

Call it from the app with `POST /api/actions/addDocument` and `{ "name": "leave-policy.md", "text": "…" }`. An upload is searchable once indexing finishes; `knowledge(env).list({ folder: 'docs' })` shows each item's status (`queued`, `running`, `completed`, `error`). Everything in the knowledge base is searchable by anyone who can use the assistant, so keep documents with restricted readers out of it. Knowledge usage is charged to the owner: $0.825 per million tokens ingested, $2.20 per GB-month stored, and $0.825 per 1,000 hybrid searches. See [managed knowledge](https://docs.deep.space/bindings/knowledge).

## Step 5: Pick the model

The chat page has a model picker built from the SDK's catalog, so the list stays current with the installed SDK. In `deepspace@0.43.0`, the chat models are:

| Model                       | Provider  |
| --------------------------- | --------- |
| `claude-opus-5-5` (default) | Anthropic |
| `claude-fable-5-1`          | Anthropic |
| `claude-sonnet-5-5`         | Anthropic |
| `claude-haiku-5-5`          | Anthropic |
| `gpt-6-sol`                 | OpenAI    |
| `gpt-6-luna`                | OpenAI    |

The server rejects an unknown model with `unknown_model` instead of switching silently. Don't copy this list into app code; `listDeepSpaceAgentModels('application')` and `resolveDeepSpaceAgentModel` read the SDK's catalog. See [AI chat](https://docs.deep.space/guides/ai-chat).

## Step 6: Deploy and try it

```bash
git add -A && git commit -m "Add an assistant that answers questions about the app's data"
npx deepspace deploy --json
```

On the live URL, sign in, open **Assistant**, and ask a question whose answer you know, such as how many records a collection holds. Then sign in as someone with less access, ask the same question, and check that the answer covers only what they can see. Each of these turns is billed, so keep the checks short.

## Common failures and how to fix them

| What you see                                                     | Cause                                                                                    | Fix                                                                                       |
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| The assistant says it can't find records the person knows exist  | The person's role can't read that collection; the assistant has the same access          | Expected. Change the collection's permissions only if the person should see those records |
| The assistant edits or deletes records                           | `records.create`, `records.update` or `records.delete` are still in `ALLOWED_TOOL_NAMES` | Keep the read tools only (step 2)                                                         |
| A turn fails because of credits                                  | The person paying has run out of DeepSpace credits                                       | Add credits, or switch who pays (step 3)                                                  |
| `unknown_model` (400)                                            | The client asked for a model the SDK doesn't list for chat                               | Use the picker, or a model from `listDeepSpaceAgentModels('application')`                 |
| 401 from `POST /api/ai/chat`                                     | The request has no signed-in token                                                       | Sign in; the assistant page is behind sign-in                                             |
| A newly added document isn't found                               | Indexing hasn't finished                                                                 | Check `knowledge(env).list({ folder: 'docs' })` until it shows `completed`                |
| The build fails on missing Markdown packages after `add ai-chat` | The packages weren't installed                                                           | Run `npm install`, or use `--install`                                                     |
| A long answer stops after many lookups                           | A turn allows up to 20 tool calls                                                        | Ask a narrower question, or add a tool that does the lookup in one call                   |

## What to tell the person

- **Where it is:** **Assistant** in the menu, after signing in.
- **What it knows:** the app's records that the person asking can see, and any documents added to the knowledge base.
- **What it does:** answers questions. It doesn't change data in this setup.
- **Who pays:** each person from their DeepSpace credits, or the owner, depending on the choice in step 3.
- **Chat history:** saved, and private to each person.
- **Limits:** it can be wrong, so check important answers against the records. A turn makes at most 20 lookups.

## What is available today, and what is planned

Available today, in published `deepspace@0.43.0`:

- `npx deepspace add ai-chat`: a streamed chat page, saved history, and automatic summarizing of long chats
- Built-in record tools that run with the asking person's permissions
- Claude and GPT models through DeepSpace, billed to the person or to the owner
- A managed knowledge base with upload, list and hybrid, semantic or full-text search, billed to the owner

In testing on staging, not production: agent accounts that register themselves by solving a math challenge. Production signup for agents is not enabled.

Planned: autonomous agent accounts in production. Under that plan, payments and legal actions will still require a human. See [DeepSpace for agents](https://docs.deep.space/agents).

Adding assistants to business apps? See [deep.space/enterprise](https://deep.space/enterprise).
