Prisma Integration
NodeLLM + Prisma made simple. Persist chats, messages, and tool calls automatically.
Added in v0.2.0
- Understanding the Persistence Flow v0.1.0+
- Setting Up Your Application
- Basic Chat Operations
- Streaming Responses
- Analytical Views (Insights) v0.1.0+
- Advanced Usage
- Error Handling
- Agent Sessions v0.5.0+
Understanding the Persistence Flow v0.1.0+
Before diving into setup, it’s important to understand how NodeLLM handles message persistence. This design ensures that your database remains the source of truth, even during streaming or complex tool execution loops.
How It Works
When calling chat.ask("What is the capital of France?"), the ORM adapter:
- Creates a User Message in your database with the input content.
- Creates an Empty Assistant Message immediately. This serves as a “placeholder” for streaming or pending responses.
- Fetches History automatically from the database to provide full context to the LLM.
- Executes the Request via the NodeLLM core:
- On Tool Call Start: Creates a record in the
ToolCalltable. - On Tool Call End: Updates the
ToolCallrecord with the result. - On Response: Logs the full API metric (tokens, latency, cost) to the
Requesttable.
- On Tool Call Start: Creates a record in the
- Finalizes the Assistant Message: Updates the previously created placeholder with the final content and usage metrics.
Why This Design?
- Streaming Optimized: Creates the database record immediately so your UI can target a specific ID for real-time updates.
- Audit Ready: Captures partial tool execution data if a process crashes mid-loop.
- Automated Cleanup: If the API call fails or is aborted, the ORM automatically cleans up the message records to prevent orphaned “empty” messages.
Setting Up Your Application
1. Schema Configuration
The fastest way to get started is to use the NodeLLM ORM CLI. Run this command in your project root to generate the required Prisma schema:
npx @node-llm/orm init
This will create a prisma/schema.prisma file (or provide instructions if one already exists) populated with the standard models.
Alternatively, you can manually copy the reference models below. You can customize the model names (e.g., using AssistantChat instead of LlmChat) using the Custom Table Names option.
model LlmChat {
id String @id @default(uuid())
model String?
provider String?
instructions String?
metadata Json? // Use Json for metadata
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
messages LlmMessage[]
requests LlmRequest[]
agentSession LlmAgentSession? // v0.5.0+
}
// Agent Session - Links Agent class to persistent Chat (v0.5.0+)
model LlmAgentSession {
id String @id @default(uuid())
agentClass String // Class name for validation (e.g., 'SupportAgent')
chatId String @unique
metadata Json? // Session context (userId, ticketId, etc.)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
chat LlmChat @relation(fields: [chatId], references: [id], onDelete: Cascade)
@@index([agentClass])
@@index([createdAt])
}
model LlmMessage {
id String @id @default(uuid())
chatId String
role String // user, assistant, system, tool
content String?
contentRaw String? // JSON raw payload
reasoning String? // Chain of thought (deprecated)
thinkingText String? // Extended thinking text (v0.2.0+)
thinkingSignature String? // Cryptographic signature (v0.2.0+)
thinkingTokens Int? // Tokens spent on thinking (v0.2.0+)
inputTokens Int?
outputTokens Int?
modelId String?
provider String?
createdAt DateTime @default(now())
chat LlmChat @relation(fields: [chatId], references: [id], onDelete: Cascade)
toolCalls LlmToolCall[]
requests LlmRequest[]
@@index([chatId])
@@index([createdAt])
}
model LlmToolCall {
id String @id @default(uuid())
messageId String
toolCallId String // ID from the provider
name String
arguments String
thought String? // The LLM's reasoning for this tool call
thoughtSignature String? // Signature for the thought
result String?
createdAt DateTime @default(now())
message LlmMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)
@@unique([messageId, toolCallId])
@@index([messageId])
@@index([createdAt])
}
model LlmRequest {
id String @id @default(uuid())
chatId String
messageId String?
provider String
model String
statusCode Int
duration Int // milliseconds
inputTokens Int
outputTokens Int
cost Float?
correctionRounds Int? // Number of self-correction retries (v0.7.0+)
cachedTokens Int? // Input tokens served from the prompt cache (v0.10.0+)
createdAt DateTime @default(now())
chat LlmChat @relation(fields: [chatId], references: [id], onDelete: Cascade)
message LlmMessage? @relation(fields: [messageId], references: [id], onDelete: Cascade)
@@index([chatId])
@@index([createdAt])
}
2. Database Migrations
For production-grade systems, always use Prisma Migrate instead of db push. This ensures you have a versioned history of changes and prevents accidental data loss.
See the Database Migration Guide for detailed instructions.
2. Manual Setup
Initialize the adapter with your PrismaClient and NodeLLMCore instance.
import { PrismaClient } from "@prisma/client";
import { createLLM } from "@node-llm/core";
import { createChat, loadChat } from "@node-llm/orm/prisma";
const prisma = new PrismaClient();
const llm = createLLM();
Basic Chat Operations
The ORM Chat implementation provides a fluent API that mirrors the core NodeLLM experience.
Creating and Loading Chats
// Start a new session with reasoning enabled by default
const chat = await createChat(prisma, llm, {
model: "claude-sonnet-5",
instructions: "You are a helpful assistant.",
thinking: { budget: 16000 }
});
// Load an existing session from DB (automatically rehydrates history)
const savedChat = await loadChat(prisma, llm, "chat-uuid-123");
Asking Questions
When you use .ask(), the persistence flow runs automatically.
// This saves the user message, calls the API, and persists the response
const messageRecord = await chat.ask("What is the capital of France?");
// You can also pass thinking configuration directly per request
const advancedResp = await chat.ask("Solve this logical puzzle", {
thinking: { budget: 32000 }
});
console.log(messageRecord.content); // "The capital of France is Paris."
console.log(messageRecord.inputTokens); // 12
Streaming Responses
For real-time user experiences, use askStream(). The assistant message record is “finalized” once the stream completes.
for await (const chunk of chat.askStream("Tell me a long story")) {
if (chunk.content) {
process.stdout.write(chunk.content);
}
}
// History is now updated in the DB
const history = await chat.messages();
Analytical Views (Insights) v0.1.0+
The ORM is great at storing data, but querying it for usage insights (e.g., “How many tokens did this user spend?”) can be complex. NodeLLM provides a built-in stats() method that aggregates conversation-level metrics efficiently using Prisma’s aggregate features.
Conversation Summary
const chat = await loadChat(prisma, llm, "chat-uuid-123");
const stats = await chat.stats();
console.log(`Input Tokens: ${stats.input_tokens}`);
console.log(`Output Tokens: ${stats.output_tokens}`);
console.log(`Total Cost: $${stats.cost}`);
This method is significantly more efficient than fetching and summing all message records manually, as it performs the calculation directly inside the database.
Advanced Usage
Custom Table Names
If you are integrating with an existing database schema, you can map the ORM to your custom table names:
const tableNames = {
chat: "AssistantChat",
message: "AssistantMessage",
toolCall: "AssistantToolCall",
request: "AssistantRequest"
};
const chat = await createChat(prisma, llm, {
model: "gpt-5",
tableNames: tableNames
});
Custom Stores
Chats and agent sessions record through a store. By default that’s your Prisma client, but anything that implements ChatStore works in its place. That’s useful when the code that talks to the model can’t reach the database, such as a worker on another machine that reports to your API:
import { createAgentSession, type ChatStore } from "@node-llm/orm";
class ApiStore implements ChatStore {
async createChat(chat) {
return post("/llm/chats", chat);
}
async createMessage(message) {
return post("/llm/messages", message);
}
// ...updateMessage, listMessages, createToolCall, finishToolCall, createRequest and the rest
async listToolCalls(messageIds) {
// Optional: lets loadAgentSession() give back earlier turns' tool calls
return post("/llm/tool-calls/search", { messageIds });
}
}
const session = await createAgentSession(new ApiStore(), llm, SupportAgent, {
tools: [lookupOrder] // tools for this session, in place of the agent class's own
});
The records are the same as in the Prisma tables (chats, messages, tool calls with their results, and a request row per API call with its duration, tokens and cost), so one schema serves both. createChat, loadChat, createAgentSession and loadAgentSession take a store or a Prisma client; isChatStore() tells them apart.
Stopping a Run From the Store
A store can stop a chat or agent session before its next request, such as when a spending limit kept outside the app is reached. Return { stop: reason } from createRequest; the ask then throws StoppedByStoreError with that reason instead of sending its next request. The tool calls that already ran keep their results in the history, and later asks on the same chat or session stop the same way.
import { StoppedByStoreError } from "@node-llm/orm";
class ApiStore implements ChatStore {
async createRequest(request) {
const { overLimit } = await post("/llm/requests", request);
if (overLimit) return { stop: "The monthly AI limit is reached." };
}
// ...
}
try {
await session.ask("Explore the checkout");
} catch (error) {
if (error instanceof StoppedByStoreError) console.log(error.reason);
}
Subagents count too v0.12.0+: every request of a subagent started from the session’s tools (Agent.toTool(), runAgents(), agentsTool()) is recorded as a request row under the answer being written, with its model and cost, and { stop } stops those workers before their next request as well. Requests sent to another model by routeModel are recorded with the model each one used.
Secrets Aren’t Saved
Everything a chat or agent session saves passes through a mask first: API keys and tokens (sk-..., AIza..., Bearer ... and the like) and passwords in URLs (postgres://user:...@host) are replaced by [REDACTED] in message text, thinking, tool arguments and tool results. It applies to the Prisma store and to custom stores alike. Tool arguments stay valid JSON.
To mask more, such as personal data your app knows about, pass redact:
const session = await createAgentSession(prisma, llm, SupportAgent, {
redact: (text) => text.replace(/\bACCT-\d+\b/g, "[ACCOUNT]")
});
createChat, loadChat and loadAgentSession take it too. It runs after the key masking, on text being saved; what the model sees is unchanged.
Using Tools
Tools are automatically tracked without additional configuration.
import { WeatherTool } from "./tools/weather";
await chat.withTool(WeatherTool).ask("How is the weather in London?");
// Check your database:
// The 'LlmToolCall' table will contain the 'get_weather' execution details.
Concurrent & Confirmed Tool Execution v0.8.0+
createChat/loadChat accept the same toolConcurrency and toolExecution options as core’s Chat (or set them fluently with withToolConcurrency() / withToolExecution()):
import { ToolExecutionMode } from "@node-llm/core";
const chat = await createChat(prisma, llm, {
model: "gpt-5",
toolConcurrency: true, // run independent tool calls in the same turn in parallel
toolExecution: ToolExecutionMode.CONFIRM
});
chat.onConfirmToolCall((call) => {
return call.function.name !== "delete_account"; // require approval per call
});
chat.onToolCallError((call, error) => {
console.error(`Tool ${call.function.name} failed:`, error);
return "STOP"; // or "CONTINUE" / "RETRY"
});
Tool Choice & Structured Output v0.8.0+
toolChoice and toolCalls mirror core’s Chat for forcing/restricting tool calls, and schema (or .withSchema()) enables structured output:
import { z } from "zod";
const chat = await createChat(prisma, llm, {
model: "gpt-5",
toolChoice: { type: "function", function: { name: "get_weather" } }, // force a specific tool
toolCalls: "one", // restrict to one tool call per turn instead of running several in parallel
schema: z.object({ summary: z.string() })
});
withToolChoice() / withToolCalls() are available fluently too. A schema passed at createChat()/loadChat() time is applied via the same normalization as .withSchema(), so a raw Zod schema works either way.
onConfirmToolCall requires every registered handler to approve a call before it runs; onToolCallError uses the first handler that returns a directive, while still calling every registered handler so each can observe the failure.
Error Handling
If an API call fails, NodeLLM follows a “clean rollback” strategy:
- The pending Assistant message is deleted.
- The initial User message is preserved so you have a record of the request for debugging.
- The error is thrown for your application to handle.
This ensures your database doesn’t fill up with “broken” chat turns.
Agent Sessions v0.5.0+
For stateful agents that need to persist across requests (e.g., support tickets, user sessions), use AgentSession. This wraps an Agent class with database persistence.
The “Code Wins” Principle
The Problem with Traditional Systems:
In traditional AI applications, if you want to resume a conversation, you have to load the implementation details (model, instructions, tools) from the database. If you updated your prompt in the code, the stale database version continues to be used instead of your improved version.
NodeLLM’s Solution:
AgentSession follows a hybrid sovereignty model where code always wins for configuration, but database always wins for history:
| Aspect | Source | Why |
|---|---|---|
| Model | Agent class (code) | Deploy upgrades immediately |
| Tools | Agent class (code) | Only code can execute functions |
| Instructions | Agent class (code) | Fix prompts without migrations |
| History | Database | Sacred, never modified |
When you resume a session after deploying new code, the session gets the new configuration but preserves the conversation history.
Schema Addition
Add LlmAgentSession to your Prisma schema:
model LlmAgentSession {
id String @id @default(uuid())
agentClass String // Class name for validation (e.g., 'SupportAgent')
chatId String @unique
metadata Json? // Session context (userId, ticketId, etc.)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
chat LlmChat @relation(fields: [chatId], references: [id], onDelete: Cascade)
@@index([agentClass])
@@index([createdAt])
}
// Update LlmChat to include the relation
model LlmChat {
// ... existing fields
agentSession LlmAgentSession?
}
Creating Sessions
import { Agent, Tool, z, createLLM } from "@node-llm/core";
import { createAgentSession, loadAgentSession } from "@node-llm/orm/prisma";
// Define your agent (config lives in code). The session metadata is the
// agent's input type.
class SupportAgent extends Agent<{ userId: string; ticketId: string }> {
static model = "gpt-4.1";
static instructions = "You are a helpful support agent. Be concise.";
static tools = [LookupOrderTool, CancelOrderTool];
}
const prisma = new PrismaClient();
const llm = createLLM({ provider: "openai" });
// Create a new persistent session
const session = await createAgentSession(prisma, llm, SupportAgent, {
metadata: { userId: "user_123", ticketId: "TKT-456" }
});
await session.ask("Where is my order #789?");
console.log(session.id); // "abc-123" - save this!
The class’s settings apply unless a session sets its own. Any agent setting except schema can be given for one session, such as a budget for one run:
const session = await createAgentSession(prisma, llm, ResearchAgent, {
maxCost: 0.5, // in place of ResearchAgent.maxCost
maxToolCalls: 40,
tools: [searchDocs] // in place of the class's tools
});
These settings aren’t saved with the session. Pass them to loadAgentSession() again when you resume it: loadAgentSession(prisma, llm, ResearchAgent, id, { maxCost: 0.5 }).
Structured Answers
For an agent with a schema, the record session.ask() returns has the parsed answer as data, typed from the schema. It is found inside a code fence or surrounding text and checked against a Zod schema, so you don’t parse content yourself. Reading data throws the schema’s error when the answer doesn’t match. data isn’t saved: it isn’t a column, and it is left out when the record is serialized.
class Repairer extends Agent<{}, z.infer<typeof proposal>> {
static model = "claude-sonnet-5-5";
static schema = proposal;
}
const session = await createAgentSession(prisma, llm, Repairer);
const answer = await session.ask("The Save button moved.");
answer.data.action; // typed, checked against the schema
Calls Made Outside the Agent
When a tool calls a model itself, such as asking a vision model about a screenshot, pass that answer to session.countCall(). It is saved as a request row under the answer being written, and counted in the agent’s usage, so stats(), totalUsage and maxCost include it:
const answer = await llm.chat("claude-haiku-5-5").ask("What is on this screen?", { images });
await session.countCall(answer);
Resuming Sessions
// Later, in a new request
const session = await loadAgentSession(prisma, llm, SupportAgent, "abc-123");
if (!session) {
throw new Error("Session not found");
}
// Continues with full history + current code config
await session.ask("Can you cancel that order?");
The history includes the tool calls of earlier turns and their results, placed before the answer they led to, so the model knows what it already looked up. A custom store gives them back through its optional listToolCalls(messageIds); without it, a loaded session gets only the messages’ text.
Resuming After a Restart
A run that stops part way, because its process restarted or crashed, keeps what it recorded: its question, and each tool call with its result as it finished. Load the session and ask it to carry on; it sees the calls that finished, and a call that never finished is left out:
// On start-up, for each run that was still going
const session = await loadAgentSession(prisma, llm, ResearchAgent, run.sessionId);
await session?.ask("You were interrupted. Continue where you left off.");
The model’s text from the stopped turn isn’t kept, since it is recorded when the turn ends; its tool calls are.
Class Validation
For safety, loadAgentSession validates that the stored agentClass matches the class you’re loading with:
// This throws an error - class mismatch
await loadAgentSession(prisma, llm, SalesAgent, "support-session-id");
// Error: Agent class mismatch: Session "support-session-id" was created for
// "SupportAgent", but is being loaded with "SalesAgent".
There is currently no option to bypass this check — loadAgentSession always validates the stored agentClass against the class you pass in.
Session Properties
| Property | Description |
|---|---|
session.id | The AgentSession UUID (for persistence) |
session.chatId | The underlying LlmChat UUID |
session.metadata | Session context (userId, ticketId, etc.) |
session.agentClass | Stored class name |
session.ask() | Send message with persistence |
session.askStream() | Stream response with persistence |
session.messages() | Get all messages from DB |
session.modelId | Current model (from code) |
session.totalUsage | Aggregate token usage |
session.instance | The underlying Agent instance, for direct access |
session.history | Current in-memory message history |
session.withTool(tool) | Add a turn-level tool to the session |
session.withInstructions(text) | Add turn-level instructions to the session |
session.updateMetadata(partial) | Merge and persist new metadata, re-resolving agent config |
session.delete() | Delete the session’s underlying chat (and cascade the session record) |