@umituz/web-ai 1.0.11 → 1.2.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 +29 -3
- package/dist/{cancellation-error-_39nYWwz.d.cts → cancellation-error-BWb59Wkj.d.cts} +1 -1
- package/dist/{cancellation-error-hYcE9AS9.d.ts → cancellation-error-D9LETLCD.d.ts} +1 -1
- package/dist/chat/index.cjs +1 -0
- package/dist/chat/index.cjs.map +1 -1
- package/dist/chat/index.js +1 -0
- package/dist/chat/index.js.map +1 -1
- package/dist/content/index.cjs +622 -8
- package/dist/content/index.cjs.map +1 -1
- package/dist/content/index.d.cts +2 -2
- package/dist/content/index.d.ts +2 -2
- package/dist/content/index.js +622 -8
- package/dist/content/index.js.map +1 -1
- package/dist/context-manager-CuZz0vnC.d.cts +104 -0
- package/dist/context-manager-CuZz0vnC.d.ts +104 -0
- package/dist/core/index.cjs +147 -10
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +91 -73
- package/dist/core/index.d.ts +91 -73
- package/dist/core/index.js +141 -11
- package/dist/core/index.js.map +1 -1
- package/dist/{create-ai-D-oEWzf9.d.ts → create-ai-Cq3HkJxd.d.ts} +61 -1
- package/dist/{create-ai-DRysRImc.d.cts → create-ai-DDyTVzef.d.cts} +61 -1
- package/dist/hooks/index.cjs +747 -15
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +57 -4
- package/dist/hooks/index.d.ts +57 -4
- package/dist/hooks/index.js +746 -16
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +1180 -242
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -6
- package/dist/index.d.ts +7 -6
- package/dist/index.js +1140 -243
- package/dist/index.js.map +1 -1
- package/dist/providers/index.cjs +1212 -362
- package/dist/providers/index.cjs.map +1 -1
- package/dist/providers/index.d.cts +422 -10
- package/dist/providers/index.d.ts +422 -10
- package/dist/providers/index.js +1179 -363
- package/dist/providers/index.js.map +1 -1
- package/dist/remote-chat-client-LrNlew4n.d.cts +70 -0
- package/dist/remote-chat-client-LrNlew4n.d.ts +70 -0
- package/dist/{requestQueue-D89wx91Q.d.cts → requestQueue--h2uZ-Q3.d.cts} +1 -1
- package/dist/{requestQueue-AP6n_bRH.d.ts → requestQueue-BGeCy4Fd.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/tool-call-accumulator-C7KhaXZA.d.cts +0 -69
- package/dist/tool-call-accumulator-C7KhaXZA.d.ts +0 -69
package/dist/content/index.js
CHANGED
|
@@ -696,6 +696,68 @@ async function extractErrorMessageFromResponse(response) {
|
|
|
696
696
|
return buildHttpStatusFallback(response.status, response.statusText);
|
|
697
697
|
}
|
|
698
698
|
|
|
699
|
+
// src/core/errors/unified-ai-error.ts
|
|
700
|
+
var STATUS_TO_CODE = {
|
|
701
|
+
400: "invalid_request",
|
|
702
|
+
401: "invalid_key",
|
|
703
|
+
403: "invalid_key",
|
|
704
|
+
404: "model_unavailable",
|
|
705
|
+
413: "invalid_request",
|
|
706
|
+
422: "invalid_request",
|
|
707
|
+
429: "rate_limited",
|
|
708
|
+
500: "upstream_error",
|
|
709
|
+
502: "upstream_error",
|
|
710
|
+
503: "capacity",
|
|
711
|
+
504: "timeout"
|
|
712
|
+
};
|
|
713
|
+
var CODE_MESSAGES = {
|
|
714
|
+
invalid_key: "The provider rejected the configured API key.",
|
|
715
|
+
missing_key: "The provider is not configured with an API key.",
|
|
716
|
+
rate_limited: "The provider rate limit was reached. Try again shortly.",
|
|
717
|
+
capacity: "The provider is temporarily at capacity. Try again shortly.",
|
|
718
|
+
timeout: "The model took too long to respond.",
|
|
719
|
+
invalid_request: "The request was rejected by the provider.",
|
|
720
|
+
model_unavailable: "The requested model is not available.",
|
|
721
|
+
upstream_error: "The provider returned an unexpected error.",
|
|
722
|
+
network: "Could not reach the provider.",
|
|
723
|
+
cancelled: "Generation was cancelled."
|
|
724
|
+
};
|
|
725
|
+
var AiError = class extends Error {
|
|
726
|
+
code;
|
|
727
|
+
constructor(code, message) {
|
|
728
|
+
super(message ?? CODE_MESSAGES[code]);
|
|
729
|
+
this.name = "AiError";
|
|
730
|
+
this.code = code;
|
|
731
|
+
}
|
|
732
|
+
get userMessage() {
|
|
733
|
+
return this.message;
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
function isApiKeyRejection(provider) {
|
|
737
|
+
if (provider.code === "invalid_api_key") return true;
|
|
738
|
+
return provider.type === void 0;
|
|
739
|
+
}
|
|
740
|
+
function errorFromStatus(status, detail, provider) {
|
|
741
|
+
let code = STATUS_TO_CODE[status] ?? "upstream_error";
|
|
742
|
+
if (status === 403 && provider && !isApiKeyRejection(provider)) {
|
|
743
|
+
code = "model_unavailable";
|
|
744
|
+
}
|
|
745
|
+
return new AiError(code, detail ? `${CODE_MESSAGES[code]} (${detail})` : void 0);
|
|
746
|
+
}
|
|
747
|
+
function errorFromUnknown(err) {
|
|
748
|
+
if (err instanceof AiError) return err;
|
|
749
|
+
if (err instanceof Error) {
|
|
750
|
+
if (err.name === "TimeoutError" || err.name === "AbortError") {
|
|
751
|
+
return new AiError("timeout");
|
|
752
|
+
}
|
|
753
|
+
if (err.name === "TypeError") {
|
|
754
|
+
return new AiError("network");
|
|
755
|
+
}
|
|
756
|
+
return new AiError("upstream_error", err.message);
|
|
757
|
+
}
|
|
758
|
+
return new AiError("upstream_error");
|
|
759
|
+
}
|
|
760
|
+
|
|
699
761
|
// src/providers/base/provider.types.ts
|
|
700
762
|
function isTextProvider(provider) {
|
|
701
763
|
return provider.capabilities.includes("text");
|
|
@@ -1450,7 +1512,7 @@ var AnthropicProvider = class {
|
|
|
1450
1512
|
);
|
|
1451
1513
|
}
|
|
1452
1514
|
const structuredPrompt = new StructuredPromptBuilder(
|
|
1453
|
-
messages[lastUserIndex]
|
|
1515
|
+
messages[lastUserIndex]?.content ?? ""
|
|
1454
1516
|
).withSchema(request.schema).build();
|
|
1455
1517
|
messages[lastUserIndex] = { role: "user", content: structuredPrompt };
|
|
1456
1518
|
const wireRequest = new AnthropicRequestBuilder(model).withRequest({ ...request, messages }).withEffort(this.config.effort).build();
|
|
@@ -1530,7 +1592,8 @@ function mapAnthropicUsage(usage) {
|
|
|
1530
1592
|
}
|
|
1531
1593
|
function findLastIndex(items, predicate) {
|
|
1532
1594
|
for (let i = items.length - 1; i >= 0; i--) {
|
|
1533
|
-
|
|
1595
|
+
const item = items[i];
|
|
1596
|
+
if (item !== void 0 && predicate(item)) return i;
|
|
1534
1597
|
}
|
|
1535
1598
|
return -1;
|
|
1536
1599
|
}
|
|
@@ -2375,7 +2438,7 @@ var GroqProvider = class {
|
|
|
2375
2438
|
);
|
|
2376
2439
|
}
|
|
2377
2440
|
const structuredPrompt = new StructuredPromptBuilder(
|
|
2378
|
-
messages[lastUserIndex]
|
|
2441
|
+
messages[lastUserIndex]?.content ?? ""
|
|
2379
2442
|
).withSchema(request.schema).build();
|
|
2380
2443
|
messages[lastUserIndex] = { role: "user", content: structuredPrompt };
|
|
2381
2444
|
const wireRequest = GroqChatRequestBuilder.for(model).withMessages(messages).withConfig(this.generationConfig(request, STRUCTURED_TEMPERATURE)).withJsonResponse(true).build();
|
|
@@ -2469,7 +2532,8 @@ function toGroqMessages(messages, systemPrompt) {
|
|
|
2469
2532
|
}
|
|
2470
2533
|
function findLastIndex2(items, predicate) {
|
|
2471
2534
|
for (let i = items.length - 1; i >= 0; i--) {
|
|
2472
|
-
|
|
2535
|
+
const item = items[i];
|
|
2536
|
+
if (item !== void 0 && predicate(item)) return i;
|
|
2473
2537
|
}
|
|
2474
2538
|
return -1;
|
|
2475
2539
|
}
|
|
@@ -2647,7 +2711,7 @@ var GeminiProvider = class extends BaseProvider {
|
|
|
2647
2711
|
}
|
|
2648
2712
|
messages[lastUserIndex] = {
|
|
2649
2713
|
role: "user",
|
|
2650
|
-
content: new StructuredPromptBuilder(messages[lastUserIndex]
|
|
2714
|
+
content: new StructuredPromptBuilder(messages[lastUserIndex]?.content ?? "").withSchema(request.schema).build()
|
|
2651
2715
|
};
|
|
2652
2716
|
const result = await this.generate({ ...request, messages, temperature: 0.1 });
|
|
2653
2717
|
return { value: this.jsonParser.parse(result.text), result };
|
|
@@ -2753,7 +2817,8 @@ function mapGeminiFinishReason(reason) {
|
|
|
2753
2817
|
}
|
|
2754
2818
|
function findLastIndex3(items, predicate) {
|
|
2755
2819
|
for (let i = items.length - 1; i >= 0; i--) {
|
|
2756
|
-
|
|
2820
|
+
const item = items[i];
|
|
2821
|
+
if (item !== void 0 && predicate(item)) return i;
|
|
2757
2822
|
}
|
|
2758
2823
|
return -1;
|
|
2759
2824
|
}
|
|
@@ -3815,6 +3880,546 @@ var PrunaProvider = class {
|
|
|
3815
3880
|
}
|
|
3816
3881
|
};
|
|
3817
3882
|
|
|
3883
|
+
// src/core/sse/tool-call-accumulator.ts
|
|
3884
|
+
var ToolCallAccumulator = class {
|
|
3885
|
+
slots = /* @__PURE__ */ new Map();
|
|
3886
|
+
push(delta) {
|
|
3887
|
+
const index = delta.index ?? 0;
|
|
3888
|
+
const slot = this.slots.get(index) ?? { id: "", name: "", args: "" };
|
|
3889
|
+
if (delta.id) slot.id = delta.id;
|
|
3890
|
+
if (delta.function?.name) slot.name = delta.function.name;
|
|
3891
|
+
if (delta.function?.arguments) slot.args += delta.function.arguments;
|
|
3892
|
+
this.slots.set(index, slot);
|
|
3893
|
+
}
|
|
3894
|
+
finish() {
|
|
3895
|
+
return Array.from(this.slots.entries()).sort(([a], [b]) => a - b).map(([, slot]) => ({
|
|
3896
|
+
id: slot.id,
|
|
3897
|
+
name: slot.name,
|
|
3898
|
+
arguments: slot.args
|
|
3899
|
+
})).filter((call) => call.id.length > 0 || call.name.length > 0);
|
|
3900
|
+
}
|
|
3901
|
+
};
|
|
3902
|
+
|
|
3903
|
+
// src/providers/adapters/openai-compatible.adapter.ts
|
|
3904
|
+
function toWireMessage(message) {
|
|
3905
|
+
if (message.role === "tool") {
|
|
3906
|
+
return { role: "tool", content: message.content, tool_call_id: message.toolCallId ?? "" };
|
|
3907
|
+
}
|
|
3908
|
+
if (message.role === "assistant" && message.toolCalls && message.toolCalls.length > 0) {
|
|
3909
|
+
return {
|
|
3910
|
+
role: "assistant",
|
|
3911
|
+
content: message.content,
|
|
3912
|
+
tool_calls: message.toolCalls.map((call) => ({
|
|
3913
|
+
id: call.id,
|
|
3914
|
+
type: "function",
|
|
3915
|
+
function: { name: call.name, arguments: call.arguments }
|
|
3916
|
+
}))
|
|
3917
|
+
};
|
|
3918
|
+
}
|
|
3919
|
+
if (message.role === "user") return { role: "user", content: message.content };
|
|
3920
|
+
return { role: message.role, content: message.content };
|
|
3921
|
+
}
|
|
3922
|
+
function mergeImages(messages, images) {
|
|
3923
|
+
if (images.length === 0) return [...messages];
|
|
3924
|
+
const parts = images.map((image) => ({
|
|
3925
|
+
type: "image_url",
|
|
3926
|
+
image_url: { url: `data:${image.mimeType};base64,${image.dataBase64}` }
|
|
3927
|
+
}));
|
|
3928
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
3929
|
+
const message = messages[index];
|
|
3930
|
+
if (!message || message.role !== "user") continue;
|
|
3931
|
+
const textParts = typeof message.content === "string" ? message.content.length > 0 ? [{ type: "text", text: message.content }] : [] : message.content;
|
|
3932
|
+
return [
|
|
3933
|
+
...messages.slice(0, index),
|
|
3934
|
+
{ role: "user", content: [...textParts, ...parts] },
|
|
3935
|
+
...messages.slice(index + 1)
|
|
3936
|
+
];
|
|
3937
|
+
}
|
|
3938
|
+
return [...messages, { role: "user", content: [...parts] }];
|
|
3939
|
+
}
|
|
3940
|
+
async function extractErrorDetail(response) {
|
|
3941
|
+
try {
|
|
3942
|
+
const body = await response.json();
|
|
3943
|
+
return body.error;
|
|
3944
|
+
} catch {
|
|
3945
|
+
return void 0;
|
|
3946
|
+
}
|
|
3947
|
+
}
|
|
3948
|
+
async function* parseSseEvent(rawEvent, toolCallAccumulator) {
|
|
3949
|
+
for (const line of rawEvent.split("\n")) {
|
|
3950
|
+
if (!line.startsWith("data:")) continue;
|
|
3951
|
+
const payload = line.slice(5).trim();
|
|
3952
|
+
if (payload.length === 0 || payload === "[DONE]") continue;
|
|
3953
|
+
let chunk;
|
|
3954
|
+
try {
|
|
3955
|
+
chunk = JSON.parse(payload);
|
|
3956
|
+
} catch {
|
|
3957
|
+
continue;
|
|
3958
|
+
}
|
|
3959
|
+
const delta = chunk.choices?.[0]?.delta;
|
|
3960
|
+
if (delta?.reasoning) {
|
|
3961
|
+
yield { type: "delta", channel: "reasoning", text: delta.reasoning };
|
|
3962
|
+
}
|
|
3963
|
+
if (delta?.content) {
|
|
3964
|
+
yield { type: "delta", channel: "answer", text: delta.content };
|
|
3965
|
+
}
|
|
3966
|
+
if (delta?.tool_calls) {
|
|
3967
|
+
for (const toolCallDelta of delta.tool_calls) toolCallAccumulator.push(toolCallDelta);
|
|
3968
|
+
}
|
|
3969
|
+
if (chunk.usage) {
|
|
3970
|
+
yield {
|
|
3971
|
+
type: "usage",
|
|
3972
|
+
usage: {
|
|
3973
|
+
inputTokens: chunk.usage.prompt_tokens ?? 0,
|
|
3974
|
+
outputTokens: chunk.usage.completion_tokens ?? 0,
|
|
3975
|
+
reasoningTokens: chunk.usage.completion_tokens_details?.reasoning_tokens
|
|
3976
|
+
}
|
|
3977
|
+
};
|
|
3978
|
+
}
|
|
3979
|
+
}
|
|
3980
|
+
}
|
|
3981
|
+
async function* parseSseStream(body) {
|
|
3982
|
+
const reader = body.getReader();
|
|
3983
|
+
const decoder = new TextDecoder();
|
|
3984
|
+
const toolCallAccumulator = new ToolCallAccumulator();
|
|
3985
|
+
let buffer = "";
|
|
3986
|
+
try {
|
|
3987
|
+
while (true) {
|
|
3988
|
+
const { done, value } = await reader.read();
|
|
3989
|
+
if (done) break;
|
|
3990
|
+
buffer += decoder.decode(value, { stream: true });
|
|
3991
|
+
let separator = buffer.indexOf("\n\n");
|
|
3992
|
+
while (separator !== -1) {
|
|
3993
|
+
const rawEvent = buffer.slice(0, separator);
|
|
3994
|
+
buffer = buffer.slice(separator + 2);
|
|
3995
|
+
separator = buffer.indexOf("\n\n");
|
|
3996
|
+
yield* parseSseEvent(rawEvent, toolCallAccumulator);
|
|
3997
|
+
}
|
|
3998
|
+
}
|
|
3999
|
+
} catch (err) {
|
|
4000
|
+
throw errorFromUnknown(err);
|
|
4001
|
+
} finally {
|
|
4002
|
+
reader.releaseLock();
|
|
4003
|
+
}
|
|
4004
|
+
const calls = toolCallAccumulator.finish();
|
|
4005
|
+
if (calls.length > 0) yield { type: "tool_calls", calls };
|
|
4006
|
+
}
|
|
4007
|
+
function createOpenAiCompatibleAdapter(config) {
|
|
4008
|
+
if (!config.baseUrl && !config.endpointUrl) {
|
|
4009
|
+
throw new Error("createOpenAiCompatibleAdapter requires baseUrl or endpointUrl");
|
|
4010
|
+
}
|
|
4011
|
+
const endpoint = config.endpointUrl ?? `${config.baseUrl}/chat/completions`;
|
|
4012
|
+
return {
|
|
4013
|
+
async *stream(req) {
|
|
4014
|
+
const timeout = AbortSignal.timeout(config.timeoutMs);
|
|
4015
|
+
const signal = req.signal ? AbortSignal.any([req.signal, timeout]) : timeout;
|
|
4016
|
+
let response;
|
|
4017
|
+
try {
|
|
4018
|
+
response = await fetch(endpoint, {
|
|
4019
|
+
method: "POST",
|
|
4020
|
+
headers: {
|
|
4021
|
+
Authorization: `Bearer ${config.apiKey}`,
|
|
4022
|
+
"Content-Type": "application/json"
|
|
4023
|
+
},
|
|
4024
|
+
body: JSON.stringify({
|
|
4025
|
+
model: req.externalModelId,
|
|
4026
|
+
messages: mergeImages(req.messages.map(toWireMessage), req.images ?? []),
|
|
4027
|
+
temperature: req.temperature,
|
|
4028
|
+
max_completion_tokens: req.maxOutputTokens,
|
|
4029
|
+
top_p: req.topP,
|
|
4030
|
+
stream: true,
|
|
4031
|
+
stream_options: { include_usage: true },
|
|
4032
|
+
...req.tools && req.tools.length > 0 ? {
|
|
4033
|
+
tools: req.tools.map((tool) => ({ type: "function", function: tool })),
|
|
4034
|
+
tool_choice: "auto"
|
|
4035
|
+
} : {}
|
|
4036
|
+
}),
|
|
4037
|
+
signal
|
|
4038
|
+
});
|
|
4039
|
+
} catch (err) {
|
|
4040
|
+
throw errorFromUnknown(err);
|
|
4041
|
+
}
|
|
4042
|
+
if (!response.ok || !response.body) {
|
|
4043
|
+
const detail = await extractErrorDetail(response);
|
|
4044
|
+
throw errorFromStatus(response.status, detail?.message, detail);
|
|
4045
|
+
}
|
|
4046
|
+
yield* parseSseStream(response.body);
|
|
4047
|
+
}
|
|
4048
|
+
};
|
|
4049
|
+
}
|
|
4050
|
+
|
|
4051
|
+
// src/providers/openai-compatible/openai-compatible.provider.ts
|
|
4052
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
4053
|
+
var STRUCTURED_TEMPERATURE2 = 0.1;
|
|
4054
|
+
var OpenAiCompatibleProvider = class {
|
|
4055
|
+
constructor(config) {
|
|
4056
|
+
this.config = config;
|
|
4057
|
+
if (!config.baseUrl && !config.endpointUrl) {
|
|
4058
|
+
throw new AIError(
|
|
4059
|
+
"MISSING_CONFIG" /* MISSING_CONFIG */,
|
|
4060
|
+
"OpenAiCompatibleProvider requires baseUrl or endpointUrl"
|
|
4061
|
+
);
|
|
4062
|
+
}
|
|
4063
|
+
this.adapter = createOpenAiCompatibleAdapter({
|
|
4064
|
+
baseUrl: config.baseUrl,
|
|
4065
|
+
endpointUrl: config.endpointUrl,
|
|
4066
|
+
apiKey: config.apiKey,
|
|
4067
|
+
timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
4068
|
+
});
|
|
4069
|
+
this.tiers = mergeTierOverrides(
|
|
4070
|
+
config.model ? { fast: config.model, balanced: config.model, powerful: config.model } : {},
|
|
4071
|
+
config.models
|
|
4072
|
+
);
|
|
4073
|
+
}
|
|
4074
|
+
config;
|
|
4075
|
+
id = "openai-compatible";
|
|
4076
|
+
name = "OpenAI-compatible";
|
|
4077
|
+
capabilities = ["text"];
|
|
4078
|
+
adapter;
|
|
4079
|
+
tiers;
|
|
4080
|
+
jsonParser = new JsonResponseParser();
|
|
4081
|
+
resolveModel(tier) {
|
|
4082
|
+
return resolveModel(this.tiers, tier, this.id);
|
|
4083
|
+
}
|
|
4084
|
+
async healthCheck() {
|
|
4085
|
+
return this.config.apiKey && (this.config.baseUrl || this.config.endpointUrl) ? "healthy" : "unavailable";
|
|
4086
|
+
}
|
|
4087
|
+
async estimateCost() {
|
|
4088
|
+
return 0;
|
|
4089
|
+
}
|
|
4090
|
+
async generate(request) {
|
|
4091
|
+
const model = this.modelFor(request);
|
|
4092
|
+
const outcome = await this.consume(this.toAdapterRequest(model, request));
|
|
4093
|
+
if (outcome.text.length === 0) {
|
|
4094
|
+
throw this.noContentError(model);
|
|
4095
|
+
}
|
|
4096
|
+
return {
|
|
4097
|
+
text: outcome.text,
|
|
4098
|
+
usage: outcome.usage,
|
|
4099
|
+
model,
|
|
4100
|
+
providerId: this.id,
|
|
4101
|
+
finishReason: "stop"
|
|
4102
|
+
};
|
|
4103
|
+
}
|
|
4104
|
+
async generateStructured(request) {
|
|
4105
|
+
const model = this.modelFor(request);
|
|
4106
|
+
const messages = this.toWireMessages(request.messages, request.systemPrompt);
|
|
4107
|
+
const lastUserIndex = findLastIndex4(messages, (m) => m.role === "user");
|
|
4108
|
+
if (lastUserIndex === -1) {
|
|
4109
|
+
throw new AIError(
|
|
4110
|
+
"UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
|
|
4111
|
+
"generateStructured requires at least one user message"
|
|
4112
|
+
);
|
|
4113
|
+
}
|
|
4114
|
+
const structuredPrompt = new StructuredPromptBuilder(
|
|
4115
|
+
messages[lastUserIndex]?.content ?? ""
|
|
4116
|
+
).withSchema(request.schema).build();
|
|
4117
|
+
messages[lastUserIndex] = { role: "user", content: structuredPrompt };
|
|
4118
|
+
const outcome = await this.consume({
|
|
4119
|
+
externalModelId: model,
|
|
4120
|
+
messages,
|
|
4121
|
+
temperature: STRUCTURED_TEMPERATURE2,
|
|
4122
|
+
signal: request.signal
|
|
4123
|
+
});
|
|
4124
|
+
if (outcome.text.length === 0) {
|
|
4125
|
+
throw this.noContentError(model);
|
|
4126
|
+
}
|
|
4127
|
+
return {
|
|
4128
|
+
value: this.jsonParser.parse(outcome.text),
|
|
4129
|
+
result: {
|
|
4130
|
+
text: outcome.text,
|
|
4131
|
+
usage: outcome.usage,
|
|
4132
|
+
model,
|
|
4133
|
+
providerId: this.id,
|
|
4134
|
+
finishReason: "stop"
|
|
4135
|
+
}
|
|
4136
|
+
};
|
|
4137
|
+
}
|
|
4138
|
+
async stream(request, callbacks) {
|
|
4139
|
+
const model = this.modelFor(request);
|
|
4140
|
+
try {
|
|
4141
|
+
const outcome = await this.consume(this.toAdapterRequest(model, request), (text) => {
|
|
4142
|
+
callbacks.onChunk?.(text);
|
|
4143
|
+
});
|
|
4144
|
+
if (outcome.text.length === 0) {
|
|
4145
|
+
throw this.noContentError(model);
|
|
4146
|
+
}
|
|
4147
|
+
const result = {
|
|
4148
|
+
text: outcome.text,
|
|
4149
|
+
usage: outcome.usage,
|
|
4150
|
+
model,
|
|
4151
|
+
providerId: this.id,
|
|
4152
|
+
finishReason: "stop"
|
|
4153
|
+
};
|
|
4154
|
+
callbacks.onComplete?.(result);
|
|
4155
|
+
return result;
|
|
4156
|
+
} catch (error) {
|
|
4157
|
+
callbacks.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
4158
|
+
throw error;
|
|
4159
|
+
}
|
|
4160
|
+
}
|
|
4161
|
+
/* ---------- internals ---------- */
|
|
4162
|
+
/** Drain one adapter stream to its end. `onChunk`, when given, sees answer
|
|
4163
|
+
* deltas as they arrive — the streaming surface is this same drain. */
|
|
4164
|
+
async consume(req, onChunk) {
|
|
4165
|
+
let text = "";
|
|
4166
|
+
let usage;
|
|
4167
|
+
for await (const event of this.adapter.stream(req)) {
|
|
4168
|
+
if (event.type === "delta" && event.channel === "answer") {
|
|
4169
|
+
text += event.text;
|
|
4170
|
+
onChunk?.(event.text);
|
|
4171
|
+
} else if (event.type === "usage") {
|
|
4172
|
+
usage = event.usage;
|
|
4173
|
+
}
|
|
4174
|
+
}
|
|
4175
|
+
return { text, usage };
|
|
4176
|
+
}
|
|
4177
|
+
modelFor(request) {
|
|
4178
|
+
return request.model ?? this.resolveModel(request.tier ?? "balanced");
|
|
4179
|
+
}
|
|
4180
|
+
noContentError(model) {
|
|
4181
|
+
return new AIError(
|
|
4182
|
+
"SERVER_ERROR" /* SERVER_ERROR */,
|
|
4183
|
+
"No content generated from the OpenAI-compatible endpoint",
|
|
4184
|
+
void 0,
|
|
4185
|
+
{ model }
|
|
4186
|
+
);
|
|
4187
|
+
}
|
|
4188
|
+
toAdapterRequest(model, request) {
|
|
4189
|
+
return {
|
|
4190
|
+
externalModelId: model,
|
|
4191
|
+
messages: this.toWireMessages(request.messages, request.systemPrompt),
|
|
4192
|
+
...request.temperature !== void 0 ? { temperature: request.temperature } : {},
|
|
4193
|
+
...request.maxTokens !== void 0 ? { maxOutputTokens: request.maxTokens } : {},
|
|
4194
|
+
...request.topP !== void 0 ? { topP: request.topP } : {},
|
|
4195
|
+
...request.signal ? { signal: request.signal } : {}
|
|
4196
|
+
};
|
|
4197
|
+
}
|
|
4198
|
+
/** Neutral messages onto the adapter's shape; systemPrompt becomes the
|
|
4199
|
+
* leading system message (in-band, the OpenAI way). */
|
|
4200
|
+
toWireMessages(messages, systemPrompt) {
|
|
4201
|
+
const wire = [];
|
|
4202
|
+
if (systemPrompt && systemPrompt.length > 0) {
|
|
4203
|
+
wire.push({ role: "system", content: systemPrompt });
|
|
4204
|
+
}
|
|
4205
|
+
for (const message of messages) {
|
|
4206
|
+
wire.push({ role: message.role, content: message.content });
|
|
4207
|
+
}
|
|
4208
|
+
return wire;
|
|
4209
|
+
}
|
|
4210
|
+
};
|
|
4211
|
+
function findLastIndex4(items, predicate) {
|
|
4212
|
+
for (let index = items.length - 1; index >= 0; index -= 1) {
|
|
4213
|
+
if (predicate(items[index])) return index;
|
|
4214
|
+
}
|
|
4215
|
+
return -1;
|
|
4216
|
+
}
|
|
4217
|
+
|
|
4218
|
+
// src/providers/workers-ai/workers-ai.entities.ts
|
|
4219
|
+
var WorkersAIError = class extends Error {
|
|
4220
|
+
status;
|
|
4221
|
+
constructor(message, status) {
|
|
4222
|
+
super(message);
|
|
4223
|
+
this.name = "WorkersAIError";
|
|
4224
|
+
this.status = status;
|
|
4225
|
+
}
|
|
4226
|
+
};
|
|
4227
|
+
|
|
4228
|
+
// src/providers/workers-ai/workers-ai.text.ts
|
|
4229
|
+
var WORKERS_AI_LLM_MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
|
|
4230
|
+
var WORKERS_AI_TEXT_TIMEOUT_MS = 25e3;
|
|
4231
|
+
function requireAi(env) {
|
|
4232
|
+
const ai = env.AI;
|
|
4233
|
+
if (!ai || typeof ai.run !== "function") throw new WorkersAIError("Workers AI is not configured");
|
|
4234
|
+
return ai;
|
|
4235
|
+
}
|
|
4236
|
+
async function runWorkersAIText(env, messages, opts = {}) {
|
|
4237
|
+
const ai = requireAi(env);
|
|
4238
|
+
const model = opts.model ?? WORKERS_AI_LLM_MODEL;
|
|
4239
|
+
let result;
|
|
4240
|
+
try {
|
|
4241
|
+
result = await Promise.race([
|
|
4242
|
+
ai.run(model, {
|
|
4243
|
+
messages: messages.map((m) => ({ role: m.role, content: m.content })),
|
|
4244
|
+
max_tokens: opts.maxTokens ?? 900,
|
|
4245
|
+
temperature: opts.temperature ?? 0.7
|
|
4246
|
+
}),
|
|
4247
|
+
new Promise(
|
|
4248
|
+
(_, reject) => setTimeout(() => reject(new WorkersAIError("Workers AI timed out")), WORKERS_AI_TEXT_TIMEOUT_MS)
|
|
4249
|
+
)
|
|
4250
|
+
]);
|
|
4251
|
+
} catch (err) {
|
|
4252
|
+
throw err instanceof WorkersAIError ? err : new WorkersAIError(err instanceof Error ? err.message : "Workers AI request failed");
|
|
4253
|
+
}
|
|
4254
|
+
const response = result ?? {};
|
|
4255
|
+
let text = response.response;
|
|
4256
|
+
if (typeof text !== "string" || text.length === 0) {
|
|
4257
|
+
text = response.choices?.[0]?.message?.content;
|
|
4258
|
+
}
|
|
4259
|
+
if (typeof text !== "string" || text.length === 0) {
|
|
4260
|
+
throw new WorkersAIError("Workers AI returned no text");
|
|
4261
|
+
}
|
|
4262
|
+
return text;
|
|
4263
|
+
}
|
|
4264
|
+
async function* streamWorkersAIText(env, messages, opts = {}) {
|
|
4265
|
+
const ai = requireAi(env);
|
|
4266
|
+
const model = opts.model ?? WORKERS_AI_LLM_MODEL;
|
|
4267
|
+
let body;
|
|
4268
|
+
try {
|
|
4269
|
+
body = await Promise.race([
|
|
4270
|
+
ai.run(model, {
|
|
4271
|
+
messages: messages.map((m) => ({ role: m.role, content: m.content })),
|
|
4272
|
+
stream: true,
|
|
4273
|
+
max_tokens: opts.maxTokens ?? 600,
|
|
4274
|
+
temperature: opts.temperature ?? 0.7
|
|
4275
|
+
}),
|
|
4276
|
+
new Promise(
|
|
4277
|
+
(_, reject) => setTimeout(() => reject(new WorkersAIError("Workers AI timed out")), WORKERS_AI_TEXT_TIMEOUT_MS)
|
|
4278
|
+
)
|
|
4279
|
+
]);
|
|
4280
|
+
} catch (err) {
|
|
4281
|
+
throw err instanceof WorkersAIError ? err : new WorkersAIError(err instanceof Error ? err.message : "Workers AI request failed");
|
|
4282
|
+
}
|
|
4283
|
+
const stream = body;
|
|
4284
|
+
const getReader = typeof stream === "object" && stream !== null && "getReader" in stream && typeof stream.getReader === "function" ? stream.getReader : void 0;
|
|
4285
|
+
if (!getReader) throw new WorkersAIError("Workers AI stream was not readable");
|
|
4286
|
+
const reader = getReader.call(stream);
|
|
4287
|
+
const decoder = new TextDecoder();
|
|
4288
|
+
let buffer = "";
|
|
4289
|
+
try {
|
|
4290
|
+
for (; ; ) {
|
|
4291
|
+
const { done, value } = await reader.read();
|
|
4292
|
+
if (done) break;
|
|
4293
|
+
buffer += decoder.decode(value, { stream: true });
|
|
4294
|
+
let newlineAt;
|
|
4295
|
+
while ((newlineAt = buffer.indexOf("\n")) !== -1) {
|
|
4296
|
+
let line = buffer.slice(0, newlineAt);
|
|
4297
|
+
buffer = buffer.slice(newlineAt + 1);
|
|
4298
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
4299
|
+
if (line.startsWith(":") || line.trim() === "") continue;
|
|
4300
|
+
if (!line.startsWith("data: ")) continue;
|
|
4301
|
+
const payload = line.slice(6).trim();
|
|
4302
|
+
if (payload === "[DONE]") return;
|
|
4303
|
+
try {
|
|
4304
|
+
const parsed = JSON.parse(payload);
|
|
4305
|
+
if (typeof parsed.response === "string" && parsed.response.length > 0) yield parsed.response;
|
|
4306
|
+
} catch {
|
|
4307
|
+
buffer = `${line}
|
|
4308
|
+
${buffer}`;
|
|
4309
|
+
break;
|
|
4310
|
+
}
|
|
4311
|
+
}
|
|
4312
|
+
}
|
|
4313
|
+
} finally {
|
|
4314
|
+
reader.releaseLock();
|
|
4315
|
+
}
|
|
4316
|
+
}
|
|
4317
|
+
|
|
4318
|
+
// src/providers/workers-ai/workers-ai.provider.ts
|
|
4319
|
+
var WORKERS_AI_TIERS = {
|
|
4320
|
+
fast: "@cf/meta/llama-3.1-8b-instruct-fp8-fast",
|
|
4321
|
+
balanced: WORKERS_AI_LLM_MODEL,
|
|
4322
|
+
powerful: WORKERS_AI_LLM_MODEL
|
|
4323
|
+
};
|
|
4324
|
+
var WorkersAIProvider = class {
|
|
4325
|
+
id = "workers-ai";
|
|
4326
|
+
name = "Cloudflare Workers AI";
|
|
4327
|
+
capabilities = ["text"];
|
|
4328
|
+
binding;
|
|
4329
|
+
tiers;
|
|
4330
|
+
jsonParser = new JsonResponseParser();
|
|
4331
|
+
constructor(config) {
|
|
4332
|
+
this.binding = config.binding;
|
|
4333
|
+
this.tiers = mergeTierOverrides(WORKERS_AI_TIERS, config.models);
|
|
4334
|
+
}
|
|
4335
|
+
resolveModel(tier) {
|
|
4336
|
+
return resolveModel(this.tiers, tier, this.id);
|
|
4337
|
+
}
|
|
4338
|
+
async healthCheck() {
|
|
4339
|
+
return typeof this.binding?.run === "function" ? "healthy" : "unavailable";
|
|
4340
|
+
}
|
|
4341
|
+
/** Workers AI is allocation-priced (neurons per deployment), not per
|
|
4342
|
+
* request — there is no per-call cost to estimate. */
|
|
4343
|
+
async estimateCost(_request) {
|
|
4344
|
+
return 0;
|
|
4345
|
+
}
|
|
4346
|
+
async generate(request) {
|
|
4347
|
+
const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
|
|
4348
|
+
const messages = withSystemPrompt(request);
|
|
4349
|
+
try {
|
|
4350
|
+
const text = await runWorkersAIText(
|
|
4351
|
+
{ AI: this.binding },
|
|
4352
|
+
messages,
|
|
4353
|
+
{
|
|
4354
|
+
model,
|
|
4355
|
+
maxTokens: request.maxTokens,
|
|
4356
|
+
temperature: request.temperature
|
|
4357
|
+
}
|
|
4358
|
+
);
|
|
4359
|
+
return { text, model, providerId: this.id, finishReason: "stop" };
|
|
4360
|
+
} catch (error) {
|
|
4361
|
+
throw toAIError(error);
|
|
4362
|
+
}
|
|
4363
|
+
}
|
|
4364
|
+
async generateStructured(request) {
|
|
4365
|
+
const messages = [...request.messages];
|
|
4366
|
+
const lastUserIndex = findLastIndex5(messages, (m) => m.role === "user");
|
|
4367
|
+
if (lastUserIndex === -1) {
|
|
4368
|
+
throw new AIError("UNKNOWN_ERROR" /* UNKNOWN_ERROR */, "generateStructured requires at least one user message");
|
|
4369
|
+
}
|
|
4370
|
+
messages[lastUserIndex] = {
|
|
4371
|
+
role: "user",
|
|
4372
|
+
content: new StructuredPromptBuilder(messages[lastUserIndex]?.content ?? "").withSchema(request.schema).build()
|
|
4373
|
+
};
|
|
4374
|
+
const result = await this.generate({ ...request, messages, temperature: 0.1 });
|
|
4375
|
+
return { value: this.jsonParser.parse(result.text), result };
|
|
4376
|
+
}
|
|
4377
|
+
async stream(request, callbacks) {
|
|
4378
|
+
const model = request.model ?? this.resolveModel(request.tier ?? "balanced");
|
|
4379
|
+
const messages = withSystemPrompt(request);
|
|
4380
|
+
let text = "";
|
|
4381
|
+
try {
|
|
4382
|
+
for await (const chunk of streamWorkersAIText({ AI: this.binding }, messages, {
|
|
4383
|
+
model,
|
|
4384
|
+
maxTokens: request.maxTokens,
|
|
4385
|
+
temperature: request.temperature
|
|
4386
|
+
})) {
|
|
4387
|
+
text += chunk;
|
|
4388
|
+
callbacks.onChunk?.(chunk);
|
|
4389
|
+
}
|
|
4390
|
+
} catch (error) {
|
|
4391
|
+
const aiError = toAIError(error);
|
|
4392
|
+
callbacks.onError?.(aiError);
|
|
4393
|
+
throw aiError;
|
|
4394
|
+
}
|
|
4395
|
+
const result = { text, model, providerId: this.id, finishReason: "stop" };
|
|
4396
|
+
callbacks.onComplete?.(result);
|
|
4397
|
+
return result;
|
|
4398
|
+
}
|
|
4399
|
+
};
|
|
4400
|
+
function withSystemPrompt(request) {
|
|
4401
|
+
if (request.systemPrompt && request.systemPrompt.length > 0) {
|
|
4402
|
+
return [
|
|
4403
|
+
{ role: "system", content: request.systemPrompt },
|
|
4404
|
+
...request.messages.filter((m) => m.role !== "system")
|
|
4405
|
+
];
|
|
4406
|
+
}
|
|
4407
|
+
return request.messages;
|
|
4408
|
+
}
|
|
4409
|
+
function toAIError(error) {
|
|
4410
|
+
if (error instanceof AIError) return error;
|
|
4411
|
+
const message = error instanceof Error ? error.message : "Workers AI request failed";
|
|
4412
|
+
const type = error instanceof WorkersAIError && error.message.includes("not configured") ? "INVALID_API_KEY" /* INVALID_API_KEY */ : "SERVER_ERROR" /* SERVER_ERROR */;
|
|
4413
|
+
return new AIError(type, message, error instanceof Error ? error : void 0);
|
|
4414
|
+
}
|
|
4415
|
+
function findLastIndex5(items, predicate) {
|
|
4416
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
4417
|
+
const item = items[i];
|
|
4418
|
+
if (item !== void 0 && predicate(item)) return i;
|
|
4419
|
+
}
|
|
4420
|
+
return -1;
|
|
4421
|
+
}
|
|
4422
|
+
|
|
3818
4423
|
// src/providers/factory/create-ai.ts
|
|
3819
4424
|
function createAI(config = {}) {
|
|
3820
4425
|
const factory = new ProviderFactory({
|
|
@@ -3837,6 +4442,15 @@ function createAI(config = {}) {
|
|
|
3837
4442
|
if (config.pruna?.apiKey) {
|
|
3838
4443
|
factory.register(new PrunaProvider({ ...config.pruna, enabled: true }));
|
|
3839
4444
|
}
|
|
4445
|
+
const openaiCompatible = config.openaiCompatible;
|
|
4446
|
+
if (openaiCompatible?.apiKey && (openaiCompatible.baseUrl || openaiCompatible.endpointUrl)) {
|
|
4447
|
+
factory.register(
|
|
4448
|
+
new OpenAiCompatibleProvider({ ...openaiCompatible, apiKey: openaiCompatible.apiKey })
|
|
4449
|
+
);
|
|
4450
|
+
}
|
|
4451
|
+
if (config.workersAI?.binding) {
|
|
4452
|
+
factory.register(new WorkersAIProvider(config.workersAI));
|
|
4453
|
+
}
|
|
3840
4454
|
return factory;
|
|
3841
4455
|
}
|
|
3842
4456
|
|
|
@@ -4349,7 +4963,7 @@ async function batchRequest(requests, options = {}) {
|
|
|
4349
4963
|
errors.push(result.reason);
|
|
4350
4964
|
if (stopOnError) {
|
|
4351
4965
|
throw new Error(
|
|
4352
|
-
`Batch request failed: ${errors[0]
|
|
4966
|
+
`Batch request failed: ${errors[0]?.message}`
|
|
4353
4967
|
);
|
|
4354
4968
|
}
|
|
4355
4969
|
}
|
|
@@ -4811,7 +5425,7 @@ function safeJSONParse(text, fallback, onError) {
|
|
|
4811
5425
|
}
|
|
4812
5426
|
if (error instanceof SyntaxError) {
|
|
4813
5427
|
const positionMatch = error.message.match(/position (\d+)/);
|
|
4814
|
-
const position = positionMatch ? parseInt(positionMatch[1], 10) : -1;
|
|
5428
|
+
const position = positionMatch ? parseInt(positionMatch[1] ?? "", 10) : -1;
|
|
4815
5429
|
if (position > 0) {
|
|
4816
5430
|
const context = text.substring(Math.max(0, position - 50), position + 50);
|
|
4817
5431
|
onError?.(`JSON parse error at position ${position}: "${context}"`);
|