nolo-cli 0.1.13 → 0.1.14
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 +9 -2
- package/agent-runtime/hostAdapter.ts +53 -0
- package/agent-runtime/index.ts +28 -0
- package/agent-runtime/localLoop.ts +62 -0
- package/agent-runtime/runtimeDecision.ts +70 -0
- package/agent-runtime/types.ts +87 -0
- package/agentRuntimeCommands.ts +139 -22
- package/agentRuntimeLocal.ts +7 -0
- package/ai/agent/_executeModel.ts +118 -0
- package/ai/agent/agentSlice.ts +544 -1
- package/ai/agent/appWorkingMemory.ts +126 -0
- package/ai/agent/avatarUtils.ts +24 -0
- package/ai/agent/buildEditingContext.ts +373 -0
- package/ai/agent/buildSystemPrompt.ts +532 -0
- package/ai/agent/cleanAgentMessages.ts +140 -0
- package/ai/agent/cliChatClient.ts +119 -0
- package/ai/agent/contextCompiler.ts +107 -0
- package/ai/agent/contextLayerContract.ts +44 -0
- package/ai/agent/createAgentSchema.ts +234 -0
- package/ai/agent/executeToolCall.ts +58 -0
- package/ai/agent/fetchAgentContexts.ts +42 -0
- package/ai/agent/generatePrompt.ts +3 -0
- package/ai/agent/getFullChatContextKeys.ts +168 -0
- package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
- package/ai/agent/hooks/useAgentConfig.ts +61 -0
- package/ai/agent/hooks/useAgentDialog.ts +35 -0
- package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
- package/ai/agent/hooks/usePublicAgents.ts +473 -0
- package/ai/agent/persistMessageWithFixedId.ts +37 -0
- package/ai/agent/planSlice.ts +259 -0
- package/ai/agent/referenceUtils.ts +229 -0
- package/ai/agent/runAgentBackground.ts +238 -0
- package/ai/agent/runAgentClientLoop.ts +138 -0
- package/ai/agent/runtimeGuidance.ts +97 -0
- package/ai/agent/runtimeServerBase.ts +37 -0
- package/ai/agent/server/fetchPublicAgents.ts +128 -0
- package/ai/agent/startParallelAgentStreams.ts +424 -0
- package/ai/agent/startupProtocol.ts +53 -0
- package/ai/agent/streamAgentChatTurn.ts +1299 -0
- package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
- package/ai/agent/types.ts +71 -0
- package/ai/agent/utils/imageOutput.ts +39 -0
- package/ai/agent/utils/publicImageAgentMode.ts +26 -0
- package/ai/agent/utils/sortUtils.ts +250 -0
- package/ai/agent/web/referencePickerUtils.ts +146 -0
- package/ai/ai.locale.ts +1083 -0
- package/ai/chat/accumulateToolCallChunks.ts +95 -0
- package/ai/chat/fetchUtils.native.ts +276 -0
- package/ai/chat/fetchUtils.ts +153 -0
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
- package/ai/chat/parseApiError.ts +64 -0
- package/ai/chat/parseMultilineSSE.ts +95 -0
- package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
- package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
- package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
- package/ai/chat/shouldUseServerProxy.ts +18 -0
- package/ai/chat/sseClient.native.ts +91 -0
- package/ai/chat/sseClient.ts +67 -0
- package/ai/chat/streamReader.native.ts +31 -0
- package/ai/chat/streamReader.ts +62 -0
- package/ai/chat/updateTotalUsage.ts +72 -0
- package/ai/context/buildReferenceContext.ts +437 -0
- package/ai/context/calculateContextUsage.ts +133 -0
- package/ai/context/retention.ts +165 -0
- package/ai/context/tokenUtils.ts +78 -0
- package/ai/index.ts +1 -1
- package/ai/llm/agentCapabilities.ts +74 -0
- package/ai/llm/calculateGeminiImageTokens.ts +57 -0
- package/ai/llm/deepinfra.ts +28 -0
- package/ai/llm/fireworks.ts +68 -0
- package/ai/llm/generateRequestBody.ts +165 -0
- package/ai/llm/getModelContextWindow.ts +84 -0
- package/ai/llm/getNoloKey.ts +37 -0
- package/ai/llm/getPricing.ts +232 -0
- package/ai/llm/hooks/useModelPricing.ts +75 -0
- package/ai/llm/imagePricing.ts +66 -0
- package/ai/llm/isResponseAPIModel.ts +13 -0
- package/ai/llm/kimi.ts +18 -0
- package/ai/llm/mimo.ts +71 -0
- package/ai/llm/mistral.ts +22 -0
- package/ai/llm/modelAvatar.ts +427 -0
- package/ai/llm/models.ts +45 -0
- package/ai/llm/openrouterModels.ts +141 -0
- package/ai/llm/providers.ts +307 -0
- package/ai/llm/reasoningModels.ts +28 -0
- package/ai/llm/types.ts +59 -0
- package/ai/llm/usageRequestOptions.ts +59 -0
- package/ai/memory/capture.ts +148 -0
- package/ai/memory/consolidate.ts +104 -0
- package/ai/memory/delete.ts +147 -0
- package/ai/memory/overlay.ts +84 -0
- package/ai/memory/query.ts +38 -0
- package/ai/memory/queryShared.ts +160 -0
- package/ai/memory/rank.ts +105 -0
- package/ai/memory/recentRelationshipRecap.ts +247 -0
- package/ai/memory/remember.ts +167 -0
- package/ai/memory/runtime.ts +76 -0
- package/ai/memory/store.ts +20 -0
- package/ai/memory/storeShared.ts +76 -0
- package/ai/memory/types.ts +46 -0
- package/ai/memory/understanding.ts +349 -0
- package/ai/memory/understandingGreeting.ts +264 -0
- package/ai/messages/type.ts +20 -0
- package/ai/policy/personalizationDialog.ts +333 -0
- package/ai/policy/runtimePolicy.ts +440 -0
- package/ai/policy/selfUpdateFields.ts +48 -0
- package/ai/policy/types.ts +64 -0
- package/ai/skills/referenceRuntime.ts +274 -0
- package/ai/skills/skillDiagnostics.ts +251 -0
- package/ai/skills/skillDocBuilder.ts +139 -0
- package/ai/skills/skillDocProtocol.ts +434 -0
- package/ai/skills/skillReferenceSummary.ts +63 -0
- package/ai/skills/skillSummaryMarker.ts +26 -0
- package/ai/token/calculatePrice.ts +546 -0
- package/ai/token/db.ts +98 -0
- package/ai/token/externalToolCost.ts +321 -0
- package/ai/token/hooks/useRecords.ts +65 -0
- package/ai/token/missingUsageEstimate.ts +42 -0
- package/ai/token/modelUsageQuery.ts +252 -0
- package/ai/token/normalizeUsage.ts +84 -0
- package/ai/token/openaiImageGenerationUsage.ts +56 -0
- package/ai/token/prepareTokenUsageData.ts +88 -0
- package/ai/token/query.ts +88 -0
- package/ai/token/queryUserTokens.ts +59 -0
- package/ai/token/resolveBillingTarget.ts +52 -0
- package/ai/token/saveTokenRecord.ts +53 -0
- package/ai/token/serverDialogProjection.ts +78 -0
- package/ai/token/serverTokenWriter.ts +143 -0
- package/ai/token/stats.ts +21 -0
- package/ai/token/tokenThunks.ts +24 -0
- package/ai/token/types.ts +93 -0
- package/ai/tools/agent/agentTools.ts +176 -0
- package/ai/tools/agent/agentUpdateShared.ts +311 -0
- package/ai/tools/agent/callAgentTool.ts +139 -0
- package/ai/tools/agent/createAgentTool.ts +512 -0
- package/ai/tools/agent/createDialogTool.ts +69 -0
- package/ai/tools/agent/createSkillAgentTool.ts +62 -0
- package/ai/tools/agent/parallelBudget.ts +221 -0
- package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
- package/ai/tools/agent/runLlmTool.ts +96 -0
- package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
- package/ai/tools/agent/skillAgentArgs.ts +106 -0
- package/ai/tools/agent/skillAgentPreset.ts +89 -0
- package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
- package/ai/tools/agent/updateAgentTool.ts +96 -0
- package/ai/tools/agent/updateSelfTool.ts +113 -0
- package/ai/tools/amazonProductScraperTool.ts +86 -0
- package/ai/tools/apifyActorClient.ts +45 -0
- package/ai/tools/appEditGuard.ts +372 -0
- package/ai/tools/appReadSnapshot.ts +153 -0
- package/ai/tools/appTools.ts +1549 -0
- package/ai/tools/applyEditTool.ts +256 -0
- package/ai/tools/applyLineEditsTool.ts +312 -0
- package/ai/tools/browserTools/click.ts +33 -0
- package/ai/tools/browserTools/closeSession.ts +29 -0
- package/ai/tools/browserTools/common.ts +27 -0
- package/ai/tools/browserTools/openSession.ts +48 -0
- package/ai/tools/browserTools/readContent.ts +38 -0
- package/ai/tools/browserTools/selectOption.ts +46 -0
- package/ai/tools/browserTools/typeText.ts +42 -0
- package/ai/tools/category/createCategoryTool.ts +66 -0
- package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
- package/ai/tools/category/updateContentCategoryTool.ts +75 -0
- package/ai/tools/cfBrowserTools.ts +319 -0
- package/ai/tools/cfSpeechToTextTool.ts +49 -0
- package/ai/tools/checkEnvTool.ts +65 -0
- package/ai/tools/cloudflareCrawlTool.ts +289 -0
- package/ai/tools/codeSearchTool.ts +111 -0
- package/ai/tools/codeTools.ts +101 -0
- package/ai/tools/createDocTool.ts +132 -0
- package/ai/tools/createPlanTool.ts +999 -0
- package/ai/tools/createSkillDocTool.ts +155 -0
- package/ai/tools/createWorkflowTool.ts +154 -0
- package/ai/tools/deepseekOcrTool.ts +34 -0
- package/ai/tools/delayTool.ts +31 -0
- package/ai/tools/deleteSpacesTool.ts +325 -0
- package/ai/tools/deleteSpacesToolModel.ts +159 -0
- package/ai/tools/devReloadUtils.ts +29 -0
- package/ai/tools/dialogMessageSearch.ts +137 -0
- package/ai/tools/doctorSkillTool.ts +72 -0
- package/ai/tools/ecommerceScraperTool.ts +86 -0
- package/ai/tools/emailTools.ts +549 -0
- package/ai/tools/evalSkillTool.ts +92 -0
- package/ai/tools/exaSearchTool.ts +64 -0
- package/ai/tools/execBashTool.ts +379 -0
- package/ai/tools/executeSqlTool.ts +192 -0
- package/ai/tools/fetchWebpageSupport.ts +309 -0
- package/ai/tools/fetchWebpageTool.ts +84 -0
- package/ai/tools/geminiImagePreviewTool.ts +361 -0
- package/ai/tools/generateDocxTool.ts +215 -0
- package/ai/tools/googleSearchScraperTool.ts +106 -0
- package/ai/tools/importDataTool.ts +133 -0
- package/ai/tools/importSkillTool.ts +162 -0
- package/ai/tools/index.ts +1927 -0
- package/ai/tools/listFilesTool.ts +82 -0
- package/ai/tools/listUserSpacesTool.ts +113 -0
- package/ai/tools/modelUsageTools.ts +199 -0
- package/ai/tools/olmOcrTool.ts +34 -0
- package/ai/tools/openaiImageTool.ts +267 -0
- package/ai/tools/prepareTools.ts +23 -0
- package/ai/tools/readDocTool.ts +84 -0
- package/ai/tools/readFileTool.ts +211 -0
- package/ai/tools/readTool.ts +163 -0
- package/ai/tools/readXPostTool.ts +233 -0
- package/ai/tools/rememberMemoryTool.ts +84 -0
- package/ai/tools/remotionVideoTool.ts +151 -0
- package/ai/tools/searchDialogMessagesTool.ts +222 -0
- package/ai/tools/searchRepoTool.ts +115 -0
- package/ai/tools/searchWorkspaceTool.ts +259 -0
- package/ai/tools/skillFollowup.ts +86 -0
- package/ai/tools/surfWeatherTool.ts +169 -0
- package/ai/tools/table/addTableRowTool.ts +217 -0
- package/ai/tools/table/createTableTool.ts +315 -0
- package/ai/tools/table/rowTools.ts +366 -0
- package/ai/tools/table/schemaTools.ts +244 -0
- package/ai/tools/table/shareTableTool.ts +148 -0
- package/ai/tools/table/toolShared.ts +129 -0
- package/ai/tools/toolApiClient.ts +198 -0
- package/ai/tools/toolNameAliases.ts +57 -0
- package/ai/tools/toolResultError.ts +42 -0
- package/ai/tools/toolRunSlice.ts +303 -0
- package/ai/tools/toolSchemaCompatibility.ts +53 -0
- package/ai/tools/toolVisibility.ts +4 -0
- package/ai/tools/types.ts +20 -0
- package/ai/tools/uiAskChoiceTool.ts +104 -0
- package/ai/tools/updateContentTitleTool.ts +84 -0
- package/ai/tools/updateDocTool.ts +105 -0
- package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
- package/ai/tools/whisperTool.ts +77 -0
- package/ai/tools/writeFileTool.ts +210 -0
- package/ai/tools/youtubeScraperTool.ts +116 -0
- package/ai/tools/ziweiChartTool.ts +678 -0
- package/ai/types.ts +55 -0
- package/ai/workflow/workflowExecutor.ts +323 -0
- package/ai/workflow/workflowSlice.ts +73 -0
- package/ai/workflow/workflowTypes.ts +106 -0
- package/client/agentRun.test.ts +240 -0
- package/client/agentRun.ts +182 -19
- package/client/compactDialog.test.ts +238 -0
- package/client/localRuntimeAdapter.test.ts +135 -0
- package/client/localRuntimeAdapter.ts +244 -0
- package/client/profileConfig.test.ts +40 -0
- package/client/streamingOutput.test.ts +22 -0
- package/client/streamingOutput.ts +38 -0
- package/commandRegistry.ts +9 -2
- package/connector-experimental/index.ts +5 -0
- package/database/actions/cacheMergedUserData.ts +64 -0
- package/database/actions/common.ts +242 -0
- package/database/actions/deleteFile.ts +40 -0
- package/database/actions/fetchUserData.ts +16 -0
- package/database/actions/fileContent.ts +125 -0
- package/database/actions/patch.ts +155 -0
- package/database/actions/read.ts +337 -0
- package/database/actions/readAndWait.ts +224 -0
- package/database/actions/readRequestManager.ts +120 -0
- package/database/actions/remove.ts +94 -0
- package/database/actions/replication.ts +366 -0
- package/database/actions/upload.ts +174 -0
- package/database/actions/upsert.ts +56 -0
- package/database/actions/write.ts +126 -0
- package/database/client/db.native.ts +73 -0
- package/database/client/db.ts +51 -0
- package/database/client/fetchUserData.ts +61 -0
- package/database/client/handleError.ts +19 -0
- package/database/client/queryRequest.ts +21 -0
- package/database/config.ts +21 -0
- package/database/dbActionThunks.ts +1 -0
- package/database/dbSlice.ts +149 -0
- package/database/email.ts +42 -0
- package/database/fileRing.ts +51 -0
- package/database/fileSharding.ts +70 -0
- package/database/fileStorage.native.ts +92 -0
- package/database/fileStorage.ts +232 -0
- package/database/fileUrl.ts +34 -0
- package/database/hooks/useUserData.ts +489 -0
- package/database/index.ts +1 -0
- package/database/keys.ts +765 -0
- package/database/queryPrefixes.ts +14 -0
- package/database/requests.ts +443 -0
- package/database/runtimeServerContext.ts +35 -0
- package/database/server/MemoryDB.ts +76 -0
- package/database/server/actorAccess.ts +76 -0
- package/database/server/agentDelegation.ts +124 -0
- package/database/server/coreDataOwnership.ts +13 -0
- package/database/server/coreDataProxy.ts +76 -0
- package/database/server/cybotReadonly.ts +18 -0
- package/database/server/dataHandlers.ts +111 -0
- package/database/server/db.ts +118 -0
- package/database/server/dbPath.ts +20 -0
- package/database/server/delete.ts +499 -0
- package/database/server/emailRepository.ts +1480 -0
- package/database/server/ensureDbOpen.ts +12 -0
- package/database/server/fileRead.ts +337 -0
- package/database/server/fileService.ts +436 -0
- package/database/server/handleTransaction.ts +86 -0
- package/database/server/patch.ts +282 -0
- package/database/server/query.ts +138 -0
- package/database/server/read.ts +325 -0
- package/database/server/resourceAccess.ts +211 -0
- package/database/server/routes.ts +110 -0
- package/database/server/spaceMemberAuthority.ts +67 -0
- package/database/server/upload.ts +159 -0
- package/database/server/write.ts +494 -0
- package/database/server/writeAuthority.ts +133 -0
- package/database/sqliteDb.ts +46 -0
- package/database/table/deleteTable.ts +120 -0
- package/database/tenantPlacement.ts +57 -0
- package/database/tombstones.ts +52 -0
- package/database/userDataLoadDecision.ts +17 -0
- package/database/userDataMerge.ts +95 -0
- package/database/userPreferenceRegister.ts +108 -0
- package/database/utils/dbPath.ts +47 -0
- package/database/utils/ulid.native.ts +6 -0
- package/database/utils/ulid.ts +1 -0
- package/index.ts +25 -15
- package/localRuntimeDb.ts +28 -0
- package/package.json +16 -4
- package/runtimeModeArgs.ts +33 -0
- package/tui/readlineWorkspace.ts +1 -0
- package/tui/session.ts +22 -0
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
// 路径: ai/token/calculatePrice.ts
|
|
2
|
+
|
|
3
|
+
import { nolotusId } from "core/init";
|
|
4
|
+
import { Model, ModelPrice } from "ai/llm/types";
|
|
5
|
+
import { findModelConfig, getModelConfig } from "ai/llm/providers";
|
|
6
|
+
import { getApproxPricePerImage } from "ai/llm/imagePricing";
|
|
7
|
+
import {
|
|
8
|
+
isOpenAIFlexPricedModel,
|
|
9
|
+
type OpenAIServiceTier,
|
|
10
|
+
resolveOpenAIServiceTier,
|
|
11
|
+
} from "integrations/openai/flexTier";
|
|
12
|
+
|
|
13
|
+
// ==================== 接口定义 ====================
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 这里的 Usage 是「已经 normalize 过」的结构
|
|
17
|
+
* ——来自 normalizeUsage,字段名统一成这几个
|
|
18
|
+
*/
|
|
19
|
+
export interface Usage {
|
|
20
|
+
input_tokens: number;
|
|
21
|
+
output_tokens: number;
|
|
22
|
+
cache_creation_input_tokens: number;
|
|
23
|
+
cache_read_input_tokens: number;
|
|
24
|
+
/**
|
|
25
|
+
* 对于 OpenRouter 等支持 usage.cost 的 provider:
|
|
26
|
+
* usage.cost 是 provider 返回的账户扣费金额。
|
|
27
|
+
* OpenRouter 官方 credits 以 USD 为基准,本仓库仍需再换算成平台 credits。
|
|
28
|
+
*/
|
|
29
|
+
cost?: number;
|
|
30
|
+
billing_service_tier?: string;
|
|
31
|
+
image_generation_count?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ExternalPrice {
|
|
35
|
+
input: number;
|
|
36
|
+
output: number;
|
|
37
|
+
creatorId?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface CalculatePriceParams {
|
|
41
|
+
modelName: string;
|
|
42
|
+
usage: Usage;
|
|
43
|
+
externalPrice?: ExternalPrice;
|
|
44
|
+
/**
|
|
45
|
+
* provider 名称(deepseek / openrouter / anthropic 等)。
|
|
46
|
+
* apiSource="custom" 的 agent 不填此字段,传 undefined 即可。
|
|
47
|
+
* 注意:不要依赖参数默认值,调用方应显式传值或不传。
|
|
48
|
+
*/
|
|
49
|
+
provider?: string;
|
|
50
|
+
billingServiceTier?: string;
|
|
51
|
+
sharingLevel?: "default" | "split" | "full";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface PriceResult {
|
|
55
|
+
cost: number;
|
|
56
|
+
pay: Record<string, number>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface CostBreakdown {
|
|
60
|
+
regular: number;
|
|
61
|
+
charge: number;
|
|
62
|
+
details?: {
|
|
63
|
+
inputCost: number;
|
|
64
|
+
outputCost: number;
|
|
65
|
+
cachingWriteCost: number;
|
|
66
|
+
cachingReadCost: number;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ==================== 核心逻辑:阶梯定价解析 ====================
|
|
71
|
+
|
|
72
|
+
const resolveModelPrice = (model: Model, usage: Usage): ModelPrice => {
|
|
73
|
+
let activePrice = { ...model.price };
|
|
74
|
+
|
|
75
|
+
if (model.pricingStrategy?.type === "tiered_context") {
|
|
76
|
+
const contextSize = usage.input_tokens || 0;
|
|
77
|
+
const tiers = model.pricingStrategy.tiers || [];
|
|
78
|
+
|
|
79
|
+
const sortedTiers = [...tiers].sort((a, b) => a.minContext - b.minContext);
|
|
80
|
+
|
|
81
|
+
for (const tier of sortedTiers) {
|
|
82
|
+
if (contextSize >= tier.minContext) {
|
|
83
|
+
activePrice = { ...tier.price };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return activePrice;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const scaleModelPrice = (price: ModelPrice, multiplier: number): ModelPrice => ({
|
|
92
|
+
input: price.input * multiplier,
|
|
93
|
+
output: price.output * multiplier,
|
|
94
|
+
...(typeof price.cachingWrite === "number"
|
|
95
|
+
? { cachingWrite: price.cachingWrite * multiplier }
|
|
96
|
+
: {}),
|
|
97
|
+
...(typeof price.cachingRead === "number"
|
|
98
|
+
? { cachingRead: price.cachingRead * multiplier }
|
|
99
|
+
: {}),
|
|
100
|
+
...(typeof price.inputCacheHit === "number"
|
|
101
|
+
? { inputCacheHit: price.inputCacheHit * multiplier }
|
|
102
|
+
: {}),
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const scaleModelInputOutputPrice = (
|
|
106
|
+
price: ModelPrice,
|
|
107
|
+
multiplier: number
|
|
108
|
+
): ModelPrice => ({
|
|
109
|
+
...price,
|
|
110
|
+
input: price.input * multiplier,
|
|
111
|
+
output: price.output * multiplier,
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
const resolveGoogleServiceTierPrice = (
|
|
115
|
+
model: Model,
|
|
116
|
+
price: ModelPrice,
|
|
117
|
+
billingServiceTier?: string
|
|
118
|
+
): ModelPrice => {
|
|
119
|
+
const normalizedTier =
|
|
120
|
+
typeof billingServiceTier === "string"
|
|
121
|
+
? billingServiceTier.trim().toLowerCase()
|
|
122
|
+
: "";
|
|
123
|
+
const imageOutputPrice =
|
|
124
|
+
typeof model.imageTokenPricePerMillion === "number"
|
|
125
|
+
? model.imageTokenPricePerMillion
|
|
126
|
+
: undefined;
|
|
127
|
+
const priceWithImageOutput =
|
|
128
|
+
typeof imageOutputPrice === "number"
|
|
129
|
+
? { ...price, output: imageOutputPrice }
|
|
130
|
+
: price;
|
|
131
|
+
|
|
132
|
+
if (normalizedTier === "flex" || normalizedTier === "batch") {
|
|
133
|
+
return scaleModelInputOutputPrice(priceWithImageOutput, 0.5);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (normalizedTier === "priority") {
|
|
137
|
+
return scaleModelInputOutputPrice(priceWithImageOutput, 1.8);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return priceWithImageOutput;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const resolveEffectiveModelPrice = ({
|
|
144
|
+
model,
|
|
145
|
+
usage,
|
|
146
|
+
provider,
|
|
147
|
+
billingServiceTier,
|
|
148
|
+
}: {
|
|
149
|
+
model: Model;
|
|
150
|
+
usage: Usage;
|
|
151
|
+
provider: string;
|
|
152
|
+
billingServiceTier?: string;
|
|
153
|
+
}): ModelPrice => {
|
|
154
|
+
const resolvedPrice = resolveModelPrice(model, usage);
|
|
155
|
+
if (provider === "google") {
|
|
156
|
+
return resolveGoogleServiceTierPrice(model, resolvedPrice, billingServiceTier);
|
|
157
|
+
}
|
|
158
|
+
const effectiveOpenAIServiceTier = resolveOpenAIServiceTier({
|
|
159
|
+
providerName: provider,
|
|
160
|
+
model: model.name,
|
|
161
|
+
requestedServiceTier: billingServiceTier as OpenAIServiceTier | undefined,
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
if (provider === "openai" && effectiveOpenAIServiceTier === "flex") {
|
|
165
|
+
if (isOpenAIFlexPricedModel(model.name)) {
|
|
166
|
+
return resolvedPrice;
|
|
167
|
+
}
|
|
168
|
+
return scaleModelPrice(resolvedPrice, 0.5);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return resolvedPrice;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// ==================== 辅助逻辑:价格保护 ====================
|
|
175
|
+
|
|
176
|
+
const getEffectivePrices = (
|
|
177
|
+
resolvedPrice: ModelPrice,
|
|
178
|
+
externalPrice?: ExternalPrice
|
|
179
|
+
): {
|
|
180
|
+
input: number;
|
|
181
|
+
output: number;
|
|
182
|
+
cachingWrite: number;
|
|
183
|
+
cachingRead: number;
|
|
184
|
+
} => {
|
|
185
|
+
const effectiveInputPrice = Math.max(
|
|
186
|
+
externalPrice?.input || 0,
|
|
187
|
+
resolvedPrice.input
|
|
188
|
+
);
|
|
189
|
+
const effectiveOutputPrice = Math.max(
|
|
190
|
+
externalPrice?.output || 0,
|
|
191
|
+
resolvedPrice.output
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
input: effectiveInputPrice,
|
|
196
|
+
output: effectiveOutputPrice,
|
|
197
|
+
cachingWrite: resolvedPrice.cachingWrite || 0,
|
|
198
|
+
cachingRead: resolvedPrice.cachingRead || 0,
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// ==================== 具体计算函数 ====================
|
|
203
|
+
|
|
204
|
+
const calculateAnthropicCost = (
|
|
205
|
+
resolvedPrice: ModelPrice,
|
|
206
|
+
usage: Usage,
|
|
207
|
+
externalPrice?: ExternalPrice
|
|
208
|
+
): CostBreakdown => {
|
|
209
|
+
const {
|
|
210
|
+
input_tokens,
|
|
211
|
+
output_tokens,
|
|
212
|
+
cache_creation_input_tokens,
|
|
213
|
+
cache_read_input_tokens,
|
|
214
|
+
} = usage;
|
|
215
|
+
|
|
216
|
+
const {
|
|
217
|
+
input: effectiveInputPrice,
|
|
218
|
+
output: effectiveOutputPrice,
|
|
219
|
+
cachingWrite: effectiveCachingWritePrice,
|
|
220
|
+
cachingRead: effectiveCachingReadPrice,
|
|
221
|
+
} = getEffectivePrices(resolvedPrice, externalPrice);
|
|
222
|
+
|
|
223
|
+
const regularInputTokens = input_tokens - cache_read_input_tokens;
|
|
224
|
+
|
|
225
|
+
const regularTotal =
|
|
226
|
+
(regularInputTokens * resolvedPrice.input +
|
|
227
|
+
output_tokens * resolvedPrice.output +
|
|
228
|
+
cache_creation_input_tokens * (resolvedPrice.cachingWrite || 0) +
|
|
229
|
+
cache_read_input_tokens * (resolvedPrice.cachingRead || 0)) /
|
|
230
|
+
1_000_000;
|
|
231
|
+
|
|
232
|
+
const chargeTotal =
|
|
233
|
+
(regularInputTokens * effectiveInputPrice +
|
|
234
|
+
output_tokens * effectiveOutputPrice +
|
|
235
|
+
cache_creation_input_tokens * effectiveCachingWritePrice +
|
|
236
|
+
cache_read_input_tokens * effectiveCachingReadPrice) /
|
|
237
|
+
1_000_000;
|
|
238
|
+
|
|
239
|
+
return {
|
|
240
|
+
regular: regularTotal,
|
|
241
|
+
charge: chargeTotal,
|
|
242
|
+
details: {
|
|
243
|
+
inputCost: (regularInputTokens * resolvedPrice.input) / 1_000_000,
|
|
244
|
+
outputCost: (output_tokens * resolvedPrice.output) / 1_000_000,
|
|
245
|
+
cachingWriteCost:
|
|
246
|
+
(cache_creation_input_tokens * (resolvedPrice.cachingWrite || 0)) /
|
|
247
|
+
1_000_000,
|
|
248
|
+
cachingReadCost:
|
|
249
|
+
(cache_read_input_tokens * (resolvedPrice.cachingRead || 0)) /
|
|
250
|
+
1_000_000,
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const calculateCacheBasedCost = (
|
|
256
|
+
resolvedPrice: ModelPrice,
|
|
257
|
+
usage: Usage,
|
|
258
|
+
externalPrice?: ExternalPrice
|
|
259
|
+
): CostBreakdown => {
|
|
260
|
+
const { input_tokens, output_tokens, cache_read_input_tokens } = usage;
|
|
261
|
+
const { input: effectiveInputPrice, output: effectiveOutputPrice } =
|
|
262
|
+
getEffectivePrices(resolvedPrice, externalPrice);
|
|
263
|
+
|
|
264
|
+
const cacheMissTokens = input_tokens - cache_read_input_tokens;
|
|
265
|
+
const cacheHitPrice = resolvedPrice.inputCacheHit || 0;
|
|
266
|
+
|
|
267
|
+
const regularTotal =
|
|
268
|
+
(cacheMissTokens * resolvedPrice.input +
|
|
269
|
+
cache_read_input_tokens * cacheHitPrice +
|
|
270
|
+
output_tokens * resolvedPrice.output) /
|
|
271
|
+
1_000_000;
|
|
272
|
+
|
|
273
|
+
const chargeTotal =
|
|
274
|
+
(cacheMissTokens * effectiveInputPrice +
|
|
275
|
+
cache_read_input_tokens * cacheHitPrice +
|
|
276
|
+
output_tokens * effectiveOutputPrice) /
|
|
277
|
+
1_000_000;
|
|
278
|
+
|
|
279
|
+
return {
|
|
280
|
+
regular: regularTotal,
|
|
281
|
+
charge: chargeTotal,
|
|
282
|
+
details: {
|
|
283
|
+
inputCost: (cacheMissTokens * resolvedPrice.input) / 1_000_000,
|
|
284
|
+
outputCost: (output_tokens * resolvedPrice.output) / 1_000_000,
|
|
285
|
+
cachingReadCost: (cache_read_input_tokens * cacheHitPrice) / 1_000_000,
|
|
286
|
+
cachingWriteCost: 0,
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
const calculateSimpleCost = (
|
|
292
|
+
resolvedPrice: ModelPrice,
|
|
293
|
+
usage: Usage,
|
|
294
|
+
externalPrice?: ExternalPrice
|
|
295
|
+
): CostBreakdown => {
|
|
296
|
+
const { input_tokens, output_tokens } = usage;
|
|
297
|
+
const { input: effectiveInputPrice, output: effectiveOutputPrice } =
|
|
298
|
+
getEffectivePrices(resolvedPrice, externalPrice);
|
|
299
|
+
|
|
300
|
+
const regularTotal =
|
|
301
|
+
(input_tokens * resolvedPrice.input +
|
|
302
|
+
output_tokens * resolvedPrice.output) /
|
|
303
|
+
1_000_000;
|
|
304
|
+
|
|
305
|
+
const chargeTotal =
|
|
306
|
+
(input_tokens * effectiveInputPrice +
|
|
307
|
+
output_tokens * effectiveOutputPrice) /
|
|
308
|
+
1_000_000;
|
|
309
|
+
|
|
310
|
+
return {
|
|
311
|
+
regular: regularTotal,
|
|
312
|
+
charge: chargeTotal,
|
|
313
|
+
details: {
|
|
314
|
+
inputCost: (input_tokens * resolvedPrice.input) / 1_000_000,
|
|
315
|
+
outputCost: (output_tokens * resolvedPrice.output) / 1_000_000,
|
|
316
|
+
cachingWriteCost: 0,
|
|
317
|
+
cachingReadCost: 0,
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const calculateOpenRouterFallbackCost = (
|
|
323
|
+
resolvedPrice: ModelPrice,
|
|
324
|
+
usage: Usage,
|
|
325
|
+
externalPrice?: ExternalPrice
|
|
326
|
+
): CostBreakdown => {
|
|
327
|
+
if (
|
|
328
|
+
typeof resolvedPrice.cachingWrite === "number" ||
|
|
329
|
+
typeof resolvedPrice.cachingRead === "number"
|
|
330
|
+
) {
|
|
331
|
+
return calculateAnthropicCost(resolvedPrice, usage, externalPrice);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (typeof resolvedPrice.inputCacheHit === "number") {
|
|
335
|
+
return calculateCacheBasedCost(resolvedPrice, usage, externalPrice);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return calculateSimpleCost(resolvedPrice, usage, externalPrice);
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// OpenRouter usage.cost 是按其账户 credit(USD 基准)返回,
|
|
342
|
+
// 本平台统一按 1 USD = 8 credits 记账,因此这里仍需做一次换算。
|
|
343
|
+
const OPENROUTER_COST_MULTIPLIER = 8;
|
|
344
|
+
|
|
345
|
+
const calculateOpenRouterCost = (usage: Usage): CostBreakdown => {
|
|
346
|
+
if (!usage || typeof usage.cost !== "number" || usage.cost <= 0) {
|
|
347
|
+
return {
|
|
348
|
+
regular: 0,
|
|
349
|
+
charge: 0,
|
|
350
|
+
details: {
|
|
351
|
+
inputCost: 0,
|
|
352
|
+
outputCost: 0,
|
|
353
|
+
cachingWriteCost: 0,
|
|
354
|
+
cachingReadCost: 0,
|
|
355
|
+
},
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const regular = usage.cost * OPENROUTER_COST_MULTIPLIER;
|
|
360
|
+
|
|
361
|
+
return {
|
|
362
|
+
regular,
|
|
363
|
+
charge: regular,
|
|
364
|
+
details: {
|
|
365
|
+
inputCost: regular,
|
|
366
|
+
outputCost: 0,
|
|
367
|
+
cachingWriteCost: 0,
|
|
368
|
+
cachingReadCost: 0,
|
|
369
|
+
},
|
|
370
|
+
};
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
const resolveOpenAIBuiltInImageSurcharge = (
|
|
374
|
+
model: Model,
|
|
375
|
+
usage: Usage
|
|
376
|
+
): number => {
|
|
377
|
+
const imageGenerationCount =
|
|
378
|
+
typeof usage.image_generation_count === "number" &&
|
|
379
|
+
Number.isFinite(usage.image_generation_count)
|
|
380
|
+
? usage.image_generation_count
|
|
381
|
+
: 0;
|
|
382
|
+
const pricePerImage =
|
|
383
|
+
getApproxPricePerImage(model) ??
|
|
384
|
+
getApproxPricePerImage(findModelConfig("openai", "gpt-image-2")) ??
|
|
385
|
+
0;
|
|
386
|
+
|
|
387
|
+
if (imageGenerationCount <= 0 || pricePerImage <= 0) return 0;
|
|
388
|
+
return imageGenerationCount * pricePerImage;
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
// ==================== 路由与分发 ====================
|
|
392
|
+
|
|
393
|
+
const calculateBasicCost = (
|
|
394
|
+
model: Model,
|
|
395
|
+
usage: Usage,
|
|
396
|
+
provider: string,
|
|
397
|
+
externalPrice?: ExternalPrice,
|
|
398
|
+
billingServiceTier?: OpenAIServiceTier
|
|
399
|
+
): CostBreakdown => {
|
|
400
|
+
if (!usage || typeof usage.input_tokens !== "number") {
|
|
401
|
+
throw new Error("Invalid usage data");
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const resolvedPrice = resolveEffectiveModelPrice({
|
|
405
|
+
model,
|
|
406
|
+
usage,
|
|
407
|
+
provider,
|
|
408
|
+
billingServiceTier,
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
switch (provider) {
|
|
412
|
+
case "deepseek":
|
|
413
|
+
case "openai":
|
|
414
|
+
case "deepinfra":
|
|
415
|
+
return calculateCacheBasedCost(resolvedPrice, usage, externalPrice);
|
|
416
|
+
|
|
417
|
+
case "anthropic":
|
|
418
|
+
return calculateAnthropicCost(resolvedPrice, usage, externalPrice);
|
|
419
|
+
|
|
420
|
+
case "google":
|
|
421
|
+
if (model.name.includes("gemini-3")) {
|
|
422
|
+
return calculateAnthropicCost(resolvedPrice, usage, externalPrice);
|
|
423
|
+
}
|
|
424
|
+
return calculateSimpleCost(resolvedPrice, usage, externalPrice);
|
|
425
|
+
|
|
426
|
+
case "openrouter": {
|
|
427
|
+
const orCost = calculateOpenRouterCost(usage);
|
|
428
|
+
if (orCost.regular > 0) return orCost;
|
|
429
|
+
return calculateOpenRouterFallbackCost(
|
|
430
|
+
resolvedPrice,
|
|
431
|
+
usage,
|
|
432
|
+
externalPrice
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
case "mistral":
|
|
437
|
+
case "xai":
|
|
438
|
+
case "fireworks":
|
|
439
|
+
default:
|
|
440
|
+
return calculateSimpleCost(resolvedPrice, usage, externalPrice);
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
const calculatePayDistribution = (
|
|
445
|
+
costs: CostBreakdown,
|
|
446
|
+
externalPrice?: ExternalPrice,
|
|
447
|
+
sharingLevel: "default" | "split" | "full"
|
|
448
|
+
): Record<string, number> => {
|
|
449
|
+
const pay: Record<string, number> = {};
|
|
450
|
+
|
|
451
|
+
pay[nolotusId] = costs.regular;
|
|
452
|
+
|
|
453
|
+
const sharingRatios = {
|
|
454
|
+
default: 0,
|
|
455
|
+
split: 0.5,
|
|
456
|
+
full: 1,
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
if (externalPrice?.creatorId) {
|
|
460
|
+
const profit = Math.max(0, costs.charge - costs.regular);
|
|
461
|
+
|
|
462
|
+
if (profit > 0) {
|
|
463
|
+
switch (sharingLevel) {
|
|
464
|
+
case "split":
|
|
465
|
+
pay[externalPrice.creatorId] = profit * sharingRatios.split;
|
|
466
|
+
break;
|
|
467
|
+
case "full":
|
|
468
|
+
pay[externalPrice.creatorId] = profit;
|
|
469
|
+
break;
|
|
470
|
+
default:
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
return Object.fromEntries(
|
|
477
|
+
Object.entries(pay).map(([key, value]) => [
|
|
478
|
+
key,
|
|
479
|
+
Number(value.toFixed(6)),
|
|
480
|
+
])
|
|
481
|
+
);
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
export const calculatePrice = ({
|
|
485
|
+
modelName,
|
|
486
|
+
usage,
|
|
487
|
+
externalPrice,
|
|
488
|
+
// 不设默认值,undefined 表示 custom/未知 provider,走 zeroCostModel 路径
|
|
489
|
+
provider,
|
|
490
|
+
billingServiceTier,
|
|
491
|
+
sharingLevel = "default",
|
|
492
|
+
}: CalculatePriceParams): PriceResult => {
|
|
493
|
+
// apiSource="custom" 的 agent 不一定有 provider,或 provider 不在 MODEL_MAP 里。
|
|
494
|
+
// 此时平台不承担 API 成本(由 agent owner 自费),但 agent 可能对外设有 inputPrice/outputPrice,
|
|
495
|
+
// 仍需走 externalPrice 计费路径向用户收费并分成给创作者。
|
|
496
|
+
// 用零成本的虚拟 model 代替,让 calculateBasicCost 正常走 externalPrice 分支。
|
|
497
|
+
let model: ReturnType<typeof getModelConfig>;
|
|
498
|
+
try {
|
|
499
|
+
model = getModelConfig(provider, modelName);
|
|
500
|
+
} catch {
|
|
501
|
+
const zeroCostModel: Model = {
|
|
502
|
+
name: modelName,
|
|
503
|
+
hasVision: false,
|
|
504
|
+
price: { input: 0, output: 0 },
|
|
505
|
+
};
|
|
506
|
+
const costs = calculateBasicCost(
|
|
507
|
+
zeroCostModel,
|
|
508
|
+
usage,
|
|
509
|
+
"custom",
|
|
510
|
+
externalPrice,
|
|
511
|
+
billingServiceTier
|
|
512
|
+
);
|
|
513
|
+
const pay = calculatePayDistribution(costs, externalPrice, sharingLevel);
|
|
514
|
+
return { cost: Number(costs.charge.toFixed(6)), pay };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const costs = calculateBasicCost(
|
|
518
|
+
model,
|
|
519
|
+
usage,
|
|
520
|
+
provider,
|
|
521
|
+
externalPrice,
|
|
522
|
+
billingServiceTier
|
|
523
|
+
);
|
|
524
|
+
const openAIImageSurcharge =
|
|
525
|
+
provider === "openai" ? resolveOpenAIBuiltInImageSurcharge(model, usage) : 0;
|
|
526
|
+
const adjustedCosts =
|
|
527
|
+
openAIImageSurcharge > 0
|
|
528
|
+
? {
|
|
529
|
+
...costs,
|
|
530
|
+
regular: costs.regular + openAIImageSurcharge,
|
|
531
|
+
charge: costs.charge + openAIImageSurcharge,
|
|
532
|
+
details: costs.details
|
|
533
|
+
? {
|
|
534
|
+
...costs.details,
|
|
535
|
+
outputCost: costs.details.outputCost + openAIImageSurcharge,
|
|
536
|
+
}
|
|
537
|
+
: costs.details,
|
|
538
|
+
}
|
|
539
|
+
: costs;
|
|
540
|
+
const pay = calculatePayDistribution(adjustedCosts, externalPrice, sharingLevel);
|
|
541
|
+
|
|
542
|
+
return {
|
|
543
|
+
cost: Number(adjustedCosts.charge.toFixed(6)),
|
|
544
|
+
pay,
|
|
545
|
+
};
|
|
546
|
+
};
|
package/ai/token/db.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { createTokenStatsKey } from "database/keys";
|
|
2
|
+
import { TokenUsageData } from "./types";
|
|
3
|
+
import { ulid } from "ulid";
|
|
4
|
+
import { createInitialDayStats } from "./stats";
|
|
5
|
+
import { format } from "date-fns";
|
|
6
|
+
import { pino } from "pino";
|
|
7
|
+
import { DataType } from "create/types";
|
|
8
|
+
import { read, write } from "database/dbSlice";
|
|
9
|
+
|
|
10
|
+
interface TokenCount {
|
|
11
|
+
input: number;
|
|
12
|
+
output: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface ModelStats {
|
|
16
|
+
count: number;
|
|
17
|
+
tokens: TokenCount;
|
|
18
|
+
cost: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface DayStats {
|
|
22
|
+
userId: string;
|
|
23
|
+
period: "day";
|
|
24
|
+
timeKey: string;
|
|
25
|
+
total: { count: number; tokens: TokenCount; cost: number };
|
|
26
|
+
models: Record<string, ModelStats>;
|
|
27
|
+
providers: Record<string, ModelStats>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const logger = pino({ name: "token-db" });
|
|
31
|
+
|
|
32
|
+
const updateStats = (
|
|
33
|
+
data: TokenUsageData,
|
|
34
|
+
stats: ModelStats = { count: 0, tokens: { input: 0, output: 0 }, cost: 0 }
|
|
35
|
+
) => ({
|
|
36
|
+
count: stats.count + 1,
|
|
37
|
+
tokens: {
|
|
38
|
+
input: stats.tokens.input + data.input_tokens,
|
|
39
|
+
output: stats.tokens.output + data.output_tokens,
|
|
40
|
+
},
|
|
41
|
+
cost: stats.cost + data.cost,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
export const saveTokenUsage = async (data: TokenUsageData, thunkApi) => {
|
|
45
|
+
try {
|
|
46
|
+
const dateKey = format(Date.now(), "yyyy-MM-dd");
|
|
47
|
+
const key = createTokenStatsKey(data.userId, dateKey);
|
|
48
|
+
|
|
49
|
+
// Get current stats or create initial stats
|
|
50
|
+
const currentStats = await thunkApi.dispatch(read({
|
|
51
|
+
dbKey: key
|
|
52
|
+
})).unwrap();
|
|
53
|
+
const stats = currentStats?.total
|
|
54
|
+
? currentStats
|
|
55
|
+
: createInitialDayStats(data.userId, dateKey);
|
|
56
|
+
|
|
57
|
+
// Update stats with new data
|
|
58
|
+
const cleanModels = { ...stats.models };
|
|
59
|
+
["unknown", "undefined"].forEach((key) => delete cleanModels[key]);
|
|
60
|
+
|
|
61
|
+
const modelName = data.model || "unknown";
|
|
62
|
+
const providerName = data.provider || "unknown";
|
|
63
|
+
|
|
64
|
+
const updatedStats = {
|
|
65
|
+
...stats,
|
|
66
|
+
total: updateStats(data, stats.total),
|
|
67
|
+
models: {
|
|
68
|
+
...cleanModels,
|
|
69
|
+
[modelName]: updateStats(data, cleanModels[modelName]),
|
|
70
|
+
},
|
|
71
|
+
providers: {
|
|
72
|
+
...stats.providers,
|
|
73
|
+
[providerName]: updateStats(data, stats.providers[providerName]),
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
logger.info({ updatedStats }, "Updated day stats");
|
|
78
|
+
|
|
79
|
+
// Save updated stats
|
|
80
|
+
await thunkApi.dispatch(
|
|
81
|
+
write({
|
|
82
|
+
data: { ...updatedStats, id: key, type: DataType.TOKEN },
|
|
83
|
+
customKey: key,
|
|
84
|
+
})
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
logger.info({ currentStats, updatedStats }, "Saved day stats");
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
success: true,
|
|
91
|
+
id: ulid(Date.now()),
|
|
92
|
+
record: updatedStats,
|
|
93
|
+
};
|
|
94
|
+
} catch (error) {
|
|
95
|
+
logger.error({ error }, "Failed to save token usage");
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
};
|