Build on Resonance

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.

Start with Core concepts (5 minutes), then How the network works and Your first app.

Core concepts

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
ConceptWhat it isWhy it matters
Physical nodeA 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.
ClusterA 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 nodeA 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 keyThe 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.
ProtocolA 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.

KeyLooks likeWhere it comes fromUse it for
Node keyrk_<node-id>.<secret>resonance api-key on the machine, or the copy button in resonance webLocal scripts, the VS Code extension, creating clusters
Logical node keyrk_s_…GET /v1/logical-nodes/:id/api-keyApps 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.

  1. 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
  2. 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.
    curl -s https://net.narsill.io/v1/clusters/$CLUSTER_ID/nodes \
      -H "Authorization: Bearer $NODE_KEY" -H "Content-Type: application/json" \
      -d "{\"nodeId\": \"$NODE_ID\"}"
    # → { "ok": true }
  3. Create a logical node for the app.
    curl -s https://net.narsill.io/v1/logical-nodes \
      -H "x-resonance-owner: $CLUSTER_OWNER_TOKEN" -H "Content-Type: application/json" \
      -d "{\"clusterId\": \"$CLUSTER_ID\", \"label\": \"crm-prod\", \"region\": \"eu-west\"}"
    # → { "id": "ln_…", "label": "crm-prod", …, "ownerToken": "ot_…" }   save as LN_ID and LN_OWNER_TOKEN
  4. Get its key and give it to the app.
    curl -s https://net.narsill.io/v1/logical-nodes/$LN_ID/api-key \
      -H "x-resonance-owner: $LN_OWNER_TOKEN"
    # → { "apiKey": "rk_s_…" }

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
Physical noderk_<node>.<secret>Clustercl_… · owner tokenLogical nodeln_… · “crm-prod”Your appBearer rk_s_…attachholds24 h key
  1. ✓Signature matches
  2. ✓Not expired (24 h)
  3. ✓Not revoked
  4. ✓Logical node exists, in this cluster
  5. ✓Logical node is running
  6. ✓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
HTTPSSSEsecure linksYour appbackend · browserControl planenet.narsill.ioAuth & keysrk_… · rk_s_…Model catalogueGET /v1/modelsSchedulerbest node for each requestSigned worksigned assignmentsMetering & walletper key · per logical nodeNodeMac · Apple GPUNodePC · RTX 4090NodeLinux server · CPUNode groupone model, 3 machines
Scheduler — Picks the node that can serve each request best — or several nodes together, for a model too big for one machine.
PieceWhat it does for you
Control planeThe 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.
NodesStay connected to the network, so work reaches them instantly. They run the model and stream tokens back.
Node groupsWhen a model is too big for one machine, several nodes serve it together — see Big models across nodes.
Model catalogueGET /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
Your appControl planeNode1 POST /v1/chat/completions2 verify the key3 pick the best node4 signed work5 verify · load if cold6 tokens, as generated7 data: {chunk} … [DONE]8 meter usage
1. POST /v1/chat/completions — Your app sends the request with Authorization: Bearer <key>. Any OpenAI-compatible client works.
  1. 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.
  2. Place. The scheduler picks the node that can serve this request best — or several nodes together, for a very large model (Routing & placement).
  3. Dispatch. The work is signed and handed to the chosen node at once; the node runs only work the network actually assigned.
  4. Generate. The node loads the model if it isn't already warm, runs it and streams tokens back as they're produced.
  5. Relay. The control plane forwards them to you — as chat.completion.chunk events with "stream": true, or as one completion object at the end.
  6. 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.

Routing · change the request
  1. Available16 → 14
    online and taking work
  2. Right tier14 → 9
    free work → the open network
  3. Fits the model9 → 5
    40 GB + room → ≥ 44 GB usable
  4. Privacy level5
    default → any of the above
  5. Best nodebest of 5
    #1 Mac Studio M2 Ultra0.90
    #2 Mac Studio M1 Ultra0.75
    #3 MacBook Pro M3 Max0.72
    computememory headroomnetworkreliabilitywarm cachelow load
  • Mac Studio M2 Ultra150 GBwarm#1
  • RTX 4090 tower22 GBwarmfits the model
  • MacBook Pro M3 Max96 GB#3
  • Linux box · 2× A600092 GBpaidright tier
  • Mac mini M422 GBwarmfits the model
  • Gaming PC · RTX 30809 GBfits the model
  • Appliance · Computa180 GBpaidteewarmright tier
  • Appliance · Computa180 GBpaidteeright tier
  • Marketplace · L40S44 GBpaidwarmright tier
  • Your Mac Studio60 GByours
  • Your RTX 4070 PC11 GByourswarmfits the model
  • Linux server · CPU120 GB
  • Laptop · M112 GBavailable
  • RTX 4090 tower22 GBavailable
  • Mac Studio M1 Ultra110 GB#2
  • Marketplace · H10076 GBpaidright tier

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.
StepRuleWhat you control
TierFree 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.
FitThe node has a free slot, supports the model on its platform, and has enough usable memory for it.model
Privacy levelThe 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 nodeAmong 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:

LevelWhere it may runIf nothing matches
standard / encrypted (default)Any eligible node—
teeOnly hardware-attested nodesRefused, with a clear "no eligible node" error
privateOnly nodes of your own operator accountRefused, 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
80 layers0–4748–79Head · Mac Studiolayers 0–47 · ~84 GB96 GB freeStage 2 · Linux serverlayers 48–79 · ~56 GB64 GB freeRTX PCnot needed40 GB freeMac mininot needed24 GB freeevery token travels across the machines and back · links encrypted · illustration
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
One by one10.3 s12345678reduceSide by side3.4 s · 3.0× faster12345678reduce0 s10.3 s
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.

CallReturnsNeeds
ctx.inputthe 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 })the model's reply, as textinference
ctx.generateMany([prompts], opts)up to 16 replies, computed side by sideinference
ctx.json(prompt, opts)the reply parsed as JSONinference
ctx.fetch(url, { method, headers, body }){ status, ok, headers, text(), json() }the host in net
The sandbox · toggle the permissions
{
  "permissions": {
    "inference": true,
    "timeoutMs": 30000
  }
}
  1. ✓ctx.log("hi", {n: 1})a log line (200 lines, 2 KB each)
  2. ✓await ctx.generate("Summarize …")one model reply — counts against maxCalls
  3. ✓await ctx.generateMany([a, b, c])three replies, side by side — 3 calls
  4. ✕await ctx.fetch("https://en.wikipedia.org/…")permission denied: en.wikipedia.org is not in permissions.net
  5. ✕await ctx.fetch("http://en.wikipedia.org/…")only https:// URLs are allowed
  6. ✕await ctx.fetch("https://intranet.example.lan/")a host must be declared in permissions.net — and private or local addresses are refused even then
  7. ✕require("fs") · import · processnot defined: the sandbox has no modules, files or processes
  8. ✕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.
PermissionDefaultLimit
inferencefalse—
net[]public DNS names only — no IPs, localhost, .local or .internal; HTTPS, no redirects, never private addresses
timeoutMs30 000120 000
maxCalls20100 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:

  1. New protocol. Pick a template; Studio creates protocols/<name>/ with the code, the manifest, tests and a README.
  2. ▶ 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.
  3. ⬆ 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.
  4. ◎ 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"
EndpointWhat it does
GET /v1/protocolsThe registry of published protocols. ?mine=1 with your key lists yours, drafts included.
GET /v1/protocols/:idName, version, permissions, deployments, how many nodes are ready; the source if published (or yours).
POST /v1/protocols/:idNew 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 · /startPause or resume every deployment.
POST /v1/protocols/:id/undeployRemove it from clusters or nodes.
GET /v1/protocols/:id/logsThe last 50 runs with their logs and errors (owner only, kept in memory only).
GET /v1/protocols/:id/metrics · /status · /instancesRuns, 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.

Account & console

Everything starts from a free account at application.narsill.com, where you add machines and track usage. API keys live on the node itself — see API keys & inheritance.

  1. Open application.narsill.com and submit the application form with your email.
  2. Wait for the confirmation email and open the link inside it to verify your address.
  3. 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.

Install it in one of two ways:

Models, inference & keys

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.

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": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "What is distributed inference?"}
    ],
    "max_tokens": 256,
    "temperature": 0.7
  }'

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].

curl -N 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": "Count to five."}],
    "stream": true
  }'
data: {"object":"chat.completion.chunk","choices":[{"delta":{"content":"One"}}]}
data: {"object":"chat.completion.chunk","choices":[{"delta":{"content":", two"}}]}
data: [DONE]

Options & tiers

Beyond model and messages, the body accepts:

FieldTypeMeaning
max_tokensintCap the generated length.
temperaturefloatSampling randomness (0 = deterministic).
top_pfloatNucleus sampling cutoff.
streamboolStream tokens as SSE (see Streaming).
thinkboolInclude the model's chain-of-thought. Default false: only the answer is returned.
tierstringfree, paid or auto. Defaults to the key's stored preference, else free.
max_price_per_sfloatPaid 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.

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": "Draft a product tagline."}],
    "tier": "paid",
    "max_price_per_s": 0.05
  }'

List models

GET /v1/models returns the models currently available on the network. Use a model's model_id as the model field in your requests.

curl https://net.narsill.io/v1/models \
  -H "Authorization: Bearer $RESONANCE_API_KEY"

Any OpenAI client

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.

SettingValue
Base URLhttps://net.narsill.io/v1 — some tools call it API base, API host, endpoint or proxy URL.
API keyYour 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.
ModelAn 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.

At a glance

ToolConnectsWhat works today
DSPyDirectChat, streaming, modules, tools
Semantic KernelDirectChat, streaming, plugins / function calling
AgnoDirectAgents with tools
CrewAIDirectCrews and agents with tools
Microsoft AutoGenDirectAgents with tools (function_calling on)
LiteLLMDirectFull chat; also the bridge for other tools
Pydantic AIDirectAgents, tools, structured output
HaystackDirectChat, streaming, tool-calling pipelines
LlamaIndexDirectChat, RAG, function-calling agents
LangChainDirectChat, streaming, bind_tools, agents
Vercel AI SDKDirectgenerateText, streamText, tools
OpenAI Agents SDKDirectAgents with function tools
MastraDirectAgents with tools
smolagentsDirectCodeAgent; ToolCallingAgent on tool models
Google ADKDirectAgents with tools (LiteLlm wrapper)
Claude CodeVia LiteLLMFull agent via LiteLLM; test multi-turn
OpenAI Codex CLIVia LiteLLMFull agent via LiteLLM
AiderDirectFull: edits use text formats
OpenCodeDirectFull agent
GooseDirectFull agent with extensions
OpenHandsDirectFull agent
PiDirectFull agent
Hermes AgentDirectFull agent
OpenClawDirectFull agent
CrushDirectFull agent
Qwen CodeDirectFull agent
Kimi CLIDirectFull agent
gptmeDirectFull agent (markdown tool calls)
CursorDirectChat models via BYOK; not Tab
WindsurfNot supportedNo custom endpoint
ZedDirectAgent panel with tools, inline assist
WarpDirectAgent with a custom endpoint model
ContinueDirectChat, edit, apply, Agent mode
ClineDirectFull agent
Roo CodeDirectFull agent
Kilo CodeDirectFull agent (tool_call: true)
JetBrains AI AssistantVia LiteLLMAI Chat and agents via LiteLLM
TraeDirectChat and agent with a custom model
ChatboxDirectChat and streaming
MstyDirectChat and streaming
Cherry StudioDirectChat and streaming
AnythingLLMDirectChat, RAG, @agent with native tools
LobeChatDirectChat and streaming
LibreChatDirectChat and streaming
Open WebUIDirectChat and streaming
JanDirectChat, streaming, tools when enabled
TypingMindDirectChat, streaming, plugins
BoltAIDirectChat and streaming
Raycast AIDirectAI Chat, commands, AI Extensions
Obsidian CopilotDirectChat and streaming
n8nDirectAI Agent and chains with tools
FlowiseDirectChatflows and agentflows
DifyDirectChat apps, workflows, agents

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.

DSPy

Direct#
pip install dspy
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.

Official docs: Installation · dspy.LM

Semantic Kernel

Direct#
# 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.

Official docs: Chat completion

Agno

Direct#
pip install -U agno openai
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.

Official docs: OpenAI-like models

CrewAI

Direct#
pip install "crewai[openai]"
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.

Official docs: LLMs

Microsoft AutoGen

Direct#
pip install "autogen-ext[openai]" autogen-agentchat
import os
from autogen_ext.models.openai import OpenAIChatCompletionClient

client = OpenAIChatCompletionClient(
    model="GLM-4.7-Flash",
    base_url="https://net.narsill.io/v1",
    api_key=os.environ["RESONANCE_API_KEY"],
    model_info={                       # required for non-OpenAI model names
        "vision": False,
        "function_calling": True,      # native tools on GLM-4.7, Qwen3-Coder-480B, …
        "json_output": False,
        "family": "unknown",
        "structured_output": False,
    },
)

Where things go: model, base_url, api_key, plus the required model_info.

With function_calling: True, pass tools to AssistantAgent as usual. Set it to False for models without tool support.

Official docs: OpenAIChatCompletionClient · Models

LiteLLM

Direct#

As a library:

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
pip install 'litellm[proxy]'
export RESONANCE_API_KEY=rk_…
export LITELLM_MASTER_KEY=sk-local-$(openssl rand -hex 12)
litellm --config config.yaml          # listens on http://localhost:4000

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.

Official docs: OpenAI-compatible endpoints · /v1/messages · /v1/responses

Pydantic AI

Direct#
pip install "pydantic-ai-slim[openai]"
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.

Official docs: OpenAI-compatible APIs · Output

Haystack

Direct#
pip install haystack-ai
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.

Official docs: OpenAIChatGenerator

LlamaIndex

Direct#
pip install llama-index-llms-openai-like
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.

Official docs: OpenAILike

LangChain

Direct#
# Python — pip install -U langchain-openai
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="GLM-4.7-Flash",
    base_url="https://net.narsill.io/v1",
    api_key=os.environ["RESONANCE_API_KEY"],
    use_responses_api=False,
)
print(llm.invoke("Say hello in one sentence.").content)
// JavaScript — npm install @langchain/openai @langchain/core
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "GLM-4.7-Flash",
  apiKey: process.env.RESONANCE_API_KEY,
  configuration: { baseURL: "https://net.narsill.io/v1" },
});

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.

Official docs: ChatOpenAI (Python) · ChatOpenAI (JS)

Vercel AI SDK

Direct#
npm install ai @ai-sdk/openai-compatible
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.

Official docs: OpenAI-compatible providers

OpenAI Agents SDK

Direct#
pip install openai-agents
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.

Official docs: Models

Mastra

Direct#
npm install @mastra/core
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.

Official docs: Models · Custom gateways

smolagents

Direct#
pip install smolagents openai
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.

Official docs: Models

Google ADK

Direct#
pip install google-adk "litellm>=1.84"
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.

Official docs: LiteLLM models · Self-hosted endpoints

Coding agents

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

Via LiteLLM#

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.

Official docs: LLM gateway · LiteLLM: Claude Code with other models

OpenAI Codex CLI

Via LiteLLM#

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:

model = "Qwen3-Coder-480B"
model_provider = "resonance"

[model_providers.resonance]
name = "Resonance (via LiteLLM)"
base_url = "http://localhost:4000/v1"
env_key = "LITELLM_MASTER_KEY"
wire_api = "responses"

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.

Official docs: Config reference · LiteLLM /v1/responses

Aider

Direct#
export OPENAI_API_BASE=https://net.narsill.io/v1
export OPENAI_API_KEY=rk_…
aider --model openai/Qwen3-Coder-480B

Or keep it in .aider.conf.yml (home directory, repo root or current directory):

model: openai/Qwen3-Coder-480B
openai-api-base: https://net.narsill.io/v1
openai-api-key: rk_…

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.

Official docs: OpenAI-compatible APIs · .aider.conf.yml · Model settings

OpenCode

Direct#

Add a custom provider in opencode.jsonc:

{
  "$schema": "https://opencode.ai/config.json",
  "model": "resonance/Qwen3-Coder-480B",
  "providers": {
    "resonance": {
      "name": "Resonance",
      "env": ["RESONANCE_API_KEY"],
      "package": "@opencode/ai/providers/openai-compatible",
      "settings": { "baseURL": "https://net.narsill.io/v1" },
      "models": { "Qwen3-Coder-480B": { "name": "Qwen3 Coder 480B" } }
    }
  }
}

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.

Official docs: Providers

Goose

Direct#

Add a custom provider with goose configure → Custom Providers → Add A Custom Provider → OpenAI compatible, or write ~/.config/goose/custom_providers/resonance.json:

{
  "name": "resonance",
  "engine": "openai",
  "display_name": "Resonance",
  "api_key_env": "RESONANCE_API_KEY",
  "base_url": "https://net.narsill.io/v1/chat/completions",
  "models": [{ "name": "Qwen3-Coder-480B", "context_limit": 128000 }],
  "supports_streaming": true,
  "requires_auth": true
}
goose session start --provider 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.

Official docs: Providers

OpenHands

Direct#

In Settings → LLM, turn on Advanced and set:

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.

Official docs: OpenAI-compatible LLMs · LLM settings

Pi

Direct#

Add a provider to ~/.pi/agent/models.json:

{
  "providers": {
    "resonance": {
      "baseUrl": "https://net.narsill.io/v1",
      "api": "openai-completions",
      "apiKey": "$RESONANCE_API_KEY",
      "models": [{ "id": "Qwen3-Coder-480B" }]
    }
  }
}

Where things go: everything in models.json: baseUrl, apiKey (an environment variable, a literal key or a command), models[].id. Pick it with /model.

Pi's agent loop runs on native tool calls, which work on the tool-capable models — reading, editing and running commands all go through Resonance.

Official docs: Custom models

Hermes Agent

Direct#

Edit ~/.hermes/config.yaml (or run hermes model and choose a custom endpoint):

model:
  provider: "custom"
  base_url: "https://net.narsill.io/v1"
  api_key: "rk_…"
  default: "Qwen3-Coder-480B"

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.

Official docs: Providers · Configuration

OpenClaw

Direct#

Add a provider in ~/.openclaw/openclaw.json (JSON5):

{
  agents: { defaults: { model: { primary: "resonance/Qwen3-Coder-480B" } } },
  models: {
    mode: "merge",
    providers: {
      resonance: {
        baseUrl: "https://net.narsill.io/v1",
        apiKey: "${RESONANCE_API_KEY}",
        api: "openai-completions",
        models: [{ id: "Qwen3-Coder-480B", name: "Qwen3 Coder 480B" }],
      },
    },
  },
}

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.

Official docs: Custom providers · Configuration

Crush

Direct#

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:

provider add resonance --type completions \
  --base-url "https://net.narsill.io/v1" \
  --api-key "$RESONANCE_API_KEY" \
  --name "Resonance"

model add resonance/Qwen3-Coder-480B --name "Qwen3 Coder 480B" \
  --context-window 128000 --default-max-tokens 8192

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.

Official docs: Configuration · README

Qwen Code

Direct#
export OPENAI_API_KEY=rk_…
export OPENAI_BASE_URL=https://net.narsill.io/v1
export OPENAI_MODEL=Qwen3-Coder-480B
qwen

Or keep it in ~/.qwen/settings.json:

{
  "modelProviders": {
    "openai": [
      {
        "id": "Qwen3-Coder-480B",
        "name": "Qwen3 Coder 480B (Resonance)",
        "baseUrl": "https://net.narsill.io/v1",
        "envKey": "RESONANCE_API_KEY"
      }
    ]
  },
  "security": { "auth": { "selectedType": "openai" } },
  "model": { "name": "Qwen3-Coder-480B" }
}

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.

Official docs: Authentication & providers

Kimi CLI

Direct#

Add a provider and a model to ~/.kimi/config.toml; openai_legacy is the provider type for OpenAI Chat Completions APIs:

default_model = "resonance-qwen3-coder"

[providers.resonance]
type = "openai_legacy"
base_url = "https://net.narsill.io/v1"
api_key = "rk_…"

[models.resonance-qwen3-coder]
provider = "resonance"
model = "Qwen3-Coder-480B"
max_context_size = 131072

Where things go: base_url and api_key under [providers.resonance], the Resonance model id in model; default_model names the [models.*] entry.

Quote table names that contain a dot ([models."x.y"]). Kimi CLI's agent works through native tool calls — use a tool-capable model.

Official docs: Providers · Config files

gptme

Direct#

Declare Resonance in ~/.config/gptme/config.toml:

[[providers]]
name = "resonance"
base_url = "https://net.narsill.io/v1"
api_key_env = "RESONANCE_API_KEY"
default_model = "Qwen3-Coder-480B"
gptme "hello" -m resonance/Qwen3-Coder-480B

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.

Official docs: Custom providers · Tools

IDEs & terminals

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.

Cursor

Direct#

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.

Official docs: API keys

Windsurf

Not supported#

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.

Official docs: Models

Zed

Direct#

Add an OpenAI-compatible provider in settings.json:

"language_models": {
  "openai_compatible": {
    "Resonance": {
      "api_url": "https://net.narsill.io/v1",
      "available_models": [
        {
          "name": "Qwen3-Coder-480B",
          "display_name": "Qwen3 Coder 480B",
          "max_tokens": 131072,
          "capabilities": { "tools": true, "images": false, "parallel_tool_calls": false, "prompt_cache_key": false }
        }
      ]
    }
  }
}

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.

Official docs: LLM providers / API access

Warp

Direct#

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.

Official docs: Custom inference endpoint

Continue

Direct#

Add a model to config.yaml:

name: Resonance
version: 0.0.1
schema: v1
models:
  - name: Qwen3 Coder 480B (Resonance)
    provider: openai
    model: Qwen3-Coder-480B
    apiBase: https://net.narsill.io/v1
    apiKey: rk_…
    roles: [chat, edit, apply]
    capabilities: [tool_use]      # Agent mode

Where things go: apiBase, apiKey, 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).

Official docs: OpenAI provider · config.yaml reference · Model capabilities

Cline

Direct#

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.

Official docs: OpenAI Compatible

Roo Code

Direct#

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.

Official docs: OpenAI Compatible

Kilo Code

Direct#

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:

{
  "$schema": "https://app.kilo.ai/config.json",
  "model": "openai-compatible/Qwen3-Coder-480B",
  "provider": {
    "openai-compatible": {
      "options": { "apiKey": "{env:RESONANCE_API_KEY}", "baseURL": "https://net.narsill.io/v1" },
      "models": {
        "Qwen3-Coder-480B": { "name": "Qwen3 Coder 480B", "tool_call": true }
      }
    }
  }
}

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.

Official docs: OpenAI Compatible · Custom models

JetBrains AI Assistant

Via LiteLLM#

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.

Official docs: Use custom models · LiteLLM proxy

Trae

Direct#

Settings → Models → Add Model, choose Custom Model:

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.

Official docs: Built-in & custom models

Chat apps

Desktop and self-hosted chat apps. All of them work for chat and streaming; add the model id by hand, since the model list can't be fetched.

Chatbox

Direct#

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.

Official docs: Providers · Custom provider walkthrough

Msty

Direct#

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.

Official docs: Online providers

Cherry Studio

Direct#

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.

Official docs: Model service settings

AnythingLLM

Direct#

In LLM Preference, choose Generic OpenAI and fill in Base URL https://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.

Official docs: docker/.env.example

LobeChat

Direct#

Self-hosted: point the OpenAI provider at Resonance with environment variables.

OPENAI_API_KEY=rk_…
OPENAI_PROXY_URL=https://net.narsill.io/v1
OPENAI_MODEL_LIST=-all,+GLM-4.7-Flash=GLM-4.7 Flash,+MiniMax-M2.5

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.

Official docs: Model provider variables · AI providers

LibreChat

Direct#

Add a custom endpoint to librechat.yaml and put RESONANCE_API_KEY=rk_… in .env:

endpoints:
  custom:
    - name: "Resonance"
      apiKey: "${RESONANCE_API_KEY}"
      baseURL: "https://net.narsill.io/v1"
      models:
        default: ["GLM-4.7-Flash", "GLM-4.7", "MiniMax-M2.5"]
        fetch: false
      titleConvo: true
      titleModel: "GLM-4.7-Flash"
      modelDisplayLabel: "Resonance"

Where things go: apiKey, baseURL, model ids in models.default with fetch: false.

Official docs: Custom endpoints

Open WebUI

Direct#

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.

OPENAI_API_BASE_URL=https://net.narsill.io/v1
OPENAI_API_KEY=rk_…

Where things go: URL and key in the connection (or the variables above, read on first start); model ids in the Model IDs allowlist.

Official docs: OpenAI-compatible providers · Environment variables

Jan

Direct#

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.

Official docs: Custom endpoints

TypingMind

Direct#

Models → Add Custom Model, one entry per model:

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.

Official docs: Custom model setup · Manage models

BoltAI

Direct#

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.

Official docs: OpenAI-compatible provider · Add an AI provider

Raycast AI

Direct#

In Settings → AI → Models & Providers, under Custom Providers, click Reveal Providers Config, copy providers.template.yaml to providers.yaml and add:

providers:
  - id: resonance
    name: Resonance
    base_url: https://net.narsill.io/v1
    api_keys:
      resonance: rk_…
    models:
      - id: GLM-4.7-Flash
        name: GLM-4.7 Flash
        context: 128000
        abilities:
          tools:
            supported: true

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.

Official docs: Custom providers

Obsidian Copilot

Direct#

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.

Official docs: Settings / BYOK

Workflow builders

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.

n8n

Direct#

Create an OpenAI credential:

API Key    rk_…
Base URL   https://net.narsill.io/v1

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.

Official docs: OpenAI credentials · OpenAI Chat Model node

Flowise

Direct#

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.

Official docs: Chat models · OpenAI Custom Model node

Dify

Direct#

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.

Official docs: OpenAI-API-compatible plugin · Model providers

Resonance SDK

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

OptionTypeDescription
baseUrlstringControl plane URL. Defaults to https://net.narsill.io.
apiKeystringYour API key. Sent as a bearer token on every request.
fetchtypeof fetchA custom fetch implementation. Defaults to the global fetch.
storeKVStoreBacking 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.

FieldTypeDescription
modelstringModel to run, for example GLM-4.7-Flash. List available models with models.list().
temperaturenumberSampling randomness. Lower is more deterministic.
maxTokensnumberMaximum tokens to generate.
topPnumberNucleus sampling cutoff.
thinkbooleanInclude 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.

import { readFile } from "node:fs/promises";

const clip = await readFile("./meeting.mp3");
const transcript = await resonance.audio.transcribe(clip, { model: "Voxtral-Small-24B" });

console.log(transcript);

Decisions

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.

resonance.tools.register({
  name: "search_docs",
  description: "Search the internal knowledge base.",
  parameters: {
    type: "object",
    properties: { query: { type: "string" } },
    required: ["query"],
  },
  handler: async ({ query }) => {
    const rows = await db.search(query);
    return rows.slice(0, 5);
  },
});

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.

await resonance.memory.store("The user prefers metric units.");
const hits = await resonance.memory.retrieve("units preference", { limit: 5 });
console.log(hits);

Custom store

Pass a store to persist sessions and memory beyond the current process, for example in Redis or a database.

const resonance = new Resonance({
  baseUrl: "https://net.narsill.io",
  apiKey: process.env.RESONANCE_KEY,
  store: myKvStore,  // implements get/set/delete
});

Protocols and sandbox

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.

const node = await resonance.nodes.create({ region: "eu-west", label: "my-node" });
await resonance.nodes.start(node.id);
console.log(await resonance.nodes.status(node.id));

API keys

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.

const results = await resonance.batch.submit(
  [
    { prompt: "Summarize article 1", params: { model: "GLM-4.7-Flash" } },
    { prompt: "Summarize article 2", params: { model: "GLM-4.7-Flash" } },
  ],
  { concurrency: 4 },
);

Priority

resonance.priority.set("high");

Metrics and health

const metrics = await resonance.metrics.get();
const health = await resonance.health.check();
console.log(health);

Errors

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.