@hilbras/sdk 3.4.3 → 3.5.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 +2 -2
- package/dist/errors/index.d.ts +12 -0
- package/dist/errors/index.js +16 -0
- package/dist/frameworks/astro/endpoints.d.ts +6 -6
- package/dist/frameworks/astro/endpoints.js +114 -43
- 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.d.ts +29 -22
- package/dist/frameworks/nextjs/route-handlers.js +114 -51
- package/dist/frameworks/nextjs/server.d.ts +24 -1
- package/dist/frameworks/nextjs/server.js +24 -1
- package/dist/frameworks/remix/actions.d.ts +12 -10
- package/dist/frameworks/remix/actions.js +116 -43
- package/dist/frameworks/remix/index.d.ts +1 -0
- package/dist/frameworks/shared/handler-core.d.ts +232 -0
- package/dist/frameworks/shared/handler-core.js +295 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +10 -2
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createNextResponseShim, } from "../next-runtime.js";
|
|
2
|
+
const NextResponse = createNextResponseShim();
|
|
3
|
+
/** In-process store. Not shared across instances — see `store`. */
|
|
4
|
+
function createMemoryStore() {
|
|
5
|
+
const hits = new Map();
|
|
6
|
+
return {
|
|
7
|
+
async hit(key, windowMs) {
|
|
8
|
+
const now = Date.now();
|
|
9
|
+
const entry = hits.get(key);
|
|
10
|
+
if (!entry || now > entry.resetAt) {
|
|
11
|
+
const fresh = { count: 1, resetAt: now + windowMs };
|
|
12
|
+
hits.set(key, fresh);
|
|
13
|
+
return fresh;
|
|
14
|
+
}
|
|
15
|
+
entry.count++;
|
|
16
|
+
return entry;
|
|
17
|
+
},
|
|
18
|
+
cleanup() {
|
|
19
|
+
const now = Date.now();
|
|
20
|
+
for (const [key, value] of hits) {
|
|
21
|
+
if (now > value.resetAt)
|
|
22
|
+
hits.delete(key);
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const DEFAULT_EXCLUDE = ["/_next", "/favicon.ico", "/api/health"];
|
|
28
|
+
/**
|
|
29
|
+
* Extract the client address from a `x-forwarded-for` list.
|
|
30
|
+
*
|
|
31
|
+
* Each proxy *appends* the address it saw, so the list reads
|
|
32
|
+
* `client-supplied, …, nearest-hop`. With `trustProxy` trusted proxies the real
|
|
33
|
+
* client sits `trustProxy` entries from the right, which is index
|
|
34
|
+
* `entries.length - trustProxy`:
|
|
35
|
+
*
|
|
36
|
+
* - `trustProxy: 0` — index `length`, i.e. out of range. Nothing is trusted, so
|
|
37
|
+
* there is no entry we can attribute to the client rather than to a proxy.
|
|
38
|
+
* - `trustProxy: 1` — `"9.9.9.1, 1.1.1.1"` gives index 1, the real client, and
|
|
39
|
+
* `9.9.9.1` (the attacker's) is correctly ignored.
|
|
40
|
+
* - `trustProxy: 2` — `"9.9.9.1, 1.1.1.1, 10.0.0.1"` gives index 1 again.
|
|
41
|
+
*
|
|
42
|
+
* Returns `undefined` when the list is absent or shorter than the trust depth,
|
|
43
|
+
* because in that case every entry present was chosen by the client.
|
|
44
|
+
*/
|
|
45
|
+
export function forwardedClientIp(headerValue, trustProxy) {
|
|
46
|
+
if (!headerValue)
|
|
47
|
+
return undefined;
|
|
48
|
+
const entries = headerValue
|
|
49
|
+
.split(",")
|
|
50
|
+
.map((entry) => entry.trim())
|
|
51
|
+
.filter(Boolean);
|
|
52
|
+
if (entries.length === 0)
|
|
53
|
+
return undefined;
|
|
54
|
+
const index = entries.length - trustProxy;
|
|
55
|
+
if (index < 0)
|
|
56
|
+
return undefined;
|
|
57
|
+
return entries[index];
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Next.js middleware for rate limiting AI API routes.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```ts
|
|
64
|
+
* // middleware.ts
|
|
65
|
+
* import { hilbrasMiddleware } from "@hilbras/sdk/nextjs/edge";
|
|
66
|
+
*
|
|
67
|
+
* export const config = { matcher: ["/api/:path*"] };
|
|
68
|
+
* export default hilbrasMiddleware({ maxRequests: 30, trustProxy: 1 });
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export function hilbrasMiddleware(options = {}) {
|
|
72
|
+
const { maxRequests = 60, windowSeconds = 60, excludePaths = DEFAULT_EXCLUDE, onError, trustProxy = 0, fallbackKey, store = createMemoryStore(), } = options;
|
|
73
|
+
function getClientKey(request) {
|
|
74
|
+
const fromHeader = forwardedClientIp(request.headers.get("x-forwarded-for"), trustProxy);
|
|
75
|
+
if (fromHeader)
|
|
76
|
+
return fromHeader;
|
|
77
|
+
// `x-real-ip` is written by the proxy rather than derived from the client's
|
|
78
|
+
// header chain, so it is a better fallback — but only when at least one
|
|
79
|
+
// proxy is trusted.
|
|
80
|
+
if (trustProxy > 0) {
|
|
81
|
+
const realIp = request.headers.get("x-real-ip")?.trim();
|
|
82
|
+
if (realIp)
|
|
83
|
+
return realIp;
|
|
84
|
+
}
|
|
85
|
+
const explicit = fallbackKey?.(request);
|
|
86
|
+
if (explicit)
|
|
87
|
+
return explicit;
|
|
88
|
+
// Deliberately not `request.ip`: Next.js derives it from the forwarded
|
|
89
|
+
// headers in exactly the way `trustProxy` exists to correct, so trusting it
|
|
90
|
+
// here would reintroduce the spoof.
|
|
91
|
+
//
|
|
92
|
+
// Collapsing everything unidentifiable into one bucket is the safe
|
|
93
|
+
// direction: it can under-serve anonymous callers, but it cannot hand an
|
|
94
|
+
// attacker a fresh budget by omitting a header.
|
|
95
|
+
return "unidentified";
|
|
96
|
+
}
|
|
97
|
+
return async function middleware(request) {
|
|
98
|
+
const path = request.nextUrl.pathname;
|
|
99
|
+
if (excludePaths.some((p) => path.startsWith(p))) {
|
|
100
|
+
return NextResponse.next();
|
|
101
|
+
}
|
|
102
|
+
await store.cleanup?.();
|
|
103
|
+
const key = `${getClientKey(request)}:${path}`;
|
|
104
|
+
const { count, resetAt } = await store.hit(key, windowSeconds * 1000);
|
|
105
|
+
if (count > maxRequests) {
|
|
106
|
+
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
|
|
107
|
+
if (onError)
|
|
108
|
+
return onError("Rate limit exceeded");
|
|
109
|
+
return NextResponse.json({ error: "Rate limit exceeded", retryAfter }, { status: 429, headers: { "Retry-After": String(retryAfter) } });
|
|
110
|
+
}
|
|
111
|
+
return NextResponse.next();
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -1,24 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @hilbras/nextjs — Route
|
|
2
|
+
* @hilbras/nextjs — Next.js Route Handlers
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Create streaming chat/completion endpoints for the Next.js App Router.
|
|
5
5
|
* Uses the HilbrasClient to generate streaming responses with full protocol support.
|
|
6
6
|
*/
|
|
7
7
|
import type { Tool } from "../../types/tools.js";
|
|
8
|
+
import { type FrameworkHandlerBaseOptions } from "../shared/handler-core.js";
|
|
9
|
+
export interface ChatMessage {
|
|
10
|
+
role: "user" | "assistant" | "system";
|
|
11
|
+
content: string;
|
|
12
|
+
}
|
|
8
13
|
export interface ChatRequest {
|
|
9
|
-
messages:
|
|
10
|
-
role: string;
|
|
11
|
-
content: string;
|
|
12
|
-
}>;
|
|
14
|
+
messages: ChatMessage[];
|
|
13
15
|
model?: string;
|
|
14
16
|
provider?: string;
|
|
15
|
-
systemPrompt?: string;
|
|
16
17
|
temperature?: number;
|
|
17
18
|
maxTokens?: number;
|
|
18
19
|
tools?: Tool[];
|
|
19
20
|
maxSteps?: number;
|
|
20
21
|
stream?: boolean;
|
|
21
22
|
}
|
|
23
|
+
export interface ChatHandlerOptions extends FrameworkHandlerBaseOptions {
|
|
24
|
+
tools?: Tool[];
|
|
25
|
+
maxSteps?: number;
|
|
26
|
+
}
|
|
22
27
|
export interface ChatResponse {
|
|
23
28
|
id: string;
|
|
24
29
|
choices: Array<{
|
|
@@ -35,34 +40,36 @@ export interface ChatResponse {
|
|
|
35
40
|
};
|
|
36
41
|
}
|
|
37
42
|
/**
|
|
38
|
-
* Create a streaming chat endpoint
|
|
43
|
+
* Create a streaming chat endpoint for Next.js.
|
|
39
44
|
*
|
|
40
45
|
* @example
|
|
41
46
|
* ```ts
|
|
42
47
|
* // app/api/chat/route.ts
|
|
43
|
-
* import { createChatHandler } from "@hilbras/nextjs";
|
|
48
|
+
* import { createChatHandler } from "@hilbras/sdk/nextjs";
|
|
44
49
|
*
|
|
45
50
|
* export const { POST } = createChatHandler({
|
|
46
|
-
* provider: "
|
|
51
|
+
* provider: "openai",
|
|
47
52
|
* model: "gpt-4o",
|
|
48
53
|
* });
|
|
49
54
|
* ```
|
|
50
55
|
*/
|
|
51
|
-
export declare function createChatHandler(options: {
|
|
52
|
-
provider: string;
|
|
53
|
-
model: string;
|
|
54
|
-
systemPrompt?: string;
|
|
55
|
-
tools?: Tool[];
|
|
56
|
-
maxSteps?: number;
|
|
57
|
-
}): {
|
|
56
|
+
export declare function createChatHandler(options: ChatHandlerOptions): {
|
|
58
57
|
POST: (req: Request) => Promise<Response>;
|
|
58
|
+
dispose: () => Promise<void>;
|
|
59
59
|
};
|
|
60
|
+
export interface CompletionRequest {
|
|
61
|
+
prompt: string;
|
|
62
|
+
model?: string;
|
|
63
|
+
temperature?: number;
|
|
64
|
+
maxTokens?: number;
|
|
65
|
+
stream?: boolean;
|
|
66
|
+
}
|
|
67
|
+
export interface CompletionHandlerOptions extends FrameworkHandlerBaseOptions {
|
|
68
|
+
}
|
|
60
69
|
/**
|
|
61
|
-
* Create a non-streaming completion endpoint
|
|
70
|
+
* Create a non-streaming completion endpoint for Next.js.
|
|
62
71
|
*/
|
|
63
|
-
export declare function createCompletionHandler(options: {
|
|
64
|
-
provider: string;
|
|
65
|
-
model: string;
|
|
66
|
-
}): {
|
|
72
|
+
export declare function createCompletionHandler(options: CompletionHandlerOptions): {
|
|
67
73
|
POST: (req: Request) => Promise<Response>;
|
|
74
|
+
dispose: () => Promise<void>;
|
|
68
75
|
};
|
|
@@ -1,80 +1,143 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @hilbras/nextjs — Route
|
|
2
|
+
* @hilbras/nextjs — Next.js Route Handlers
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Create streaming chat/completion endpoints for the Next.js App Router.
|
|
5
5
|
* Uses the HilbrasClient to generate streaming responses with full protocol support.
|
|
6
6
|
*/
|
|
7
|
-
import { HilbrasClient } from "../../client/client.js";
|
|
8
7
|
import { createSSEResponse } from "../../utils/sse-writer.js";
|
|
8
|
+
import { createFrameworkClientPool, errorResponse, isRequestPhaseError, readJsonBody, resolveChatFields, resolveCompletionFields, resolveLimits, } from "../shared/handler-core.js";
|
|
9
9
|
/**
|
|
10
|
-
* Create a streaming chat endpoint
|
|
10
|
+
* Create a streaming chat endpoint for Next.js.
|
|
11
11
|
*
|
|
12
12
|
* @example
|
|
13
13
|
* ```ts
|
|
14
14
|
* // app/api/chat/route.ts
|
|
15
|
-
* import { createChatHandler } from "@hilbras/nextjs";
|
|
15
|
+
* import { createChatHandler } from "@hilbras/sdk/nextjs";
|
|
16
16
|
*
|
|
17
17
|
* export const { POST } = createChatHandler({
|
|
18
|
-
* provider: "
|
|
18
|
+
* provider: "openai",
|
|
19
19
|
* model: "gpt-4o",
|
|
20
20
|
* });
|
|
21
21
|
* ```
|
|
22
22
|
*/
|
|
23
23
|
export function createChatHandler(options) {
|
|
24
|
+
const pool = createFrameworkClientPool({
|
|
25
|
+
provider: options.provider,
|
|
26
|
+
model: options.model,
|
|
27
|
+
apiKey: options.apiKey,
|
|
28
|
+
});
|
|
29
|
+
const limits = resolveLimits(options.limits);
|
|
30
|
+
const trustClientFields = options.trustClientFields ?? true;
|
|
24
31
|
async function POST(req) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const result = await client.complete({
|
|
34
|
-
provider: options.provider,
|
|
35
|
-
model: body.model ?? options.model,
|
|
36
|
-
messages,
|
|
37
|
-
temperature: body.temperature,
|
|
38
|
-
maxTokens: body.maxTokens,
|
|
32
|
+
try {
|
|
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,
|
|
39
40
|
});
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
// Resolving the client before responding means a bad provider or model
|
|
42
|
+
// produces a real error status instead of an HTTP 200 whose body carries
|
|
43
|
+
// the failure.
|
|
44
|
+
const client = pool.get(fields.model);
|
|
45
|
+
const providerName = pool.providerName;
|
|
46
|
+
const effective = { ...fields, provider: providerName };
|
|
47
|
+
await options.onRequest?.({ request: req, body, effective });
|
|
48
|
+
const allMessages = [
|
|
49
|
+
...(options.systemPrompt ? [{ role: "system", content: options.systemPrompt }] : []),
|
|
50
|
+
...fields.messages,
|
|
51
|
+
];
|
|
52
|
+
if (!effective.stream) {
|
|
53
|
+
const result = await client.complete({
|
|
54
|
+
provider: providerName,
|
|
55
|
+
model: fields.model,
|
|
56
|
+
messages: allMessages,
|
|
57
|
+
temperature: fields.temperature,
|
|
58
|
+
maxTokens: fields.maxTokens,
|
|
59
|
+
signal: req.signal,
|
|
60
|
+
});
|
|
61
|
+
return Response.json({
|
|
62
|
+
id: `cmpl-${Date.now()}`,
|
|
63
|
+
choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const chunks = client.streamText({
|
|
67
|
+
provider: providerName,
|
|
68
|
+
model: fields.model,
|
|
69
|
+
messages: allMessages,
|
|
70
|
+
temperature: fields.temperature,
|
|
71
|
+
maxTokens: fields.maxTokens,
|
|
72
|
+
tools: fields.tools,
|
|
73
|
+
maxSteps: fields.maxSteps,
|
|
74
|
+
signal: req.signal,
|
|
43
75
|
});
|
|
76
|
+
return createSSEResponse(chunks);
|
|
44
77
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
|
|
78
|
+
catch (error) {
|
|
79
|
+
if (options.onError) {
|
|
80
|
+
await options.onError(error, {
|
|
81
|
+
request: req,
|
|
82
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return errorResponse(error);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** Release the cached clients. Call this on server shutdown. */
|
|
89
|
+
async function dispose() {
|
|
90
|
+
await pool.dispose();
|
|
55
91
|
}
|
|
56
|
-
return { POST };
|
|
92
|
+
return { POST, dispose };
|
|
57
93
|
}
|
|
58
94
|
/**
|
|
59
|
-
* Create a non-streaming completion endpoint
|
|
95
|
+
* Create a non-streaming completion endpoint for Next.js.
|
|
60
96
|
*/
|
|
61
97
|
export function createCompletionHandler(options) {
|
|
98
|
+
const pool = createFrameworkClientPool({
|
|
99
|
+
provider: options.provider,
|
|
100
|
+
model: options.model,
|
|
101
|
+
apiKey: options.apiKey,
|
|
102
|
+
});
|
|
103
|
+
const limits = resolveLimits(options.limits);
|
|
104
|
+
const trustClientFields = options.trustClientFields ?? true;
|
|
62
105
|
async function POST(req) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}],
|
|
77
|
-
|
|
106
|
+
try {
|
|
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 });
|
|
116
|
+
const result = await client.complete({
|
|
117
|
+
provider: pool.providerName,
|
|
118
|
+
model: fields.model,
|
|
119
|
+
messages: [{ role: "user", content: fields.prompt }],
|
|
120
|
+
temperature: fields.temperature,
|
|
121
|
+
maxTokens: fields.maxTokens,
|
|
122
|
+
signal: req.signal,
|
|
123
|
+
});
|
|
124
|
+
return Response.json({
|
|
125
|
+
id: `cmpl-${Date.now()}`,
|
|
126
|
+
choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (options.onError) {
|
|
131
|
+
await options.onError(error, {
|
|
132
|
+
request: req,
|
|
133
|
+
phase: isRequestPhaseError(error) ? "request" : "provider",
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return errorResponse(error);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async function dispose() {
|
|
140
|
+
await pool.dispose();
|
|
78
141
|
}
|
|
79
|
-
return { POST };
|
|
142
|
+
return { POST, dispose };
|
|
80
143
|
}
|
|
@@ -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;
|
|
@@ -5,14 +5,12 @@
|
|
|
5
5
|
* Uses the HilbrasClient to generate streaming responses with full protocol support.
|
|
6
6
|
*/
|
|
7
7
|
import type { Tool } from "../../types/tools.js";
|
|
8
|
+
import { type FrameworkHandlerBaseOptions } from "../shared/handler-core.js";
|
|
8
9
|
export interface ChatMessage {
|
|
9
10
|
role: "user" | "assistant" | "system";
|
|
10
11
|
content: string;
|
|
11
12
|
}
|
|
12
|
-
export interface ActionOptions {
|
|
13
|
-
provider: string;
|
|
14
|
-
model: string;
|
|
15
|
-
systemPrompt?: string;
|
|
13
|
+
export interface ActionOptions extends FrameworkHandlerBaseOptions {
|
|
16
14
|
tools?: Tool[];
|
|
17
15
|
maxSteps?: number;
|
|
18
16
|
}
|
|
@@ -22,20 +20,24 @@ export interface ActionOptions {
|
|
|
22
20
|
* @example
|
|
23
21
|
* ```ts
|
|
24
22
|
* // app/routes/api.chat.ts
|
|
25
|
-
* import { createChatAction } from "@hilbras/remix";
|
|
23
|
+
* import { createChatAction } from "@hilbras/sdk/remix";
|
|
26
24
|
*
|
|
27
25
|
* export const action = createChatAction({
|
|
28
|
-
* provider: "
|
|
26
|
+
* provider: "openai",
|
|
29
27
|
* model: "gpt-4o",
|
|
30
28
|
* });
|
|
31
29
|
* ```
|
|
32
30
|
*/
|
|
33
|
-
export declare function createChatAction(options: ActionOptions): ({ request }: {
|
|
31
|
+
export declare function createChatAction(options: ActionOptions): (({ request }: {
|
|
34
32
|
request: Request;
|
|
35
|
-
}) => Promise<Response
|
|
33
|
+
}) => Promise<Response>) & {
|
|
34
|
+
dispose: () => Promise<void>;
|
|
35
|
+
};
|
|
36
36
|
/**
|
|
37
37
|
* Create a non-streaming completion action for Remix.
|
|
38
38
|
*/
|
|
39
|
-
export declare function createCompletionAction(options: ActionOptions): ({ request }: {
|
|
39
|
+
export declare function createCompletionAction(options: ActionOptions): (({ request }: {
|
|
40
40
|
request: Request;
|
|
41
|
-
}) => Promise<Response
|
|
41
|
+
}) => Promise<Response>) & {
|
|
42
|
+
dispose: () => Promise<void>;
|
|
43
|
+
};
|