TypeScript SDK for managed SaaS, licensed, and self-hosted IgnitionRAG deployments. Zero dependencies, compatible with Node.js 20+, Bun, edge runtimes and browsers. API keys stay in trusted server runtimes; browsers use delegated user tokens.
npm install @ignitionai/sdk@next
# or
bun add @ignitionai/sdk@nextThis source tree prepares 1.0.0 for contract 2026.11; publication is a
separate reviewed release step. ingest.file and ingest.url are breaking
changes from 0.3.0-rc.4: they return AsyncIngestResult.
The latest tag remains on the stable 0.2.x line until the official promotion.
import { IgnitionAI } from "@ignitionai/sdk";
const client = new IgnitionAI({
apiKey: "ign_xxxxxxxxxxxx",
baseURL: "https://rag.example.com",
});Or use the IGNITION_API_KEY environment variable:
const client = IgnitionAI.fromEnv({
baseURL: "https://rag.example.com",
});const client = new IgnitionAI({
apiKey: "ign_xxxx", // trusted runtime only
baseURL: "https://rag.example.com", // required: your deployment
maxRetries: 3, // default: 2
timeout: 60_000, // default: 60_000ms
fetch: customFetch, // custom fetch implementation
});There is deliberately no hosted SaaS fallback. An omitted baseURL is a configuration error.
import { IgnitionAI } from "@ignitionai/sdk/browser";
const client = new IgnitionAI({
baseURL: "https://rag.example.com",
tokenProvider: () => authSession.getAccessToken(),
});The browser export rejects API keys at runtime and in TypeScript.
const deployment = await client.compatibility.assertCompatible();
console.log(deployment.contractVersion, deployment.capabilities);The SDK caches metadata briefly and fails explicitly on an unsupported version
or a changed digest under its current contract version. This client recognizes
deployments advertising 2026.11, 2026.10 or 2026.09. This is
new-client compatibility with older deployments: SDKs that do not recognize
2026.11 must be upgraded before connecting to a 2026.11 deployment.
The current revision requires the exact generated shape digest. Previous-revision
admission checks the version and advertised capabilities; it does not compare
the previous deployment digest with the current revision digest.
The prospective compatibility policy starts with 2026.09; it does not restore
capabilities removed before that baseline.
The direct client.chat methods below are the licensed/self-hosted contract.
Managed SaaS callers should use client.chat.managed, documented below.
const response = await client.chat.send({
collectionId: "coll_xxxx",
query: "What is the refund policy?",
});
console.log(response.answer);
console.log(`${response.sources.length} sources used`);const stream = client.chat.stream({
collectionId: "coll_xxxx",
query: "Explain the onboarding process",
});
for await (const event of stream) {
if (event.type === "chunk") {
process.stdout.write(event.content);
}
if (event.type === "sources") {
console.log("\nSources:", event.sources.length);
}
}for await (const text of stream.toTextStream()) {
process.stdout.write(text);
}const { text, sources, metrics } = await stream.getFullResponse();Track RAG pipeline stages in real time:
const stream = client.chat.streamProgressive({
collectionId: "coll_xxxx",
query: "Compare pricing plans",
});
for await (const event of stream) {
switch (event.type) {
case "stage":
console.log(`[${event.stage}] ${event.elapsed}ms`);
break;
case "sources":
console.log(`Found ${event.sources.length} sources`);
break;
case "chunk":
process.stdout.write(event.content);
break;
case "metrics":
console.log(`\nTotal: ${event.pipelineMetrics.totalTimeMs}ms`);
break;
}
}const stream = client.agentChat.stream("agent_xxxx", {
query: "How do I configure SSO?",
// sessionId auto-generated if omitted
});
for await (const event of stream) {
switch (event.type) {
case "chunk":
process.stdout.write(event.content);
break;
case "tool_call":
console.log(`\n[Tool: ${event.name}]`);
break;
case "tool_result":
console.log(`[Result: ${event.name}]`);
break;
case "sources":
console.log(`\n${event.sources.length} sources`);
break;
}
}Monitor and cancel a Deep Research run that was started by an agent. Closing
the stream only stops the local listener; call cancel() to stop the remote
execution.
const current = await client.deepResearch.status("agent_xxxx");
if (current) {
console.log(current.execution.status, current.execution.tokenCount);
}
for await (const event of client.deepResearch.stream("agent_xxxx")) {
console.log(event.type, event.data);
}
await client.deepResearch.cancel("agent_xxxx");The direct agent methods below retain the licensed/self-hosted configuration
contract, including deployment-owned model and MCP settings. Managed SaaS uses
the separate client.agents.managed and client.agentChat.managed contracts.
// List
const agents = await client.agents.list();
// Get
const agent = await client.agents.get("agent_xxxx");
// Create
const agent = await client.agents.create({
name: "Support Bot",
collectionId: "coll_xxxx",
model: "gpt-4.1-mini",
temperature: 30,
enabledBuiltinTools: [
"web_search",
{ id: "calculator", humanInTheLoop: true },
],
mcpServers: [
{
name: "Slack",
url: "https://mcp.example.com/slack",
toolPolicies: {
post_message: { humanInTheLoop: true },
},
},
],
});
// Generate config with AI wizard
const config = await client.agents.generate({
description: "A customer support agent for our SaaS platform",
language: "en",
});
// Update
await client.agents.update("agent_xxxx", { temperature: 50 });
// Delete (soft)
await client.agents.delete("agent_xxxx");
// Delete (permanent)
await client.agents.delete("agent_xxxx", true);const validation = await client.workflows.validate("workflow_xxxx");
if (!validation.valid) {
console.error(validation.errors);
}
const run = await client.workflows.execute("workflow_xxxx", {
input: { question: "Summarize the latest customer feedback" },
});
// SaaS: the server derives the credit envelope from the workspace balance.
const managedRun = await client.workflows.executeManaged("workflow_xxxx", {
requestId: crypto.randomUUID(),
input: { question: "Summarize the latest customer feedback" },
});
const execution = await client.workflows.getExecution(run.executionId);
console.log(execution.status, execution.output);
const history = await client.workflows.listExecutions("workflow_xxxx", {
limit: 20,
});
if (execution.status === "running") {
await client.workflows.cancelExecution(execution.id);
}Aborting the HTTP request does not cancel a remote workflow execution. Use
cancelExecution() when the execution itself must stop.
execute() remains the licensed deployment contract. SaaS callers must use
executeManaged(); the server resolves providers and tariffs and rejects
client-supplied model or secret fields.
The direct widget methods retain the licensed deployment contract. Managed SaaS
uses client.widgets.managed and omits provider selection and secret fields.
Manage embeddable collection, agent, and workflow widgets through the same authenticated client.
const created = await client.widgets.create({
name: "Support",
type: "agent",
agentId: "agent_xxxx",
allowedDomains: ["https://app.example.com"],
position: "bottom-right",
});
console.log(created.widgetKey, created.embedCode);
await client.widgets.update(created.widget.id, {
welcomeMessage: "How can I help?",
theme: { preset: "dark", primaryColor: "#6d28d9" },
});
const analytics = await client.widgets.analytics(created.widget.id, "30d");
console.log(analytics.totalSessions, analytics.resolutionRate);
const rotated = await client.widgets.regenerateKey(created.widget.id);
console.log(rotated.embedCode);The widget key is returned only at creation or rotation time. Store it in the integrating application; do not confuse it with the server-side API key.
client.dataChat is deprecated and retained for older deployments whose
/api/meta advertises data_connectors. Contract 2026.09 does not expose Data
Chat. Both helpers check that capability first and raise
UnsupportedCapabilityError before sending a request to a retired route when
it is absent. They do not redirect the query to another service.
On a compatible legacy deployment, query collections and external data connectors through the same governed request. Run the precheck first when you want to surface incompatible or unavailable sources before execution.
const resources = [
{ type: "collection" as const, id: "coll_xxxx" },
{ type: "data_connector" as const, id: "connector_xxxx" },
];
const precheck = await client.dataChat.precheck({
llmConfigId: "llm_xxxx",
resources,
});
if (!precheck.compatible) {
console.warn(precheck.resources.filter((resource) => !resource.compatible));
}
const response = await client.dataChat.send({
query: "Compare Q2 revenue with the signed customer reports",
llmConfigId: "llm_xxxx",
resources,
});
console.log(response.answer);
if (response.completeness === "partial") {
console.warn("Missing sources:", response.missingSources);
}Every source reports its own outcome and provenance. A failed connector can therefore produce an explicit partial response instead of hiding the failure or discarding successful results from the other sources.
// List
const collections = await client.collections.list();
const readable = await client.collections.list({
includeShared: true,
includePublic: true,
});
// Browse the dedicated public catalog and resolve one item by slug
const publicCatalog = await client.collections.listPublic({
minTier: "pro",
query: "labor",
});
const publicDataset = await client.collections.getPublic("code-du-travail");
console.log(publicDataset.sampleQueries);
for (const collection of readable) {
if (collection.isReadOnly) {
console.log(`${collection.name} is readable but not writable`);
}
if (collection.requiredPlanId) {
console.log(`${collection.name} requires ${collection.requiredPlanId}`);
}
}
// Create
const coll = await client.collections.create({
name: "Product Docs",
description: "All product documentation",
});
// Search
const results = await client.collections.search("coll_xxxx", {
query: "authentication",
limit: 10,
filters: [{ field: "category", operator: "eq", value: "security" }],
});
// Browse chunks
const { chunks, total, hasMore } = await client.collections.chunks("coll_xxxx", {
limit: 20,
type: "text",
});
// Stats & insights
const stats = await client.collections.stats("coll_xxxx");
const insights = await client.collections.insights("coll_xxxx");
// Update / Delete
await client.collections.update("coll_xxxx", { name: "Renamed" });
await client.collections.delete("coll_xxxx");Shared and public collections expose access metadata on Collection:
isReadOnly, accessTier, publisherOrgId, slug, and requiredPlanId.
Treat isReadOnly: true as a hard no-write signal for ingestion, sync, delete,
and workflow output storage.
import { PermissionError } from "@ignitionai/sdk";
try {
await client.ingest.document({
collectionId: "coll_public",
content: "New text",
filename: "note.txt",
});
} catch (error) {
if (error instanceof PermissionError) {
console.log(error.reasonCode); // COLLECTION_READ_ONLY or PUBLIC_COLLECTION_PLAN_REQUIRED
console.log(error.collectionId);
console.log(error.requiredPlanId);
}
}On managed SaaS, members use the metered async routes. ingest.file,
ingest.url, and ingest.document queue a durable job and return
AsyncIngestResult. Wait with getJob or streamJob.
// Single URL (POST /api/ingest/url/async)
const fromUrl = await client.ingest.url({
collectionId: "coll_xxxx",
url: "https://docs.example.com/guide",
});
await client.ingest.getJob(fromUrl.jobId);
// Raw text as a file (POST /api/ingest/file/async)
const fromText = await client.ingest.document({
collectionId: "coll_xxxx",
content: "Your document content...",
filename: "guide.txt",
});
await client.ingest.getJob(fromText.jobId);
// Upload file (durable job; SaaS rejects sync /ingest/file)
const started = await client.ingest.file({
collectionId: "coll_xxxx",
file: new File([buffer], "report.pdf", { type: "application/pdf" }),
enableMultimodal: true,
});
await client.ingest.getJob(started.jobId);Synchronous site crawl, dataset import, and discovery remain license-only.
On SaaS they throw OfferingUnavailableError (OFFERING_UNAVAILABLE) instead
of a 503 AI_TEMPORARILY_UNAVAILABLE outage. Members should call the async
variants:
await client.ingest.crawlAsync({
collectionId: "coll_xxxx",
url: "https://docs.example.com",
maxPages: 50,
});
await client.ingest.datasetAsync({
collectionId: "coll_xxxx",
datasetId: "squad",
split: "train",
limit: 1000,
});Licensed and self-hosted deployments still admit ingest.crawl,
ingest.dataset, and ingest.discover. For long ingestions, the asynchronous
variants return a jobId immediately; transport cancellation does not cancel
the remote job.
const discovered = await client.ingest.discover({
url: "https://docs.example.com",
maxPages: 500,
});
const job = await client.ingest.crawlSelectedAsync({
collectionId: "coll_xxxx",
urls: discovered.pages.map((page) => page.url),
});
console.log(job.jobId);
await client.ingest.fileAsync({
collectionId: "coll_xxxx",
file: new File([buffer], "manual.pdf", { type: "application/pdf" }),
});Score the quality of a collection with synthetic questions (auto-generated) or your own golden set (CSV-style). Runs asynchronously — create the job, poll for status, receive an email when it's done.
// Auto-eval: 10 LLM-generated questions from your chunks
const run = await client.evaluations.create("coll_xxxx", {
numQuestions: 10,
notifyEmail: "team@acme.com", // optional, fallback to requester email
});
console.log(run.status); // "queued"
// Poll until completion
let detail = await client.evaluations.get(run.id);
while (detail.status !== "completed" && detail.status !== "failed") {
await new Promise((r) => setTimeout(r, 5000));
detail = await client.evaluations.get(run.id);
}
console.log(`Score: ${detail.result?.aggregate.score}/100`);
// Custom eval with your own questions + expected answers
const custom = await client.evaluations.create("coll_xxxx", {
goldenSet: [
{ query: "Quel est le délai de rétractation ?", expectedAnswer: "14 jours calendaires", expectedKeywords: ["14", "jours"] },
{ query: "Qui paie les cotisations ?", expectedAnswer: "L'employeur" },
{ query: "Comment fonctionne le PACS ?" }, // answer optional → grounded-in-context judge
],
});
// History
const history = await client.evaluations.list("coll_xxxx");
history.forEach((e) => console.log(e.id, e.score));
// Re-run with the same questions (to A/B a config change)
await client.evaluations.create("coll_xxxx", {
inheritFromEvaluationId: run.id,
});Cost: every question runs the full RAG pipeline + an LLM judge against your BYOK provider. Budget ~€0.02 per 10 questions on gpt-4.1-mini pricing. Caps: 30 synthetic / 50 user-provided per run.
// Aggregate stats across all docs: extraction methods, OCR, chunking strategies, warnings
const report = await client.collections.qualityReport("coll_xxxx");
console.log(
report.totalDocuments,
report.chunking.strategyDistribution, // { "legal-article": 8, "semantic": 2 }
report.warnings.topMessages,
);
// Per-doc listing with ingestion report attached
const docs = await client.collections.documents("coll_xxxx");
docs.forEach((doc) => {
console.log(doc.filename, doc.ingestionReport?.chunking.strategy);
});import { RETRIEVAL_PRESETS } from "@ignitionai/sdk";
// Apply a named preset (Balanced / Precision / Recall / Speed)
await client.collections.applyRagPreset("coll_xxxx", "PRECISION");
// Or inline a custom partial config
await client.collections.applyRagPreset("coll_xxxx", RETRIEVAL_PRESETS.RECALL);
// Force a specific chunking strategy for future ingestions
await client.collections.setDefaultChunkingStrategy("coll_xxxx", "semantic");
await client.collections.setDefaultChunkingStrategy("coll_xxxx", null); // clear overridePresets write to the collection's ragConfig via PUT /rag-config. Combined with evaluation re-runs, this enables a simple A/B loop: applyRagPreset → create({ inheritFromEvaluationId }) → compare scores.
MCP servers belong to each private IgnitionRAG deployment. The former client.mcp helper remains temporarily available so existing 0.2.x integrations do not break, but it is deprecated and excluded from new quickstarts. Configure and operate MCP through the deployment itself.
All errors extend IgnitionAIError. HTTP errors are automatically mapped:
import {
IgnitionAI,
RateLimitError,
AuthenticationError,
NotFoundError,
} from "@ignitionai/sdk";
try {
await client.chat.send({ collectionId: "coll_xxxx", query: "Hello" });
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof AuthenticationError) {
console.log("Invalid API key");
} else if (error instanceof NotFoundError) {
console.log("Resource not found");
}
}| Error Class | Status Code |
|---|---|
BadRequestError |
400 |
AuthenticationError |
401 |
PermissionError |
403 |
NotFoundError |
404 |
RateLimitError |
429 |
InternalServerError |
500+ |
APIConnectionError |
Network failure |
APIConnectionTimeoutError |
Timeout |
Retries are automatic for status codes 408, 429, 500, 502, 503 and 504 with exponential backoff. Mutating requests are retried only when an Idempotency-Key header is supplied.
Drop-in adapter for Next.js with useChat():
import { IgnitionAI } from "@ignitionai/sdk";
import { toAIStreamResponse } from "@ignitionai/sdk/adapters/vercel-ai";
const client = IgnitionAI.fromEnv({
baseURL: process.env.IGNITION_BASE_URL!,
});
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = client.chat.stream({
collectionId: process.env.COLLECTION_ID!,
query: messages.at(-1).content,
history: messages.slice(0, -1),
});
return toAIStreamResponse(stream);
}"use client";
import { useChat } from "ai/react";
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
<div>
{messages.map((m) => (
<div key={m.id}>
{m.role}: {m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleInputChange} />
</form>
</div>
);
}Works with AgentChatStream too:
const stream = client.agentChat.stream(agentId, { query, sessionId });
return toAIStreamResponse(stream);| Variable | Description | Required |
|---|---|---|
IGNITION_API_KEY |
API key (starts with ign_) |
Yes (or pass in constructor) |
IGNITION_BASE_URL |
Your deployment URL (pass it as baseURL) |
Yes |
Use the explicit managed namespace for SaaS chat. It accepts an optional
maximumMilliCredits ceiling as a positive integer string (at most 16 digits);
"1000" means a ceiling of one credit, not a fixed charge. These methods reject
model and LLM configuration overrides before sending a request, with or without
a budget. The server selects the model and applies workspace policy.
await client.chat.managed.send({
collectionId: "collection-id",
query: "Summarize the onboarding procedure.",
maximumMilliCredits: "1000",
});
const stream = client.chat.managed.stream({
collectionId: "collection-id",
query: "Summarize the onboarding procedure.",
});
for await (const event of stream) {
if (event.type === "chunk") process.stdout.write(event.content);
}Managed response DTOs omit model/provider configuration and internal usage
metadata. Existing client.chat.send, stream, and streamProgressive methods
remain the licensed/self-hosted compatibility contract.
Use the managed agent namespace for agent resources and the durable metered chat
admission API. Requests require an idempotency requestId, session, and server
credit ceiling. Poll or cancel the returned execution explicitly; a streaming
licensed agent-chat call is not the managed admission contract.
const agent = await client.agents.managed.create({
name: "Support assistant",
collectionId: "00000000-0000-4000-8000-000000000001",
systemPrompt: "Answer from the approved support content.",
enabledBuiltinTools: ["web_search"],
});
const execution = await client.agentChat.managed.start(agent.id, {
requestId: crypto.randomUUID(),
sessionId: "support-session-1",
query: "How do I update my billing details?",
maximumMilliCredits: "1000",
});
const current = await client.agentChat.managed.get(agent.id, execution.executionId);Managed agent contracts accept business prompts and resource references but
omit provider, model, MCP credential, and runtime fields. The existing
client.agents and client.agentChat.stream methods remain available for
licensed/self-hosted deployments.
const created = await client.widgets.managed.create({
name: "Support widget",
type: "agent",
agentId: "agent-id",
allowedDomains: ["https://app.example.com"],
theme: { preset: "dark", primaryColor: "#6d28d9" },
});
console.log(created.widgetKey, created.embedCode);Managed widget inputs allow presentation and supported business settings only.
The response omits provider selection and secret escalation targets. The
one-time widget key is returned at creation or rotation so the embed can be
installed. Existing client.widgets methods preserve the licensed deployment
contract.
- Node.js 20+ / Bun / modern browser
- Zero dependencies
MIT