Resonance is a network of machines that run AI models. You send it a request — the same shape as an OpenAI chat request — and it picks a node that serves the model, runs the job and streams the answer back. You never rent a GPU or deploy a model.
What makes it different to build on is the shape of the capacity: many nodes, each serving requests at the same time. Work that splits into independent pieces — scoring 500 leads, triaging an inbox, reading every page of a handbook — runs side by side instead of in a queue.
What people build
Business copilots
A CRM that scores deals and writes follow-ups, a helpdesk that triages and drafts replies.
Knowledge tools
Ask questions over docs, contracts or wikis and get answers with sources.
Batch pipelines
Classify, extract or summarise thousands of records in parallel.
Agents
Tool-using agents built with the SDK that call models on the network and act on the results.
Five words cover the whole model. The first two you already have if you run a node; the other three are how you give apps and teams their own slice of it.
Your machines
Physical nodelaptop · server · GPU box
Physical nodeholds the real key rk_…
→
You group them
Clusterthe trust boundary
→
Your apps use
Logical node “crm-prod”own key rk_s_… · own usage
Logical node “helpdesk”own key rk_s_… · own usage
Logical node “acme-tenant”own key rk_s_… · own usage
Concept
What it is
Why it matters
Physical node
A real machine running resonance. It serves inference for the network and has one API key, rk_<node-id>.<secret>.
It's your identity on the network. Its key never needs to leave the machine.
Cluster
A group you create and attach your physical nodes to.
It's the boundary keys are inherited across. You can only attach a node you can authenticate as, so nobody can borrow someone else's key.
Logical node
A virtual node inside a cluster, with a label and a region. It has no hardware of its own.
One per app, environment, team or customer: each gets its own key, its own usage meter and its own start/stop switch.
Inherited key
The key of a logical node, rk_s_…: derived from the cluster, valid while the cluster has a physical node, expires after 24 hours.
You give apps a key you can scope and replace, not your machine's master key.
Protocol
A packaged piece of logic that runs in a least-privilege sandbox, deployable onto clusters and logical nodes.
Ship reusable behaviour (a pipeline, an agent) with only the permissions it declares.
Why not just use the node's key everywhere?
You can — for a script on your own laptop it's the simplest choice. But the node key is the machine's identity: rotating it (resonance api-key rotate) touches everything that machine runs, and every request made with it shows up as one bucket of usage. As soon as there is more than one app, or code you deploy somewhere else, give each one a logical node:
Separate usage. Each logical node counts its own requests and tokens (GET /v1/logical-nodes/:id/usage) — per app, per environment, or per customer you resell to.
Small blast radius. A leaked rk_s_ key works only through its cluster and lapses within a day. Your machine's key was never in the app.
Inherited, not copied. Add a second machine to the cluster and the logical nodes keep working on it; remove the last physical node and every inherited key stops at once.
API keys & inheritance
There are two kinds of key. Both go in the same place — Authorization: Bearer … — and work with every endpoint in these docs.
Key
Looks like
Where it comes from
Use it for
Node key
rk_<node-id>.<secret>
resonance api-key on the machine, or the copy button in resonance web
Local scripts, the VS Code extension, creating clusters
Logical node key
rk_s_…
GET /v1/logical-nodes/:id/api-key
Apps you deploy, teams, customers
Your node key
resonance api-key # show this machine's key
resonance api-key rotate # issue a new key; the old one stops working
Rotation happens on the node — from the CLI, the TUI or resonance web — and the VS Code extension on that machine picks up the new key automatically.
Give an app its own key, step by step
Four calls, run once with your node key. Save the two owner tokens they return: they are what lets you manage the cluster and the logical node later.
Create a cluster. Pass your node id as owner so your node key can manage it later too.
export NODE_KEY=$(resonance api-key) # rk_<node-id>.<secret>
export NODE_ID=${NODE_KEY#rk_}; export NODE_ID=${NODE_ID%%.*}
curl -s https://net.narsill.io/v1/clusters \
-H "Authorization: Bearer $NODE_KEY" -H "Content-Type: application/json" \
-d "{\"label\": \"my-apps\", \"owner\": \"$NODE_ID\"}"
# → { "id": "cl_…", "ownerToken": "ot_…" } save them as CLUSTER_ID and CLUSTER_OWNER_TOKEN
Attach your machine. This is where the key is inherited from. You authenticate as the node you attach, so only your own machines can back your cluster.
The app now calls /v1/chat/completions with Bearer rk_s_… exactly as it would with any key, and its traffic is counted on crm-prod.
What happens on every request
Logical node keys · pick what happened
✓Signature matches
✓Not expired (24 h)
✓Not revoked
✓Logical node exists, in this cluster
✓Logical node is running
✓Cluster has a physical node
Response200served — usage metered to crm-prod
Valid key. Every check passes, so the request is served and its usage is counted on the logical node.
The rules
24-hour keys. A logical node key expires a day after it is issued. Fetch a fresh one from your backend on a schedule (step 4) — the owner token stays valid, so this is one call.
Backed by a machine. A logical node key works only while its cluster has at least one physical node. Remove the last one (DELETE /v1/clusters/:id/nodes/:nodeId) and every key in the cluster stops at once.
Null means no backing. If step 4 returns {"apiKey": null}, the logical node isn't in a cluster with a physical node yet — go back to step 2.
The real key stays home. The node key is never sent to the logical node or the app; the rk_s_ key is issued by the network for that cluster.
Owner tokens (ot_…) are capabilities: anyone holding one can manage that cluster or logical node. Keep them on your server like the keys themselves.
The SDK wraps the same flow as resonance.clusters, resonance.nodes and resonance.keys — see Network and nodes and API keys.
Your first app
A tiny lead scorer, in plain JavaScript with fetch — three moves most apps are made of: ask for JSON, fan out in parallel, stream the long answer.
1. Pick a model
The Models page compares every model on the network; the API lists their ids:
curl https://net.narsill.io/v1/models # use any "model_id" from the list
2. Ask for structured output
Tell the model the exact JSON you want, then parse it. Low temperature keeps it on format.
const API = "https://net.narsill.io/v1/chat/completions";
const KEY = process.env.RESONANCE_API_KEY; // a logical node key (rk_s_…) or your node key
const MODEL = "GLM-4.7-Flash";
async function scoreLead(lead) {
const res = await fetch(API, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${KEY}` },
body: JSON.stringify({
model: MODEL,
temperature: 0.2,
messages: [
{ role: "system", content: 'Score how likely this deal is to close. Reply ONLY with JSON: {"score": 0-100, "reason": "<short>"}' },
{ role: "user", content: lead },
],
}),
});
if (!res.ok) throw new Error(await res.text());
const text = (await res.json()).choices[0].message.content;
return JSON.parse(text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1));
}
3. Fan out
Each lead is an independent request, so send several at once — the network serves them on different nodes. Cap the concurrency so you stay a good citizen.
async function pool(items, fn, limit = 4) {
const out = []; let i = 0;
await Promise.all(Array.from({ length: limit }, async () => {
while (i < items.length) { const n = i++; out[n] = await fn(items[n]).catch((e) => ({ error: e.message })); }
}));
return out;
}
const scores = await pool(leads, scoreLead); // 50 leads ≈ the time of a dozen, not fifty
4. Stream the long part
For text a person reads — a summary, an email — stream it so the first words appear right away.
const res = await fetch(API, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${KEY}` },
body: JSON.stringify({ model: MODEL, stream: true, messages: [{ role: "user", content: "Write a follow-up email to …" }] }),
});
const reader = res.body.getReader(); const dec = new TextDecoder(); let buf = "";
for (;;) {
const { value, done } = await reader.read(); if (done) break;
buf += dec.decode(value, { stream: true });
let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1);
if (!line.startsWith("data:") || line === "data: [DONE]") continue;
process.stdout.write(JSON.parse(line.slice(5)).choices[0]?.delta?.content ?? "");
}
}
This example calls the API straight from the browser so you can try it with your own key. In a product, put these calls behind your server and keep the key there — give the server a logical node key and refresh it daily.
Prefer a typed client? The SDK does all of this as generateStructured, batch.submit and onToken.
How the network works
Three pieces: your app, the control plane at net.narsill.io, and the nodes — machines running resonance that hold models and serve them. Your app only ever talks to the control plane.
The network · click any piece
Scheduler — Picks the node that can serve each request best — or several nodes together, for a model too big for one machine.
Piece
What it does for you
Control plane
The only address you call. It checks your key, knows which models exist and which nodes are online, picks where each request runs, relays the answer and meters usage.
Nodes
Stay connected to the network, so work reaches them instantly. They run the model and stream tokens back.
Node groups
When a model is too big for one machine, several nodes serve it together — see Big models across nodes.
Model catalogue
GET /v1/models: every model the network serves, with its runtime and tags (text-generation, coding, vision, speech, decision).
What this means when you build
One endpoint, no infrastructure. You never pick, rent or keep a node alive. Ask for a model; the network finds one that serves it.
Many requests at once is the natural shape. Each request is placed independently, so a hundred small requests spread over many nodes instead of queueing on one GPU. Design around that — see Patterns that scale.
Plain HTTP. OpenAI-compatible JSON in, JSON or Server-Sent Events out. Any language, any OpenAI client.
Life of a request
What happens between your fetch and the first token, step by step.
Life of a request · step through it
1 / 8
1. POST /v1/chat/completions — Your app sends the request with Authorization: Bearer <key>. Any OpenAI-compatible client works.
Authenticate. The bearer key is either a node key (rk_…) or a logical node key (rk_s_…), checked for signature, expiry, revocation and cluster backing — see API keys & inheritance. A bad key gets a 401 before anything else runs.
Place. The scheduler picks the node that can serve this request best — or several nodes together, for a very large model (Routing & placement).
Dispatch. The work is signed and handed to the chosen node at once; the node runs only work the network actually assigned.
Generate. The node loads the model if it isn't already warm, runs it and streams tokens back as they're produced.
Relay. The control plane forwards them to you — as chat.completion.chunk events with "stream": true, or as one completion object at the end.
Meter. Usage is counted against the key that called: your node, or the logical node whose key it was. Paid-tier work is charged per second of node time to the wallet behind the key.
If a node fails mid-request, it is excluded for that request and the work is re-planned on the next best node. Node-side failures reach you as a generic, retryable error — never another operator's internals.
Timing you can expect
Warm model: the first token arrives as soon as the node starts generating; streaming hides the rest.
Cold model: the first request to a node that doesn't have the model loaded waits for the load. The scheduler prefers nodes that already have it cached.
Parallel requests don't wait for each other: each is planned on its own.
Routing & placement
Every request goes through the same checks before it is placed. Nothing here needs configuring for a normal chat request — this is what happens for you.
An illustration: the fleet, the checks and the ranking are simplified.
16 nodes → 5 eligible → Mac Studio M2 Ultra. It beats #2 mostly on warm cache; if it fails mid-request, the request is re-planned on #2.
Step
Rule
What you control
Tier
Free work runs on the open network; paid work runs only on paid nodes (marketplace sellers and hardware-attested appliances), which are kept for paid work.
tier: free · paid · auto, and max_price_per_s to cap the price.
Fit
The node has a free slot, supports the model on its platform, and has enough usable memory for it.
model
Privacy level
The default level allows any eligible node. tee keeps work on hardware-attested nodes; private keeps it on your own nodes.
privacy_level on the workloads API (below)
Best node
Among the nodes that pass, the network picks the one likely to answer fastest and most reliably.
—
Privacy levels
Chat completions run at the default level: any eligible node may serve them, and that node's machine processes your prompt to generate the answer. The control plane never writes prompts, attachments or answers to its database — only the request's metadata — and links between nodes serving one model are encrypted. When the content must stay on hardware you choose, use the workloads API with a stricter level — those levels are hard constraints, never preferences:
Level
Where it may run
If nothing matches
standard / encrypted (default)
Any eligible node
—
tee
Only hardware-attested nodes
Refused, with a clear "no eligible node" error
private
Only nodes of your own operator account
Refused, with a clear "no eligible node" error
Run a node yourself and private work never leaves your machines — a simple way to build on the network with data that can't be shared.
Big models across nodes
Some models don't fit in one machine's memory. You still call them like any other model: when no single node can hold it, the network serves it from several nodes together.
One model, several machines · drag the size
140 GB is too big for any one machine → 2 nodes serve it together; every token travels across them and back, over encrypted links.
One node coordinates the answer; the others each compute part of the model for every token.
Data between them travels over encrypted links.
The answer streams back exactly as from a single node, so your code doesn't change.
Splitting adds a network hop per token, so a split model generates more slowly than one that fits on a single machine. The scheduler only splits when it has to; for interactive work, prefer the largest model that fits on one node.
Patterns that scale
A network of many nodes rewards a particular shape of app: lots of small, independent requests rather than one giant one. Three patterns cover most products.
Patterns that scale
8 items: 10.3 s one by one, 3.4 s side by side. Each item is a small JSON request; with five in flight the network serves them on different nodes at once, then one call reduces the results. Relay, Folio and Kestrel work this way.
Fan out, then reduce
Split the work into independent items — leads, tickets, pages — and send one small request per item, a few at a time. Ask each for a compact JSON object. Then send one final request that sees only the results. Relay triages ten tickets this way and then finds the incident they share; Folio reads every handbook page, then answers from the matches.
// one JSON request per item, at most 5 in flight, failures kept per item
const results = await pool(items, (item) => askJson(item), 5);
const summary = await ask(reducePrompt(results.filter((r) => !r.error)));
Chain
When a step needs the previous answer, chain small calls instead of writing one huge prompt: each is easier for the model, cheaper to retry and easy to inspect. Folio rewrites a follow-up into a standalone question, fans out over the pages with it, then answers.
Stream what people read
Anything a person reads — an email, a reply, a brief — should use "stream": true, so text appears while it's generated. Keep an AbortController so people can stop a draft they don't want.
Rules of thumb
Cap concurrency (4–8 per user action) and keep failures per item; one slow item shouldn't sink the batch.
Ask for JSON with an exact shape and a low temperature; parse defensively (find the first { and the last }).
Keep each prompt small: one item, one question. Smaller prompts are faster to prefill and fit more models.
One logical node per app or environment, so each one's usage and keys are separate.
Protocols
A protocol is code that runs on the network: one JavaScript file defining async function run(ctx, input), deployed to the machines of a cluster you own and called over HTTP. It is the simplest way to put logic next to the models — a pipeline, an agent step, an extractor — without running a server.
Protocols · how they work
2. Test on testnet — Every test case runs on your machine in the node's own sandbox (resonance protocol test, or ▶ Test in Studio) — same engine, permissions and limits as the network. Model calls go to the network, or to mock models for free.
One file and a manifest.protocol.js holds the code; resonance.json declares what it may do (permissions); tests.json lists inputs to try.
It runs on your machines. Code only ever runs on the physical nodes of clusters whose owners deployed it — never on someone else's hardware without their choice.
Callers pay for their own model calls. A run token minted for each call bills model usage to whoever called the protocol.
Private until you publish. A deployed draft answers only you; publishing lists it in the registry for everyone.
ctx & permissions
A protocol gets one argument object, ctx, and nothing else: no require, import, process, files or sockets. Each capability works only if resonance.json declares it.
Call
Returns
Needs
ctx.input
the input (also the second argument of run)
—
ctx.log(...args)
a log line (200 per run, 2 KB each)
—
ctx.generate(prompt | messages, { model, system, maxTokens, temperature })
✓ctx.log("hi", {n: 1})a log line (200 lines, 2 KB each)
✓await ctx.generate("Summarize …")one model reply — counts against maxCalls
✓await ctx.generateMany([a, b, c])three replies, side by side — 3 calls
✕await ctx.fetch("https://en.wikipedia.org/…")permission denied: en.wikipedia.org is not in permissions.net
✕await ctx.fetch("http://en.wikipedia.org/…")only https:// URLs are allowed
✕await ctx.fetch("https://intranet.example.lan/")a host must be declared in permissions.net — and private or local addresses are refused even then
✕require("fs") · import · processnot defined: the sandbox has no modules, files or processes
✕for (;;) {}stopped at 30 s (permissions.timeoutMs)
3 of 8 allowed. Permissions are checked by the node, in its own code, before anything happens — the protocol cannot widen them. Studio's testnet and resonance protocol test apply exactly the same rules.
Permission
Default
Limit
inference
false
—
net
[]
public DNS names only — no IPs, localhost, .local or .internal; HTTPS, no redirects, never private addresses
timeoutMs
30 000
120 000
maxCalls
20
100 model + fetch calls per run
Every run also gets 64 MB of memory, 1 MB of input and output, and 2 MB per fetched response. Node operators can turn protocols off entirely with RESONANCE_PROTOCOLS=0.
Sample protocols
Six protocols that run as they are — the same ones Resonance Studio offers as templates (Protocols → New protocol). Each shows one idea; together they cover everything ctx can do.
Hellocode only
The smallest protocol: plain code, no model, no network. Start here.
// hello — the smallest protocol: plain code, no model, no network.
// Run it on the testnet (▶ Test above), change it, run it again.
async function run(ctx, input) {
const name = (input && input.name) || "world";
ctx.log("greeting", name);
return { message: `Hello, ${name}!`, letters: name.length };
}
Summarize1 model call · ctx.json
Any text → a title, a one-line summary and key points, as JSON checked in code.
// summarize — any text → a title, a one-line summary and up to five key points.
// One model call with a JSON reply; the shape is enforced in code before returning.
async function run(ctx, input) {
const text = String((input && input.text) || "").slice(0, 12000);
if (!text.trim()) throw new Error("input.text is required");
const r = await ctx.json(
'Summarize the text. Reply as {"title": string, "summary": string (one sentence), "points": [up to 5 short strings]}.\n\n' + text,
{ maxTokens: 400, temperature: 0.2 },
);
return {
title: String(r.title || ""),
summary: String(r.summary || ""),
points: Array.isArray(r.points) ? r.points.map(String).slice(0, 5) : [],
};
}
Triagectx.generateMany · fan-out
Label many messages at once — one model call each, in parallel — with labels checked against a list.
// triage — label many support messages at once. Each message is classified in
// parallel (ctx.generateMany: one model call each, side by side on the network); any
// label outside the allowed list is rejected in code.
const LABELS = ["billing", "bug", "outage", "how-to", "feedback"];
async function run(ctx, input) {
const items = ((input && input.messages) || []).map(String).slice(0, 16);
const replies = await ctx.generateMany(
items.map((m) => `Label this support message with exactly one of: ${LABELS.join(", ")}. Reply with the label only.\n\n${m}`),
{ maxTokens: 8, temperature: 0 },
);
const results = items.map((message, i) => {
const label = replies[i].trim().toLowerCase().replace(/[^a-z-]/g, "");
return { message, label: LABELS.includes(label) ? label : "unknown" };
});
const counts = {};
for (const l of LABELS) counts[l] = results.filter((r) => r.label === l).length;
return { results, counts };
}
Councilfan-out → reduce · 4 calls
Three reviewers answer at the same time, then a chair merges their views into a recommendation.
// council — three reviewers with different perspectives answer at the same time,
// then a chair merges their views. Fan-out → reduce in two steps.
const SEATS = [
["skeptic", "You look for risks, costs and what could go wrong."],
["builder", "You look for the fastest way to make it work."],
["user", "You speak for the end user: clarity, value, friction."],
];
async function run(ctx, input) {
const question = String((input && input.question) || "");
if (!question) throw new Error("input.question is required");
const views = await ctx.generateMany(
SEATS.map(([, role]) => [
{ role: "system", content: role + " Answer in at most three sentences." },
{ role: "user", content: question },
]),
{ maxTokens: 200 },
);
ctx.log("views", views.length);
const verdict = await ctx.json(
"Question: " + question + "\n\n" + SEATS.map(([n], i) => n + ": " + views[i]).join("\n\n") +
'\n\nMerge these views. Reply as {"recommendation": string, "confidence": "low"|"medium"|"high", "dissent": string}.',
{ maxTokens: 300 },
);
const byName = {};
SEATS.forEach(([n], i) => { byName[n] = views[i]; });
return { views: byName, recommendation: verdict.recommendation, confidence: verdict.confidence, dissent: verdict.dissent };
}
Wiki digestctx.fetch · permissions.net
Fetch a Wikipedia summary (the only host it may reach) and explain it for any audience.
// wiki-digest — fetch a Wikipedia page summary and explain it for an audience.
// ctx.fetch can reach only the hosts in resonance.json → permissions.net (here just
// en.wikipedia.org), over HTTPS, never private addresses.
async function run(ctx, input) {
const topic = encodeURIComponent(String((input && input.topic) || "Peer-to-peer").replace(/ /g, "_"));
const res = await ctx.fetch("https://en.wikipedia.org/api/rest_v1/page/summary/" + topic, {
headers: { accept: "application/json", "user-agent": "resonance-protocol-sample/1.0" },
});
if (!res.ok) throw new Error("Wikipedia answered " + res.status);
const page = await res.json();
const audience = (input && input.audience) || "a curious 12-year-old";
const explained = await ctx.generate("Explain this to " + audience + " in three sentences:\n\n" + page.extract, { maxTokens: 220 });
return { title: page.title, source: page.content_urls ? page.content_urls.desktop.page : null, explained };
}
Extractctx.json · checks in code
Messy text (an invoice email) → typed fields, validated in code: the model reads, code decides.
// extract — messy text (an invoice email) → typed fields, then validated in code.
// The model reads; the code decides what is valid (date format, lines adding up).
async function run(ctx, input) {
const text = String((input && input.text) || "");
const r = await ctx.json(
'Extract from the text: {"vendor": string, "invoice_number": string|null, "date": "YYYY-MM-DD"|null, "currency": ISO code, "total": number, "lines": [{"item": string, "amount": number}]}.\n\n' + text,
{ maxTokens: 500, temperature: 0 },
);
const lines = Array.isArray(r.lines) ? r.lines : [];
const sum = Math.round(lines.reduce((a, l) => a + Number(l.amount || 0), 0) * 100) / 100;
const problems = [];
if (!/^\d{4}-\d{2}-\d{2}$/.test(r.date || "")) problems.push("missing or malformed date");
if (lines.length && Math.abs(sum - Number(r.total)) > 0.01) problems.push("lines add up to " + sum + ", the total says " + r.total);
return { vendor: r.vendor, invoice_number: r.invoice_number, date: r.date, currency: r.currency, total: Number(r.total), lines, checks: { ok: problems.length === 0, problems } };
}
Build in VS Code
Resonance Studio turns the four steps into four buttons — on its Protocols page, and right above run in the editor:
New protocol. Pick a template; Studio creates protocols/<name>/ with the code, the manifest, tests and a README.
▶ Test on testnet. Every case in tests.json runs on your machine — in the node's own sandbox when the resonance CLI is installed. expect checks the output ("*" = any non-empty value); mock models make runs free and offline. The network's save checks appear as you type, as editor errors.
⬆ Deploy to my cluster. Saves a new version and deploys it to your cluster — Studio creates one with your node if you have none. Run on network runs the tests on your nodes; Logs shows the last runs.
◎ Publish. After a confirmation it is in the registry. The registry in Studio lets you try any published protocol, run it on your own nodes too, or fork its code.
Without VS Code, test any file in the node's sandbox:
resonance protocol test protocols/summarize/protocol.js \
--input '{"text": "Resonance is a peer-to-peer AI network…"}'
# → { "ok": true, "output": {…}, "logs": […], "ms": 3135, "calls": 1 }
Deploy, run & publish (HTTP)
The same steps over plain HTTP. Your node's key (resonance api-key) makes you the owner of what you create.
KEY=$(resonance api-key)
API=https://net.narsill.io
# 1. Save it — returns {"id": "proto_…"}. New code later: POST $API/v1/protocols/$ID {"source": …}
jq -n --rawfile src protocol.js --slurpfile m resonance.json \
'{name: $m[0].name, source: $src, permissions: $m[0].permissions}' |
curl -s $API/v1/protocols -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d @-
# 2. Deploy it onto a cluster you own (its physical nodes run it)
curl -s $API/v1/protocols/$ID/deploy -H "Authorization: Bearer $KEY" \
-H "Content-Type: application/json" -d '{"clusters": ["'$CLUSTER_ID'"]}'
# 3. Run it — any API key once published; model calls are billed to the caller
curl -s $API/v1/protocols/$ID/run -H "Authorization: Bearer $KEY" \
-H "Content-Type: application/json" -d '{"input": {"text": "…"}}'
# → { "ok": true, "output": {…}, "logs": […], "ms": 812, "calls": 1, "node": "rn_…", "version": "1.0.1" }
# 4. Publish it
curl -s -X POST $API/v1/protocols/$ID/publish -H "Authorization: Bearer $KEY"
Endpoint
What it does
GET /v1/protocols
The registry of published protocols. ?mine=1 with your key lists yours, drafts included.
GET /v1/protocols/:id
Name, version, permissions, deployments, how many nodes are ready; the source if published (or yours).
POST /v1/protocols/:id
New source or permissions make a new version; the old one is kept.
POST /v1/protocols/:id/rollback
{"version": "1.0.0"} — back to a saved version.
POST /v1/protocols/:id/stop · /start
Pause or resume every deployment.
POST /v1/protocols/:id/undeploy
Remove it from clusters or nodes.
GET /v1/protocols/:id/logs
The last 50 runs with their logs and errors (owner only, kept in memory only).
GET /v1/protocols/:id/metrics · /status · /instances
Runs, errors, p50/p95 latency, and where it can run now.
A run answers 503 with the reason when no node can take it: not deployed yet, or no node of its clusters is online with protocol support (resonance 0.7.23 or newer).
The Resonance node
The node is the client that joins a machine to the Resonance network. One binary, resonance, runs in the background and serves inference jobs you get paid for.
Run resonance with no command to open the Hub — the home screen for this machine; it links this machine to your account on first run. Everything else is a subcommand below.
Supported platforms: macOS (Apple Silicon), Linux (x86_64), and Windows via install.ps1.
Wait for the confirmation email and open the link inside it to verify your address.
Sign in, open My machines, and request the one-line installer command for a new node.
Access rolls out gradually during the alpha, so admin approval can take a little while. A newly registered node keeps retrying until it is whitelisted.
Install the node
Request your exact command from the console, then run it on the machine you want to add. The installer downloads the right prebuilt binary and sets it to start at boot.
# one-line installer (get the exact command from the console)
curl -fsSL https://net.narsill.io/install.sh | sh
Guided or manual setup
The installer first asks how you want to configure the machine. Pick Guided (recommended) and it asks a few short questions — whether to run a node and whether you want the terminal UI or a headless server — then shows the setup it picked and asks you to approve it. Pick Manual to choose a mode yourself.
Either way the choice decides whether bare resonance opens the Hub or (for a headless server) just reports status. You can change it later in resonance config.
Manual modes
Full
A desktop machine you use directly: the node, with the Hub.
TUI
A terminal interface for the node, for servers you check over SSH without a desktop.
Headless
No interface, boot service only. For remote servers and always-on nodes.
Pairing & access
A node must be linked to your account before it can work. Linking is one command.
resonance pair
On a machine you are sitting at, resonance pair shows a QR code: scan it with your signed-in session to link instantly. A remote or headless machine has no screen to scan, so link it with the short-lived pairing code shown in the console under My machines instead.
Pairing links the machine to you. Whitelisting (admin approval) is separate: a freshly registered node keeps retrying until an admin approves it.
Node commands
The node is driven by the resonance command. These are the everyday ones.
resonance # open the Hub / link this machine on first run
resonance node # open the node panel (short: r-node)
resonance network # open the network page (short: r-network)
resonance auth # link this machine (QR), or report status if already linked
resonance pair # link this machine to your account (QR code)
resonance status # version, account link, and whether the node is running
resonance doctor # diagnose setup: config, link, API key, network, engine
resonance config # show the config (paths, network, model, mode)
resonance config --edit # open the config in $EDITOR
resonance update # update to the latest version (--check to only look)
resonance node start # start the node in the background
resonance node status # node status
resonance node logs # recent node logs
resonance node stop # stop the node running in the background
resonance uninstall # remove the node, its data and the boot service
r-node and r-network are short commands that are exactly the same as resonance node and resonance network.
The node home holds identity.json, session.json, apikey and config.json. It lives at $RESONANCE_HOME, or /var/lib/resonance on servers, or ~/.resonance otherwise. To pause or resume taking work without stopping the node, write 0 or 1 to <home>/participate.
Resonance web
resonance web opens everything in your browser — no terminal needed. It starts a small local server on 127.0.0.1 and opens your default browser to it; nothing is served to the network.
resonance web # open the browser app
resonance web --port 7777 # pin a port (default: a free one)
The app is laid out like a code editor: a thin activity rail switches between pages, pages open as tabs you can reorder, close, or drag to the side for a split view, and a status bar at the bottom shows the node version, id and compute score, and whether the node is computing.
Pages
Node — status, hardware, a copyable API key, the participation toggle, and live network stats. A Network page shows the fleet and a live event feed.
Settings — choose the theme and see everything Resonance stores for you on this machine, such as logs, with the option to clear it. Nothing there is uploaded to the network.
It is additive and runs only when you launch it — the headless node and the terminal UIs are unaffected.
VS Code extension
Resonance Studio is a management panel for the network inside VS Code: your nodes, clusters, protocols and the SDK, without leaving the editor. For protocols it turns the whole cycle into buttons: create a protocol from a template, test it on the testnet, deploy it to your cluster and publish it — each one click, also right above run in the editor. It unlocks automatically once a node is linked to your account.
The resonance CLI is a single entry point to the network, so you can explore models, run inference, and manage keys without VS Code.
# explore models
resonance models list
resonance models inspect <model-id>
# run a model
resonance run <model-id> "Explain this code"
resonance inference "Summarize this document" # auto-selects a model
# keys and usage
resonance api-key # show this machine's API key
resonance api-key rotate # issue a new key; the old one stops working
resonance usage # network usage for this machine's key
Integrate over HTTP
The network speaks the OpenAI Chat Completions protocol, so you can call it from any language or tool — curl, your backend, a no-code platform — with no SDK at all.
Base URL https://net.narsill.io. Authenticate with a bearer API key: your node's key (resonance api-key) or a logical node's key — see API keys & inheritance. Every request names a model (list the available ids with List models) and an array of messages.
curl https://net.narsill.io/v1/chat/completions \
-H "Authorization: Bearer $RESONANCE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "GLM-4.7-Flash",
"messages": [{"role": "user", "content": "Explain the Resonance network in one sentence."}]
}'
Keep your API key on a server, never in client-side code you ship. For a deployed app, use a logical node key rather than your node's own key.
Chat completions
POST /v1/chat/completions with a model and a list of messages. Messages use the roles system, user and assistant, exactly like OpenAI.
The reply is a standard completion object; the text is in choices[0].message.content.
{
"id": "cmpl_…",
"object": "chat.completion",
"model": "GLM-4.7-Flash",
"choices": [
{ "index": 0,
"message": { "role": "assistant", "content": "Distributed inference splits one model's work across many machines…" },
"finish_reason": "stop" }
]
}
Streaming
Set "stream": true to receive tokens as Server-Sent Events. Each event is a chat.completion.chunk whose choices[0].delta.content holds the next piece; the stream ends with data: [DONE].
Include the model's chain-of-thought. Default false: only the answer is returned.
tier
string
free, paid or auto. Defaults to the key's stored preference, else free.
max_price_per_s
float
Paid tier: the most to pay per second of node time, in credits.
Free runs on the open network. Paid runs on verified paid nodes, charged per second to the wallet behind your key — add max_price_per_s to cap it. Auto uses paid when your wallet covers the job, free otherwise.
Because the API is OpenAI-compatible, point an existing OpenAI SDK at the Resonance base URL and use your rk_ key — nothing else changes.
# Python
from openai import OpenAI
client = OpenAI(base_url="https://net.narsill.io/v1", api_key="rk_…")
r = client.chat.completions.create(
model="GLM-4.7-Flash",
messages=[{"role": "user", "content": "Hello from Resonance"}],
)
print(r.choices[0].message.content)
// Node.js
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://net.narsill.io/v1", apiKey: "rk_…" });
const r = await client.chat.completions.create({
model: "GLM-4.7-Flash",
messages: [{ role: "user", content: "Hello from Resonance" }],
});
console.log(r.choices[0].message.content);
Want a first-class typed client with vision, audio, structured output, decisions and agents? Use the Resonance SDK below. Using a ready-made tool instead — an editor, a coding agent, a chat app? See Integrations.
Use Resonance in your tools
Resonance speaks the OpenAI Chat Completions protocol, so any tool that lets you set a custom OpenAI base URL can run on the network's models. Three values are all it takes.
Setting
Value
Base URL
https://net.narsill.io/v1 — some tools call it API base, API host, endpoint or proxy URL.
API key
Your node key rk_… (run resonance api-key), or a logical node key rk_s_… for an app or a team — see API keys & inheritance. Sent as Authorization: Bearer.
Model
An id from GET https://net.narsill.io/v1/models (or the Models page), typed exactly — for example GLM-4.7-Flash, GLM-4.7, MiniMax-M2.5, Devstral-2-123B, Qwen3-Coder-480B.
curl https://net.narsill.io/v1/models -H "Authorization: Bearer $RESONANCE_API_KEY" # the model ids
export RESONANCE_API_KEY=$(resonance api-key) # on a machine running the node
Compatibility notes
Type the model id by hand./v1/models returns Resonance's own catalogue format, not OpenAI's {"object": "list", "data": […]}. Tools that fetch the model list will show nothing or an error; add the id manually (each guide below says where).
Native tool calling on the large models.GLM-4.7, GLM-4.7-Flash, MiniMax-M2.5, Devstral-2-123B and Qwen3-Coder-480B accept OpenAI tools and tool_choice, assistant turns with tool_calls (content may be null) and tool turns with tool_call_id. Replies carry message.tool_calls with finish_reason: "tool_calls". When streaming, the calls arrive as one complete delta.tool_calls chunk (index, id, type: "function", function.name, function.arguments) at the end of the turn — not token by token — followed by a chunk with finish_reason: "tool_calls". Whether several calls come in one turn (parallel tool calls) depends on the model. Small community-node models don't support tools: pick one of the models above for agents.
Streaming is standard SSE."stream": true returns chat.completion.chunk events ending with data: [DONE], as every OpenAI client expects.
Tools that speak another API
A few tools only talk to Anthropic's Messages API (Claude Code) or OpenAI's Responses API (Codex CLI). For those, run LiteLLM as a local proxy: it accepts /v1/messages and /v1/responses and forwards them to Resonance as chat completions. The same proxy helps tools that can only pick models from the endpoint's own list (JetBrains AI Assistant): its /v1/models is in OpenAI's format.
For coding agents, Qwen3-Coder-480B and GLM-4.7 handle tools best. Every guide was written from the tool's own documentation; settings move between releases, so follow the official link under each guide if a label differs.
Agent frameworks
Python and TypeScript frameworks take the base URL and key in their OpenAI (or OpenAI-compatible) model class. Every snippet reads the key from RESONANCE_API_KEY and uses GLM-4.7-Flash; swap in any id from /v1/models.
import os, dspy
lm = dspy.LM(
"openai/GLM-4.7-Flash",
api_base="https://net.narsill.io/v1",
api_key=os.environ["RESONANCE_API_KEY"],
model_type="chat", # stay on Chat Completions
)
dspy.configure(lm=lm)
print(lm("Say hello in one sentence."))
Where things go: the model id after openai/, the base URL in api_base, the key in api_key.
model_type="chat" keeps DSPy on Chat Completions rather than OpenAI's Responses API. Tool-using modules work on the tool-capable models listed in the overview.
# Python — pip install semantic-kernel
import os
from openai import AsyncOpenAI
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
client = AsyncOpenAI(api_key=os.environ["RESONANCE_API_KEY"], base_url="https://net.narsill.io/v1")
chat = OpenAIChatCompletion(ai_model_id="GLM-4.7-Flash", async_client=client, service_id="resonance")
kernel = Kernel()
kernel.add_service(chat)
// .NET — dotnet add package Microsoft.SemanticKernel.Connectors.OpenAI
#pragma warning disable SKEXP0010 // custom endpoints are experimental
var builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion(
modelId: "GLM-4.7-Flash",
apiKey: Environment.GetEnvironmentVariable("RESONANCE_API_KEY"),
endpoint: new Uri("https://net.narsill.io/v1"));
var kernel = builder.Build();
Where things go: Python: base URL and key on the AsyncOpenAI client, model in ai_model_id. .NET: endpoint, apiKey, modelId.
Plugins and automatic function invocation work through native function calling: enable them with FunctionChoiceBehavior.Auto() in your execution settings, as in Semantic Kernel's function calling docs.
import os
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
agent = Agent(model=OpenAILike(
id="GLM-4.7-Flash",
api_key=os.environ["RESONANCE_API_KEY"],
base_url="https://net.narsill.io/v1",
))
agent.print_response("Say hello in one sentence.")
Where things go:id is the model, api_key the key, base_url the base URL.
Pass tools=[…] to the agent as usual. Use OpenAILike rather than a Responses-API model class.
import os
from crewai import LLM
llm = LLM(
model="openai/GLM-4.7-Flash",
base_url="https://net.narsill.io/v1",
api_key=os.environ["RESONANCE_API_KEY"],
)
# pass llm=llm to your Agent(...)
Where things go:model="openai/<id>", base_url, api_key.
CrewAI assumes a small context window for models it doesn't know — see its LLM docs to set the real one. Agents with tools work through native function calling.
import os, litellm
r = litellm.completion(
model="openai/GLM-4.7-Flash",
api_base="https://net.narsill.io/v1",
api_key=os.environ["RESONANCE_API_KEY"],
messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(r.choices[0].message.content)
As a proxy — the bridge for tools that don't speak Chat Completions (Claude Code, Codex CLI). Save as config.yaml:
model_list:
- model_name: Qwen3-Coder-480B # the name your tools ask for
litellm_params:
model: openai/Qwen3-Coder-480B # openai/ + the Resonance model id
api_base: https://net.narsill.io/v1
api_key: os.environ/RESONANCE_API_KEY
use_chat_completions_api: true # /v1/responses clients (Codex) → /chat/completions
litellm_settings:
use_chat_completions_url_for_anthropic_messages: true # /v1/messages clients (Claude Code) → /chat/completions
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY # the key your tools send to the proxy
Where things go: model openai/<id>, api_base (ending in /v1) and api_key; in the proxy, model_name is the name clients ask for.
Both flags matter: without them LiteLLM forwards Anthropic- and Responses-format requests to /responses on the backend, which Resonance doesn't serve. The proxy's own /v1/models lists your model_name entries, so tools behind it get a working model list. Tool calls from the client are translated to OpenAI tools and back, so agents behind the proxy keep their full workflow on the tool-capable models.
import os
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider
model = OpenAIChatModel(
"GLM-4.7-Flash",
provider=OpenAICompatibleProvider(
"resonance",
base_url="https://net.narsill.io/v1",
api_key=os.environ["RESONANCE_API_KEY"],
),
)
agent = Agent(model)
print(agent.run_sync("Say hello in one sentence.").output)
Where things go: base URL and key on OpenAICompatibleProvider, the model id on OpenAIChatModel.
Use OpenAIChatModel, not the Responses model. @agent.tool functions and structured output_type (which uses tool calls by default) work on the tool-capable models; for other models wrap the type in PromptedOutput.
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
gen = OpenAIChatGenerator(
api_key=Secret.from_env_var("RESONANCE_API_KEY"),
model="GLM-4.7-Flash",
api_base_url="https://net.narsill.io/v1",
)
print(gen.run([ChatMessage.from_user("Say hello in one sentence.")]))
Where things go:api_key (a Secret), model, api_base_url.
Pass tools=[…] for tool-calling pipelines and agents. Streaming works through streaming_callback.
import os
from llama_index.llms.openai_like import OpenAILike
llm = OpenAILike(
model="GLM-4.7-Flash",
api_base="https://net.narsill.io/v1",
api_key=os.environ["RESONANCE_API_KEY"],
is_chat_model=True, # otherwise calls go to /completions
is_function_calling_model=True, # GLM-4.7, Qwen3-Coder-480B, …
context_window=128000, # set to the model's real window
)
print(llm.complete("Say hello in one sentence."))
Where things go:model, api_base, api_key.
Always set is_chat_model=True. is_function_calling_model=True enables function-calling agents (FunctionAgent); set it to False for models without tools and use ReAct-style agents.
Where things go: Python: base_url, api_key, model. JS: apiKey and model at the top, baseURL inside configuration.
use_responses_api=False keeps LangChain on Chat Completions. bind_tools, tool-calling agents, chains, streaming and RAG all work on the tool-capable models.
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { generateText } from "ai";
const resonance = createOpenAICompatible({
name: "resonance",
apiKey: process.env.RESONANCE_API_KEY,
baseURL: "https://net.narsill.io/v1",
});
const { text } = await generateText({
model: resonance("GLM-4.7-Flash"),
prompt: "Say hello in one sentence.",
});
console.log(text);
Where things go:baseURL and apiKey on createOpenAICompatible, the model id in resonance("<id>").
@ai-sdk/openai-compatible is the AI SDK's provider for OpenAI-compatible endpoints and talks Chat Completions. streamText and tools work on the tool-capable models; add includeUsage: true to the provider settings to get token usage while streaming.
import os
from agents import Agent, AsyncOpenAI, OpenAIChatCompletionsModel, Runner, set_tracing_disabled
set_tracing_disabled(True) # traces are uploaded to OpenAI and need an OpenAI key
client = AsyncOpenAI(base_url="https://net.narsill.io/v1", api_key=os.environ["RESONANCE_API_KEY"])
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant.",
model=OpenAIChatCompletionsModel(model="GLM-4.7-Flash", openai_client=client),
)
print(Runner.run_sync(agent, "Say hello in one sentence.").final_output)
Where things go: base URL and key on the AsyncOpenAI client, the model id on OpenAIChatCompletionsModel.
The SDK defaults to OpenAI's Responses API, which Resonance doesn't serve; OpenAIChatCompletionsModel keeps the agent on Chat Completions. To set this once for every agent, use set_default_openai_client(...) with set_default_openai_api("chat_completions"). @function_tool tools and handoffs work on the tool-capable models.
import { Agent } from "@mastra/core/agent";
const agent = new Agent({
id: "assistant",
name: "Assistant",
instructions: "You are a helpful assistant.",
model: {
id: "custom/GLM-4.7-Flash",
url: "https://net.narsill.io/v1",
apiKey: process.env.RESONANCE_API_KEY,
},
});
const res = await agent.generate("Say hello in one sentence.");
console.log(res.text);
Where things go:url is the base URL (not the /chat/completions address), apiKey the key, id is custom/<model id>.
Mastra doesn't read a key from the environment for a url model, so always pass apiKey. Agent tools go through native tool calls — use a tool-capable model.
import os
from smolagents import CodeAgent, OpenAIModel
model = OpenAIModel(
model_id="GLM-4.7-Flash",
api_base="https://net.narsill.io/v1",
api_key=os.environ["RESONANCE_API_KEY"],
)
agent = CodeAgent(tools=[], model=model)
agent.run("What is 17 * 23?")
Where things go:model_id, api_base, api_key.
OpenAIModel connects to any OpenAI-compatible server (earlier releases called it OpenAIServerModel). CodeAgent writes its actions as Python code, so it works with any model on the network; ToolCallingAgent uses native tool calls and needs a tool-capable model.
import os
from google.adk.agents import LlmAgent
from google.adk.models.lite_llm import LiteLlm
agent = LlmAgent(
name="assistant",
model=LiteLlm(
model="openai/GLM-4.7-Flash",
api_base="https://net.narsill.io/v1",
api_key=os.environ["RESONANCE_API_KEY"],
),
instruction="You are a helpful assistant.",
)
Where things go: all inside LiteLlm: the model as openai/<id>, api_base, api_key.
ADK reaches models outside Gemini through its LiteLlm wrapper — LiteLLM as a library, no proxy to run. The openai/ prefix makes LiteLLM speak Chat Completions. ADK tools are native function calls, so use a tool-capable model. ADK's docs warn that LiteLLM 1.82.7 and 1.82.8 on PyPI were compromised: install a newer version.
Terminal coding agents. These agents read files, edit code and run commands through native tool calls, which Resonance supports on its large models. The snippets use Qwen3-Coder-480B; GLM-4.7 is the other strong choice for tool-heavy work. Avoid small community-node models: they don't support tools.
Claude Code only speaks Anthropic's Messages API, so it needs a bridge: run the LiteLLM proxy with the config shown there (the use_chat_completions_url_for_anthropic_messages flag is the one Claude Code needs), then point Claude Code at the proxy.
litellm --config config.yaml # see the LiteLLM guide
export ANTHROPIC_BASE_URL=http://localhost:4000
export ANTHROPIC_AUTH_TOKEN="$LITELLM_MASTER_KEY"
export ANTHROPIC_DEFAULT_SONNET_MODEL=Qwen3-Coder-480B
export ANTHROPIC_DEFAULT_HAIKU_MODEL=Qwen3-Coder-480B # background tasks
claude --model Qwen3-Coder-480B
Where things go: the Resonance key and base URL in LiteLLM's config.yaml; Claude Code gets the proxy in ANTHROPIC_BASE_URL and the proxy key in ANTHROPIC_AUTH_TOKEN; the model is the proxy's model_name. The same variables can go in the env block of ~/.claude/settings.json.
Every Claude Code action — reading files, editing, running commands — is a tool call; LiteLLM turns them into OpenAI tools and back, so the full agent loop runs on Resonance. Two caveats: Anthropic doesn't support routing Claude Code to non-Claude models, and LiteLLM's Anthropic-to-chat translation has known rough edges on longer conversations — run a multi-turn session with a few edits before relying on it. If the proxy rejects extra request fields, Claude Code's gateway docs suggest CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1.
Codex CLI only speaks OpenAI's Responses API (wire_api = "responses" is the only supported value; "chat" was removed), so it needs a bridge: run the LiteLLM proxy — its use_chat_completions_api: true line turns Responses calls into chat completions — and add it as a provider in ~/.codex/config.toml:
Where things go: the Resonance key and base URL in LiteLLM; Codex gets the proxy in base_url and the name of the variable holding the proxy key in env_key; the model in model. Put this in the user-level file — a project .codex/config.toml ignores model_provider.
Codex runs shell commands and applies patches as function calls; through the proxy they reach Resonance as native tool calls, so the full agent workflow works.
Where things go:OPENAI_API_BASE / OPENAI_API_KEY (or openai-api-base / openai-api-key), the model as openai/<id>.
Aider edits code through text edit formats (diff, whole, udiff) rather than tool calls, so it works with any model on the network. To silence the unknown-model warning, describe the model in .aider.model.settings.yml (e.g. edit_format: diff) or .aider.model.metadata.json.
Where things go: the key in the environment variable named in env, the base URL in settings.baseURL, the model id as a key of models, selected as resonance/<id>.
OpenCode's agent edits files and runs commands with native tool calls, which work on the tool-capable models — the full agent workflow runs on Resonance.
Where things go: the key in the variable named by api_key_env, the URL in base_url (Goose's example uses the full /chat/completions URL), the model in models[].name.
Goose drives its extensions (developer tools, shell, MCP servers) with native tool calls, so pick a tool-capable model and keep extensions on for the full agent workflow.
Custom Model openai/Qwen3-Coder-480B
Base URL https://net.narsill.io/v1
API Key rk_…
Where things go: the three fields above.
Leave native tool calling on with a tool-capable model for the full agent workflow. For a model without tools, turn it off in the same advanced settings: OpenHands then describes its tools in the prompt and parses the calls from text.
Where things go:model.base_url is the network address https://net.narsill.io/v1, model.api_key your key, model.default the model id exactly as in /v1/models — no prefix.
Hermes does its agent work through native tool calls, which work on the tool-capable models. Its docs also ask for at least a 64K context for agent use with tools — Qwen3-Coder-480B and GLM-4.7 qualify.
Where things go:models.providers.resonance holds baseUrl, apiKey and models[].id; agents.defaults.model.primary selects resonance/<id>.
The config is strictly validated — unknown keys stop the gateway from starting. OpenClaw's agent acts through native tool calls, which work on the tool-capable models.
Crush reads a crushrc — Bash with Crush builtins — from ./.crushrc, ./crushrc or ~/.config/crush/crushrc. Add Resonance as a completions provider and register the model:
Where things go:--base-url, --api-key (here read from the environment), the model as resonance/<id>. Pick it in Crush with ctrl+l.
completions is Crush's type for OpenAI-compatible APIs (older configs say openai-compat, which Crush migrates). The JSON config still loads but is deprecated. Crush's agent edits files and runs commands through native tool calls, so use a tool-capable model.
Where things go: environment: OPENAI_BASE_URL, OPENAI_API_KEY, OPENAI_MODEL. settings.json: baseUrl, the variable named in envKey, the model in id — model.name must match it.
Qwen Code's agent reads, edits and runs commands with native tool calls; Qwen3-Coder-480B is the natural pick. Switch models with /model.
Where things go:base_url, the variable named in api_key_env, the model as -m resonance/<id> (or just -m resonance for default_model).
gptme's default tool format has the model write tool calls as fenced code blocks rather than native calls, so it works with any model on the network; its native tool format works on the tool-capable models.
Editors, editor extensions and AI terminals. Chat, inline edits and agent modes (which act through native tool calls) work on the tool-capable models — Qwen3-Coder-480B or GLM-4.7 for agent work.
In Cursor Settings → Models → API Keys: paste your rk_… key as the OpenAI API key, turn on Override OpenAI Base URL and set it to https://net.narsill.io/v1, then add a custom model named exactly Qwen3-Coder-480B.
Where things go: key in the OpenAI API key field, base URL in the override, model id in the custom model list.
Cursor's docs cover bring-your-own-key but not the base URL override itself, and Cursor doesn't officially support providers it doesn't list. Per its docs, requests go through Cursor's servers (Resonance is public, so that works), custom keys only work with chat models, and Tab completion keeps using Cursor's own models. Cursor's docs don't say whether Agent mode is available with your own key. The override applies to every OpenAI-named model, so switch it off to use Cursor's built-in ones again.
Windsurf can't be pointed at a custom OpenAI-compatible endpoint: its documented models are the built-in ones billed through your plan, and the only bring-your-own-key option it has documented is for Anthropic keys. There is no documented bridge. If that changes, the setting will be on Windsurf's models page linked below.
Where things go:api_url is the base URL, available_models[].name the model id. The key goes in the system keychain through the agent settings (agent: open settings → LLM Providers), or in the environment as RESONANCE_API_KEY (Zed reads <PROVIDER_ID>_API_KEY) — never in settings.json.
Keep tools: true so the Agent panel can read and edit files and run commands. Leave parallel_tool_calls off unless the model emits several calls per turn. Set max_tokens to the model's real context size.
Open Settings → AI and find custom inference endpoint (searching settings for “inference endpoint” gets you there). Add the base URL https://net.narsill.io/v1, your rk_… key and the model id Qwen3-Coder-480B, save, and pick the model in the model selector.
Where things go: all three in the custom inference endpoint form.
Requests go through Warp's servers, so the endpoint must be public (Resonance is). Auto model selection keeps using Warp's own models. Warp's agent uses tool calls, so choose a tool-capable model.
capabilities: [tool_use] tells Continue the model supports native tools, which Agent mode needs. Leave it out for a model without tools; Continue can then describe tools in the system message instead (see its model capabilities page).
Open Cline's settings (gear icon), choose API Provider OpenAI Compatible, and fill in:
Base URL https://net.narsill.io/v1
API Key rk_…
Model ID Qwen3-Coder-480B
Where things go: each in its own field; set the context window and max output tokens under Model Configuration.
Cline uses native tool calling for every action — reading files, editing, running commands, browsing — so with a tool-capable model the full agent workflow runs on Resonance.
In Roo Code's settings choose API Provider OpenAI Compatible and fill in:
Base URL https://net.narsill.io/v1
API Key rk_…
Model Qwen3-Coder-480B
Where things go: each in its own field; set the context window and max output tokens under Model Configuration.
Roo Code uses native tool calling exclusively, so use one of the tool-capable models; with them every mode (Code, Architect, Debug) runs its full workflow on Resonance.
Add a custom provider from the extension (Provider API OpenAI Compatible, base URL, key, then add the model id by hand), or in ~/.config/kilo/kilo.jsonc:
Where things go:options.baseURL, options.apiKey, the model id under models and in model as provider/id. {env:…} is only read from the global config; in a project kilo.jsonc paste the key instead.
tool_call: true lets Kilo's agent edit files and use the terminal; keep it on for the tool-capable models.
AI Assistant's OpenAI-compatible provider takes only a URL and a key — the models come from the endpoint — and Resonance's /v1/models isn't in OpenAI's list format. Run the LiteLLM proxy in front (its /v1/models lists your model_name entries), then open Settings | Tools | AI Assistant | Providers & API keys and, under Third-party AI providers, choose OpenAI-compatible:
URL http://localhost:4000/v1
API Key $LITELLM_MASTER_KEY # the proxy key
Tool calling on # tool-capable models only
Where things go: the Resonance key and base URL in LiteLLM's config.yaml; the proxy address and proxy key in AI Assistant. Click Test Connection, then Apply; if the test fails, try the proxy root http://localhost:4000.
The models appear in their own section of the AI Chat model selector. Until you assign them under Models Assignment (Core features, Instant helpers) they are used only in AI Chat. Inline completion is configured separately under AI Completion and isn't covered here.
API Format OpenAI Chat Completions
Custom Request URL https://net.narsill.io/v1 # Full URL switch off
Model ID Qwen3-Coder-480B
API Key rk_…
Where things go: the base URL in Custom Request URL with Full URL off (TRAE appends the path), or https://net.narsill.io/v1/chat/completions with it on; the model id typed in Model ID.
TRAE checks the connection when you click Add Model and shows the error if it fails. Under Advanced Settings, leave Model Series on Default and set Context Window to the model's real size. The agent uses tools, so pick a tool-capable model.
Settings → Model Provider → Add → Add Custom Provider, API type OpenAI API Compatible:
Name Resonance
API Key rk_…
API Host https://net.narsill.io/v1
API Path /chat/completions
Where things go: key in API Key; the URL split across API Host and API Path (the full URL must contain /v1/chat/completions once); model via Models → New, Model ID GLM-4.7-Flash.
Settings → Model Providers → Add Provider, choose the OpenAI-compatible provider type, enter the endpoint https://net.narsill.io/v1 and your rk_… key. Fetch Models won't find anything, so click Add Custom Model and enter GLM-4.7-Flash, keep Show in Model Selector on, and save.
Where things go: endpoint and key in the provider form, the model id via Add Custom Model.
In Settings → Model Providers, add a provider of type OpenAI, paste your rk_… key and set the API Host:
API Host https://net.narsill.io # Cherry appends /v1/chat/completions
# or the exact URL, with # to stop Cherry appending anything:
API Host https://net.narsill.io/v1/chat/completions#
Where things go: key in API Key, address in API Host, the model with the + next to Sync models (Model ID GLM-4.7-Flash). Run Model Check, then turn on the provider switch.
Cherry's rules for appending paths have changed between releases; check the request URL preview under the field ends in exactly one /v1/chat/completions.
In LLM Preference, choose Generic OpenAI and fill in Base URLhttps://net.narsill.io/v1, API Key, Model context window, Max Tokens, and type GLM-4.7-Flash as the model id. For Docker, the same in .env:
LLM_PROVIDER='generic-openai'
GENERIC_OPEN_AI_BASE_PATH='https://net.narsill.io/v1'
GENERIC_OPEN_AI_API_KEY='rk_…'
GENERIC_OPEN_AI_MODEL_PREF='GLM-4.7-Flash'
GENERIC_OPEN_AI_MODEL_TOKEN_LIMIT=32768 # the model's context window
Where things go: Base URL, API Key and the model id in the Generic OpenAI form (or the variables above).
@agent uses native tool calling by default, which works on the tool-capable models. For a model without tools, set PROVIDER_DISABLE_NATIVE_TOOL_CALLING="generic-openai" to switch the agent to prompt-based tool calls.
Where things go: key in OPENAI_API_KEY, base URL in OPENAI_PROXY_URL, model ids in OPENAI_MODEL_LIST (-all hides the defaults, +id=Name adds one).
This replaces the built-in OpenAI provider. In the app you can instead add a custom OpenAI-compatible provider under Settings → AI Providers — see LobeHub's provider docs for the current form.
Admin Settings → Connections → OpenAI API → Add Connection: URL https://net.narsill.io/v1, API Key rk_…, then type GLM-4.7-Flash in Model IDs and click +. The connection check may report an error because of the model list format; chat completions still work and the model appears in the selector.
Settings → Model Providers → Add Provider, API format OpenAI-compatible:
Base URL https://net.narsill.io/v1
API key rk_…
Where things go: both in the provider form, then Create. Jan's model fetch finds nothing, so in the provider's Models section click + and enter GLM-4.7-Flash.
Jan can't detect what a custom provider's models support: to let assistants use tools, click the pencil next to a tool-capable model and turn on Tools under Capabilities.
Name GLM-4.7 Flash (Resonance)
API Type OpenAI Chat Completions API
Endpoint URL https://net.narsill.io/v1/chat/completions
Model ID GLM-4.7-Flash
Context Length 32768 # the model's context window
Custom header Authorization: Bearer rk_…
Where things go: the full chat completions address in Endpoint URL (not the base URL), the key as an Authorization header via Add Custom Headers, the id in Model ID. Click Test, then Add Model.
Turn on Support Plugins only for the tool-capable models — plugins use function calling.
Settings › AI Providers → +, then under Other Providers choose Custom:
Friendly Name Resonance
API Key rk_…
Base URL https://net.narsill.io/v1
Where things go: all three in the form. Click Next, then Skip Test (the model list can't be read), Add Models Manually with one id per line (GLM-4.7-Flash), Set as Default, and Add Service.
The Base URL must end in /v1 as above — BoltAI's docs name a missing version path as the usual reason chats fail.
Where things go:base_url, the key under api_keys, the model id in models[].id. Raycast watches the file, so no restart is needed.
Custom Providers is a Raycast Pro feature; requests go straight from your device to Resonance. Set tools.supported: true only on the tool-capable models (needed for AI Extensions): without it Raycast assumes no tools, and declaring an ability a model lacks makes requests fail.
Settings → Copilot → BYOK → Add a provider → Add a custom provider:
Display name Resonance
API key rk_…
Base URL https://net.narsill.io/v1
Model ID GLM-4.7-Flash # then Add
Where things go: Base URL and API key in the form; the model through Model ID → Add, since the endpoint's model list can't be read. Save needs at least one model.
Leave Enable CORS off unless requests fail with a network error: it's a compatibility option for endpoints that reject browser-style requests, and with it on replies arrive in one piece instead of streaming.
Visual builders for AI workflows and agents. Each has an OpenAI-compatible model node or provider with a base URL field. Type the model id by hand, and use a tool-capable model (GLM-4.7, Qwen3-Coder-480B, …) for agent nodes that call tools.
Then in the OpenAI Chat Model node (under an AI Agent or Basic LLM Chain) pick that credential and switch Model from From List to ID: GLM-4.7-Flash.
Where things go: key and base URL on the credential; the model id in the node's Model field, in ID mode, since the list can't be read.
Leave Use Responses API off so the node uses Chat Completions. The AI Agent node calls its tools through native function calling, so pick a tool-capable model.
Use the OpenAI Custom Model chat node (ChatOpenAI Custom), made for models behind an OpenAI-compatible chat API. Create an OpenAI API credential with your rk_… key, then set:
Connect Credential OpenAI API (your rk_… key)
Model Name GLM-4.7-Flash
Base Path https://net.narsill.io/v1 # under Additional Parameters
Where things go: the key in the credential, the model id in Model Name (free text), the base URL in Base Path under Additional Parameters.
Connect the node to chatflows and agentflows like any chat model; agents that call tools need a tool-capable model.
Install the OpenAI-API-compatible plugin from Integrations → Model Provider, then Add Model on its card:
Model Type LLM
Model Name GLM-4.7-Flash
API Key rk_…
API Base URL https://net.narsill.io/v1
model name for API endpoint GLM-4.7-Flash
Completion mode Chat
Model context size 32768 # the model's context window
Function Call Type Tool Call # tool-capable models only
Where things go: key, API Base URL and the model id in the model form; Dify checks the credentials before the model becomes available.
Function Call Type: Tool Call lets agents and workflow agent nodes use native tool calling; leave it on Not Support for models without tools. Only workspace owners and admins can add providers.
The Resonance SDK is the fastest way to run inference on the Resonance network from Node.js, Bun, Deno, or the browser. You create one client, point it at the control plane, and call typed methods for text, vision, audio, structured output, decisions, agents, and network management.
Every request is routed to a whitelisted node that serves the model you ask for. You never manage servers, weights, or GPUs. The same code runs against a local control plane during development and the public network in production by changing one option.
You need an API key: your node's key (resonance api-key) or a logical node's key — see API keys & inheritance. Keep it on the server. Do not ship it in client-side bundles.
Install the SDK
Install the package with your package manager of choice. The SDK ships types, so no extra @types package is needed.
npm install resonance-sdk
# or
pnpm add resonance-sdk
# or
bun add resonance-sdk
Requirements: Node.js 18 or newer (for the global fetch), or any runtime that provides fetch. In older runtimes pass your own fetch through the client options.
Quickstart
Create a client and generate a response in four lines. Set your key in the environment first.
export RESONANCE_KEY=$(resonance api-key) # or a logical node key, rk_s_…
import { Resonance } from "resonance-sdk";
const resonance = new Resonance({
baseUrl: "https://net.narsill.io",
apiKey: process.env.RESONANCE_KEY,
});
const { text } = await resonance.generate("Explain vector clocks in two sentences.", {
model: "GLM-4.7-Flash",
});
console.log(text);
That is the whole loop: construct once, call generate, read text. Everything else in this guide builds on this client.
The client
The Resonance class is the single entry point. Construct it once and reuse it. It exposes namespaces for each area of the API.
import { Resonance } from "resonance-sdk";
const resonance = new Resonance({
baseUrl: "https://net.narsill.io", // control plane URL
apiKey: process.env.RESONANCE_KEY, // your API key
});
Options
Option
Type
Description
baseUrl
string
Control plane URL. Defaults to https://net.narsill.io.
apiKey
string
Your API key. Sent as a bearer token on every request.
fetch
typeof fetch
A custom fetch implementation. Defaults to the global fetch.
store
KVStore
Backing store for local sessions and memory. Defaults to in-process.
Reconfigure at runtime
Change the key or routing targets without building a new client with configure.
resonance.configure({ apiKey: "rk_live_other" });
Namespaces
The client groups methods by area: inference, models, tools, agents, sessions, memory, network, nodes, clusters, keys, protocols, and sandbox. Common calls are also available directly on the client: generate, chat, vision, audio, decisions, batch, priority, metrics, and health.
Authentication
Authentication is a bearer API key — your node's key or a logical node's key (API keys & inheritance). The SDK attaches the key to every request, so you only set it once.
const resonance = new Resonance({
baseUrl: "https://net.narsill.io",
apiKey: process.env.RESONANCE_KEY,
});
Treat the key as a secret. Load it from an environment variable or a secrets manager, never hardcode it. If your node key leaks, run resonance api-key rotate on the node and the old key stops working.
A request with a missing or revoked key fails with an authentication error. See Errors for how to handle it.
Text generation
Use generate for a single prompt. It returns the full response once the model finishes.
const result = await resonance.generate("Write a haiku about distributed systems.", {
model: "GLM-4.7-Flash",
temperature: 0.7,
maxTokens: 200,
});
console.log(result.text);
console.log(result.model); // the model that served the request
console.log(result.usage); // token counts
The result is a GenerateResult with the generated text, the model that served it, and usage token counts. See Parameters for every option.
Chat
Use chat for multi-turn conversations. Pass an array of messages with roles system, user, and assistant.
const r = await resonance.chat(
[
{ role: "system", content: "You are a precise assistant. Answer in one line." },
{ role: "user", content: "What is a Merkle tree?" },
],
{ model: "GLM-4.7-Flash" },
);
console.log(r.text);
To continue the conversation, append the assistant reply and the next user message, then call chat again with the full history.
const history = [
{ role: "system", content: "You are a precise assistant." },
{ role: "user", content: "What is a Merkle tree?" },
];
const first = await resonance.chat(history, { model: "GLM-4.7-Flash" });
history.push({ role: "assistant", content: first.text });
history.push({ role: "user", content: "Where are they used in practice?" });
const second = await resonance.chat(history, { model: "GLM-4.7-Flash" });
Streaming
Stream tokens as they are produced instead of waiting for the full response. There are two ways to stream.
With a callback
Pass onToken to generate or chat. The callback runs for each delta, and the promise still resolves with the full result.
const result = await resonance.generate("Tell me a short story.", { model: "GLM-4.7-Flash" }, {
onToken: (delta) => process.stdout.write(delta),
});
console.log("\n\nfull text:", result.text);
As an async iterator
Use inference.stream for a cancellable handle you can iterate. Call interrupt to stop early.
const gen = resonance.inference.stream(
[{ role: "user", content: "Write a haiku, then explain it." }],
{ model: "GLM-4.7-Flash" },
);
for await (const delta of gen) {
process.stdout.write(delta);
if (shouldStop()) { resonance.inference.interrupt(); break; }
}
Structured output
Use generateStructured to get a typed object that matches a JSON schema. The SDK instructs the model to return valid JSON and parses it for you.
const person = await resonance.inference.generateStructured(
"Extract the person from: Ada Lovelace, born 1815 in London.",
{
type: "object",
properties: {
name: { type: "string" },
birthYear: { type: "number" },
city: { type: "string" },
},
required: ["name", "birthYear"],
},
{ model: "GLM-4.7-Flash" },
);
console.log(person.name); // "Ada Lovelace"
console.log(person.birthYear); // 1815
Pass a generic to type the return value: generateStructured<Person>(...). Keep schemas small and explicit for the most reliable extraction.
Parameters
Both generate and chat accept a GenerateParams object.
Field
Type
Description
model
string
Model to run, for example GLM-4.7-Flash. List available models with models.list().
temperature
number
Sampling randomness. Lower is more deterministic.
maxTokens
number
Maximum tokens to generate.
topP
number
Nucleus sampling cutoff.
think
boolean
Include the model chain-of-thought in the output when supported.
priority
"low" | "normal" | "high"
Scheduling priority on the network.
Set a default priority for every call on the client with priority.set.
resonance.priority.set("high");
// subsequent generate/chat calls default to high priority
Vision
Analyze an image on a vision-capable model with vision.analyze. The input can be a URL, a data URL, a Buffer, or a base64 string.
const description = await resonance.vision.analyze(
"https://example.com/chart.png",
"Describe what this chart shows and the key trend.",
{ model: "Qwen3-VL-235B" },
);
console.log(description);
Pass a local file by reading it into a Buffer first.
import { readFile } from "node:fs/promises";
const bytes = await readFile("./photo.jpg");
const answer = await resonance.vision.analyze(bytes, "What objects are in this photo?", {
model: "Qwen3-VL-235B",
});
Audio
Transcribe audio with audio.transcribe. The input can be a URL, a Buffer, or a base64 string.
Decisions run a System-1 model that classifies a state against typed questions and returns calibrated answers. There is no text generation, so it is fast and cheap for routing, scoring, and triage.
const ticket = { subject: "Cannot log in", body: "I have tried three times and I am locked out." };
const verdict = await resonance.decision(
ticket,
{
urgency: { type: "score", instructions: "How urgent is this ticket from 0 to 1?" },
category: { type: "label", options: ["billing", "access", "bug", "other"] },
},
{ model: "Laya" },
);
console.log(verdict.urgency); // calibrated score
console.log(verdict.category); // chosen label
resonance.decision(state, questions, opts) is a convenience over resonance.decisions.predict(...). Both take the same arguments.
Agents
An agent is a model plus a set of tools and a loop. You define the agent once, then run it with a task. The agent decides when to call tools, the SDK executes them, and the loop continues until the agent returns a final answer.
import { Resonance, Agent } from "resonance-sdk";
const resonance = new Resonance({ baseUrl: "https://net.narsill.io", apiKey: process.env.RESONANCE_KEY });
resonance.tools.register({
name: "get_weather",
description: "Get the current weather for a city.",
parameters: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"],
},
handler: async ({ city }) => ({ tempC: 21, city }),
});
const agent = resonance.agents.create({
model: "GLM-4.7-Flash",
instructions: "You help users with weather. Use tools when needed.",
tools: ["get_weather"],
});
const run = await agent.run("What is the weather in Milan right now?");
console.log(run.output); // final answer
console.log(run.steps); // every step the agent took
The run result includes the final output and the full list of steps, so you can inspect every tool call and intermediate decision.
Tools
Tools are functions the model may call. You register them on the client with a name, a description, and a JSON schema for the parameters. The handler runs locally in your process, so the model never executes code directly.
Write clear descriptions and tight schemas. The model picks a tool from its description, so be explicit about what each one does and when to use it. Once registered, reference a tool by name when creating an agent. Other methods on the namespace: tools.unregister(name), tools.list(), and tools.get(name).
Memory and sessions
Sessions keep conversation history so you do not have to pass the full message array every turn. Memory stores facts the model can recall across sessions. Both use the client store, which is in-process by default and can be backed by your own KVStore.
// Create a session, append turns, then generate from its stored history.
const session = await resonance.sessions.create({ system: "You are a precise assistant." });
resonance.sessions.append(session.id, { role: "user", content: "My name is Dana." });
let s = await resonance.sessions.get(session.id);
const r1 = await resonance.chat(s.messages, { model: "GLM-4.7-Flash" });
resonance.sessions.append(session.id, { role: "assistant", content: r1.text });
resonance.sessions.append(session.id, { role: "user", content: "What is my name?" });
s = await resonance.sessions.get(session.id);
const r2 = await resonance.chat(s.messages, { model: "GLM-4.7-Flash" });
console.log(r2.text); // knows it is Dana, the history was kept for you
A session is a stored list of messages (id, messages, createdAt, scope). Use sessions.create, sessions.append, sessions.get, and sessions.delete to manage it, and pass session.messages to chat.
Memory
Store facts and retrieve them later by similarity.
Protocols are small programs that run on your nodes: one file defining async function run(ctx, input) plus the permissions it declares. Test one locally with the SDK's sandbox — the same ctx contract and limits as a node — then save, deploy and call it with resonance.protocols.
const source = `async function run(ctx, input) {
return await ctx.json("Three key points of: " + input.text);
}`;
const permissions = { inference: true, maxCalls: 2 };
// 1. On your machine
const local = await resonance.sandbox.run({ name: "points", source, permissions }, { text: "…" });
console.log(local.ok, local.output, local.logs);
// 2. On the network: save → deploy to your cluster → run (→ publish)
const { id } = await resonance.protocols.create({ name: "points", source, permissions });
await resonance.protocols.deploy(id, { clusters: [clusterId] });
const run = await resonance.protocols.run(id, { text: "…" });
console.log(run.output, run.node, run.version);
Also protocols.list({ mine: true }), update (a new version), rollback, logs, metrics and publish. See sample protocols for six that run as they are.
Models
List the models available on the network and inspect their capabilities before you call them. To compare them first — what each is good at, how fast it answers, how much the network uses it — see the Models page.
const models = await resonance.models.list();
for (const m of models) {
console.log(m.id, m.capabilities); // text, vision, audio, tools
}
Capabilities tell you which features a model supports, so you can pick a vision model for images or an audio model for transcription at runtime.
Network and nodes
Read the live list of nodes serving the network with network.status.
const nodes = await resonance.network.status();
for (const n of nodes) console.log(n.id, n.status, n.region);
If you operate nodes, resonance.nodes manages your own logical nodes: nodes.create,nodes.start, nodes.stop, nodes.restart, nodes.status,nodes.metrics, nodes.health, and nodes.logs. Group them withresonance.clusters.
Your node's key comes from resonance api-key; logical nodes get theirs from the cluster (API keys & inheritance). The SDK manages the lifecycle of existing keys with resonance.keys (also available asresonance.key): list, rotate, revoke, disable, enable, and verify.
// List the keys on a cluster you own.
const all = await resonance.keys.list(clusterId);
// Rotate a key, keeping the old one valid for a grace period.
await resonance.keys.rotate(keyId, { gracePeriodMs: 60000, clusterId });
// Revoke immediately, or disable/enable without destroying it.
await resonance.keys.revoke(keyId, clusterId);
await resonance.keys.disable(keyId, clusterId);
// Check a key is still valid and authorized.
const { valid, reason } = await resonance.keys.verify(keyId);
Key mutations are owner-gated by the key's cluster. Pass the owning clusterId whose owner token was captured when you created the cluster.
Batch, priority, metrics, health
Operational helpers for throughput and observability.
Batch
Submit many prompts at once with bounded concurrency.
The SDK throws typed errors so you can handle each case directly. Wrap calls in a try/catch and branch on the error type.
import {
Resonance,
ResonanceAuthError,
ResonanceUnavailableError,
ResonanceValidationError,
ResonanceCancelledError,
ResonanceError,
} from "resonance-sdk";
try {
const { text } = await resonance.generate("Hello", { model: "GLM-4.7-Flash" });
} catch (err) {
if (err instanceof ResonanceAuthError) {
// invalid or revoked API key
} else if (err instanceof ResonanceUnavailableError) {
// the network or a node is temporarily unavailable, back off and retry
} else if (err instanceof ResonanceValidationError) {
// the request was malformed, fix the parameters
} else if (err instanceof ResonanceCancelledError) {
// the request was interrupted
} else if (err instanceof ResonanceError) {
// any other error from the network
console.error(err.message);
} else {
throw err;
}
}
All SDK errors extend ResonanceError, so catching that base type handles everything from the network. Match the more specific types first when you want tailored handling.
Node-side failures are reported generically on purpose. You get a clear message to retry, not the internal reason a specific node failed.