bailinghub 0.8.0 → 0.9.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.en.md +6 -5
- package/README.md +6 -5
- package/docker-compose.images.yml +2 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +12 -1
- package/docs/CHANGELOG.md +12 -1
- package/docs/COMPATIBILITY.en.md +4 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/MODEL_BILLING.en.md +123 -0
- package/docs/MODEL_BILLING.md +125 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
- package/docs/README.en.md +5 -1
- package/docs/README.md +4 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
- package/docs/UPGRADE_v0.9.0.en.md +54 -0
- package/docs/UPGRADE_v0.9.0.md +54 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
- package/package.json +1 -1
- package/scripts/check-doc-links.mjs +4 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +1 -0
- package/scripts/sdk-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +1 -0
- package/sdk/node/README.md +17 -0
- package/sdk/node/examples/billing.mjs +21 -0
- package/sdk/node/package.json +5 -1
- package/sdk/node/src/index.mjs +2 -0
- package/sdk/node/src/usage.d.mts +74 -0
- package/sdk/node/src/usage.mjs +62 -0
- package/sdk/node/tests/usage-types.mts +23 -0
- package/sdk/node/tests/usage.test.mjs +81 -0
- package/sdk/php7/README.md +19 -2
- package/sdk/php7/examples/billing.php +27 -0
- package/sdk/php7/examples/well-known.php +1 -1
- package/sdk/php7/src/ToolSpec.php +1 -1
- package/sdk/php7/src/UsageClient.php +95 -0
- package/sdk/php7/src/UsageClientException.php +22 -0
- package/sdk/php7/tests/billing-core-http.php +59 -0
- package/sdk/php7/tests/usage-client.php +78 -0
- package/sql/063_usage_model_billing.sql +153 -0
- package/sql/064_period_plan_allowance.sql +25 -0
- package/sql/README.en.md +12 -4
- package/sql/README.md +14 -6
- package/src/app/auth.ts +2 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/infrastructure/config/configstore.ts +6 -0
- package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
- package/src/modules/usage/billing-contracts.ts +59 -0
- package/src/modules/usage/billing-decimal.test.ts +22 -0
- package/src/modules/usage/billing-decimal.ts +36 -0
- package/src/modules/usage/billing-external.ts +39 -0
- package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
- package/src/modules/usage/billing-ledger.test.ts +51 -0
- package/src/modules/usage/billing-ledger.ts +104 -0
- package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
- package/src/modules/usage/billing-presentation.test.ts +49 -0
- package/src/modules/usage/billing-presentation.ts +34 -0
- package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
- package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
- package/src/modules/usage/billing-repository.ts +463 -0
- package/src/modules/usage/contracts.ts +49 -0
- package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
- package/src/modules/usage/errors.ts +19 -0
- package/src/modules/usage/http.ts +85 -0
- package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
- package/src/modules/usage/identity.mysql.test.ts +120 -0
- package/src/modules/usage/identity.ts +303 -0
- package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
- package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
- package/src/modules/usage/model-gateway.ts +229 -0
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
- package/src/modules/usage/model-tool-provider.test.ts +37 -0
- package/src/modules/usage/model-tool-provider.ts +110 -0
- package/src/modules/usage/model-tools.test.ts +36 -0
- package/src/modules/usage/model-tools.ts +62 -0
- package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
- package/src/modules/usage/period.test.ts +26 -0
- package/src/modules/usage/period.ts +96 -0
- package/src/modules/usage/pricing.test.ts +178 -0
- package/src/modules/usage/pricing.ts +228 -0
- package/src/modules/usage/provider-failure.ts +37 -0
- package/src/modules/usage/provider-stream.test.ts +85 -0
- package/src/modules/usage/provider-stream.ts +77 -0
- package/src/modules/usage/provider.test.ts +67 -0
- package/src/modules/usage/provider.ts +142 -0
- package/src/modules/usage/repository.ts +539 -0
- package/src/modules/usage/service-availability.mysql.test.ts +68 -0
- package/src/modules/usage/service-availability.ts +13 -0
- package/src/modules/usage/service-delete.mysql.test.ts +87 -0
- package/src/modules/usage/stream-http.ts +32 -0
- package/src/modules/usage/test-harness.ts +108 -0
- package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
- package/src/modules/usage/usage-deletion.ts +119 -0
- package/src/modules/usage/validation.test.ts +18 -0
- package/src/modules/usage/validation.ts +33 -0
- package/src/routes/admin-billing-usage.ts +73 -0
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +4 -0
- package/src/routes/private.ts +8 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-Bervi5JU.css +1 -0
- package/web/console/assets/Accounts-DnddhY6t.js +3 -0
- package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-VInbD7JS.js} +1 -1
- package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-34qUPHf0.js} +1 -1
- package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-BbVgkSm2.js} +1 -1
- package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-DgscF28e.js} +1 -1
- package/web/console/assets/{Channels-B9n4fbxg.js → Channels-Bp-yuk8d.js} +1 -1
- package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-C9Ft60TS.js} +1 -1
- package/web/console/assets/{Clients-CI3DBDHf.js → Clients-NPldD-DD.js} +1 -1
- package/web/console/assets/{Cost-JgNXQPlN.js → Cost-DZcuB-EB.js} +1 -1
- package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-RTT7N6zl.js} +1 -1
- package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-_LeK8cce.js} +1 -1
- package/web/console/assets/{Executors-CRbboOCZ.js → Executors-Bi7H8rIm.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
- package/web/console/assets/{Kb-CgLNGjRp.js → Kb-BHamz8NP.js} +2 -2
- package/web/console/assets/{Login-C52JmXzx.js → Login-C1rJR-6w.js} +1 -1
- package/web/console/assets/{Projects-CDOvHPVS.js → Projects-BRA4a48v.js} +1 -1
- package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
- package/web/console/assets/Routes-CyXV4Pba.css +1 -0
- package/web/console/assets/{Runs-DYNDXsqk.js → Runs-B_fa_BlD.js} +1 -1
- package/web/console/assets/{Setup-B91P6i1x.js → Setup-C1_d0mFy.js} +1 -1
- package/web/console/assets/Shell-CHEV6RGC.js +1 -0
- package/web/console/assets/Shell-ykb-tUfo.css +1 -0
- package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DlG3ojhA.js} +1 -1
- package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-DYo2gg6d.js} +1 -1
- package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-DKCoUZlq.js} +1 -1
- package/web/console/assets/{Targets-CuuIYeZO.js → Targets-CdkG6BPR.js} +1 -1
- package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DVpCt0ox.js} +1 -1
- package/web/console/assets/Usage-CAeDGjrb.css +1 -0
- package/web/console/assets/Usage-DWCpLugC.js +1 -0
- package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
- package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
- package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
- package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
- package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
- package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
- package/web/console/assets/index-H1kfa0Mj.js +2 -0
- package/web/console/assets/{request-DeGya810.js → request-DLsP1_ot.js} +1 -1
- package/web/console/assets/{schema-BqlqLw1R.js → schema-BLOHvAJQ.js} +1 -1
- package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
- package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
- package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
- package/web/console/index.html +3 -3
- package/web-admin/README.md +17 -0
- package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
- package/web-admin/src/components/UsageHelp.vue +72 -0
- package/web-admin/src/components/UsageServiceReferences.vue +169 -0
- package/web-admin/src/layout/Shell.vue +22 -5
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentTasks.vue +2 -2
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +8 -4
- package/web-admin/src/styles/base.css +57 -0
- package/web-admin/src/table-widths.ts +16 -1
- package/web-admin/src/usage-deletion.ts +40 -0
- package/web-admin/src/usage-management.ts +13 -0
- package/web-admin/src/usage-presentation.test.ts +21 -0
- package/web-admin/src/usage-presentation.ts +107 -0
- package/web-admin/src/usage-price-preview.test.ts +60 -0
- package/web-admin/src/usage-price-preview.ts +54 -0
- package/web-admin/tests/token-usage.browser.mjs +773 -0
- package/web-admin/tests/usage-access.browser.mjs +398 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
- package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
- package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
- package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-X9vHLpKW.js +0 -124
- package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
- package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
- package/web/console/assets/index-UGvfF3Xr.js +0 -2
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { ResolvedLlmCredential } from '../../core/runtime/credential-resolver';
|
|
2
|
+
import type { UsageServiceConfig } from './contracts';
|
|
3
|
+
import { UsageError, usageAssert } from './errors';
|
|
4
|
+
import { readProviderExchange } from './provider-stream';
|
|
5
|
+
|
|
6
|
+
export type JsonObject = Record<string, unknown>;
|
|
7
|
+
export interface UsageModelRequest {
|
|
8
|
+
operation_id: string;
|
|
9
|
+
messages: JsonObject[];
|
|
10
|
+
tools?: JsonObject[];
|
|
11
|
+
tool_choice?: unknown;
|
|
12
|
+
temperature?: number;
|
|
13
|
+
provider_options?: JsonObject;
|
|
14
|
+
}
|
|
15
|
+
export interface ProviderResult {
|
|
16
|
+
response: JsonObject;
|
|
17
|
+
executionId: string | null;
|
|
18
|
+
usage?: { inputTokens: number; outputTokens: number };
|
|
19
|
+
rawUsage?: JsonObject;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function object(value: unknown): value is JsonObject {
|
|
23
|
+
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
|
24
|
+
}
|
|
25
|
+
function onlyKeys(value: JsonObject, allowed: string[]): void {
|
|
26
|
+
usageAssert(Object.keys(value).every(key => allowed.includes(key)), 'USAGE_UNSUPPORTED_INPUT', 'This input field is not supported by the model gateway.', 400);
|
|
27
|
+
}
|
|
28
|
+
function nonempty(value: unknown, max: number): value is string { return typeof value === 'string' && value.length > 0 && value.length <= max; }
|
|
29
|
+
function tokenCount(value: unknown): value is number { return Number.isSafeInteger(value) && Number(value) >= 0; }
|
|
30
|
+
|
|
31
|
+
/** Copy the host's supported model wire format; credentials and routing remain service-owned. */
|
|
32
|
+
export function normalizeModelRequest(value: unknown): UsageModelRequest {
|
|
33
|
+
usageAssert(object(value), 'USAGE_INVALID_INPUT', 'A JSON object is required.', 400);
|
|
34
|
+
onlyKeys(value, ['operation_id', 'messages', 'tools', 'tool_choice', 'temperature', 'provider_options']);
|
|
35
|
+
usageAssert(nonempty(value.operation_id, 191), 'USAGE_INVALID_INPUT', 'An original operation ID is required.', 400);
|
|
36
|
+
usageAssert(Array.isArray(value.messages) && value.messages.length > 0 && value.messages.length <= 1024, 'USAGE_INVALID_INPUT', 'A bounded message list is required.', 400);
|
|
37
|
+
for (const message of value.messages) {
|
|
38
|
+
usageAssert(object(message), 'USAGE_INVALID_INPUT', 'Invalid message.', 400);
|
|
39
|
+
onlyKeys(message, ['role', 'content', 'name', 'tool_call_id', 'tool_calls', 'reasoning_content']);
|
|
40
|
+
usageAssert(['system', 'developer', 'user', 'assistant', 'tool'].includes(String(message.role)), 'USAGE_UNSUPPORTED_INPUT', 'Unsupported message role.', 400);
|
|
41
|
+
usageAssert(typeof message.content === 'string' || validContentParts(message.content) || (message.role === 'assistant' && message.content === null && Array.isArray(message.tool_calls)), 'USAGE_UNSUPPORTED_INPUT', 'Only text, image content parts and function-call messages are supported.', 400);
|
|
42
|
+
if (message.reasoning_content !== undefined) usageAssert(message.role === 'assistant' && typeof message.reasoning_content === 'string', 'USAGE_INVALID_INPUT', 'Invalid assistant reasoning content.', 400);
|
|
43
|
+
if (message.name !== undefined) usageAssert(nonempty(message.name, 128), 'USAGE_INVALID_INPUT', 'Invalid message name.', 400);
|
|
44
|
+
if (message.role === 'tool') usageAssert(nonempty(message.tool_call_id, 256), 'USAGE_INVALID_INPUT', 'A tool result requires its original call ID.', 400);
|
|
45
|
+
if (message.tool_calls !== undefined) {
|
|
46
|
+
usageAssert(message.role === 'assistant' && Array.isArray(message.tool_calls) && message.tool_calls.length <= 128, 'USAGE_INVALID_INPUT', 'Invalid function calls.', 400);
|
|
47
|
+
for (const call of message.tool_calls) {
|
|
48
|
+
usageAssert(object(call) && object(call.function), 'USAGE_INVALID_INPUT', 'Invalid function call.', 400);
|
|
49
|
+
onlyKeys(call, ['id', 'type', 'function']); onlyKeys(call.function, ['name', 'arguments']);
|
|
50
|
+
usageAssert(nonempty(call.id, 256) && call.type === 'function' && nonempty(call.function.name, 128) && typeof call.function.arguments === 'string', 'USAGE_INVALID_INPUT', 'Invalid function call.', 400);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (value.tools !== undefined) {
|
|
55
|
+
usageAssert(Array.isArray(value.tools) && value.tools.length <= 128, 'USAGE_INVALID_INPUT', 'Too many function declarations.', 400);
|
|
56
|
+
for (const tool of value.tools) {
|
|
57
|
+
usageAssert(object(tool) && tool.type === 'function' && object(tool.function), 'USAGE_UNSUPPORTED_INPUT', 'Only function declarations are supported.', 400);
|
|
58
|
+
onlyKeys(tool, ['type', 'function']); onlyKeys(tool.function, ['name', 'description', 'parameters', 'strict']);
|
|
59
|
+
usageAssert(nonempty(tool.function.name, 128) && object(tool.function.parameters), 'USAGE_INVALID_INPUT', 'A function requires its name and full schema.', 400);
|
|
60
|
+
if (tool.function.description !== undefined) usageAssert(typeof tool.function.description === 'string', 'USAGE_INVALID_INPUT', 'Invalid function description.', 400);
|
|
61
|
+
if (tool.function.strict !== undefined) usageAssert(typeof tool.function.strict === 'boolean', 'USAGE_INVALID_INPUT', 'Invalid strict flag.', 400);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (value.tool_choice !== undefined) {
|
|
65
|
+
const choice = value.tool_choice;
|
|
66
|
+
const named = object(choice) && choice.type === 'function' && object(choice.function) && nonempty(choice.function.name, 128);
|
|
67
|
+
usageAssert(['auto', 'none', 'required'].includes(String(choice)) || named, 'USAGE_UNSUPPORTED_INPUT', 'Invalid tool choice.', 400);
|
|
68
|
+
if (named) { onlyKeys(choice as JsonObject, ['type', 'function']); onlyKeys((choice as JsonObject).function as JsonObject, ['name']); }
|
|
69
|
+
}
|
|
70
|
+
if (value.temperature !== undefined) usageAssert(typeof value.temperature === 'number' && Number.isFinite(value.temperature) && value.temperature >= 0 && value.temperature <= 2, 'USAGE_INVALID_INPUT', 'Temperature must be between zero and two.', 400);
|
|
71
|
+
if (value.provider_options !== undefined) validateProviderOptions(value.provider_options);
|
|
72
|
+
return value as unknown as UsageModelRequest;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Gateway transport formats do not promise that the configured provider/model supports every modality.
|
|
76
|
+
function validContentParts(value: unknown): boolean {
|
|
77
|
+
return Array.isArray(value) && value.length > 0 && value.every(part => {
|
|
78
|
+
if (!object(part)) return false;
|
|
79
|
+
if (part.type === 'text') return typeof part.text === 'string' && Object.keys(part).every(k => ['type', 'text'].includes(k));
|
|
80
|
+
if (part.type !== 'image_url' || !object(part.image_url)) return false;
|
|
81
|
+
const image = part.image_url;
|
|
82
|
+
if (typeof image.url !== 'string' || !/^(https?:\/\/|data:image\/[a-zA-Z0-9.+-]+;base64,)/.test(image.url)) return false;
|
|
83
|
+
return Object.keys(part).every(k => ['type', 'image_url'].includes(k))
|
|
84
|
+
&& Object.keys(image).every(k => ['url', 'detail'].includes(k))
|
|
85
|
+
&& (image.detail === undefined || ['auto', 'low', 'high'].includes(String(image.detail)));
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
const PROVIDER_OPTION_KEYS = ['max_tokens', 'max_completion_tokens', 'top_p', 'stop', 'seed', 'presence_penalty',
|
|
89
|
+
'frequency_penalty', 'parallel_tool_calls', 'response_format', 'reasoning_effort', 'enable_thinking', 'thinking', 'verbosity'];
|
|
90
|
+
function validateProviderOptions(value: unknown): asserts value is JsonObject {
|
|
91
|
+
usageAssert(object(value), 'USAGE_INVALID_INPUT', 'Provider options must be an object.', 400);
|
|
92
|
+
onlyKeys(value, PROVIDER_OPTION_KEYS);
|
|
93
|
+
usageAssert(!(value.max_tokens !== undefined && value.max_completion_tokens !== undefined), 'USAGE_INVALID_INPUT', 'Choose one output limit field.', 400);
|
|
94
|
+
for (const key of ['max_tokens', 'max_completion_tokens']) if (value[key] !== undefined)
|
|
95
|
+
usageAssert(Number.isSafeInteger(value[key]) && Number(value[key]) > 0, 'USAGE_INVALID_INPUT', 'Invalid output limit.', 400);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function canonicalJson(value: unknown): string {
|
|
99
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
|
100
|
+
if (object(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
|
|
101
|
+
return JSON.stringify(value);
|
|
102
|
+
}
|
|
103
|
+
export function providerBody(request: UsageModelRequest, config: UsageServiceConfig, streaming = false): JsonObject {
|
|
104
|
+
if (config.inputModalities && !config.inputModalities.includes('image')) usageAssert(
|
|
105
|
+
!request.messages.some(message => Array.isArray(message.content) && message.content.some(part => object(part) && part.type === 'image_url')),
|
|
106
|
+
'USAGE_UNSUPPORTED_INPUT', 'This model service is configured for text input only.', 400);
|
|
107
|
+
const options = request.provider_options ?? {};
|
|
108
|
+
validateProviderOptions(options);
|
|
109
|
+
const outputKey = options.max_completion_tokens === undefined ? 'max_tokens' : 'max_completion_tokens';
|
|
110
|
+
const requested = Number(options[outputKey] ?? config.maxOutputTokens);
|
|
111
|
+
usageAssert(requested <= config.maxOutputTokens, 'USAGE_OUTPUT_LIMIT', 'The requested output limit exceeds the model service limit.', 413);
|
|
112
|
+
const result: JsonObject = { ...options, model: config.model, messages: request.messages, stream: streaming, [outputKey]: requested,
|
|
113
|
+
...(streaming ? { stream_options: { include_usage: true } } : {}) };
|
|
114
|
+
for (const name of ['tools', 'tool_choice', 'temperature'] as const) if (request[name] !== undefined) result[name] = request[name];
|
|
115
|
+
const actual = Buffer.byteLength(JSON.stringify(result), 'utf8');
|
|
116
|
+
if (actual > config.maxInputBytes) throw new UsageError('USAGE_INPUT_LIMIT', 'The complete model request exceeds this service input byte limit.', 413,
|
|
117
|
+
{ input_limit: { kind: 'serialized_provider_bytes', actual, allowed: config.maxInputBytes,
|
|
118
|
+
message_count: request.messages.length, tool_count: request.tools?.length ?? 0 } });
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
function providerUrl(credential: ResolvedLlmCredential, path: string): string {
|
|
122
|
+
const base = new URL(credential.base_url.endsWith('/') ? credential.base_url : `${credential.base_url}/`);
|
|
123
|
+
usageAssert(['http:', 'https:'].includes(base.protocol) && !base.username && !base.password && !base.search && !base.hash, 'USAGE_SERVICE_UNAVAILABLE', 'The configured model endpoint is invalid.', 503);
|
|
124
|
+
const result = new URL(path, base);
|
|
125
|
+
usageAssert(result.origin === base.origin && !result.search && !result.hash, 'USAGE_SERVICE_UNAVAILABLE', 'The service endpoint must remain in the configured provider origin.', 503);
|
|
126
|
+
return result.href;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function verifiedUsage(value: unknown): ProviderResult['usage'] {
|
|
130
|
+
if (!object(value) || !tokenCount(value.prompt_tokens) || !tokenCount(value.completion_tokens)) return undefined;
|
|
131
|
+
if (value.total_tokens !== undefined && (!tokenCount(value.total_tokens) || value.total_tokens !== Number(value.prompt_tokens) + Number(value.completion_tokens))) return undefined;
|
|
132
|
+
return { inputTokens: Number(value.prompt_tokens), outputTokens: Number(value.completion_tokens) };
|
|
133
|
+
}
|
|
134
|
+
/** Transport completion and model semantics are separate. The local adapter owns the latter. */
|
|
135
|
+
export async function executeProvider(credential: ResolvedLlmCredential, config: UsageServiceConfig, body: JsonObject, fetcher: typeof fetch = fetch,
|
|
136
|
+
onProvider?: (packet: JsonObject) => Promise<void>): Promise<ProviderResult> {
|
|
137
|
+
const signal = AbortSignal.timeout(config.timeoutMs);
|
|
138
|
+
const response = await fetcher(providerUrl(credential, 'chat/completions'), { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json', authorization: `Bearer ${credential.api_key}` }, body: JSON.stringify(body), signal });
|
|
139
|
+
// HTTP error bodies are also returned to the local provider adapter. Do not
|
|
140
|
+
// retry them or mistake a transport-complete error response for a missing body.
|
|
141
|
+
return readProviderExchange(response, onProvider, signal);
|
|
142
|
+
}
|