@openuidev/server
API reference for OpenUIClient on your server, covering conversations, artifacts and dashboards, and SDK integrations with Autofix.
@openuidev/server connects your server to OpenUI Gateway. One client, OpenUIClient, holds your API key, so use it only on the server. This reference covers it in three parts:
- Conversations: your users' conversations and their items.
- Artifacts: saved dashboards, slides and reports, and building dashboards.
- SDK integrations: conversations in your SDK's messages, and Autofix for its output.
Import everything from @openuidev/server.
Install
pnpm add @openuidev/serverSome parts use an optional peer. Install it only if you use that part:
| Peer | Used by |
|---|---|
openai | openui.chat, for its Chat Completions types |
ai | openui.ai, for its Vercel AI SDK types |
@langchain/core | openui.langgraph |
@modelcontextprotocol/sdk | An MCP Client to pass as mcp to defineDashboard |
Client
new OpenUIClient(options?)
import { OpenUIClient } from "@openuidev/server";
export const openui = new OpenUIClient();new OpenUIClient(options?: {
apiKey?: string; // default: THESYS_API_KEY
baseUrl?: string; // default: https://api.thesys.dev
appId?: string; // your app, when one API key serves several
fetch?: typeof globalThis.fetch;
});- The key is read on each request, so a missing key fails the first call with
missing_api_key, not the constructor. - With
appId, frontend tokens, conversations and artifacts belong to that app, and scripts run only from it. - Calls act as your org, or as one of your users when you pass their
userId, plusgroupIdsso group shares count. Take the user from your session, never from the browser. Dashboard calls always act as the user incontext, and conversation calls by id always act as your org.
openui.createFrontendToken(params, options?)
Mints a frontend token for the signed-in user. The browser uses it to read their artifacts and conversations. Return it from your token route as is.
import { openui } from "@/lib/openui";
import { getSession } from "@/lib/auth"; // your session lookup
export async function POST(request: Request) {
const session = await getSession(request);
if (!session) return new Response("Unauthorized", { status: 401 });
const token = await openui.createFrontendToken(
{ userId: session.user.id, groupIds: session.user.teamIds },
{ signal: request.signal },
);
return Response.json(token, { headers: { "Cache-Control": "private, no-store" } });
}function createFrontendToken(
params: { userId: string; groupIds?: string[] },
options?: { signal?: AbortSignal },
): Promise<{ token: string; expires_at: number }>;tokenisfct_…, andexpires_atis in unix seconds.OpenUICloudProviderreads this shape.userIdis required. A user has up to 10groupIds, each up to 64 characters. A change shows on the next token.
See Authentication.
Conversations
openui.conversations manages your users' conversations and their items, in OpenAI's Conversations API item shape. To store and read your SDK's messages instead, use openui.chat or openui.langgraph.
// A conversation id from the browser isn't proof: check it's the user's
const conversation = await openui.conversations.get(threadId);
if (conversation.userId !== session.user.id) return new Response("Not found", { status: 404 });
const created = await openui.conversations.create(
{ title: "Q3 planning" },
{ userId: session.user.id },
);
const page = await openui.conversations.items.list(created.id, { order: "asc" });type Options = { signal?: AbortSignal };
type Page = { limit?: number; after?: string; before?: string };
type List<T> = { data: T[]; hasMore: boolean; firstId?: string; lastId?: string };
interface Conversations {
list(params?: Options & Page & { userId?: string }): Promise<List<CloudConversation>>;
create(
params: { title?: string; metadata?: Record<string, string> },
options: Options & { userId: string },
): Promise<CloudConversation>;
get(id: string, options?: Options): Promise<CloudConversation>;
update(
id: string,
params: { title?: string; metadata?: Record<string, string> },
options?: Options,
): Promise<CloudConversation>;
delete(id: string, options?: Options): Promise<void>;
items: {
list(
id: string,
params?: Options & Page & { order?: "asc" | "desc" },
): Promise<List<ConversationItem>>;
create(
id: string,
items: readonly ConversationItemInput[],
options?: Options,
): Promise<ConversationItem[]>;
get(id: string, itemId: string, options?: Options): Promise<ConversationItem>;
update(
id: string,
itemId: string,
params: { content?: unknown; status?: ConversationItemStatus },
options?: Options,
): Promise<ConversationItem>;
};
}
interface CloudConversation {
id: string;
title?: string;
metadata?: Record<string, string>;
userId?: string; // the owner
appId?: string;
createdAt: number; // unix milliseconds
}
type ConversationItemInput =
| { type: "message"; role: "user" | "assistant"; content: string | ConversationContentPart[] }
| { type: "function_call"; call_id: string; name: string; arguments: string }
| { type: "function_call_output"; call_id: string; output: string };- Calls by id act as your org. Before acting on an id from the browser, check the conversation's
userIdis the signed-in user. createneeds the owner'suserId, so their frontend token can read the conversation. It belongs to the client'sappId.metadataholds up to 16 pairs, with keys up to 64 characters and values up to 512.listis newest first, and withuserIdlists only that user's conversations, in every app.items.listis newest first unless you passorder: "asc".items.createadds only the new turn, up to 100 items, and sends no request for none. System messages can't be stored. Stored items keep OpenAI's shape, withcreated_atin unix seconds: narrow ontype.items.updatechanges only an item'scontentandstatus. Deleted conversations can't be restored.
See Conversations from your server.
Artifacts
Saved dashboards, slides and reports. openui.artifacts reads and manages them, and openui.defineDashboard builds dashboards.
openui.artifacts
Pass userId and groupIds to act as that user, seeing what their frontend token would, or neither to act as your org.
const asUser = { userId: session.user.id, groupIds: session.user.teamIds };
const page = await openui.artifacts.list({ ...asUser, kind: "dashboard", limit: 20 });
await openui.artifacts.update(id, { name: "Orders by region" }, asUser);
await openui.artifacts.share(id, { type: "group", id: "team:sales", access: "view" }, asUser);
await openui.artifacts.pin(id, asUser);type AsUser = { userId?: string; groupIds?: string[]; signal?: AbortSignal };
type Target = { type: "user" | "group"; id: string };
interface Artifacts {
list(
params?: AsUser & {
kind?: CloudArtifact["kind"] | CloudArtifact["kind"][];
name?: string; // case-insensitive match
pinned?: boolean;
isOwner?: boolean; // needs userId
conversationId?: string;
limit?: number; // 1 to 100
after?: string; // the last page's lastId
before?: string; // the last page's firstId
order?: "asc" | "desc";
},
): Promise<{ data: CloudArtifact[]; hasMore: boolean; firstId?: string; lastId?: string }>;
get(id: string, options?: AsUser): Promise<CloudArtifact>;
update(
id: string,
params: { name?: string; content?: string },
options?: AsUser,
): Promise<CloudArtifact>;
delete(id: string, options?: AsUser): Promise<void>;
pin(id: string, options: AsUser & { userId: string }): Promise<CloudArtifact>;
unpin(id: string, options: AsUser & { userId: string }): Promise<CloudArtifact>;
share(
id: string,
params: Target & { access: "view" | "edit" },
options?: AsUser,
): Promise<CloudArtifact>;
unshare(id: string, target: Target, options?: AsUser): Promise<CloudArtifact>;
}
interface CloudArtifact {
id: string;
kind: "dashboard" | "slides" | "report";
name?: string;
content: string; // the OpenUI Lang program
version?: string;
pinned: boolean;
isOwner: boolean;
isEditable: boolean;
shares?: Array<Target & { access: "view" | "edit"; createdBy: string; createdAt: number }>;
conversationId?: string;
userId?: string;
appId?: string;
createdAt: number; // unix milliseconds
updatedAt?: number;
}listis newest first. WhilehasMore, passlastIdasafterfor the next page.updatesavescontentas a new version, and anamealone renames. Acting as a user,update,shareandunshareneed edit access.pinandunpinneeduserId: each user pins their own.viewopens and runs an artifact, andeditalso edits, renames and shares it. Sharing again changes the access, and removing a share that isn't there does nothing.- Deleted artifacts can't be restored.
openui.defineDashboard(options)
Sets up how every dashboard is built: the components, the model and the data tools. Define it once.
import { OpenUIClient } from "@openuidev/server";
import spec from "../generated/spec.json";
import { dataTools } from "./data";
export const openui = new OpenUIClient();
export const dashboards = openui.defineDashboard({
library: spec,
model: "anthropic/claude-sonnet-5.5",
tools: dataTools,
instructions: "An online store. Revenue is in USD. Weeks start on Monday.",
});function defineDashboard<Context extends ExecutionContext = ExecutionContext>(options: {
library: LibrarySpec;
model: string;
tools?: Record<string, DataTool<Context>>;
mcp?: McpToolClient | McpConfig<Context> | Array<McpToolClient | McpConfig<Context>>;
instructions?: string;
promptOptions?: { preamble?: string; examples?: string[]; additionalRules?: string[] };
reasoningEffort?: "minimal" | "low" | "medium" | "high";
maxToolRounds?: number;
}): Dashboard<Context>;| Option | Description |
|---|---|
library | The component library's spec: openui generate --spec JSON, or library.toSpec(). |
model | The model that builds and edits dashboards, as provider/model. |
tools | Your data tools, each { description, parameters, output, execute }. See Connect data. |
mcp | MCP servers whose tools dashboards can call. See MCP servers. |
instructions | Your business context: what it does, who reads the dashboards, your terms, calendar and units. The same for every user. |
promptOptions | preamble, examples and additionalRules added to the prompt. |
reasoningEffort | How much the model thinks, for models that can. |
maxToolRounds | Tool-call rounds before the model must write the dashboard. Default: 20. With 0, the model calls no tools, but its scripts still do. |
tools,mcp, or both are required.- Bad options throw at once:
invalid_inputfor a missingmodel,libraryor data tools, andinvalid_libraryfor a spec the prompt can't be built from. - Add your own fields to the context with the generic:
openui.defineDashboard<{ userId: string; accountId: string }>(…). Your tools then get them typed.
See Define dashboards.
MCP servers
The mcp option offers an MCP server's tools to dashboards. Pass a client with listTools and callTool, such as Client from @modelcontextprotocol/sdk, or { client, include, outputs, connect }, or an array of them. The tools the server marks read-only (readOnlyHint) are offered by default. include picks others, outputs gives example results, and connect(context) returns a client with the user's credentials. See Connect data.
Dashboard methods
defineDashboard returns dashboards. Each method takes the signed-in user as context, and acts as them.
const user = { userId: session.user.id, groupIds: session.user.teamIds };
// Build or change a dashboard. Return `response` from your tool and render it.
const response = await dashboards.create({ title: "Orders, last 30 days", prompt }, user);
await dashboards.edit({ id, prompt: "Add a chart of refunds by reason." }, user);
const { name, content } = await dashboards.get({ id }, user);
// In your interpreter route: run the renderer's data request, and return { result }
const result = await dashboards.interpreter.execute(await request.json(), user, { signal });interface Dashboard<Context extends ExecutionContext> {
create(
params: { title: string; prompt: string },
context: Context,
options?: { signal?: AbortSignal; stream?: boolean },
): Promise<string>; // AsyncIterable<string> with { stream: true }
edit(
params: { id: string; prompt: string },
context: Context,
options?: { signal?: AbortSignal; stream?: boolean },
): Promise<string>; // AsyncIterable<string> with { stream: true }
get(
params: { id: string },
context: Context,
options?: { signal?: AbortSignal },
): Promise<CloudArtifact>;
interpreter: {
execute(
request: { name: string; arguments?: Record<string, unknown>; id?: string; version?: string },
context: Context,
options?: { signal?: AbortSignal; timeoutMs?: number },
): Promise<unknown>;
};
}
interface ExecutionContext {
userId: string;
groupIds?: string[];
}createandeditrun the model's tool rounds, typically 20 to 45 seconds. Once generation starts, they resolve with the tool response: return it from your tool as is, and pass it toLiveArtifactRendererasresponse. Later failures show in the renderer. With{ stream: true }, they yield a message once the dashboard has an id, and a last one once it's saved or failed: return the last one.promptis all the builder sees, so include any data it needs. A new dashboard is the user's alone until it's shared. Its owner can edit it, and so can anyone it's shared with for editing.getreads a dashboard the user can open. Give the model itsnameandcontent, or the renderer itsid.interpreter.executeruns your tool whennameis one. Otherwise it runs a script the model wrote, from the dashboardidnames, for users who can open it. A script for an olderversionthan the saved one is refused with409.timeoutMscovers the whole run: default 60 seconds. Failures throwToolExecutionError:tool_not_found(404),tool_timeout(504),script_limitor the script's own code (502),invalid_input, or the Gateway's code and status.
See Generate, Render and Add to your agent.
SDK integrations
The client has a namespace for each SDK it works with. Each takes and returns that SDK's own types.
| Namespace | SDK | Has | Types from |
|---|---|---|---|
openui.chat | OpenAI Chat Completions | conversations and createAutofix | openai |
openui.langgraph | LangGraph | conversations | @langchain/core |
openui.ai | Vercel AI SDK | createAutofix | ai |
Conversation messages
openui.chat.conversations and openui.langgraph.conversations have the same calls as openui.conversations, but their items go in and come out as your SDK's messages:
openui.chat.conversationstakes and returns Chat Completions messages.openui.langgraph.conversationstakes LangChain messages, or the plain ones it returns, and returns plain{ role, content }messages thatgraph.invoketakes.
items.create(id, messages, options?)
Stores the new turn, and resolves with it as stored, in the same shape items.list returns.
await openui.chat.conversations.items.create(threadId, [
{ role: "user", content: lastUserText },
{ role: "assistant", content: assistantText },
]);function create(
id: string,
messages: readonly ChatCompletionMessageParam[], // LangGraph: readonly (BaseMessage | LangGraphHistoryMessage)[]
options?: { signal?: AbortSignal },
): Promise<ChatCompletionMessageParam[]>; // LangGraph: Promise<LangGraphHistoryMessage[]>- Pass only the new turn. Earlier messages are already stored, so the full history would duplicate them.
- System and developer messages are skipped.
- A tool call is stored only together with its result, so a turn stopped mid tool call leaves the thread valid for the next request.
- What's skipped isn't stored, so it isn't in the result. With nothing to store, it resolves with
[]and sends no request.
items.list(id, options?)
Reads the whole thread, oldest first, ready to send to the model. It reads every page.
const history = await openui.chat.conversations.items.list(threadId);
const completion = await client.chat.completions.create({
model,
messages: [systemMessage, ...history, userMessage],
});function list(
id: string,
options?: { signal?: AbortSignal },
): Promise<ChatCompletionMessageParam[]>; // LangGraph: Promise<LangGraphHistoryMessage[]>
type LangGraphHistoryMessage =
| { role: "human"; content: MessageContent }
| { role: "ai"; content: string; tool_calls?: ToolCall[] }
| { role: "tool"; content: string; tool_call_id: string };- User images come back as
image_urlparts. Other stored items, such asreasoning, are skipped. - LangGraph messages are plain objects.
graph.invoke, orcoerceMessageLikeToMessagefrom@langchain/core/messages, turns them into LangChain messages.
Autofix
Autofix checks generated OpenUI Lang against your library and repairs invalid output through the Autofix API.
createAutofix(params)
Creates the Autofix helpers for your SDK: openui.chat.createAutofix for Chat Completions, openui.ai.createAutofix for the Vercel AI SDK.
import library from "./openui.spec.json";
export const autofix = openui.chat.createAutofix({ library });function createAutofix(params: { library: LibrarySpec & { schema: LibraryJSONSchema } }): {
fix;
stream;
};- Use the spec from
openui generate --spec, for the same library as your renderer. It needsschema. - Requests use the client's API key,
baseUrlandfetch.
autofix.fix(input)
Checks completed OpenUI text. Valid output is returned as is. Invalid output is sent to the Autofix API.
const result = await autofix.fix({ generation, messages, signal });
if (result.content !== null) {
// already_valid or fixed: use result.content
} else {
console.warn(result.unfixedErrors); // fix_failed: choose a fallback
}function fix(input: {
generation: string;
messages?: ChatCompletionMessageParam[];
signal?: AbortSignal;
}): Promise<AutofixResult>;
type AutofixResult = {
original: string;
fixedErrors: AutofixDiagnostic[];
unfixedErrors: AutofixDiagnostic[];
} & (
{ status: "already_valid" | "fixed"; content: string } | { status: "fix_failed"; content: null }
);
interface AutofixDiagnostic {
code: string;
message: string;
component?: string;
path?: string;
statementId?: string;
}generationis the completed OpenUI text, up to 100,000 characters.messagesis the conversation before it.- On
fixed,contentis the program the Autofix API returned. - Valid output needs no request, so it needs no API key.
autofix.stream(input)
Wraps your SDK's stream. It forwards every event, and inserts a repair before the stream completes when the finished UI is invalid.
import OpenAI from "openai";
import { autofix } from "@/lib/autofix";
const model = new OpenAI();
export async function POST(request: Request) {
const { messages } = await request.json();
const source = await model.chat.completions.create(
{ model: "openai/gpt-5.5", messages, stream: true },
{ signal: request.signal },
);
return autofix.stream({ stream: source, messages, signal: request.signal }).toResponse();
}function stream(input: {
stream: AsyncIterable<Chunk> & { controller?: AbortController };
messages?: ChatCompletionMessageParam[];
signal?: AbortSignal;
}): AutofixStream<Chunk>;
interface AutofixStream<Chunk> {
chunks: AsyncIterable<Chunk>;
toResponse(): Response;
result: Promise<AutofixResult | null>;
}- From
openui.chat, pass a Chat Completions stream;toResponse()is the SSE the frontendopenAIAdapter()reads. Fromopenui.ai, passtoUIMessageStream({ stream: result.stream }), notresult.stream;toResponse()is the UI message streamuseChatreads. - Read
chunksor calltoResponse(), once.resultsettles after that. - Save
result.contentwhen it's a string: that's the final program, not the joined stream text.resultisnullwhen Autofix didn't run. - A failed repair throws
AutofixErrorwith codefix_failed.
const output = autofix.stream({ stream: source, messages, signal });
for await (const chunk of output.chunks) {
// your SDK's events, including any repair
}
const settled = await output.result;
if (settled?.content) await save(settled.content);Autofix errors
Autofix throws AutofixError, with a code:
code | When |
|---|---|
missing_api_key | No API key: pass apiKey or set THESYS_API_KEY |
invalid_library | library.schema is missing |
generation_too_large | The generation is over 100,000 characters |
http_error | The Autofix request failed. status is set. |
invalid_response | The Autofix response couldn't be read |
stream_consumed | chunks or toResponse() was used more than once |
fix_failed | A streamed generation couldn't be repaired |
On fix_failed, error.result holds the diagnostics.
Errors
Every error has a code string, and status when there's an HTTP status to report.
| Class | Thrown by |
|---|---|
OpenUIApiError | The client, artifacts, conversations, dashboards and createFrontendToken |
ToolExecutionError | interpreter.execute, and a bad context on any dashboard call |
AutofixError | Autofix; see Autofix errors |
code | status | When |
|---|---|---|
missing_api_key | none | No API key: pass apiKey or set THESYS_API_KEY |
invalid_input | none or 400 | A bad argument, caught before any request |
invalid_library | none | defineDashboard couldn't build a prompt from library |
invalid_response | 502 | The Gateway's response couldn't be read |
| the Gateway's | the Gateway's | The Gateway refused the call, such as 404 for an artifact the user can't see, or 429 |
Return the code and status from your routes:
import { OpenUIApiError, ToolExecutionError } from "@openuidev/server";
function errorResponse(error: unknown) {
if (error instanceof OpenUIApiError || error instanceof ToolExecutionError) {
return Response.json(
{ error: { code: error.code, message: error.message } },
{ status: error.status ?? 500 },
);
}
return Response.json({ error: { code: "internal_error" } }, { status: 500 });
}Exports
| Export | Description |
|---|---|
OpenUIClient | The client |
OpenUIApiError, ToolExecutionError, AutofixError | The error classes |
Types:
- Client:
OpenUIClientOptions,CloudList. - Conversations:
CloudConversation,CloudConversationList,ConversationMetadata,ConversationItem,ConversationItemInput,ConversationItemList,ConversationItemStatus,ConversationContentPart,ListConversationsParams,ListConversationItemsParams. - Artifacts:
CloudArtifact,CloudArtifactList,CloudArtifactShare,ListArtifactsParams,ShareArtifactParams,ArtifactShareTarget. - Dashboards:
Dashboard,DashboardOptions,DataTool,ExecutionContext,InterpreterRequest,McpConfig,McpToolClient. - SDK integrations:
ChatConversations,LangGraphConversations,LangGraphHistoryMessage,MessageConversations,MessageConversationItems. - Autofix:
ChatAutofix,AIAutofix,AutofixHelpers,CreateAutofixParams,AutofixInput,AutofixStreamInput,AutofixResult,AutofixDiagnostic,AutofixStream.