@hilbras/sdk 3.4.4 → 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 +17 -10
- package/dist/frameworks/astro/endpoints.js +58 -16
- package/dist/frameworks/astro/index.d.ts +1 -0
- package/dist/frameworks/nextjs/api/index.d.ts +15 -0
- package/dist/frameworks/nextjs/api/index.js +14 -0
- package/dist/frameworks/nextjs/api/stream.d.ts +44 -0
- package/dist/frameworks/nextjs/api/stream.js +150 -0
- package/dist/frameworks/nextjs/edge/index.d.ts +12 -0
- package/dist/frameworks/nextjs/edge/index.js +11 -0
- package/dist/frameworks/nextjs/edge/middleware.d.ts +85 -0
- package/dist/frameworks/nextjs/edge/middleware.js +113 -0
- package/dist/frameworks/nextjs/index.d.ts +1 -0
- package/dist/frameworks/nextjs/next-runtime.d.ts +63 -0
- package/dist/frameworks/nextjs/next-runtime.js +41 -0
- package/dist/frameworks/nextjs/route-handlers.js +51 -27
- package/dist/frameworks/nextjs/server.d.ts +24 -1
- package/dist/frameworks/nextjs/server.js +24 -1
- package/dist/frameworks/react-client/index.d.ts +35 -0
- package/dist/frameworks/react-client/index.js +31 -0
- package/dist/frameworks/react-client/provider.d.ts +45 -0
- package/dist/frameworks/react-client/provider.js +40 -0
- package/dist/frameworks/react-client/use-chat.d.ts +85 -0
- package/dist/frameworks/react-client/use-chat.js +202 -0
- package/dist/frameworks/react-client/use-completion.d.ts +66 -0
- package/dist/frameworks/react-client/use-completion.js +117 -0
- package/dist/frameworks/react-client/use-cost.d.ts +62 -0
- package/dist/frameworks/react-client/use-cost.js +68 -0
- package/dist/frameworks/remix/actions.js +58 -16
- package/dist/frameworks/remix/index.d.ts +1 -0
- package/dist/frameworks/shared/handler-core.d.ts +143 -2
- package/dist/frameworks/shared/handler-core.js +134 -5
- package/package.json +17 -3
|
@@ -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
|
+
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Uses the HilbrasClient to generate streaming responses with full protocol support.
|
|
6
6
|
*/
|
|
7
7
|
import { createSSEResponse } from "../../utils/sse-writer.js";
|
|
8
|
-
import { createFrameworkClientPool, errorResponse, readJsonBody,
|
|
8
|
+
import { createFrameworkClientPool, errorResponse, isRequestPhaseError, readJsonBody, resolveChatFields, resolveCompletionFields, resolveLimits, } from "../shared/handler-core.js";
|
|
9
9
|
/**
|
|
10
10
|
* Create a streaming chat action for Remix.
|
|
11
11
|
*
|
|
@@ -26,20 +26,35 @@ export function createChatAction(options) {
|
|
|
26
26
|
model: options.model,
|
|
27
27
|
apiKey: options.apiKey,
|
|
28
28
|
});
|
|
29
|
+
const limits = resolveLimits(options.limits);
|
|
30
|
+
// This adapter never read `model`/`tools`/`maxSteps` from the body in v3.4, so
|
|
31
|
+
// its default is `false`. Defaulting to `true` would have widened the
|
|
32
|
+
// caller's influence over a route that did not previously have any.
|
|
33
|
+
const trustClientFields = options.trustClientFields ?? false;
|
|
29
34
|
const action = async ({ request }) => {
|
|
30
35
|
try {
|
|
31
|
-
const body = await readJsonBody(request);
|
|
32
|
-
const
|
|
33
|
-
|
|
36
|
+
const body = await readJsonBody(request, limits);
|
|
37
|
+
const fields = resolveChatFields(body, {
|
|
38
|
+
model: options.model,
|
|
39
|
+
tools: options.tools,
|
|
40
|
+
maxSteps: options.maxSteps,
|
|
41
|
+
trustClientFields,
|
|
42
|
+
limits,
|
|
43
|
+
});
|
|
44
|
+
const client = pool.get(fields.model);
|
|
34
45
|
const providerName = pool.providerName;
|
|
46
|
+
const effective = { ...fields, provider: providerName };
|
|
47
|
+
await options.onRequest?.({ request, body, effective });
|
|
35
48
|
const allMessages = options.systemPrompt
|
|
36
|
-
? [{ role: "system", content: options.systemPrompt }, ...messages]
|
|
37
|
-
: messages;
|
|
38
|
-
if (
|
|
49
|
+
? [{ role: "system", content: options.systemPrompt }, ...fields.messages]
|
|
50
|
+
: fields.messages;
|
|
51
|
+
if (!effective.stream) {
|
|
39
52
|
const result = await client.complete({
|
|
40
53
|
provider: providerName,
|
|
41
|
-
model:
|
|
54
|
+
model: fields.model,
|
|
42
55
|
messages: allMessages,
|
|
56
|
+
temperature: fields.temperature,
|
|
57
|
+
maxTokens: fields.maxTokens,
|
|
43
58
|
signal: request.signal,
|
|
44
59
|
});
|
|
45
60
|
return new Response(JSON.stringify({
|
|
@@ -51,15 +66,23 @@ export function createChatAction(options) {
|
|
|
51
66
|
}
|
|
52
67
|
const chunks = client.streamText({
|
|
53
68
|
provider: providerName,
|
|
54
|
-
model:
|
|
69
|
+
model: fields.model,
|
|
55
70
|
messages: allMessages,
|
|
56
|
-
|
|
57
|
-
|
|
71
|
+
temperature: fields.temperature,
|
|
72
|
+
maxTokens: fields.maxTokens,
|
|
73
|
+
tools: fields.tools,
|
|
74
|
+
maxSteps: fields.maxSteps,
|
|
58
75
|
signal: request.signal,
|
|
59
76
|
});
|
|
60
77
|
return createSSEResponse(chunks);
|
|
61
78
|
}
|
|
62
79
|
catch (error) {
|
|
80
|
+
if (options.onError) {
|
|
81
|
+
await options.onError(error, {
|
|
82
|
+
request,
|
|
83
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
63
86
|
return errorResponse(error);
|
|
64
87
|
}
|
|
65
88
|
};
|
|
@@ -77,15 +100,28 @@ export function createCompletionAction(options) {
|
|
|
77
100
|
model: options.model,
|
|
78
101
|
apiKey: options.apiKey,
|
|
79
102
|
});
|
|
103
|
+
const limits = resolveLimits(options.limits);
|
|
104
|
+
// This adapter never read `model`/`tools`/`maxSteps` from the body in v3.4, so
|
|
105
|
+
// its default is `false`. Defaulting to `true` would have widened the
|
|
106
|
+
// caller's influence over a route that did not previously have any.
|
|
107
|
+
const trustClientFields = options.trustClientFields ?? false;
|
|
80
108
|
const action = async ({ request }) => {
|
|
81
109
|
try {
|
|
82
|
-
const body = await readJsonBody(request);
|
|
83
|
-
const
|
|
84
|
-
|
|
110
|
+
const body = await readJsonBody(request, limits);
|
|
111
|
+
const fields = resolveCompletionFields(body, {
|
|
112
|
+
model: options.model,
|
|
113
|
+
trustClientFields,
|
|
114
|
+
limits,
|
|
115
|
+
});
|
|
116
|
+
const client = pool.get(fields.model);
|
|
117
|
+
const effective = { ...fields, provider: pool.providerName };
|
|
118
|
+
await options.onRequest?.({ request, body, effective });
|
|
85
119
|
const result = await client.complete({
|
|
86
120
|
provider: pool.providerName,
|
|
87
|
-
model:
|
|
88
|
-
messages: [{ role: "user", content: prompt }],
|
|
121
|
+
model: fields.model,
|
|
122
|
+
messages: [{ role: "user", content: fields.prompt }],
|
|
123
|
+
temperature: fields.temperature,
|
|
124
|
+
maxTokens: fields.maxTokens,
|
|
89
125
|
signal: request.signal,
|
|
90
126
|
});
|
|
91
127
|
return new Response(JSON.stringify({
|
|
@@ -96,6 +132,12 @@ export function createCompletionAction(options) {
|
|
|
96
132
|
});
|
|
97
133
|
}
|
|
98
134
|
catch (error) {
|
|
135
|
+
if (options.onError) {
|
|
136
|
+
await options.onError(error, {
|
|
137
|
+
request,
|
|
138
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
139
|
+
});
|
|
140
|
+
}
|
|
99
141
|
return errorResponse(error);
|
|
100
142
|
}
|
|
101
143
|
};
|
|
@@ -4,4 +4,5 @@
|
|
|
4
4
|
* Actions and hooks for Remix.
|
|
5
5
|
*/
|
|
6
6
|
export { createChatAction, createCompletionAction, type ActionOptions, type ChatMessage } from "./actions.js";
|
|
7
|
+
export type { FrameworkErrorContext, FrameworkHandlerLimits, FrameworkRequestContext, } from "../shared/handler-core.js";
|
|
7
8
|
export { createChatHook, type UseChatOptions, type UseChatReturn, type Message } from "./hooks.js";
|