@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
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* - useCompletion: Text completion hook
|
|
15
15
|
*/
|
|
16
16
|
export { createServerClient, ServerHilbrasClient, type ServerClientOptions } from "./server.js";
|
|
17
|
+
export type { FrameworkErrorContext, FrameworkHandlerLimits, FrameworkRequestContext, } from "../shared/handler-core.js";
|
|
17
18
|
export { createChatHandler, createCompletionHandler, type ChatRequest, type ChatResponse } from "./route-handlers.js";
|
|
18
19
|
export { useChat, type UseChatOptions, type UseChatReturn } from "./use-chat.js";
|
|
19
20
|
export { useCompletion, type UseCompletionOptions, type UseCompletionReturn } from "./use-completion.js";
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Next.js runtime surface
|
|
3
|
+
*
|
|
4
|
+
* Minimal structural types for the pieces of `next/server` these helpers use.
|
|
5
|
+
*
|
|
6
|
+
* The SDK cannot import from `next/server`: `next` is an optional peer
|
|
7
|
+
* dependency, and the published package must typecheck and build in a project
|
|
8
|
+
* that has never installed Next. Declaring the surface here keeps the build
|
|
9
|
+
* self-contained.
|
|
10
|
+
*
|
|
11
|
+
* Every member below is structurally satisfied by the real Next types, so a
|
|
12
|
+
* Next `NextRequest`/`NextResponse` is assignable to these without a cast, and
|
|
13
|
+
* a real Next route accepts a handler typed against them. That is the whole
|
|
14
|
+
* point of declaring the *shape* rather than the nominal class.
|
|
15
|
+
*/
|
|
16
|
+
/** The subset of `NextRequest` the helpers read. */
|
|
17
|
+
export interface HilbrasNextRequest {
|
|
18
|
+
/** Parse the body as JSON. Present on the Web `Request`. */
|
|
19
|
+
json(): Promise<unknown>;
|
|
20
|
+
/** Abort signal for a client disconnect. */
|
|
21
|
+
readonly signal: AbortSignal;
|
|
22
|
+
/** Incoming headers. */
|
|
23
|
+
readonly headers: Headers;
|
|
24
|
+
/** Path of the matched route, e.g. `/api/chat`. */
|
|
25
|
+
readonly nextUrl: {
|
|
26
|
+
readonly pathname: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Next-resolved client IP.
|
|
30
|
+
*
|
|
31
|
+
* Deliberately never read by the middleware: Next derives this from the
|
|
32
|
+
* forwarded headers, which is the value `trustProxy` exists to correct.
|
|
33
|
+
*/
|
|
34
|
+
readonly ip?: string;
|
|
35
|
+
}
|
|
36
|
+
/** The subset of `NextResponse` the helpers produce. */
|
|
37
|
+
export interface HilbrasNextResponse {
|
|
38
|
+
json(body: unknown, init?: {
|
|
39
|
+
status?: number;
|
|
40
|
+
headers?: Record<string, string>;
|
|
41
|
+
}): HilbrasNextResponse;
|
|
42
|
+
next(init?: unknown): HilbrasNextResponse;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A Next middleware request, typed structurally.
|
|
46
|
+
*
|
|
47
|
+
* A real `NextRequest` satisfies this: it extends the Web `Request`, so it has
|
|
48
|
+
* `json`, `signal` and `headers`, and Next adds `nextUrl` and `ip`.
|
|
49
|
+
*/
|
|
50
|
+
export type NextRequestLike = HilbrasNextRequest;
|
|
51
|
+
/**
|
|
52
|
+
* Build the minimal `NextResponse` surface at runtime.
|
|
53
|
+
*
|
|
54
|
+
* `NextResponse.json` and `NextResponse.next` return objects that the Next
|
|
55
|
+
* runtime converts into a real response. Outside Next — in a unit test, or in
|
|
56
|
+
* an app using the Web `Response` — the standard constructors do the same job,
|
|
57
|
+
* so they are used as the fallback and keep the SDK free of a hard Next
|
|
58
|
+
* dependency at runtime too.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createNextResponseShim(): {
|
|
61
|
+
json: HilbrasNextResponse["json"];
|
|
62
|
+
next: HilbrasNextResponse["next"];
|
|
63
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Next.js runtime surface
|
|
3
|
+
*
|
|
4
|
+
* Minimal structural types for the pieces of `next/server` these helpers use.
|
|
5
|
+
*
|
|
6
|
+
* The SDK cannot import from `next/server`: `next` is an optional peer
|
|
7
|
+
* dependency, and the published package must typecheck and build in a project
|
|
8
|
+
* that has never installed Next. Declaring the surface here keeps the build
|
|
9
|
+
* self-contained.
|
|
10
|
+
*
|
|
11
|
+
* Every member below is structurally satisfied by the real Next types, so a
|
|
12
|
+
* Next `NextRequest`/`NextResponse` is assignable to these without a cast, and
|
|
13
|
+
* a real Next route accepts a handler typed against them. That is the whole
|
|
14
|
+
* point of declaring the *shape* rather than the nominal class.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Build the minimal `NextResponse` surface at runtime.
|
|
18
|
+
*
|
|
19
|
+
* `NextResponse.json` and `NextResponse.next` return objects that the Next
|
|
20
|
+
* runtime converts into a real response. Outside Next — in a unit test, or in
|
|
21
|
+
* an app using the Web `Response` — the standard constructors do the same job,
|
|
22
|
+
* so they are used as the fallback and keep the SDK free of a hard Next
|
|
23
|
+
* dependency at runtime too.
|
|
24
|
+
*/
|
|
25
|
+
export function createNextResponseShim() {
|
|
26
|
+
return {
|
|
27
|
+
json(body, init) {
|
|
28
|
+
// A plain `Response` already exposes `.status` and `.headers`, which is
|
|
29
|
+
// everything these helpers and their tests read. `Object.assign` cannot
|
|
30
|
+
// be used to graft on a `status` property: `Response.status` is a
|
|
31
|
+
// getter-only accessor on the prototype, so assignment throws.
|
|
32
|
+
return new Response(JSON.stringify(body), {
|
|
33
|
+
status: init?.status ?? 200,
|
|
34
|
+
headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
next() {
|
|
38
|
+
return new Response(null, { status: 200 });
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
@@ -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 endpoint for Next.js.
|
|
11
11
|
*
|
|
@@ -26,29 +26,36 @@ export function createChatHandler(options) {
|
|
|
26
26
|
model: options.model,
|
|
27
27
|
apiKey: options.apiKey,
|
|
28
28
|
});
|
|
29
|
+
const limits = resolveLimits(options.limits);
|
|
30
|
+
const trustClientFields = options.trustClientFields ?? true;
|
|
29
31
|
async function POST(req) {
|
|
30
32
|
try {
|
|
31
|
-
const body = await readJsonBody(req);
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
: options.
|
|
33
|
+
const body = await readJsonBody(req, limits);
|
|
34
|
+
const fields = resolveChatFields(body, {
|
|
35
|
+
model: options.model,
|
|
36
|
+
tools: options.tools,
|
|
37
|
+
maxSteps: options.maxSteps,
|
|
38
|
+
trustClientFields,
|
|
39
|
+
limits,
|
|
40
|
+
});
|
|
36
41
|
// Resolving the client before responding means a bad provider or model
|
|
37
42
|
// produces a real error status instead of an HTTP 200 whose body carries
|
|
38
43
|
// the failure.
|
|
39
|
-
const client = pool.get(model);
|
|
44
|
+
const client = pool.get(fields.model);
|
|
40
45
|
const providerName = pool.providerName;
|
|
46
|
+
const effective = { ...fields, provider: providerName };
|
|
47
|
+
await options.onRequest?.({ request: req, body, effective });
|
|
41
48
|
const allMessages = [
|
|
42
49
|
...(options.systemPrompt ? [{ role: "system", content: options.systemPrompt }] : []),
|
|
43
|
-
...messages,
|
|
50
|
+
...fields.messages,
|
|
44
51
|
];
|
|
45
|
-
if (
|
|
52
|
+
if (!effective.stream) {
|
|
46
53
|
const result = await client.complete({
|
|
47
54
|
provider: providerName,
|
|
48
|
-
model,
|
|
55
|
+
model: fields.model,
|
|
49
56
|
messages: allMessages,
|
|
50
|
-
temperature:
|
|
51
|
-
maxTokens:
|
|
57
|
+
temperature: fields.temperature,
|
|
58
|
+
maxTokens: fields.maxTokens,
|
|
52
59
|
signal: req.signal,
|
|
53
60
|
});
|
|
54
61
|
return Response.json({
|
|
@@ -58,17 +65,23 @@ export function createChatHandler(options) {
|
|
|
58
65
|
}
|
|
59
66
|
const chunks = client.streamText({
|
|
60
67
|
provider: providerName,
|
|
61
|
-
model,
|
|
68
|
+
model: fields.model,
|
|
62
69
|
messages: allMessages,
|
|
63
|
-
temperature:
|
|
64
|
-
maxTokens:
|
|
65
|
-
tools:
|
|
66
|
-
maxSteps:
|
|
70
|
+
temperature: fields.temperature,
|
|
71
|
+
maxTokens: fields.maxTokens,
|
|
72
|
+
tools: fields.tools,
|
|
73
|
+
maxSteps: fields.maxSteps,
|
|
67
74
|
signal: req.signal,
|
|
68
75
|
});
|
|
69
76
|
return createSSEResponse(chunks);
|
|
70
77
|
}
|
|
71
78
|
catch (error) {
|
|
79
|
+
if (options.onError) {
|
|
80
|
+
await options.onError(error, {
|
|
81
|
+
request: req,
|
|
82
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
83
|
+
});
|
|
84
|
+
}
|
|
72
85
|
return errorResponse(error);
|
|
73
86
|
}
|
|
74
87
|
}
|
|
@@ -87,20 +100,25 @@ export function createCompletionHandler(options) {
|
|
|
87
100
|
model: options.model,
|
|
88
101
|
apiKey: options.apiKey,
|
|
89
102
|
});
|
|
103
|
+
const limits = resolveLimits(options.limits);
|
|
104
|
+
const trustClientFields = options.trustClientFields ?? true;
|
|
90
105
|
async function POST(req) {
|
|
91
106
|
try {
|
|
92
|
-
const body = await readJsonBody(req);
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
107
|
+
const body = await readJsonBody(req, limits);
|
|
108
|
+
const fields = resolveCompletionFields(body, {
|
|
109
|
+
model: options.model,
|
|
110
|
+
trustClientFields,
|
|
111
|
+
limits,
|
|
112
|
+
});
|
|
113
|
+
const client = pool.get(fields.model);
|
|
114
|
+
const effective = { ...fields, provider: pool.providerName };
|
|
115
|
+
await options.onRequest?.({ request: req, body, effective });
|
|
98
116
|
const result = await client.complete({
|
|
99
117
|
provider: pool.providerName,
|
|
100
|
-
model,
|
|
101
|
-
messages: [{ role: "user", content: prompt }],
|
|
102
|
-
temperature:
|
|
103
|
-
maxTokens:
|
|
118
|
+
model: fields.model,
|
|
119
|
+
messages: [{ role: "user", content: fields.prompt }],
|
|
120
|
+
temperature: fields.temperature,
|
|
121
|
+
maxTokens: fields.maxTokens,
|
|
104
122
|
signal: req.signal,
|
|
105
123
|
});
|
|
106
124
|
return Response.json({
|
|
@@ -109,6 +127,12 @@ export function createCompletionHandler(options) {
|
|
|
109
127
|
});
|
|
110
128
|
}
|
|
111
129
|
catch (error) {
|
|
130
|
+
if (options.onError) {
|
|
131
|
+
await options.onError(error, {
|
|
132
|
+
request: req,
|
|
133
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
134
|
+
});
|
|
135
|
+
}
|
|
112
136
|
return errorResponse(error);
|
|
113
137
|
}
|
|
114
138
|
}
|
|
@@ -1,7 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @hilbras/nextjs — Server Client
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* @deprecated This module is a non-functional stub and will be removed in
|
|
5
|
+
* 4.0.0. `ServerHilbrasClient.streamResponse` never calls a provider: it
|
|
6
|
+
* echoes each user message back character by character, and ignores `apiKey`,
|
|
7
|
+
* `baseUrl`, `adapter`, `provider` and `model` entirely. It is kept only so an
|
|
8
|
+
* existing import resolves.
|
|
9
|
+
*
|
|
10
|
+
* Use `new HilbrasClient()` directly:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { HilbrasClient } from "@hilbras/sdk";
|
|
14
|
+
*
|
|
15
|
+
* const client = new HilbrasClient();
|
|
16
|
+
* client.addProviderFromCatalog("openai", "gpt-4o", process.env.OPENAI_API_KEY!);
|
|
17
|
+
*
|
|
18
|
+
* export async function POST(req: Request) {
|
|
19
|
+
* const { messages } = await req.json();
|
|
20
|
+
* return client.streamText({ provider: "OpenAI", model: "gpt-4o", messages });
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Or, for a route handler with no client plumbing, use `createChatHandler`.
|
|
5
25
|
*/
|
|
6
26
|
export interface ServerClientOptions {
|
|
7
27
|
/** API key (defaults to env vars) */
|
|
@@ -49,6 +69,9 @@ export declare class ServerHilbrasClient {
|
|
|
49
69
|
constructor(options?: ServerClientOptions);
|
|
50
70
|
/**
|
|
51
71
|
* Create a streaming response for Next.js App Router.
|
|
72
|
+
*
|
|
73
|
+
* @deprecated Returns a simulated echo of the request, not a provider
|
|
74
|
+
* response. Removed in 4.0.0 — see the module deprecation notice.
|
|
52
75
|
*/
|
|
53
76
|
streamResponse(params: {
|
|
54
77
|
messages: Array<{
|
|
@@ -1,7 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @hilbras/nextjs — Server Client
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* @deprecated This module is a non-functional stub and will be removed in
|
|
5
|
+
* 4.0.0. `ServerHilbrasClient.streamResponse` never calls a provider: it
|
|
6
|
+
* echoes each user message back character by character, and ignores `apiKey`,
|
|
7
|
+
* `baseUrl`, `adapter`, `provider` and `model` entirely. It is kept only so an
|
|
8
|
+
* existing import resolves.
|
|
9
|
+
*
|
|
10
|
+
* Use `new HilbrasClient()` directly:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { HilbrasClient } from "@hilbras/sdk";
|
|
14
|
+
*
|
|
15
|
+
* const client = new HilbrasClient();
|
|
16
|
+
* client.addProviderFromCatalog("openai", "gpt-4o", process.env.OPENAI_API_KEY!);
|
|
17
|
+
*
|
|
18
|
+
* export async function POST(req: Request) {
|
|
19
|
+
* const { messages } = await req.json();
|
|
20
|
+
* return client.streamText({ provider: "OpenAI", model: "gpt-4o", messages });
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Or, for a route handler with no client plumbing, use `createChatHandler`.
|
|
5
25
|
*/
|
|
6
26
|
/**
|
|
7
27
|
* Create a HilbrasClient for server-side use.
|
|
@@ -41,6 +61,9 @@ export class ServerHilbrasClient {
|
|
|
41
61
|
}
|
|
42
62
|
/**
|
|
43
63
|
* Create a streaming response for Next.js App Router.
|
|
64
|
+
*
|
|
65
|
+
* @deprecated Returns a simulated echo of the request, not a provider
|
|
66
|
+
* response. Removed in 4.0.0 — see the module deprecation notice.
|
|
44
67
|
*/
|
|
45
68
|
async streamResponse(params) {
|
|
46
69
|
const { messages, model, provider, systemPrompt } = params;
|
|
@@ -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;
|