library / AI and blockchain / Model tool calling / SI0045
Live token price tool
A token price handler a model can call from either vendor's tool format: two wrappers over one JSON Schema, one result carrying mint, price, slot and read time, and a plain answer when a mint has no price.
Two definitions, one schema
A model picks a tool from the definition you send. The two common tool-calling APIs wrap the same three parts differently: a name, a description and a JSON Schema for the arguments. Write the schema once and wrap it twice, and the handler behind it never learns which vendor called.
| Part | Anthropic Messages | OpenAI Chat Completions |
|---|---|---|
| Definition | { name, description, input_schema } | { type: "function", function: { name, description, parameters } } |
| Schema key | input_schema | parameters |
| Call from the model | a tool_use block with an id and an input object | an entry in tool_calls with an id and function.arguments, a JSON string |
| Result you send back | a tool_result block with the tool_use_id | a message with role tool, a tool_call_id and a string content |
The one difference that touches code is the arguments. Anthropic hands you an object and OpenAI hands you a string to parse, so runOpenAI parses it and passes the object on. OpenAI's Responses API takes the same function with name and parameters at the top level of the tool, and the schema inside is unchanged.
The description carries what a model gets wrong. This one says the mint is a base58 address, that the answer is a read at one moment, and that found is false when no price exists, so the model reports a missing price and does not invent one. additionalProperties: false tells the model nothing else is accepted. The schema informs the model and enforces nothing, so any failure in the handler comes back as an error result.
The handler
Install the one dependency with npm i @solana/[email protected] and set CARBIUM_KEY; the file exits with a message when it is missing. It runs on Node 24, which strips the types on load. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh.
// SI0045 · Live token price tool// https://carbium.sh/library/si/live-token-price-tool// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: one token price handler, wrapped as an Anthropic tool and as an OpenAI function. Run: CARBIUM_KEY=... node main.tsimport { 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 headers = { "x-api-key": key };const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers }));const name = "get_token_price";const description = "Price of one Solana token from its base58 mint address, with the slot at confirmed commitment and the UTC time of the read. Read only. Say the price was read at that time, never how old it is. found is false when no price exists for the mint.";const schema = { type: "object", properties: { mint: { type: "string", description: "Base58 mint address, copied exactly" } }, required: ["mint"], additionalProperties: false,};export const forAnthropic = { name, description, input_schema: schema };export const forOpenAI = { type: "function", function: { name, description, parameters: schema } };type Row = [string, number | null, ...unknown[]];// The quote plane's prices method; kit has no method for it, so it is a plain JSON-RPC POST.async function priceRow(mint: string): Promise<Row | undefined> { const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "prices", params: { mints: [mint] } }); const res = await fetch(url, { method: "POST", headers: { ...headers, "content-type": "application/json" }, body }); if (res.status === 429) throw new Error("rate limited, wait a few seconds before the next call"); const j = (await res.json()) as { result?: { rows?: Row[] }; error?: { message?: string } }; if (!j.result) throw new Error(j.error?.message ?? `prices answered ${res.status}`); return j.result.rows?.find((r) => r[0] === mint);}export async function getTokenPrice(input: { mint?: unknown }) { const mint = String(input.mint ?? ""); const [px, slot] = await Promise.allSettled([priceRow(mint), rpc.getSlot().send()]); if (px.status === "rejected") return { error: px.reason instanceof Error ? px.reason.message : String(px.reason) }; const readAt = new Date().toISOString(); const base = { mint, slot: slot.status === "fulfilled" ? Number(slot.value) : null, readAt }; const price = px.value?.[1]; return typeof price === "number" ? { found: true, price, ...base } : { found: false, ...base };}// OpenAI sends the arguments as a JSON string; Anthropic sends an object.export async function runOpenAI(args: string) { try { return await getTokenPrice(JSON.parse(args)); } catch { return { error: "arguments were not a JSON object" }; }}if (import.meta.main) { console.log(JSON.stringify([forAnthropic, forOpenAI], null, 1)); const SOL = "So11111111111111111111111111111111111111112"; const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; const NONE = "11111111111111111111111111111111"; console.log(JSON.stringify(await getTokenPrice({ mint: SOL }))); console.log(JSON.stringify(await runOpenAI(JSON.stringify({ mint: USDC })))); console.log(JSON.stringify(await getTokenPrice({ mint: NONE })));}
run: node main.ts
prices is one of the four methods the quote plane answers on the RPC endpoint, next to quote, swap and health. Kit has no method for it, so the handler posts it with fetch to the same URL, with the same x-api-key request header and { mints: [mint] } as params. Kit makes the getSlot call. A key without the QUOTE scope is refused with 401 and -32001, and the handler returns that message as an error result.
Both calls start together under Promise.allSettled. A failed price call returns { error }, which you send back as the tool result so the model can say what happened. A failed slot call leaves slot null and the price still goes out.
A run prints the two definitions as JSON, then three results: SOL through the object path, USDC through the string path that runOpenAI takes, and the system program address, which is no token and has no price row.
What a result carries
| Field | Meaning |
|---|---|
| mint | the string the model sent, echoed so a result still reads right beside others in one turn |
| found | true when the answer held a row for the mint with a numeric price |
| price | the price from that row, as the prices method states it; absent when found is false |
| slot | the slot getSlot answered, at confirmed commitment because kit fills that in; null when that call failed |
| readAt | UTC time in ISO 8601, taken once both answers reached the handler |
slot and readAt say when the read happened. A slot is about 200 ms since the Alpenglow switch and a model turn takes seconds, so by the time the model writes its answer the chain is several slots past slot. Put in the description that the model should say the price was read at that time, and quote readAt.
The slot comes from its own call, made beside the price call. The two calls run together, so the slot places the read on the chain to within the moment between the two answers. It does not tie the price to that slot. Kit returns the slot as a bigint, which JSON.stringify refuses, so the handler turns it into a number before the result is serialised.
A mint with no row
The prices method answers with rows for the mints it prices. A mint with no row is a normal answer, and the handler does not guess one. It returns found: false with the mint, the slot and readAt, and no price key. A row whose price is null gets the same result.
Send it back as a successful result. An error result says the call failed, and found: false says the call worked and the answer is empty, which a model words differently. The system program address in the run shows it. A mistyped mint may land here or come back as an error result with the reason; either reaches the model, so the description asks it to copy the mint exactly from the user's message or an earlier result.
Where it ends
- readAt is the time both answers reached the handler. The handler reads two columns of a row, the mint and the price, and nothing it reads dates the price at its source. A price can be older than readAt.
- One mint a call. prices takes a list in mints, so a model that needs ten tokens makes ten calls in a turn, or you add a second tool that sends the list.
- Price only. The tool returns no supply, decimals or authorities; Token mint supply and authorities reads those from the mint.
- No model request and no loop. The file prints what each vendor's client would receive and then runs the handler; sending the definitions and returning the results belongs to your model client, and LLM tool calling shows one turn of that loop.
- The getSlot call is RPC work that credits meter, while the price call spends none.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The OpenAI call reaches the handler with an undefined mint. | function.arguments is a JSON string. Parse it before the handler reads it; runOpenAI does and returns an error result for text that is not a JSON object. |
| The model describes the price as current, or states how old it is. | The handler cannot date the price at its source. Tell the model in the description to say the price was read at readAt, and never to give an age. |
| Every call returns 401 with -32001. | The key lacks the QUOTE scope. Give it the scope and send the whole key in the x-api-key header. |
| JSON.stringify throws on the slot. | Kit returns slots as bigint. Convert with Number before the result is serialised, as the handler does. |
| The model gives a price for a mint whose result says found: false. | Leave the price key out of that result and state in the description that found: false means no price exists for the mint. |
| A turn with many price calls comes back as 429. | priceRow turns a 429 into an error result telling the model to wait, so cap the price calls per task in your loop. |
Questions
Can one handler serve both vendors?
Yes. The wrappers differ in where the schema sits and in how arguments arrive, an object or a JSON string. The Carbium calls and the result are the same for both.
Why post `prices` with fetch when kit is installed?
Kit has no method for prices, so the handler sends the same JSON-RPC to the same URL with the same key header. Kit makes the getSlot call, which is a cached read at 1 cell.
Does the price call spend credits?
No. Credits meter RPC, WebSocket, stream and webhook work, and the quote plane spends none, because its own plan is the meter. That plan's Free tier runs at 10 quotes a second.
What should the model say about time?
That the price was read at readAt, at the slot in the result. It has no source time to quote, so it should not name an age.
Which commitment does `slot` use?
Confirmed. Kit fills that in when a call leaves commitment out, and the description says so.