The Open Standard for Generative UI
---
title: "Pi Coding Agent"
---
<Example
prompt="Read package.json and show this project's scripts and dependencies as a dashboard."
image="/integrations/examples/pi-coding-agent"
width={1600}
height={1300}
alt="The Pi harness answering a request to summarize package.json. Pi calls its read tool, and OpenUI renders a project dashboard with dependency, dev dependency and script counts, tabs, and a table of development dependencies."
href="https://github.com/thesysdev/openui/tree/main/examples/harnesses/pi"
>
The `pi` harness embeds the Pi coding agent in a Next.js app and points it at a folder on your machine. Here it ran with read-only tools: Pi read the project's `package.json` and answered with a dashboard instead of a wall of text.
```bash title="Terminal"
cd examples/harnesses/pi
pnpm install --ignore-workspace
cp .env.example .env # add your THESYS_API_KEY
# read-only: Pi can read files but can't run commands or edit them
PI_WEB_TOOLS=read-only pnpm dev -- /absolute/path/to/your/project
```
</Example>
<Steps>
<Step title="Embed the Pi SDK" source="https://github.com/thesysdev/openui/blob/main/examples/harnesses/pi/src/lib/pi-session.ts">
Create one Pi `AgentSession` per chat thread with `createAgentSession`, and reuse it on later turns: Pi keeps the transcript itself. Point the session's model at OpenUI Cloud and append the generated OpenUI prompt to Pi's system prompt.
```ts title="src/lib/pi-session.ts"
import { join } from "node:path";
// Builds the OpenUI prompt; copy src/lib/cloud-prompt.ts from the example.
import { cloudInstructions } from "./cloud-prompt";
// Call once per chat thread and reuse the session: Pi keeps its own transcript.
export async function createSession(cwd: string) {
// The Pi SDK is ESM-only, so load it with a native dynamic import().
const pi = await import("@earendil-works/pi-coding-agent");
const agentDir = pi.getAgentDir();
const settingsManager = pi.SettingsManager.create(cwd, agentDir);
const shared = { cwd, agentDir, settingsManager };
// OpenUI Cloud is the model; copy src/lib/openui-cloud-models.json from the example.
const authStorage = pi.AuthStorage.inMemory();
authStorage.setRuntimeApiKey("openui-cloud", process.env.THESYS_API_KEY!);
const modelsPath = join(process.cwd(), "src/lib/openui-cloud-models.json");
const modelRegistry = pi.ModelRegistry.create(authStorage, modelsPath);
const model = modelRegistry.find("openui-cloud", "google/gemini-3.6-flash-free");
// Append the OpenUI Lang prompt (the example also passes coding-agent rules to it).
const resourceLoader = new pi.DefaultResourceLoader({
...shared,
appendSystemPrompt: [cloudInstructions()],
});
await resourceLoader.reload();
const { session } = await pi.createAgentSession({
...shared,
resourceLoader,
authStorage,
modelRegistry,
model,
});
return session;
}
```
</Step>
<Step title="Translate Pi events" source="https://github.com/thesysdev/openui/blob/main/examples/harnesses/pi/src/app/api/chat/route.ts">
Subscribe to the session and write each event as an OpenAI `chat.completion.chunk` on its own NDJSON line: text deltas go in `delta.content`, and reasoning and tool executions go in `delta.tool_calls`.
```ts title="src/app/api/chat/route.ts"
// One OpenAI chat.completion.chunk per NDJSON line.
function ndjsonChunk(delta: Record<string, unknown>, finishReason: string | null = null) {
return `${JSON.stringify({
id: "pi-chat",
object: "chat.completion.chunk",
choices: [{ index: 0, delta, finish_reason: finishReason }],
})}\n`;
}
// Inside the POST handler's ReadableStream: `session` is this thread's Pi session,
// `enqueue(line)` writes to the response, and `userText` is the newest user message.
let toolIndex = 0;
const unsubscribe = session.subscribe((event) => {
if (event.type === "message_update") {
const ame = event.assistantMessageEvent;
if (ame.type === "text_delta" && ame.delta) {
enqueue(ndjsonChunk({ content: ame.delta }));
}
// thinking_delta streams into a single "Thinking" tool call the same way.
} else if (event.type === "tool_execution_start") {
// Each tool run (read, bash, edit, write) becomes an OpenAI tool call card.
const call = {
index: toolIndex++,
id: event.toolCallId,
type: "function",
function: { name: event.toolName, arguments: JSON.stringify(event.args) },
};
enqueue(ndjsonChunk({ tool_calls: [call] }));
}
});
await session.prompt(userText);
unsubscribe();
enqueue(ndjsonChunk({}, "stop"));
```
</Step>
<Step title="Render with the NDJSON adapter" source="https://github.com/thesysdev/openui/blob/main/examples/harnesses/pi/src/app/page.tsx">
Parse the stream with `openAIReadableStreamAdapter()`, and render the answers, reasoning and tool activity with `AgentInterface` or with your own UI built on `ChatProvider`.
```tsx title="src/app/page.tsx"
"use client";
import {
AgentInterface,
fetchLLM,
openAIMessageFormat,
openAIReadableStreamAdapter,
} from "@openuidev/react-ui";
import { openuiLibrary } from "@openuidev/react-ui/genui-lib";
// fetchLLM POSTs { threadId, messages }; the route reuses one Pi session per threadId.
const llm = fetchLLM({
url: "/api/chat",
streamAdapter: openAIReadableStreamAdapter(),
messageFormat: openAIMessageFormat,
});
export default function Home() {
return <AgentInterface llm={llm} componentLibrary={openuiLibrary} />;
}
```
</Step>
</Steps>