Connect a model
Hand the bridge's tools to a model through the Vercel AI SDK or the Anthropic SDK — the model on your server, the tools in the browser — plus OpenAI's JSON Schema and a tool of your own.
On this page
The bridge lives in the browser, next to the components it reads. The model's key must not: it stays on your server. So every recipe here splits the same way. A route on your server calls the model with the bridge's tools and no way to run them; the model answers with tool calls; the browser runs each with agent.callTool and sends the result back on the next request. The page's agent is the one from Connect, in lib/agent.ts.
@cloudlet/agent is experimental: the tools' descriptions and schemas may change in any 0.x release. Read them from agent.tools, never copy them.
Vercel AI SDK
npm install ai @ai-sdk/react @ai-sdk/anthropicThe route streams the model's answer. Its tools have a schema and no execute, so the AI SDK hands their calls to the browser:
import { anthropic } from '@ai-sdk/anthropic';
import { createAgent } from '@cloudlet/agent';
import { convertToModelMessages, jsonSchema, streamText, type JSONSchema7, type UIMessage } from 'ai';
// The tools are plain data, the same for every agent: read them once, on the server.
const tools = Object.fromEntries(
createAgent().tools.map((tool) => [tool.name, { description: tool.description, inputSchema: jsonSchema(tool.inputSchema as JSONSchema7) }]),
);
export async function POST(request: Request) {
const { messages }: { messages: UIMessage[] } = await request.json();
const result = streamText({
model: anthropic('claude-sonnet-5-5'), // ANTHROPIC_API_KEY on the server
instructions: 'You help the user with the notifications and colors on this page. Use the cloudlet tools.',
messages: await convertToModelMessages(messages),
tools,
});
return result.toUIMessageStreamResponse();
}useChat runs each call in onToolCall and sends the conversation again once every call has its output:
'use client';
import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from 'ai';
import { agent } from '../lib/agent';
export function Assistant() {
const { messages, sendMessage, addToolOutput } = useChat({
transport: new DefaultChatTransport({ api: '/api/agent' }),
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
async onToolCall({ toolCall }) {
// callTool never rejects: an error comes back as data the model can read.
const output = await agent.callTool(toolCall.toolName, toolCall.input);
// Not awaited inside onToolCall, as the AI SDK asks.
void addToolOutput({ tool: toolCall.toolName, toolCallId: toolCall.toolCallId, output });
},
});
return (
<form
onSubmit={(event) => {
event.preventDefault();
const field = event.currentTarget.elements.namedItem('prompt') as HTMLInputElement;
void sendMessage({ text: field.value });
field.value = '';
}}
>
<output>{messages.length} messages</output>
<input name="prompt" aria-label="Ask the assistant" />
</form>
);
}Anthropic SDK
npm install @anthropic-ai/sdkThe route forwards one turn to the Messages API with the bridge's tools and returns the model's message as it is:
import Anthropic from '@anthropic-ai/sdk';
import { createAgent } from '@cloudlet/agent';
const client = new Anthropic(); // ANTHROPIC_API_KEY on the server
const tools = createAgent().tools.map((tool) => ({
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema as Anthropic.Tool.InputSchema,
}));
export async function POST(request: Request) {
const { messages }: { messages: Anthropic.MessageParam[] } = await request.json();
const message = await client.messages.create({
model: 'claude-sonnet-5-5',
max_tokens: 2048,
system: 'You help the user with the notifications and colors on this page. Use the cloudlet tools.',
tools,
messages,
});
return Response.json(message);
}The browser keeps the conversation and turns the loop: every tool_use block runs through callTool, and its answer goes back as a tool_result:
import type Anthropic from '@anthropic-ai/sdk';
import { agent } from './agent';
export async function askClaude(prompt: string, signal?: AbortSignal): Promise<string> {
const messages: Anthropic.MessageParam[] = [{ role: 'user', content: prompt }];
// A bound on the loop: a model that keeps calling tools stops here.
for (let turn = 0; turn < 10; turn += 1) {
const response = await fetch('/api/claude', { method: 'POST', body: JSON.stringify({ messages }), signal: signal ?? null });
if (!response.ok) throw new Error(`The route answered ${response.status}`);
const message: Anthropic.Message = await response.json();
messages.push({ role: 'assistant', content: message.content });
if (message.stop_reason !== 'tool_use') {
return message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('\n');
}
const results: Anthropic.ToolResultBlockParam[] = [];
// One by one: calls of one agent queue anyway, and the order is the model's plan.
for (const block of message.content) {
if (block.type !== 'tool_use') continue;
const output = await agent.callTool(block.name, block.input, signal ? { signal } : {});
results.push({ type: 'tool_result', tool_use_id: block.id, content: JSON.stringify(output), is_error: 'ok' in output && !output.ok });
}
messages.push({ role: 'user', content: results });
}
return 'Stopped after ten turns.';
}The route sends whatever messages the browser posts to a model on your account: put it behind the same authentication and rate limits as the rest of your API.
OpenAI and JSON Schema
inputSchema is a plain JSON Schema object, so it fits a function's parameters as it is. OpenAI's strict mode (strict: true) asks for more than the bridge's schema gives: every property listed in required and a type for every value. cloudlet_act leaves args optional and accepts any value in it, because each verb takes its own arguments. Send the tools without strict: the bridge checks every input itself, and an invalid call comes back with a message saying what to change, which the model can act on.
Changes between turns
A cloudlet_act result carries the changes heard while the call ran, whoever made them. Between calls the bridge keeps nothing, so what happened while the model was not looking — the person closed a notification, a timer ran out — is yours to tell it. Collect the changes and send them with the next message:
import type { AgentChange } from '@cloudlet/agent';
import { agent } from './agent';
let pending: AgentChange[] = [];
agent.subscribe((changes) => {
pending.push(...changes);
});
/** The changes since the last call, as a line for the next user message; empty when nothing changed. */
export function changesSince(): string {
const text = pending.map((change) => `${change.source} changed ${change.key} of ${change.label ?? change.ref} to ${JSON.stringify(change.value)}`).join('; ');
pending = [];
return text ? `Since your last turn: ${text}.` : '';
}Let the model show a notification
The bridge works with what is on screen; it cannot show a notification, by design. When a model should be able to tell the user something, give it a tool of your own that your app runs with the controller's show. The notification is your app's, so its source is app:
import type { ReactCloudletController } from '@cloudlet/toast';
/** A tool of the app's own, in the same shape as the bridge's tools. */
export const notifyTool = {
name: 'show_notification',
description: 'Shows the user a short notification. Use it to report what you did; never for questions.',
inputSchema: {
type: 'object',
properties: { title: { type: 'string', maxLength: 80 }, description: { type: 'string', maxLength: 200 } },
required: ['title'],
additionalProperties: false,
},
} as const;
/** Runs it with the page's controller and answers plain data, like callTool. */
export function runNotifyTool(cloudlet: ReactCloudletController, input: unknown) {
const { title, description } = (input ?? {}) as { title?: unknown; description?: unknown };
if (typeof title !== 'string' || !title.trim()) return { ok: false, error: { message: 'show_notification takes a title.' } };
const result = cloudlet.show({
title,
...(typeof description === 'string' ? { description: { kind: 'text', text: description } } : {}),
});
return result.status === 'rejected' ? { ok: false, error: { message: `Not shown: ${result.reason}` } } : { ok: true };
}Add notifyTool next to the bridge's tools on the server, and in the browser answer its calls with runNotifyTool instead of agent.callTool.