Skip to Content
Foir AIUse an agent in your app

Use an agent in your app

Your app talks to an agent through the same API it reads its content with. It sends a message with the startAgentRun mutation and follows the answer with the agentRun subscription, as it is written. There is no server to write and no model key to hold: the agent runs on Foir, as whoever sent the message.

This page builds one end to end: a support agent that answers a signed-in user about their own orders, and nobody else’s.

1. Declare the agent, and who may talk to it

Three parts of your config do the work: the model the orders live in, the role a signed-in user holds, and the agent.

import { defineConfig } from '@foir/cli/configs'; export default defineConfig({ key: 'shop', name: 'Shop', models: [ { key: 'order', name: 'Order', fields: [ { key: 'number', type: 'text', label: 'Number', required: true }, { key: 'status', type: 'text', label: 'Status' }, ], // Each order belongs to the user who placed it. access: { ownerPlane: 'user', defaultVisibility: 'private' }, }, ], userRoles: [ { key: 'shopper', name: 'Shopper', // Their own orders, and the support agent. grants: ['records:read:order', 'agents:execute:support'], isDefault: true, }, ], apiKeys: [ { name: 'Shop app', kind: 'publishable', envVar: 'PLATFORM_API_KEY', // The most anyone signed in through this key may do. grants: ['records:read', 'agents:execute:support'], // What a visitor who has not signed in gets: nothing of the agent. baselineGrants: [], // The records of every model, those added later among them. allModels: true, }, ], agents: [ { key: 'support', name: 'Support', instructions: [ 'You help people with their own orders.', 'Look the order up before you answer anything about it.', 'If you cannot find it, say so. Never guess a status.', ].join('\n'), model: { tier: 'fast' }, tools: [ { verb: 'foir_list_records', models: ['order'] }, { verb: 'foir_get_record', models: ['order'] }, ], }, ], });

Push it and release it:

foir push --publish

Here is what each part decides:

  • The role says a user holding it reads order records with no reach written, which is their own. So when the agent lists orders for them, it lists theirs. It cannot be talked into reading anyone else’s, because the run never holds more than they do.
  • The key is the ceiling for everyone who signs in through it, and it gives a visitor nothing. A signed-in user reaches the agent because both their role and the key name it.
  • The agent lists two record verbs over order. They get them because their role reads orders. Someone whose role read no orders would get an agent with no tools.

2. Sign the user in

Use the hosted sign-in, as Auth for a single-page app sets it up. The provider gives you getToken, which the data client sends with every request:

import { FoirProvider } from '@foir/sdk/react'; const env = { PLATFORM_API_URL: 'https://api.foir.dev/graphql', PLATFORM_API_KEY: 'foir_pub_…', }; export function Root() { return ( <FoirProvider env={env} hostedSession={{ loginOrigin: 'https://login.shop.example' }}> <App /> </FoirProvider> ); }

3. Ask the agent

askAgent sends the message, follows the run, and resolves with the answer. onText hands you each piece as it is written, so the answer appears as the agent types it:

import { useMemo, useRef, useState } from 'react'; import { useFoirAuth } from '@foir/sdk/react'; import { askAgent, createFoirClient } from '@foir/sdk/data'; export function SupportChat() { const { getToken } = useFoirAuth(); const foir = useMemo( () => createFoirClient({ apiUrl: env.PLATFORM_API_URL, apiKey: env.PLATFORM_API_KEY, bearerToken: getToken, }), [getToken], ); const thread = useRef<string | null>(null); const [answer, setAnswer] = useState(''); async function ask(message: string) { setAnswer(''); const reply = await askAgent(foir, { agent: 'support', message, threadId: thread.current ?? undefined, onText: (text) => setAnswer((a) => a + text), }); // The next message carries on the same conversation. thread.current = reply.threadId; if (reply.status === 'HELD') setAnswer(reply.answer + '\n\nThis is waiting for your approval.'); } return ( <form onSubmit={(e) => { e.preventDefault(); const input = e.currentTarget.elements.namedItem('q') as HTMLInputElement; void ask(input.value); input.value = ''; }} > <p>{answer}</p> <input name="q" placeholder="Where is my order?" /> </form> ); }

That is the whole app. Ask “where is order 1042?” as one user, and the agent finds it if it is theirs. Ask as another, and it is not there to find.

With the AI SDK’s useChat

If your app already uses the AI SDK , give useChat a Fóir transport. The hook, the message parts and the approval step are the AI SDK’s own, so components you have written for it work unchanged. Install ai and @ai-sdk/react alongside @foir/sdk.

import { useMemo } from 'react'; import { useChat } from '@ai-sdk/react'; import { lastAssistantMessageIsCompleteWithApprovalResponses } from 'ai'; import { useFoirAuth } from '@foir/sdk/react'; import { createFoirClient } from '@foir/sdk/data'; import { foirChatTransport } from '@foir/sdk/ai'; export function SupportChat() { const { getToken } = useFoirAuth(); const transport = useMemo( () => foirChatTransport({ client: createFoirClient({ apiUrl: env.PLATFORM_API_URL, apiKey: env.PLATFORM_API_KEY, bearerToken: getToken }), agent: 'support', // A signed-in person: no visitor secret. visitorToken: null, }), [getToken], ); const { messages, sendMessage, addToolApprovalResponse } = useChat({ transport, // Send the person's decision as soon as they make it. sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses, }); // Render messages as you would for any useChat app. }

What each part of a message is:

PartWhat it is
textThe answer, as it is written.
reasoningThe model’s reasoning, where the model gives it.
dynamic-toolOne step the agent took: a verb, an operation, a remote tool or another agent, named by toolName, with its input and output.

When the agent holds an act for the person, its step is in the approval-requested state. Call addToolApprovalResponse({ id: part.approval.id, approved }), and the run carries on in the same answer. An act held for the project’s team shows as an output-available step whose output says status: 'held': the person waits, and the team decides it in Work.

Fóir keeps the conversation. The transport keeps each chat’s thread id in the browser’s storage, so a reload carries on the same thread. foirChatMessages(foir, threadId) reads a thread back as useChat’s messages. A visitor who has not signed in leaves visitorToken out, and the transport uses the secret the browser keeps.

A typed answer and data for your components

An agent can give your app more than words. Each is declared on the agent, in your config or in the console’s agent form under In your app, with a JSON Schema of an object.

agents: [ { key: 'shop', name: 'Shop assistant', tools: [{ verb: 'foir_list_records' }], // A run answers with a value that fits this, rather than with prose. outputSchema: { type: 'object', properties: { count: { type: 'integer' } }, required: ['count'] }, // Data the agent sends beside its answer, for your own components. dataParts: [ { name: 'product-list', description: 'Products to show.', schema: { type: 'object', properties: { ids: { type: 'array', items: { type: 'string' } } } } }, ], // The agent may use the tools your page sends with a message. pageTools: true, }, ],

A typed answer. A run of an agent with an outputSchema ends with a value that fits it. askAgent returns it as reply.output, and the agentRun query and subscription carry it as output. An answer that does not fit fails the run and says why.

Data for your components. The model sends one of the agent’s data parts by calling a tool named after it (send_product_list). Data that fits the part’s schema reaches useChat as a data-product-list part, which you render with your own component. Data that does not fit is refused to the model, which can send it again.

Tools of your page

Your page can give the agent tools of its own, such as opening a product or filling in a form. You define them once, in foirChatTransport, and the transport sends them with every message. The agent only has to allow them: pageTools: true in your config, or May use the page’s tools in the console.

import { z } from 'zod'; const transport = foirChatTransport({ client: foir, agent: 'shop', pageTools: { show_product: { description: 'Open a product on the page.', inputSchema: z.object({ id: z.string() }), execute: ({ id }) => { router.push(`/products/${id}`); return { shown: id }; }, }, }, });

When the agent calls show_product, the transport runs execute, and the run carries on with what it returned in the same answer. The call shows in the message as a dynamic-tool part. An AI SDK tool({ ... }) works here as well. inputSchema takes a Zod schema, a Standard Schema, or a JSON Schema made with the AI SDK’s jsonSchema(). Leave it out for a tool that takes no input.

Fóir checks each call before your page sees it. Input that does not fit the tool’s schema goes back to the model, and execute never runs. Whatever execute throws reaches the model as { error }, so it can try again or tell the person.

A tool’s name is lowercase letters, digits and _, and cannot be the name of one of the agent’s own tools. A page offers at most 20. A message that offers tools to an agent that does not allow them is refused.

Some tools need the person, such as one that asks them to pick a size. Leave execute out of that tool’s definition and answer the call in onToolCall:

const { addToolOutput } = useChat({ transport, sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls, onToolCall: async ({ toolCall }) => { if (toolCall.toolName === 'pick_size') { const size = await askForSize(); addToolOutput({ tool: 'pick_size', toolCallId: toolCall.toolCallId, output: { size } }); } }, });

Only the run’s own caller can answer a call. Each held call reaches the caller with a reply that is good for that call alone, and nobody else who reads the run is given one. A call the page does not answer within 10 minutes ends, and the agent is told the page did not answer.

Without the SDK, send the tools as the pageTools argument of startAgentRun. To answer a call, send the replyToStep mutation to reply.endpoint, with the call’s id and { "result": ... } as its reply. Sign it with two headers: Authorization: Bearer and reply.token, and X-Foir-Signature: sha256= and the hex HMAC-SHA256 of the request body under reply.signingKey. replyToStep in @foir/sdk/server does this for you.

Images and PDFs in a message

A message can carry images (PNG, JPEG, GIF or WebP, up to 5 MB each) and PDFs (up to 10 MB each), at most five at a time. The model reads them along with the text. A visitor who has not signed in can send images only, up to 20 a day, because the safety check on a public conversation reads images but not PDFs.

With useChat, pass the files to sendMessage. The transport uploads each one and sends it with the message:

<form onSubmit={(event) => { event.preventDefault(); sendMessage({ text: input, files: fileInput.current?.files ?? undefined }); }} > <input type="file" ref={fileInput} accept="image/png,image/jpeg,image/gif,image/webp,application/pdf" multiple /> </form>

With askAgent, pass them as files:

const reply = await askAgent(foir, { agent: 'support', message: 'What is wrong with this?', files: [screenshot] });

Each file goes straight to the project’s storage. The message keeps a reference to it, never the bytes, and only the person who sent it can read it, through their own conversation. A thread read back gives each file a link that lasts an hour. A file is removed with its conversation. A file that is too large, of a type the model cannot read, or past a visitor’s day is refused before anything runs, and costs nothing.

Without the SDK, call the createAgentAttachment mutation, PUT the bytes to the uploadUrl it answers with, using the file’s type as the Content-Type, and pass the attachment’s id in startAgentRun’s attachmentIds.

Pointing at things in a message

A message can point at things of the project: a record, one field of a record, a model, a person, a file, an operation, an agent, a hook, a schedule, an organisation or a note. Each is a tag, kept on the message by id beside its text. A tag is never resolved into the message. The agent is told what was pointed at and reads it with its own tools, as the caller, so a tag reaches nothing the caller couldn’t. “Translate @Spring launch into French” goes straight to that record, with no search first.

With useChat, put a data-tag part on the message, beside its text. Your app’s own picker decides what to offer:

sendMessage({ parts: [ { type: 'text', text: 'Translate @Spring launch into French' }, { type: 'data-tag', data: { kind: 'record', id: record.id, model: 'posts', label: 'Spring launch' } }, ], });

With askAgent, or startAgentRun without the SDK, pass tags: { kind: 'RECORD', id, model, label }. A field’s tag names its record’s id, its model and the field’s path as field. A message takes at most 20 tags. In the console, typing @ in Ask Fóir’s message box offers what you can read.

What the run returns

askAgent resolves with:

FieldWhat it is
answerThe agent’s answer, or why the message was refused.
statusCOMPLETED, FAILED, SKIPPED (refused before it ran), CANCELLED, or HELD (an act waits for an approval).
threadIdPass it as threadId to carry on the conversation.
runIdThe run, to read again with the agentRun query or to cancel.
errorWhy the run failed, when it did.

A message refused at the door, by a limit, the safety check or one of your rules, comes back as a SKIPPED run whose answer says why. It costs nothing.

Without the SDK

askAgent calls two fields of the generated API, which any GraphQL client can call. The mutation starts the run:

mutation Ask($message: String!, $thread: String) { startAgentRun(agent: support, message: $message, threadId: $thread) { id threadId status answer } }

The agent is an enum of your project’s agents, so a mistyped name is refused before anything runs.

The agentRun subscription follows it, over the WebSocket endpoint. It replays the run from its start, so a client that subscribes after starting the run misses nothing, and it ends after a final status:

client.subscribe( { query: ` subscription Follow($id: String!) { agentRun(id: $id) { seq kind # TEXT, REASONING, NODE, MESSAGE or STATUS text # TEXT: the next piece of the answer status # STATUS: where the run now stands answer } } `, variables: { id: run.id }, }, { next: ({ data }) => render(data.agentRun) }, );

The same two calls on the SDK client, for a chat that renders each step and not only the answer:

const run = await foir.ns.agents.startAgentRun({ agent: 'support', message }); const sub = foir.ns.agents.onRun({ id: run.id, onData: (event) => { if (event.kind === 'NODE') showStep(event.node); if (event.kind === 'TEXT') appendText(event.text); }, });

The API also offers what a chat needs around a run: agentThreads and agentThread to list and read a person’s conversations, renameAgentThread and deleteAgentThread, cancelAgentRun, myAgentApprovals and decideAgentApproval, and connectMcpServer for a remote server the person connects their own account to. Each is on foir.ns.agents too.

Visitors who have not signed in

An agent can answer visitors too. Give it to them on the key, by name:

grants: ['records:read', 'agents:execute:faq'], baselineGrants: ['records:read', 'agents:execute:faq'],

A visitor has no account, so their conversation is theirs by a secret their browser keeps. Pass visitorToken() from @foir/sdk/data with each message, and they come back to the same conversation:

import { askAgent, visitorToken } from '@foir/sdk/data'; await askAgent(foir, { agent: 'faq', message, visitorToken: visitorToken() });

A public agent is held to more than its limits: a safety check on every message, your own refusal rules, a shorter message and conversation, and a credit check that refuses when it cannot read the balance. Give it a quotas limit too, so one visitor cannot spend your credits: a visitor is counted by the address they ask from.

limits: { maxCreditsPerRun: 0.5, quotas: { rules: [{ points: 20, duration: 86400, scope: 'actor', failClosed: true, message: 'That is all for today.' }], }, },

Run it from the browser, not from a server of your own: from a server, every visitor would ask from the server’s one address and share one quota.

Last updated on