@blockrun/llm 4.1.0 โ 4.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -27
- package/dist/index.cjs +184 -6
- package/dist/index.d.cts +21 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +184 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,7 +44,7 @@ console.log(r.response); // the proof
|
|
|
44
44
|
## Why This SDK
|
|
45
45
|
|
|
46
46
|
- ๐ง **Smart routing that pays for itself.** The bundled [Router Core V3](https://github.com/BlockRunAI/router-core) engine (shared with [ClawRouter](https://github.com/BlockRunAI/ClawRouter)) classifies every request locally in <1ms across <!-- br:clawrouter.dimensions -->15<!-- /br:clawrouter.dimensions --> dimensions and routes to the cheapest capable model.
|
|
47
|
-
- ๐ **<!-- br:models.free -->9<!-- /br:models.free --> genuinely free models.** $0 in and out, including two 1M-context Nemotrons, two that accept images,
|
|
47
|
+
- ๐ **<!-- br:models.free -->9<!-- /br:models.free --> genuinely free models.** $0 in and out, including two 1M-context Nemotrons, two that accept images, a 1M-context MiniMax and a free Poolside coding model.
|
|
48
48
|
- ๐ **Two ways to connect.** A **BlockRun API key** billed against account credit ([sign up](https://user.blockrun.ai), [create a key](https://user.blockrun.ai/dashboard/keys), [add credit](https://user.blockrun.ai/dashboard/credits)), or a wallet signature with x402 micropayments and no account at all. Same code either way.
|
|
49
49
|
- ๐ธ **Pay per request in USDC.** x402 micropayments on Solana, Base or Arc. Agents can fund and pay their own way.
|
|
50
50
|
- ๐ก๏ธ **Automatic failover.** Transient errors (timeouts, 429, 5xx) before payment walk the router's ranked fallback chain instead of failing your request; a failure after a payment was sent never buys a second model.
|
|
@@ -111,6 +111,7 @@ The Anthropic SDK is a runtime dependency because the public compatibility wrapp
|
|
|
111
111
|
| Try it for $0 | [Try It Free](#try-it-free-no-usdc-required) and [Free Tier](#free-tier) |
|
|
112
112
|
| Understand wallet payments and settlement | [How Payment Works](#how-payment-works) |
|
|
113
113
|
| Pay from a Solana wallet | [Solana Support](#solana-support) |
|
|
114
|
+
| Pay with USDC on Circle's Arc | [Arc Support](#arc-support) |
|
|
114
115
|
| Enable metered batch settlement | [Batch settlement](#batch-settlement-optional-metered-billing) and the [full reference](https://github.com/BlockRunAI/blockrun-llm-ts/blob/main/docs/solana-batch.md) |
|
|
115
116
|
| Stream tokens, use tools | [Chat, Tools and Streaming](#chat-tools-and-streaming) |
|
|
116
117
|
| Generate media or query data services | [Models and Service APIs](#models-and-service-apis) |
|
|
@@ -227,7 +228,7 @@ console.log(result.response); // 'The capital of France is Paris.'
|
|
|
227
228
|
console.log(result.routing.savings); // 1 (100%)
|
|
228
229
|
```
|
|
229
230
|
|
|
230
|
-
The
|
|
231
|
+
The free models to pin are listed under [Free Tier](#free-tier). `eco` lands on
|
|
231
232
|
a free model when one can handle the request and moves to the cheapest paid
|
|
232
233
|
model when none can; pin a free id when the call must cost $0.
|
|
233
234
|
|
|
@@ -404,7 +405,7 @@ anchors the portfolio's candidate pool):
|
|
|
404
405
|
|
|
405
406
|
| Tier | Example Tasks | ECO | AUTO | PREMIUM |
|
|
406
407
|
|------|---------------|-----|------|---------|
|
|
407
|
-
| SIMPLE | "What is the capital of France?", definitions | nemotron-3.5-lightning (**FREE**) | gemini-2.5-flash | gemini-
|
|
408
|
+
| SIMPLE | "What is the capital of France?", definitions | nemotron-3.5-lightning (**FREE**) | gemini-2.5-flash | gemini-3.5-flash |
|
|
408
409
|
| MEDIUM | Code snippets, explanations | glm-5.3-flash | gemini-3.5-flash | gpt-5.3-codex |
|
|
409
410
|
| COMPLEX | Architecture, long documents | glm-5.3-flash | gemini-3.1-pro | claude-fable-5 |
|
|
410
411
|
| REASONING | Proofs, multi-step reasoning | deepseek-reasoner | deepseek-reasoner | claude-sonnet-5 |
|
|
@@ -437,7 +438,7 @@ picked:
|
|
|
437
438
|
| `costEstimate` / `baselineCost` | Estimated cost of the pick vs that baseline, in USD |
|
|
438
439
|
| `confidence` | Sigmoid-calibrated classifier confidence, 0โ1 |
|
|
439
440
|
| `routerVersion` | `'v3-portfolio'` or `'v2-rules'` |
|
|
440
|
-
| `profile` |
|
|
441
|
+
| `profile` | Tier set the decision used: `'auto'`, `'eco'`, `'premium'`, or `'agentic'` (the router's own set for agentic requests; not a `routingProfile` you can pass) |
|
|
441
442
|
| `reasoning` | Human-readable explanation of the decision |
|
|
442
443
|
| `tierConfigs` | The tier โ primary/fallback map the decision was made against |
|
|
443
444
|
|
|
@@ -639,6 +640,7 @@ own default applies, and some default to their highest effort (Reflection Beam
|
|
|
639
640
|
defaults to `"max"`); reasoning tokens bill as output:
|
|
640
641
|
|
|
641
642
|
```typescript
|
|
643
|
+
const messages = [{ role: 'user' as const, content: 'Summarize x402 in one line' }];
|
|
642
644
|
const quick = await client.chatCompletion('reflection/beam-1.0-501b-a23b', messages, {
|
|
643
645
|
reasoningEffort: 'low', // none | minimal | low | medium | high | xhigh | max, per model
|
|
644
646
|
maxTokens: 8192, // reasoning counts toward max_tokens
|
|
@@ -648,9 +650,12 @@ const quick = await client.chatCompletion('reflection/beam-1.0-501b-a23b', messa
|
|
|
648
650
|
`costUsd`, `settlement` and the per-call `timeout` work the same on `LLMClient`
|
|
649
651
|
(Base / Arc). Both clients default to a 600 s request timeout
|
|
650
652
|
(`BLOCKRUN_CHAT_TIMEOUT`, in seconds, overrides it; the `timeout` option, in
|
|
651
|
-
ms, overrides both)
|
|
652
|
-
charged
|
|
653
|
-
|
|
653
|
+
ms, overrides both). A call aborted after its payment was sent may already
|
|
654
|
+
have been charged; under Solana batch settlement such a call raises
|
|
655
|
+
`BatchPaymentUnresolvedError` rather than being paid again (see
|
|
656
|
+
[Batch settlement](#batch-settlement-optional-metered-billing)).
|
|
657
|
+
|
|
658
|
+
`costUsd` is what the call added to `getSpending()`: the signed price under `exact`, the metered `extra.chargedAmount` under batch settlement,
|
|
654
659
|
`0` for a free model; it is undefined in API-key mode (billed to the account).
|
|
655
660
|
When the gateway answers a paid request from a free fallback model it skips
|
|
656
661
|
settlement: `costUsd` is `0`, `settlement.skipped` is `"free-fallback"`, and
|
|
@@ -732,8 +737,9 @@ await client.closeBatchChannel();
|
|
|
732
737
|
- **Explicit trust.** `operators` has no default, and the SDK never learns a trusted key from a 402.
|
|
733
738
|
- **Bounded exposure.** `maxDeposit` caps the escrow deposited and not yet settled on-chain; it is the most the operator could claim without another authorization from you.
|
|
734
739
|
- **Never pays twice.** Anything that goes wrong before a batch payment is sent falls back to `exact`. Once one is sent, a call whose payment may have been charged throws `BatchPaymentUnresolvedError` and is never paid again (no new payment, no `exact`, no fallback model).
|
|
735
|
-
- **
|
|
740
|
+
- **Chat, buffered and streamed.** `chat`, `chatCompletion`, `smartChat`, `smartChatCompletion` and `stream()` use batch; media jobs pay `exact`. A stream's receipt arrives as a final SSE event the SDK reads and removes before your loop sees it (it never reaches your chunks), or, for a stream that is cut, from `POST /v1/batch/receipt` afterwards. Its charge is booked in `getSpending()` once that receipt is in, which can be a few seconds after your loop ends: the model may keep generating after a disconnect, and that is charged too.
|
|
736
741
|
- **One channel per wallet.** All clients for a wallet share one channel, saved to `~/.blockrun/solana-batch/<wallet>.json` (mode `0600`) so a restart reuses it.
|
|
742
|
+
- **One call at a time per wallet.** A channel carries one pending authorization, and each voucher builds on the previous call's metered charge, which is known only once that call's answer is in. So the wallet stays busy from payment until the answer is reconciled: the whole generation, and for `stream()` the whole stream (including a stream your loop stopped reading: the SDK keeps reading it to its receipt, because everything generated is charged). A concurrent chat call on the same wallet (`chat`, `chatCompletion`, `smartChat`, `smartChatCompletion`, `stream()`) falls back to `exact` meanwhile, reported as `channel_busy`; it does not queue. For parallel batch calls, give each worker its own wallet ([#98](https://github.com/BlockRunAI/blockrun-llm-ts/issues/98) tracks queueing and multi-channel options).
|
|
737
743
|
- **One process per wallet.** The process that opens the channel holds its store's lock until it exits. Other processes on that wallet (worker pools, PM2/cluster workers, parallel runs) pay `exact`, reported as `channel_store_locked`. Give each worker its own wallet, or route calls through one process. `batch.onLocked: "wait"` waits up to `batch.lockWaitMs` (default 60 s) for the lock, and `"throw"` raises `BatchChannelLockedError` (unpaid, nothing signed) instead of paying `exact`.
|
|
738
744
|
- **Observable.** Every fallback, backoff, recovery and re-read writes one stderr line; `batch.onEvent` and `client.getBatchStats()` expose the same events and counters.
|
|
739
745
|
|
|
@@ -760,7 +766,7 @@ The 402 from that host names `eip155:5042`, and the SDK signs the EIP-3009 autho
|
|
|
760
766
|
|
|
761
767
|
**Setup:**
|
|
762
768
|
1. Same wallet key as Base: `export BASE_CHAIN_WALLET_KEY="0x..."`
|
|
763
|
-
2. Fund it with USDC on Arc (Arc's native token
|
|
769
|
+
2. Fund it with USDC on Arc (Arc's native gas token; the SDK pays through its ERC-20 interface at `0x3600โฆ0000`)
|
|
764
770
|
3. `apiUrl: 'https://arc.blockrun.ai/api'` โ payments are automatic via x402
|
|
765
771
|
|
|
766
772
|
**Endpoint:** `https://arc.blockrun.ai/api` ยท **Payment:** USDC on Arc (chain 5042), settled by Circle
|
|
@@ -808,9 +814,10 @@ console.log(result.choices[0].message.content);
|
|
|
808
814
|
### Streaming
|
|
809
815
|
|
|
810
816
|
Every client streams with automatic payment. On `LLMClient` in Base / Arc
|
|
811
|
-
wallet mode, `chatCompletionStream()` also keeps a **pre-auth cache**:
|
|
812
|
-
first call
|
|
813
|
-
(about
|
|
817
|
+
wallet mode, `chatCompletionStream()` also keeps a **pre-auth cache**: once a
|
|
818
|
+
first call has learned a model's price, later calls to that model sign the
|
|
819
|
+
payment before sending and skip the 402 round-trip (about 200 ms saved per
|
|
820
|
+
request).
|
|
814
821
|
|
|
815
822
|
#### OpenAI-compatible (recommended)
|
|
816
823
|
|
|
@@ -871,8 +878,10 @@ while (true) {
|
|
|
871
878
|
yields each `data:` frame already parsed as JSON and stops at `[DONE]`. The
|
|
872
879
|
x402 handshake happens before the first frame โ 402, sign an SPL
|
|
873
880
|
TransferChecked authorization locally, replay with `PAYMENT-SIGNATURE` โ
|
|
874
|
-
including the fresh-blockhash re-sign on a verification-phase rejection.
|
|
875
|
-
|
|
881
|
+
including the fresh-blockhash re-sign on a verification-phase rejection. When
|
|
882
|
+
the client is constructed with `batch`, the stream is paid with a channel
|
|
883
|
+
voucher instead and charged the metered cost (see [Batch settlement](#batch-settlement-optional-metered-billing)).
|
|
884
|
+
A free model, or an account key, is answered `200` with no handshake at all and
|
|
876
885
|
settles nothing. Pass a concrete model id: `stream()` does not resolve the
|
|
877
886
|
`blockrun/*` aliases.
|
|
878
887
|
|
|
@@ -928,16 +937,17 @@ prefix, or let `routingProfile: 'eco'` rank them first.
|
|
|
928
937
|
| `nvidia/nemotron-3.5-lightning` | 1M | Thinking-mode reasoning at 1M context |
|
|
929
938
|
| `nvidia/nemotron-3-ultra-550b` | 1M | Largest free model โ 550B, 1M context |
|
|
930
939
|
| `nvidia/nemotron-3-nano-omni-30b-a3b-reasoning` | 256K | Multimodal reasoning โ text + images |
|
|
940
|
+
| `nvidia/minimax-m3.1-flash` | 1M | MiniMax M3.1 Flash โ reasons, calls tools |
|
|
931
941
|
| `nvidia/nemotron-3.5-bolt` | 128K | Free vision โ verified on real image probes on Base and Solana |
|
|
932
942
|
| `poolside/laguna-xs-2.1` | 128K | Coding model |
|
|
933
943
|
|
|
934
944
|
A free model can be briefly marked unavailable in the live catalog while the
|
|
935
945
|
gateway's health check holds it back; it stays on the free tier.
|
|
936
946
|
|
|
937
|
-
`nvidia/llama-3.2-11b-vision`, `
|
|
938
|
-
still answer, but
|
|
939
|
-
|
|
940
|
-
|
|
947
|
+
`nvidia/llama-3.2-11b-vision`, `nvidia/nemotron-3-super-120b`,
|
|
948
|
+
`cohere/north-mini-code` and `nvidia/muse-glimmer-30b` still answer, but since
|
|
949
|
+
2026-11 the gateway serves them with a different model. Don't pin them; use
|
|
950
|
+
`nemotron-3.5-bolt` for free image input.
|
|
941
951
|
|
|
942
952
|
<details>
|
|
943
953
|
<summary><strong>Paid chat models</strong> โ OpenAI, Anthropic, Google, DeepSeek, xAI, Moonshot, MiniMax, Z.ai, Qwen, Mistral, Tencent, Poolside, Xiaomi</summary>
|
|
@@ -976,7 +986,6 @@ token price.
|
|
|
976
986
|
| `openai/gpt-5-mini` | 200K | |
|
|
977
987
|
| `openai/gpt-4.1` | 128K | |
|
|
978
988
|
| `openai/gpt-4.1-mini` | 128K | |
|
|
979
|
-
| `openai/gpt-4.1-nano` | 128K | |
|
|
980
989
|
| `openai/gpt-4o` | 128K | |
|
|
981
990
|
| `openai/gpt-4o-mini` | 128K | |
|
|
982
991
|
| `openai/o1` | 200K | Reasoning |
|
|
@@ -988,7 +997,8 @@ token price.
|
|
|
988
997
|
|
|
989
998
|
| Model | Context | Notes |
|
|
990
999
|
|---|---|---|
|
|
991
|
-
| `anthropic/claude-fable-5.
|
|
1000
|
+
| `anthropic/claude-fable-5.2` | 1M | Most capable โ successor to Fable 5.1 at a lower price, 128K output |
|
|
1001
|
+
| `anthropic/claude-fable-5.1` | 1M | Successor to Fable 5 at the same tier and price |
|
|
992
1002
|
| `anthropic/claude-fable-5` | 1M | Mythos-class flagship above Opus โ always-on thinking, 128K output |
|
|
993
1003
|
| `anthropic/claude-opus-5.5` | 1M | Newest Opus โ Opus-class reasoning at a lower price than Opus 5 |
|
|
994
1004
|
| `anthropic/claude-opus-5` | 1M | Flagship โ the baseline the routing savings claim is measured against |
|
|
@@ -1005,6 +1015,7 @@ token price.
|
|
|
1005
1015
|
|
|
1006
1016
|
| Model | Context |
|
|
1007
1017
|
|---|---|
|
|
1018
|
+
| `google/gemini-4-carbon` | 1M |
|
|
1008
1019
|
| `google/gemini-4-argon` | 1M |
|
|
1009
1020
|
| `google/gemini-3.1-pro` | 1M |
|
|
1010
1021
|
| `google/gemini-3.8-flash` | 1M |
|
|
@@ -1026,6 +1037,7 @@ paid SKU; the vision SKU is an experimental preview.
|
|
|
1026
1037
|
| Model | Context | Notes |
|
|
1027
1038
|
|---|---|---|
|
|
1028
1039
|
| `deepseek/deepseek-v4-pro` | 1M | V4 flagship โ strongest open-weight reasoner |
|
|
1040
|
+
| `deepseek/deepseek-v4.1-flash` | 1M | V4.1 Flash non-thinking |
|
|
1029
1041
|
| `deepseek/deepseek-v4-flash-vision-exp` | 1M | Experimental vision preview |
|
|
1030
1042
|
| `deepseek/deepseek-chat` | 1M | V4 Flash non-thinking |
|
|
1031
1043
|
| `deepseek/deepseek-reasoner` | 1M | V4 Flash thinking (same upstream, thinking on by default) |
|
|
@@ -1048,7 +1060,7 @@ callable โ the gateway redirects them to a healthy model.
|
|
|
1048
1060
|
|
|
1049
1061
|
| Model | Context | Notes |
|
|
1050
1062
|
|---|---|---|
|
|
1051
|
-
| `moonshot/kimi-k3` | 1M |
|
|
1063
|
+
| `moonshot/kimi-k3.1-pro` | 1M | Flagship, image + text input; `kimi-k3` stays callable but is unlisted |
|
|
1052
1064
|
| `minimax/minimax-m3` | 1M | |
|
|
1053
1065
|
| `minimax/minimax-m2.7` | 200K | |
|
|
1054
1066
|
| `zai/glm-5.3` | 1M | |
|
|
@@ -1196,7 +1208,8 @@ console.log(fused.data[0].url);
|
|
|
1196
1208
|
| `bytedance/seedance-2.0-mini` | 5s | 15s | 480p/720p, lowest-cost Seedance 2.0. RealFace supported |
|
|
1197
1209
|
| `bytedance/seedance-2.0` | 5s | 15s | Premium, up to 4K, synced audio. RealFace supported |
|
|
1198
1210
|
| `bytedance/seedance-2.5` | 5s | 30s | Long-form โ up to 30s, 480p/720p, multilingual, up to 30 reference images |
|
|
1199
|
-
|
|
1211
|
+
|
|
1212
|
+
Sora 2 (`azure/sora-2`, `openai/sora-2`) was retired by its providers on 2026-11-02 and is no longer served.
|
|
1200
1213
|
|
|
1201
1214
|
```typescript
|
|
1202
1215
|
import { VideoClient } from '@blockrun/llm';
|
|
@@ -1417,7 +1430,7 @@ Supported `StockMarket` values: `us, hk, jp, kr, gb, de, fr, nl, ie, lu, cn, ca`
|
|
|
1417
1430
|
Prediction-market data from Polymarket, Kalshi, Limitless, Opinion,
|
|
1418
1431
|
Predict.Fun, Binance Futures, UMA oracle resolutions and sports markets via
|
|
1419
1432
|
[Predexon](https://predexon.com). Every endpoint costs the same flat price per
|
|
1420
|
-
call
|
|
1433
|
+
call. Use an account API key or x402 wallet
|
|
1421
1434
|
payments; no separate Predexon key is needed. `pm()` works on both `LLMClient`
|
|
1422
1435
|
and `SolanaLLMClient`; query parameters are strings.
|
|
1423
1436
|
|
|
@@ -1593,8 +1606,9 @@ const gptResponse = await client.messages.create({
|
|
|
1593
1606
|
|
|
1594
1607
|
This wrapper proxies straight to the gateway's `/v1/messages` and does not
|
|
1595
1608
|
resolve `blockrun/*` aliases; pass a concrete model id. Anthropic's own dashed
|
|
1596
|
-
ids resolve, including the Mythos-class `claude-fable-5
|
|
1597
|
-
`claude-fable-5-1` / `claude-fable-5.1`
|
|
1609
|
+
ids resolve, including the Mythos-class `claude-fable-5`,
|
|
1610
|
+
`claude-fable-5-1` / `claude-fable-5.1` and `claude-fable-5-2` /
|
|
1611
|
+
`claude-fable-5.2` (1M context, always-on thinking).
|
|
1598
1612
|
|
|
1599
1613
|
## Wallets
|
|
1600
1614
|
|
|
@@ -1835,10 +1849,10 @@ A TypeScript SDK that cuts LLM costs by <!-- br:savings.autoVsBaselinePct -->84<
|
|
|
1835
1849
|
Router Core V3, bundled into the SDK: the same deterministic engine that powers ClawRouter. It analyzes each request across <!-- br:clawrouter.dimensions -->15<!-- /br:clawrouter.dimensions --> dimensions locally, in under 1ms, and picks the cheapest capable model. Use `smartChat()`, `smartChatCompletion()`, or the `blockrun/auto` model alias. See [Smart Routing](#smart-routing-router-core-v3).
|
|
1836
1850
|
|
|
1837
1851
|
### Does it support streaming?
|
|
1838
|
-
Yes: `LLMClient.chatCompletionStream()`, `stream: true` in the OpenAI-compatible client, and `
|
|
1852
|
+
Yes: `LLMClient.chatCompletionStream()`, `stream: true` in the OpenAI-compatible client, `SolanaLLMClient.stream()`, and `BlockrunClient.stream()`. The payment is signed before the first token (under Solana batch settlement the metered charge is booked once the stream's receipt arrives), and with an API key the stream is billed to your account.
|
|
1839
1853
|
|
|
1840
1854
|
### How much does it cost?
|
|
1841
|
-
Pay only for what you use: no minimums, subscriptions, or monthly fees, and
|
|
1855
|
+
Pay only for what you use: no minimums, subscriptions, or monthly fees, and the [free tier](#free-tier) costs $0. Live per-model rates are at [blockrun.ai/models](https://blockrun.ai/models).
|
|
1842
1856
|
|
|
1843
1857
|
### Do I need a crypto wallet?
|
|
1844
1858
|
No. An account API key from [user.blockrun.ai](https://user.blockrun.ai) works without any wallet or chain. Wallets are for x402 pay-per-request on Solana (`SolanaLLMClient`, recommended), Base or Arc (`LLMClient`).
|
package/dist/index.cjs
CHANGED
|
@@ -5317,7 +5317,7 @@ function getCostSummary() {
|
|
|
5317
5317
|
}
|
|
5318
5318
|
|
|
5319
5319
|
// src/version.ts
|
|
5320
|
-
var SDK_VERSION = "4.1
|
|
5320
|
+
var SDK_VERSION = "4.2.1";
|
|
5321
5321
|
var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
|
|
5322
5322
|
|
|
5323
5323
|
// src/client.ts
|
|
@@ -10477,6 +10477,103 @@ function signPollOwnership(secretKey, kind, jobId, nowMs = Date.now()) {
|
|
|
10477
10477
|
};
|
|
10478
10478
|
}
|
|
10479
10479
|
|
|
10480
|
+
// src/stream-receipt.ts
|
|
10481
|
+
var STREAM_RECEIPT_HEADER = "X-BlockRun-Stream-Receipt";
|
|
10482
|
+
var RECEIPT_EVENT = "payment-response";
|
|
10483
|
+
var EVENT_END = /\r?\n\r?\n/;
|
|
10484
|
+
function isReceiptBlock(block) {
|
|
10485
|
+
return block.split(/\r?\n/).some((line) => line.trim() === `event: ${RECEIPT_EVENT}` || line.trim() === `event:${RECEIPT_EVENT}`);
|
|
10486
|
+
}
|
|
10487
|
+
function parseReceiptBlock(block) {
|
|
10488
|
+
const data = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
|
|
10489
|
+
try {
|
|
10490
|
+
const parsed = JSON.parse(data);
|
|
10491
|
+
if (typeof parsed?.status !== "string") return void 0;
|
|
10492
|
+
return { status: parsed.status, ...typeof parsed.payment_response === "string" ? { paymentResponse: parsed.payment_response } : {} };
|
|
10493
|
+
} catch {
|
|
10494
|
+
return void 0;
|
|
10495
|
+
}
|
|
10496
|
+
}
|
|
10497
|
+
function withoutReceiptEvent(body) {
|
|
10498
|
+
const decoder = new TextDecoder();
|
|
10499
|
+
const encoder = new TextEncoder();
|
|
10500
|
+
let pending = "";
|
|
10501
|
+
return body.pipeThrough(
|
|
10502
|
+
new TransformStream({
|
|
10503
|
+
transform(chunk, controller) {
|
|
10504
|
+
pending += decoder.decode(chunk, { stream: true });
|
|
10505
|
+
let out = "";
|
|
10506
|
+
for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
|
|
10507
|
+
const end = match.index + match[0].length;
|
|
10508
|
+
const block = pending.slice(0, end);
|
|
10509
|
+
pending = pending.slice(end);
|
|
10510
|
+
if (!isReceiptBlock(block)) out += block;
|
|
10511
|
+
}
|
|
10512
|
+
if (out) controller.enqueue(encoder.encode(out));
|
|
10513
|
+
},
|
|
10514
|
+
flush(controller) {
|
|
10515
|
+
const rest = pending + decoder.decode();
|
|
10516
|
+
if (rest && !isReceiptBlock(rest)) controller.enqueue(encoder.encode(rest));
|
|
10517
|
+
}
|
|
10518
|
+
})
|
|
10519
|
+
);
|
|
10520
|
+
}
|
|
10521
|
+
async function readReceiptEvent(body) {
|
|
10522
|
+
const reader = body.getReader();
|
|
10523
|
+
const decoder = new TextDecoder();
|
|
10524
|
+
let pending = "";
|
|
10525
|
+
try {
|
|
10526
|
+
for (; ; ) {
|
|
10527
|
+
const { done, value } = await reader.read();
|
|
10528
|
+
if (done) return void 0;
|
|
10529
|
+
pending += decoder.decode(value, { stream: true });
|
|
10530
|
+
for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
|
|
10531
|
+
const end = match.index + match[0].length;
|
|
10532
|
+
const block = pending.slice(0, end);
|
|
10533
|
+
pending = pending.slice(end);
|
|
10534
|
+
if (isReceiptBlock(block)) {
|
|
10535
|
+
void reader.cancel().catch(() => void 0);
|
|
10536
|
+
return parseReceiptBlock(block);
|
|
10537
|
+
}
|
|
10538
|
+
}
|
|
10539
|
+
}
|
|
10540
|
+
} catch {
|
|
10541
|
+
return void 0;
|
|
10542
|
+
} finally {
|
|
10543
|
+
try {
|
|
10544
|
+
reader.releaseLock();
|
|
10545
|
+
} catch {
|
|
10546
|
+
}
|
|
10547
|
+
}
|
|
10548
|
+
}
|
|
10549
|
+
async function lookupReceipt(apiUrl, paymentHeader, opts = {}) {
|
|
10550
|
+
const doFetch = opts.fetch ?? fetch;
|
|
10551
|
+
const attempts = opts.attempts ?? 8;
|
|
10552
|
+
const delayMs = opts.delayMs ?? 2e3;
|
|
10553
|
+
const sleep4 = opts.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
|
|
10554
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
10555
|
+
if (attempt > 0) await sleep4(Math.min(delayMs * 2 ** (attempt - 1), 15e3));
|
|
10556
|
+
let answer;
|
|
10557
|
+
try {
|
|
10558
|
+
const res = await doFetch(`${apiUrl}/v1/batch/receipt`, {
|
|
10559
|
+
method: "POST",
|
|
10560
|
+
headers: { "Content-Type": "application/json" },
|
|
10561
|
+
body: JSON.stringify({ paymentHeader })
|
|
10562
|
+
});
|
|
10563
|
+
if (res.status >= 500) continue;
|
|
10564
|
+
if (!res.ok) return void 0;
|
|
10565
|
+
answer = await res.json();
|
|
10566
|
+
} catch {
|
|
10567
|
+
continue;
|
|
10568
|
+
}
|
|
10569
|
+
if (answer?.status !== "pending") return answer;
|
|
10570
|
+
}
|
|
10571
|
+
return void 0;
|
|
10572
|
+
}
|
|
10573
|
+
function isEventStream(response) {
|
|
10574
|
+
return (response.headers.get("content-type") ?? "").includes("text/event-stream");
|
|
10575
|
+
}
|
|
10576
|
+
|
|
10480
10577
|
// src/solana-batch.ts
|
|
10481
10578
|
var import_async_hooks = require("async_hooks");
|
|
10482
10579
|
var import_crypto2 = require("crypto");
|
|
@@ -13539,6 +13636,7 @@ var SolanaLLMClient = class {
|
|
|
13539
13636
|
* @returns a response whose body has not been read.
|
|
13540
13637
|
*/
|
|
13541
13638
|
async openPaidStream(url, requestBody) {
|
|
13639
|
+
const closesAtStart = await this.batchPayer?.closeFence();
|
|
13542
13640
|
for (let staleRetries = 0; ; ) {
|
|
13543
13641
|
const response = await this.fetchWithTimeout(url, {
|
|
13544
13642
|
method: "POST",
|
|
@@ -13556,11 +13654,15 @@ var SolanaLLMClient = class {
|
|
|
13556
13654
|
throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
|
|
13557
13655
|
}
|
|
13558
13656
|
try {
|
|
13559
|
-
|
|
13560
|
-
|
|
13561
|
-
response,
|
|
13562
|
-
|
|
13563
|
-
|
|
13657
|
+
let exactPayment;
|
|
13658
|
+
if (this.batchPayer && staleRetries === 0) {
|
|
13659
|
+
const batch = await this.openBatchStream(url, requestBody, await this.readPaymentRequired(response), closesAtStart);
|
|
13660
|
+
if (batch.kind === "stream") return batch.response;
|
|
13661
|
+
exactPayment = await this.signExactPayment(url, batch.paymentRequired, false);
|
|
13662
|
+
} else {
|
|
13663
|
+
exactPayment = await this.signPaymentFrom402(url, response, staleRetries > 0);
|
|
13664
|
+
}
|
|
13665
|
+
const { paymentPayload, costUsd } = exactPayment;
|
|
13564
13666
|
const paid = await this.fetchWithTimeout(url, {
|
|
13565
13667
|
method: "POST",
|
|
13566
13668
|
headers: {
|
|
@@ -13580,6 +13682,82 @@ var SolanaLLMClient = class {
|
|
|
13580
13682
|
}
|
|
13581
13683
|
}
|
|
13582
13684
|
}
|
|
13685
|
+
/**
|
|
13686
|
+
* Pay a stream with batch-settlement, when the gateway offers it.
|
|
13687
|
+
*
|
|
13688
|
+
* A stream's charge is committed after its headers are sent, so its receipt
|
|
13689
|
+
* cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
|
|
13690
|
+
* buffered call with. The request asks for it as a final SSE event instead
|
|
13691
|
+
* ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
|
|
13692
|
+
* its branch at once, live, with the receipt event taken out; the payer reads
|
|
13693
|
+
* the other branch to that event and is handed the answer with the receipt
|
|
13694
|
+
* restored as its header, so the channel advances exactly as it does for a
|
|
13695
|
+
* buffered call. A stream that ends without the event (cut, failed upstream,
|
|
13696
|
+
* an older gateway) is looked up at `POST /v1/batch/receipt`.
|
|
13697
|
+
*
|
|
13698
|
+
* The payer's branch reads to the receipt even when the caller stops early,
|
|
13699
|
+
* so the connection stays open: the gateway charges for what the model
|
|
13700
|
+
* generates either way, and only an open stream brings its receipt back.
|
|
13701
|
+
*
|
|
13702
|
+
* @returns the caller's stream, or the requirements to pay `exact` against
|
|
13703
|
+
* when batch is unavailable for this call.
|
|
13704
|
+
*/
|
|
13705
|
+
async openBatchStream(url, requestBody, paymentRequired, closesAtStart) {
|
|
13706
|
+
const headers = { "Content-Type": "application/json", "User-Agent": USER_AGENT, [STREAM_RECEIPT_HEADER]: "1" };
|
|
13707
|
+
let handOff;
|
|
13708
|
+
const handedOff = new Promise((resolve2) => {
|
|
13709
|
+
handOff = resolve2;
|
|
13710
|
+
});
|
|
13711
|
+
const attempt = this.batchPayer.pay(
|
|
13712
|
+
paymentRequired,
|
|
13713
|
+
async (paymentHeaders) => {
|
|
13714
|
+
const answer = await this.fetchWithTimeout(url, { method: "POST", headers: { ...headers, ...paymentHeaders }, body: requestBody });
|
|
13715
|
+
if (!answer.ok || !answer.body || !isEventStream(answer)) return answer;
|
|
13716
|
+
const [forCaller, forPayer] = answer.body.tee();
|
|
13717
|
+
handOff(new Response(withoutReceiptEvent(forCaller), { status: answer.status, statusText: answer.statusText, headers: answer.headers }));
|
|
13718
|
+
let receipt = (await readReceiptEvent(forPayer))?.paymentResponse;
|
|
13719
|
+
const signed = paymentHeaders["PAYMENT-SIGNATURE"];
|
|
13720
|
+
if (receipt === void 0 && signed) receipt = (await lookupReceipt(this.apiUrl, signed))?.payment_response;
|
|
13721
|
+
const settled2 = new Headers(answer.headers);
|
|
13722
|
+
if (receipt) settled2.set("PAYMENT-RESPONSE", receipt);
|
|
13723
|
+
return new Response(null, { status: answer.status, statusText: answer.statusText, headers: settled2 });
|
|
13724
|
+
},
|
|
13725
|
+
// A fresh, unpaid challenge after a 429 wait, as chatCompletion sends.
|
|
13726
|
+
async () => {
|
|
13727
|
+
const challenge = await this.sendUnpaid(url, { method: "POST", headers, body: requestBody });
|
|
13728
|
+
if (challenge.status === 402) {
|
|
13729
|
+
try {
|
|
13730
|
+
return { kind: "challenge", paymentRequired: await this.readPaymentRequired(challenge) };
|
|
13731
|
+
} catch (error) {
|
|
13732
|
+
throw withDisposition(error, "unpaid");
|
|
13733
|
+
}
|
|
13734
|
+
}
|
|
13735
|
+
if (challenge.ok) return { kind: "served", response: challenge };
|
|
13736
|
+
throw await unpaidApiError(challenge);
|
|
13737
|
+
},
|
|
13738
|
+
closesAtStart
|
|
13739
|
+
);
|
|
13740
|
+
const settled = attempt.then(
|
|
13741
|
+
(outcome2) => ({ outcome: outcome2 }),
|
|
13742
|
+
(error) => ({ error })
|
|
13743
|
+
);
|
|
13744
|
+
const first = await Promise.race([handedOff.then((response) => ({ response })), settled]);
|
|
13745
|
+
if ("response" in first) {
|
|
13746
|
+
void settled.then((result) => {
|
|
13747
|
+
if ("outcome" in result && result.outcome.kind === "paid") this.recordSettlement(result.outcome.chargedUsd, result.outcome.response);
|
|
13748
|
+
});
|
|
13749
|
+
return { kind: "stream", response: first.response };
|
|
13750
|
+
}
|
|
13751
|
+
if ("error" in first) throw first.error;
|
|
13752
|
+
const outcome = first.outcome;
|
|
13753
|
+
if (outcome.kind === "paid") {
|
|
13754
|
+
this.recordSettlement(outcome.chargedUsd, outcome.response);
|
|
13755
|
+
return { kind: "stream", response: outcome.response };
|
|
13756
|
+
}
|
|
13757
|
+
if (outcome.kind === "served") return { kind: "stream", response: outcome.response };
|
|
13758
|
+
if (outcome.kind === "failed") throw outcome.error;
|
|
13759
|
+
return { kind: "exact", paymentRequired: outcome.paymentRequired ?? paymentRequired };
|
|
13760
|
+
}
|
|
13583
13761
|
/**
|
|
13584
13762
|
* Resolve an endpoint path against this client's API root.
|
|
13585
13763
|
*
|
package/dist/index.d.cts
CHANGED
|
@@ -3931,6 +3931,27 @@ declare class SolanaLLMClient {
|
|
|
3931
3931
|
* @returns a response whose body has not been read.
|
|
3932
3932
|
*/
|
|
3933
3933
|
private openPaidStream;
|
|
3934
|
+
/**
|
|
3935
|
+
* Pay a stream with batch-settlement, when the gateway offers it.
|
|
3936
|
+
*
|
|
3937
|
+
* A stream's charge is committed after its headers are sent, so its receipt
|
|
3938
|
+
* cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
|
|
3939
|
+
* buffered call with. The request asks for it as a final SSE event instead
|
|
3940
|
+
* ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
|
|
3941
|
+
* its branch at once, live, with the receipt event taken out; the payer reads
|
|
3942
|
+
* the other branch to that event and is handed the answer with the receipt
|
|
3943
|
+
* restored as its header, so the channel advances exactly as it does for a
|
|
3944
|
+
* buffered call. A stream that ends without the event (cut, failed upstream,
|
|
3945
|
+
* an older gateway) is looked up at `POST /v1/batch/receipt`.
|
|
3946
|
+
*
|
|
3947
|
+
* The payer's branch reads to the receipt even when the caller stops early,
|
|
3948
|
+
* so the connection stays open: the gateway charges for what the model
|
|
3949
|
+
* generates either way, and only an open stream brings its receipt back.
|
|
3950
|
+
*
|
|
3951
|
+
* @returns the caller's stream, or the requirements to pay `exact` against
|
|
3952
|
+
* when batch is unavailable for this call.
|
|
3953
|
+
*/
|
|
3954
|
+
private openBatchStream;
|
|
3934
3955
|
/**
|
|
3935
3956
|
* Resolve an endpoint path against this client's API root.
|
|
3936
3957
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -3931,6 +3931,27 @@ declare class SolanaLLMClient {
|
|
|
3931
3931
|
* @returns a response whose body has not been read.
|
|
3932
3932
|
*/
|
|
3933
3933
|
private openPaidStream;
|
|
3934
|
+
/**
|
|
3935
|
+
* Pay a stream with batch-settlement, when the gateway offers it.
|
|
3936
|
+
*
|
|
3937
|
+
* A stream's charge is committed after its headers are sent, so its receipt
|
|
3938
|
+
* cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
|
|
3939
|
+
* buffered call with. The request asks for it as a final SSE event instead
|
|
3940
|
+
* ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
|
|
3941
|
+
* its branch at once, live, with the receipt event taken out; the payer reads
|
|
3942
|
+
* the other branch to that event and is handed the answer with the receipt
|
|
3943
|
+
* restored as its header, so the channel advances exactly as it does for a
|
|
3944
|
+
* buffered call. A stream that ends without the event (cut, failed upstream,
|
|
3945
|
+
* an older gateway) is looked up at `POST /v1/batch/receipt`.
|
|
3946
|
+
*
|
|
3947
|
+
* The payer's branch reads to the receipt even when the caller stops early,
|
|
3948
|
+
* so the connection stays open: the gateway charges for what the model
|
|
3949
|
+
* generates either way, and only an open stream brings its receipt back.
|
|
3950
|
+
*
|
|
3951
|
+
* @returns the caller's stream, or the requirements to pay `exact` against
|
|
3952
|
+
* when batch is unavailable for this call.
|
|
3953
|
+
*/
|
|
3954
|
+
private openBatchStream;
|
|
3934
3955
|
/**
|
|
3935
3956
|
* Resolve an endpoint path against this client's API root.
|
|
3936
3957
|
*
|
package/dist/index.js
CHANGED
|
@@ -5179,7 +5179,7 @@ function getCostSummary() {
|
|
|
5179
5179
|
}
|
|
5180
5180
|
|
|
5181
5181
|
// src/version.ts
|
|
5182
|
-
var SDK_VERSION = "4.1
|
|
5182
|
+
var SDK_VERSION = "4.2.1";
|
|
5183
5183
|
var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
|
|
5184
5184
|
|
|
5185
5185
|
// src/client.ts
|
|
@@ -10339,6 +10339,103 @@ function signPollOwnership(secretKey, kind, jobId, nowMs = Date.now()) {
|
|
|
10339
10339
|
};
|
|
10340
10340
|
}
|
|
10341
10341
|
|
|
10342
|
+
// src/stream-receipt.ts
|
|
10343
|
+
var STREAM_RECEIPT_HEADER = "X-BlockRun-Stream-Receipt";
|
|
10344
|
+
var RECEIPT_EVENT = "payment-response";
|
|
10345
|
+
var EVENT_END = /\r?\n\r?\n/;
|
|
10346
|
+
function isReceiptBlock(block) {
|
|
10347
|
+
return block.split(/\r?\n/).some((line) => line.trim() === `event: ${RECEIPT_EVENT}` || line.trim() === `event:${RECEIPT_EVENT}`);
|
|
10348
|
+
}
|
|
10349
|
+
function parseReceiptBlock(block) {
|
|
10350
|
+
const data = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
|
|
10351
|
+
try {
|
|
10352
|
+
const parsed = JSON.parse(data);
|
|
10353
|
+
if (typeof parsed?.status !== "string") return void 0;
|
|
10354
|
+
return { status: parsed.status, ...typeof parsed.payment_response === "string" ? { paymentResponse: parsed.payment_response } : {} };
|
|
10355
|
+
} catch {
|
|
10356
|
+
return void 0;
|
|
10357
|
+
}
|
|
10358
|
+
}
|
|
10359
|
+
function withoutReceiptEvent(body) {
|
|
10360
|
+
const decoder = new TextDecoder();
|
|
10361
|
+
const encoder = new TextEncoder();
|
|
10362
|
+
let pending = "";
|
|
10363
|
+
return body.pipeThrough(
|
|
10364
|
+
new TransformStream({
|
|
10365
|
+
transform(chunk, controller) {
|
|
10366
|
+
pending += decoder.decode(chunk, { stream: true });
|
|
10367
|
+
let out = "";
|
|
10368
|
+
for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
|
|
10369
|
+
const end = match.index + match[0].length;
|
|
10370
|
+
const block = pending.slice(0, end);
|
|
10371
|
+
pending = pending.slice(end);
|
|
10372
|
+
if (!isReceiptBlock(block)) out += block;
|
|
10373
|
+
}
|
|
10374
|
+
if (out) controller.enqueue(encoder.encode(out));
|
|
10375
|
+
},
|
|
10376
|
+
flush(controller) {
|
|
10377
|
+
const rest = pending + decoder.decode();
|
|
10378
|
+
if (rest && !isReceiptBlock(rest)) controller.enqueue(encoder.encode(rest));
|
|
10379
|
+
}
|
|
10380
|
+
})
|
|
10381
|
+
);
|
|
10382
|
+
}
|
|
10383
|
+
async function readReceiptEvent(body) {
|
|
10384
|
+
const reader = body.getReader();
|
|
10385
|
+
const decoder = new TextDecoder();
|
|
10386
|
+
let pending = "";
|
|
10387
|
+
try {
|
|
10388
|
+
for (; ; ) {
|
|
10389
|
+
const { done, value } = await reader.read();
|
|
10390
|
+
if (done) return void 0;
|
|
10391
|
+
pending += decoder.decode(value, { stream: true });
|
|
10392
|
+
for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
|
|
10393
|
+
const end = match.index + match[0].length;
|
|
10394
|
+
const block = pending.slice(0, end);
|
|
10395
|
+
pending = pending.slice(end);
|
|
10396
|
+
if (isReceiptBlock(block)) {
|
|
10397
|
+
void reader.cancel().catch(() => void 0);
|
|
10398
|
+
return parseReceiptBlock(block);
|
|
10399
|
+
}
|
|
10400
|
+
}
|
|
10401
|
+
}
|
|
10402
|
+
} catch {
|
|
10403
|
+
return void 0;
|
|
10404
|
+
} finally {
|
|
10405
|
+
try {
|
|
10406
|
+
reader.releaseLock();
|
|
10407
|
+
} catch {
|
|
10408
|
+
}
|
|
10409
|
+
}
|
|
10410
|
+
}
|
|
10411
|
+
async function lookupReceipt(apiUrl, paymentHeader, opts = {}) {
|
|
10412
|
+
const doFetch = opts.fetch ?? fetch;
|
|
10413
|
+
const attempts = opts.attempts ?? 8;
|
|
10414
|
+
const delayMs = opts.delayMs ?? 2e3;
|
|
10415
|
+
const sleep4 = opts.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
|
|
10416
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
10417
|
+
if (attempt > 0) await sleep4(Math.min(delayMs * 2 ** (attempt - 1), 15e3));
|
|
10418
|
+
let answer;
|
|
10419
|
+
try {
|
|
10420
|
+
const res = await doFetch(`${apiUrl}/v1/batch/receipt`, {
|
|
10421
|
+
method: "POST",
|
|
10422
|
+
headers: { "Content-Type": "application/json" },
|
|
10423
|
+
body: JSON.stringify({ paymentHeader })
|
|
10424
|
+
});
|
|
10425
|
+
if (res.status >= 500) continue;
|
|
10426
|
+
if (!res.ok) return void 0;
|
|
10427
|
+
answer = await res.json();
|
|
10428
|
+
} catch {
|
|
10429
|
+
continue;
|
|
10430
|
+
}
|
|
10431
|
+
if (answer?.status !== "pending") return answer;
|
|
10432
|
+
}
|
|
10433
|
+
return void 0;
|
|
10434
|
+
}
|
|
10435
|
+
function isEventStream(response) {
|
|
10436
|
+
return (response.headers.get("content-type") ?? "").includes("text/event-stream");
|
|
10437
|
+
}
|
|
10438
|
+
|
|
10342
10439
|
// src/solana-batch.ts
|
|
10343
10440
|
import { AsyncLocalStorage } from "async_hooks";
|
|
10344
10441
|
import { randomUUID } from "crypto";
|
|
@@ -13401,6 +13498,7 @@ var SolanaLLMClient = class {
|
|
|
13401
13498
|
* @returns a response whose body has not been read.
|
|
13402
13499
|
*/
|
|
13403
13500
|
async openPaidStream(url, requestBody) {
|
|
13501
|
+
const closesAtStart = await this.batchPayer?.closeFence();
|
|
13404
13502
|
for (let staleRetries = 0; ; ) {
|
|
13405
13503
|
const response = await this.fetchWithTimeout(url, {
|
|
13406
13504
|
method: "POST",
|
|
@@ -13418,11 +13516,15 @@ var SolanaLLMClient = class {
|
|
|
13418
13516
|
throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
|
|
13419
13517
|
}
|
|
13420
13518
|
try {
|
|
13421
|
-
|
|
13422
|
-
|
|
13423
|
-
response,
|
|
13424
|
-
|
|
13425
|
-
|
|
13519
|
+
let exactPayment;
|
|
13520
|
+
if (this.batchPayer && staleRetries === 0) {
|
|
13521
|
+
const batch = await this.openBatchStream(url, requestBody, await this.readPaymentRequired(response), closesAtStart);
|
|
13522
|
+
if (batch.kind === "stream") return batch.response;
|
|
13523
|
+
exactPayment = await this.signExactPayment(url, batch.paymentRequired, false);
|
|
13524
|
+
} else {
|
|
13525
|
+
exactPayment = await this.signPaymentFrom402(url, response, staleRetries > 0);
|
|
13526
|
+
}
|
|
13527
|
+
const { paymentPayload, costUsd } = exactPayment;
|
|
13426
13528
|
const paid = await this.fetchWithTimeout(url, {
|
|
13427
13529
|
method: "POST",
|
|
13428
13530
|
headers: {
|
|
@@ -13442,6 +13544,82 @@ var SolanaLLMClient = class {
|
|
|
13442
13544
|
}
|
|
13443
13545
|
}
|
|
13444
13546
|
}
|
|
13547
|
+
/**
|
|
13548
|
+
* Pay a stream with batch-settlement, when the gateway offers it.
|
|
13549
|
+
*
|
|
13550
|
+
* A stream's charge is committed after its headers are sent, so its receipt
|
|
13551
|
+
* cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
|
|
13552
|
+
* buffered call with. The request asks for it as a final SSE event instead
|
|
13553
|
+
* ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
|
|
13554
|
+
* its branch at once, live, with the receipt event taken out; the payer reads
|
|
13555
|
+
* the other branch to that event and is handed the answer with the receipt
|
|
13556
|
+
* restored as its header, so the channel advances exactly as it does for a
|
|
13557
|
+
* buffered call. A stream that ends without the event (cut, failed upstream,
|
|
13558
|
+
* an older gateway) is looked up at `POST /v1/batch/receipt`.
|
|
13559
|
+
*
|
|
13560
|
+
* The payer's branch reads to the receipt even when the caller stops early,
|
|
13561
|
+
* so the connection stays open: the gateway charges for what the model
|
|
13562
|
+
* generates either way, and only an open stream brings its receipt back.
|
|
13563
|
+
*
|
|
13564
|
+
* @returns the caller's stream, or the requirements to pay `exact` against
|
|
13565
|
+
* when batch is unavailable for this call.
|
|
13566
|
+
*/
|
|
13567
|
+
async openBatchStream(url, requestBody, paymentRequired, closesAtStart) {
|
|
13568
|
+
const headers = { "Content-Type": "application/json", "User-Agent": USER_AGENT, [STREAM_RECEIPT_HEADER]: "1" };
|
|
13569
|
+
let handOff;
|
|
13570
|
+
const handedOff = new Promise((resolve2) => {
|
|
13571
|
+
handOff = resolve2;
|
|
13572
|
+
});
|
|
13573
|
+
const attempt = this.batchPayer.pay(
|
|
13574
|
+
paymentRequired,
|
|
13575
|
+
async (paymentHeaders) => {
|
|
13576
|
+
const answer = await this.fetchWithTimeout(url, { method: "POST", headers: { ...headers, ...paymentHeaders }, body: requestBody });
|
|
13577
|
+
if (!answer.ok || !answer.body || !isEventStream(answer)) return answer;
|
|
13578
|
+
const [forCaller, forPayer] = answer.body.tee();
|
|
13579
|
+
handOff(new Response(withoutReceiptEvent(forCaller), { status: answer.status, statusText: answer.statusText, headers: answer.headers }));
|
|
13580
|
+
let receipt = (await readReceiptEvent(forPayer))?.paymentResponse;
|
|
13581
|
+
const signed = paymentHeaders["PAYMENT-SIGNATURE"];
|
|
13582
|
+
if (receipt === void 0 && signed) receipt = (await lookupReceipt(this.apiUrl, signed))?.payment_response;
|
|
13583
|
+
const settled2 = new Headers(answer.headers);
|
|
13584
|
+
if (receipt) settled2.set("PAYMENT-RESPONSE", receipt);
|
|
13585
|
+
return new Response(null, { status: answer.status, statusText: answer.statusText, headers: settled2 });
|
|
13586
|
+
},
|
|
13587
|
+
// A fresh, unpaid challenge after a 429 wait, as chatCompletion sends.
|
|
13588
|
+
async () => {
|
|
13589
|
+
const challenge = await this.sendUnpaid(url, { method: "POST", headers, body: requestBody });
|
|
13590
|
+
if (challenge.status === 402) {
|
|
13591
|
+
try {
|
|
13592
|
+
return { kind: "challenge", paymentRequired: await this.readPaymentRequired(challenge) };
|
|
13593
|
+
} catch (error) {
|
|
13594
|
+
throw withDisposition(error, "unpaid");
|
|
13595
|
+
}
|
|
13596
|
+
}
|
|
13597
|
+
if (challenge.ok) return { kind: "served", response: challenge };
|
|
13598
|
+
throw await unpaidApiError(challenge);
|
|
13599
|
+
},
|
|
13600
|
+
closesAtStart
|
|
13601
|
+
);
|
|
13602
|
+
const settled = attempt.then(
|
|
13603
|
+
(outcome2) => ({ outcome: outcome2 }),
|
|
13604
|
+
(error) => ({ error })
|
|
13605
|
+
);
|
|
13606
|
+
const first = await Promise.race([handedOff.then((response) => ({ response })), settled]);
|
|
13607
|
+
if ("response" in first) {
|
|
13608
|
+
void settled.then((result) => {
|
|
13609
|
+
if ("outcome" in result && result.outcome.kind === "paid") this.recordSettlement(result.outcome.chargedUsd, result.outcome.response);
|
|
13610
|
+
});
|
|
13611
|
+
return { kind: "stream", response: first.response };
|
|
13612
|
+
}
|
|
13613
|
+
if ("error" in first) throw first.error;
|
|
13614
|
+
const outcome = first.outcome;
|
|
13615
|
+
if (outcome.kind === "paid") {
|
|
13616
|
+
this.recordSettlement(outcome.chargedUsd, outcome.response);
|
|
13617
|
+
return { kind: "stream", response: outcome.response };
|
|
13618
|
+
}
|
|
13619
|
+
if (outcome.kind === "served") return { kind: "stream", response: outcome.response };
|
|
13620
|
+
if (outcome.kind === "failed") throw outcome.error;
|
|
13621
|
+
return { kind: "exact", paymentRequired: outcome.paymentRequired ?? paymentRequired };
|
|
13622
|
+
}
|
|
13445
13623
|
/**
|
|
13446
13624
|
* Resolve an endpoint path against this client's API root.
|
|
13447
13625
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blockrun/llm",
|
|
3
|
-
"version": "4.1
|
|
3
|
+
"version": "4.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "TypeScript SDK for BlockRun - every frontier model behind one OpenAI-compatible client. Pay with a BlockRun API key or per-call in USDC. Smart routing picks the cheapest capable model. No rate limits.",
|
|
6
6
|
"main": "dist/index.cjs",
|