@latens/sdk 0.0.0-stage → 1.4.0

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/src/client.ts ADDED
@@ -0,0 +1,342 @@
1
+ import { estimateLlmVramRequirements, rankOffersByTco } from "./sizing.js";
2
+ import { isValidEvmAddress } from "./standing.js";
3
+ import type {
4
+ AgentCalculateInput,
5
+ AgentOffersQuery,
6
+ AgentOffersSort,
7
+ GpuPriceHistoryQuery,
8
+ GpuPriceHistoryResponse,
9
+ HolderTierId,
10
+ LlmSizingInput,
11
+ LlmSizingResult,
12
+ NormalizedGpuOffer,
13
+ OfferTcoComparisonOptions,
14
+ OfferTcoComparisonResult,
15
+ TokenStandingResponse,
16
+ X402ExecutionReceipt,
17
+ X402QuoteChallenge,
18
+ X402QuoteRequestInput,
19
+ } from "./types.js";
20
+
21
+ export interface LatensClientOptions {
22
+ baseUrl?: string;
23
+ walletAddress?: string;
24
+ fetchImpl?: typeof fetch;
25
+ timeoutMs?: number;
26
+ }
27
+
28
+ export class LatensReadOnlyClient {
29
+ private readonly baseUrl: string;
30
+ private readonly walletAddress: string | null;
31
+ private readonly fetcher: typeof fetch;
32
+ private readonly timeoutMs: number;
33
+
34
+ constructor(options?: LatensClientOptions) {
35
+ this.baseUrl = (options?.baseUrl ?? "https://latens.trade").replace(/\/+$/, "");
36
+ const candidate = options?.walletAddress?.trim() ?? "";
37
+ this.walletAddress = isValidEvmAddress(candidate) ? candidate : null;
38
+ this.fetcher = options?.fetchImpl ?? fetch;
39
+ this.timeoutMs = options?.timeoutMs ?? 15_000;
40
+ }
41
+
42
+ async listOffers(query: AgentOffersQuery = {}): Promise<{
43
+ count: number;
44
+ total: number;
45
+ offset: number;
46
+ limit: number;
47
+ sort: AgentOffersSort;
48
+ next_offset: number | null;
49
+ offers: NormalizedGpuOffer[];
50
+ data: NormalizedGpuOffer[];
51
+ last_synced_at?: string | null;
52
+ }> {
53
+ const params = new URLSearchParams();
54
+ const resolvedModel = query.model ?? query.gpu_model;
55
+ const resolvedMaxPrice = query.max_price_per_gpu_usd ?? query.max_hourly_usd;
56
+
57
+ if (resolvedModel) params.set("model", resolvedModel);
58
+ if (query.provider) params.set("provider", query.provider);
59
+ if (query.category) params.set("category", query.category);
60
+ if (query.min_vram_gb !== undefined) params.set("min_vram_gb", String(query.min_vram_gb));
61
+ if (resolvedMaxPrice !== undefined) {
62
+ params.set("max_price_per_gpu_usd", String(resolvedMaxPrice));
63
+ }
64
+ if (query.gpu_count !== undefined) params.set("gpu_count", String(query.gpu_count));
65
+ if (query.region) params.set("region", query.region);
66
+ if (query.available_only !== undefined) {
67
+ params.set("available_only", query.available_only ? "true" : "false");
68
+ }
69
+ if (query.sort) params.set("sort", query.sort);
70
+ if (query.offset !== undefined) params.set("offset", String(query.offset));
71
+ if (query.limit !== undefined) params.set("limit", String(query.limit));
72
+
73
+ const qs = params.toString();
74
+ const raw = await this.requestJson<{
75
+ count: number;
76
+ total?: number;
77
+ offset?: number;
78
+ limit?: number;
79
+ sort?: AgentOffersSort;
80
+ next_offset?: number | null;
81
+ data?: NormalizedGpuOffer[];
82
+ offers?: NormalizedGpuOffer[];
83
+ last_synced_at?: string | null;
84
+ }>(`/api/v1/agent/offers${qs ? `?${qs}` : ""}`);
85
+
86
+ const list = raw.data ?? raw.offers ?? [];
87
+ const offset = raw.offset ?? query.offset ?? 0;
88
+ const limit = raw.limit ?? query.limit ?? 50;
89
+ const total = raw.total ?? list.length;
90
+ const nextOffset =
91
+ raw.next_offset !== undefined
92
+ ? raw.next_offset
93
+ : offset + list.length < total
94
+ ? offset + list.length
95
+ : null;
96
+
97
+ return {
98
+ count: raw.count ?? list.length,
99
+ total,
100
+ offset,
101
+ limit,
102
+ sort: raw.sort ?? query.sort ?? "price_asc",
103
+ next_offset: nextOffset,
104
+ offers: list,
105
+ data: list,
106
+ last_synced_at: raw.last_synced_at,
107
+ };
108
+ }
109
+
110
+ async listModels(): Promise<{
111
+ count: number;
112
+ models: Array<{
113
+ gpu_model: string;
114
+ manufacturer: string;
115
+ available_offer_count: number;
116
+ min_price_per_gpu_usd: number;
117
+ median_price_per_gpu_usd: number;
118
+ vram_per_gpu_gb: number;
119
+ providers: string[];
120
+ }>;
121
+ }> {
122
+ const raw = await this.requestJson<{
123
+ count: number;
124
+ data?: Array<{
125
+ gpu_model: string;
126
+ manufacturer: string;
127
+ available_offer_count: number;
128
+ min_price_per_gpu_usd: number;
129
+ median_price_per_gpu_usd: number;
130
+ vram_per_gpu_gb: number;
131
+ providers: string[];
132
+ }>;
133
+ models?: Array<{
134
+ gpu_model: string;
135
+ manufacturer: string;
136
+ available_offer_count: number;
137
+ min_price_per_gpu_usd: number;
138
+ median_price_per_gpu_usd: number;
139
+ vram_per_gpu_gb: number;
140
+ providers: string[];
141
+ }>;
142
+ }>("/api/v1/agent/models");
143
+
144
+ const models = raw.data ?? raw.models ?? [];
145
+ return { count: raw.count ?? models.length, models };
146
+ }
147
+
148
+ async getPriceHistory(
149
+ query: GpuPriceHistoryQuery
150
+ ): Promise<GpuPriceHistoryResponse> {
151
+ const model = query.model?.trim() ?? "";
152
+ if (!model) {
153
+ throw new TypeError("model is required for getPriceHistory()");
154
+ }
155
+ const params = new URLSearchParams();
156
+ params.set("model", model);
157
+ if (query.window) params.set("window", query.window);
158
+ if (query.interval) params.set("interval", query.interval);
159
+ if (query.category) params.set("category", query.category);
160
+
161
+ return this.requestJson<GpuPriceHistoryResponse>(
162
+ `/api/v1/agent/models/history?${params.toString()}`
163
+ );
164
+ }
165
+
166
+ async calculateCost(input: AgentCalculateInput): Promise<{
167
+ read_only: boolean;
168
+ deterministic: boolean;
169
+ data: Record<string, unknown>;
170
+ }> {
171
+ return this.requestJson("/api/v1/agent/calculate", {
172
+ method: "POST",
173
+ body: input,
174
+ });
175
+ }
176
+
177
+ async getProviderStatus(): Promise<{
178
+ caller_holder_tier?: HolderTierId;
179
+ ecosystem_token?: {
180
+ ticker: string;
181
+ contract_address: string;
182
+ decimals: number;
183
+ total_supply: number;
184
+ wallet_header: string;
185
+ };
186
+ summary: {
187
+ totalOffers: number;
188
+ filteredOffers?: number;
189
+ connectedProviders: number;
190
+ totalProviders: number;
191
+ lastSyncedAt: string | null;
192
+ };
193
+ providers: Array<{
194
+ provider: string;
195
+ status: string;
196
+ offerCount?: number;
197
+ offer_count?: number;
198
+ }>;
199
+ }> {
200
+ return this.requestJson("/api/v1/agent/status");
201
+ }
202
+
203
+ async getTokenStanding(
204
+ address?: string,
205
+ options?: { refresh?: boolean }
206
+ ): Promise<TokenStandingResponse> {
207
+ const target = (address ?? this.walletAddress ?? "").trim();
208
+ const params = new URLSearchParams();
209
+ if (target) {
210
+ if (!isValidEvmAddress(target)) {
211
+ throw new TypeError("Invalid 42-character EVM wallet address.");
212
+ }
213
+ params.set("address", target);
214
+ }
215
+ if (options?.refresh) {
216
+ params.set("refresh", "1");
217
+ }
218
+ const qs = params.toString();
219
+ return this.requestJson(`/api/token/standing${qs ? `?${qs}` : ""}`);
220
+ }
221
+
222
+ async compareLiveOffersForWorkload(params: {
223
+ workload: LlmSizingInput;
224
+ comparison: OfferTcoComparisonOptions;
225
+ query?: AgentOffersQuery;
226
+ }): Promise<{
227
+ sizing: LlmSizingResult;
228
+ comparison: OfferTcoComparisonResult;
229
+ }> {
230
+ const sizing = estimateLlmVramRequirements(params.workload);
231
+ const { offers } = await this.listOffers({
232
+ available_only: params.comparison.availableOnly ?? true,
233
+ limit: params.query?.limit ?? 100,
234
+ ...params.query,
235
+ });
236
+ const comparison = rankOffersByTco(offers, {
237
+ ...params.comparison,
238
+ minTotalVramGb:
239
+ params.comparison.minTotalVramGb ?? sizing.recommendedVramGb,
240
+ });
241
+ return { sizing, comparison };
242
+ }
243
+
244
+ private async requestJson<T>(
245
+ pathname: string,
246
+ init?: {
247
+ method?: "GET" | "POST" | "DELETE";
248
+ body?: unknown;
249
+ headers?: Record<string, string>;
250
+ allowStatuses?: number[];
251
+ }
252
+ ): Promise<T> {
253
+ const controller = new AbortController();
254
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
255
+ try {
256
+ const headers: Record<string, string> = {
257
+ Accept: "application/json",
258
+ ...(init?.headers ?? {}),
259
+ };
260
+ if (this.walletAddress && !headers["X-Latens-Wallet"]) {
261
+ headers["X-Latens-Wallet"] = this.walletAddress;
262
+ }
263
+ if (init?.body !== undefined) {
264
+ headers["Content-Type"] = "application/json";
265
+ }
266
+
267
+ const res = await this.fetcher(`${this.baseUrl}${pathname}`, {
268
+ method: init?.method ?? "GET",
269
+ headers,
270
+ body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,
271
+ signal: controller.signal,
272
+ });
273
+ if (!res.ok && !(init?.allowStatuses ?? []).includes(res.status)) {
274
+ throw new Error(`LATENS API HTTP ${res.status} on ${pathname}`);
275
+ }
276
+ return (await res.json()) as T;
277
+ } finally {
278
+ clearTimeout(timer);
279
+ }
280
+ }
281
+
282
+ async requestX402Quote(input: X402QuoteRequestInput): Promise<X402QuoteChallenge> {
283
+ return this.requestJson<X402QuoteChallenge>("/api/v1/agent/execute", {
284
+ method: "POST",
285
+ body: {
286
+ walletAddress: input.walletAddress ?? this.walletAddress ?? undefined,
287
+ ...input,
288
+ },
289
+ allowStatuses: [402],
290
+ });
291
+ }
292
+
293
+ async settleX402Execution(params: {
294
+ quoteId: string;
295
+ txHash: string;
296
+ payer?: string;
297
+ }): Promise<X402ExecutionReceipt> {
298
+ const encoded = Buffer.from(
299
+ JSON.stringify({
300
+ quoteId: params.quoteId,
301
+ txHash: params.txHash,
302
+ payer: params.payer ?? this.walletAddress ?? undefined,
303
+ }),
304
+ "utf8"
305
+ ).toString("base64");
306
+
307
+ return this.requestJson<X402ExecutionReceipt>("/api/v1/agent/execute", {
308
+ method: "POST",
309
+ headers: {
310
+ "X-Payment": encoded,
311
+ ...(params.payer ? { "X-Latens-Wallet": params.payer } : {}),
312
+ },
313
+ body: {},
314
+ });
315
+ }
316
+
317
+ async getAgentRentalStatus(
318
+ rentalId: string,
319
+ rentalAccessToken: string
320
+ ): Promise<{ object: string; rental: Record<string, unknown> }> {
321
+ return this.requestJson(`/api/v1/agent/rentals/${encodeURIComponent(rentalId)}`, {
322
+ method: "GET",
323
+ headers: {
324
+ Authorization: `Bearer ${rentalAccessToken.replace(/^Bearer\s+/i, "")}`,
325
+ },
326
+ });
327
+ }
328
+
329
+ async terminateAgentRental(
330
+ rentalId: string,
331
+ rentalAccessToken: string
332
+ ): Promise<{ object: string; rental: Record<string, unknown> }> {
333
+ return this.requestJson(`/api/v1/agent/rentals/${encodeURIComponent(rentalId)}`, {
334
+ method: "DELETE",
335
+ headers: {
336
+ Authorization: `Bearer ${rentalAccessToken.replace(/^Bearer\s+/i, "")}`,
337
+ },
338
+ });
339
+ }
340
+ }
341
+
342
+ export const LatensAgentClient = LatensReadOnlyClient;
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./types.js";
2
+ export * from "./normalizer.js";
3
+ export * from "./calculator.js";
4
+ export * from "./standing.js";
5
+ export * from "./sizing.js";
6
+ export * from "./client.js";
@@ -0,0 +1,43 @@
1
+ const MODEL_PATTERNS: Array<[RegExp, string]> = [
2
+ [/\bb200\b/i, "B200"],
3
+ [/\bgh200\b/i, "GH200"],
4
+ [/\bh200\b/i, "H200"],
5
+ [/\bh100\b.*\bsxm\b/i, "H100 SXM"],
6
+ [/\bh100\b.*\bpcie\b/i, "H100 PCIe"],
7
+ [/\bh100\b.*\bnvl\b/i, "H100 NVL"],
8
+ [/\bh100\b/i, "H100 SXM"],
9
+ [/\ba100\b.*\bsxm\b/i, "A100 SXM"],
10
+ [/\ba100\b.*\bpcie\b/i, "A100 PCIe"],
11
+ [/\ba100\b/i, "A100 SXM"],
12
+ [/\bmi300x\b/i, "MI300X"],
13
+ [/\bl40s\b/i, "L40S"],
14
+ [/\bl40\b/i, "L40"],
15
+ [/\brtx\s*6000\s*ada\b/i, "RTX 6000 Ada"],
16
+ [/\brtx\s*a6000\b/i, "RTX A6000"],
17
+ [/\brtx\s*5090\b/i, "RTX 5090"],
18
+ [/\brtx\s*4090\b/i, "RTX 4090"],
19
+ [/\brtx\s*3090\b/i, "RTX 3090"],
20
+ [/\ba40\b/i, "A40"],
21
+ [/\bl4\b/i, "L4"],
22
+ ];
23
+
24
+ export function normalizeGpuModelName(rawName: string): string {
25
+ const cleaned = rawName
26
+ .replace(/^NVIDIA[\s_-]+/i, "")
27
+ .replace(/^AMD[\s_-]+/i, "")
28
+ .replace(/_/g, " ")
29
+ .replace(/\s+/g, " ")
30
+ .trim();
31
+
32
+ for (const [pattern, canonical] of MODEL_PATTERNS) {
33
+ if (pattern.test(cleaned)) {
34
+ return canonical;
35
+ }
36
+ }
37
+ return cleaned || "Unknown GPU";
38
+ }
39
+
40
+ export function roundUsd(value: number, decimals = 4): number {
41
+ const factor = 10 ** decimals;
42
+ return Math.round((value + Number.EPSILON) * factor) / factor;
43
+ }