Tutorial: Build an Assistant Backend
By the end you'll have: an authenticated user, a LatticeClient built from their
token, a runtime picker, a dispatched completion, and typed error handling.
What you need first#
-
An OAuth app. Register one in the developer portal with the
lattice:compute:inferencescope and a redirect URI for your app. -
Sign in with Lovelace, wired up. Follow the auth quickstart so your server holds the signed-in user's access token in the
lovelace_access_tokencookie. This tutorial picks up from there. -
The SDK installed:
pnpm add @reasonabletech/lattice-client
1. The assistant endpoint#
Create a route that takes the user's chat messages and returns a completion. It reads the signed-in user's access token, builds a client scoped to that user, and dispatches the work.
// app/api/assistant/route.ts
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import {
LatticeClient,
LatticeError,
PersonalRuntimeRequiresUserTokenError,
} from "@reasonabletech/lattice-client";
export async function POST(request: Request) {
// 1. Require a signed-in user.
const accessToken = (await cookies()).get("lovelace_access_token")?.value;
if (accessToken == null) {
return NextResponse.json({ error: "not_signed_in" }, { status: 401 });
}
const { messages } = (await request.json()) as {
messages: { role: "user" | "assistant" | "system"; content: string }[];
};
// 2. Build a client that runs as THIS user, on their compute.
const lattice = new LatticeClient({
credential: { kind: "oauth", accessToken },
});
try {
// 3. Prefer the user's own paired machine if one is reachable…
const runtimes = await lattice.listReachablePersonalRuntimes();
const runtime = runtimes[0];
const completion =
runtime !== undefined
? await lattice.chatCompleteForPersonalRuntime(runtime, { messages })
: await lattice.chatComplete({ messages });
const reply = completion.choices[0]?.message.content ?? "";
return NextResponse.json({ reply });
} catch (error) {
// 4. Handle the failures that need a user action, by code.
if (error instanceof PersonalRuntimeRequiresUserTokenError) {
return NextResponse.json({ error: "reconnect_runtime" }, { status: 409 });
}
if (error instanceof LatticeError && error.code === "insufficient_scopes") {
return NextResponse.json({ error: "reauthorize" }, { status: 403 });
}
throw error;
}
}
Why it's shaped this way:
- The token is the user's, so the request runs on their account and compute — you are not paying for their inference, and their data stays theirs.
- Runtime discovery is explicit. Listing reachable personal runtimes lets you route to the user's own machine when it's online and fall back cleanly when it isn't, instead of silently changing where the work runs.
- Errors branch on
code, never on message text.insufficient_scopesand a revoked grant mean "send the user back through sign-in"; a personal-runtime error means "ask them to reconnect a machine."
2. A minimal chat UI#
Post the conversation to the endpoint and render the reply. This is a client component inside your authenticated app.
// app/assistant/Chat.tsx
"use client";
import { useState } from "react";
export function Chat() {
const [input, setInput] = useState("");
const [reply, setReply] = useState("");
async function send() {
const res = await fetch("/api/assistant", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: input }] }),
});
if (res.status === 403 || res.status === 401) {
// grant missing/expired — send the user back through sign-in
return;
}
const data = (await res.json()) as { reply?: string };
setReply(data.reply ?? "");
}
return (
<div>
<textarea value={input} onChange={(e) => setInput(e.target.value)} />
<button onClick={() => void send()}>Ask</button>
{reply !== "" && <p>{reply}</p>}
</div>
);
}
3. Run it#
- Start your app and sign in as a test user (the auth quickstart
flow), approving the
lattice:compute:inferencescope on the consent screen. - Send a message. You should get a real completion back.
- To exercise the personal-runtime path, pair a machine
(Personal runtimes) and confirm the reply
comes back through it —
listReachablePersonalRuntimes()will return it and the code routes there automatically.
You're done — and this is the whole integration#
An assistant that runs on each user's own compute is now three moving parts you control: the user's token, a runtime choice, and a dispatch. Swapping an existing OpenAI-style call for this is usually just replacing the client and credential — the API is OpenAI-compatible.
Next#
- Personal runtimes — pair a user's machine
- OpenAI-compatible API — migrate an existing OpenAI client
- Sample app — the same shape, checked against the SDK
- Quickstart — the step-by-step version