---
id: SI0011
title: "Live account RAG"
url: https://carbium.sh/library/si/live-account-rag
collection: AI and blockchain
category: RAG and embeddings
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Live account RAG

A question goes in. The matching accounts come from a small catalog by embedding similarity, one getMultipleAccounts read returns their current state, and the prompt carries that state with the slot it was read at.

## What live means here

Retrieval-augmented generation over Solana has a problem that document RAG does not. A document chunk stays true until someone edits the document. An account can change in every slot, about 200 ms apart. Embed a token supply or a balance into a vector store and the index answers with a number that was true when you wrote it and has drifted since.

The job splits along that line. The catalog holds what does not move: an address and a short description of it. Embedding similarity picks addresses. The numbers come from a read of those addresses at question time, and the slot of that read goes into the prompt beside them. The model never sees a stored balance.

| Data | Where it lives | Why |
|---|---|---|
| Address and description of an account | the catalog | it changes only when you edit it |
| Supply, decimals, balance, owner | a live read per question | it changes between slots |
| Slot and commitment | the first lines of the prompt | they tell the reader how old the numbers are |

> [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) covers the other design, where the model chooses its own reads behind a fixed allowlist. Here the code chooses the reads and the model only receives the result.

## The file

One file. Node 24 runs the TypeScript directly, and the only import is `@solana/kit`. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. `CARBIUM_RPC_URL` overrides the endpoint, which defaults to `https://services.carbium.sh`.

`main.ts` (run: `node main.ts "USDC supply and decimals"`)

```ts
// SI0011 · Live account RAG
// https://carbium.sh/library/si/live-account-rag
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Live account RAG: rank a catalog by embedding similarity, read the matches live, print the prompt.
// Run: CARBIUM_KEY=... node main.ts "USDC supply and decimals"
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));
const TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const COMMITMENT = "confirmed" as const;

// What does not move: an address and a description. Numbers never go in here.
const CATALOG = [
  { pubkey: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", note: "USDC mint, dollar stablecoin" },
  { pubkey: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", note: "USDT mint, dollar stablecoin" },
  { pubkey: "So11111111111111111111111111111111111111112", note: "wrapped SOL mint" },
];

// Character-trigram hash embedding: it matches spelling. Swap in a model's embedding with the same shape.
const DIMS = 4096;
function embed(text: string): Float32Array {
  const v = new Float32Array(DIMS);
  for (const word of text.toLowerCase().match(/[a-z0-9]+/g) ?? []) {
    const padded = ` ${word} `;
    for (let i = 0; i + 3 <= padded.length; i++) {
      let h = 2166136261;
      for (let j = i; j < i + 3; j++) h = Math.imul(h ^ padded.charCodeAt(j), 16777619);
      v[(h >>> 0) % DIMS] += 1;
    }
  }
  let norm = 0;
  for (const x of v) norm += x * x;
  return v.map((x) => x / (Math.sqrt(norm) || 1));
}
const dot = (a: Float32Array, b: Float32Array) => a.reduce((sum, x, i) => sum + x * (b[i] as number), 0);

const question = process.argv[2] ?? "USDC supply and decimals";
const q = embed(question);
const scored = CATALOG.map((d) => ({ ...d, score: dot(q, embed(d.note)) })).sort((a, b) => b.score - a.score);
const best = scored[0]?.score ?? 0;
const hits = scored.slice(0, 3).filter((d) => d.score >= 0.1 && d.score >= best * 0.75);
if (!hits.length) {
  console.log("No catalog entry matches the question, so nothing is read.");
  process.exit(0);
}
console.log("retrieved:", hits.map((h) => `${h.note} ${h.score.toFixed(2)}`).join("; "));

// One call, one slot for every account in it.
const { context, value } = await rpc
  .getMultipleAccounts(hits.map((h) => address(h.pubkey)), { commitment: COMMITMENT, encoding: "base64" })
  .send();

const lines = hits.map((h, i) => {
  const account = value[i];
  if (!account) return `- ${h.note} (${h.pubkey}): account not found`;
  const bytes = Buffer.from((account.data as unknown as [string, string])[0], "base64");
  if (String(account.owner) !== TOKEN_PROGRAM || bytes.length !== 82) {
    return `- ${h.note} (${h.pubkey}): not a token mint, not decoded`;
  }
  const decimals = bytes[44] as number;
  const raw = bytes.readBigUInt64LE(36).toString();
  const padded = raw.padStart(decimals + 1, "0");
  const ui = decimals ? `${padded.slice(0, -decimals)}.${padded.slice(-decimals)}` : padded;
  return `- ${h.note} (${h.pubkey}): supply ${ui} (raw ${raw}), decimals ${decimals}, owner token program`;
});

console.log(
  [
    "Answer from the context only. If it lacks the answer, say so.",
    `Question: ${question}`,
    `Context, read at slot ${context.slot} with ${COMMITMENT} commitment:`,
    ...lines,
  ].join("\n"),
);
```

The run prints the retrieved entries with their scores, then the prompt: an instruction, the question, a header naming the slot and the commitment, and one line per account. For the default question, `USDC supply and decimals`, the USDC mint ranks first, and its line shows the supply as a decimal string next to the raw integer, with the decimals.

`embed` hashes character trigrams into 4,096 buckets and normalises the result. It matches spelling: a question that says `USDC` finds the entry that says `USDC`. It has no idea that "Circle's token" means USDC. That is the part to replace with your model's embedding call. Keep the same normalised `Float32Array` shape. Two things in the file change with it: a model embedding call is async, so the scoring lines need `await`, and the 0.1 floor is tuned to trigram scores, so set it again for the model's score range.

Retrieval keeps at most three entries, each scoring at least 0.1 and within 25 percent of the best one. A question that names nothing in the catalog reads nothing, and the file makes no RPC call for it.

## One read for every match

[`getMultipleAccounts`](https://carbium.sh/docs#rpc) charges 10 cells per pubkey. It takes up to 300 pubkeys, but the 1024-cell burst limits one call to 100 pubkeys on every plan below Pro, so 300 holds only on Pro. Three matches cost 30 cells in one call. The cost follows the number of matches, so the top-k limit is a budget setting as well as a relevance setting.

One call also gives one slot for every account in it. Three separate `getAccountInfo` calls can land on different slots, and the prompt would then mix states from different moments under a single label. The `context.slot` of the one response is the label the prompt prints.

## Commitment and freshness

The file sets `COMMITMENT` to `"confirmed"` and passes it in the call, and the same constant fills the prompt header. If the answer must not change afterwards, switch the constant to `finalized`.

The slot in the prompt dates the read, and the numbers can be out of date one slot later. A conversation of several turns reads again on each turn that needs a number.

## Keeping a cached context current

If the same questions arrive many times a minute, a read per question adds up, and a [WebSocket subscription](https://carbium.sh/docs#websocket) can tell you when to read again. `accountSubscribe` sends a notification when an account changes, for accounts the stream carries. A plain SOL wallet stays silent there: use `logsSubscribe` with a mention, plus `getBalance`. Take the notification as the cue to drop the cached context and read again at the commitment you chose.

The WebSocket endpoint is `wss://services.carbium.sh`, with the key in the URL as `?api-key=<YOUR_KEY>`. An account or logs-mention subscription opens at 25 credits, then costs 20 credits per MiB sent, and a refused subscription is free. Free carries 5 sockets, and connection and subscription counts are capped per account by tier.

## Where it ends

- The embedding matches spelling only. Paraphrase, synonyms and other languages need a model's embedding in place of `embed`.
- The catalog is yours to maintain, and the file decodes token mints only. Any other account type needs its own layout before its bytes mean anything to a model.
- Each question gets one snapshot. A change after the read is invisible to that answer, which is only as new as the slot printed in its prompt.
- History is shallow. `getSignaturesForAddress` costs 50 cells and pages from Carbium's own address index, which keeps up to 30 days. An empty page past that is the index's age limit, and the address may have older transactions, so retrieval over past activity covers 30 days at most.
- Some retrieval ideas have no method behind them. `getTokenLargestAccounts` and `getProgramAccountsV2` are not served and answer -32601, method not served, which means do not retry. A step that needs every holder of a mint has to come from your own list.
- Text that strangers wrote on chain, such as token names and memos, can contain instructions. This file puts no on-chain text in the prompt, only the question, your catalog notes, numbers and addresses. If you add token names or memos, put them in quotes below the instruction line, marked as data.
- The file is read-only: no signing, no sending, no keys beyond the Carbium key.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The prompt mixes numbers from different slots. | Read all matches in one `getMultipleAccounts` call and print its `context.slot`. Avoid one `getAccountInfo` call per match. |
| A question about USDC also pulls in the USDT entry. | Trigram hashes of near-identical names overlap. Keep the relative score cutoff, or switch `embed` to a model embedding, and name both tokens when you want both. |
| The model quotes a supply that was stored in the index. | Keep only addresses and descriptions in the catalog. Anything that changes between slots comes from the live read. |
| An address with no account leaves a null in `value`, and the prompt shows a blank. | Print `account not found` for that entry, as the file does, so the model is told the account is missing and does not guess. |

## Questions

### Does this need an embedding endpoint?

Not as written: `embed` runs locally and matches spelling. For paraphrase you need an embedding model, which replaces `embed` and returns the same kind of normalised array.

### Why not embed the account data itself?

Account state changes between slots, so a stored vector describes a moment that has passed. Embed the description, which changes only when you edit it, and read the state at question time.

### How many accounts can one read carry?

Up to 100 pubkeys per `getMultipleAccounts` call on Free, Dev and Business, and up to 300 on Pro, at 10 cells each. Most questions need two or three, so the retrieval cutoff matters more than the cap.

### Can I use the WebSocket instead of reading again?

A subscription tells you that an account changed, for accounts the stream carries, and it is billed in credits by filter weight and by MiB sent. Use the notification as the cue to read again.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
