React integration
This guide puts an agent inside a React app with
@distri/react. It follows the
docs-agent sample:
a React developer portal with a chat beside the docs, where the agent searches
the portal's pages and opens the one it answered from. Both of its tools run in
the reader's browser.
Every code block below is from that sample. For the full client surface (Angular, local servers, every option) see Using Distri in your product.
Before you start
- The
distriCLI, signed in: see Installation. - A workspace API key for the server-side token exchange: see API keys.
1. Define the agent
The agent is a markdown file with TOML front matter. The tools listed under
[tools] external are not on the server: your page provides them.
agents/docs_agent.md from the sample:
---
name = "docs_agent"
description = "Answers questions about {{params.product_name}} from the portal's docs pages and opens the page it used."
max_iterations = 6
tool_format = "provider"
runtime = "web"
[tools]
builtin = ["final"]
external = ["search_docs", "open_page"]
---
# ROLE
You are the docs assistant inside the **{{params.product_name}}** developer portal.
# HOW TO ANSWER
- Call `search_docs` with the reader's question first. Answer only from the sections it returns.
- Quote commands and code exactly as the docs give them.
- End by calling `open_page` with the slug of the page you used, and name that page in your answer.
- If no section answers the question, say so and suggest the closest page. Never invent endpoints, limits or prices.
Every front matter field is described in Agent definition.
Create it in your workspace. From a checkout of distrihub/distri, the sample applies with:
distri login
distri apply samples/docs-agent --set site_url=http://localhost:5302
site_url is the origin that serves the portal; the sample's blueprint.toml
uses it as the allowed origin of its [embed] section. For your own agents,
see distri push and distri apply in the CLI reference.
2. Install the packages
npm install @distri/core @distri/react
3. Exchange the API key for a short-lived token, on your server
The browser must never see your API key. Your server calls
POST {baseUrl}/token with the key in the x-api-key header and a ttl, and
hands the page the returned access_token.
In the sample this is a Vite dev-server middleware,
app/server/distri-token.ts (trimmed):
// Dev-server endpoint: exchanges the long-lived DISTRI_API_KEY for a
// short-lived token (POST {baseUrl}/token with x-api-key). In production, put
// the same exchange in your backend; never ship the API key to the browser.
server.middlewares.use('/api/distri/token', async (_req, res) => {
res.setHeader('content-type', 'application/json');
const r = await fetch(`${opts.baseUrl.replace(/\/$/, '')}/token`, {
method: 'POST',
headers: { 'x-api-key': opts.apiKey, 'content-type': 'application/json' },
body: JSON.stringify({ ttl: 3600 }),
});
const body = (await r.json().catch(() => ({}))) as { access_token?: string };
if (!r.ok || !body.access_token) {
res.statusCode = 502;
res.end(JSON.stringify({ error: `token exchange returned ${r.status}` }));
return;
}
res.end(JSON.stringify({ access_token: body.access_token, base_url: opts.baseUrl, workspace_id: opts.workspaceId }));
});
vite.config.ts reads the key from DISTRI_API_KEY (no VITE_ prefix, so it
stays in the Node process), the base URL from DISTRI_URL (default
https://api.distri.dev/v1) and, when the key is not tied to one workspace,
DISTRI_WORKSPACE_ID.
The page fetches the token once:
function useToken() {
const [token, setToken] = useState<{ access_token: string; base_url: string; workspace_id?: string } | string | null>(null);
useEffect(() => {
fetch('/api/distri/token', { method: 'POST' })
.then(async (r) => (r.ok ? r.json() : Promise.reject(new Error((await r.json()).error))))
.then(setToken)
.catch((e: Error) => setToken(e.message));
}, []);
return token;
}
4. Wrap the chat in DistriProvider and render <Chat>
Import the stylesheet once, pass the token to DistriProvider, and render
<Chat> with the agent's name and a thread id:
import { Chat, DistriProvider } from '@distri/react';
import '@distri/react/globals.css';
// inside the component
const [threadId] = useState(() => `docs-${Date.now()}`);
<DistriProvider config={{ baseUrl: token.base_url, accessToken: token.access_token, workspaceId: token.workspace_id, authReady: true }}>
<Chat agentId="docs_agent" threadId={threadId} externalTools={tools} />
</DistriProvider>
| Config | Value in the sample |
|---|---|
baseUrl | The API URL the server returned (https://api.distri.dev/v1 by default) |
accessToken | The short-lived token from step 3 |
workspaceId | Sent when the key is not tied to one workspace |
authReady | true: the provider is only rendered once the token has arrived |
The sample shows "Connecting…" until the token arrives and the error message if the exchange fails.
5. Give the agent tools that run in the page
Each name in [tools] external needs a DistriFnTool with the same name, a
JSON-schema parameters object and a handler. Whatever the handler returns
goes back to the agent. From app/src/main.tsx:
import type { DistriFnTool } from '@distri/core';
// Tools the agent calls; they run here, in the reader's browser. Both only
// read the docs and switch the page, so they run without asking the reader
// (autoExecute); leave it off for tools that change data.
function docsTools(open: (slug: string) => void): DistriFnTool[] {
return [
{
type: 'function',
name: 'search_docs',
autoExecute: true,
description: 'Search the portal docs. Returns matching pages with slug, title and body.',
parameters: {
type: 'object',
properties: { query: { type: 'string', description: 'The reader question or keywords' } },
required: ['query'],
},
handler: async ({ query }: { query: string }) => JSON.stringify(searchDocs(query)),
},
{
type: 'function',
name: 'open_page',
autoExecute: true,
description: 'Open a docs page for the reader by its slug.',
parameters: {
type: 'object',
properties: { slug: { type: 'string', enum: DOCS.map((d) => d.slug) } },
required: ['slug'],
},
handler: async ({ slug }: { slug: string }) => {
open(slug);
return `Opened ${slug}`;
},
},
];
}
// in the component: build them once and pass them to <Chat externalTools={tools} />
const tools = useMemo(() => docsTools(setSlug), []);
Flags on a tool (from DistriBaseTool in @distri/core):
| Flag | Effect |
|---|---|
autoExecute | Runs the handler without asking. Leave it off for tools that change data, and the user confirms each call. |
stopAfterTurn | Ends the agent's turn as soon as this tool's result is sent back, instead of another model round-trip. |
is_final | Marks the tool as the agent's terminal tool, on the model side. |
More patterns (UI tools, approvals, typed handlers) are in In-product tools.
6. Send page context and pick a theme
beforeSendMessage changes each message before it is sent. The
form-filler sample
prepends the form's HTML so the agent knows which fields exist, and renders the
chat dark:
const beforeSendMessage = useCallback(async (message: DistriMessage): Promise<DistriMessage> => {
const formContextPart = {
part_type: 'text' as const,
data: `[Form HTML for analysis]\n${getFormHtml()}`,
};
return {
...message,
parts: [formContextPart, ...(message.parts || [])],
};
}, []);
<Chat
agentId="form_filler_agent_v2"
threadId={threadId}
externalTools={tools}
beforeSendMessage={beforeSendMessage}
theme="dark"
/>
theme takes 'light', 'dark' or 'auto'. To change colours, see
Theming; to use the chat's parts outside a chat panel, see
Components.
7. Run the sample
distri login
distri apply samples/docs-agent --set site_url=http://localhost:5302
cd samples/docs-agent/app
npm install
echo "DISTRI_API_KEY=<your key>" > .env
npx vite
Open http://localhost:5302 and ask "What happens when I go over the rate
limit?". The agent calls search_docs, then open_page, and the portal
switches to Rate limits.
To use it on your own portal, replace DOCS in app/src/docs.ts with your
pages, or make search_docs call your search.
No React? Use the script tag
When a blueprint has an [embed] section, distri apply creates a public
client for the listed origins and returns a step, "Add the chat to your site",
with a snippet to paste before </body>:
<script src="https://embed.distri.dev/v1/embed.js"></script>
<script>
DistriEmbed.init({
clientId: "<client id>",
agentId: "<agent>",
workspaceId: "<workspace id>",
embedUrl: "https://embed.distri.dev",
apiUrl: "https://api.distri.dev/v1",
});
</script>
Use the snippet distri apply prints: it fills in your client id, agent and
workspace id.