Skip to content
pleach

Quickstart

For a SaaS engineer adding streaming chat. Three files, one env var, one minute.

If you're adding a streaming chat surface to an existing app — Next.js, Astro, SvelteKit, Remix, Vite, Hono, plain Node — this is the shortest path. It's the same wire-level surface Getting started covers; this page goes deeper on the env-var detection, the error contract, and what useChat actually gives you.

Is this the right page?

This page is for a new project with no runtime yet. If you already have an agent loop, the chooser on Adoption paths routes you by where you are: keep your loop and record each call with @pleach/observe (not on npm yet; no family lock, replay or checkpoints), let Pleach drive the turn over your provider and store with createBrownfieldRuntime (storage paired with a checkpointer), or migrate off another runtime.

Not on npm yet

The @pleach/* packages aren't on npm yet. Some names are reserved with 0.0.1 placeholders. Each package's first real release ships under FSL-1.1-Apache-2.0. The commands on this page describe the install once it lands. Packages tracks each package's status.

One install, one env var, three files

npm install @pleach/core

Set one provider env var:

# .env (or your platform's env config)
ANTHROPIC_API_KEY=sk-ant-...
// app/api/chat/route.ts
import { createPleachRoute } from "@pleach/core/quickstart";

export const POST = createPleachRoute();
// app/page.tsx
"use client";
import { ChatBox } from "@pleach/core/quickstart/react";

export default function Home() {
  return <ChatBox apiUrl="/api/chat" />;
}

Run npm run dev. You have a streaming chat against Anthropic.

useChat and <ChatBox /> import from @pleach/core/quickstart/react; createPleachRoute stays on @pleach/core/quickstart, which loads on a server with no react installed. The old useChat and ChatBox names on @pleach/core/quickstart still work on Node and in SSR but are deprecated, and browser code must import from the /react subpath.

.env setup

The runtime checks env vars in priority order. The first one with a non-empty value wins. The default order scans Anthropic, OpenAI and OpenRouter first, then DeepSeek and Google, then Mistral and Moonshot, so ANTHROPIC_API_KEY wins over OPENROUTER_API_KEY when both are set, and OPENAI_API_KEY wins over GOOGLE_API_KEY. A DeepSeek or Google key on its own streams from that vendor's own OpenAI-compatible endpoint. A Mistral or Moonshot key on its own is detected, but the route answers 503 no_provider_key until you pass a providerStream. This behavior is regression-tested in the package suite.

ProviderEnv var
AnthropicANTHROPIC_API_KEY
DeepSeekDEEPSEEK_API_KEY
GoogleGOOGLE_GENERATIVE_AI_API_KEY (or legacy GOOGLE_API_KEY)
MistralMISTRAL_API_KEY
MoonshotMOONSHOT_API_KEY
OpenAIOPENAI_API_KEY
OpenRouterOPENROUTER_API_KEY

Default model. With only OPENROUTER_API_KEY set, the default provider stream calls deepseek/deepseek-v4.1-flash-1017. Pass model to use another slug.

The seven-provider surface mirrors the ProviderFamily set exported from @pleach/core/modelfamily plus OpenRouter as a gateway transport. The (family × callClass) resolution matrix itself is host-supplied — you provide it through the AgentAdapter.resolveModel<C>() seam. See Provider detection for the full resolution matrix and how to override priority.

What you get

  • Streaming response — <ChatBox /> renders tokens as they arrive via the useChat hook, which speaks Pleach's StreamEvent discriminated union directly.
  • Multi-turn memory — useChat owns a sessionId and reuses it across calls. Each user message appends to the same session history.
  • Stop is a user stop — useChat().stop() aborts the in-flight request. The hook declares its disconnect intent on every execute request (PLEACH_ON_DISCONNECT_HEADER), so createPleachRoute classifies the abort as "user" and runtime.wasLastTurnAbortedByUser() is true. See Stopping a streamed turn from the client.
  • bot.reset() equivalent — in the React surface, this is clearMessages() on the useChat return; on the recipes path (below), it's bot.reset() or bot.newSession() on the Chatbot.
  • ChatStreamError rejection — when the underlying stream emits { type: "error" } or the generator throws, the failure surfaces to the caller. The original cause is preserved on error.cause; any stream-emitted code is preserved on error.code. The factory contract is in @pleach/recipes/chatbot.

The agent has a name. The quickstart agent is called Hazel, and its identity section opens with "Your name is Hazel." Pass agentName to createPleachRoute or createPleachAgent to choose another name, or agentName: null to leave it unnamed. A name: line in the heartwood wins over the option. A name over 32 characters, one with characters outside letters, digits, space and .-_', or a reserved label such as you, user or assistant names nobody.

Beyond one route: the whole family

createPleachRoute mounts the single execute leg. When you want the rest of what the runtime speaks — sessions CRUD, interrupts, checkpoints, rollback, events-recall, sync, fork — reach for the standalone-agent façade from the same subpath:

// app/api/harness/[...path]/route.ts
import { createPleachAgent } from "@pleach/core/quickstart";

const agent = createPleachAgent({
  context: { provider: "anthropic", systemPrompt: "You are a helpful assistant." },
  // tools defaults to the base-tools bundle
  // db omitted → in-memory durable store (recall works, no Supabase)
});

export const { GET, POST, PUT, DELETE } = agent.nextRoutes();

createPleachAgent({ context, tools, db }) takes three arms and hands back the whole route family plus agent.store for direct reads. Omit db and it uses an in-memory DurableStore — recall and the audit ledger work with no external database, state resets on restart. See Standalone agent for the lower-level createPleachRoutes factory and the durable interrupt-resolver note.

The family turns the approval authority on by default. A gated tool call (interrupt: { interruptBefore: [...] }) pauses only for a user your own resolveUserId names, and the resolve must present the approvalNonce from that turn's interrupt.requested frame. With no resolveUserId, gated calls are refused. A tool flagged requiresApproval pauses only when you also pass an interrupt config (interrupt: {} is enough). Without one there is no interrupt manager to ask through, so the call is refused even when resolveUserId is set. Pass approvalAuthority: false to opt out. See Interrupts → Who can decide.

Troubleshooting

"No provider API key found in environment." (HTTP 503)

The route handler fails loudly when no provider env var is set rather than silently falling back to a stub. Surface the 503 in your client; it's the signal that ANTHROPIC_API_KEY (or your equivalent) didn't reach the runtime.

The error payload is:

{
  "error": "no_provider_detected",
  "detail": "No provider API key found in environment. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY, or pass `provider` to createPleachRoute()."
}

Fix: set one of the env vars from the table above, or pass provider: "anthropic" explicitly to createPleachRoute({ provider }). A custom providerStream does not resolve a provider by itself: with no key in the environment, pin provider alongside it, or the route still answers this 503.

There is no keyless mode. With no provider key the route refuses every turn with HTTP 503 and a typed JSON body, { error: "no_provider_key", provider, envVar, detail }, where detail names the env var to set. A canned answer proves no value prop, so one is never served. Set a real key to chat.

localStorage is not defined

If you see this from the runtime in an SSR / Node context (server route, serverless function, test harness), it was resolved 2026-06-15 in fix(core): generateClientId guards window.localStorage consistently (jsdom + SSR safe). generateClientId() now checks typeof window === "undefined" || !window.localStorage before attempting any read.

Upgrade @pleach/core to a version published after 2026-06-15.

ChatStreamError rejection

Chatbot.ask() (on the recipes path) rejects with ChatStreamError when the underlying stream fails. The original failure is preserved:

try {
  await bot.ask("hello");
} catch (err) {
  if (err instanceof ChatStreamError) {
    console.error("stream failed", err.message);
    console.error("root cause:", err.cause);
    console.error("stream code:", err.code);
  }
}

Common root causes: provider API key invalid (check .env), provider rate limit hit, request aborted upstream. Inspect err.cause for the provider-level error.

Alternative: @pleach/recipes/chatbot (no route handler)

If you don't need an HTTP boundary — for example you're building a CLI, a Node script, or a server-internal helper — reach for the recipes path:

npm install @pleach/recipes @pleach/core
import { simpleChatbot } from "@pleach/recipes/chatbot";
import { AiSdkProvider } from "@pleach/core";
import { anthropic } from "@ai-sdk/anthropic";

const bot = simpleChatbot({
  systemPrompt: "You are a helpful assistant.",
  provider: new AiSdkProvider({ model: anthropic("claude-sonnet-4-6") }),
});

console.log(await bot.ask("hello"));
console.log(await bot.ask("what did I just say?"));  // same session
await bot.reset();
console.log(await bot.ask("fresh conversation"));    // new session

Unlike the route handler, simpleChatbot does NOT auto-detect provider env vars. You pass the provider explicitly; the model comes from the provider. With no provider (and no orchestratorConfig), ask() rejects with NoProviderConfiguredError rather than returning canned text.

The bot.runtime field is the underlying SessionRuntime. Use it directly when you need plugins, checkpoint inspection, custom observers, or anything below the ask() surface. See Upgrading to @pleach/core.

Where to go next