nolo-cli 0.1.40 → 0.1.41
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/agent-runtime/hybridRecordStore.ts +5 -3
- package/ai/agent/_executeModel.ts +146 -0
- package/ai/agent/agentSlice.ts +556 -1
- package/ai/agent/appWorkingMemory.ts +126 -0
- package/ai/agent/buildEditingContext.ts +378 -0
- package/ai/agent/buildSystemPrompt.ts +585 -0
- package/ai/agent/canvasEditingContext.ts +49 -0
- package/ai/agent/cleanAgentMessages.ts +140 -0
- package/ai/agent/cliChatClient.ts +153 -0
- package/ai/agent/cliExecutor.ts +65 -6
- package/ai/agent/contextCompiler.ts +107 -0
- package/ai/agent/contextLayerContract.ts +44 -0
- package/ai/agent/createAgentSchema.ts +272 -0
- package/ai/agent/currentTimeContext.ts +65 -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/guidedCreation/capabilities.ts +84 -0
- package/ai/agent/guidedCreation/types.ts +38 -0
- package/ai/agent/isLiveAudioOnlyAgent.ts +26 -0
- package/ai/agent/liveAudioModel.ts +2 -0
- package/ai/agent/pageBuilderHandoffRules.ts +75 -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 +310 -0
- package/ai/agent/runAgentClientLoop.ts +164 -0
- package/ai/agent/runtimeGuidance.ts +116 -0
- package/ai/agent/serverOrigin.ts +7 -0
- package/ai/agent/startParallelAgentStreams.ts +424 -0
- package/ai/agent/startupProtocol.ts +53 -0
- package/ai/agent/streamAgentChatTurn.ts +2001 -0
- package/ai/agent/streamAgentChatTurnUtils.ts +860 -0
- package/ai/agent/toolFailureGuard.ts +99 -0
- package/ai/agent/types.ts +73 -0
- package/ai/agent/utils/imageOutput.ts +37 -0
- package/ai/agent/utils/publicImageAgentMode.ts +26 -0
- package/ai/ai.locale.ts +1095 -0
- package/ai/chat/accumulateToolCallChunks.ts +126 -0
- package/ai/chat/fetchUtils.ts +143 -0
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
- package/ai/chat/parseApiError.ts +67 -0
- package/ai/chat/parseMultilineSSE.ts +95 -0
- package/ai/chat/sendOpenAICompletionsRequest.ts +897 -0
- package/ai/chat/sendOpenAIResponseRequest.ts +720 -0
- package/ai/chat/serverProxyRetry.ts +102 -0
- package/ai/chat/shouldUseServerProxy.ts +18 -0
- package/ai/chat/streamRetry.ts +46 -0
- package/ai/chat/updateTotalUsage.ts +89 -0
- package/ai/context/buildReferenceContext.ts +437 -0
- package/ai/context/retention.ts +165 -0
- package/ai/context/tokenUtils.ts +78 -0
- package/ai/llm/agentCapabilities.ts +74 -0
- package/ai/llm/deepinfra.ts +79 -0
- package/ai/llm/fireworks.ts +68 -0
- package/ai/llm/generateRequestBody.ts +165 -0
- package/ai/llm/getModelContextWindow.ts +93 -0
- package/ai/llm/getPricing.ts +252 -0
- package/ai/llm/imagePricing.ts +66 -0
- package/ai/llm/isResponseAPIModel.ts +13 -0
- package/ai/llm/kimi.ts +23 -0
- package/ai/llm/mimo.ts +99 -0
- package/ai/llm/mistral.ts +21 -0
- package/ai/llm/models.ts +45 -0
- package/ai/llm/openrouterModels.ts +6 -0
- package/ai/llm/providers.ts +313 -0
- package/ai/llm/reasoningModels.ts +27 -0
- package/ai/llm/types.ts +82 -0
- package/ai/llm/usageRequestOptions.ts +59 -0
- package/ai/memory/queryShared.ts +161 -0
- package/ai/memory/recentRelationshipRecap.ts +247 -0
- package/ai/memory/remember.ts +167 -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/policy/personalizationDialog.ts +333 -0
- package/ai/policy/runtimePolicy.ts +454 -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/skillSummaryMarker.ts +26 -0
- package/ai/token/calculatePrice.ts +576 -0
- package/ai/token/missingUsageEstimate.ts +42 -0
- package/ai/token/normalizeUsage.ts +124 -0
- package/ai/token/openaiImageGenerationUsage.ts +56 -0
- package/ai/token/prepareTokenUsageData.ts +93 -0
- package/ai/token/resolveBillingTarget.ts +52 -0
- package/ai/token/saveTokenRecord.ts +53 -0
- package/ai/token/types.ts +103 -0
- package/ai/tools/agent/agentTools.ts +235 -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/prepareAgentDraftTool.ts +159 -0
- package/ai/tools/agent/presets/appBuilderPreset.ts +154 -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/startAgentDialogTool.ts +53 -0
- package/ai/tools/agent/streamParallelAgentsTool.ts +123 -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 +259 -0
- package/ai/tools/applyLineEditsTool.ts +315 -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 +102 -0
- package/ai/tools/cloudflareCrawlTool.ts +289 -0
- package/ai/tools/codeSearchTool.ts +123 -0
- package/ai/tools/codeTools.ts +101 -0
- package/ai/tools/convertMarxistsBookTool.ts +103 -0
- package/ai/tools/createDocTool.ts +132 -0
- package/ai/tools/createSkillDocTool.ts +155 -0
- package/ai/tools/createWorkflowTool.ts +154 -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 +63 -0
- package/ai/tools/execShellTool.ts +266 -0
- package/ai/tools/executeSqlTool.ts +192 -0
- package/ai/tools/fetchWebpageSupport.ts +333 -0
- package/ai/tools/fetchWebpageTool.ts +97 -0
- package/ai/tools/geminiImagePreviewTool.ts +386 -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 +2308 -0
- package/ai/tools/jdProductScraperTool.ts +821 -0
- package/ai/tools/listUserSpacesTool.ts +113 -0
- package/ai/tools/localFilesTool.ts +276 -0
- package/ai/tools/marxistsOfflineBook.ts +253 -0
- package/ai/tools/modelUsageTools.ts +206 -0
- package/ai/tools/noloWorkspaceReadTools.ts +467 -0
- package/ai/tools/olmOcrTool.ts +33 -0
- package/ai/tools/openaiImageTool.ts +267 -0
- package/ai/tools/prepareTools.ts +23 -0
- package/ai/tools/readDocTool.ts +88 -0
- package/ai/tools/readFileTool.ts +214 -0
- package/ai/tools/readTool.ts +194 -0
- package/ai/tools/readXPostTool.ts +229 -0
- package/ai/tools/readXhsProfileTool.ts +627 -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/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 +386 -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/taobaoTmallProductScraperTool.ts +49 -0
- package/ai/tools/toolApiClient.ts +279 -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/uiAskChoiceTool.ts +104 -0
- package/ai/tools/updateContentTitleTool.ts +84 -0
- package/ai/tools/updateDocTool.ts +105 -0
- package/ai/tools/updateUserPreferenceProfileTool.ts +153 -0
- package/ai/tools/wereadGatewayTool.ts +152 -0
- package/ai/tools/whisperTool.ts +76 -0
- package/ai/tools/writeFileTool.ts +213 -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/app/actions/syncAppRecord.ts +73 -0
- package/app/constants/animationSets.ts +21 -0
- package/app/constants/appEditor.ts +99 -0
- package/app/favorite/favoriteSlice.ts +690 -0
- package/app/favorite/type.ts +43 -0
- package/app/hooks/deleteDbKey.ts +233 -0
- package/app/i18n/client.ts +13 -0
- package/app/i18n/i18n.base.ts +14 -0
- package/app/i18n/i18n.config.ts +77 -0
- package/app/i18n/index.ts +15 -0
- package/app/i18n/mapLanguage.ts +11 -0
- package/app/i18n/translations/appBuilder.locale.ts +453 -0
- package/app/i18n/translations/error.locale.ts +246 -0
- package/app/i18n/translations/interface.locale.ts +2174 -0
- package/app/i18n/translations/pricing.locale.ts +397 -0
- package/app/i18n/translations/privacy.locale.ts +168 -0
- package/app/i18n/translations/seo.locale.ts +129 -0
- package/app/i18n/translations/terms.locale.ts +124 -0
- package/app/i18n/types.ts +6 -0
- package/app/notifications/model.ts +77 -0
- package/app/notifications/notificationSlice.ts +141 -0
- package/app/reducer.ts +36 -0
- package/app/settings/dbActionThunks.ts +34 -0
- package/app/settings/defaultSpacePreference.ts +87 -0
- package/app/settings/settingSlice.tsx +1212 -0
- package/app/settings/settingsRecord.ts +8 -0
- package/app/stateViews/runtime.ts +90 -0
- package/app/store.ts +55 -0
- package/app/theme/colors.ts +280 -0
- package/app/theme/fontPreference.ts +77 -0
- package/app/theme/theme.config.ts +120 -0
- package/app/theme/themeModeBootstrap.ts +123 -0
- package/app/types/appSummary.ts +114 -0
- package/app/types.ts +358 -0
- package/app/utils/appKeys.ts +55 -0
- package/app/utils/async.ts +28 -0
- package/app/utils/desktopAgentRuntimeTurnClient.ts +73 -0
- package/app/utils/env.ts +17 -0
- package/app/utils/fileUtils.ts +229 -0
- package/app/utils/imageUtils.ts +274 -0
- package/app/utils/myContentItems.ts +289 -0
- package/app/utils/retryAfter.ts +36 -0
- package/app/utils/retryFetch.ts +61 -0
- package/app/utils/toast.ts +3 -0
- package/auth/action/signUpAction.ts +227 -0
- package/auth/adminPermissions.ts +18 -0
- package/auth/authSlice.ts +531 -0
- package/auth/client/loginRequest.ts +14 -0
- package/auth/resetAuthScopedClientState.ts +27 -0
- package/auth/routes.ts +178 -0
- package/auth/token.ts +63 -0
- package/auth/types.ts +40 -0
- package/chat/chat.locale.ts +813 -0
- package/chat/dialog/actions/addCybotAction.ts +52 -0
- package/chat/dialog/actions/addReferenceKeysAction.ts +62 -0
- package/chat/dialog/actions/builtinDialogLlm.ts +35 -0
- package/chat/dialog/actions/cleanupCliSession.ts +40 -0
- package/chat/dialog/actions/createDialogAction.ts +379 -0
- package/chat/dialog/actions/createScheduledTaskAction.ts +78 -0
- package/chat/dialog/actions/handleSendMessageAction.ts +197 -0
- package/chat/dialog/actions/handleSendMessageResolver.ts +27 -0
- package/chat/dialog/actions/removeCybotAction.ts +6 -0
- package/chat/dialog/actions/removeDialogAgentAction.ts +44 -0
- package/chat/dialog/actions/replacePrimaryCybotAction.ts +6 -0
- package/chat/dialog/actions/setPrimaryDialogAgentAction.ts +52 -0
- package/chat/dialog/actions/updateDialogSummaryAction.ts +430 -0
- package/chat/dialog/actions/updateDialogTitleAction.ts +151 -0
- package/chat/dialog/actions/updateDialogTitlePolicy.ts +30 -0
- package/chat/dialog/actions/updateTokensAction.ts +233 -0
- package/chat/dialog/dialogAgents.ts +72 -0
- package/chat/dialog/dialogSlice.ts +872 -0
- package/chat/dialog/dialogTitle.ts +81 -0
- package/chat/dialog/dialogTokenStats.ts +12 -0
- package/chat/dialog/dialogUrl.ts +6 -0
- package/chat/dialog/goal.ts +108 -0
- package/chat/dialog/objectAssistantRegistry.ts +286 -0
- package/chat/dialog/schedule.ts +17 -0
- package/chat/messages/fetchAndCacheMessages.ts +119 -0
- package/chat/messages/fetchConvMsgs.ts +51 -0
- package/chat/messages/fileUrl.ts +13 -0
- package/chat/messages/messageAgent.ts +8 -0
- package/chat/messages/messageContent.ts +199 -0
- package/chat/messages/messageContract.ts +88 -0
- package/chat/messages/messageSlice.ts +1367 -0
- package/chat/messages/toolThunks.ts +625 -0
- package/cli/client/agentRun.ts +27 -8
- package/cli/client/localRuntimeAdapter.ts +144 -28
- package/client/agentRun.test.ts +52 -0
- package/client/agentRun.ts +27 -8
- package/client/localRuntimeAdapter.test.ts +437 -6
- package/client/localRuntimeAdapter.ts +144 -28
- package/core/builtinAgents.ts +209 -0
- package/core/config.ts +15 -0
- package/core/crypto.ts +51 -0
- package/core/generateKeyPairFromSeedV1.ts +15 -0
- package/core/generateMainKey.ts +22 -0
- package/core/init.ts +41 -0
- package/core/localOrigins.ts +8 -0
- package/core/password.ts +13 -0
- package/core/prefix.ts +23 -0
- package/create/editor/transforms/fromMarkdown/index.ts +260 -0
- package/create/editor/transforms/fromMarkdown/inline.ts +285 -0
- package/create/editor/transforms/fromMarkdown/table.ts +130 -0
- package/create/editor/transforms/markdownToSlate.ts +24 -0
- package/create/editor/transforms/slateToRenderMarkdown.ts +218 -0
- package/create/editor/transforms/slateToSimplifiedMarkdown.ts +224 -0
- package/create/editor/transforms/slateToText.ts +33 -0
- package/create/editor/utils/slateUtils.ts +233 -0
- package/create/space/addSpaceAction.ts +193 -0
- package/create/space/category/categoryActions.ts +427 -0
- package/create/space/changeSpaceAction.ts +36 -0
- package/create/space/constants.ts +8 -0
- package/create/space/content/addContentAction.ts +116 -0
- package/create/space/content/contentThunks.ts +90 -0
- package/create/space/content/deleteContentFromSpaceAction.ts +187 -0
- package/create/space/content/deleteMultipleContentAction.ts +112 -0
- package/create/space/content/moveContentAction.ts +285 -0
- package/create/space/content/updateContentCategoryAction.ts +154 -0
- package/create/space/content/updateContentTitleAction.ts +151 -0
- package/create/space/content/uploadAndAddFileToSpaceAction.ts +98 -0
- package/create/space/contentKeyUtils.ts +117 -0
- package/create/space/deleteSpaceAction.ts +276 -0
- package/create/space/fetchSpaceAction.ts +70 -0
- package/create/space/fetchSpaceSidebarStateAction.ts +26 -0
- package/create/space/loadDefaultSpaceAction.ts +57 -0
- package/create/space/member/addMemberAction.ts +79 -0
- package/create/space/member/fetchUserSpaceMembershipsAction.ts +386 -0
- package/create/space/member/memberThunks.ts +47 -0
- package/create/space/member/removeMemberAction.ts +67 -0
- package/create/space/resolvePreferredSpaceId.ts +113 -0
- package/create/space/sidebarVisibleTypes.ts +241 -0
- package/create/space/space.locale.ts +1087 -0
- package/create/space/spaceAccess.ts +182 -0
- package/create/space/spaceCollapsedState.ts +54 -0
- package/create/space/spaceKeys.ts +65 -0
- package/create/space/spaceSlice.ts +328 -0
- package/create/space/spaceThunks.ts +410 -0
- package/create/space/types.ts +27 -0
- package/create/space/updateSpaceAction.ts +107 -0
- package/create/space/utils/permissions.ts +47 -0
- package/create/types.ts +21 -0
- package/database/actions/agentReadResolution.ts +33 -0
- package/database/actions/common.ts +243 -0
- package/database/actions/deleteFile.ts +40 -0
- package/database/actions/fileContent.ts +125 -0
- package/database/actions/patch.ts +155 -0
- package/database/actions/read.ts +358 -0
- package/database/actions/readAndWait.ts +260 -0
- package/database/actions/readRequestManager.ts +120 -0
- package/database/actions/readResolution.ts +125 -0
- package/database/actions/remove.ts +94 -0
- package/database/actions/replication.ts +477 -0
- package/database/actions/upload.ts +186 -0
- package/database/actions/upsert.ts +56 -0
- package/database/actions/write.ts +146 -0
- package/database/authority/ownerKey.ts +80 -0
- package/database/authority/recordAuthority.ts +67 -0
- package/database/authority/userAuthorityRegistry.ts +54 -0
- package/database/client/fetchUserData.ts +61 -0
- package/database/dbActionThunks.ts +1 -0
- package/database/dbSlice.ts +149 -0
- package/database/fileRing.ts +51 -0
- package/database/fileStorage.ts +232 -0
- package/database/fileUrl.ts +34 -0
- package/database/keys.ts +767 -0
- package/database/queryPrefixes.ts +14 -0
- package/database/requests.ts +443 -0
- package/database/runtimeServerContext.ts +54 -0
- package/database/tenantPlacement.ts +57 -0
- package/database/userPreferenceRegister.ts +131 -0
- package/database/utils/ulid.ts +1 -0
- package/integrations/anthropic/anthropicModels.ts +47 -0
- package/integrations/deepseek/models.ts +37 -0
- package/integrations/google/models.ts +341 -0
- package/integrations/openai/chatCompletionStreamMode.ts +10 -0
- package/integrations/openai/filterAndCleanMessages.ts +284 -0
- package/integrations/openai/flexTier.ts +102 -0
- package/integrations/openai/generateOpenAIRequestBody.ts +274 -0
- package/integrations/openai/generateResponseRequestBody.ts +77 -0
- package/integrations/openai/models.ts +271 -0
- package/integrations/openai/providerBodyCompatibility.ts +23 -0
- package/integrations/openai/responsesHelpers.ts +297 -0
- package/integrations/x-reader/types.ts +109 -0
- package/integrations/xai/models.ts +13 -0
- package/integrations/xhs-reader/analyze/profileAnalyzer.ts +205 -0
- package/integrations/xhs-reader/backends/playwrightProfileCollector.ts +624 -0
- package/integrations/xhs-reader/bridge/readXhsProfileWithBridge.ts +227 -0
- package/integrations/xhs-reader/client/xhsWebApiClient.ts +229 -0
- package/integrations/xhs-reader/normalize.ts +390 -0
- package/integrations/xhs-reader/orchestrator.ts +178 -0
- package/integrations/xhs-reader/redaction.ts +68 -0
- package/integrations/xhs-reader/types.ts +244 -0
- package/integrations/xhs-reader/url.ts +57 -0
- package/package.json +430 -4
- package/render/page/createPageAction.ts +183 -0
- package/render/page/docSlice.ts +468 -0
- package/render/page/types.ts +17 -0
- package/render/table/createTableAction.ts +270 -0
- package/render/table/deleteTableAction.ts +193 -0
- package/render/table/fetchAndCacheTableRows.ts +174 -0
- package/render/table/tableSlice.ts +1106 -0
- package/render/table/toolValueUtils.ts +363 -0
- package/render/table/types.ts +252 -0
- package/render/table/utils/tableSerialization.ts +50 -0
- package/server/handlers/agentRun/types.ts +104 -0
- package/share/action.ts +225 -0
- package/share/helpers.ts +302 -0
- package/share/keys.ts +243 -0
- package/share/publicSharePolicy.ts +27 -0
- package/share/shareSlice.ts +53 -0
- package/share/types.ts +100 -0
|
@@ -0,0 +1,897 @@
|
|
|
1
|
+
// 文件路径: chat/sendOpenAICompletionsRequest.ts
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
addActiveController,
|
|
5
|
+
removeActiveController,
|
|
6
|
+
tokenUsageLiveUpdate,
|
|
7
|
+
} from "../../chat/dialog/dialogSlice";
|
|
8
|
+
import {
|
|
9
|
+
messageStreamEnd,
|
|
10
|
+
messageStreaming,
|
|
11
|
+
} from "../../chat/messages/messageSlice";
|
|
12
|
+
import { handleToolCalls } from "../../chat/messages/toolThunks";
|
|
13
|
+
import {
|
|
14
|
+
MessageContentPart,
|
|
15
|
+
ImageGenerationState,
|
|
16
|
+
Message,
|
|
17
|
+
OpenAITextContent,
|
|
18
|
+
} from "../../chat/messages/types";
|
|
19
|
+
import { selectCurrentServer } from "../../app/settings/settingSlice";
|
|
20
|
+
import { selectCurrentSpaceId } from "../../create/space/spaceSlice";
|
|
21
|
+
import { getApiEndpoint } from "../llm/providers";
|
|
22
|
+
import { createDialogMessageKeyAndId } from "../../database/keys";
|
|
23
|
+
import { selectCurrentToken } from "../../auth/authSlice";
|
|
24
|
+
import { extractCustomId } from "../../core/prefix";
|
|
25
|
+
|
|
26
|
+
import { performFetchRequest } from "./fetchUtils";
|
|
27
|
+
import { createSSEParser } from "./parseMultilineSSE";
|
|
28
|
+
import { parseApiError } from "./parseApiError";
|
|
29
|
+
import { updateTotalUsage } from "./updateTotalUsage";
|
|
30
|
+
import { accumulateToolCallChunks } from "./accumulateToolCallChunks";
|
|
31
|
+
import { prepareTools } from "../tools/prepareTools";
|
|
32
|
+
import {
|
|
33
|
+
inlineImageUrlsForCustomProvider,
|
|
34
|
+
shouldInlineImageUrlsForAgent,
|
|
35
|
+
} from "./inlineImageUrlsForCustomProvider";
|
|
36
|
+
|
|
37
|
+
import { getModelInfo } from "../llm/getModelContextWindow";
|
|
38
|
+
import { supportsImageGeneration } from "../agent/utils/imageOutput";
|
|
39
|
+
|
|
40
|
+
import type { RootState } from "../../app/store";
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 追加文本 chunk 到 contentBuffer(不可变更新)
|
|
44
|
+
*/
|
|
45
|
+
function appendTextChunk(
|
|
46
|
+
currentContentBuffer: MessageContentPart[],
|
|
47
|
+
textChunk: string
|
|
48
|
+
): MessageContentPart[] {
|
|
49
|
+
if (!textChunk) return currentContentBuffer;
|
|
50
|
+
|
|
51
|
+
const updatedContentBuffer = [...currentContentBuffer];
|
|
52
|
+
const lastIndex = updatedContentBuffer.length - 1;
|
|
53
|
+
|
|
54
|
+
if (lastIndex >= 0 && updatedContentBuffer[lastIndex].type === "text") {
|
|
55
|
+
const last = updatedContentBuffer[lastIndex] as OpenAITextContent;
|
|
56
|
+
updatedContentBuffer[lastIndex] = {
|
|
57
|
+
...last,
|
|
58
|
+
text: (last.text || "") + textChunk,
|
|
59
|
+
};
|
|
60
|
+
} else {
|
|
61
|
+
updatedContentBuffer.push({ type: "text", text: textChunk });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return updatedContentBuffer;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** OpenAI 标准 tool_call 结构 */
|
|
68
|
+
type AssistantToolCall = {
|
|
69
|
+
id: string;
|
|
70
|
+
type: "function";
|
|
71
|
+
function: { name: string; arguments: string };
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const EXPLICIT_IMAGE_TOOL_NAMES = new Set([
|
|
75
|
+
"openAIGptImage",
|
|
76
|
+
"openAIGptImageGenerate",
|
|
77
|
+
"openAIGptImageEdit",
|
|
78
|
+
"geminiProImagePreview",
|
|
79
|
+
]);
|
|
80
|
+
|
|
81
|
+
function getStreamErrorMessage(data: any): string {
|
|
82
|
+
const message =
|
|
83
|
+
typeof data?.error?.message === "string" && data.error.message.trim()
|
|
84
|
+
? data.error.message.trim()
|
|
85
|
+
: typeof data?.error?.msg === "string" && data.error.msg.trim()
|
|
86
|
+
? data.error.msg.trim()
|
|
87
|
+
: typeof data?.message === "string" && data.message.trim()
|
|
88
|
+
? data.message.trim()
|
|
89
|
+
: null;
|
|
90
|
+
if (message) return message;
|
|
91
|
+
|
|
92
|
+
const code =
|
|
93
|
+
typeof data?.error?.code === "string" && data.error.code.trim()
|
|
94
|
+
? data.error.code.trim()
|
|
95
|
+
: typeof data?.code === "string" && data.code.trim()
|
|
96
|
+
? data.code.trim()
|
|
97
|
+
: null;
|
|
98
|
+
if (code) return code;
|
|
99
|
+
|
|
100
|
+
const type =
|
|
101
|
+
typeof data?.error?.type === "string" && data.error.type.trim()
|
|
102
|
+
? data.error.type.trim()
|
|
103
|
+
: null;
|
|
104
|
+
if (type) return type;
|
|
105
|
+
|
|
106
|
+
return "Unknown error";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function formatStreamErrorMessage(data: any): string {
|
|
110
|
+
const rawMessage = getStreamErrorMessage(data);
|
|
111
|
+
if (
|
|
112
|
+
/prohibited|violation|terms\s+of\s+service|content\s+policy|safety/i.test(
|
|
113
|
+
rawMessage
|
|
114
|
+
)
|
|
115
|
+
) {
|
|
116
|
+
return "当前模型服务商拒绝了这次请求。你可以稍后重试,或切换到其他模型继续。";
|
|
117
|
+
}
|
|
118
|
+
return rawMessage;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 单次流式请求过程中的全部中间状态(显式 state) */
|
|
122
|
+
type StreamState = {
|
|
123
|
+
contentBuffer: MessageContentPart[];
|
|
124
|
+
totalUsage: any | null;
|
|
125
|
+
accumulatedToolCalls: any[];
|
|
126
|
+
reasoningBuffer: string;
|
|
127
|
+
assistantToolCalls?: AssistantToolCall[];
|
|
128
|
+
hasHandedOff: boolean;
|
|
129
|
+
hasProcessedToolCalls: boolean;
|
|
130
|
+
alreadyFinalized: boolean;
|
|
131
|
+
finishReason: string | null;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
type FinalizeContext = {
|
|
135
|
+
dispatch: any;
|
|
136
|
+
msgKey: string;
|
|
137
|
+
dialogId: string;
|
|
138
|
+
dialogKey: string;
|
|
139
|
+
messageId: string;
|
|
140
|
+
agentConfig: any;
|
|
141
|
+
spaceId?: string;
|
|
142
|
+
messageMetadata?: Partial<Message>;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
type ToolCallsContext = {
|
|
146
|
+
dispatch: any;
|
|
147
|
+
agentConfig: any;
|
|
148
|
+
dialogId: string;
|
|
149
|
+
dialogKey: string;
|
|
150
|
+
messageId: string;
|
|
151
|
+
messageMetadata?: Partial<Message>;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
type StreamCompletionContext = {
|
|
155
|
+
dispatch: any;
|
|
156
|
+
dialogId: string;
|
|
157
|
+
dialogKey: string;
|
|
158
|
+
messageId: string;
|
|
159
|
+
agentConfig: any;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const withImageGenerationStage = (
|
|
163
|
+
messageMetadata: Partial<Message> | undefined,
|
|
164
|
+
stage: ImageGenerationState["stage"]
|
|
165
|
+
): Partial<Message> | undefined => {
|
|
166
|
+
const previousState = messageMetadata?.imageGenerationState;
|
|
167
|
+
if (previousState?.kind !== "image_generation") {
|
|
168
|
+
return messageMetadata;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
...(messageMetadata ?? {}),
|
|
173
|
+
imageGenerationState: {
|
|
174
|
+
...previousState,
|
|
175
|
+
stage,
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const shouldShowImageSavingState = (contentBuffer: MessageContentPart[]) =>
|
|
181
|
+
contentBuffer.some((part) => part?.type === "image_url") &&
|
|
182
|
+
!contentBuffer.some(
|
|
183
|
+
(part) =>
|
|
184
|
+
part?.type === "text" &&
|
|
185
|
+
typeof part.text === "string" &&
|
|
186
|
+
part.text.trim().length > 0
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
/** 单轮调用后返回给 Agent Loop 的元信息 */
|
|
190
|
+
export type CompletionMeta = {
|
|
191
|
+
hasToolCalls: boolean;
|
|
192
|
+
hasPendingInteraction: boolean;
|
|
193
|
+
hasHandedOff: boolean;
|
|
194
|
+
finishReason: string | null;
|
|
195
|
+
messageId: string;
|
|
196
|
+
usage?: any;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const STREAM_READ_TIMEOUT_MS = 45_000;
|
|
200
|
+
|
|
201
|
+
const logQuickChatPerfStage = (
|
|
202
|
+
startedAt: number | undefined,
|
|
203
|
+
stage: string,
|
|
204
|
+
details?: Record<string, unknown>
|
|
205
|
+
) => {
|
|
206
|
+
if (!startedAt) return;
|
|
207
|
+
const now = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
208
|
+
console.info("[QuickChatPerf]", {
|
|
209
|
+
stage,
|
|
210
|
+
elapsedMs: now - startedAt,
|
|
211
|
+
...(typeof performance !== "undefined" ? { atMs: now } : {}),
|
|
212
|
+
...(details ?? {}),
|
|
213
|
+
});
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 初始化流式状态
|
|
218
|
+
*/
|
|
219
|
+
function createInitialStreamState(): StreamState {
|
|
220
|
+
return {
|
|
221
|
+
contentBuffer: [],
|
|
222
|
+
totalUsage: null,
|
|
223
|
+
accumulatedToolCalls: [],
|
|
224
|
+
reasoningBuffer: "",
|
|
225
|
+
assistantToolCalls: undefined,
|
|
226
|
+
hasHandedOff: false,
|
|
227
|
+
hasProcessedToolCalls: false,
|
|
228
|
+
alreadyFinalized: false,
|
|
229
|
+
finishReason: null,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* 根据 tools 配置生成本次请求体(不改动外部传入的 bodyData)
|
|
235
|
+
*/
|
|
236
|
+
function buildRequestBodyWithTools(
|
|
237
|
+
bodyData: any,
|
|
238
|
+
agentConfig: any,
|
|
239
|
+
disableToolsForThisRequest: boolean
|
|
240
|
+
): any {
|
|
241
|
+
if (disableToolsForThisRequest) return bodyData;
|
|
242
|
+
|
|
243
|
+
// 如果模型拥有图像输出能力,则不组装任何 tools
|
|
244
|
+
const modelInfo = getModelInfo(agentConfig.model);
|
|
245
|
+
if (modelInfo?.hasImageOutput) {
|
|
246
|
+
return bodyData;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const rawTools = agentConfig.tools;
|
|
250
|
+
if (!Array.isArray(rawTools) || rawTools.length === 0) return bodyData;
|
|
251
|
+
const hasExplicitImageTool = rawTools.some(
|
|
252
|
+
(toolName: unknown) =>
|
|
253
|
+
typeof toolName === "string" && EXPLICIT_IMAGE_TOOL_NAMES.has(toolName)
|
|
254
|
+
);
|
|
255
|
+
if (supportsImageGeneration(agentConfig) && !hasExplicitImageTool) {
|
|
256
|
+
return bodyData;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const tools = prepareTools(rawTools, { provider: agentConfig.provider });
|
|
260
|
+
if (!tools.length) return bodyData;
|
|
261
|
+
|
|
262
|
+
return {
|
|
263
|
+
...bodyData,
|
|
264
|
+
tools,
|
|
265
|
+
tool_choice: bodyData.tool_choice ?? "auto",
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* 结束当前流式消息,派发 messageStreamEnd(带幂等保护)
|
|
271
|
+
*/
|
|
272
|
+
async function finalizeStream(
|
|
273
|
+
state: StreamState,
|
|
274
|
+
ctx: FinalizeContext
|
|
275
|
+
): Promise<StreamState> {
|
|
276
|
+
if (state.hasHandedOff || state.alreadyFinalized) return state;
|
|
277
|
+
|
|
278
|
+
const savingMetadata = withImageGenerationStage(
|
|
279
|
+
ctx.messageMetadata,
|
|
280
|
+
"saving"
|
|
281
|
+
);
|
|
282
|
+
if (savingMetadata && shouldShowImageSavingState(state.contentBuffer)) {
|
|
283
|
+
ctx.dispatch(
|
|
284
|
+
messageStreaming({
|
|
285
|
+
id: ctx.messageId,
|
|
286
|
+
dialogId: ctx.dialogId,
|
|
287
|
+
dbKey: ctx.msgKey,
|
|
288
|
+
content: "",
|
|
289
|
+
thinkContent: state.reasoningBuffer,
|
|
290
|
+
role: "assistant",
|
|
291
|
+
agentKey: ctx.agentConfig.dbKey,
|
|
292
|
+
cybotKey: ctx.agentConfig.dbKey,
|
|
293
|
+
...(typeof ctx.agentConfig?.name === "string" && ctx.agentConfig.name.trim()
|
|
294
|
+
? { agentName: ctx.agentConfig.name.trim() }
|
|
295
|
+
: {}),
|
|
296
|
+
...(savingMetadata ?? {}),
|
|
297
|
+
})
|
|
298
|
+
);
|
|
299
|
+
ctx.messageMetadata = savingMetadata;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
await ctx.dispatch(
|
|
303
|
+
messageStreamEnd({
|
|
304
|
+
finalContentBuffer: state.contentBuffer,
|
|
305
|
+
totalUsage: state.totalUsage,
|
|
306
|
+
msgKey: ctx.msgKey,
|
|
307
|
+
agentConfig: ctx.agentConfig,
|
|
308
|
+
dialogId: ctx.dialogId,
|
|
309
|
+
dialogKey: ctx.dialogKey,
|
|
310
|
+
messageId: ctx.messageId,
|
|
311
|
+
reasoningBuffer: state.reasoningBuffer,
|
|
312
|
+
messageMetadata: ctx.messageMetadata,
|
|
313
|
+
toolCalls: state.assistantToolCalls,
|
|
314
|
+
spaceId: ctx.spaceId,
|
|
315
|
+
})
|
|
316
|
+
);
|
|
317
|
+
|
|
318
|
+
return {
|
|
319
|
+
...state,
|
|
320
|
+
alreadyFinalized: true,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* 累积 usage
|
|
326
|
+
*/
|
|
327
|
+
function applyUsage(state: StreamState, data: any): StreamState {
|
|
328
|
+
if (!data.usage) return state;
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
...state,
|
|
332
|
+
totalUsage: updateTotalUsage(state.totalUsage, data.usage),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* 处理单个 delta(文本 / 推理 / tool_calls / 图片)
|
|
338
|
+
*/
|
|
339
|
+
function applyDelta(
|
|
340
|
+
state: StreamState,
|
|
341
|
+
delta: any
|
|
342
|
+
): { state: StreamState; hasNewVisibleContent: boolean } {
|
|
343
|
+
let hasNewVisibleContent = false;
|
|
344
|
+
let next: StreamState = { ...state };
|
|
345
|
+
|
|
346
|
+
// reasoning_content 增量(DeepSeek)/ reasoning 增量(Ollama/Qwen3)
|
|
347
|
+
const reasoningChunk: string = delta.reasoning_content ?? delta.reasoning ?? "";
|
|
348
|
+
if (reasoningChunk) {
|
|
349
|
+
next.reasoningBuffer = (next.reasoningBuffer || "") + reasoningChunk;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// tool_calls 累积 + 映射为 OpenAI 标准格式
|
|
353
|
+
if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) {
|
|
354
|
+
const accumulated = accumulateToolCallChunks(
|
|
355
|
+
next.accumulatedToolCalls,
|
|
356
|
+
delta.tool_calls
|
|
357
|
+
);
|
|
358
|
+
|
|
359
|
+
next = {
|
|
360
|
+
...next,
|
|
361
|
+
accumulatedToolCalls: accumulated,
|
|
362
|
+
assistantToolCalls: accumulated.map((call: any) => ({
|
|
363
|
+
id: call.id,
|
|
364
|
+
type: "function",
|
|
365
|
+
function: {
|
|
366
|
+
name: call.function?.name,
|
|
367
|
+
arguments:
|
|
368
|
+
typeof call.function?.arguments === "string"
|
|
369
|
+
? call.function.arguments
|
|
370
|
+
: JSON.stringify(call.function?.arguments ?? {}),
|
|
371
|
+
},
|
|
372
|
+
})),
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// 图片增量
|
|
377
|
+
const deltaAny = delta as any;
|
|
378
|
+
if (Array.isArray(deltaAny.images) && deltaAny.images.length > 0) {
|
|
379
|
+
next = {
|
|
380
|
+
...next,
|
|
381
|
+
contentBuffer: [...next.contentBuffer, ...deltaAny.images],
|
|
382
|
+
};
|
|
383
|
+
hasNewVisibleContent = true;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// 文本增量
|
|
387
|
+
const contentChunk = delta.content || "";
|
|
388
|
+
if (contentChunk) {
|
|
389
|
+
next = {
|
|
390
|
+
...next,
|
|
391
|
+
contentBuffer: appendTextChunk(next.contentBuffer, contentChunk),
|
|
392
|
+
};
|
|
393
|
+
hasNewVisibleContent = true;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
return { state: next, hasNewVisibleContent };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 如果有新可见内容,则派发一次 messageStreaming 更新前端
|
|
401
|
+
*/
|
|
402
|
+
function emitStreamingUpdate(
|
|
403
|
+
hasNewVisibleContent: boolean,
|
|
404
|
+
state: StreamState,
|
|
405
|
+
ctx: {
|
|
406
|
+
dispatch: any;
|
|
407
|
+
agentConfig: any;
|
|
408
|
+
messageId: string;
|
|
409
|
+
msgKey: string;
|
|
410
|
+
dialogId: string;
|
|
411
|
+
messageMetadata?: Partial<Message>;
|
|
412
|
+
}
|
|
413
|
+
) {
|
|
414
|
+
if (!hasNewVisibleContent) return;
|
|
415
|
+
|
|
416
|
+
ctx.dispatch(
|
|
417
|
+
messageStreaming({
|
|
418
|
+
id: ctx.messageId,
|
|
419
|
+
dialogId: ctx.dialogId,
|
|
420
|
+
dbKey: ctx.msgKey,
|
|
421
|
+
content: state.contentBuffer,
|
|
422
|
+
thinkContent: state.reasoningBuffer,
|
|
423
|
+
role: "assistant",
|
|
424
|
+
agentKey: ctx.agentConfig.dbKey,
|
|
425
|
+
cybotKey: ctx.agentConfig.dbKey,
|
|
426
|
+
...(typeof ctx.agentConfig?.name === "string" && ctx.agentConfig.name.trim()
|
|
427
|
+
? { agentName: ctx.agentConfig.name.trim() }
|
|
428
|
+
: {}),
|
|
429
|
+
...(ctx.messageMetadata ?? {}),
|
|
430
|
+
})
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* 处理已经累积好的 tool_calls
|
|
436
|
+
*/
|
|
437
|
+
async function processAccumulatedToolCalls(
|
|
438
|
+
state: StreamState,
|
|
439
|
+
ctx: ToolCallsContext
|
|
440
|
+
): Promise<{
|
|
441
|
+
state: StreamState;
|
|
442
|
+
hasHandedOff: boolean;
|
|
443
|
+
hasPendingInteraction: boolean;
|
|
444
|
+
}> {
|
|
445
|
+
if (!state.accumulatedToolCalls.length) {
|
|
446
|
+
return {
|
|
447
|
+
state,
|
|
448
|
+
hasHandedOff: false,
|
|
449
|
+
hasPendingInteraction: false,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const result = await ctx
|
|
454
|
+
.dispatch(
|
|
455
|
+
handleToolCalls({
|
|
456
|
+
accumulatedCalls: state.accumulatedToolCalls,
|
|
457
|
+
currentContentBuffer: state.contentBuffer,
|
|
458
|
+
agentConfig: ctx.agentConfig,
|
|
459
|
+
messageId: ctx.messageId,
|
|
460
|
+
dialogId: ctx.dialogId,
|
|
461
|
+
dialogKey: ctx.dialogKey,
|
|
462
|
+
parallelSessionId: ctx.messageMetadata?.parallelSessionId,
|
|
463
|
+
parallelBranchId: ctx.messageMetadata?.parallelBranchId,
|
|
464
|
+
parallelLabel: ctx.messageMetadata?.parallelLabel,
|
|
465
|
+
parallelIndex: ctx.messageMetadata?.parallelIndex,
|
|
466
|
+
})
|
|
467
|
+
)
|
|
468
|
+
.unwrap();
|
|
469
|
+
|
|
470
|
+
const nextState: StreamState = {
|
|
471
|
+
...state,
|
|
472
|
+
contentBuffer: result.finalContentBuffer,
|
|
473
|
+
accumulatedToolCalls: [],
|
|
474
|
+
hasProcessedToolCalls: true,
|
|
475
|
+
hasHandedOff: result.hasHandedOff,
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
return {
|
|
479
|
+
state: nextState,
|
|
480
|
+
hasHandedOff: result.hasHandedOff,
|
|
481
|
+
hasPendingInteraction: result.hasPendingInteraction,
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
async function readStreamChunkWithTimeout(
|
|
486
|
+
reader: ReadableStreamDefaultReader<Uint8Array>
|
|
487
|
+
) {
|
|
488
|
+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
489
|
+
try {
|
|
490
|
+
return await Promise.race([
|
|
491
|
+
reader.read(),
|
|
492
|
+
new Promise<ReadableStreamReadResult<Uint8Array>>((_, reject) => {
|
|
493
|
+
timeoutId = setTimeout(() => {
|
|
494
|
+
reject(
|
|
495
|
+
new Error(
|
|
496
|
+
`模型响应流 ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)} 秒内没有返回新内容`
|
|
497
|
+
)
|
|
498
|
+
);
|
|
499
|
+
}, STREAM_READ_TIMEOUT_MS);
|
|
500
|
+
}),
|
|
501
|
+
]);
|
|
502
|
+
} finally {
|
|
503
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* 处理「流结束」场景(done === true)
|
|
509
|
+
*/
|
|
510
|
+
async function handleStreamCompletion(
|
|
511
|
+
state: StreamState,
|
|
512
|
+
ctx: StreamCompletionContext,
|
|
513
|
+
finalizeCtx: FinalizeContext
|
|
514
|
+
): Promise<{
|
|
515
|
+
state: StreamState;
|
|
516
|
+
hasHandedOff: boolean;
|
|
517
|
+
hasPendingInteraction: boolean;
|
|
518
|
+
}> {
|
|
519
|
+
let hasHandedOff = false;
|
|
520
|
+
let hasPendingInteraction = false;
|
|
521
|
+
|
|
522
|
+
if (!state.hasProcessedToolCalls && state.accumulatedToolCalls.length > 0) {
|
|
523
|
+
// Tool 开始前先更新 TopBar token 显示
|
|
524
|
+
if (state.totalUsage) {
|
|
525
|
+
ctx.dispatch(tokenUsageLiveUpdate({
|
|
526
|
+
input_tokens: state.totalUsage.prompt_tokens ?? state.totalUsage.input_tokens,
|
|
527
|
+
output_tokens: state.totalUsage.completion_tokens ?? state.totalUsage.output_tokens,
|
|
528
|
+
cost: state.totalUsage.cost,
|
|
529
|
+
dialogKey: ctx.dialogKey,
|
|
530
|
+
}));
|
|
531
|
+
}
|
|
532
|
+
const toolResult = await processAccumulatedToolCalls(state, {
|
|
533
|
+
dispatch: ctx.dispatch,
|
|
534
|
+
agentConfig: ctx.agentConfig,
|
|
535
|
+
dialogId: ctx.dialogId,
|
|
536
|
+
dialogKey: ctx.dialogKey,
|
|
537
|
+
messageId: ctx.messageId,
|
|
538
|
+
messageMetadata: ctx.messageMetadata,
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
let next = toolResult.state;
|
|
542
|
+
hasHandedOff ||= toolResult.hasHandedOff;
|
|
543
|
+
hasPendingInteraction ||= toolResult.hasPendingInteraction;
|
|
544
|
+
|
|
545
|
+
next = await finalizeStream(next, finalizeCtx);
|
|
546
|
+
return { state: next, hasHandedOff, hasPendingInteraction };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const finalized = await finalizeStream(state, finalizeCtx);
|
|
550
|
+
return { state: finalized, hasHandedOff, hasPendingInteraction };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* 主流程:发送请求 + 处理流式 SSE + 工具调用
|
|
555
|
+
*/
|
|
556
|
+
export const sendOpenAICompletionsRequest = async ({
|
|
557
|
+
bodyData,
|
|
558
|
+
agentConfig,
|
|
559
|
+
thunkApi,
|
|
560
|
+
dialogKey,
|
|
561
|
+
parentMessageId,
|
|
562
|
+
messageMetadata,
|
|
563
|
+
disableToolsForThisRequest = false,
|
|
564
|
+
quickChatPerfStartedAt,
|
|
565
|
+
}: {
|
|
566
|
+
bodyData: any;
|
|
567
|
+
agentConfig: any;
|
|
568
|
+
thunkApi: any;
|
|
569
|
+
dialogKey: string;
|
|
570
|
+
parentMessageId?: string;
|
|
571
|
+
messageMetadata?: Partial<Message>;
|
|
572
|
+
disableToolsForThisRequest?: boolean;
|
|
573
|
+
quickChatPerfStartedAt?: number;
|
|
574
|
+
}): Promise<CompletionMeta> => {
|
|
575
|
+
const { dispatch, getState, signal: thunkSignal } = thunkApi;
|
|
576
|
+
|
|
577
|
+
const dialogId = extractCustomId(dialogKey);
|
|
578
|
+
const controller = new AbortController();
|
|
579
|
+
thunkSignal.addEventListener("abort", () => controller.abort());
|
|
580
|
+
const signal = controller.signal;
|
|
581
|
+
const streamSpaceId = selectCurrentSpaceId(getState() as RootState) || undefined;
|
|
582
|
+
|
|
583
|
+
let messageId: string;
|
|
584
|
+
let msgKey: string;
|
|
585
|
+
|
|
586
|
+
if (parentMessageId) {
|
|
587
|
+
messageId = parentMessageId;
|
|
588
|
+
msgKey = `msg:${dialogId}:${messageId}`;
|
|
589
|
+
} else {
|
|
590
|
+
const newIds = createDialogMessageKeyAndId(dialogId);
|
|
591
|
+
messageId = newIds.messageId;
|
|
592
|
+
msgKey = newIds.key;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
dispatch(addActiveController({ messageId, controller, dialogKey }));
|
|
596
|
+
|
|
597
|
+
const requestBody = await inlineImageUrlsForCustomProvider(
|
|
598
|
+
buildRequestBodyWithTools(
|
|
599
|
+
bodyData,
|
|
600
|
+
agentConfig,
|
|
601
|
+
disableToolsForThisRequest
|
|
602
|
+
),
|
|
603
|
+
{
|
|
604
|
+
shouldInline: shouldInlineImageUrlsForAgent(agentConfig),
|
|
605
|
+
},
|
|
606
|
+
);
|
|
607
|
+
|
|
608
|
+
let streamState: StreamState = createInitialStreamState();
|
|
609
|
+
const parseSSE = createSSEParser();
|
|
610
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
611
|
+
|
|
612
|
+
const finalizeCtx: FinalizeContext = {
|
|
613
|
+
dispatch,
|
|
614
|
+
msgKey,
|
|
615
|
+
dialogId,
|
|
616
|
+
dialogKey,
|
|
617
|
+
messageId,
|
|
618
|
+
agentConfig,
|
|
619
|
+
spaceId: streamSpaceId,
|
|
620
|
+
messageMetadata,
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
let hasHandedOffOverall = false;
|
|
624
|
+
let hasPendingInteractionOverall = false;
|
|
625
|
+
let lastFinishReason: string | null = null;
|
|
626
|
+
let activeMessageMetadata = messageMetadata;
|
|
627
|
+
|
|
628
|
+
const buildMeta = (): CompletionMeta => ({
|
|
629
|
+
hasToolCalls:
|
|
630
|
+
Array.isArray(streamState.assistantToolCalls) &&
|
|
631
|
+
streamState.assistantToolCalls.length > 0,
|
|
632
|
+
hasPendingInteraction: hasPendingInteractionOverall,
|
|
633
|
+
hasHandedOff: hasHandedOffOverall,
|
|
634
|
+
finishReason: lastFinishReason,
|
|
635
|
+
messageId,
|
|
636
|
+
usage: streamState.totalUsage ?? undefined,
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
try {
|
|
640
|
+
if (!parentMessageId) {
|
|
641
|
+
dispatch(
|
|
642
|
+
messageStreaming({
|
|
643
|
+
id: messageId,
|
|
644
|
+
dialogId,
|
|
645
|
+
dbKey: msgKey,
|
|
646
|
+
content: "",
|
|
647
|
+
role: "assistant",
|
|
648
|
+
agentKey: agentConfig.dbKey,
|
|
649
|
+
cybotKey: agentConfig.dbKey,
|
|
650
|
+
...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
|
|
651
|
+
? { agentName: agentConfig.name.trim() }
|
|
652
|
+
: {}),
|
|
653
|
+
...(activeMessageMetadata ?? {}),
|
|
654
|
+
isStreaming: true,
|
|
655
|
+
})
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
const api = getApiEndpoint(agentConfig);
|
|
660
|
+
const token = selectCurrentToken(getState() as RootState);
|
|
661
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "openai-completions-fetch-starting", {
|
|
662
|
+
api,
|
|
663
|
+
dialogKey,
|
|
664
|
+
});
|
|
665
|
+
const response = await performFetchRequest({
|
|
666
|
+
agentConfig,
|
|
667
|
+
api,
|
|
668
|
+
bodyData: requestBody,
|
|
669
|
+
currentServer: selectCurrentServer(getState() as RootState),
|
|
670
|
+
signal,
|
|
671
|
+
token,
|
|
672
|
+
});
|
|
673
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "openai-completions-fetch-response", {
|
|
674
|
+
ok: response.ok,
|
|
675
|
+
status: response.status,
|
|
676
|
+
dialogKey,
|
|
677
|
+
});
|
|
678
|
+
activeMessageMetadata = withImageGenerationStage(
|
|
679
|
+
activeMessageMetadata,
|
|
680
|
+
"generating"
|
|
681
|
+
);
|
|
682
|
+
finalizeCtx.messageMetadata = activeMessageMetadata;
|
|
683
|
+
if (!parentMessageId && activeMessageMetadata?.imageGenerationState) {
|
|
684
|
+
dispatch(
|
|
685
|
+
messageStreaming({
|
|
686
|
+
id: messageId,
|
|
687
|
+
dialogId,
|
|
688
|
+
dbKey: msgKey,
|
|
689
|
+
content: "",
|
|
690
|
+
role: "assistant",
|
|
691
|
+
agentKey: agentConfig.dbKey,
|
|
692
|
+
cybotKey: agentConfig.dbKey,
|
|
693
|
+
...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
|
|
694
|
+
? { agentName: agentConfig.name.trim() }
|
|
695
|
+
: {}),
|
|
696
|
+
...(activeMessageMetadata ?? {}),
|
|
697
|
+
isStreaming: true,
|
|
698
|
+
})
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
if (!response.ok) {
|
|
703
|
+
const errorMessage = await parseApiError(response);
|
|
704
|
+
streamState = {
|
|
705
|
+
...streamState,
|
|
706
|
+
contentBuffer: appendTextChunk(
|
|
707
|
+
streamState.contentBuffer,
|
|
708
|
+
`[错误: ${errorMessage}]`
|
|
709
|
+
),
|
|
710
|
+
};
|
|
711
|
+
streamState = await finalizeStream(streamState, finalizeCtx);
|
|
712
|
+
return buildMeta();
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
reader = response.body?.getReader();
|
|
716
|
+
if (!reader) {
|
|
717
|
+
streamState = await finalizeStream(streamState, finalizeCtx);
|
|
718
|
+
return buildMeta();
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const decoder = new TextDecoder();
|
|
722
|
+
let loggedFirstStreamChunk = false;
|
|
723
|
+
let loggedFirstParsedEvent = false;
|
|
724
|
+
let loggedFirstVisibleDelta = false;
|
|
725
|
+
|
|
726
|
+
while (true) {
|
|
727
|
+
const { done, value } = await readStreamChunkWithTimeout(reader);
|
|
728
|
+
|
|
729
|
+
if (done) {
|
|
730
|
+
const completion = await handleStreamCompletion(
|
|
731
|
+
streamState,
|
|
732
|
+
{
|
|
733
|
+
dispatch,
|
|
734
|
+
dialogId,
|
|
735
|
+
dialogKey: finalizeCtx.dialogKey,
|
|
736
|
+
messageId,
|
|
737
|
+
agentConfig,
|
|
738
|
+
},
|
|
739
|
+
finalizeCtx
|
|
740
|
+
);
|
|
741
|
+
|
|
742
|
+
streamState = completion.state;
|
|
743
|
+
hasHandedOffOverall ||= completion.hasHandedOff;
|
|
744
|
+
hasPendingInteractionOverall ||= completion.hasPendingInteraction;
|
|
745
|
+
|
|
746
|
+
break;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
if (!loggedFirstStreamChunk) {
|
|
750
|
+
loggedFirstStreamChunk = true;
|
|
751
|
+
logQuickChatPerfStage(
|
|
752
|
+
quickChatPerfStartedAt,
|
|
753
|
+
"openai-completions-first-stream-chunk",
|
|
754
|
+
{ dialogKey, byteLength: value.byteLength }
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
759
|
+
const parsedResults = parseSSE(chunk);
|
|
760
|
+
if (parsedResults.length > 0 && !loggedFirstParsedEvent) {
|
|
761
|
+
loggedFirstParsedEvent = true;
|
|
762
|
+
logQuickChatPerfStage(
|
|
763
|
+
quickChatPerfStartedAt,
|
|
764
|
+
"openai-completions-first-sse-event",
|
|
765
|
+
{ dialogKey, eventCount: parsedResults.length }
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
for (const parsedData of parsedResults) {
|
|
770
|
+
const dataList = Array.isArray(parsedData) ? parsedData : [parsedData];
|
|
771
|
+
|
|
772
|
+
for (const data of dataList) {
|
|
773
|
+
streamState = applyUsage(streamState, data);
|
|
774
|
+
|
|
775
|
+
if (data === "[DONE]") {
|
|
776
|
+
// Web 端通常依赖 reader.read() 的 done 状态来结束,
|
|
777
|
+
// 但如果流中显式包含 [DONE],也可以直接 break。
|
|
778
|
+
// 这里我们选择忽略它,让 reader 自然结束。
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
if (data.error) {
|
|
783
|
+
const errorMsg = `Error: ${formatStreamErrorMessage(data)}`;
|
|
784
|
+
streamState = {
|
|
785
|
+
...streamState,
|
|
786
|
+
contentBuffer: appendTextChunk(
|
|
787
|
+
streamState.contentBuffer,
|
|
788
|
+
`\n[API Error] ${errorMsg}`
|
|
789
|
+
),
|
|
790
|
+
};
|
|
791
|
+
await reader.cancel();
|
|
792
|
+
break;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const choice = data.choices?.[0];
|
|
796
|
+
if (!choice) continue;
|
|
797
|
+
|
|
798
|
+
const delta = choice.delta || {};
|
|
799
|
+
|
|
800
|
+
const { state: updatedState, hasNewVisibleContent } = applyDelta(
|
|
801
|
+
streamState,
|
|
802
|
+
delta
|
|
803
|
+
);
|
|
804
|
+
streamState = updatedState;
|
|
805
|
+
if (hasNewVisibleContent && !loggedFirstVisibleDelta) {
|
|
806
|
+
loggedFirstVisibleDelta = true;
|
|
807
|
+
logQuickChatPerfStage(
|
|
808
|
+
quickChatPerfStartedAt,
|
|
809
|
+
"openai-completions-first-visible-delta",
|
|
810
|
+
{ dialogKey }
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
emitStreamingUpdate(hasNewVisibleContent, streamState, {
|
|
815
|
+
dispatch,
|
|
816
|
+
agentConfig,
|
|
817
|
+
messageId,
|
|
818
|
+
msgKey,
|
|
819
|
+
dialogId,
|
|
820
|
+
messageMetadata: activeMessageMetadata,
|
|
821
|
+
});
|
|
822
|
+
|
|
823
|
+
const finishReason = choice.finish_reason;
|
|
824
|
+
if (finishReason) {
|
|
825
|
+
lastFinishReason = finishReason;
|
|
826
|
+
streamState.finishReason = finishReason;
|
|
827
|
+
|
|
828
|
+
if (finishReason === "tool_calls") {
|
|
829
|
+
// Tool 开始前先更新 TopBar token 显示
|
|
830
|
+
if (streamState.totalUsage) {
|
|
831
|
+
dispatch(tokenUsageLiveUpdate({
|
|
832
|
+
input_tokens: streamState.totalUsage.prompt_tokens ?? streamState.totalUsage.input_tokens,
|
|
833
|
+
output_tokens: streamState.totalUsage.completion_tokens ?? streamState.totalUsage.output_tokens,
|
|
834
|
+
cost: streamState.totalUsage.cost,
|
|
835
|
+
dialogKey,
|
|
836
|
+
}));
|
|
837
|
+
}
|
|
838
|
+
const toolResult = await processAccumulatedToolCalls(
|
|
839
|
+
streamState,
|
|
840
|
+
{
|
|
841
|
+
dispatch,
|
|
842
|
+
agentConfig,
|
|
843
|
+
dialogId,
|
|
844
|
+
dialogKey,
|
|
845
|
+
messageId,
|
|
846
|
+
messageMetadata,
|
|
847
|
+
}
|
|
848
|
+
);
|
|
849
|
+
|
|
850
|
+
streamState = toolResult.state;
|
|
851
|
+
hasHandedOffOverall ||= toolResult.hasHandedOff;
|
|
852
|
+
hasPendingInteractionOverall ||= toolResult.hasPendingInteraction;
|
|
853
|
+
|
|
854
|
+
// 无论是否 handoff,都 finalize 当前 assistant 消息(stub)
|
|
855
|
+
streamState = await finalizeStream(streamState, finalizeCtx);
|
|
856
|
+
} else if (finishReason !== "stop") {
|
|
857
|
+
streamState = {
|
|
858
|
+
...streamState,
|
|
859
|
+
contentBuffer: appendTextChunk(
|
|
860
|
+
streamState.contentBuffer,
|
|
861
|
+
`\n[流结束原因: ${finishReason}]`
|
|
862
|
+
),
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
} catch (error: any) {
|
|
870
|
+
let errorText: string;
|
|
871
|
+
if (error?.name === "AbortError") {
|
|
872
|
+
errorText = "\n[用户中断]";
|
|
873
|
+
} else {
|
|
874
|
+
errorText = `\n[错误: ${error?.message || String(error)}]`;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
console.error("[SSE] sendOpenAICompletionsRequest error:", error);
|
|
878
|
+
|
|
879
|
+
streamState = {
|
|
880
|
+
...streamState,
|
|
881
|
+
contentBuffer: appendTextChunk(streamState.contentBuffer, errorText),
|
|
882
|
+
};
|
|
883
|
+
streamState = await finalizeStream(streamState, finalizeCtx);
|
|
884
|
+
} finally {
|
|
885
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "openai-completions-stream-finished", {
|
|
886
|
+
dialogKey,
|
|
887
|
+
});
|
|
888
|
+
dispatch(removeActiveController({ messageId, dialogKey }));
|
|
889
|
+
try {
|
|
890
|
+
await reader?.cancel();
|
|
891
|
+
} catch (_e) {
|
|
892
|
+
// ignore
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
return buildMeta();
|
|
897
|
+
};
|