@omnicross/core 0.1.1 → 0.1.2
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/dist/ApiConverter.cjs +3 -778
- package/dist/ApiConverter.js +12 -751
- package/dist/{CompletionService-DtOF_War.d.cts → CompletionService-D3a47vdU.d.cts} +2 -1
- package/dist/{CompletionService-7fCmKAP3.d.ts → CompletionService-DdWaAxq0.d.ts} +2 -1
- package/dist/auth/GeminiCodeAssistProjectResolver.cjs +27 -60
- package/dist/auth/GeminiCodeAssistProjectResolver.js +5 -9
- package/dist/builtin-web-fetch-77JZUZGM.cjs +100 -0
- package/dist/builtin-web-fetch-IGLBX2XY.js +100 -0
- package/dist/chunk-2DCNB7DF.cjs +514 -0
- package/dist/chunk-2FEVTJWG.js +4400 -0
- package/dist/chunk-3MEACFK3.js +193 -0
- package/dist/chunk-3OPYJG76.cjs +266 -0
- package/dist/chunk-46RLHI7D.js +0 -0
- package/dist/chunk-46ZIFWYG.cjs +277 -0
- package/dist/chunk-4NBS6KPV.cjs +43 -0
- package/dist/chunk-4VAVYUZS.cjs +991 -0
- package/dist/chunk-5ERIZW3D.js +44 -0
- package/dist/chunk-5HTVET6E.js +514 -0
- package/dist/chunk-5ZQBEOMD.js +764 -0
- package/dist/chunk-6VIXXLMX.cjs +14 -0
- package/dist/chunk-745DV5FL.js +147 -0
- package/dist/chunk-74TMJA7Z.js +53 -0
- package/dist/chunk-7VU7V2E4.js +0 -0
- package/dist/chunk-7YN22L2H.cjs +87 -0
- package/dist/chunk-A2YMUCBT.cjs +105 -0
- package/dist/chunk-AQ5TNQB7.js +13 -0
- package/dist/chunk-AVYJ4YBN.js +58 -0
- package/dist/chunk-C72S6TTV.cjs +49 -0
- package/dist/chunk-C7PSERMH.js +87 -0
- package/dist/chunk-CDHS2QDC.js +179 -0
- package/dist/chunk-DK4A7DLE.js +266 -0
- package/dist/chunk-DRWHTIIZ.js +13 -0
- package/dist/chunk-DWKQZ2SK.cjs +254 -0
- package/dist/chunk-E3WHL7CO.js +14 -0
- package/dist/chunk-EYZYXJTJ.cjs +1 -0
- package/dist/chunk-FMOBD2OQ.js +39 -0
- package/dist/chunk-FTQ7IQUC.js +991 -0
- package/dist/chunk-FZ46M34D.cjs +1 -0
- package/dist/chunk-G2FUJNA2.cjs +193 -0
- package/dist/chunk-G2UTNSGU.js +277 -0
- package/dist/chunk-GBHYAGX3.cjs +26 -0
- package/dist/chunk-GMMT7RVN.cjs +39 -0
- package/dist/chunk-H5JUT3KV.js +105 -0
- package/dist/chunk-HQP3K7PU.cjs +431 -0
- package/dist/chunk-JO5NLTLY.js +46 -0
- package/dist/chunk-JWC6APFQ.js +23 -0
- package/dist/chunk-KUU2RNG6.cjs +46 -0
- package/dist/chunk-LKZJEL6E.cjs +124 -0
- package/dist/chunk-MNYKI4CI.js +94 -0
- package/dist/chunk-MZNPGW5Q.js +26 -0
- package/dist/chunk-N3V2J5ZO.cjs +53 -0
- package/dist/chunk-NYUNU75A.cjs +44 -0
- package/dist/chunk-NZYN7C3P.cjs +179 -0
- package/dist/chunk-O466Y272.js +235 -0
- package/dist/chunk-PXUJF5HS.js +124 -0
- package/dist/chunk-QBZJ7P2T.cjs +13 -0
- package/dist/chunk-QOCNX236.js +46 -0
- package/dist/chunk-QXD4MV2X.cjs +23 -0
- package/dist/chunk-R3HK6R4B.cjs +13 -0
- package/dist/chunk-RSJ3TWJQ.cjs +186 -0
- package/dist/chunk-S4WBV25P.js +913 -0
- package/dist/chunk-SN3YWBX7.cjs +4400 -0
- package/dist/chunk-SPVWWUHX.cjs +46 -0
- package/dist/chunk-SUEGJ75D.cjs +764 -0
- package/dist/chunk-SVNDB62D.cjs +58 -0
- package/dist/chunk-UYPEN5XE.cjs +235 -0
- package/dist/chunk-V5KPWNYX.cjs +147 -0
- package/dist/chunk-VVEHS2LI.js +431 -0
- package/dist/chunk-XBSYYZIY.cjs +94 -0
- package/dist/chunk-YGXJGRFI.cjs +913 -0
- package/dist/chunk-YMFAJFQT.cjs +173 -0
- package/dist/chunk-Z7LUNECE.js +49 -0
- package/dist/chunk-Z7Y2NPHY.js +186 -0
- package/dist/chunk-ZJZAOKI7.js +254 -0
- package/dist/chunk-ZLX3KGXX.js +173 -0
- package/dist/chunk-ZSVQT3PW.js +43 -0
- package/dist/completion/ApiKeyPoolService.cjs +23 -48
- package/dist/completion/ApiKeyPoolService.d.cts +150 -2
- package/dist/completion/ApiKeyPoolService.d.ts +150 -2
- package/dist/completion/BuiltinToolExecutor.cjs +9 -324
- package/dist/completion/BuiltinToolExecutor.js +6 -290
- package/dist/completion/CompletionService.cjs +38 -3487
- package/dist/completion/CompletionService.d.cts +3 -2
- package/dist/completion/CompletionService.d.ts +3 -2
- package/dist/completion/CompletionService.js +34 -3457
- package/dist/completion/NativeSearchInjector.cjs +8 -192
- package/dist/completion/NativeSearchInjector.js +7 -162
- package/dist/completion/ProviderSearchInjector.cjs +12 -39
- package/dist/completion/native-search-types.cjs +13 -66
- package/dist/completion/native-search-types.js +7 -31
- package/dist/completion/openrouter-headers.cjs +15 -71
- package/dist/completion/openrouter-headers.js +8 -34
- package/dist/completion/openrouter-models.cjs +10 -67
- package/dist/completion/openrouter-models.js +4 -34
- package/dist/completion/types.cjs +1 -18
- package/dist/completion/url-builder.cjs +24 -138
- package/dist/completion/url-builder.js +12 -92
- package/dist/completion.cjs +55 -3989
- package/dist/completion.d.cts +3 -2
- package/dist/completion.d.ts +3 -2
- package/dist/completion.js +63 -3953
- package/dist/index.cjs +197 -10429
- package/dist/index.d.cts +9 -2
- package/dist/index.d.ts +9 -2
- package/dist/index.js +125 -10268
- package/dist/logger-4GvQNzhE.d.cts +22 -0
- package/dist/logger-4GvQNzhE.d.ts +22 -0
- package/dist/outbound-api/routeResolver.cjs +7 -217
- package/dist/outbound-api/routeResolver.d.cts +2 -1
- package/dist/outbound-api/routeResolver.d.ts +2 -1
- package/dist/outbound-api/routeResolver.js +6 -187
- package/dist/outbound-api/subscriptionRegistryPort.cjs +7 -37
- package/dist/outbound-api/subscriptionRegistryPort.d.cts +2 -1
- package/dist/outbound-api/subscriptionRegistryPort.d.ts +2 -1
- package/dist/outbound-api/subscriptionRegistryPort.js +4 -8
- package/dist/outbound-api/types.cjs +1 -18
- package/dist/outbound-api/types.d.cts +2 -1
- package/dist/outbound-api/types.d.ts +2 -1
- package/dist/outbound-api.cjs +35 -5221
- package/dist/outbound-api.d.cts +2 -1
- package/dist/outbound-api.d.ts +2 -1
- package/dist/outbound-api.js +54 -5194
- package/dist/pipeline/AuthSource.cjs +1 -18
- package/dist/pipeline/LlmConfigProviderAuth.cjs +5 -166
- package/dist/pipeline/LlmConfigProviderAuth.d.cts +2 -1
- package/dist/pipeline/LlmConfigProviderAuth.d.ts +2 -1
- package/dist/pipeline/LlmConfigProviderAuth.js +5 -139
- package/dist/pipeline/SubscriptionAuthSource.cjs +6 -128
- package/dist/pipeline/SubscriptionAuthSource.js +5 -99
- package/dist/pipeline/SubscriptionAuthStrategy.cjs +1 -18
- package/dist/pipeline/executeProviderCall.cjs +5 -69
- package/dist/pipeline/executeProviderCall.js +3 -42
- package/dist/pipeline/resolveProviderChain.cjs +5 -46
- package/dist/pipeline/resolveProviderChain.js +3 -19
- package/dist/pipeline/resolveSubscriptionChain.cjs +5 -67
- package/dist/pipeline/resolveSubscriptionChain.js +3 -40
- package/dist/ports/gemini-code-assist-resolver.cjs +7 -37
- package/dist/ports/gemini-code-assist-resolver.js +4 -8
- package/dist/ports/pricing-store.cjs +1 -0
- package/dist/ports/pricing-store.d.cts +50 -0
- package/dist/ports/pricing-store.d.ts +50 -0
- package/dist/ports/pricing-store.js +0 -0
- package/dist/ports/provider-config-source.cjs +1 -18
- package/dist/ports/usage-event-store.cjs +1 -0
- package/dist/ports/usage-event-store.d.cts +29 -0
- package/dist/ports/usage-event-store.d.ts +29 -0
- package/dist/ports/usage-event-store.js +0 -0
- package/dist/ports/web-search-backend.cjs +1 -18
- package/dist/ports.cjs +1 -18
- package/dist/ports.d.cts +6 -1
- package/dist/ports.d.ts +6 -1
- package/dist/provider-proxy/ProviderProxy.cjs +40 -4643
- package/dist/provider-proxy/ProviderProxy.d.cts +2 -1
- package/dist/provider-proxy/ProviderProxy.d.ts +2 -1
- package/dist/provider-proxy/ProviderProxy.js +35 -4613
- package/dist/provider-proxy/ingress/providerProxyShared.cjs +35 -2941
- package/dist/provider-proxy/ingress/providerProxyShared.d.cts +2 -1
- package/dist/provider-proxy/ingress/providerProxyShared.d.ts +2 -1
- package/dist/provider-proxy/ingress/providerProxyShared.js +41 -2914
- package/dist/provider-proxy/matchText.cjs +11 -72
- package/dist/provider-proxy/matchText.js +6 -39
- package/dist/provider-proxy/types.cjs +1 -18
- package/dist/provider-proxy/types.d.cts +2 -1
- package/dist/provider-proxy/types.d.ts +2 -1
- package/dist/provider-proxy.cjs +35 -4655
- package/dist/provider-proxy.d.cts +2 -1
- package/dist/provider-proxy.d.ts +2 -1
- package/dist/provider-proxy.js +39 -4628
- package/dist/serializeError.cjs +5 -81
- package/dist/serializeError.js +3 -54
- package/dist/sse-parser.cjs +7 -455
- package/dist/sse-parser.js +4 -426
- package/dist/transformer/TransformerChainExecutor.cjs +4 -318
- package/dist/transformer/TransformerChainExecutor.js +4 -291
- package/dist/transformer/TransformerService.cjs +5 -289
- package/dist/transformer/TransformerService.js +3 -262
- package/dist/transformer/anthropicBetaInject.cjs +7 -50
- package/dist/transformer/anthropicBetaInject.js +4 -21
- package/dist/transformer/transformers/AnthropicTransformer.cjs +3 -1014
- package/dist/transformer/transformers/AnthropicTransformer.js +3 -987
- package/dist/transformer/transformers/GeminiCodeAssistTransformer.cjs +4 -1106
- package/dist/transformer/transformers/GeminiCodeAssistTransformer.js +7 -1079
- package/dist/transformer/transformers/GeminiTransformer.cjs +4 -1010
- package/dist/transformer/transformers/GeminiTransformer.js +4 -983
- package/dist/transformer/transformers/OpenAIResponseTransformer.cjs +3 -535
- package/dist/transformer/transformers/OpenAIResponseTransformer.js +3 -510
- package/dist/transformer/transformers/OpenCodeGoTransformer.cjs +5 -72
- package/dist/transformer/transformers/OpenCodeGoTransformer.js +3 -45
- package/dist/transformer/transformers/ReasoningTransformer.cjs +3 -270
- package/dist/transformer/transformers/ReasoningTransformer.js +2 -249
- package/dist/transformer/transformers.cjs +10 -3177
- package/dist/transformer/transformers.js +23 -3158
- package/dist/transformer/types.cjs +1 -18
- package/dist/transformer.cjs +13 -3726
- package/dist/transformer.js +17 -3706
- package/dist/usage/pricing-engine.cjs +6 -0
- package/dist/usage/pricing-engine.d.cts +83 -0
- package/dist/usage/pricing-engine.d.ts +83 -0
- package/dist/usage/pricing-engine.js +6 -0
- package/dist/usage/usage-recorder.cjs +6 -0
- package/dist/usage/usage-recorder.d.cts +73 -0
- package/dist/usage/usage-recorder.d.ts +73 -0
- package/dist/usage/usage-recorder.js +6 -0
- package/dist/usage.cjs +11 -0
- package/dist/usage.d.cts +8 -0
- package/dist/usage.d.ts +8 -0
- package/dist/usage.js +11 -0
- package/package.json +1 -1
- package/dist/ApiKeyPoolService-BmMkau07.d.cts +0 -170
- package/dist/ApiKeyPoolService-BmMkau07.d.ts +0 -170
|
@@ -1,1017 +1,6 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
19
2
|
|
|
20
|
-
|
|
21
|
-
var AnthropicTransformer_exports = {};
|
|
22
|
-
__export(AnthropicTransformer_exports, {
|
|
23
|
-
AnthropicTransformer: () => AnthropicTransformer
|
|
24
|
-
});
|
|
25
|
-
module.exports = __toCommonJS(AnthropicTransformer_exports);
|
|
3
|
+
var _chunk4VAVYUZScjs = require('../../chunk-4VAVYUZS.cjs');
|
|
26
4
|
|
|
27
|
-
// src/transformer/transformers/AnthropicToolHandling.ts
|
|
28
|
-
function isServerSideTool(tool) {
|
|
29
|
-
const type = String(tool.type || "");
|
|
30
|
-
return type.startsWith("web_search_") || type.startsWith("code_execution_") || type.startsWith("text_editor_") || type.startsWith("memory_") || type.startsWith("web_fetch_") || type.startsWith("search_tool_");
|
|
31
|
-
}
|
|
32
|
-
function convertAnthropicToolsToOpenAI(tools) {
|
|
33
|
-
return tools.filter((tool) => !isServerSideTool(tool)).map((tool) => ({
|
|
34
|
-
type: "function",
|
|
35
|
-
function: {
|
|
36
|
-
name: String(tool.name),
|
|
37
|
-
description: String(tool.description || ""),
|
|
38
|
-
parameters: tool.input_schema
|
|
39
|
-
}
|
|
40
|
-
}));
|
|
41
|
-
}
|
|
42
5
|
|
|
43
|
-
|
|
44
|
-
function getThinkLevel(budgetTokens) {
|
|
45
|
-
if (!budgetTokens || budgetTokens <= 0) return "none";
|
|
46
|
-
if (budgetTokens < 4096) return "low";
|
|
47
|
-
if (budgetTokens < 16384) return "medium";
|
|
48
|
-
return "high";
|
|
49
|
-
}
|
|
50
|
-
function formatBase64(data, mediaType) {
|
|
51
|
-
if (data.startsWith("data:")) return data;
|
|
52
|
-
return `data:${mediaType || "image/png"};base64,${data}`;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// src/transformer/transformers/AnthropicRequestBuilder.ts
|
|
56
|
-
function buildAnthropicRequestBody(request) {
|
|
57
|
-
let systemContent;
|
|
58
|
-
const anthropicMessages = [];
|
|
59
|
-
for (let i = 0; i < request.messages.length; i++) {
|
|
60
|
-
const msg = request.messages[i];
|
|
61
|
-
if (msg.role === "system") {
|
|
62
|
-
if (typeof msg.content === "string") {
|
|
63
|
-
systemContent = msg.content;
|
|
64
|
-
} else if (Array.isArray(msg.content)) {
|
|
65
|
-
systemContent = msg.content.filter((c) => c.type === "text").map((c) => ({
|
|
66
|
-
type: "text",
|
|
67
|
-
text: c.text,
|
|
68
|
-
...c.cache_control ? { cache_control: c.cache_control } : {}
|
|
69
|
-
}));
|
|
70
|
-
}
|
|
71
|
-
continue;
|
|
72
|
-
}
|
|
73
|
-
if (msg.role === "assistant") {
|
|
74
|
-
const content = [];
|
|
75
|
-
if (msg.thinking?.content) {
|
|
76
|
-
const block = {
|
|
77
|
-
type: "thinking",
|
|
78
|
-
thinking: msg.thinking.content
|
|
79
|
-
};
|
|
80
|
-
if (msg.thinking.signature) {
|
|
81
|
-
block.signature = msg.thinking.signature;
|
|
82
|
-
}
|
|
83
|
-
content.push(block);
|
|
84
|
-
}
|
|
85
|
-
if (msg.content) {
|
|
86
|
-
const text = typeof msg.content === "string" ? msg.content : msg.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
|
|
87
|
-
if (text) {
|
|
88
|
-
content.push({ type: "text", text });
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
if (msg.tool_calls?.length) {
|
|
92
|
-
for (const tc of msg.tool_calls) {
|
|
93
|
-
let input;
|
|
94
|
-
try {
|
|
95
|
-
input = typeof tc.function.arguments === "string" ? JSON.parse(tc.function.arguments) : tc.function.arguments;
|
|
96
|
-
} catch {
|
|
97
|
-
input = { text: tc.function.arguments || "" };
|
|
98
|
-
}
|
|
99
|
-
content.push({
|
|
100
|
-
type: "tool_use",
|
|
101
|
-
id: tc.id,
|
|
102
|
-
name: tc.function.name,
|
|
103
|
-
input
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
anthropicMessages.push({
|
|
108
|
-
role: "assistant",
|
|
109
|
-
content: content.length > 0 ? content : ""
|
|
110
|
-
});
|
|
111
|
-
continue;
|
|
112
|
-
}
|
|
113
|
-
if (msg.role === "tool") {
|
|
114
|
-
const toolResults = [];
|
|
115
|
-
let j = i;
|
|
116
|
-
while (j < request.messages.length && request.messages[j].role === "tool") {
|
|
117
|
-
const t = request.messages[j];
|
|
118
|
-
toolResults.push({
|
|
119
|
-
type: "tool_result",
|
|
120
|
-
tool_use_id: t.tool_call_id || "",
|
|
121
|
-
content: typeof t.content === "string" ? t.content : JSON.stringify(t.content),
|
|
122
|
-
...t.cache_control ? { cache_control: t.cache_control } : {}
|
|
123
|
-
});
|
|
124
|
-
j++;
|
|
125
|
-
}
|
|
126
|
-
anthropicMessages.push({ role: "user", content: toolResults });
|
|
127
|
-
i = j - 1;
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
if (typeof msg.content === "string") {
|
|
131
|
-
anthropicMessages.push({ role: "user", content: msg.content });
|
|
132
|
-
} else if (Array.isArray(msg.content)) {
|
|
133
|
-
const content = msg.content.map((part) => {
|
|
134
|
-
if (part.type === "image_url") {
|
|
135
|
-
const url = part.image_url.url;
|
|
136
|
-
if (url.startsWith("data:")) {
|
|
137
|
-
const match = url.match(/^data:([^;]+);base64,(.+)$/);
|
|
138
|
-
if (match) {
|
|
139
|
-
return {
|
|
140
|
-
type: "image",
|
|
141
|
-
source: { type: "base64", media_type: match[1], data: match[2] }
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
return {
|
|
146
|
-
type: "image",
|
|
147
|
-
source: { type: "url", url }
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
return { type: "text", text: part.text };
|
|
151
|
-
});
|
|
152
|
-
anthropicMessages.push({ role: "user", content });
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
const body = {
|
|
156
|
-
model: request.model,
|
|
157
|
-
messages: anthropicMessages,
|
|
158
|
-
max_tokens: request.max_tokens || 4096,
|
|
159
|
-
stream: request.stream ?? false
|
|
160
|
-
};
|
|
161
|
-
if (request.temperature !== void 0) {
|
|
162
|
-
body.temperature = request.temperature;
|
|
163
|
-
}
|
|
164
|
-
if (systemContent !== void 0) {
|
|
165
|
-
body.system = systemContent;
|
|
166
|
-
}
|
|
167
|
-
if (request.tools?.length) {
|
|
168
|
-
body.tools = request.tools.map((tool) => ({
|
|
169
|
-
name: tool.function.name,
|
|
170
|
-
description: tool.function.description || "",
|
|
171
|
-
input_schema: tool.function.parameters
|
|
172
|
-
}));
|
|
173
|
-
}
|
|
174
|
-
const serverSideTools = request._serverSideTools;
|
|
175
|
-
if (serverSideTools?.length) {
|
|
176
|
-
body.tools = [...body.tools || [], ...serverSideTools];
|
|
177
|
-
}
|
|
178
|
-
if (request.tool_choice) {
|
|
179
|
-
if (typeof request.tool_choice === "string") {
|
|
180
|
-
if (request.tool_choice === "required") {
|
|
181
|
-
body.tool_choice = { type: "any" };
|
|
182
|
-
} else if (request.tool_choice !== "none") {
|
|
183
|
-
body.tool_choice = { type: request.tool_choice };
|
|
184
|
-
}
|
|
185
|
-
} else if (typeof request.tool_choice === "object" && "function" in request.tool_choice) {
|
|
186
|
-
body.tool_choice = { type: "tool", name: request.tool_choice.function.name };
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
if (request.reasoning?.enabled) {
|
|
190
|
-
const budgetMap = { low: 2048, medium: 8192, high: 32768 };
|
|
191
|
-
const budget = request.reasoning.max_tokens || budgetMap[request.reasoning.effort || "medium"] || 8192;
|
|
192
|
-
body.thinking = { type: "enabled", budget_tokens: budget };
|
|
193
|
-
body.temperature = 1;
|
|
194
|
-
}
|
|
195
|
-
return body;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
// src/transformer/transformers/AnthropicResponseConversion.ts
|
|
199
|
-
function convertAnthropicResponseToOpenAI(anthropicResponse) {
|
|
200
|
-
const content = anthropicResponse.content || [];
|
|
201
|
-
const textParts = content.filter((c) => c.type === "text").map((c) => c.text);
|
|
202
|
-
const toolUses = content.filter((c) => c.type === "tool_use" || c.type === "server_tool_use");
|
|
203
|
-
const thinkingBlock = content.find((c) => c.type === "thinking");
|
|
204
|
-
const searchResults = content.filter((c) => c.type === "web_search_tool_result");
|
|
205
|
-
for (const sr of searchResults) {
|
|
206
|
-
const searches = sr.content;
|
|
207
|
-
if (searches?.length) {
|
|
208
|
-
const formatted = searches.map((s) => `[${s.title}](${s.url}): ${s.page_content || s.snippet || ""}`).join("\n");
|
|
209
|
-
textParts.push(`
|
|
210
|
-
|
|
211
|
-
**Search Results:**
|
|
212
|
-
${formatted}`);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
const message = {
|
|
216
|
-
role: "assistant",
|
|
217
|
-
content: textParts.join("") || null
|
|
218
|
-
};
|
|
219
|
-
if (toolUses.length > 0) {
|
|
220
|
-
message.tool_calls = toolUses.map((tc) => ({
|
|
221
|
-
id: tc.id,
|
|
222
|
-
type: "function",
|
|
223
|
-
function: {
|
|
224
|
-
name: tc.name,
|
|
225
|
-
arguments: JSON.stringify(tc.input || {})
|
|
226
|
-
}
|
|
227
|
-
}));
|
|
228
|
-
}
|
|
229
|
-
if (thinkingBlock) {
|
|
230
|
-
message.thinking = {
|
|
231
|
-
content: thinkingBlock.thinking,
|
|
232
|
-
signature: thinkingBlock.signature
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
const stopReasonMapping = {
|
|
236
|
-
end_turn: "stop",
|
|
237
|
-
max_tokens: "length",
|
|
238
|
-
tool_use: "tool_calls",
|
|
239
|
-
stop_sequence: "stop"
|
|
240
|
-
};
|
|
241
|
-
const usage = anthropicResponse.usage;
|
|
242
|
-
return {
|
|
243
|
-
id: anthropicResponse.id || `chatcmpl-${Date.now()}`,
|
|
244
|
-
object: "chat.completion",
|
|
245
|
-
created: Math.floor(Date.now() / 1e3),
|
|
246
|
-
model: anthropicResponse.model || "unknown",
|
|
247
|
-
choices: [{
|
|
248
|
-
index: 0,
|
|
249
|
-
message,
|
|
250
|
-
finish_reason: stopReasonMapping[anthropicResponse.stop_reason] || "stop"
|
|
251
|
-
}],
|
|
252
|
-
usage: usage ? {
|
|
253
|
-
prompt_tokens: usage.input_tokens || 0,
|
|
254
|
-
completion_tokens: usage.output_tokens || 0,
|
|
255
|
-
total_tokens: (usage.input_tokens || 0) + (usage.output_tokens || 0)
|
|
256
|
-
} : void 0
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
function convertOpenAIResponseToAnthropic(openaiResponse) {
|
|
260
|
-
const choice = openaiResponse.choices?.[0];
|
|
261
|
-
if (!choice) {
|
|
262
|
-
throw new Error("No choices found in OpenAI response");
|
|
263
|
-
}
|
|
264
|
-
const message = choice.message;
|
|
265
|
-
const content = [];
|
|
266
|
-
if (message.content) {
|
|
267
|
-
content.push({
|
|
268
|
-
type: "text",
|
|
269
|
-
text: message.content
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
const toolCalls = message.tool_calls;
|
|
273
|
-
if (toolCalls?.length) {
|
|
274
|
-
for (const toolCall of toolCalls) {
|
|
275
|
-
const func = toolCall.function;
|
|
276
|
-
let parsedInput = {};
|
|
277
|
-
try {
|
|
278
|
-
const args = func.arguments;
|
|
279
|
-
parsedInput = typeof args === "string" ? JSON.parse(args) : args;
|
|
280
|
-
} catch {
|
|
281
|
-
parsedInput = { text: func.arguments || "" };
|
|
282
|
-
}
|
|
283
|
-
content.push({
|
|
284
|
-
type: "tool_use",
|
|
285
|
-
id: toolCall.id,
|
|
286
|
-
name: func.name,
|
|
287
|
-
input: parsedInput
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
const thinking = message.thinking;
|
|
292
|
-
if (thinking?.content) {
|
|
293
|
-
content.push({
|
|
294
|
-
type: "thinking",
|
|
295
|
-
thinking: thinking.content,
|
|
296
|
-
signature: thinking.signature
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
const finishReason = choice.finish_reason;
|
|
300
|
-
const stopReasonMapping = {
|
|
301
|
-
stop: "end_turn",
|
|
302
|
-
length: "max_tokens",
|
|
303
|
-
tool_calls: "tool_use",
|
|
304
|
-
content_filter: "stop_sequence"
|
|
305
|
-
};
|
|
306
|
-
const usage = openaiResponse.usage;
|
|
307
|
-
const usageDetails = usage?.prompt_tokens_details;
|
|
308
|
-
return {
|
|
309
|
-
id: openaiResponse.id,
|
|
310
|
-
type: "message",
|
|
311
|
-
role: "assistant",
|
|
312
|
-
model: openaiResponse.model,
|
|
313
|
-
content,
|
|
314
|
-
stop_reason: stopReasonMapping[finishReason] || "end_turn",
|
|
315
|
-
stop_sequence: null,
|
|
316
|
-
usage: {
|
|
317
|
-
input_tokens: (usage?.prompt_tokens || 0) - (usageDetails?.cached_tokens || 0),
|
|
318
|
-
output_tokens: usage?.completion_tokens || 0,
|
|
319
|
-
cache_read_input_tokens: usageDetails?.cached_tokens || 0
|
|
320
|
-
}
|
|
321
|
-
};
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// src/transformer/transformers/AnthropicConversion.ts
|
|
325
|
-
function transformAnthropicRequestToUnified(request) {
|
|
326
|
-
const anthropicRequest = request;
|
|
327
|
-
const messages = [];
|
|
328
|
-
if (anthropicRequest.system) {
|
|
329
|
-
if (typeof anthropicRequest.system === "string") {
|
|
330
|
-
messages.push({
|
|
331
|
-
role: "system",
|
|
332
|
-
content: anthropicRequest.system
|
|
333
|
-
});
|
|
334
|
-
} else if (Array.isArray(anthropicRequest.system)) {
|
|
335
|
-
const textParts = anthropicRequest.system.filter((item) => item.type === "text" && item.text).map((item) => ({
|
|
336
|
-
type: "text",
|
|
337
|
-
text: item.text,
|
|
338
|
-
cache_control: item.cache_control
|
|
339
|
-
}));
|
|
340
|
-
if (textParts.length > 0) {
|
|
341
|
-
messages.push({
|
|
342
|
-
role: "system",
|
|
343
|
-
content: textParts
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
const requestMessages = JSON.parse(JSON.stringify(anthropicRequest.messages || []));
|
|
349
|
-
for (const msg of requestMessages) {
|
|
350
|
-
if (msg.role !== "user" && msg.role !== "assistant") continue;
|
|
351
|
-
if (typeof msg.content === "string") {
|
|
352
|
-
messages.push({
|
|
353
|
-
role: msg.role,
|
|
354
|
-
content: msg.content
|
|
355
|
-
});
|
|
356
|
-
continue;
|
|
357
|
-
}
|
|
358
|
-
if (Array.isArray(msg.content)) {
|
|
359
|
-
if (msg.role === "user") {
|
|
360
|
-
const toolParts = msg.content.filter(
|
|
361
|
-
(c) => c.type === "tool_result" && c.tool_use_id
|
|
362
|
-
);
|
|
363
|
-
for (const tool of toolParts) {
|
|
364
|
-
messages.push({
|
|
365
|
-
role: "tool",
|
|
366
|
-
content: typeof tool.content === "string" ? tool.content : JSON.stringify(tool.content),
|
|
367
|
-
tool_call_id: tool.tool_use_id,
|
|
368
|
-
cache_control: tool.cache_control
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
const textAndMediaParts = msg.content.filter(
|
|
372
|
-
(c) => c.type === "text" && c.text || c.type === "image" && c.source
|
|
373
|
-
);
|
|
374
|
-
if (textAndMediaParts.length > 0) {
|
|
375
|
-
messages.push({
|
|
376
|
-
role: "user",
|
|
377
|
-
content: textAndMediaParts.map((part) => {
|
|
378
|
-
if (part.type === "image") {
|
|
379
|
-
const imagePart = part;
|
|
380
|
-
return {
|
|
381
|
-
type: "image_url",
|
|
382
|
-
image_url: {
|
|
383
|
-
url: imagePart.source.type === "base64" ? formatBase64(imagePart.source.data || "", imagePart.source.media_type) : imagePart.source.url || ""
|
|
384
|
-
},
|
|
385
|
-
media_type: imagePart.source.media_type
|
|
386
|
-
};
|
|
387
|
-
}
|
|
388
|
-
return {
|
|
389
|
-
type: "text",
|
|
390
|
-
text: part.text
|
|
391
|
-
};
|
|
392
|
-
})
|
|
393
|
-
});
|
|
394
|
-
}
|
|
395
|
-
} else if (msg.role === "assistant") {
|
|
396
|
-
const assistantMessage = {
|
|
397
|
-
role: "assistant",
|
|
398
|
-
content: ""
|
|
399
|
-
};
|
|
400
|
-
const textParts = msg.content.filter(
|
|
401
|
-
(c) => c.type === "text" && c.text
|
|
402
|
-
);
|
|
403
|
-
if (textParts.length > 0) {
|
|
404
|
-
assistantMessage.content = textParts.map((t) => t.text).join("\n");
|
|
405
|
-
}
|
|
406
|
-
const toolCallParts = msg.content.filter(
|
|
407
|
-
(c) => c.type === "tool_use" && c.id
|
|
408
|
-
);
|
|
409
|
-
if (toolCallParts.length > 0) {
|
|
410
|
-
assistantMessage.tool_calls = toolCallParts.map((tool) => ({
|
|
411
|
-
id: tool.id,
|
|
412
|
-
type: "function",
|
|
413
|
-
function: {
|
|
414
|
-
name: tool.name,
|
|
415
|
-
arguments: JSON.stringify(tool.input || {})
|
|
416
|
-
}
|
|
417
|
-
}));
|
|
418
|
-
}
|
|
419
|
-
const thinkingPart = msg.content.find(
|
|
420
|
-
(c) => c.type === "thinking"
|
|
421
|
-
);
|
|
422
|
-
if (thinkingPart?.thinking) {
|
|
423
|
-
assistantMessage.thinking = {
|
|
424
|
-
content: thinkingPart.thinking,
|
|
425
|
-
signature: thinkingPart.signature
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
messages.push(assistantMessage);
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
const rawTools = anthropicRequest.tools || [];
|
|
433
|
-
const serverSideTools = rawTools.filter((t) => isServerSideTool(t));
|
|
434
|
-
const functionTools = rawTools.length > 0 ? convertAnthropicToolsToOpenAI(rawTools) : void 0;
|
|
435
|
-
const result = {
|
|
436
|
-
messages,
|
|
437
|
-
model: anthropicRequest.model,
|
|
438
|
-
max_tokens: anthropicRequest.max_tokens,
|
|
439
|
-
temperature: anthropicRequest.temperature,
|
|
440
|
-
stream: anthropicRequest.stream,
|
|
441
|
-
tools: functionTools?.length ? functionTools : void 0
|
|
442
|
-
};
|
|
443
|
-
if (serverSideTools.length > 0) {
|
|
444
|
-
result._serverSideTools = serverSideTools;
|
|
445
|
-
}
|
|
446
|
-
if (anthropicRequest.thinking) {
|
|
447
|
-
result.reasoning = {
|
|
448
|
-
effort: getThinkLevel(anthropicRequest.thinking.budget_tokens),
|
|
449
|
-
enabled: anthropicRequest.thinking.type === "enabled"
|
|
450
|
-
};
|
|
451
|
-
}
|
|
452
|
-
if (anthropicRequest.tool_choice) {
|
|
453
|
-
if (anthropicRequest.tool_choice.type === "tool" && anthropicRequest.tool_choice.name) {
|
|
454
|
-
result.tool_choice = {
|
|
455
|
-
type: "function",
|
|
456
|
-
function: { name: anthropicRequest.tool_choice.name }
|
|
457
|
-
};
|
|
458
|
-
} else {
|
|
459
|
-
result.tool_choice = anthropicRequest.tool_choice.type;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
return result;
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
// src/transformer/transformers/AnthropicAnthropicToOpenAIStream.ts
|
|
466
|
-
function convertAnthropicStreamToOpenAI(anthropicStream, logger) {
|
|
467
|
-
const decoder = new TextDecoder();
|
|
468
|
-
const encoder = new TextEncoder();
|
|
469
|
-
const activeToolCalls = /* @__PURE__ */ new Map();
|
|
470
|
-
let toolCallCounter = 0;
|
|
471
|
-
let model = "unknown";
|
|
472
|
-
let messageId = `chatcmpl-${Date.now()}`;
|
|
473
|
-
return new ReadableStream({
|
|
474
|
-
start: async (controller) => {
|
|
475
|
-
const reader = anthropicStream.getReader();
|
|
476
|
-
let buffer = "";
|
|
477
|
-
let isClosed = false;
|
|
478
|
-
const safeEnqueue = (data) => {
|
|
479
|
-
if (!isClosed) {
|
|
480
|
-
try {
|
|
481
|
-
controller.enqueue(encoder.encode(data));
|
|
482
|
-
} catch {
|
|
483
|
-
isClosed = true;
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
};
|
|
487
|
-
try {
|
|
488
|
-
while (true) {
|
|
489
|
-
const { done, value } = await reader.read();
|
|
490
|
-
if (done) break;
|
|
491
|
-
buffer += decoder.decode(value, { stream: true });
|
|
492
|
-
const lines = buffer.split("\n");
|
|
493
|
-
buffer = lines.pop() || "";
|
|
494
|
-
for (const line of lines) {
|
|
495
|
-
if (isClosed) break;
|
|
496
|
-
if (!line.startsWith("data:")) continue;
|
|
497
|
-
const data = line.slice(5).trim();
|
|
498
|
-
if (!data || data === "[DONE]") continue;
|
|
499
|
-
try {
|
|
500
|
-
const event = JSON.parse(data);
|
|
501
|
-
if (event.type === "message_start" && event.message) {
|
|
502
|
-
model = event.message.model || model;
|
|
503
|
-
messageId = event.message.id || messageId;
|
|
504
|
-
}
|
|
505
|
-
if (event.type === "content_block_delta" && event.delta) {
|
|
506
|
-
const chunk = {
|
|
507
|
-
id: messageId,
|
|
508
|
-
object: "chat.completion.chunk",
|
|
509
|
-
created: Math.floor(Date.now() / 1e3),
|
|
510
|
-
model,
|
|
511
|
-
choices: [{ index: 0, delta: {}, finish_reason: null }]
|
|
512
|
-
};
|
|
513
|
-
const delta = chunk.choices[0].delta;
|
|
514
|
-
if (event.delta.type === "text_delta") {
|
|
515
|
-
delta.content = event.delta.text;
|
|
516
|
-
} else if (event.delta.type === "input_json_delta") {
|
|
517
|
-
const toolInfo = activeToolCalls.get(event.index);
|
|
518
|
-
if (toolInfo) {
|
|
519
|
-
delta.tool_calls = [{
|
|
520
|
-
index: toolInfo.index,
|
|
521
|
-
function: { arguments: event.delta.partial_json }
|
|
522
|
-
}];
|
|
523
|
-
}
|
|
524
|
-
} else if (event.delta.type === "thinking_delta") {
|
|
525
|
-
delta.thinking = { content: event.delta.thinking };
|
|
526
|
-
} else if (event.delta.type === "signature_delta") {
|
|
527
|
-
delta.thinking = { signature: event.delta.signature };
|
|
528
|
-
} else {
|
|
529
|
-
continue;
|
|
530
|
-
}
|
|
531
|
-
safeEnqueue(`data: ${JSON.stringify(chunk)}
|
|
532
|
-
|
|
533
|
-
`);
|
|
534
|
-
}
|
|
535
|
-
if (event.type === "content_block_start" && event.content_block) {
|
|
536
|
-
if (event.content_block.type === "tool_use" || event.content_block.type === "server_tool_use") {
|
|
537
|
-
const tcIndex = toolCallCounter++;
|
|
538
|
-
activeToolCalls.set(event.index, {
|
|
539
|
-
id: event.content_block.id,
|
|
540
|
-
name: event.content_block.name,
|
|
541
|
-
index: tcIndex
|
|
542
|
-
});
|
|
543
|
-
const chunk = {
|
|
544
|
-
id: messageId,
|
|
545
|
-
object: "chat.completion.chunk",
|
|
546
|
-
created: Math.floor(Date.now() / 1e3),
|
|
547
|
-
model,
|
|
548
|
-
choices: [{
|
|
549
|
-
index: 0,
|
|
550
|
-
delta: {
|
|
551
|
-
tool_calls: [{
|
|
552
|
-
index: tcIndex,
|
|
553
|
-
id: event.content_block.id,
|
|
554
|
-
type: "function",
|
|
555
|
-
function: { name: event.content_block.name, arguments: "" }
|
|
556
|
-
}]
|
|
557
|
-
},
|
|
558
|
-
finish_reason: null
|
|
559
|
-
}]
|
|
560
|
-
};
|
|
561
|
-
safeEnqueue(`data: ${JSON.stringify(chunk)}
|
|
562
|
-
|
|
563
|
-
`);
|
|
564
|
-
} else if (event.content_block.type === "web_search_tool_result") {
|
|
565
|
-
const searches = event.content_block.content;
|
|
566
|
-
if (searches?.length) {
|
|
567
|
-
const formatted = searches.map((s) => `[${s.title}](${s.url}): ${s.page_content || s.snippet || ""}`).join("\n");
|
|
568
|
-
const chunk = {
|
|
569
|
-
id: messageId,
|
|
570
|
-
object: "chat.completion.chunk",
|
|
571
|
-
created: Math.floor(Date.now() / 1e3),
|
|
572
|
-
model,
|
|
573
|
-
choices: [{
|
|
574
|
-
index: 0,
|
|
575
|
-
delta: { content: `
|
|
576
|
-
|
|
577
|
-
**Search Results:**
|
|
578
|
-
${formatted}` },
|
|
579
|
-
finish_reason: null
|
|
580
|
-
}]
|
|
581
|
-
};
|
|
582
|
-
safeEnqueue(`data: ${JSON.stringify(chunk)}
|
|
583
|
-
|
|
584
|
-
`);
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
if (event.type === "message_delta" && event.delta) {
|
|
589
|
-
const stopReasonMapping = {
|
|
590
|
-
end_turn: "stop",
|
|
591
|
-
max_tokens: "length",
|
|
592
|
-
tool_use: "tool_calls",
|
|
593
|
-
stop_sequence: "stop"
|
|
594
|
-
};
|
|
595
|
-
const chunk = {
|
|
596
|
-
id: messageId,
|
|
597
|
-
object: "chat.completion.chunk",
|
|
598
|
-
created: Math.floor(Date.now() / 1e3),
|
|
599
|
-
model,
|
|
600
|
-
choices: [{
|
|
601
|
-
index: 0,
|
|
602
|
-
delta: {},
|
|
603
|
-
finish_reason: stopReasonMapping[event.delta.stop_reason] || "stop"
|
|
604
|
-
}]
|
|
605
|
-
};
|
|
606
|
-
if (event.usage) {
|
|
607
|
-
chunk.usage = {
|
|
608
|
-
prompt_tokens: event.usage.input_tokens || 0,
|
|
609
|
-
completion_tokens: event.usage.output_tokens || 0,
|
|
610
|
-
total_tokens: (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0)
|
|
611
|
-
};
|
|
612
|
-
}
|
|
613
|
-
safeEnqueue(`data: ${JSON.stringify(chunk)}
|
|
614
|
-
|
|
615
|
-
`);
|
|
616
|
-
}
|
|
617
|
-
} catch (e) {
|
|
618
|
-
logger?.error("Error parsing Anthropic stream event:", e);
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
} catch (e) {
|
|
623
|
-
if (!isClosed) {
|
|
624
|
-
controller.error(e);
|
|
625
|
-
}
|
|
626
|
-
} finally {
|
|
627
|
-
safeEnqueue("data: [DONE]\n\n");
|
|
628
|
-
if (!isClosed) {
|
|
629
|
-
try {
|
|
630
|
-
controller.close();
|
|
631
|
-
} catch {
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
reader.releaseLock();
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
});
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
// src/transformer/transformers/AnthropicOpenAIToAnthropicStream.ts
|
|
641
|
-
function convertOpenAIStreamToAnthropic(openaiStream, _context, logger) {
|
|
642
|
-
const decoder = new TextDecoder();
|
|
643
|
-
const encoder = new TextEncoder();
|
|
644
|
-
let hasStarted = false;
|
|
645
|
-
let hasTextContentStarted = false;
|
|
646
|
-
let isThinkingStarted = false;
|
|
647
|
-
let contentIndex = 0;
|
|
648
|
-
let currentContentBlockIndex = -1;
|
|
649
|
-
const toolCallIndexToContentBlockIndex = /* @__PURE__ */ new Map();
|
|
650
|
-
return new ReadableStream({
|
|
651
|
-
start: async (controller) => {
|
|
652
|
-
const reader = openaiStream.getReader();
|
|
653
|
-
let buffer = "";
|
|
654
|
-
const messageId = `msg_${Date.now()}`;
|
|
655
|
-
let model = "unknown";
|
|
656
|
-
let isClosed = false;
|
|
657
|
-
let stopReasonDelta = null;
|
|
658
|
-
const safeEnqueue = (data) => {
|
|
659
|
-
if (!isClosed) {
|
|
660
|
-
try {
|
|
661
|
-
controller.enqueue(encoder.encode(data));
|
|
662
|
-
} catch (_e) {
|
|
663
|
-
isClosed = true;
|
|
664
|
-
}
|
|
665
|
-
}
|
|
666
|
-
};
|
|
667
|
-
const assignContentBlockIndex = () => {
|
|
668
|
-
return contentIndex++;
|
|
669
|
-
};
|
|
670
|
-
const safeClose = () => {
|
|
671
|
-
if (isClosed) return;
|
|
672
|
-
if (currentContentBlockIndex >= 0) {
|
|
673
|
-
safeEnqueue(`event: content_block_stop
|
|
674
|
-
data: ${JSON.stringify({
|
|
675
|
-
type: "content_block_stop",
|
|
676
|
-
index: currentContentBlockIndex
|
|
677
|
-
})}
|
|
678
|
-
|
|
679
|
-
`);
|
|
680
|
-
}
|
|
681
|
-
if (stopReasonDelta) {
|
|
682
|
-
safeEnqueue(`event: message_delta
|
|
683
|
-
data: ${JSON.stringify(stopReasonDelta)}
|
|
684
|
-
|
|
685
|
-
`);
|
|
686
|
-
} else {
|
|
687
|
-
safeEnqueue(`event: message_delta
|
|
688
|
-
data: ${JSON.stringify({
|
|
689
|
-
type: "message_delta",
|
|
690
|
-
delta: { stop_reason: "end_turn", stop_sequence: null },
|
|
691
|
-
usage: { input_tokens: 0, output_tokens: 0 }
|
|
692
|
-
})}
|
|
693
|
-
|
|
694
|
-
`);
|
|
695
|
-
}
|
|
696
|
-
safeEnqueue(`event: message_stop
|
|
697
|
-
data: ${JSON.stringify({ type: "message_stop" })}
|
|
698
|
-
|
|
699
|
-
`);
|
|
700
|
-
try {
|
|
701
|
-
controller.close();
|
|
702
|
-
} catch (_e) {
|
|
703
|
-
}
|
|
704
|
-
isClosed = true;
|
|
705
|
-
};
|
|
706
|
-
try {
|
|
707
|
-
while (true) {
|
|
708
|
-
const { done, value } = await reader.read();
|
|
709
|
-
if (done) break;
|
|
710
|
-
buffer += decoder.decode(value, { stream: true });
|
|
711
|
-
const lines = buffer.split("\n");
|
|
712
|
-
buffer = lines.pop() || "";
|
|
713
|
-
for (const line of lines) {
|
|
714
|
-
if (isClosed) break;
|
|
715
|
-
if (!line.startsWith("data:")) continue;
|
|
716
|
-
const data = line.slice(5).trim();
|
|
717
|
-
if (data === "[DONE]") continue;
|
|
718
|
-
try {
|
|
719
|
-
const chunk = JSON.parse(data);
|
|
720
|
-
if (chunk.error) {
|
|
721
|
-
safeEnqueue(`event: error
|
|
722
|
-
data: ${JSON.stringify({
|
|
723
|
-
type: "error",
|
|
724
|
-
message: { type: "api_error", message: JSON.stringify(chunk.error) }
|
|
725
|
-
})}
|
|
726
|
-
|
|
727
|
-
`);
|
|
728
|
-
continue;
|
|
729
|
-
}
|
|
730
|
-
model = chunk.model || model;
|
|
731
|
-
if (!hasStarted) {
|
|
732
|
-
hasStarted = true;
|
|
733
|
-
safeEnqueue(`event: message_start
|
|
734
|
-
data: ${JSON.stringify({
|
|
735
|
-
type: "message_start",
|
|
736
|
-
message: {
|
|
737
|
-
id: messageId,
|
|
738
|
-
type: "message",
|
|
739
|
-
role: "assistant",
|
|
740
|
-
content: [],
|
|
741
|
-
model,
|
|
742
|
-
stop_reason: null,
|
|
743
|
-
stop_sequence: null,
|
|
744
|
-
usage: { input_tokens: 0, output_tokens: 0 }
|
|
745
|
-
}
|
|
746
|
-
})}
|
|
747
|
-
|
|
748
|
-
`);
|
|
749
|
-
}
|
|
750
|
-
const choice = chunk.choices?.[0];
|
|
751
|
-
if (!choice) continue;
|
|
752
|
-
if (chunk.usage) {
|
|
753
|
-
stopReasonDelta = {
|
|
754
|
-
type: "message_delta",
|
|
755
|
-
delta: { stop_reason: "end_turn", stop_sequence: null },
|
|
756
|
-
usage: {
|
|
757
|
-
input_tokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0),
|
|
758
|
-
output_tokens: chunk.usage.completion_tokens || 0,
|
|
759
|
-
cache_read_input_tokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0
|
|
760
|
-
}
|
|
761
|
-
};
|
|
762
|
-
}
|
|
763
|
-
if (choice.delta?.thinking) {
|
|
764
|
-
if (!isThinkingStarted) {
|
|
765
|
-
const thinkingBlockIndex = assignContentBlockIndex();
|
|
766
|
-
safeEnqueue(`event: content_block_start
|
|
767
|
-
data: ${JSON.stringify({
|
|
768
|
-
type: "content_block_start",
|
|
769
|
-
index: thinkingBlockIndex,
|
|
770
|
-
content_block: { type: "thinking", thinking: "" }
|
|
771
|
-
})}
|
|
772
|
-
|
|
773
|
-
`);
|
|
774
|
-
currentContentBlockIndex = thinkingBlockIndex;
|
|
775
|
-
isThinkingStarted = true;
|
|
776
|
-
}
|
|
777
|
-
if (choice.delta.thinking.signature) {
|
|
778
|
-
safeEnqueue(`event: content_block_delta
|
|
779
|
-
data: ${JSON.stringify({
|
|
780
|
-
type: "content_block_delta",
|
|
781
|
-
index: currentContentBlockIndex,
|
|
782
|
-
delta: { type: "signature_delta", signature: choice.delta.thinking.signature }
|
|
783
|
-
})}
|
|
784
|
-
|
|
785
|
-
`);
|
|
786
|
-
safeEnqueue(`event: content_block_stop
|
|
787
|
-
data: ${JSON.stringify({
|
|
788
|
-
type: "content_block_stop",
|
|
789
|
-
index: currentContentBlockIndex
|
|
790
|
-
})}
|
|
791
|
-
|
|
792
|
-
`);
|
|
793
|
-
currentContentBlockIndex = -1;
|
|
794
|
-
} else if (choice.delta.thinking.content) {
|
|
795
|
-
safeEnqueue(`event: content_block_delta
|
|
796
|
-
data: ${JSON.stringify({
|
|
797
|
-
type: "content_block_delta",
|
|
798
|
-
index: currentContentBlockIndex,
|
|
799
|
-
delta: { type: "thinking_delta", thinking: choice.delta.thinking.content }
|
|
800
|
-
})}
|
|
801
|
-
|
|
802
|
-
`);
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
if (choice.delta?.content) {
|
|
806
|
-
if (!hasTextContentStarted) {
|
|
807
|
-
if (currentContentBlockIndex >= 0 && isThinkingStarted) {
|
|
808
|
-
safeEnqueue(`event: content_block_stop
|
|
809
|
-
data: ${JSON.stringify({
|
|
810
|
-
type: "content_block_stop",
|
|
811
|
-
index: currentContentBlockIndex
|
|
812
|
-
})}
|
|
813
|
-
|
|
814
|
-
`);
|
|
815
|
-
}
|
|
816
|
-
hasTextContentStarted = true;
|
|
817
|
-
const textBlockIndex = assignContentBlockIndex();
|
|
818
|
-
safeEnqueue(`event: content_block_start
|
|
819
|
-
data: ${JSON.stringify({
|
|
820
|
-
type: "content_block_start",
|
|
821
|
-
index: textBlockIndex,
|
|
822
|
-
content_block: { type: "text", text: "" }
|
|
823
|
-
})}
|
|
824
|
-
|
|
825
|
-
`);
|
|
826
|
-
currentContentBlockIndex = textBlockIndex;
|
|
827
|
-
}
|
|
828
|
-
safeEnqueue(`event: content_block_delta
|
|
829
|
-
data: ${JSON.stringify({
|
|
830
|
-
type: "content_block_delta",
|
|
831
|
-
index: currentContentBlockIndex,
|
|
832
|
-
delta: { type: "text_delta", text: choice.delta.content }
|
|
833
|
-
})}
|
|
834
|
-
|
|
835
|
-
`);
|
|
836
|
-
}
|
|
837
|
-
if (choice.delta?.tool_calls) {
|
|
838
|
-
for (const toolCall of choice.delta.tool_calls) {
|
|
839
|
-
const toolCallIndex = toolCall.index ?? 0;
|
|
840
|
-
if (!toolCallIndexToContentBlockIndex.has(toolCallIndex)) {
|
|
841
|
-
if (currentContentBlockIndex >= 0) {
|
|
842
|
-
safeEnqueue(`event: content_block_stop
|
|
843
|
-
data: ${JSON.stringify({
|
|
844
|
-
type: "content_block_stop",
|
|
845
|
-
index: currentContentBlockIndex
|
|
846
|
-
})}
|
|
847
|
-
|
|
848
|
-
`);
|
|
849
|
-
hasTextContentStarted = false;
|
|
850
|
-
}
|
|
851
|
-
const newBlockIndex = assignContentBlockIndex();
|
|
852
|
-
toolCallIndexToContentBlockIndex.set(toolCallIndex, newBlockIndex);
|
|
853
|
-
safeEnqueue(`event: content_block_start
|
|
854
|
-
data: ${JSON.stringify({
|
|
855
|
-
type: "content_block_start",
|
|
856
|
-
index: newBlockIndex,
|
|
857
|
-
content_block: {
|
|
858
|
-
type: "tool_use",
|
|
859
|
-
id: toolCall.id || `call_${Date.now()}_${toolCallIndex}`,
|
|
860
|
-
name: toolCall.function?.name || `tool_${toolCallIndex}`,
|
|
861
|
-
input: {}
|
|
862
|
-
}
|
|
863
|
-
})}
|
|
864
|
-
|
|
865
|
-
`);
|
|
866
|
-
currentContentBlockIndex = newBlockIndex;
|
|
867
|
-
}
|
|
868
|
-
if (toolCall.function?.arguments) {
|
|
869
|
-
const blockIndex = toolCallIndexToContentBlockIndex.get(toolCallIndex);
|
|
870
|
-
if (blockIndex !== void 0) {
|
|
871
|
-
safeEnqueue(`event: content_block_delta
|
|
872
|
-
data: ${JSON.stringify({
|
|
873
|
-
type: "content_block_delta",
|
|
874
|
-
index: blockIndex,
|
|
875
|
-
delta: { type: "input_json_delta", partial_json: toolCall.function.arguments }
|
|
876
|
-
})}
|
|
877
|
-
|
|
878
|
-
`);
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
if (choice.finish_reason) {
|
|
884
|
-
const stopReasonMapping = {
|
|
885
|
-
stop: "end_turn",
|
|
886
|
-
length: "max_tokens",
|
|
887
|
-
tool_calls: "tool_use",
|
|
888
|
-
content_filter: "stop_sequence"
|
|
889
|
-
};
|
|
890
|
-
stopReasonDelta = {
|
|
891
|
-
type: "message_delta",
|
|
892
|
-
delta: {
|
|
893
|
-
stop_reason: stopReasonMapping[choice.finish_reason] || "end_turn",
|
|
894
|
-
stop_sequence: null
|
|
895
|
-
},
|
|
896
|
-
usage: {
|
|
897
|
-
input_tokens: (chunk.usage?.prompt_tokens || 0) - (chunk.usage?.prompt_tokens_details?.cached_tokens || 0),
|
|
898
|
-
output_tokens: chunk.usage?.completion_tokens || 0,
|
|
899
|
-
cache_read_input_tokens: chunk.usage?.prompt_tokens_details?.cached_tokens || 0
|
|
900
|
-
}
|
|
901
|
-
};
|
|
902
|
-
}
|
|
903
|
-
} catch (e) {
|
|
904
|
-
logger?.error("Error parsing stream chunk:", e);
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
} catch (e) {
|
|
909
|
-
if (!isClosed) {
|
|
910
|
-
controller.error(e);
|
|
911
|
-
}
|
|
912
|
-
} finally {
|
|
913
|
-
safeClose();
|
|
914
|
-
reader.releaseLock();
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
});
|
|
918
|
-
}
|
|
919
|
-
|
|
920
|
-
// src/transformer/transformers/AnthropicTransformer.ts
|
|
921
|
-
var AnthropicTransformer = class {
|
|
922
|
-
static TransformerName = "anthropic";
|
|
923
|
-
name = "anthropic";
|
|
924
|
-
logger;
|
|
925
|
-
endPoint = "/v1/messages";
|
|
926
|
-
useBearer;
|
|
927
|
-
constructor(options) {
|
|
928
|
-
this.useBearer = options?.UseBearer ?? false;
|
|
929
|
-
}
|
|
930
|
-
/**
|
|
931
|
-
* Handle authentication - Anthropic uses x-api-key header
|
|
932
|
-
*/
|
|
933
|
-
async auth(request, provider, _context) {
|
|
934
|
-
const headers = {};
|
|
935
|
-
if (this.useBearer) {
|
|
936
|
-
headers["authorization"] = `Bearer ${provider.apiKey}`;
|
|
937
|
-
headers["x-api-key"] = void 0;
|
|
938
|
-
} else {
|
|
939
|
-
headers["x-api-key"] = provider.apiKey;
|
|
940
|
-
headers["authorization"] = void 0;
|
|
941
|
-
}
|
|
942
|
-
return {
|
|
943
|
-
body: request,
|
|
944
|
-
config: { headers }
|
|
945
|
-
};
|
|
946
|
-
}
|
|
947
|
-
/**
|
|
948
|
-
* Transform Anthropic request to unified format.
|
|
949
|
-
*/
|
|
950
|
-
async transformRequestOut(request, _context) {
|
|
951
|
-
return transformAnthropicRequestToUnified(request);
|
|
952
|
-
}
|
|
953
|
-
/**
|
|
954
|
-
* Transform OpenAI/unified response back to Anthropic format
|
|
955
|
-
* (auto-detects stream vs JSON via Content-Type).
|
|
956
|
-
*/
|
|
957
|
-
async transformResponseIn(response, context) {
|
|
958
|
-
const contentType = response.headers.get("Content-Type") ?? "";
|
|
959
|
-
if (contentType.includes("text/event-stream")) {
|
|
960
|
-
if (!response.body) {
|
|
961
|
-
throw new Error("Stream response body is null");
|
|
962
|
-
}
|
|
963
|
-
const convertedStream = convertOpenAIStreamToAnthropic(response.body, context, this.logger);
|
|
964
|
-
return new Response(convertedStream, {
|
|
965
|
-
headers: {
|
|
966
|
-
"Content-Type": "text/event-stream",
|
|
967
|
-
"Cache-Control": "no-cache",
|
|
968
|
-
Connection: "keep-alive"
|
|
969
|
-
}
|
|
970
|
-
});
|
|
971
|
-
} else {
|
|
972
|
-
const data = await response.json();
|
|
973
|
-
const anthropicResponse = convertOpenAIResponseToAnthropic(data);
|
|
974
|
-
return new Response(JSON.stringify(anthropicResponse), {
|
|
975
|
-
headers: { "Content-Type": "application/json" }
|
|
976
|
-
});
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
/**
|
|
980
|
-
* Transform unified request to Anthropic Messages API format.
|
|
981
|
-
* This is the reverse of transformRequestOut — converts OpenAI/unified format
|
|
982
|
-
* to Anthropic's expected request body structure.
|
|
983
|
-
*/
|
|
984
|
-
async transformRequestIn(request, _provider, _context) {
|
|
985
|
-
return buildAnthropicRequestBody(request);
|
|
986
|
-
}
|
|
987
|
-
/**
|
|
988
|
-
* Transform Anthropic response to OpenAI/unified format
|
|
989
|
-
* (auto-detects stream vs JSON via Content-Type).
|
|
990
|
-
*/
|
|
991
|
-
async transformResponseOut(response, _context) {
|
|
992
|
-
const contentType = response.headers.get("Content-Type") ?? "";
|
|
993
|
-
if (contentType.includes("text/event-stream")) {
|
|
994
|
-
if (!response.body) {
|
|
995
|
-
throw new Error("Stream response body is null");
|
|
996
|
-
}
|
|
997
|
-
const convertedStream = convertAnthropicStreamToOpenAI(response.body, this.logger);
|
|
998
|
-
return new Response(convertedStream, {
|
|
999
|
-
headers: {
|
|
1000
|
-
"Content-Type": "text/event-stream",
|
|
1001
|
-
"Cache-Control": "no-cache",
|
|
1002
|
-
Connection: "keep-alive"
|
|
1003
|
-
}
|
|
1004
|
-
});
|
|
1005
|
-
} else {
|
|
1006
|
-
const data = await response.json();
|
|
1007
|
-
const openaiResponse = convertAnthropicResponseToOpenAI(data);
|
|
1008
|
-
return new Response(JSON.stringify(openaiResponse), {
|
|
1009
|
-
headers: { "Content-Type": "application/json" }
|
|
1010
|
-
});
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
};
|
|
1014
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1015
|
-
0 && (module.exports = {
|
|
1016
|
-
AnthropicTransformer
|
|
1017
|
-
});
|
|
6
|
+
exports.AnthropicTransformer = _chunk4VAVYUZScjs.AnthropicTransformer;
|