Use cases
Chat
An assistant that answers questions with reports.
The stack you choose picks the code on this page. Options marked coming soon can't be chosen yet.
Copies the Quill CLI's install command: curl -fsSL https://quill.co/install.sh | shView as MarkdownThe whole page, with the code for the chosen stack.
import { QuillProvider } from "@quillsql/react";
import { useEffect, useState } from "react";
import { ChatPanel } from "@/features/chat/chat-panel";
import { MessageReportEmbed } from "@/features/chat/message-report-embed";
import type { ChatMessage } from "@/features/chat/types";
import { useReportingChat } from "@/features/chat/use-reporting-chat";
import { chatQuill } from "@/integrations/quill/config";
import { quillTheme } from "@/integrations/quill/theme";
/**
* The theme's colors in the order the chat's chart had them when it showed
* escalated calls by level: most of it purple, then blue, a band of orange and
* a little indigo. A chart's series take the colors in order, so the example's
* plans (Enterprise, Pro, Scale, Starter) come out the same: Enterprise, the
* most revenue, purple; Pro orange; Scale blue; Starter indigo. Teal and rose
* for a fifth and sixth.
*/
const chatTheme = {
...quillTheme,
chartColors: [
"#895AF6",
"#F59F0A",
"#3C83F6",
"#6467F2",
"#14B8A5",
"#F43E5C",
],
};
/** The chat's Quill client: the public key its server gives at /config (chatQuill), or none until it has. */
function usePublicKey() {
const [publicKey, setPublicKey] = useState("");
useEffect(() => {
let current = true;
fetch(`${chatQuill.endpoint}/config`)
.then((res) =>
res.ok
? res.json()
: Promise.reject(
new Error(`The chat's Quill endpoint answered ${res.status}`),
),
)
.then(
(config: { publicKey: string }) =>
current && setPublicKey(config.publicKey),
)
.catch((error) => console.error(error));
return () => {
current = false;
};
}, []);
return publicKey;
}
/**
* A question the agent answered on the blocks demo's data (chatQuill), and its
* reply, word for word. The report under it is the client's own saved Revenue
* by plan (the tabbed dashboard's), the same chart the agent built: its draft
* is kept only by the Quill server that made it, and the deployed demos' is
* another, where a saved report is found as everywhere else.
*/
const EXAMPLE_EXCHANGE: ChatMessage[] = [
{
id: "example-question",
role: "user",
content:
"Break down monthly revenue by plan as a stacked bar chart, oldest month first",
},
{
id: "example-answer",
role: "assistant",
content:
"**Monthly Revenue by Plan**\n\n\nThis report shows your total revenue broken down by subscription plan for each month, ordered from the earliest to the most recent month.",
reportId: "6af337f0802380dce4bb38d4",
},
];
export function ChatRoute() {
// Each report's state as its card shows it; a message is about the newest report in the thread.
const [reportStates, setReportStates] = useState<Record<string, unknown>>({});
const chat = useReportingChat({
welcomeMessage: "Hi, I'm the Acme reporting assistant.",
welcomeMessageId: "welcome",
initialMessages: EXAMPLE_EXCHANGE,
state: (messages: ChatMessage[]) => {
const reportId = messages.findLast((message) => message.reportId)?.reportId;
return reportId ? reportStates[reportId] : undefined;
},
});
const publicKey = usePublicKey();
// Behind the chat, the blocks demos' page gray (their --surface-muted, this
// app's --muted), so it sits on the landing page as they do. Its reports are
// the blocks demo's client's, from its server (chatQuill).
return (
<QuillProvider
publicKey={publicKey}
queryEndpoint={chatQuill.endpoint}
theme={chatTheme}
>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-muted p-4 lg:p-6">
<ChatPanel
chat={chat}
variant="page"
renderReport={(reportId, reply) => (
<MessageReportEmbed
key={reportId}
reportId={reportId}
reply={reply}
onState={(id, state) => setReportStates((states) => (states[id] === state ? states : { ...states, [id]: state }))}
/>
)}
/>
</div>
</QuillProvider>
);
}import { useCallback, useEffect, useRef, useState } from "react";
import { requestAgentLightReport } from "@/integrations/quill/client";
import type { ChatMessage, ChatRole } from "./types";
let fallbackId = 0;
function createMessageId(role: ChatRole): string {
const uniquePart =
typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID()
: `${Date.now()}-${(fallbackId += 1)}`;
return `${uniquePart}-${role}`;
}
export type UseReportingChatOptions = {
welcomeMessage: string;
welcomeMessageId?: string;
/** Messages the thread opens with after the welcome, e.g. an earlier question and the report it got. */
initialMessages?: ChatMessage[];
/** The report the next message is about, or a function of the thread that returns it, read when the message is sent. */
state?: unknown | ((messages: ChatMessage[]) => unknown);
onReportGenerated?: (reportId: string) => void;
reportGeneratedMessage?: string;
};
export function useReportingChat(options: UseReportingChatOptions) {
const optionsRef = useRef(options);
optionsRef.current = options;
const [messages, setMessages] = useState<ChatMessage[]>(() => [
{
id: options.welcomeMessageId ?? createMessageId("assistant"),
role: "assistant",
content: options.welcomeMessage,
},
...(options.initialMessages ?? []),
]);
const messagesRef = useRef(messages);
const [prompt, setPrompt] = useState("");
const [isPending, setIsPending] = useState(false);
const pendingRef = useRef(false);
const [error, setError] = useState("");
const abortControllerRef = useRef<AbortController | null>(null);
const replaceMessages = useCallback(
(updater: (previous: ChatMessage[]) => ChatMessage[]) => {
setMessages((previous) => {
const next = updater(previous);
messagesRef.current = next;
return next;
});
},
[],
);
const cancel = useCallback(() => {
abortControllerRef.current?.abort();
}, []);
const submit = useCallback(
async (promptOverride?: string) => {
const submitted = (promptOverride ?? prompt).trim();
if (!submitted || pendingRef.current) {
return;
}
pendingRef.current = true;
setIsPending(true);
setError("");
setPrompt("");
const userMessage: ChatMessage = {
id: createMessageId("user"),
role: "user",
content: submitted,
};
const assistantMessageId = createMessageId("assistant");
const requestMessages = [...messagesRef.current, userMessage];
replaceMessages(() => [
...requestMessages,
{
id: assistantMessageId,
role: "assistant",
content: "",
},
]);
const controller = new AbortController();
abortControllerRef.current = controller;
try {
let streamedAssistantText = "";
const { state } = optionsRef.current;
const result = await requestAgentLightReport(requestMessages, {
signal: controller.signal,
state: typeof state === "function" ? state(requestMessages) : state,
onTextChunk: (chunk) => {
streamedAssistantText += chunk;
replaceMessages((previous) =>
previous.map((message) =>
message.id === assistantMessageId
? { ...message, content: streamedAssistantText }
: message,
),
);
},
});
const finalAssistantText =
streamedAssistantText.trim() ||
result.assistantText ||
(result.reportId
? (optionsRef.current.reportGeneratedMessage ??
"I ran the reporting tool and loaded the report.")
: "");
replaceMessages((previous) =>
previous.map((message) =>
message.id === assistantMessageId
? {
...message,
content: finalAssistantText,
reportId: result.reportId ?? undefined,
}
: message,
),
);
if (result.reportId) {
optionsRef.current.onReportGenerated?.(result.reportId);
}
} catch (caught) {
replaceMessages((previous) =>
previous.filter((message) => message.id !== assistantMessageId),
);
if (!(caught instanceof Error && caught.name === "AbortError")) {
setError(
caught instanceof Error
? caught.message
: "Unknown error while calling Quill AI.",
);
}
} finally {
if (abortControllerRef.current === controller) {
abortControllerRef.current = null;
pendingRef.current = false;
setIsPending(false);
}
}
},
[prompt, replaceMessages],
);
useEffect(() => cancel, [cancel]);
return {
messages,
prompt,
setPrompt,
isPending,
error,
submit,
cancel,
};
}import { chatQuill } from "./config";
import { NO_QUERY_YET } from "./constants";
import {
extractAssistantTextFromSseEvents,
extractDisplayTextFromSseEvent,
extractReportIdFromSseEvents,
extractReportIdFromToolEvent,
parseAgentLightSseBlock,
parseAgentLightSseEvents,
} from "./sse";
import type { AgentLightSseEvent } from "./types";
export type AgentLightMessageInput = Readonly<{
role: "user" | "assistant";
content: string;
}>;
export type RequestAgentLightReportOptions = {
onTextChunk?: (chunk: string) => void;
onReportId?: (reportId: string) => void;
signal?: AbortSignal;
state?: unknown;
};
export async function requestAgentLightReport(
messages: readonly AgentLightMessageInput[],
options: RequestAgentLightReportOptions = {},
) {
const { onTextChunk, onReportId, signal, state } = options;
// The client and the tenant are the chat's server's to add (config.ts, chatQuill).
const requestBody = {
model: chatQuill.model,
dashboardName: chatQuill.dashboardName,
state: state ?? NO_QUERY_YET,
// Strip chat UI fields (id, reportId) before sending to Quill.
messages: messages.map(({ role, content }) => ({ role, content })),
};
const response = await fetch(`${chatQuill.endpoint}/ai`, {
method: "POST",
headers: {
Accept: "text/event-stream",
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
signal,
});
if (!response.ok) {
const responseText = await response.text();
throw new Error(
`Quill agent stream failed (${response.status}): ${responseText}`,
);
}
const events: AgentLightSseEvent[] = [];
const processEvent = (event: AgentLightSseEvent) => {
events.push(event);
if (typeof event !== "object") {
const nextChunk = extractDisplayTextFromSseEvent(event);
if (nextChunk) {
onTextChunk?.(nextChunk);
}
return;
}
const reportId = extractReportIdFromToolEvent(event);
if (reportId) {
onReportId?.(reportId);
}
const nextChunk = extractDisplayTextFromSseEvent(event);
if (nextChunk) {
onTextChunk?.(nextChunk);
}
};
if (!response.body) {
const responseText = await response.text();
parseAgentLightSseEvents(responseText).forEach(processEvent);
return {
reportId: extractReportIdFromSseEvents(events),
assistantText: extractAssistantTextFromSseEvents(events),
};
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
buffer += decoder.decode(value, { stream: true }).replace(/\r/g, "");
let separatorIndex = buffer.indexOf("\n\n");
while (separatorIndex !== -1) {
const block = buffer.slice(0, separatorIndex);
buffer = buffer.slice(separatorIndex + 2);
const event = parseAgentLightSseBlock(block);
if (event) {
processEvent(event);
}
separatorIndex = buffer.indexOf("\n\n");
}
}
buffer += decoder.decode().replace(/\r/g, "");
if (buffer.trim().length > 0) {
const trailingEvent = parseAgentLightSseBlock(buffer);
if (trailingEvent) {
processEvent(trailingEvent);
}
}
return {
reportId: extractReportIdFromSseEvents(events),
assistantText: extractAssistantTextFromSseEvents(events),
};
}import { Chart, useReport } from "@quillsql/react";
import { PencilIcon } from "lucide-react";
import { useEffect } from "react";
import type { RuleGroupType } from "react-querybuilder";
import { chatQuill } from "@/integrations/quill/config";
import css from "./message-report-embed.module.css";
// The Metric explorer and its sentence filters, from the blocks demo, on its tokens (its foundation.css: main.tsx
// loads it for the demo's own page, inline.tsx nests it under the demo in another page).
import { MetricExplorer } from "../../../../blocks/src/components/blocks/metric-explorer/metric-explorer";
import { Select } from "../../../../blocks/src/components/filter-builder/filter-builder";
import { FilterSentence } from "../../../../blocks/src/blocks/FilterSentence";
import styles from "../../../../blocks/src/blocks/MetricExplorerBlock.module.css";
const ROWS_PER_PAGE = 5;
/** Radix select items can't have an empty value, so no column grouping has its own. */
const NO_COLUMNS = "none";
/** A field (table.column, or table::column for grouping) by its column, in sentence case: agent_team is "Agent team". */
const labelOf = (field: string) =>
(field.split(/::|\./).pop() ?? field).replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase());
const relabel = (options: { value: string }[]) => options.map(({ value }) => ({ value, label: labelOf(value) }));
/** The agent introduces a report with its name in bold, then a sentence on what it shows. */
const REPLY = /^\*\*(.+?)\*\*\s*([\s\S]*)$/;
/**
* A report the agent built, in the Metric explorer: the agent's reply as its header, its filters as a sentence, its
* chart with Group by and Segment by selects, and a Table view of its rows, formatted and paged by Quill, all from one
* useReport.
*/
export function MessageReportEmbed({ reportId, reply, onState }: {
reportId: string;
reply: string;
/** The report as the card shows it now, filters and edits included, for the chat's next message. */
onState?: (reportId: string, state: unknown) => void;
}) {
const report = useReport(reportId, {
destinationDashboardName: chatQuill.dashboardName,
rowsPerRequest: 100,
initialPagination: { pageIndex: 0, pageSize: ROWS_PER_PAGE },
});
const { table, setReport } = report;
useEffect(() => {
if (report.reportBuilderState) onState?.(reportId, report.reportBuilderState);
}, [reportId, report.reportBuilderState]);
// A report without a pivot has nothing to group.
const grouping = report.groupRowsByOptions.length > 0 && (
<>
<Select className={styles.group} label="Group by" value={report.groupRowsBy ?? ""} options={relabel(report.groupRowsByOptions)}
onChange={(groupRowsBy) => setReport({ groupRowsBy })} />
<Select className={styles.group} label="Segment by" value={report.groupColumnsBy || NO_COLUMNS}
options={[{ value: NO_COLUMNS, label: "None" }, ...relabel(report.groupColumnsByOptions)]}
onChange={(value) => setReport({ groupColumnsBy: value === NO_COLUMNS ? "" : value })} />
</>
);
const [, title = "", description = reply] = REPLY.exec(reply.trim()) ?? [];
return (
<MetricExplorer
detailOnly
metrics={false}
loading={report.loading}
// The filters row is the panel's top row, so the report's header sits in it, above the sentence.
filters={
<>
<header className={css.header}>
<div className={css.title}>
{title && <h3>{title}</h3>}
{description && <p>{description}</p>}
</div>
<button type="button" className={css.open}>
<PencilIcon size={14} strokeWidth={1.75} aria-hidden="true" />
Open in report builder
</button>
</header>
<FilterSentence filters={report.filters as RuleGroupType} queryBuilderProps={report.filterQueryBuilderProps}
labelOf={labelOf} onChange={report.setFilters} />
</>
}
chartControls={grouping}
chart={
<Chart chart={report.chart} chartLoading={report.chartLoading} showLegend={report.showLegend}
containerStyle={{ width: "100%", height: 240 }} />
}
// The explorer shows its Chart / Table switch for a block that listens; both views are loaded already.
onViewChange={() => undefined}
table={{
columns: table.columns,
rows: table.rows,
page: table.pagination.pageIndex + 1,
pageCount: Math.max(0, table.getPageCount()),
rowCount: table.getRowCount(),
loading: report.tableLoading,
onPageChange: (next) => table.setPageIndex(next - 1),
}}
rowsPerPage={ROWS_PER_PAGE}
/>
);
}import { Quill } from '@quillsql/node';
const quill = new Quill({
privateKey: process.env.QUILL_PRIVATE_KEY,
databaseType: 'postgresql',
databaseConnectionString: process.env.DATABASE_URL,
});
// "authenticate" is your existing auth middleware.
app.post('/quill', authenticate, async (req, res) => {
const result = await quill.query({
tenants: [{ tenantField: 'organization_id', tenantIds: [req.user.organizationId] }],
metadata: req.body.metadata,
});
res.send(result);
});Connect to your existing agent as a tool call
1. Add a new tool
import OpenAI from "openai";
import { askQuill } from "./quill";
// OpenRouter speaks OpenAI's Chat Completions API.
const openrouter = new OpenAI({ baseURL: "https://openrouter.ai/api/v1", apiKey: process.env.OPENROUTER_API_KEY });
const tools: OpenAI.ChatCompletionTool[] = [
{
type: "function",
function: {
name: "ask_data_assistant",
description: "Answer a question about the user's data with a report",
parameters: { type: "object", properties: { question: { type: "string" } }, required: ["question"] },
},
},
];
export async function reply(messages: OpenAI.ChatCompletionMessageParam[], user: User) {
let reportId: string | undefined;
for (;;) {
const completion = await openrouter.chat.completions.create({ model: "particle-ai/particle-1", messages, tools });
const message = completion.choices[0].message;
messages.push(message);
if (!message.tool_calls?.length) return { text: message.content ?? "", reportId };
for (const call of message.tool_calls) {
if (call.type !== "function") continue;
reportId = await askQuill(JSON.parse(call.function.arguments).question, user);
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify({ reportId }) });
}
}
}import { GoogleGenAI } from "@google/genai";
import { askQuill } from "./quill";
// Reads GEMINI_API_KEY.
const gemini = new GoogleGenAI({});
// An interaction doesn't keep its tools, so every request sends them.
const tools = [
{
type: "function" as const,
name: "ask_data_assistant",
description: "Answer a question about the user's data with a report",
parameters: { type: "object", properties: { question: { type: "string" } }, required: ["question"] },
},
];
export async function reply(input: string, user: User) {
let reportId: string | undefined;
let interaction = await gemini.interactions.create({ model: "gemini-4-neon", input, tools });
for (;;) {
const results = [];
for (const step of interaction.steps) {
if (step.type !== "function_call") continue;
reportId = await askQuill(step.arguments.question, user);
results.push({ type: "function_result" as const, name: step.name, call_id: step.id, result: [{ type: "text" as const, text: JSON.stringify({ reportId }) }] });
}
if (!results.length) return { text: interaction.output_text, reportId };
interaction = await gemini.interactions.create({ model: "gemini-4-neon", previous_interaction_id: interaction.id, input: results, tools });
}
}import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
import { askQuill } from "./quill";
const anthropic = new Anthropic();
export async function reply(messages: Anthropic.Beta.BetaMessageParam[], user: User) {
let reportId: string | undefined;
const askDataAssistant = betaZodTool({
name: "ask_data_assistant",
description: "Answer a question about the user's data with a report",
inputSchema: z.object({ question: z.string() }),
run: async ({ question }) => {
reportId = await askQuill(question, user);
return JSON.stringify({ reportId });
},
});
// The tool runner calls the tool and loops until Claude answers.
const message = await anthropic.beta.messages.toolRunner({
model: "claude-opus-5-5",
max_tokens: 16000,
betas: ["server-side-fallback-2026-07-01"],
fallbacks: "default",
tools: [askDataAssistant],
messages,
});
const text = message.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("");
return { text, reportId };
}import OpenAI from "openai";
import { askQuill } from "./quill";
const openai = new OpenAI();
const tools: OpenAI.Responses.Tool[] = [
{
type: "function",
name: "ask_data_assistant",
description: "Answer a question about the user's data with a report",
parameters: { type: "object", properties: { question: { type: "string" } }, required: ["question"], additionalProperties: false },
strict: true,
},
];
export async function reply(input: OpenAI.Responses.ResponseInput, user: User) {
let reportId: string | undefined;
let response = await openai.responses.create({ model: "gpt-5.6", input, tools });
for (;;) {
const outputs: OpenAI.Responses.ResponseInputItem[] = [];
for (const item of response.output) {
if (item.type !== "function_call") continue;
reportId = await askQuill(JSON.parse(item.arguments).question, user);
outputs.push({ type: "function_call_output", call_id: item.call_id, output: JSON.stringify({ reportId }) });
}
if (!outputs.length) return { text: response.output_text, reportId };
response = await openai.responses.create({ model: "gpt-5.6", previous_response_id: response.id, input: outputs, tools });
}
}2. The tool call is a simple request to the Quill /ai endpoint
export async function askQuill(question: string, user: User) {
const res = await fetch("https://api.quill.co/v1/ai", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.QUILL_PRIVATE_KEY}`,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify({
publicKey: process.env.QUILL_PUBLIC_KEY,
messages: [{ role: "user", content: question }],
// From your signed-in user, never from the model
tenants: [{ tenantField: "organization_id", tenantIds: [user.orgId] }],
}),
});
const stream = await res.text();
return stream.match(/"reportId":"(\w+)"/)?.[1];
}3. Output of the tool call is the same param that useReport uses
import { Chart, useReport } from "@quillsql/react";
export function Message({ message }: { message: ChatMessage }) {
if (message.reportId) return <ReportMessage reportId={message.reportId} />;
return <Bubble role={message.role}>{message.text}</Bubble>;
}
function ReportMessage({ reportId }: { reportId: string }) {
const { name } = useReport(reportId);
return (
<Card title={name} action={<Link href={`/reports/${reportId}`}>Open in report builder</Link>}>
<Chart reportId={reportId} />
</Card>
);
}You can build any reporting experience with useReport. Here are some examples: Chat, Insight, Reporting and Drilldowns.