@hilbras/sdk 3.5.0 → 3.6.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/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  <p align="center">
2
- <img src="https://img.shields.io/badge/version-3.5.0-blue" alt="version">
2
+ <img src="https://img.shields.io/badge/version-3.6.0-blue" alt="version">
3
3
  <img src="https://img.shields.io/badge/license-MIT-green" alt="license">
4
4
  <img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
5
5
  <img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
6
- <img src="https://img.shields.io/badge/tests-1932%20passing-brightgreen" alt="tests">
6
+ <img src="https://img.shields.io/badge/tests-1939%20passing-brightgreen" alt="tests">
7
7
  <img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
8
8
  </p>
9
9
 
@@ -62,7 +62,7 @@ npm install @hilbras/sdk
62
62
  ### React (optional)
63
63
 
64
64
  ```bash
65
- npm install @hilbras/react
65
+ npm install @hilbras/sdk
66
66
  ```
67
67
 
68
68
  ## Quick start
@@ -372,10 +372,17 @@ console.log(`Winner: ${result.winner.name}`);
372
372
 
373
373
  ## React Hooks
374
374
 
375
- First-class React integration via `@hilbras/react`. Zero runtime dependencies beyond React itself.
375
+ First-class React integration. Zero runtime dependencies beyond React itself.
376
+
377
+ Two React subpaths, because they are different designs:
378
+
379
+ | Subpath | Transport | Use when |
380
+ |---------|-----------|----------|
381
+ | `@hilbras/sdk/react` | `fetch(api)` against your route | **Default.** Credentials stay on your server. |
382
+ | `@hilbras/sdk/react-client` | `client.stream()` in the browser | Trusted/internal apps only. A key passed here is bundled into client JS. |
376
383
 
377
384
  ```bash
378
- npm install @hilbras/react
385
+ npm install @hilbras/sdk
379
386
  ```
380
387
 
381
388
  ### useChat — Streaming chat
@@ -387,7 +394,7 @@ an API key in browser props or a client component.
387
394
  ```tsx
388
395
  // app/page.tsx (server component)
389
396
  import { HilbrasClient } from "@hilbras/sdk";
390
- import { HilbrasProvider } from "@hilbras/react";
397
+ import { HilbrasProvider } from "@hilbras/sdk/react-client";
391
398
  import { Chat } from "./chat";
392
399
 
393
400
  export default function Page() {
@@ -399,7 +406,7 @@ export default function Page() {
399
406
 
400
407
  ```tsx
401
408
  // app/chat.tsx (client component)
402
- import { useChat } from "@hilbras/react";
409
+ import { useChat } from "@hilbras/sdk/react-client";
403
410
 
404
411
  export function Chat() {
405
412
  const { messages, input, setInput, handleSubmit, isLoading, stop } = useChat({
@@ -424,7 +431,7 @@ export function Chat() {
424
431
  ### useCompletion — Text completion
425
432
 
426
433
  ```tsx
427
- import { useCompletion } from "@hilbras/react";
434
+ import { useCompletion } from "@hilbras/sdk/react-client";
428
435
 
429
436
  function AutoComplete() {
430
437
  const { completion, prompt, setPrompt, complete, isLoading } = useCompletion({
@@ -446,7 +453,7 @@ function AutoComplete() {
446
453
  ### useCost — Real-time cost tracking
447
454
 
448
455
  ```tsx
449
- import { useCost } from "@hilbras/react";
456
+ import { useCost } from "@hilbras/sdk/react-client";
450
457
 
451
458
  function CostDisplay() {
452
459
  const { snapshot, isBudgetLow } = useCost();
@@ -500,7 +507,7 @@ import { CostAlertMonitor } from "@hilbras/sdk"; // Cost alerts
500
507
  import { runABTest } from "@hilbras/sdk"; // A/B testing
501
508
 
502
509
  // React package
503
- import { useChat, useCompletion, useCost, HilbrasProvider } from "@hilbras/react";
510
+ import { useChat, useCompletion, useCost, HilbrasProvider } from "@hilbras/sdk/react-client";
504
511
 
505
512
  // Framework subpaths from the root package
506
513
  import { useChat } from "@hilbras/sdk/vue";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @hilbras/sdk — React client-mode hooks
3
+ *
4
+ * Subpath: `@hilbras/sdk/react-client`
5
+ *
6
+ * These hooks hold a `HilbrasClient` and call `client.stream()` directly, so
7
+ * inference runs **in the browser**. They live under their own subpath rather
8
+ * than joining `@hilbras/sdk/react` for two reasons:
9
+ *
10
+ * 1. Name collision. `useChat` and `useCompletion` are exported by both, with
11
+ * different signatures and different transports. Merging them into one
12
+ * entry would make the import ambiguous.
13
+ * 2. Different design. `@hilbras/sdk/react`'s `useChat` takes an `api` route and
14
+ * calls `fetch(api)` — credentials stay on your server. These take a
15
+ * `provider` and `model` and reach the provider from the browser.
16
+ *
17
+ * ## Prefer the route-based hooks
18
+ *
19
+ * A client built from `config` with an API key will bundle that key into your
20
+ * client-side JavaScript, where anyone can read it. For a public app, use
21
+ * `@hilbras/sdk/react` and point `api` at a route handler from
22
+ * `@hilbras/sdk/nextjs/api` — the key never leaves the server.
23
+ *
24
+ * These hooks remain the supported path for a **trusted, authenticated
25
+ * environment** — an internal tool behind SSO, an Electron app, or a server
26
+ * component tree where the "client" is not really a browser.
27
+ */
28
+ export { HilbrasProvider, useHilbrasClient } from "./provider.js";
29
+ export type { HilbrasProviderProps } from "./provider.js";
30
+ export { useChat } from "./use-chat.js";
31
+ export type { ChatMessage, UseChatOptions, UseChatReturn } from "./use-chat.js";
32
+ export { useCompletion } from "./use-completion.js";
33
+ export type { UseCompletionOptions, UseCompletionReturn } from "./use-completion.js";
34
+ export { useCost } from "./use-cost.js";
35
+ export type { CostSnapshot, UseCostOptions, UseCostReturn } from "./use-cost.js";
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @hilbras/sdk — React client-mode hooks
3
+ *
4
+ * Subpath: `@hilbras/sdk/react-client`
5
+ *
6
+ * These hooks hold a `HilbrasClient` and call `client.stream()` directly, so
7
+ * inference runs **in the browser**. They live under their own subpath rather
8
+ * than joining `@hilbras/sdk/react` for two reasons:
9
+ *
10
+ * 1. Name collision. `useChat` and `useCompletion` are exported by both, with
11
+ * different signatures and different transports. Merging them into one
12
+ * entry would make the import ambiguous.
13
+ * 2. Different design. `@hilbras/sdk/react`'s `useChat` takes an `api` route and
14
+ * calls `fetch(api)` — credentials stay on your server. These take a
15
+ * `provider` and `model` and reach the provider from the browser.
16
+ *
17
+ * ## Prefer the route-based hooks
18
+ *
19
+ * A client built from `config` with an API key will bundle that key into your
20
+ * client-side JavaScript, where anyone can read it. For a public app, use
21
+ * `@hilbras/sdk/react` and point `api` at a route handler from
22
+ * `@hilbras/sdk/nextjs/api` — the key never leaves the server.
23
+ *
24
+ * These hooks remain the supported path for a **trusted, authenticated
25
+ * environment** — an internal tool behind SSO, an Electron app, or a server
26
+ * component tree where the "client" is not really a browser.
27
+ */
28
+ export { HilbrasProvider, useHilbrasClient } from "./provider.js";
29
+ export { useChat } from "./use-chat.js";
30
+ export { useCompletion } from "./use-completion.js";
31
+ export { useCost } from "./use-cost.js";
@@ -0,0 +1,45 @@
1
+ import { type ReactNode } from "react";
2
+ import { HilbrasClient, type HilbrasClientConfig } from "../../client/client.js";
3
+ interface HilbrasContextValue {
4
+ client: HilbrasClient;
5
+ }
6
+ export interface HilbrasProviderProps {
7
+ children: ReactNode;
8
+ /**
9
+ * HilbrasClient config — creates a new client if not provided.
10
+ *
11
+ * @warning Passing an API key here bundles it into your client-side
12
+ * JavaScript, where anyone can read it. In a browser this is a public secret.
13
+ * Prefer passing a server-created `client` down from a Server Component, or
14
+ * use the route-based hooks in `@hilbras/sdk/react` instead.
15
+ */
16
+ config?: HilbrasClientConfig;
17
+ /**
18
+ * Pre-existing client instance (overrides config).
19
+ *
20
+ * Build this on the server and pass it in, so no credential is serialised
21
+ * into the browser bundle.
22
+ */
23
+ client?: HilbrasClient;
24
+ }
25
+ /**
26
+ * HilbrasProvider — wraps your app and provides a shared HilbrasClient.
27
+ *
28
+ * @warning The client this provides calls providers **from the browser**. For a
29
+ * public app, use `@hilbras/sdk/react`'s route-based `useChat` with
30
+ * `createChatHandler` from `@hilbras/sdk/nextjs` so the key stays on your
31
+ * server. See `@hilbras/sdk/react-client` for when this is appropriate.
32
+ *
33
+ * @example
34
+ * ```tsx
35
+ * <HilbrasProvider client={client}>
36
+ * <App />
37
+ * </HilbrasProvider>
38
+ * ```
39
+ */
40
+ export declare function HilbrasProvider({ children, config, client: existingClient }: HilbrasProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<HilbrasContextValue | null>>;
41
+ /**
42
+ * Access the shared HilbrasClient from the nearest HilbrasProvider.
43
+ */
44
+ export declare function useHilbrasClient(): HilbrasClient;
45
+ export {};
@@ -0,0 +1,40 @@
1
+ "use client";
2
+ import { createContext, createElement, useContext, useMemo } from "react";
3
+ import { HilbrasClient } from "../../client/client.js";
4
+ const HilbrasContext = createContext(null);
5
+ /**
6
+ * HilbrasProvider — wraps your app and provides a shared HilbrasClient.
7
+ *
8
+ * @warning The client this provides calls providers **from the browser**. For a
9
+ * public app, use `@hilbras/sdk/react`'s route-based `useChat` with
10
+ * `createChatHandler` from `@hilbras/sdk/nextjs` so the key stays on your
11
+ * server. See `@hilbras/sdk/react-client` for when this is appropriate.
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * <HilbrasProvider client={client}>
16
+ * <App />
17
+ * </HilbrasProvider>
18
+ * ```
19
+ */
20
+ export function HilbrasProvider({ children, config, client: existingClient }) {
21
+ const value = useMemo(() => {
22
+ const client = existingClient ?? new HilbrasClient(config);
23
+ return { client };
24
+ }, [existingClient, config]);
25
+ // `createElement` rather than JSX: the SDK ships no `.tsx` and its tsconfig has
26
+ // no `--jsx`, matching how `src/frameworks/react/generative-ui.ts` builds
27
+ // elements. Enabling JSX for one file would change the build for all of src.
28
+ return createElement(HilbrasContext.Provider, { value }, children);
29
+ }
30
+ /**
31
+ * Access the shared HilbrasClient from the nearest HilbrasProvider.
32
+ */
33
+ export function useHilbrasClient() {
34
+ const ctx = useContext(HilbrasContext);
35
+ if (!ctx) {
36
+ throw new Error("useHilbrasClient must be used within a <HilbrasProvider>. " +
37
+ "Wrap your app with <HilbrasProvider config={...}> or pass a client directly.");
38
+ }
39
+ return ctx.client;
40
+ }
@@ -0,0 +1,85 @@
1
+ export interface ChatMessage {
2
+ id: string;
3
+ role: "user" | "assistant" | "system";
4
+ content: string;
5
+ timestamp: number;
6
+ provider?: string;
7
+ model?: string;
8
+ tokens?: {
9
+ input: number;
10
+ output: number;
11
+ total: number;
12
+ };
13
+ cost?: number;
14
+ }
15
+ export interface UseChatOptions {
16
+ /** Provider name */
17
+ provider: string;
18
+ /** Model ID */
19
+ model: string;
20
+ /** System prompt */
21
+ systemPrompt?: string;
22
+ /** Initial messages */
23
+ initialMessages?: ChatMessage[];
24
+ /** Max messages to keep in context (older messages trimmed) */
25
+ maxContextMessages?: number;
26
+ /** Called on each text chunk during streaming */
27
+ onChunk?: (chunk: {
28
+ text: string;
29
+ accumulated: string;
30
+ }) => void;
31
+ /** Called when a message completes */
32
+ onComplete?: (message: ChatMessage) => void;
33
+ /** Called on error */
34
+ onError?: (error: Error) => void;
35
+ }
36
+ export interface UseChatReturn {
37
+ /** Chat messages */
38
+ messages: ChatMessage[];
39
+ /** Current input value */
40
+ input: string;
41
+ /** Set input value */
42
+ setInput: (value: string) => void;
43
+ /** Send a message (uses current input) */
44
+ handleSubmit: (e?: React.FormEvent) => Promise<void>;
45
+ /** Send an arbitrary message */
46
+ sendMessage: (content: string) => Promise<void>;
47
+ /** Whether a response is being generated */
48
+ isLoading: boolean;
49
+ /** Whether streaming is in progress */
50
+ isStreaming: boolean;
51
+ /** Current error (if any) */
52
+ error: Error | null;
53
+ /** Abort the current request */
54
+ stop: () => void;
55
+ /** Clear all messages */
56
+ clear: () => void;
57
+ /** Retry the last message */
58
+ retry: () => Promise<void>;
59
+ /** Total tokens used */
60
+ totalTokens: number;
61
+ /** Total cost */
62
+ totalCost: number;
63
+ }
64
+ /**
65
+ * useChat — streaming chat hook for React.
66
+ *
67
+ * @example
68
+ * ```tsx
69
+ * function Chat() {
70
+ * const { messages, input, setInput, handleSubmit, isLoading } = useChat({
71
+ * provider: "openai",
72
+ * model: "gpt-4o",
73
+ * });
74
+ *
75
+ * return (
76
+ * <div>
77
+ * {messages.map(m => <div key={m.id}>{m.content}</div>)}
78
+ * <input value={input} onChange={e => setInput(e.target.value)} />
79
+ * <button onClick={handleSubmit} disabled={isLoading}>Send</button>
80
+ * </div>
81
+ * );
82
+ * }
83
+ * ```
84
+ */
85
+ export declare function useChat(options: UseChatOptions): UseChatReturn;
@@ -0,0 +1,202 @@
1
+ "use client";
2
+ import { useState, useCallback, useRef, useEffect } from "react";
3
+ import { useHilbrasClient } from "./provider.js";
4
+ let _idCounter = 0;
5
+ function nextId() {
6
+ return `msg_${Date.now()}_${++_idCounter}`;
7
+ }
8
+ /**
9
+ * useChat — streaming chat hook for React.
10
+ *
11
+ * @example
12
+ * ```tsx
13
+ * function Chat() {
14
+ * const { messages, input, setInput, handleSubmit, isLoading } = useChat({
15
+ * provider: "openai",
16
+ * model: "gpt-4o",
17
+ * });
18
+ *
19
+ * return (
20
+ * <div>
21
+ * {messages.map(m => <div key={m.id}>{m.content}</div>)}
22
+ * <input value={input} onChange={e => setInput(e.target.value)} />
23
+ * <button onClick={handleSubmit} disabled={isLoading}>Send</button>
24
+ * </div>
25
+ * );
26
+ * }
27
+ * ```
28
+ */
29
+ export function useChat(options) {
30
+ const { provider, model, systemPrompt, initialMessages, maxContextMessages = 50, onChunk, onComplete, onError } = options;
31
+ const client = useHilbrasClient();
32
+ const [messages, setMessages] = useState(initialMessages ?? []);
33
+ const [input, setInput] = useState("");
34
+ const [isLoading, setIsLoading] = useState(false);
35
+ const [isStreaming, setIsStreaming] = useState(false);
36
+ const [error, setError] = useState(null);
37
+ const [totalTokens, setTotalTokens] = useState(0);
38
+ const [totalCost, setTotalCost] = useState(0);
39
+ const abortRef = useRef(null);
40
+ const lastUserMessageRef = useRef("");
41
+ // Cleanup on unmount
42
+ useEffect(() => {
43
+ return () => {
44
+ abortRef.current?.abort();
45
+ };
46
+ }, []);
47
+ const stop = useCallback(() => {
48
+ abortRef.current?.abort();
49
+ abortRef.current = null;
50
+ setIsLoading(false);
51
+ setIsStreaming(false);
52
+ }, []);
53
+ const clear = useCallback(() => {
54
+ stop();
55
+ setMessages([]);
56
+ setError(null);
57
+ setTotalTokens(0);
58
+ setTotalCost(0);
59
+ }, [stop]);
60
+ const sendMessage = useCallback(async (content) => {
61
+ if (!content.trim() || isLoading)
62
+ return;
63
+ const userMessage = {
64
+ id: nextId(),
65
+ role: "user",
66
+ content: content.trim(),
67
+ timestamp: Date.now(),
68
+ };
69
+ lastUserMessageRef.current = content.trim();
70
+ setMessages((prev) => {
71
+ const updated = [...prev, userMessage];
72
+ // Trim context window
73
+ if (updated.length > maxContextMessages + 1) {
74
+ return updated.slice(-maxContextMessages);
75
+ }
76
+ return updated;
77
+ });
78
+ setInput("");
79
+ setIsLoading(true);
80
+ setIsStreaming(true);
81
+ setError(null);
82
+ const controller = new AbortController();
83
+ abortRef.current = controller;
84
+ try {
85
+ // Build message array for the API
86
+ const apiMessages = [];
87
+ if (systemPrompt) {
88
+ apiMessages.push({ role: "system", content: systemPrompt });
89
+ }
90
+ // Add context messages (all except the latest user message)
91
+ const contextMessages = messages.slice(-maxContextMessages);
92
+ for (const msg of contextMessages) {
93
+ apiMessages.push({ role: msg.role, content: msg.content });
94
+ }
95
+ apiMessages.push({ role: "user", content: userMessage.content });
96
+ let assistantContent = "";
97
+ let inputTokens = 0;
98
+ let outputTokens = 0;
99
+ for await (const chunk of client.stream({
100
+ messages: apiMessages,
101
+ model,
102
+ provider,
103
+ signal: controller.signal,
104
+ })) {
105
+ if (chunk.type === "text") {
106
+ assistantContent += chunk.text;
107
+ setMessages((prev) => {
108
+ const updated = [...prev];
109
+ const last = updated[updated.length - 1];
110
+ if (last && last.role === "assistant") {
111
+ updated[updated.length - 1] = { ...last, content: assistantContent };
112
+ }
113
+ else {
114
+ updated.push({
115
+ id: nextId(),
116
+ role: "assistant",
117
+ content: assistantContent,
118
+ timestamp: Date.now(),
119
+ provider,
120
+ model,
121
+ });
122
+ }
123
+ return updated;
124
+ });
125
+ onChunk?.({ text: chunk.text, accumulated: assistantContent });
126
+ }
127
+ if (chunk.type === "usage") {
128
+ inputTokens = chunk.inputTokens ?? 0;
129
+ outputTokens = chunk.outputTokens ?? 0;
130
+ }
131
+ }
132
+ // Finalize message with token counts
133
+ const finalMessage = {
134
+ id: nextId(),
135
+ role: "assistant",
136
+ content: assistantContent,
137
+ timestamp: Date.now(),
138
+ provider,
139
+ model,
140
+ tokens: { input: inputTokens, output: outputTokens, total: inputTokens + outputTokens },
141
+ };
142
+ setMessages((prev) => {
143
+ const updated = [...prev];
144
+ // Replace the streaming message with the final one
145
+ const lastIdx = updated.findIndex((m) => m.role === "assistant" && m.content === assistantContent);
146
+ if (lastIdx >= 0) {
147
+ updated[lastIdx] = finalMessage;
148
+ }
149
+ else {
150
+ updated.push(finalMessage);
151
+ }
152
+ return updated;
153
+ });
154
+ setTotalTokens((prev) => prev + inputTokens + outputTokens);
155
+ onComplete?.(finalMessage);
156
+ }
157
+ catch (err) {
158
+ if (err instanceof Error && err.name === "AbortError")
159
+ return;
160
+ const error = err instanceof Error ? err : new Error(String(err));
161
+ setError(error);
162
+ onError?.(error);
163
+ }
164
+ finally {
165
+ setIsLoading(false);
166
+ setIsStreaming(false);
167
+ abortRef.current = null;
168
+ }
169
+ }, [client, messages, provider, model, systemPrompt, maxContextMessages, isLoading, onChunk, onComplete, onError]);
170
+ const handleSubmit = useCallback(async (e) => {
171
+ e?.preventDefault();
172
+ await sendMessage(input);
173
+ }, [input, sendMessage]);
174
+ const retry = useCallback(async () => {
175
+ if (!lastUserMessageRef.current || isLoading)
176
+ return;
177
+ // Remove last assistant message
178
+ setMessages((prev) => {
179
+ const lastIdx = prev.length - 1;
180
+ if (lastIdx >= 0 && prev[lastIdx].role === "assistant") {
181
+ return prev.slice(0, -1);
182
+ }
183
+ return prev;
184
+ });
185
+ await sendMessage(lastUserMessageRef.current);
186
+ }, [isLoading, sendMessage]);
187
+ return {
188
+ messages,
189
+ input,
190
+ setInput,
191
+ handleSubmit,
192
+ sendMessage,
193
+ isLoading,
194
+ isStreaming,
195
+ error,
196
+ stop,
197
+ clear,
198
+ retry,
199
+ totalTokens,
200
+ totalCost,
201
+ };
202
+ }
@@ -0,0 +1,66 @@
1
+ export interface UseCompletionOptions {
2
+ /** Provider name */
3
+ provider: string;
4
+ /** Model ID */
5
+ model: string;
6
+ /** System prompt */
7
+ systemPrompt?: string;
8
+ /** Called on each text chunk during streaming */
9
+ onChunk?: (chunk: {
10
+ text: string;
11
+ accumulated: string;
12
+ }) => void;
13
+ /** Called when completion finishes */
14
+ onComplete?: (text: string) => void;
15
+ /** Called on error */
16
+ onError?: (error: Error) => void;
17
+ }
18
+ export interface UseCompletionReturn {
19
+ /** Current completion text */
20
+ completion: string;
21
+ /** The full prompt sent */
22
+ prompt: string;
23
+ /** Set the prompt */
24
+ setPrompt: (value: string) => void;
25
+ /** Generate completion from current prompt */
26
+ complete: (promptOverride?: string) => Promise<string>;
27
+ /** Whether generating */
28
+ isLoading: boolean;
29
+ /** Whether streaming */
30
+ isStreaming: boolean;
31
+ /** Current error */
32
+ error: Error | null;
33
+ /** Abort current generation */
34
+ stop: () => void;
35
+ /** Clear completion */
36
+ clear: () => void;
37
+ /** Token count */
38
+ tokens: {
39
+ input: number;
40
+ output: number;
41
+ total: number;
42
+ };
43
+ }
44
+ /**
45
+ * useCompletion — text completion hook for React.
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * function AutoComplete() {
50
+ * const { completion, prompt, setPrompt, complete, isLoading } = useCompletion({
51
+ * provider: "openai",
52
+ * model: "gpt-4o",
53
+ * systemPrompt: "Complete the following text:",
54
+ * });
55
+ *
56
+ * return (
57
+ * <div>
58
+ * <textarea value={prompt} onChange={e => setPrompt(e.target.value)} />
59
+ * <button onClick={() => complete()} disabled={isLoading}>Complete</button>
60
+ * {completion && <div>{completion}</div>}
61
+ * </div>
62
+ * );
63
+ * }
64
+ * ```
65
+ */
66
+ export declare function useCompletion(options: UseCompletionOptions): UseCompletionReturn;
@@ -0,0 +1,117 @@
1
+ "use client";
2
+ import { useState, useCallback, useRef, useEffect } from "react";
3
+ import { useHilbrasClient } from "./provider.js";
4
+ /**
5
+ * useCompletion — text completion hook for React.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * function AutoComplete() {
10
+ * const { completion, prompt, setPrompt, complete, isLoading } = useCompletion({
11
+ * provider: "openai",
12
+ * model: "gpt-4o",
13
+ * systemPrompt: "Complete the following text:",
14
+ * });
15
+ *
16
+ * return (
17
+ * <div>
18
+ * <textarea value={prompt} onChange={e => setPrompt(e.target.value)} />
19
+ * <button onClick={() => complete()} disabled={isLoading}>Complete</button>
20
+ * {completion && <div>{completion}</div>}
21
+ * </div>
22
+ * );
23
+ * }
24
+ * ```
25
+ */
26
+ export function useCompletion(options) {
27
+ const { provider, model, systemPrompt, onChunk, onComplete, onError } = options;
28
+ const client = useHilbrasClient();
29
+ const [completion, setCompletion] = useState("");
30
+ const [prompt, setPrompt] = useState("");
31
+ const [isLoading, setIsLoading] = useState(false);
32
+ const [isStreaming, setIsStreaming] = useState(false);
33
+ const [error, setError] = useState(null);
34
+ const [tokens, setTokens] = useState({ input: 0, output: 0, total: 0 });
35
+ const abortRef = useRef(null);
36
+ useEffect(() => {
37
+ return () => {
38
+ abortRef.current?.abort();
39
+ };
40
+ }, []);
41
+ const stop = useCallback(() => {
42
+ abortRef.current?.abort();
43
+ abortRef.current = null;
44
+ setIsLoading(false);
45
+ setIsStreaming(false);
46
+ }, []);
47
+ const clear = useCallback(() => {
48
+ stop();
49
+ setCompletion("");
50
+ setError(null);
51
+ setTokens({ input: 0, output: 0, total: 0 });
52
+ }, [stop]);
53
+ const complete = useCallback(async (promptOverride) => {
54
+ const promptText = promptOverride ?? prompt;
55
+ if (!promptText.trim() || isLoading)
56
+ return "";
57
+ setIsLoading(true);
58
+ setIsStreaming(true);
59
+ setError(null);
60
+ const controller = new AbortController();
61
+ abortRef.current = controller;
62
+ try {
63
+ const apiMessages = [];
64
+ if (systemPrompt) {
65
+ apiMessages.push({ role: "system", content: systemPrompt });
66
+ }
67
+ apiMessages.push({ role: "user", content: promptText });
68
+ let text = "";
69
+ let inputTokens = 0;
70
+ let outputTokens = 0;
71
+ for await (const chunk of client.stream({
72
+ messages: apiMessages,
73
+ model,
74
+ provider,
75
+ signal: controller.signal,
76
+ })) {
77
+ if (chunk.type === "text") {
78
+ text += chunk.text;
79
+ setCompletion(text);
80
+ onChunk?.({ text: chunk.text, accumulated: text });
81
+ }
82
+ if (chunk.type === "usage") {
83
+ inputTokens = chunk.inputTokens ?? 0;
84
+ outputTokens = chunk.outputTokens ?? 0;
85
+ }
86
+ }
87
+ setTokens({ input: inputTokens, output: outputTokens, total: inputTokens + outputTokens });
88
+ onComplete?.(text);
89
+ return text;
90
+ }
91
+ catch (err) {
92
+ if (err instanceof Error && err.name === "AbortError")
93
+ return completion;
94
+ const error = err instanceof Error ? err : new Error(String(err));
95
+ setError(error);
96
+ onError?.(error);
97
+ return completion;
98
+ }
99
+ finally {
100
+ setIsLoading(false);
101
+ setIsStreaming(false);
102
+ abortRef.current = null;
103
+ }
104
+ }, [client, prompt, provider, model, systemPrompt, isLoading, completion, onChunk, onComplete, onError]);
105
+ return {
106
+ completion,
107
+ prompt,
108
+ setPrompt,
109
+ complete,
110
+ isLoading,
111
+ isStreaming,
112
+ error,
113
+ stop,
114
+ clear,
115
+ tokens,
116
+ };
117
+ }
@@ -0,0 +1,62 @@
1
+ export interface CostSnapshot {
2
+ /** Total cost in dollars */
3
+ totalCost: number;
4
+ /** Total tokens used */
5
+ totalTokens: number;
6
+ /** Total requests made */
7
+ totalRequests: number;
8
+ /** Average cost per request */
9
+ avgCostPerRequest: number;
10
+ /** Average tokens per request */
11
+ avgTokensPerRequest: number;
12
+ /** Cost breakdown by provider */
13
+ byProvider: Record<string, {
14
+ cost: number;
15
+ tokens: number;
16
+ requests: number;
17
+ }>;
18
+ /** Cost breakdown by model */
19
+ byModel: Record<string, {
20
+ cost: number;
21
+ tokens: number;
22
+ requests: number;
23
+ }>;
24
+ /** Remaining budget (null if no budget set) */
25
+ remainingBudget: number | null;
26
+ /** Budget exceeded flag */
27
+ budgetExceeded: boolean;
28
+ }
29
+ export interface UseCostOptions {
30
+ /** Poll interval in ms (default: 1000) */
31
+ pollIntervalMs?: number;
32
+ /** Whether to auto-poll (default: true) */
33
+ enabled?: boolean;
34
+ }
35
+ export interface UseCostReturn {
36
+ /** Current cost snapshot */
37
+ snapshot: CostSnapshot;
38
+ /** Manually refresh the snapshot */
39
+ refresh: () => void;
40
+ /** Whether budget is low (< 20% remaining) */
41
+ isBudgetLow: boolean;
42
+ /** Whether budget is exceeded */
43
+ isBudgetExceeded: boolean;
44
+ }
45
+ /**
46
+ * useCost — real-time cost tracking hook.
47
+ *
48
+ * @example
49
+ * ```tsx
50
+ * function CostDisplay() {
51
+ * const { snapshot, isBudgetLow } = useCost();
52
+ *
53
+ * return (
54
+ * <div style={{ color: isBudgetLow ? "red" : "green" }}>
55
+ * Cost: ${snapshot.totalCost.toFixed(4)} | Tokens: {snapshot.totalTokens}
56
+ * {snapshot.remainingBudget != null && ` | Remaining: $${snapshot.remainingBudget.toFixed(2)}`}
57
+ * </div>
58
+ * );
59
+ * }
60
+ * ```
61
+ */
62
+ export declare function useCost(options?: UseCostOptions): UseCostReturn;
@@ -0,0 +1,68 @@
1
+ "use client";
2
+ import { useState, useCallback, useEffect } from "react";
3
+ import { useHilbrasClient } from "./provider.js";
4
+ /**
5
+ * useCost — real-time cost tracking hook.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * function CostDisplay() {
10
+ * const { snapshot, isBudgetLow } = useCost();
11
+ *
12
+ * return (
13
+ * <div style={{ color: isBudgetLow ? "red" : "green" }}>
14
+ * Cost: ${snapshot.totalCost.toFixed(4)} | Tokens: {snapshot.totalTokens}
15
+ * {snapshot.remainingBudget != null && ` | Remaining: $${snapshot.remainingBudget.toFixed(2)}`}
16
+ * </div>
17
+ * );
18
+ * }
19
+ * ```
20
+ */
21
+ export function useCost(options = {}) {
22
+ const { pollIntervalMs = 1000, enabled = true } = options;
23
+ const client = useHilbrasClient();
24
+ const [snapshot, setSnapshot] = useState({
25
+ totalCost: 0,
26
+ totalTokens: 0,
27
+ totalRequests: 0,
28
+ avgCostPerRequest: 0,
29
+ avgTokensPerRequest: 0,
30
+ byProvider: {},
31
+ byModel: {},
32
+ remainingBudget: null,
33
+ budgetExceeded: false,
34
+ });
35
+ const refresh = useCallback(() => {
36
+ try {
37
+ const report = client.costReport();
38
+ const byProvider = Object.fromEntries(Object.entries(report.byProvider).map(([provider, metrics]) => [
39
+ provider,
40
+ { cost: metrics.actual, tokens: 0, requests: metrics.requests },
41
+ ]));
42
+ setSnapshot({
43
+ totalCost: report.totalActual,
44
+ totalTokens: 0, // Will be filled from hooks if available
45
+ totalRequests: report.requestCount,
46
+ avgCostPerRequest: report.requestCount > 0 ? report.totalActual / report.requestCount : 0,
47
+ avgTokensPerRequest: 0,
48
+ byProvider,
49
+ byModel: {},
50
+ remainingBudget: report.remainingBudget,
51
+ budgetExceeded: report.budgetExceeded,
52
+ });
53
+ }
54
+ catch {
55
+ // Client may not have cost tracking enabled
56
+ }
57
+ }, [client]);
58
+ useEffect(() => {
59
+ if (!enabled)
60
+ return;
61
+ refresh();
62
+ const interval = setInterval(refresh, pollIntervalMs);
63
+ return () => clearInterval(interval);
64
+ }, [enabled, pollIntervalMs, refresh]);
65
+ const isBudgetLow = snapshot.remainingBudget != null && snapshot.remainingBudget < 1.0;
66
+ const isBudgetExceeded = snapshot.budgetExceeded;
67
+ return { snapshot, refresh, isBudgetLow, isBudgetExceeded };
68
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hilbras/sdk",
3
- "version": "3.5.0",
4
- "description": "Provider-agnostic LLM client SDK — streaming, tool calling, embeddings, image generation, speech synthesis, transcription, reranking, circuit breaker, retry, reasoning normalization, cost enforcement, structured output with schema validation, type-safe tool builder, and SSRF-safe provider registration. Zero runtime dependencies.",
3
+ "version": "3.6.0",
4
+ "description": "Provider-agnostic LLM client SDK \u2014 streaming, tool calling, embeddings, image generation, speech synthesis, transcription, reranking, circuit breaker, retry, reasoning normalization, cost enforcement, structured output with schema validation, type-safe tool builder, and SSRF-safe provider registration. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -167,6 +167,10 @@
167
167
  "types": "./dist/frameworks/react/index.d.ts",
168
168
  "import": "./dist/frameworks/react/index.js"
169
169
  },
170
+ "./react-client": {
171
+ "types": "./dist/frameworks/react-client/index.d.ts",
172
+ "import": "./dist/frameworks/react-client/index.js"
173
+ },
170
174
  "./vue": {
171
175
  "types": "./dist/frameworks/vue/index.d.ts",
172
176
  "import": "./dist/frameworks/vue/index.js"
@@ -250,7 +254,9 @@
250
254
  "check:package": "npm run build && node tools/check-package.mjs",
251
255
  "test:root": "vitest run",
252
256
  "build:packages": "npm run build --workspaces --if-present",
253
- "test:packages": "npm run build:packages && npm run test --workspace hilbras --workspace create-hilbras-app --workspace @hilbras/react --workspace @hilbras/ui"
257
+ "test:packages": "npm run build:packages && npm run test --workspace hilbras --workspace create-hilbras-app --workspace @hilbras/ui",
258
+ "check:docs": "bash tools/check-doc-examples.sh",
259
+ "check:subpaths": "node tools/gen-subpath-table.mjs --check"
254
260
  },
255
261
  "engines": {
256
262
  "node": ">=18"