@realtimex/node-llama-cpp 0.1.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/LICENSE +21 -0
- package/README.md +108 -0
- package/dist/ChatWrapper.d.ts +27 -0
- package/dist/ChatWrapper.js +233 -0
- package/dist/ChatWrapper.js.map +1 -0
- package/dist/apiDocsIndex.d.ts +1 -0
- package/dist/apiDocsIndex.js +7 -0
- package/dist/apiDocsIndex.js.map +1 -0
- package/dist/bindings/AddonTypes.d.ts +203 -0
- package/dist/bindings/AddonTypes.js +2 -0
- package/dist/bindings/AddonTypes.js.map +1 -0
- package/dist/bindings/Llama.d.ts +104 -0
- package/dist/bindings/Llama.js +570 -0
- package/dist/bindings/Llama.js.map +1 -0
- package/dist/bindings/consts.d.ts +2 -0
- package/dist/bindings/consts.js +13 -0
- package/dist/bindings/consts.js.map +1 -0
- package/dist/bindings/getLlama.d.ts +297 -0
- package/dist/bindings/getLlama.js +569 -0
- package/dist/bindings/getLlama.js.map +1 -0
- package/dist/bindings/types.d.ts +72 -0
- package/dist/bindings/types.js +105 -0
- package/dist/bindings/types.js.map +1 -0
- package/dist/bindings/utils/MemoryOrchestrator.d.ts +23 -0
- package/dist/bindings/utils/MemoryOrchestrator.js +50 -0
- package/dist/bindings/utils/MemoryOrchestrator.js.map +1 -0
- package/dist/bindings/utils/NoBinaryFoundError.d.ts +2 -0
- package/dist/bindings/utils/NoBinaryFoundError.js +7 -0
- package/dist/bindings/utils/NoBinaryFoundError.js.map +1 -0
- package/dist/bindings/utils/asyncEvery.d.ts +5 -0
- package/dist/bindings/utils/asyncEvery.js +15 -0
- package/dist/bindings/utils/asyncEvery.js.map +1 -0
- package/dist/bindings/utils/asyncSome.d.ts +5 -0
- package/dist/bindings/utils/asyncSome.js +29 -0
- package/dist/bindings/utils/asyncSome.js.map +1 -0
- package/dist/bindings/utils/binariesGithubRelease.d.ts +6 -0
- package/dist/bindings/utils/binariesGithubRelease.js +15 -0
- package/dist/bindings/utils/binariesGithubRelease.js.map +1 -0
- package/dist/bindings/utils/clearAllLocalBuilds.d.ts +1 -0
- package/dist/bindings/utils/clearAllLocalBuilds.js +47 -0
- package/dist/bindings/utils/clearAllLocalBuilds.js.map +1 -0
- package/dist/bindings/utils/cloneLlamaCppRepo.d.ts +11 -0
- package/dist/bindings/utils/cloneLlamaCppRepo.js +166 -0
- package/dist/bindings/utils/cloneLlamaCppRepo.js.map +1 -0
- package/dist/bindings/utils/compileLLamaCpp.d.ts +22 -0
- package/dist/bindings/utils/compileLLamaCpp.js +526 -0
- package/dist/bindings/utils/compileLLamaCpp.js.map +1 -0
- package/dist/bindings/utils/detectAvailableComputeLayers.d.ts +18 -0
- package/dist/bindings/utils/detectAvailableComputeLayers.js +311 -0
- package/dist/bindings/utils/detectAvailableComputeLayers.js.map +1 -0
- package/dist/bindings/utils/detectBuildTools.d.ts +14 -0
- package/dist/bindings/utils/detectBuildTools.js +149 -0
- package/dist/bindings/utils/detectBuildTools.js.map +1 -0
- package/dist/bindings/utils/detectGlibc.d.ts +4 -0
- package/dist/bindings/utils/detectGlibc.js +74 -0
- package/dist/bindings/utils/detectGlibc.js.map +1 -0
- package/dist/bindings/utils/disposeBeforeExit.d.ts +8 -0
- package/dist/bindings/utils/disposeBeforeExit.js +36 -0
- package/dist/bindings/utils/disposeBeforeExit.js.map +1 -0
- package/dist/bindings/utils/getBestComputeLayersAvailable.d.ts +9 -0
- package/dist/bindings/utils/getBestComputeLayersAvailable.js +29 -0
- package/dist/bindings/utils/getBestComputeLayersAvailable.js.map +1 -0
- package/dist/bindings/utils/getBuildFolderNameForBuildOptions.d.ts +6 -0
- package/dist/bindings/utils/getBuildFolderNameForBuildOptions.js +105 -0
- package/dist/bindings/utils/getBuildFolderNameForBuildOptions.js.map +1 -0
- package/dist/bindings/utils/getCanUsePrebuiltBinaries.d.ts +1 -0
- package/dist/bindings/utils/getCanUsePrebuiltBinaries.js +8 -0
- package/dist/bindings/utils/getCanUsePrebuiltBinaries.js.map +1 -0
- package/dist/bindings/utils/getExampleUsageCodeOfGetLlama.d.ts +2 -0
- package/dist/bindings/utils/getExampleUsageCodeOfGetLlama.js +21 -0
- package/dist/bindings/utils/getExampleUsageCodeOfGetLlama.js.map +1 -0
- package/dist/bindings/utils/getGpuTypesToUseForOption.d.ts +12 -0
- package/dist/bindings/utils/getGpuTypesToUseForOption.js +39 -0
- package/dist/bindings/utils/getGpuTypesToUseForOption.js.map +1 -0
- package/dist/bindings/utils/getLinuxDistroInfo.d.ts +9 -0
- package/dist/bindings/utils/getLinuxDistroInfo.js +46 -0
- package/dist/bindings/utils/getLinuxDistroInfo.js.map +1 -0
- package/dist/bindings/utils/getLlamaGpuTypes.d.ts +13 -0
- package/dist/bindings/utils/getLlamaGpuTypes.js +36 -0
- package/dist/bindings/utils/getLlamaGpuTypes.js.map +1 -0
- package/dist/bindings/utils/getLlamaWithoutBackend.d.ts +5 -0
- package/dist/bindings/utils/getLlamaWithoutBackend.js +40 -0
- package/dist/bindings/utils/getLlamaWithoutBackend.js.map +1 -0
- package/dist/bindings/utils/getPlatform.d.ts +2 -0
- package/dist/bindings/utils/getPlatform.js +15 -0
- package/dist/bindings/utils/getPlatform.js.map +1 -0
- package/dist/bindings/utils/getPlatformInfo.d.ts +5 -0
- package/dist/bindings/utils/getPlatformInfo.js +28 -0
- package/dist/bindings/utils/getPlatformInfo.js.map +1 -0
- package/dist/bindings/utils/hasBuildingFromSourceDependenciesInstalled.d.ts +3 -0
- package/dist/bindings/utils/hasBuildingFromSourceDependenciesInstalled.js +27 -0
- package/dist/bindings/utils/hasBuildingFromSourceDependenciesInstalled.js.map +1 -0
- package/dist/bindings/utils/hasFileInPath.d.ts +2 -0
- package/dist/bindings/utils/hasFileInPath.js +34 -0
- package/dist/bindings/utils/hasFileInPath.js.map +1 -0
- package/dist/bindings/utils/lastBuildInfo.d.ts +6 -0
- package/dist/bindings/utils/lastBuildInfo.js +17 -0
- package/dist/bindings/utils/lastBuildInfo.js.map +1 -0
- package/dist/bindings/utils/logBinaryUsageExampleToConsole.d.ts +2 -0
- package/dist/bindings/utils/logBinaryUsageExampleToConsole.js +22 -0
- package/dist/bindings/utils/logBinaryUsageExampleToConsole.js.map +1 -0
- package/dist/bindings/utils/logDistroInstallInstruction.d.ts +14 -0
- package/dist/bindings/utils/logDistroInstallInstruction.js +48 -0
- package/dist/bindings/utils/logDistroInstallInstruction.js.map +1 -0
- package/dist/bindings/utils/resolveActualBindingBinaryPath.d.ts +1 -0
- package/dist/bindings/utils/resolveActualBindingBinaryPath.js +18 -0
- package/dist/bindings/utils/resolveActualBindingBinaryPath.js.map +1 -0
- package/dist/bindings/utils/resolveCustomCmakeOptions.d.ts +1 -0
- package/dist/bindings/utils/resolveCustomCmakeOptions.js +43 -0
- package/dist/bindings/utils/resolveCustomCmakeOptions.js.map +1 -0
- package/dist/bindings/utils/testBindingBinary.d.ts +2 -0
- package/dist/bindings/utils/testBindingBinary.js +269 -0
- package/dist/bindings/utils/testBindingBinary.js.map +1 -0
- package/dist/bindings/utils/testCmakeBinary.d.ts +5 -0
- package/dist/bindings/utils/testCmakeBinary.js +32 -0
- package/dist/bindings/utils/testCmakeBinary.js.map +1 -0
- package/dist/chatWrappers/AlpacaChatWrapper.d.ts +17 -0
- package/dist/chatWrappers/AlpacaChatWrapper.js +33 -0
- package/dist/chatWrappers/AlpacaChatWrapper.js.map +1 -0
- package/dist/chatWrappers/ChatMLChatWrapper.d.ts +6 -0
- package/dist/chatWrappers/ChatMLChatWrapper.js +85 -0
- package/dist/chatWrappers/ChatMLChatWrapper.js.map +1 -0
- package/dist/chatWrappers/DeepSeekChatWrapper.d.ts +37 -0
- package/dist/chatWrappers/DeepSeekChatWrapper.js +294 -0
- package/dist/chatWrappers/DeepSeekChatWrapper.js.map +1 -0
- package/dist/chatWrappers/EmptyChatWrapper.d.ts +4 -0
- package/dist/chatWrappers/EmptyChatWrapper.js +5 -0
- package/dist/chatWrappers/EmptyChatWrapper.js.map +1 -0
- package/dist/chatWrappers/FalconChatWrapper.d.ts +19 -0
- package/dist/chatWrappers/FalconChatWrapper.js +126 -0
- package/dist/chatWrappers/FalconChatWrapper.js.map +1 -0
- package/dist/chatWrappers/FunctionaryChatWrapper.d.ts +17 -0
- package/dist/chatWrappers/FunctionaryChatWrapper.js +622 -0
- package/dist/chatWrappers/FunctionaryChatWrapper.js.map +1 -0
- package/dist/chatWrappers/GemmaChatWrapper.d.ts +7 -0
- package/dist/chatWrappers/GemmaChatWrapper.js +96 -0
- package/dist/chatWrappers/GemmaChatWrapper.js.map +1 -0
- package/dist/chatWrappers/GeneralChatWrapper.d.ts +19 -0
- package/dist/chatWrappers/GeneralChatWrapper.js +140 -0
- package/dist/chatWrappers/GeneralChatWrapper.js.map +1 -0
- package/dist/chatWrappers/HarmonyChatWrapper.d.ts +78 -0
- package/dist/chatWrappers/HarmonyChatWrapper.js +539 -0
- package/dist/chatWrappers/HarmonyChatWrapper.js.map +1 -0
- package/dist/chatWrappers/Llama2ChatWrapper.d.ts +12 -0
- package/dist/chatWrappers/Llama2ChatWrapper.js +95 -0
- package/dist/chatWrappers/Llama2ChatWrapper.js.map +1 -0
- package/dist/chatWrappers/Llama3ChatWrapper.d.ts +16 -0
- package/dist/chatWrappers/Llama3ChatWrapper.js +173 -0
- package/dist/chatWrappers/Llama3ChatWrapper.js.map +1 -0
- package/dist/chatWrappers/Llama3_1ChatWrapper.d.ts +32 -0
- package/dist/chatWrappers/Llama3_1ChatWrapper.js +290 -0
- package/dist/chatWrappers/Llama3_1ChatWrapper.js.map +1 -0
- package/dist/chatWrappers/Llama3_2LightweightChatWrapper.d.ts +35 -0
- package/dist/chatWrappers/Llama3_2LightweightChatWrapper.js +264 -0
- package/dist/chatWrappers/Llama3_2LightweightChatWrapper.js.map +1 -0
- package/dist/chatWrappers/MistralChatWrapper.d.ts +16 -0
- package/dist/chatWrappers/MistralChatWrapper.js +180 -0
- package/dist/chatWrappers/MistralChatWrapper.js.map +1 -0
- package/dist/chatWrappers/QwenChatWrapper.d.ts +36 -0
- package/dist/chatWrappers/QwenChatWrapper.js +344 -0
- package/dist/chatWrappers/QwenChatWrapper.js.map +1 -0
- package/dist/chatWrappers/SeedChatWrapper.d.ts +25 -0
- package/dist/chatWrappers/SeedChatWrapper.js +183 -0
- package/dist/chatWrappers/SeedChatWrapper.js.map +1 -0
- package/dist/chatWrappers/generic/JinjaTemplateChatWrapper.d.ts +138 -0
- package/dist/chatWrappers/generic/JinjaTemplateChatWrapper.js +665 -0
- package/dist/chatWrappers/generic/JinjaTemplateChatWrapper.js.map +1 -0
- package/dist/chatWrappers/generic/TemplateChatWrapper.d.ts +76 -0
- package/dist/chatWrappers/generic/TemplateChatWrapper.js +212 -0
- package/dist/chatWrappers/generic/TemplateChatWrapper.js.map +1 -0
- package/dist/chatWrappers/generic/utils/UniqueIdGenerator.d.ts +7 -0
- package/dist/chatWrappers/generic/utils/UniqueIdGenerator.js +30 -0
- package/dist/chatWrappers/generic/utils/UniqueIdGenerator.js.map +1 -0
- package/dist/chatWrappers/generic/utils/chatHistoryFunctionCallMessageTemplate.d.ts +24 -0
- package/dist/chatWrappers/generic/utils/chatHistoryFunctionCallMessageTemplate.js +45 -0
- package/dist/chatWrappers/generic/utils/chatHistoryFunctionCallMessageTemplate.js.map +1 -0
- package/dist/chatWrappers/generic/utils/extractFunctionCallSettingsFromJinjaTemplate.d.ts +25 -0
- package/dist/chatWrappers/generic/utils/extractFunctionCallSettingsFromJinjaTemplate.js +690 -0
- package/dist/chatWrappers/generic/utils/extractFunctionCallSettingsFromJinjaTemplate.js.map +1 -0
- package/dist/chatWrappers/generic/utils/extractSegmentSettingsFromTokenizerAndChatTemplate.d.ts +2 -0
- package/dist/chatWrappers/generic/utils/extractSegmentSettingsFromTokenizerAndChatTemplate.js +66 -0
- package/dist/chatWrappers/generic/utils/extractSegmentSettingsFromTokenizerAndChatTemplate.js.map +1 -0
- package/dist/chatWrappers/generic/utils/getFirstValidResult.d.ts +6 -0
- package/dist/chatWrappers/generic/utils/getFirstValidResult.js +19 -0
- package/dist/chatWrappers/generic/utils/getFirstValidResult.js.map +1 -0
- package/dist/chatWrappers/generic/utils/squashChatHistoryItems.d.ts +2 -0
- package/dist/chatWrappers/generic/utils/squashChatHistoryItems.js +35 -0
- package/dist/chatWrappers/generic/utils/squashChatHistoryItems.js.map +1 -0
- package/dist/chatWrappers/generic/utils/templateSegmentOptionsToChatWrapperSettings.d.ts +22 -0
- package/dist/chatWrappers/generic/utils/templateSegmentOptionsToChatWrapperSettings.js +28 -0
- package/dist/chatWrappers/generic/utils/templateSegmentOptionsToChatWrapperSettings.js.map +1 -0
- package/dist/chatWrappers/utils/ChatModelFunctionsDocumentationGenerator.d.ts +76 -0
- package/dist/chatWrappers/utils/ChatModelFunctionsDocumentationGenerator.js +177 -0
- package/dist/chatWrappers/utils/ChatModelFunctionsDocumentationGenerator.js.map +1 -0
- package/dist/chatWrappers/utils/chunkChatItems.d.ts +10 -0
- package/dist/chatWrappers/utils/chunkChatItems.js +44 -0
- package/dist/chatWrappers/utils/chunkChatItems.js.map +1 -0
- package/dist/chatWrappers/utils/getModelLinageNames.d.ts +2 -0
- package/dist/chatWrappers/utils/getModelLinageNames.js +18 -0
- package/dist/chatWrappers/utils/getModelLinageNames.js.map +1 -0
- package/dist/chatWrappers/utils/isJinjaTemplateEquivalentToSpecializedChatWrapper.d.ts +4 -0
- package/dist/chatWrappers/utils/isJinjaTemplateEquivalentToSpecializedChatWrapper.js +394 -0
- package/dist/chatWrappers/utils/isJinjaTemplateEquivalentToSpecializedChatWrapper.js.map +1 -0
- package/dist/chatWrappers/utils/isLlama3_2LightweightModel.d.ts +2 -0
- package/dist/chatWrappers/utils/isLlama3_2LightweightModel.js +9 -0
- package/dist/chatWrappers/utils/isLlama3_2LightweightModel.js.map +1 -0
- package/dist/chatWrappers/utils/jsonDumps.d.ts +7 -0
- package/dist/chatWrappers/utils/jsonDumps.js +18 -0
- package/dist/chatWrappers/utils/jsonDumps.js.map +1 -0
- package/dist/chatWrappers/utils/resolveChatWrapper.d.ts +148 -0
- package/dist/chatWrappers/utils/resolveChatWrapper.js +325 -0
- package/dist/chatWrappers/utils/resolveChatWrapper.js.map +1 -0
- package/dist/cli/cli.d.ts +2 -0
- package/dist/cli/cli.js +45 -0
- package/dist/cli/cli.js.map +1 -0
- package/dist/cli/commands/ChatCommand.d.ts +59 -0
- package/dist/cli/commands/ChatCommand.js +856 -0
- package/dist/cli/commands/ChatCommand.js.map +1 -0
- package/dist/cli/commands/CompleteCommand.d.ts +47 -0
- package/dist/cli/commands/CompleteCommand.js +658 -0
- package/dist/cli/commands/CompleteCommand.js.map +1 -0
- package/dist/cli/commands/DebugCommand.d.ts +7 -0
- package/dist/cli/commands/DebugCommand.js +55 -0
- package/dist/cli/commands/DebugCommand.js.map +1 -0
- package/dist/cli/commands/InfillCommand.d.ts +49 -0
- package/dist/cli/commands/InfillCommand.js +693 -0
- package/dist/cli/commands/InfillCommand.js.map +1 -0
- package/dist/cli/commands/InitCommand.d.ts +12 -0
- package/dist/cli/commands/InitCommand.js +230 -0
- package/dist/cli/commands/InitCommand.js.map +1 -0
- package/dist/cli/commands/OnPostInstallCommand.d.ts +4 -0
- package/dist/cli/commands/OnPostInstallCommand.js +62 -0
- package/dist/cli/commands/OnPostInstallCommand.js.map +1 -0
- package/dist/cli/commands/PullCommand.d.ts +13 -0
- package/dist/cli/commands/PullCommand.js +158 -0
- package/dist/cli/commands/PullCommand.js.map +1 -0
- package/dist/cli/commands/inspect/InspectCommand.d.ts +4 -0
- package/dist/cli/commands/inspect/InspectCommand.js +21 -0
- package/dist/cli/commands/inspect/InspectCommand.js.map +1 -0
- package/dist/cli/commands/inspect/commands/InspectEstimateCommand.d.ts +17 -0
- package/dist/cli/commands/inspect/commands/InspectEstimateCommand.js +275 -0
- package/dist/cli/commands/inspect/commands/InspectEstimateCommand.js.map +1 -0
- package/dist/cli/commands/inspect/commands/InspectGgufCommand.d.ts +13 -0
- package/dist/cli/commands/inspect/commands/InspectGgufCommand.js +230 -0
- package/dist/cli/commands/inspect/commands/InspectGgufCommand.js.map +1 -0
- package/dist/cli/commands/inspect/commands/InspectGpuCommand.d.ts +4 -0
- package/dist/cli/commands/inspect/commands/InspectGpuCommand.js +296 -0
- package/dist/cli/commands/inspect/commands/InspectGpuCommand.js.map +1 -0
- package/dist/cli/commands/inspect/commands/InspectMeasureCommand.d.ts +26 -0
- package/dist/cli/commands/inspect/commands/InspectMeasureCommand.js +869 -0
- package/dist/cli/commands/inspect/commands/InspectMeasureCommand.js.map +1 -0
- package/dist/cli/commands/source/SourceCommand.d.ts +4 -0
- package/dist/cli/commands/source/SourceCommand.js +19 -0
- package/dist/cli/commands/source/SourceCommand.js.map +1 -0
- package/dist/cli/commands/source/commands/BuildCommand.d.ts +16 -0
- package/dist/cli/commands/source/commands/BuildCommand.js +148 -0
- package/dist/cli/commands/source/commands/BuildCommand.js.map +1 -0
- package/dist/cli/commands/source/commands/ClearCommand.d.ts +7 -0
- package/dist/cli/commands/source/commands/ClearCommand.js +54 -0
- package/dist/cli/commands/source/commands/ClearCommand.js.map +1 -0
- package/dist/cli/commands/source/commands/DownloadCommand.d.ts +16 -0
- package/dist/cli/commands/source/commands/DownloadCommand.js +219 -0
- package/dist/cli/commands/source/commands/DownloadCommand.js.map +1 -0
- package/dist/cli/projectTemplates.d.ts +7 -0
- package/dist/cli/projectTemplates.js +10 -0
- package/dist/cli/projectTemplates.js.map +1 -0
- package/dist/cli/recommendedModels.d.ts +2 -0
- package/dist/cli/recommendedModels.js +428 -0
- package/dist/cli/recommendedModels.js.map +1 -0
- package/dist/cli/startCreateCli.d.ts +2 -0
- package/dist/cli/startCreateCli.js +26 -0
- package/dist/cli/startCreateCli.js.map +1 -0
- package/dist/cli/utils/ConsoleInteraction.d.ts +22 -0
- package/dist/cli/utils/ConsoleInteraction.js +122 -0
- package/dist/cli/utils/ConsoleInteraction.js.map +1 -0
- package/dist/cli/utils/ConsoleTable.d.ts +24 -0
- package/dist/cli/utils/ConsoleTable.js +90 -0
- package/dist/cli/utils/ConsoleTable.js.map +1 -0
- package/dist/cli/utils/basicChooseFromListConsoleInteraction.d.ts +13 -0
- package/dist/cli/utils/basicChooseFromListConsoleInteraction.js +111 -0
- package/dist/cli/utils/basicChooseFromListConsoleInteraction.js.map +1 -0
- package/dist/cli/utils/consolePromptQuestion.d.ts +6 -0
- package/dist/cli/utils/consolePromptQuestion.js +81 -0
- package/dist/cli/utils/consolePromptQuestion.js.map +1 -0
- package/dist/cli/utils/getReadablePath.d.ts +1 -0
- package/dist/cli/utils/getReadablePath.js +14 -0
- package/dist/cli/utils/getReadablePath.js.map +1 -0
- package/dist/cli/utils/interactivelyAskForModel.d.ts +13 -0
- package/dist/cli/utils/interactivelyAskForModel.js +485 -0
- package/dist/cli/utils/interactivelyAskForModel.js.map +1 -0
- package/dist/cli/utils/isRunningUnderRosetta.d.ts +1 -0
- package/dist/cli/utils/isRunningUnderRosetta.js +20 -0
- package/dist/cli/utils/isRunningUnderRosetta.js.map +1 -0
- package/dist/cli/utils/logUsedGpuTypeOption.d.ts +2 -0
- package/dist/cli/utils/logUsedGpuTypeOption.js +9 -0
- package/dist/cli/utils/logUsedGpuTypeOption.js.map +1 -0
- package/dist/cli/utils/packageJsonConfig.d.ts +6 -0
- package/dist/cli/utils/packageJsonConfig.js +51 -0
- package/dist/cli/utils/packageJsonConfig.js.map +1 -0
- package/dist/cli/utils/packageManager.d.ts +1 -0
- package/dist/cli/utils/packageManager.js +15 -0
- package/dist/cli/utils/packageManager.js.map +1 -0
- package/dist/cli/utils/parseXtcArg.d.ts +5 -0
- package/dist/cli/utils/parseXtcArg.js +16 -0
- package/dist/cli/utils/parseXtcArg.js.map +1 -0
- package/dist/cli/utils/printCommonInfoLines.d.ts +12 -0
- package/dist/cli/utils/printCommonInfoLines.js +163 -0
- package/dist/cli/utils/printCommonInfoLines.js.map +1 -0
- package/dist/cli/utils/printInfoLine.d.ts +12 -0
- package/dist/cli/utils/printInfoLine.js +54 -0
- package/dist/cli/utils/printInfoLine.js.map +1 -0
- package/dist/cli/utils/printModelDestination.d.ts +2 -0
- package/dist/cli/utils/printModelDestination.js +11 -0
- package/dist/cli/utils/printModelDestination.js.map +1 -0
- package/dist/cli/utils/projectTemplates.d.ts +19 -0
- package/dist/cli/utils/projectTemplates.js +47 -0
- package/dist/cli/utils/projectTemplates.js.map +1 -0
- package/dist/cli/utils/renderModelCompatibilityPercentageWithColors.d.ts +6 -0
- package/dist/cli/utils/renderModelCompatibilityPercentageWithColors.js +14 -0
- package/dist/cli/utils/renderModelCompatibilityPercentageWithColors.js.map +1 -0
- package/dist/cli/utils/resolveCommandGgufPath.d.ts +19 -0
- package/dist/cli/utils/resolveCommandGgufPath.js +123 -0
- package/dist/cli/utils/resolveCommandGgufPath.js.map +1 -0
- package/dist/cli/utils/resolveHeaderFlag.d.ts +1 -0
- package/dist/cli/utils/resolveHeaderFlag.js +21 -0
- package/dist/cli/utils/resolveHeaderFlag.js.map +1 -0
- package/dist/cli/utils/resolveModelRecommendationFileOptions.d.ts +14 -0
- package/dist/cli/utils/resolveModelRecommendationFileOptions.js +12 -0
- package/dist/cli/utils/resolveModelRecommendationFileOptions.js.map +1 -0
- package/dist/cli/utils/resolveNpmrcConfig.d.ts +18 -0
- package/dist/cli/utils/resolveNpmrcConfig.js +129 -0
- package/dist/cli/utils/resolveNpmrcConfig.js.map +1 -0
- package/dist/cli/utils/splitAnsiToLines.d.ts +1 -0
- package/dist/cli/utils/splitAnsiToLines.js +32 -0
- package/dist/cli/utils/splitAnsiToLines.js.map +1 -0
- package/dist/cli/utils/toBytes.d.ts +1 -0
- package/dist/cli/utils/toBytes.js +5 -0
- package/dist/cli/utils/toBytes.js.map +1 -0
- package/dist/cli/utils/withCliCommandDescriptionDocsUrl.d.ts +2 -0
- package/dist/cli/utils/withCliCommandDescriptionDocsUrl.js +23 -0
- package/dist/cli/utils/withCliCommandDescriptionDocsUrl.js.map +1 -0
- package/dist/commands.d.ts +6 -0
- package/dist/commands.js +9 -0
- package/dist/commands.js.map +1 -0
- package/dist/config.d.ts +79 -0
- package/dist/config.js +127 -0
- package/dist/config.js.map +1 -0
- package/dist/consts.d.ts +4 -0
- package/dist/consts.js +11 -0
- package/dist/consts.js.map +1 -0
- package/dist/evaluator/LlamaChat/LlamaChat.d.ts +500 -0
- package/dist/evaluator/LlamaChat/LlamaChat.js +2696 -0
- package/dist/evaluator/LlamaChat/LlamaChat.js.map +1 -0
- package/dist/evaluator/LlamaChat/utils/FunctionCallNameGrammar.d.ts +11 -0
- package/dist/evaluator/LlamaChat/utils/FunctionCallNameGrammar.js +55 -0
- package/dist/evaluator/LlamaChat/utils/FunctionCallNameGrammar.js.map +1 -0
- package/dist/evaluator/LlamaChat/utils/FunctionCallParamsGrammar.d.ts +16 -0
- package/dist/evaluator/LlamaChat/utils/FunctionCallParamsGrammar.js +45 -0
- package/dist/evaluator/LlamaChat/utils/FunctionCallParamsGrammar.js.map +1 -0
- package/dist/evaluator/LlamaChat/utils/LlamaFunctionCallValidationError.d.ts +8 -0
- package/dist/evaluator/LlamaChat/utils/LlamaFunctionCallValidationError.js +12 -0
- package/dist/evaluator/LlamaChat/utils/LlamaFunctionCallValidationError.js.map +1 -0
- package/dist/evaluator/LlamaChat/utils/contextShiftStrategies/eraseFirstResponseAndKeepFirstSystemChatContextShiftStrategy.d.ts +16 -0
- package/dist/evaluator/LlamaChat/utils/contextShiftStrategies/eraseFirstResponseAndKeepFirstSystemChatContextShiftStrategy.js +260 -0
- package/dist/evaluator/LlamaChat/utils/contextShiftStrategies/eraseFirstResponseAndKeepFirstSystemChatContextShiftStrategy.js.map +1 -0
- package/dist/evaluator/LlamaChatSession/LlamaChatSession.d.ts +520 -0
- package/dist/evaluator/LlamaChatSession/LlamaChatSession.js +628 -0
- package/dist/evaluator/LlamaChatSession/LlamaChatSession.js.map +1 -0
- package/dist/evaluator/LlamaChatSession/utils/LlamaChatSessionPromptCompletionEngine.d.ts +45 -0
- package/dist/evaluator/LlamaChatSession/utils/LlamaChatSessionPromptCompletionEngine.js +191 -0
- package/dist/evaluator/LlamaChatSession/utils/LlamaChatSessionPromptCompletionEngine.js.map +1 -0
- package/dist/evaluator/LlamaChatSession/utils/defineChatSessionFunction.d.ts +15 -0
- package/dist/evaluator/LlamaChatSession/utils/defineChatSessionFunction.js +16 -0
- package/dist/evaluator/LlamaChatSession/utils/defineChatSessionFunction.js.map +1 -0
- package/dist/evaluator/LlamaCompletion.d.ts +219 -0
- package/dist/evaluator/LlamaCompletion.js +498 -0
- package/dist/evaluator/LlamaCompletion.js.map +1 -0
- package/dist/evaluator/LlamaContext/LlamaContext.d.ts +336 -0
- package/dist/evaluator/LlamaContext/LlamaContext.js +1919 -0
- package/dist/evaluator/LlamaContext/LlamaContext.js.map +1 -0
- package/dist/evaluator/LlamaContext/LlamaContextSequenceCheckpoints.d.ts +27 -0
- package/dist/evaluator/LlamaContext/LlamaContextSequenceCheckpoints.js +130 -0
- package/dist/evaluator/LlamaContext/LlamaContextSequenceCheckpoints.js.map +1 -0
- package/dist/evaluator/LlamaContext/LlamaSampler.d.ts +1 -0
- package/dist/evaluator/LlamaContext/LlamaSampler.js +39 -0
- package/dist/evaluator/LlamaContext/LlamaSampler.js.map +1 -0
- package/dist/evaluator/LlamaContext/TokenPredictor.d.ts +55 -0
- package/dist/evaluator/LlamaContext/TokenPredictor.js +20 -0
- package/dist/evaluator/LlamaContext/TokenPredictor.js.map +1 -0
- package/dist/evaluator/LlamaContext/tokenPredictors/DraftSequenceTokenPredictor.d.ts +56 -0
- package/dist/evaluator/LlamaContext/tokenPredictors/DraftSequenceTokenPredictor.js +266 -0
- package/dist/evaluator/LlamaContext/tokenPredictors/DraftSequenceTokenPredictor.js.map +1 -0
- package/dist/evaluator/LlamaContext/tokenPredictors/InputLookupTokenPredictor.d.ts +58 -0
- package/dist/evaluator/LlamaContext/tokenPredictors/InputLookupTokenPredictor.js +138 -0
- package/dist/evaluator/LlamaContext/tokenPredictors/InputLookupTokenPredictor.js.map +1 -0
- package/dist/evaluator/LlamaContext/types.d.ts +602 -0
- package/dist/evaluator/LlamaContext/types.js +2 -0
- package/dist/evaluator/LlamaContext/types.js.map +1 -0
- package/dist/evaluator/LlamaContext/utils/batchItemsPrioritizationStrategies/firstInFirstOutStrategy.d.ts +5 -0
- package/dist/evaluator/LlamaContext/utils/batchItemsPrioritizationStrategies/firstInFirstOutStrategy.js +16 -0
- package/dist/evaluator/LlamaContext/utils/batchItemsPrioritizationStrategies/firstInFirstOutStrategy.js.map +1 -0
- package/dist/evaluator/LlamaContext/utils/batchItemsPrioritizationStrategies/maximumParallelismStrategy.d.ts +5 -0
- package/dist/evaluator/LlamaContext/utils/batchItemsPrioritizationStrategies/maximumParallelismStrategy.js +42 -0
- package/dist/evaluator/LlamaContext/utils/batchItemsPrioritizationStrategies/maximumParallelismStrategy.js.map +1 -0
- package/dist/evaluator/LlamaContext/utils/padSafeContextSize.d.ts +1 -0
- package/dist/evaluator/LlamaContext/utils/padSafeContextSize.js +18 -0
- package/dist/evaluator/LlamaContext/utils/padSafeContextSize.js.map +1 -0
- package/dist/evaluator/LlamaContext/utils/resolveBatchItemsPrioritizationStrategy.d.ts +2 -0
- package/dist/evaluator/LlamaContext/utils/resolveBatchItemsPrioritizationStrategy.js +13 -0
- package/dist/evaluator/LlamaContext/utils/resolveBatchItemsPrioritizationStrategy.js.map +1 -0
- package/dist/evaluator/LlamaEmbedding.d.ts +21 -0
- package/dist/evaluator/LlamaEmbedding.js +53 -0
- package/dist/evaluator/LlamaEmbedding.js.map +1 -0
- package/dist/evaluator/LlamaEmbeddingContext.d.ts +52 -0
- package/dist/evaluator/LlamaEmbeddingContext.js +86 -0
- package/dist/evaluator/LlamaEmbeddingContext.js.map +1 -0
- package/dist/evaluator/LlamaGrammar.d.ts +39 -0
- package/dist/evaluator/LlamaGrammar.js +72 -0
- package/dist/evaluator/LlamaGrammar.js.map +1 -0
- package/dist/evaluator/LlamaGrammarEvaluationState.d.ts +19 -0
- package/dist/evaluator/LlamaGrammarEvaluationState.js +29 -0
- package/dist/evaluator/LlamaGrammarEvaluationState.js.map +1 -0
- package/dist/evaluator/LlamaJsonSchemaGrammar.d.ts +17 -0
- package/dist/evaluator/LlamaJsonSchemaGrammar.js +35 -0
- package/dist/evaluator/LlamaJsonSchemaGrammar.js.map +1 -0
- package/dist/evaluator/LlamaModel/LlamaModel.d.ts +344 -0
- package/dist/evaluator/LlamaModel/LlamaModel.js +853 -0
- package/dist/evaluator/LlamaModel/LlamaModel.js.map +1 -0
- package/dist/evaluator/LlamaModel/utils/TokenAttributes.d.ts +29 -0
- package/dist/evaluator/LlamaModel/utils/TokenAttributes.js +65 -0
- package/dist/evaluator/LlamaModel/utils/TokenAttributes.js.map +1 -0
- package/dist/evaluator/LlamaRankingContext.d.ts +91 -0
- package/dist/evaluator/LlamaRankingContext.js +178 -0
- package/dist/evaluator/LlamaRankingContext.js.map +1 -0
- package/dist/evaluator/TokenBias.d.ts +37 -0
- package/dist/evaluator/TokenBias.js +68 -0
- package/dist/evaluator/TokenBias.js.map +1 -0
- package/dist/evaluator/TokenMeter.d.ts +45 -0
- package/dist/evaluator/TokenMeter.js +74 -0
- package/dist/evaluator/TokenMeter.js.map +1 -0
- package/dist/evaluator/utils/chunkDocument.d.ts +86 -0
- package/dist/evaluator/utils/chunkDocument.js +212 -0
- package/dist/evaluator/utils/chunkDocument.js.map +1 -0
- package/dist/gguf/consts.d.ts +4 -0
- package/dist/gguf/consts.js +12 -0
- package/dist/gguf/consts.js.map +1 -0
- package/dist/gguf/errors/InvalidGgufMagicError.d.ts +3 -0
- package/dist/gguf/errors/InvalidGgufMagicError.js +6 -0
- package/dist/gguf/errors/InvalidGgufMagicError.js.map +1 -0
- package/dist/gguf/errors/UnsupportedGgufValueTypeError.d.ts +4 -0
- package/dist/gguf/errors/UnsupportedGgufValueTypeError.js +9 -0
- package/dist/gguf/errors/UnsupportedGgufValueTypeError.js.map +1 -0
- package/dist/gguf/fileReaders/GgufFileReader.d.ts +36 -0
- package/dist/gguf/fileReaders/GgufFileReader.js +106 -0
- package/dist/gguf/fileReaders/GgufFileReader.js.map +1 -0
- package/dist/gguf/fileReaders/GgufFsFileReader.d.ts +16 -0
- package/dist/gguf/fileReaders/GgufFsFileReader.js +62 -0
- package/dist/gguf/fileReaders/GgufFsFileReader.js.map +1 -0
- package/dist/gguf/fileReaders/GgufNetworkFetchFileReader.d.ts +28 -0
- package/dist/gguf/fileReaders/GgufNetworkFetchFileReader.js +94 -0
- package/dist/gguf/fileReaders/GgufNetworkFetchFileReader.js.map +1 -0
- package/dist/gguf/insights/GgufInsights.d.ts +78 -0
- package/dist/gguf/insights/GgufInsights.js +854 -0
- package/dist/gguf/insights/GgufInsights.js.map +1 -0
- package/dist/gguf/insights/GgufInsightsConfigurationResolver.d.ts +203 -0
- package/dist/gguf/insights/GgufInsightsConfigurationResolver.js +284 -0
- package/dist/gguf/insights/GgufInsightsConfigurationResolver.js.map +1 -0
- package/dist/gguf/insights/GgufInsightsTokens.d.ts +5 -0
- package/dist/gguf/insights/GgufInsightsTokens.js +40 -0
- package/dist/gguf/insights/GgufInsightsTokens.js.map +1 -0
- package/dist/gguf/insights/utils/getRamUsageFromUnifiedVram.d.ts +5 -0
- package/dist/gguf/insights/utils/getRamUsageFromUnifiedVram.js +7 -0
- package/dist/gguf/insights/utils/getRamUsageFromUnifiedVram.js.map +1 -0
- package/dist/gguf/insights/utils/resolveContextContextSizeOption.d.ts +33 -0
- package/dist/gguf/insights/utils/resolveContextContextSizeOption.js +117 -0
- package/dist/gguf/insights/utils/resolveContextContextSizeOption.js.map +1 -0
- package/dist/gguf/insights/utils/resolveModelGpuLayersOption.d.ts +20 -0
- package/dist/gguf/insights/utils/resolveModelGpuLayersOption.js +251 -0
- package/dist/gguf/insights/utils/resolveModelGpuLayersOption.js.map +1 -0
- package/dist/gguf/insights/utils/scoreLevels.d.ts +5 -0
- package/dist/gguf/insights/utils/scoreLevels.js +16 -0
- package/dist/gguf/insights/utils/scoreLevels.js.map +1 -0
- package/dist/gguf/parser/GgufV2Parser.d.ts +20 -0
- package/dist/gguf/parser/GgufV2Parser.js +184 -0
- package/dist/gguf/parser/GgufV2Parser.js.map +1 -0
- package/dist/gguf/parser/GgufV3Parser.d.ts +3 -0
- package/dist/gguf/parser/GgufV3Parser.js +4 -0
- package/dist/gguf/parser/GgufV3Parser.js.map +1 -0
- package/dist/gguf/parser/parseGguf.d.ts +8 -0
- package/dist/gguf/parser/parseGguf.js +61 -0
- package/dist/gguf/parser/parseGguf.js.map +1 -0
- package/dist/gguf/readGgufFileInfo.d.ts +54 -0
- package/dist/gguf/readGgufFileInfo.js +82 -0
- package/dist/gguf/readGgufFileInfo.js.map +1 -0
- package/dist/gguf/types/GgufFileInfoTypes.d.ts +85 -0
- package/dist/gguf/types/GgufFileInfoTypes.js +18 -0
- package/dist/gguf/types/GgufFileInfoTypes.js.map +1 -0
- package/dist/gguf/types/GgufMetadataTypes.d.ts +480 -0
- package/dist/gguf/types/GgufMetadataTypes.js +194 -0
- package/dist/gguf/types/GgufMetadataTypes.js.map +1 -0
- package/dist/gguf/types/GgufTensorInfoTypes.d.ts +63 -0
- package/dist/gguf/types/GgufTensorInfoTypes.js +54 -0
- package/dist/gguf/types/GgufTensorInfoTypes.js.map +1 -0
- package/dist/gguf/utils/GgufReadOffset.d.ts +6 -0
- package/dist/gguf/utils/GgufReadOffset.js +18 -0
- package/dist/gguf/utils/GgufReadOffset.js.map +1 -0
- package/dist/gguf/utils/convertMetadataKeyValueRecordToNestedObject.d.ts +6 -0
- package/dist/gguf/utils/convertMetadataKeyValueRecordToNestedObject.js +76 -0
- package/dist/gguf/utils/convertMetadataKeyValueRecordToNestedObject.js.map +1 -0
- package/dist/gguf/utils/getGgufFileTypeName.d.ts +4 -0
- package/dist/gguf/utils/getGgufFileTypeName.js +13 -0
- package/dist/gguf/utils/getGgufFileTypeName.js.map +1 -0
- package/dist/gguf/utils/getGgufMetadataArchitectureData.d.ts +3 -0
- package/dist/gguf/utils/getGgufMetadataArchitectureData.js +4 -0
- package/dist/gguf/utils/getGgufMetadataArchitectureData.js.map +1 -0
- package/dist/gguf/utils/getGgufMetadataKeyValue.d.ts +1 -0
- package/dist/gguf/utils/getGgufMetadataKeyValue.js +27 -0
- package/dist/gguf/utils/getGgufMetadataKeyValue.js.map +1 -0
- package/dist/gguf/utils/ggufQuantNames.d.ts +2 -0
- package/dist/gguf/utils/ggufQuantNames.js +42 -0
- package/dist/gguf/utils/ggufQuantNames.js.map +1 -0
- package/dist/gguf/utils/normalizeGgufDownloadUrl.d.ts +2 -0
- package/dist/gguf/utils/normalizeGgufDownloadUrl.js +18 -0
- package/dist/gguf/utils/normalizeGgufDownloadUrl.js.map +1 -0
- package/dist/gguf/utils/resolveBinarySplitGgufPartUrls.d.ts +2 -0
- package/dist/gguf/utils/resolveBinarySplitGgufPartUrls.js +38 -0
- package/dist/gguf/utils/resolveBinarySplitGgufPartUrls.js.map +1 -0
- package/dist/gguf/utils/resolveSplitGgufParts.d.ts +7 -0
- package/dist/gguf/utils/resolveSplitGgufParts.js +64 -0
- package/dist/gguf/utils/resolveSplitGgufParts.js.map +1 -0
- package/dist/index.d.ts +71 -0
- package/dist/index.js +64 -0
- package/dist/index.js.map +1 -0
- package/dist/state.d.ts +6 -0
- package/dist/state.js +22 -0
- package/dist/state.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types.d.ts +408 -0
- package/dist/types.js +13 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/DisposeGuard.d.ts +13 -0
- package/dist/utils/DisposeGuard.js +120 -0
- package/dist/utils/DisposeGuard.js.map +1 -0
- package/dist/utils/InsufficientMemoryError.d.ts +3 -0
- package/dist/utils/InsufficientMemoryError.js +6 -0
- package/dist/utils/InsufficientMemoryError.js.map +1 -0
- package/dist/utils/LlamaText.d.ts +92 -0
- package/dist/utils/LlamaText.js +527 -0
- package/dist/utils/LlamaText.js.map +1 -0
- package/dist/utils/LruCache.d.ts +12 -0
- package/dist/utils/LruCache.js +44 -0
- package/dist/utils/LruCache.js.map +1 -0
- package/dist/utils/OpenAIFormat.d.ts +177 -0
- package/dist/utils/OpenAIFormat.js +488 -0
- package/dist/utils/OpenAIFormat.js.map +1 -0
- package/dist/utils/OverridesObject.d.ts +7 -0
- package/dist/utils/OverridesObject.js +2 -0
- package/dist/utils/OverridesObject.js.map +1 -0
- package/dist/utils/ReplHistory.d.ts +9 -0
- package/dist/utils/ReplHistory.js +72 -0
- package/dist/utils/ReplHistory.js.map +1 -0
- package/dist/utils/StopGenerationDetector.d.ts +47 -0
- package/dist/utils/StopGenerationDetector.js +291 -0
- package/dist/utils/StopGenerationDetector.js.map +1 -0
- package/dist/utils/ThreadsSplitter.d.ts +32 -0
- package/dist/utils/ThreadsSplitter.js +177 -0
- package/dist/utils/ThreadsSplitter.js.map +1 -0
- package/dist/utils/TokenStreamRegulator.d.ts +38 -0
- package/dist/utils/TokenStreamRegulator.js +200 -0
- package/dist/utils/TokenStreamRegulator.js.map +1 -0
- package/dist/utils/UnsupportedError.d.ts +2 -0
- package/dist/utils/UnsupportedError.js +7 -0
- package/dist/utils/UnsupportedError.js.map +1 -0
- package/dist/utils/appendUserMessageToChatHistory.d.ts +6 -0
- package/dist/utils/appendUserMessageToChatHistory.js +22 -0
- package/dist/utils/appendUserMessageToChatHistory.js.map +1 -0
- package/dist/utils/clearTempFolder.d.ts +1 -0
- package/dist/utils/clearTempFolder.js +16 -0
- package/dist/utils/clearTempFolder.js.map +1 -0
- package/dist/utils/cmake.d.ts +10 -0
- package/dist/utils/cmake.js +146 -0
- package/dist/utils/cmake.js.map +1 -0
- package/dist/utils/compareTokens.d.ts +2 -0
- package/dist/utils/compareTokens.js +4 -0
- package/dist/utils/compareTokens.js.map +1 -0
- package/dist/utils/createModelDownloader.d.ts +262 -0
- package/dist/utils/createModelDownloader.js +486 -0
- package/dist/utils/createModelDownloader.js.map +1 -0
- package/dist/utils/findBestOption.d.ts +4 -0
- package/dist/utils/findBestOption.js +15 -0
- package/dist/utils/findBestOption.js.map +1 -0
- package/dist/utils/findCharacterRemovalCountToFitChatHistoryInContext.d.ts +20 -0
- package/dist/utils/findCharacterRemovalCountToFitChatHistoryInContext.js +85 -0
- package/dist/utils/findCharacterRemovalCountToFitChatHistoryInContext.js.map +1 -0
- package/dist/utils/gbnfJson/GbnfGrammarGenerator.d.ts +19 -0
- package/dist/utils/gbnfJson/GbnfGrammarGenerator.js +60 -0
- package/dist/utils/gbnfJson/GbnfGrammarGenerator.js.map +1 -0
- package/dist/utils/gbnfJson/GbnfTerminal.d.ts +11 -0
- package/dist/utils/gbnfJson/GbnfTerminal.js +54 -0
- package/dist/utils/gbnfJson/GbnfTerminal.js.map +1 -0
- package/dist/utils/gbnfJson/getGbnfGrammarForGbnfJsonSchema.d.ts +5 -0
- package/dist/utils/gbnfJson/getGbnfGrammarForGbnfJsonSchema.js +11 -0
- package/dist/utils/gbnfJson/getGbnfGrammarForGbnfJsonSchema.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfAnyJson.d.ts +9 -0
- package/dist/utils/gbnfJson/terminals/GbnfAnyJson.js +53 -0
- package/dist/utils/gbnfJson/terminals/GbnfAnyJson.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfArray.d.ts +18 -0
- package/dist/utils/gbnfJson/terminals/GbnfArray.js +83 -0
- package/dist/utils/gbnfJson/terminals/GbnfArray.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfBoolean.d.ts +7 -0
- package/dist/utils/gbnfJson/terminals/GbnfBoolean.js +22 -0
- package/dist/utils/gbnfJson/terminals/GbnfBoolean.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfBooleanValue.d.ts +7 -0
- package/dist/utils/gbnfJson/terminals/GbnfBooleanValue.js +17 -0
- package/dist/utils/gbnfJson/terminals/GbnfBooleanValue.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfCommaWhitespace.d.ts +11 -0
- package/dist/utils/gbnfJson/terminals/GbnfCommaWhitespace.js +28 -0
- package/dist/utils/gbnfJson/terminals/GbnfCommaWhitespace.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfFormatString.d.ts +11 -0
- package/dist/utils/gbnfJson/terminals/GbnfFormatString.js +90 -0
- package/dist/utils/gbnfJson/terminals/GbnfFormatString.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfGrammar.d.ts +9 -0
- package/dist/utils/gbnfJson/terminals/GbnfGrammar.js +23 -0
- package/dist/utils/gbnfJson/terminals/GbnfGrammar.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfInsideStringChar.d.ts +5 -0
- package/dist/utils/gbnfJson/terminals/GbnfInsideStringChar.js +24 -0
- package/dist/utils/gbnfJson/terminals/GbnfInsideStringChar.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfNull.d.ts +5 -0
- package/dist/utils/gbnfJson/terminals/GbnfNull.js +11 -0
- package/dist/utils/gbnfJson/terminals/GbnfNull.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfNumber.d.ts +9 -0
- package/dist/utils/gbnfJson/terminals/GbnfNumber.js +22 -0
- package/dist/utils/gbnfJson/terminals/GbnfNumber.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfNumberValue.d.ts +9 -0
- package/dist/utils/gbnfJson/terminals/GbnfNumberValue.js +21 -0
- package/dist/utils/gbnfJson/terminals/GbnfNumberValue.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfObjectMap.d.ts +28 -0
- package/dist/utils/gbnfJson/terminals/GbnfObjectMap.js +88 -0
- package/dist/utils/gbnfJson/terminals/GbnfObjectMap.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfOr.d.ts +9 -0
- package/dist/utils/gbnfJson/terminals/GbnfOr.js +34 -0
- package/dist/utils/gbnfJson/terminals/GbnfOr.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfRef.d.ts +15 -0
- package/dist/utils/gbnfJson/terminals/GbnfRef.js +34 -0
- package/dist/utils/gbnfJson/terminals/GbnfRef.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfRepetition.d.ts +15 -0
- package/dist/utils/gbnfJson/terminals/GbnfRepetition.js +86 -0
- package/dist/utils/gbnfJson/terminals/GbnfRepetition.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfString.d.ts +12 -0
- package/dist/utils/gbnfJson/terminals/GbnfString.js +43 -0
- package/dist/utils/gbnfJson/terminals/GbnfString.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfStringValue.d.ts +8 -0
- package/dist/utils/gbnfJson/terminals/GbnfStringValue.js +26 -0
- package/dist/utils/gbnfJson/terminals/GbnfStringValue.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfVerbatimText.d.ts +6 -0
- package/dist/utils/gbnfJson/terminals/GbnfVerbatimText.js +21 -0
- package/dist/utils/gbnfJson/terminals/GbnfVerbatimText.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/GbnfWhitespace.d.ts +13 -0
- package/dist/utils/gbnfJson/terminals/GbnfWhitespace.js +67 -0
- package/dist/utils/gbnfJson/terminals/GbnfWhitespace.js.map +1 -0
- package/dist/utils/gbnfJson/terminals/gbnfConsts.d.ts +30 -0
- package/dist/utils/gbnfJson/terminals/gbnfConsts.js +72 -0
- package/dist/utils/gbnfJson/terminals/gbnfConsts.js.map +1 -0
- package/dist/utils/gbnfJson/types.d.ts +213 -0
- package/dist/utils/gbnfJson/types.js +30 -0
- package/dist/utils/gbnfJson/types.js.map +1 -0
- package/dist/utils/gbnfJson/utils/GbnfJsonScopeState.d.ts +10 -0
- package/dist/utils/gbnfJson/utils/GbnfJsonScopeState.js +15 -0
- package/dist/utils/gbnfJson/utils/GbnfJsonScopeState.js.map +1 -0
- package/dist/utils/gbnfJson/utils/defsScope.d.ts +7 -0
- package/dist/utils/gbnfJson/utils/defsScope.js +17 -0
- package/dist/utils/gbnfJson/utils/defsScope.js.map +1 -0
- package/dist/utils/gbnfJson/utils/getGbnfJsonTerminalForGbnfJsonSchema.d.ts +5 -0
- package/dist/utils/gbnfJson/utils/getGbnfJsonTerminalForGbnfJsonSchema.js +143 -0
- package/dist/utils/gbnfJson/utils/getGbnfJsonTerminalForGbnfJsonSchema.js.map +1 -0
- package/dist/utils/gbnfJson/utils/getGbnfJsonTerminalForLiteral.d.ts +5 -0
- package/dist/utils/gbnfJson/utils/getGbnfJsonTerminalForLiteral.js +16 -0
- package/dist/utils/gbnfJson/utils/getGbnfJsonTerminalForLiteral.js.map +1 -0
- package/dist/utils/gbnfJson/utils/validateObjectAgainstGbnfSchema.d.ts +8 -0
- package/dist/utils/gbnfJson/utils/validateObjectAgainstGbnfSchema.js +242 -0
- package/dist/utils/gbnfJson/utils/validateObjectAgainstGbnfSchema.js.map +1 -0
- package/dist/utils/getBuildDefaults.d.ts +5 -0
- package/dist/utils/getBuildDefaults.js +9 -0
- package/dist/utils/getBuildDefaults.js.map +1 -0
- package/dist/utils/getChatWrapperSegmentDefinition.d.ts +2 -0
- package/dist/utils/getChatWrapperSegmentDefinition.js +9 -0
- package/dist/utils/getChatWrapperSegmentDefinition.js.map +1 -0
- package/dist/utils/getConsoleLogPrefix.d.ts +1 -0
- package/dist/utils/getConsoleLogPrefix.js +10 -0
- package/dist/utils/getConsoleLogPrefix.js.map +1 -0
- package/dist/utils/getFirstWritableDir.d.ts +8 -0
- package/dist/utils/getFirstWritableDir.js +60 -0
- package/dist/utils/getFirstWritableDir.js.map +1 -0
- package/dist/utils/getGrammarsFolder.d.ts +2 -0
- package/dist/utils/getGrammarsFolder.js +19 -0
- package/dist/utils/getGrammarsFolder.js.map +1 -0
- package/dist/utils/getLlamaClasses.d.ts +9 -0
- package/dist/utils/getLlamaClasses.js +14 -0
- package/dist/utils/getLlamaClasses.js.map +1 -0
- package/dist/utils/getModuleVersion.d.ts +1 -0
- package/dist/utils/getModuleVersion.js +13 -0
- package/dist/utils/getModuleVersion.js.map +1 -0
- package/dist/utils/getQueuedTokensBeforeStopTrigger.d.ts +6 -0
- package/dist/utils/getQueuedTokensBeforeStopTrigger.js +22 -0
- package/dist/utils/getQueuedTokensBeforeStopTrigger.js.map +1 -0
- package/dist/utils/getReadableContextSize.d.ts +1 -0
- package/dist/utils/getReadableContextSize.js +7 -0
- package/dist/utils/getReadableContextSize.js.map +1 -0
- package/dist/utils/getTempDir.d.ts +10 -0
- package/dist/utils/getTempDir.js +121 -0
- package/dist/utils/getTempDir.js.map +1 -0
- package/dist/utils/getTypeScriptTypeStringForGbnfJsonSchema.d.ts +2 -0
- package/dist/utils/getTypeScriptTypeStringForGbnfJsonSchema.js +205 -0
- package/dist/utils/getTypeScriptTypeStringForGbnfJsonSchema.js.map +1 -0
- package/dist/utils/gitReleaseBundles.d.ts +2 -0
- package/dist/utils/gitReleaseBundles.js +132 -0
- package/dist/utils/gitReleaseBundles.js.map +1 -0
- package/dist/utils/hashString.d.ts +1 -0
- package/dist/utils/hashString.js +8 -0
- package/dist/utils/hashString.js.map +1 -0
- package/dist/utils/includesText.d.ts +1 -0
- package/dist/utils/includesText.js +12 -0
- package/dist/utils/includesText.js.map +1 -0
- package/dist/utils/isLockfileActive.d.ts +4 -0
- package/dist/utils/isLockfileActive.js +12 -0
- package/dist/utils/isLockfileActive.js.map +1 -0
- package/dist/utils/isToken.d.ts +2 -0
- package/dist/utils/isToken.js +4 -0
- package/dist/utils/isToken.js.map +1 -0
- package/dist/utils/isUrl.d.ts +1 -0
- package/dist/utils/isUrl.js +15 -0
- package/dist/utils/isUrl.js.map +1 -0
- package/dist/utils/mergeUnionTypes.d.ts +10 -0
- package/dist/utils/mergeUnionTypes.js +2 -0
- package/dist/utils/mergeUnionTypes.js.map +1 -0
- package/dist/utils/modelDownloadEndpoints.d.ts +13 -0
- package/dist/utils/modelDownloadEndpoints.js +27 -0
- package/dist/utils/modelDownloadEndpoints.js.map +1 -0
- package/dist/utils/modelFileAccessTokens.d.ts +5 -0
- package/dist/utils/modelFileAccessTokens.js +41 -0
- package/dist/utils/modelFileAccessTokens.js.map +1 -0
- package/dist/utils/optionsMatrix.d.ts +58 -0
- package/dist/utils/optionsMatrix.js +97 -0
- package/dist/utils/optionsMatrix.js.map +1 -0
- package/dist/utils/parseModelFileName.d.ts +15 -0
- package/dist/utils/parseModelFileName.js +132 -0
- package/dist/utils/parseModelFileName.js.map +1 -0
- package/dist/utils/parseModelUri.d.ts +40 -0
- package/dist/utils/parseModelUri.js +346 -0
- package/dist/utils/parseModelUri.js.map +1 -0
- package/dist/utils/parseTextTemplate.d.ts +66 -0
- package/dist/utils/parseTextTemplate.js +116 -0
- package/dist/utils/parseTextTemplate.js.map +1 -0
- package/dist/utils/prettyPrintObject.d.ts +10 -0
- package/dist/utils/prettyPrintObject.js +84 -0
- package/dist/utils/prettyPrintObject.js.map +1 -0
- package/dist/utils/pushAll.d.ts +6 -0
- package/dist/utils/pushAll.js +11 -0
- package/dist/utils/pushAll.js.map +1 -0
- package/dist/utils/removeNullFields.d.ts +2 -0
- package/dist/utils/removeNullFields.js +17 -0
- package/dist/utils/removeNullFields.js.map +1 -0
- package/dist/utils/resolveGithubRelease.d.ts +2 -0
- package/dist/utils/resolveGithubRelease.js +77 -0
- package/dist/utils/resolveGithubRelease.js.map +1 -0
- package/dist/utils/resolveLastTokens.d.ts +2 -0
- package/dist/utils/resolveLastTokens.js +12 -0
- package/dist/utils/resolveLastTokens.js.map +1 -0
- package/dist/utils/resolveModelDestination.d.ts +16 -0
- package/dist/utils/resolveModelDestination.js +54 -0
- package/dist/utils/resolveModelDestination.js.map +1 -0
- package/dist/utils/resolveModelFile.d.ts +142 -0
- package/dist/utils/resolveModelFile.js +201 -0
- package/dist/utils/resolveModelFile.js.map +1 -0
- package/dist/utils/runtime.d.ts +4 -0
- package/dist/utils/runtime.js +8 -0
- package/dist/utils/runtime.js.map +1 -0
- package/dist/utils/safeEventCallback.d.ts +6 -0
- package/dist/utils/safeEventCallback.js +29 -0
- package/dist/utils/safeEventCallback.js.map +1 -0
- package/dist/utils/signalSleep.d.ts +1 -0
- package/dist/utils/signalSleep.js +20 -0
- package/dist/utils/signalSleep.js.map +1 -0
- package/dist/utils/spawnCommand.d.ts +11 -0
- package/dist/utils/spawnCommand.js +89 -0
- package/dist/utils/spawnCommand.js.map +1 -0
- package/dist/utils/tokenizeInput.d.ts +3 -0
- package/dist/utils/tokenizeInput.js +14 -0
- package/dist/utils/tokenizeInput.js.map +1 -0
- package/dist/utils/tokenizerUtils.d.ts +12 -0
- package/dist/utils/tokenizerUtils.js +32 -0
- package/dist/utils/tokenizerUtils.js.map +1 -0
- package/dist/utils/transformPromisable.d.ts +54 -0
- package/dist/utils/transformPromisable.js +95 -0
- package/dist/utils/transformPromisable.js.map +1 -0
- package/dist/utils/truncateTextAndRoundToWords.d.ts +11 -0
- package/dist/utils/truncateTextAndRoundToWords.js +110 -0
- package/dist/utils/truncateTextAndRoundToWords.js.map +1 -0
- package/dist/utils/utilTypes.d.ts +18 -0
- package/dist/utils/utilTypes.js +2 -0
- package/dist/utils/utilTypes.js.map +1 -0
- package/dist/utils/waitForLockfileRelease.d.ts +5 -0
- package/dist/utils/waitForLockfileRelease.js +19 -0
- package/dist/utils/waitForLockfileRelease.js.map +1 -0
- package/dist/utils/withLockfile.d.ts +7 -0
- package/dist/utils/withLockfile.js +44 -0
- package/dist/utils/withLockfile.js.map +1 -0
- package/dist/utils/withOra.d.ts +7 -0
- package/dist/utils/withOra.js +37 -0
- package/dist/utils/withOra.js.map +1 -0
- package/dist/utils/withProgressLog.d.ts +22 -0
- package/dist/utils/withProgressLog.js +211 -0
- package/dist/utils/withProgressLog.js.map +1 -0
- package/dist/utils/withStatusLogs.d.ts +6 -0
- package/dist/utils/withStatusLogs.js +25 -0
- package/dist/utils/withStatusLogs.js.map +1 -0
- package/dist/utils/wrapAbortSignal.d.ts +1 -0
- package/dist/utils/wrapAbortSignal.js +14 -0
- package/dist/utils/wrapAbortSignal.js.map +1 -0
- package/llama/.clang-format +46 -0
- package/llama/CMakeLists.txt +141 -0
- package/llama/addon/AddonContext.cpp +1181 -0
- package/llama/addon/AddonContext.h +85 -0
- package/llama/addon/AddonGrammar.cpp +92 -0
- package/llama/addon/AddonGrammar.h +22 -0
- package/llama/addon/AddonGrammarEvaluationState.cpp +36 -0
- package/llama/addon/AddonGrammarEvaluationState.h +17 -0
- package/llama/addon/AddonModel.cpp +691 -0
- package/llama/addon/AddonModel.h +64 -0
- package/llama/addon/AddonModelData.cpp +25 -0
- package/llama/addon/AddonModelData.h +15 -0
- package/llama/addon/AddonModelLora.cpp +103 -0
- package/llama/addon/AddonModelLora.h +28 -0
- package/llama/addon/AddonSampler.cpp +669 -0
- package/llama/addon/AddonSampler.h +75 -0
- package/llama/addon/RingBuffer.h +109 -0
- package/llama/addon/addon.cpp +330 -0
- package/llama/addon/addonGlobals.cpp +22 -0
- package/llama/addon/addonGlobals.h +12 -0
- package/llama/addon/globals/addonLog.cpp +143 -0
- package/llama/addon/globals/addonLog.h +24 -0
- package/llama/addon/globals/addonProgress.cpp +15 -0
- package/llama/addon/globals/addonProgress.h +15 -0
- package/llama/addon/globals/getGpuInfo.cpp +146 -0
- package/llama/addon/globals/getGpuInfo.h +11 -0
- package/llama/addon/globals/getMemoryInfo.cpp +63 -0
- package/llama/addon/globals/getMemoryInfo.h +4 -0
- package/llama/addon/globals/getSwapInfo.cpp +69 -0
- package/llama/addon/globals/getSwapInfo.h +4 -0
- package/llama/binariesGithubRelease.json +3 -0
- package/llama/cmake/addVariantSuffix.cmake +21 -0
- package/llama/cmake/win32.ensureNinjaPath.cmake +68 -0
- package/llama/cmake/win32.ensureNodeLib.cmake +34 -0
- package/llama/cmake/win32.llvmApplyGnuModeAdaptations.cmake +12 -0
- package/llama/cmake/win32.llvmEnsureCmakeAr.cmake +37 -0
- package/llama/cmake/win32.llvmUseGnuModeCompilers.cmake +87 -0
- package/llama/cmake/win32.programFilesPaths.cmake +35 -0
- package/llama/gpuInfo/vulkan-gpu-info.cpp +207 -0
- package/llama/gpuInfo/vulkan-gpu-info.h +9 -0
- package/llama/package.json +5 -0
- package/llama/profiles/llvm.win32.host-arm64.target-arm64.cmake +14 -0
- package/llama/profiles/llvm.win32.host-x64.target-arm64.cmake +14 -0
- package/llama/profiles/llvm.win32.host-x64.target-x64.cmake +14 -0
- package/llama/toolchains/darwin.host-x64.target-arm64.cmake +8 -0
- package/llama/toolchains/linux.host-arm64.target-x64.cmake +5 -0
- package/llama/toolchains/linux.host-x64.target-arm64.cmake +5 -0
- package/llama/toolchains/linux.host-x64.target-arm71.cmake +5 -0
- package/llama/toolchains/llvm.win32.host-x64.target-x64.cmake +20 -0
- package/llama/toolchains/win32.host-arm64.target-arm64.cmake +21 -0
- package/llama/toolchains/win32.host-x64.target-arm64.cmake +21 -0
- package/llama/xpack/package.json +10 -0
- package/package.json +241 -0
- package/templates/README.md +6 -0
- package/templates/package.json +10 -0
- package/templates/packed/electron-typescript-react.json +1 -0
- package/templates/packed/node-typescript.json +1 -0
|
@@ -0,0 +1,2696 @@
|
|
|
1
|
+
import { DisposeAggregator, DisposedError, EventRelay, withLock } from "lifecycle-utils";
|
|
2
|
+
import { internalCheckpoints } from "../LlamaContext/LlamaContext.js";
|
|
3
|
+
import { isChatModelResponseFunctionCall, isChatModelResponseSegment, allSegmentTypes } from "../../types.js";
|
|
4
|
+
import { removeNullFields } from "../../utils/removeNullFields.js";
|
|
5
|
+
import { LlamaGrammarEvaluationState } from "../LlamaGrammarEvaluationState.js";
|
|
6
|
+
import { LlamaText, SpecialToken } from "../../utils/LlamaText.js";
|
|
7
|
+
import { StopGenerationDetector } from "../../utils/StopGenerationDetector.js";
|
|
8
|
+
import { TokenStreamRegulator } from "../../utils/TokenStreamRegulator.js";
|
|
9
|
+
import { maxRecentDetokenizerTokens, UNKNOWN_UNICODE_CHAR } from "../../consts.js";
|
|
10
|
+
import { getQueuedTokensBeforeStopTrigger } from "../../utils/getQueuedTokensBeforeStopTrigger.js";
|
|
11
|
+
import { resolveChatWrapper } from "../../chatWrappers/utils/resolveChatWrapper.js";
|
|
12
|
+
import { safeEventCallback } from "../../utils/safeEventCallback.js";
|
|
13
|
+
import { pushAll } from "../../utils/pushAll.js";
|
|
14
|
+
import { resolveLastTokens } from "../../utils/resolveLastTokens.js";
|
|
15
|
+
import { LlamaSampler } from "../LlamaContext/LlamaSampler.js";
|
|
16
|
+
import { getChatWrapperSegmentDefinition } from "../../utils/getChatWrapperSegmentDefinition.js";
|
|
17
|
+
import { jsonDumps } from "../../chatWrappers/utils/jsonDumps.js";
|
|
18
|
+
import { defaultMaxPreloadTokens } from "../LlamaChatSession/utils/LlamaChatSessionPromptCompletionEngine.js";
|
|
19
|
+
import { LlamaLogLevel } from "../../bindings/types.js";
|
|
20
|
+
import { eraseFirstResponseAndKeepFirstSystemChatContextShiftStrategy } from "./utils/contextShiftStrategies/eraseFirstResponseAndKeepFirstSystemChatContextShiftStrategy.js";
|
|
21
|
+
import { FunctionCallNameGrammar } from "./utils/FunctionCallNameGrammar.js";
|
|
22
|
+
import { FunctionCallParamsGrammar } from "./utils/FunctionCallParamsGrammar.js";
|
|
23
|
+
const defaultContextShiftOptions = {
|
|
24
|
+
size: (sequence) => Math.max(1, Math.floor(sequence.context.contextSize / 10)),
|
|
25
|
+
strategy: "eraseFirstResponseAndKeepFirstSystem",
|
|
26
|
+
lastEvaluationMetadata: null
|
|
27
|
+
};
|
|
28
|
+
const defaultRepeatPenaltyLastTokens = 64;
|
|
29
|
+
const defaultTrimWhitespaceSuffix = false;
|
|
30
|
+
const defaultEvaluationPriority = 5;
|
|
31
|
+
const defaultSegmentBudgetSize = (contextSize) => (contextSize < 8192
|
|
32
|
+
? contextSize * 0.5
|
|
33
|
+
: contextSize * 0.75);
|
|
34
|
+
export class LlamaChat {
|
|
35
|
+
/** @internal */ _chatWrapper;
|
|
36
|
+
/** @internal */ _disposeAggregator = new DisposeAggregator();
|
|
37
|
+
/** @internal */ _autoDisposeSequence;
|
|
38
|
+
/** @internal */ _chatLock = {};
|
|
39
|
+
/** @internal */ _sequence;
|
|
40
|
+
onDispose = new EventRelay();
|
|
41
|
+
constructor({ contextSequence, chatWrapper = "auto", autoDisposeSequence = false }) {
|
|
42
|
+
if (contextSequence == null)
|
|
43
|
+
throw new Error("contextSequence cannot be null");
|
|
44
|
+
if (contextSequence.disposed)
|
|
45
|
+
throw new DisposedError();
|
|
46
|
+
this._sequence = contextSequence;
|
|
47
|
+
this._autoDisposeSequence = autoDisposeSequence;
|
|
48
|
+
this._disposeAggregator.add(this._sequence.onDispose.createListener(() => {
|
|
49
|
+
this.dispose();
|
|
50
|
+
}));
|
|
51
|
+
this._disposeAggregator.add(this.onDispose.dispatchEvent);
|
|
52
|
+
this._chatWrapper = chatWrapper === "auto"
|
|
53
|
+
? resolveChatWrapper(contextSequence.model)
|
|
54
|
+
: chatWrapper;
|
|
55
|
+
}
|
|
56
|
+
dispose({ disposeSequence = this._autoDisposeSequence } = {}) {
|
|
57
|
+
if (this._sequence == null)
|
|
58
|
+
return;
|
|
59
|
+
if (disposeSequence)
|
|
60
|
+
this._sequence.dispose();
|
|
61
|
+
this._sequence = null;
|
|
62
|
+
this._disposeAggregator.dispose();
|
|
63
|
+
}
|
|
64
|
+
/** @hidden */
|
|
65
|
+
[Symbol.dispose]() {
|
|
66
|
+
return this.dispose();
|
|
67
|
+
}
|
|
68
|
+
get disposed() {
|
|
69
|
+
return this._sequence == null;
|
|
70
|
+
}
|
|
71
|
+
get chatWrapper() {
|
|
72
|
+
if (this._sequence == null)
|
|
73
|
+
throw new DisposedError();
|
|
74
|
+
return this._chatWrapper;
|
|
75
|
+
}
|
|
76
|
+
get sequence() {
|
|
77
|
+
if (this._sequence == null)
|
|
78
|
+
throw new DisposedError();
|
|
79
|
+
return this._sequence;
|
|
80
|
+
}
|
|
81
|
+
get context() {
|
|
82
|
+
return this.sequence.context;
|
|
83
|
+
}
|
|
84
|
+
get model() {
|
|
85
|
+
return this.sequence.model;
|
|
86
|
+
}
|
|
87
|
+
async generateResponse(history, options = {}) {
|
|
88
|
+
const { onTextChunk, onToken, onResponseChunk, onFunctionCallParamsChunk, budgets, signal, stopOnAbortSignal = false, maxTokens, temperature, minP, topK, topP, seed, xtc, grammar, trimWhitespaceSuffix = defaultTrimWhitespaceSuffix, repeatPenalty = {}, dryRepeatPenalty, tokenBias, evaluationPriority = defaultEvaluationPriority, functions, onFunctionCall, documentFunctionParams, maxParallelFunctionCalls, contextShift = defaultContextShiftOptions, customStopTriggers, abortOnNonText = false, lastEvaluationContextWindow: { history: lastEvaluationContextWindowHistory, minimumOverlapPercentageToPreventContextShift = 0.5 } = {} } = options;
|
|
89
|
+
this.sequence.tokenPredictor?.updateInputTokens?.(this.model.tokenize(findLastUserMessageInChatHistory(history)?.text ?? ""));
|
|
90
|
+
const generateResponseState = new GenerateResponseState(this, this._chatWrapper, history, {
|
|
91
|
+
onTextChunk,
|
|
92
|
+
onToken,
|
|
93
|
+
onResponseChunk,
|
|
94
|
+
onFunctionCallParamsChunk,
|
|
95
|
+
budgets,
|
|
96
|
+
signal,
|
|
97
|
+
stopOnAbortSignal,
|
|
98
|
+
maxTokens,
|
|
99
|
+
temperature,
|
|
100
|
+
minP,
|
|
101
|
+
topK,
|
|
102
|
+
topP,
|
|
103
|
+
seed,
|
|
104
|
+
xtc,
|
|
105
|
+
grammar: grammar, // this is a workaround to allow passing both `functions` and `grammar`
|
|
106
|
+
trimWhitespaceSuffix,
|
|
107
|
+
repeatPenalty,
|
|
108
|
+
dryRepeatPenalty,
|
|
109
|
+
tokenBias,
|
|
110
|
+
evaluationPriority,
|
|
111
|
+
functions,
|
|
112
|
+
onFunctionCall,
|
|
113
|
+
documentFunctionParams,
|
|
114
|
+
maxParallelFunctionCalls,
|
|
115
|
+
contextShift,
|
|
116
|
+
customStopTriggers,
|
|
117
|
+
abortOnNonText,
|
|
118
|
+
lastEvaluationContextWindow: {
|
|
119
|
+
history: lastEvaluationContextWindowHistory,
|
|
120
|
+
minimumOverlapPercentageToPreventContextShift
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
if (generateResponseState.grammar != null && generateResponseState.functionsEnabled && !abortOnNonText)
|
|
124
|
+
throw new Error("Using both grammar and functions is not supported yet");
|
|
125
|
+
return await withLock([this._chatLock, "evaluate"], signal, async () => {
|
|
126
|
+
let hadError = false;
|
|
127
|
+
try {
|
|
128
|
+
let tookInitialCheckpoint = false;
|
|
129
|
+
generateResponseState.ensureLastHistoryItemIsModel();
|
|
130
|
+
generateResponseState.ensureReopenedThoughtSegmentAfterFunctionCallsIfNeeded();
|
|
131
|
+
const loadContextWindow = async (avoidReloadingHistory = false) => {
|
|
132
|
+
await generateResponseState.loadContextWindow(generateResponseState.getResolvedHistoryWithCurrentModelResponse(), generateResponseState.getContextWindowsHistoryWithCurrentModelResponse(), false, avoidReloadingHistory);
|
|
133
|
+
};
|
|
134
|
+
const loadContextWindowForFunctionCallingLoop = async () => loadContextWindow(true);
|
|
135
|
+
while (true) {
|
|
136
|
+
generateResponseState.startTokenLoop();
|
|
137
|
+
generateResponseState.handleRerender();
|
|
138
|
+
const shouldHandlePrefixTriggers = generateResponseState.isRerender;
|
|
139
|
+
generateResponseState.canAvoidReloadingHistory = false;
|
|
140
|
+
await loadContextWindow();
|
|
141
|
+
generateResponseState.isRerender = false;
|
|
142
|
+
generateResponseState.addStopGenerationTriggersFromChatWrapper();
|
|
143
|
+
if (generateResponseState.generatedTokens === 0) {
|
|
144
|
+
generateResponseState.addIgnoreStartTextTriggersFromChatWrapper();
|
|
145
|
+
if (generateResponseState.functionsEnabled) {
|
|
146
|
+
generateResponseState.initFunctions();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const abortRes = generateResponseState.handleAbortTrigger("model");
|
|
150
|
+
if (abortRes != null)
|
|
151
|
+
return abortRes;
|
|
152
|
+
if (shouldHandlePrefixTriggers) {
|
|
153
|
+
const handlePrefixTriggersRes = await generateResponseState.handlePrefixTriggers(loadContextWindowForFunctionCallingLoop);
|
|
154
|
+
if (handlePrefixTriggersRes != null)
|
|
155
|
+
return handlePrefixTriggersRes;
|
|
156
|
+
}
|
|
157
|
+
if (generateResponseState.functionEvaluationMode !== false && !generateResponseState.abortOnNonText) {
|
|
158
|
+
const functionsCallsRes = await generateResponseState.enterFunctionCallingLoop(loadContextWindowForFunctionCallingLoop);
|
|
159
|
+
if (functionsCallsRes != null)
|
|
160
|
+
return functionsCallsRes;
|
|
161
|
+
await loadContextWindowForFunctionCallingLoop();
|
|
162
|
+
}
|
|
163
|
+
await generateResponseState.alignCurrentSequenceStateWithCurrentTokens();
|
|
164
|
+
await generateResponseState.createNewEvaluationIterator();
|
|
165
|
+
while (await generateResponseState.iterateEvaluation()) {
|
|
166
|
+
if (!tookInitialCheckpoint && this.sequence.needsCheckpoints) {
|
|
167
|
+
await this.sequence.takeCheckpoint();
|
|
168
|
+
tookInitialCheckpoint = true;
|
|
169
|
+
}
|
|
170
|
+
if (!generateResponseState.holdPartialTokensForNextEvaluation()) {
|
|
171
|
+
generateResponseState.waitOnPartialCharactersOrWhiteSpaceTokens();
|
|
172
|
+
generateResponseState.detectAndHandleFunctionStartSyntax();
|
|
173
|
+
if (generateResponseState.functionEvaluationMode !== false) {
|
|
174
|
+
generateResponseState.canAvoidReloadingHistory = false;
|
|
175
|
+
generateResponseState.releasePartiallyFreeTokensBeforeFunctionCallStart();
|
|
176
|
+
const functionsCallsRes = await generateResponseState.enterFunctionCallingLoop(loadContextWindowForFunctionCallingLoop);
|
|
177
|
+
if (functionsCallsRes != null)
|
|
178
|
+
return functionsCallsRes;
|
|
179
|
+
}
|
|
180
|
+
{
|
|
181
|
+
const resPromise = generateResponseState.recordStopGenerationEvaluation();
|
|
182
|
+
if (resPromise instanceof Promise)
|
|
183
|
+
await resPromise;
|
|
184
|
+
}
|
|
185
|
+
generateResponseState.popStreamRegulatorFreeTokens();
|
|
186
|
+
generateResponseState.removeFoundStartIgnoreTextsFromPendingTokens();
|
|
187
|
+
const stopGenerationTriggerRes = generateResponseState.handleStopGenerationTrigger("model");
|
|
188
|
+
if (stopGenerationTriggerRes != null)
|
|
189
|
+
return stopGenerationTriggerRes;
|
|
190
|
+
generateResponseState.spliceIgnoreStartTextDetectedTokens();
|
|
191
|
+
generateResponseState.moveFreePendingTokensToRes();
|
|
192
|
+
}
|
|
193
|
+
const maxTokensTriggerRes = generateResponseState.handleMaxTokensTrigger("model");
|
|
194
|
+
if (maxTokensTriggerRes != null)
|
|
195
|
+
return maxTokensTriggerRes;
|
|
196
|
+
if (generateResponseState.handleShouldRerender() || generateResponseState.updateShouldContextShift())
|
|
197
|
+
break;
|
|
198
|
+
if (await generateResponseState.handleBudgetTriggers()) {
|
|
199
|
+
generateResponseState.shouldRerender = true;
|
|
200
|
+
generateResponseState.skipClosingResponseItemOnRerender = true;
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
if (generateResponseState.handleShouldRerender() || generateResponseState.updateShouldContextShift())
|
|
204
|
+
break;
|
|
205
|
+
const abortRes = generateResponseState.handleAbortTrigger("model");
|
|
206
|
+
if (abortRes != null)
|
|
207
|
+
return abortRes;
|
|
208
|
+
}
|
|
209
|
+
generateResponseState.isFirstEvaluation = false;
|
|
210
|
+
if (generateResponseState.shouldRerender || generateResponseState.shouldContextShift)
|
|
211
|
+
continue;
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
throw new Error("The context size is too small to generate a response");
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
hadError = true;
|
|
218
|
+
throw err;
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
await generateResponseState.dispose();
|
|
222
|
+
if (!hadError && this.sequence.needsCheckpoints)
|
|
223
|
+
void this.sequence.takeCheckpoint();
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
async loadChatAndCompleteUserMessage(history, options = {}) {
|
|
228
|
+
const { initialUserPrompt = "", stopOnAbortSignal = false, onTextChunk, onToken, signal, maxTokens = defaultMaxPreloadTokens(this.sequence), temperature, minP, topK, topP, seed, xtc, grammar, trimWhitespaceSuffix = defaultTrimWhitespaceSuffix, repeatPenalty = {}, dryRepeatPenalty, tokenBias, evaluationPriority = defaultEvaluationPriority, functions, documentFunctionParams, contextShift = defaultContextShiftOptions, customStopTriggers, lastEvaluationContextWindow: { history: lastEvaluationContextWindowHistory, minimumOverlapPercentageToPreventContextShift = 0.8 } = {} } = options;
|
|
229
|
+
this.sequence.tokenPredictor?.updateInputTokens?.(this.model.tokenize((findLastModelMessageInChatHistory(history)?.response ?? [])
|
|
230
|
+
.map((item) => {
|
|
231
|
+
if (typeof item === "string")
|
|
232
|
+
return item;
|
|
233
|
+
else if (isChatModelResponseFunctionCall(item))
|
|
234
|
+
return null;
|
|
235
|
+
else if (isChatModelResponseSegment(item))
|
|
236
|
+
return item.text;
|
|
237
|
+
void item;
|
|
238
|
+
return null;
|
|
239
|
+
})
|
|
240
|
+
.filter((item) => item != null)
|
|
241
|
+
.join(" ")));
|
|
242
|
+
const generateResponseState = new GenerateResponseState(this, this._chatWrapper, mergeGeneratedResultWithChatHistory("user", history, [initialUserPrompt]), {
|
|
243
|
+
onTextChunk,
|
|
244
|
+
onToken,
|
|
245
|
+
signal,
|
|
246
|
+
stopOnAbortSignal,
|
|
247
|
+
maxTokens,
|
|
248
|
+
temperature,
|
|
249
|
+
minP,
|
|
250
|
+
topK,
|
|
251
|
+
topP,
|
|
252
|
+
seed,
|
|
253
|
+
xtc,
|
|
254
|
+
grammar: grammar, // this is a workaround to allow passing both `functions` and `grammar`
|
|
255
|
+
trimWhitespaceSuffix,
|
|
256
|
+
repeatPenalty,
|
|
257
|
+
dryRepeatPenalty,
|
|
258
|
+
tokenBias,
|
|
259
|
+
evaluationPriority,
|
|
260
|
+
functions,
|
|
261
|
+
documentFunctionParams,
|
|
262
|
+
contextShift,
|
|
263
|
+
customStopTriggers,
|
|
264
|
+
lastEvaluationContextWindow: {
|
|
265
|
+
history: mergeGeneratedResultWithChatHistory("user", lastEvaluationContextWindowHistory ?? history, [initialUserPrompt]),
|
|
266
|
+
minimumOverlapPercentageToPreventContextShift
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
return await withLock([this._chatLock, "evaluate"], signal, async () => {
|
|
270
|
+
try {
|
|
271
|
+
let tookInitialCheckpoint = false;
|
|
272
|
+
generateResponseState.ensureLastHistoryItemIsUser();
|
|
273
|
+
while (true) {
|
|
274
|
+
generateResponseState.startTokenLoop();
|
|
275
|
+
const { userTextSuffix } = await generateResponseState.loadContextWindow(mergeGeneratedResultWithChatHistory("user", generateResponseState.resolvedHistory, generateResponseState.segmentHandler.getModelResponseSegments()), mergeGeneratedResultWithChatHistory("user", generateResponseState.lastContextWindowHistory, generateResponseState.segmentHandler.getContextWindowModelResponseSegments()), true);
|
|
276
|
+
generateResponseState.isRerender = false;
|
|
277
|
+
generateResponseState.functionEvaluationMode = false;
|
|
278
|
+
generateResponseState.addStopGenerationTriggersFromChatWrapper();
|
|
279
|
+
if (userTextSuffix != null && userTextSuffix.values.length > 0)
|
|
280
|
+
generateResponseState.stopGenerationDetector.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(userTextSuffix, this.model.tokenizer));
|
|
281
|
+
generateResponseState.rerenderTriggers.forEach((trigger) => (generateResponseState.stopGenerationDetector.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(trigger, this.model.tokenizer))));
|
|
282
|
+
allSegmentTypes
|
|
283
|
+
.map((segmentType) => getChatWrapperSegmentDefinition(this._chatWrapper.settings, segmentType))
|
|
284
|
+
.filter((segmentDefinition) => segmentDefinition != null)
|
|
285
|
+
.flatMap((segmentDefinition) => [segmentDefinition?.prefix, segmentDefinition?.suffix])
|
|
286
|
+
.filter((trigger) => trigger != null)
|
|
287
|
+
.forEach((trigger) => (generateResponseState.stopGenerationDetector.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText(trigger), this.model.tokenizer))));
|
|
288
|
+
await generateResponseState.alignCurrentSequenceStateWithCurrentTokens();
|
|
289
|
+
if (generateResponseState.maxTokens === 0) {
|
|
290
|
+
await generateResponseState.evaluateWithoutGeneratingNewTokens();
|
|
291
|
+
return {
|
|
292
|
+
completion: "",
|
|
293
|
+
lastEvaluation: {
|
|
294
|
+
contextWindow: mergeGeneratedResultWithChatHistory("user", generateResponseState.lastContextWindowHistory, generateResponseState.segmentHandler.getContextWindowModelResponseSegments()),
|
|
295
|
+
contextShiftMetadata: generateResponseState.lastHistoryCompressionMetadata
|
|
296
|
+
},
|
|
297
|
+
metadata: {
|
|
298
|
+
stopReason: "maxTokens"
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
await generateResponseState.createNewEvaluationIterator();
|
|
303
|
+
while (await generateResponseState.iterateEvaluation()) {
|
|
304
|
+
if (!tookInitialCheckpoint && this.sequence.needsCheckpoints) {
|
|
305
|
+
await this.sequence.takeCheckpoint();
|
|
306
|
+
tookInitialCheckpoint = true;
|
|
307
|
+
}
|
|
308
|
+
if (!generateResponseState.holdPartialTokensForNextEvaluation()) {
|
|
309
|
+
generateResponseState.waitOnPartialCharactersOrWhiteSpaceTokens();
|
|
310
|
+
{
|
|
311
|
+
const resPromise = generateResponseState.recordStopGenerationEvaluation();
|
|
312
|
+
if (resPromise instanceof Promise)
|
|
313
|
+
await resPromise;
|
|
314
|
+
}
|
|
315
|
+
generateResponseState.popStreamRegulatorFreeTokens();
|
|
316
|
+
const someOfCurrentTokensAreSpecial = generateResponseState.currentTokens.some((token) => (this.model.isSpecialToken(token)));
|
|
317
|
+
const stopGenerationTriggerRes = generateResponseState.handleStopGenerationTrigger("user", someOfCurrentTokensAreSpecial
|
|
318
|
+
? "eogToken"
|
|
319
|
+
: undefined);
|
|
320
|
+
if (stopGenerationTriggerRes != null)
|
|
321
|
+
return {
|
|
322
|
+
completion: stopGenerationTriggerRes.response,
|
|
323
|
+
lastEvaluation: {
|
|
324
|
+
contextWindow: mergeGeneratedResultWithChatHistory("user", generateResponseState.lastContextWindowHistory, generateResponseState.segmentHandler.getContextWindowModelResponseSegments()),
|
|
325
|
+
contextShiftMetadata: stopGenerationTriggerRes.lastEvaluation.contextShiftMetadata
|
|
326
|
+
},
|
|
327
|
+
metadata: stopGenerationTriggerRes.metadata.stopReason === "customStopTrigger"
|
|
328
|
+
? stopGenerationTriggerRes.metadata
|
|
329
|
+
: stopGenerationTriggerRes.metadata
|
|
330
|
+
};
|
|
331
|
+
generateResponseState.moveFreePendingTokensToRes(false);
|
|
332
|
+
}
|
|
333
|
+
const maxTokensTriggerRes = generateResponseState.handleMaxTokensTrigger("user");
|
|
334
|
+
if (maxTokensTriggerRes != null)
|
|
335
|
+
return {
|
|
336
|
+
completion: maxTokensTriggerRes.response,
|
|
337
|
+
lastEvaluation: {
|
|
338
|
+
contextWindow: mergeGeneratedResultWithChatHistory("user", generateResponseState.lastContextWindowHistory, generateResponseState.segmentHandler.getContextWindowModelResponseSegments()),
|
|
339
|
+
contextShiftMetadata: maxTokensTriggerRes.lastEvaluation.contextShiftMetadata
|
|
340
|
+
},
|
|
341
|
+
metadata: maxTokensTriggerRes.metadata
|
|
342
|
+
};
|
|
343
|
+
if (generateResponseState.updateShouldContextShift())
|
|
344
|
+
break;
|
|
345
|
+
const abortRes = generateResponseState.handleAbortTrigger("user");
|
|
346
|
+
if (abortRes != null)
|
|
347
|
+
return {
|
|
348
|
+
completion: abortRes.response,
|
|
349
|
+
lastEvaluation: {
|
|
350
|
+
contextWindow: mergeGeneratedResultWithChatHistory("user", generateResponseState.lastContextWindowHistory, generateResponseState.segmentHandler.getContextWindowModelResponseSegments()),
|
|
351
|
+
contextShiftMetadata: abortRes.lastEvaluation.contextShiftMetadata
|
|
352
|
+
},
|
|
353
|
+
metadata: abortRes.metadata
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
generateResponseState.isFirstEvaluation = false;
|
|
357
|
+
if (generateResponseState.shouldContextShift)
|
|
358
|
+
continue;
|
|
359
|
+
break;
|
|
360
|
+
}
|
|
361
|
+
throw new Error("The context size is too small to generate a completion");
|
|
362
|
+
}
|
|
363
|
+
finally {
|
|
364
|
+
await generateResponseState.dispose();
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function removeRawFromHistoryItem(historyItem) {
|
|
370
|
+
if (historyItem.type === "model") {
|
|
371
|
+
const newHistoryItem = { ...historyItem };
|
|
372
|
+
newHistoryItem.response = newHistoryItem.response.map((item) => {
|
|
373
|
+
if (typeof item === "string")
|
|
374
|
+
return item;
|
|
375
|
+
else if (isChatModelResponseFunctionCall(item))
|
|
376
|
+
return {
|
|
377
|
+
...item,
|
|
378
|
+
rawCall: undefined
|
|
379
|
+
};
|
|
380
|
+
else if (isChatModelResponseSegment(item))
|
|
381
|
+
return {
|
|
382
|
+
...item,
|
|
383
|
+
raw: undefined
|
|
384
|
+
};
|
|
385
|
+
void item;
|
|
386
|
+
return item;
|
|
387
|
+
});
|
|
388
|
+
return newHistoryItem;
|
|
389
|
+
}
|
|
390
|
+
return historyItem;
|
|
391
|
+
}
|
|
392
|
+
async function compressHistoryToFitContextSize({ history, contextShiftSize, contextShiftStrategy, contextShiftLastEvaluationMetadata, contextSize, tokenizer, chatWrapper, functions, documentFunctionParams }) {
|
|
393
|
+
function checkIfHistoryFitsContext(history) {
|
|
394
|
+
const { contextText } = chatWrapper.generateContextState({
|
|
395
|
+
chatHistory: history,
|
|
396
|
+
availableFunctions: functions,
|
|
397
|
+
documentFunctionParams
|
|
398
|
+
});
|
|
399
|
+
const tokens = contextText.tokenize(tokenizer);
|
|
400
|
+
return tokens.length <= contextSize - contextShiftSize;
|
|
401
|
+
}
|
|
402
|
+
if (contextSize - contextShiftSize <= 0)
|
|
403
|
+
throw new Error(`The context size (${contextSize}) is too small to fit the context shift size (${contextShiftSize})`);
|
|
404
|
+
if (checkIfHistoryFitsContext(history))
|
|
405
|
+
return {
|
|
406
|
+
compressedHistory: history,
|
|
407
|
+
metadata: null
|
|
408
|
+
};
|
|
409
|
+
if (contextShiftStrategy instanceof Function) {
|
|
410
|
+
try {
|
|
411
|
+
const { chatHistory, metadata } = await contextShiftStrategy({
|
|
412
|
+
chatHistory: history,
|
|
413
|
+
maxTokensCount: contextSize - contextShiftSize,
|
|
414
|
+
tokenizer,
|
|
415
|
+
chatWrapper,
|
|
416
|
+
lastShiftMetadata: contextShiftLastEvaluationMetadata
|
|
417
|
+
});
|
|
418
|
+
if (checkIfHistoryFitsContext(chatHistory))
|
|
419
|
+
return {
|
|
420
|
+
compressedHistory: chatHistory,
|
|
421
|
+
metadata
|
|
422
|
+
};
|
|
423
|
+
console.warn("The provided context shift strategy did not return a history that fits the context size. " +
|
|
424
|
+
"Using the default strategy instead.");
|
|
425
|
+
}
|
|
426
|
+
catch (err) {
|
|
427
|
+
console.error("The provided context shift strategy threw an error. " +
|
|
428
|
+
"Using the default strategy instead.", err);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
else if (contextShiftStrategy !== "eraseFirstResponseAndKeepFirstSystem")
|
|
432
|
+
console.warn(`Unknown context shift strategy "${contextShiftStrategy}". ` +
|
|
433
|
+
"Using the default strategy instead.");
|
|
434
|
+
const { chatHistory, metadata } = await eraseFirstResponseAndKeepFirstSystemChatContextShiftStrategy({
|
|
435
|
+
chatHistory: history,
|
|
436
|
+
maxTokensCount: contextSize - contextShiftSize,
|
|
437
|
+
tokenizer,
|
|
438
|
+
chatWrapper,
|
|
439
|
+
lastShiftMetadata: contextShiftLastEvaluationMetadata
|
|
440
|
+
});
|
|
441
|
+
if (!checkIfHistoryFitsContext(chatHistory))
|
|
442
|
+
throw new Error("The default context shift strategy did not return a history that fits the context size. " +
|
|
443
|
+
"This may happen due to the system prompt being too long");
|
|
444
|
+
return {
|
|
445
|
+
compressedHistory: chatHistory,
|
|
446
|
+
metadata
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
function getLastModelMessageFullResponseFromChatHistory(chatHistory) {
|
|
450
|
+
const lastModelResponseItem = chatHistory.at(-1);
|
|
451
|
+
if (lastModelResponseItem == null || lastModelResponseItem.type !== "model")
|
|
452
|
+
return [];
|
|
453
|
+
return lastModelResponseItem.response;
|
|
454
|
+
}
|
|
455
|
+
function getLastUserTextFromChatHistory(chatHistory) {
|
|
456
|
+
if (chatHistory.length === 0 || chatHistory[chatHistory.length - 1].type !== "user")
|
|
457
|
+
return "";
|
|
458
|
+
return chatHistory[chatHistory.length - 1].text;
|
|
459
|
+
}
|
|
460
|
+
function setLastUserTextInChatHistory(chatHistory, userText) {
|
|
461
|
+
const newChatHistory = chatHistory.slice();
|
|
462
|
+
if (newChatHistory.length === 0 || newChatHistory[newChatHistory.length - 1].type !== "user")
|
|
463
|
+
newChatHistory.push({
|
|
464
|
+
type: "user",
|
|
465
|
+
text: ""
|
|
466
|
+
});
|
|
467
|
+
const lastUserItem = newChatHistory[newChatHistory.length - 1];
|
|
468
|
+
const newLastUserItem = { ...lastUserItem };
|
|
469
|
+
newChatHistory[newChatHistory.length - 1] = newLastUserItem;
|
|
470
|
+
newLastUserItem.text = userText;
|
|
471
|
+
return newChatHistory;
|
|
472
|
+
}
|
|
473
|
+
function mergeGeneratedResultWithChatHistory(itemType, chatHistory, generatedResult) {
|
|
474
|
+
if (generatedResult.length === 0 || (generatedResult.length === 1 && generatedResult[0] === ""))
|
|
475
|
+
return chatHistory;
|
|
476
|
+
const newChatHistory = chatHistory.slice();
|
|
477
|
+
if (itemType === "user") {
|
|
478
|
+
let lastUserItem = newChatHistory.at(-1);
|
|
479
|
+
if (lastUserItem?.type !== "user") {
|
|
480
|
+
lastUserItem = {
|
|
481
|
+
type: "user",
|
|
482
|
+
text: ""
|
|
483
|
+
};
|
|
484
|
+
newChatHistory.push(lastUserItem);
|
|
485
|
+
}
|
|
486
|
+
const newLastUserItem = { ...lastUserItem };
|
|
487
|
+
newChatHistory[newChatHistory.length - 1] = newLastUserItem;
|
|
488
|
+
newLastUserItem.text += generatedResult
|
|
489
|
+
.map((item) => {
|
|
490
|
+
if (typeof item === "string")
|
|
491
|
+
return item;
|
|
492
|
+
return item.text;
|
|
493
|
+
})
|
|
494
|
+
.join("");
|
|
495
|
+
return newChatHistory;
|
|
496
|
+
}
|
|
497
|
+
else {
|
|
498
|
+
let lastModelItem = newChatHistory.at(-1);
|
|
499
|
+
if (lastModelItem?.type !== "model") {
|
|
500
|
+
lastModelItem = {
|
|
501
|
+
type: "model",
|
|
502
|
+
response: []
|
|
503
|
+
};
|
|
504
|
+
newChatHistory.push(lastModelItem);
|
|
505
|
+
}
|
|
506
|
+
const newLastModelItem = { ...lastModelItem };
|
|
507
|
+
newChatHistory[newChatHistory.length - 1] = newLastModelItem;
|
|
508
|
+
const modelResponse = newLastModelItem.response.slice();
|
|
509
|
+
newLastModelItem.response = modelResponse;
|
|
510
|
+
const firstGeneratedResultItem = generatedResult[0];
|
|
511
|
+
if (firstGeneratedResultItem == null)
|
|
512
|
+
return newChatHistory;
|
|
513
|
+
const lastModelResponseItem = modelResponse.at(-1);
|
|
514
|
+
if (typeof firstGeneratedResultItem === "string" && typeof lastModelResponseItem === "string") {
|
|
515
|
+
modelResponse[modelResponse.length - 1] = lastModelResponseItem + firstGeneratedResultItem;
|
|
516
|
+
}
|
|
517
|
+
else if (typeof firstGeneratedResultItem !== "string" && isChatModelResponseSegment(firstGeneratedResultItem) &&
|
|
518
|
+
typeof lastModelResponseItem !== "string" && isChatModelResponseSegment(lastModelResponseItem) &&
|
|
519
|
+
!lastModelResponseItem.ended && lastModelResponseItem.segmentType === firstGeneratedResultItem.segmentType) {
|
|
520
|
+
modelResponse[modelResponse.length - 1] = {
|
|
521
|
+
...lastModelResponseItem,
|
|
522
|
+
...firstGeneratedResultItem,
|
|
523
|
+
text: lastModelResponseItem.text + firstGeneratedResultItem.text,
|
|
524
|
+
ended: firstGeneratedResultItem.ended,
|
|
525
|
+
raw: (lastModelResponseItem.raw != null && firstGeneratedResultItem.raw != null)
|
|
526
|
+
? LlamaText([
|
|
527
|
+
LlamaText.fromJSON(lastModelResponseItem.raw),
|
|
528
|
+
LlamaText.fromJSON(firstGeneratedResultItem.raw)
|
|
529
|
+
]).toJSON()
|
|
530
|
+
: undefined,
|
|
531
|
+
startTime: lastModelResponseItem.startTime,
|
|
532
|
+
endTime: firstGeneratedResultItem.endTime
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
else
|
|
536
|
+
modelResponse.push(firstGeneratedResultItem);
|
|
537
|
+
pushAll(modelResponse, generatedResult.slice(1));
|
|
538
|
+
return newChatHistory;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
function findLastUserMessageInChatHistory(chatHistory) {
|
|
542
|
+
for (let i = chatHistory.length - 1; i >= 0; i--) {
|
|
543
|
+
const item = chatHistory[i];
|
|
544
|
+
if (item.type === "user")
|
|
545
|
+
return item;
|
|
546
|
+
}
|
|
547
|
+
return undefined;
|
|
548
|
+
}
|
|
549
|
+
function findLastModelMessageInChatHistory(chatHistory) {
|
|
550
|
+
for (let i = chatHistory.length - 1; i >= 0; i--) {
|
|
551
|
+
const item = chatHistory[i];
|
|
552
|
+
if (item.type === "model")
|
|
553
|
+
return item;
|
|
554
|
+
}
|
|
555
|
+
return undefined;
|
|
556
|
+
}
|
|
557
|
+
function generateContextText(endWithUserText, chatWrapper, options) {
|
|
558
|
+
if (endWithUserText)
|
|
559
|
+
return generateContextTextThatEndsWithUserText(chatWrapper, options);
|
|
560
|
+
return chatWrapper.generateContextState(options);
|
|
561
|
+
}
|
|
562
|
+
function generateContextTextThatEndsWithUserText(chatWrapper, options) {
|
|
563
|
+
const lastUserText = getLastUserTextFromChatHistory(options.chatHistory);
|
|
564
|
+
const randomId = "W" + (Math.random()
|
|
565
|
+
.toString(36)
|
|
566
|
+
.slice(2)) + "W";
|
|
567
|
+
const { contextText, ...rest } = chatWrapper.generateContextState({
|
|
568
|
+
...options,
|
|
569
|
+
chatHistory: setLastUserTextInChatHistory(options.chatHistory, lastUserText + randomId)
|
|
570
|
+
});
|
|
571
|
+
for (let i = 0; i < contextText.values.length; i++) {
|
|
572
|
+
const item = contextText.values[i];
|
|
573
|
+
if (typeof item !== "string")
|
|
574
|
+
continue;
|
|
575
|
+
const randomTextIndex = item.indexOf(randomId);
|
|
576
|
+
if (randomTextIndex < 0)
|
|
577
|
+
continue;
|
|
578
|
+
const newValue = item.slice(0, randomTextIndex);
|
|
579
|
+
return {
|
|
580
|
+
contextText: LlamaText([
|
|
581
|
+
...contextText.values.slice(0, i),
|
|
582
|
+
newValue
|
|
583
|
+
]),
|
|
584
|
+
userTextSuffix: LlamaText([
|
|
585
|
+
item.slice(randomTextIndex + randomId.length),
|
|
586
|
+
...contextText.values.slice(i + 1)
|
|
587
|
+
]),
|
|
588
|
+
...rest
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
throw new Error("The random ID was not found in the context text. " +
|
|
592
|
+
`There might be an issue with the chat wrapper "${chatWrapper.wrapperName}" ` +
|
|
593
|
+
"where not all user messages are properly added to the the result LlamaText");
|
|
594
|
+
}
|
|
595
|
+
async function getContextWindow({ resolvedHistory, resolvedContextShift, lastHistoryCompressionMetadata, pendingTokensCount = 0, isFirstEvaluation, isRerender, chatWrapper, lastEvaluationContextWindowHistory, minimumOverlapPercentageToPreventContextShift, sequence, minFreeContextTokens = 1, functions, documentFunctionParams, endWithUserText }) {
|
|
596
|
+
if (sequence == null)
|
|
597
|
+
throw new DisposedError();
|
|
598
|
+
const model = sequence.model;
|
|
599
|
+
const context = sequence.context;
|
|
600
|
+
let removeRawFromHistory = false;
|
|
601
|
+
if ((isFirstEvaluation || isRerender) && lastEvaluationContextWindowHistory != null && sequence.isLoadedToMemory) {
|
|
602
|
+
const newContextWindow = lastEvaluationContextWindowHistory.slice();
|
|
603
|
+
if (endWithUserText) {
|
|
604
|
+
if (newContextWindow.length === 0 || newContextWindow[newContextWindow.length - 1].type !== "user")
|
|
605
|
+
newContextWindow.push({
|
|
606
|
+
type: "user",
|
|
607
|
+
text: ""
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
else if (newContextWindow.length === 0 || newContextWindow[newContextWindow.length - 1].type !== "model")
|
|
611
|
+
newContextWindow.push({
|
|
612
|
+
type: "model",
|
|
613
|
+
response: []
|
|
614
|
+
});
|
|
615
|
+
const { contextText, stopGenerationTriggers, ignoreStartText, functionCall, userTextSuffix, prefixTriggers, noPrefixTrigger, rerender, detectFunctionCalls } = generateContextText(endWithUserText, chatWrapper, {
|
|
616
|
+
chatHistory: newContextWindow,
|
|
617
|
+
availableFunctions: functions,
|
|
618
|
+
documentFunctionParams
|
|
619
|
+
});
|
|
620
|
+
const tokens = contextText.tokenize(model.tokenizer);
|
|
621
|
+
if (tokens.length + pendingTokensCount + minFreeContextTokens < context.contextSize) {
|
|
622
|
+
const { firstDifferentIndex } = sequence.compareContextTokens(tokens);
|
|
623
|
+
const existingEvaluationPercentage = firstDifferentIndex / tokens.length;
|
|
624
|
+
if (isRerender || existingEvaluationPercentage >= minimumOverlapPercentageToPreventContextShift)
|
|
625
|
+
return {
|
|
626
|
+
history: newContextWindow,
|
|
627
|
+
stopGenerationTriggers,
|
|
628
|
+
tokens,
|
|
629
|
+
removeRawFromHistory,
|
|
630
|
+
newHistoryCompressionMetadata: lastHistoryCompressionMetadata,
|
|
631
|
+
ignoreStartText: ignoreStartText ?? [],
|
|
632
|
+
functionCallInitiallyEngaged: functionCall?.initiallyEngaged ?? false,
|
|
633
|
+
disengageInitiallyEngagedFunctionCall: functionCall?.disengageInitiallyEngaged ?? [],
|
|
634
|
+
userTextSuffix,
|
|
635
|
+
prefixTriggers,
|
|
636
|
+
noPrefixTrigger,
|
|
637
|
+
rerender,
|
|
638
|
+
detectFunctionCalls
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
removeRawFromHistory = !sequence.isLoadedToMemory;
|
|
643
|
+
resolvedHistory = removeRawFromHistory
|
|
644
|
+
? resolvedHistory.map(removeRawFromHistoryItem)
|
|
645
|
+
: resolvedHistory.slice();
|
|
646
|
+
if (resolvedContextShift.lastEvaluationMetadata != null) {
|
|
647
|
+
const contextShiftSize = resolvedContextShift.size instanceof Function
|
|
648
|
+
? await resolvedContextShift.size(sequence)
|
|
649
|
+
: resolvedContextShift.size;
|
|
650
|
+
const { compressedHistory, metadata } = await compressHistoryToFitContextSize({
|
|
651
|
+
history: resolvedHistory,
|
|
652
|
+
contextShiftSize: Math.max(minFreeContextTokens, Math.min(contextShiftSize, context.contextSize - pendingTokensCount)) + pendingTokensCount,
|
|
653
|
+
contextShiftStrategy: resolvedContextShift.strategy,
|
|
654
|
+
contextShiftLastEvaluationMetadata: resolvedContextShift.lastEvaluationMetadata,
|
|
655
|
+
contextSize: context.contextSize,
|
|
656
|
+
tokenizer: model.tokenizer,
|
|
657
|
+
chatWrapper: chatWrapper,
|
|
658
|
+
functions,
|
|
659
|
+
documentFunctionParams
|
|
660
|
+
});
|
|
661
|
+
const { contextText, stopGenerationTriggers, ignoreStartText, functionCall, userTextSuffix, prefixTriggers, noPrefixTrigger, rerender, detectFunctionCalls } = generateContextText(endWithUserText, chatWrapper, {
|
|
662
|
+
chatHistory: compressedHistory,
|
|
663
|
+
availableFunctions: functions,
|
|
664
|
+
documentFunctionParams
|
|
665
|
+
});
|
|
666
|
+
return {
|
|
667
|
+
history: compressedHistory,
|
|
668
|
+
stopGenerationTriggers,
|
|
669
|
+
tokens: contextText.tokenize(model.tokenizer),
|
|
670
|
+
removeRawFromHistory,
|
|
671
|
+
newHistoryCompressionMetadata: metadata,
|
|
672
|
+
ignoreStartText: ignoreStartText ?? [],
|
|
673
|
+
functionCallInitiallyEngaged: functionCall?.initiallyEngaged ?? false,
|
|
674
|
+
disengageInitiallyEngagedFunctionCall: functionCall?.disengageInitiallyEngaged ?? [],
|
|
675
|
+
userTextSuffix,
|
|
676
|
+
prefixTriggers,
|
|
677
|
+
noPrefixTrigger,
|
|
678
|
+
rerender,
|
|
679
|
+
detectFunctionCalls
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
{
|
|
683
|
+
const { contextText, stopGenerationTriggers, ignoreStartText, functionCall, userTextSuffix, prefixTriggers, noPrefixTrigger, rerender, detectFunctionCalls } = generateContextText(endWithUserText, chatWrapper, {
|
|
684
|
+
chatHistory: resolvedHistory,
|
|
685
|
+
availableFunctions: functions,
|
|
686
|
+
documentFunctionParams
|
|
687
|
+
});
|
|
688
|
+
const tokens = contextText.tokenize(model.tokenizer);
|
|
689
|
+
if (tokens.length + pendingTokensCount + minFreeContextTokens < context.contextSize)
|
|
690
|
+
return {
|
|
691
|
+
history: resolvedHistory,
|
|
692
|
+
stopGenerationTriggers,
|
|
693
|
+
tokens,
|
|
694
|
+
removeRawFromHistory,
|
|
695
|
+
newHistoryCompressionMetadata: lastHistoryCompressionMetadata,
|
|
696
|
+
ignoreStartText: ignoreStartText ?? [],
|
|
697
|
+
functionCallInitiallyEngaged: functionCall?.initiallyEngaged ?? false,
|
|
698
|
+
disengageInitiallyEngagedFunctionCall: functionCall?.disengageInitiallyEngaged ?? [],
|
|
699
|
+
userTextSuffix,
|
|
700
|
+
prefixTriggers,
|
|
701
|
+
noPrefixTrigger,
|
|
702
|
+
rerender,
|
|
703
|
+
detectFunctionCalls
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
const contextShiftSize = Math.min(context.contextSize, Math.max(1, Math.floor(resolvedContextShift.size instanceof Function
|
|
707
|
+
? await resolvedContextShift.size(sequence)
|
|
708
|
+
: resolvedContextShift.size)));
|
|
709
|
+
const { compressedHistory, metadata } = await compressHistoryToFitContextSize({
|
|
710
|
+
history: resolvedHistory,
|
|
711
|
+
contextShiftSize: Math.max(minFreeContextTokens, Math.min(contextShiftSize, context.contextSize - pendingTokensCount)) + pendingTokensCount,
|
|
712
|
+
contextShiftStrategy: resolvedContextShift.strategy,
|
|
713
|
+
contextShiftLastEvaluationMetadata: resolvedContextShift.lastEvaluationMetadata,
|
|
714
|
+
contextSize: context.contextSize,
|
|
715
|
+
tokenizer: model.tokenizer,
|
|
716
|
+
chatWrapper: chatWrapper,
|
|
717
|
+
functions,
|
|
718
|
+
documentFunctionParams
|
|
719
|
+
});
|
|
720
|
+
const { contextText, stopGenerationTriggers, ignoreStartText, functionCall, userTextSuffix, prefixTriggers, noPrefixTrigger, rerender, detectFunctionCalls } = generateContextText(endWithUserText, chatWrapper, {
|
|
721
|
+
chatHistory: compressedHistory,
|
|
722
|
+
availableFunctions: functions,
|
|
723
|
+
documentFunctionParams
|
|
724
|
+
});
|
|
725
|
+
return {
|
|
726
|
+
history: compressedHistory,
|
|
727
|
+
stopGenerationTriggers,
|
|
728
|
+
tokens: contextText.tokenize(model.tokenizer),
|
|
729
|
+
removeRawFromHistory,
|
|
730
|
+
newHistoryCompressionMetadata: metadata,
|
|
731
|
+
ignoreStartText: ignoreStartText ?? [],
|
|
732
|
+
functionCallInitiallyEngaged: functionCall?.initiallyEngaged ?? false,
|
|
733
|
+
disengageInitiallyEngagedFunctionCall: functionCall?.disengageInitiallyEngaged ?? [],
|
|
734
|
+
userTextSuffix,
|
|
735
|
+
prefixTriggers,
|
|
736
|
+
noPrefixTrigger,
|
|
737
|
+
rerender,
|
|
738
|
+
detectFunctionCalls
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
class GenerateResponseState {
|
|
742
|
+
llamaChat;
|
|
743
|
+
chatWrapper;
|
|
744
|
+
history;
|
|
745
|
+
onTextChunk;
|
|
746
|
+
onToken;
|
|
747
|
+
onResponseChunk;
|
|
748
|
+
onFunctionCallParamsChunk;
|
|
749
|
+
budgets;
|
|
750
|
+
signal;
|
|
751
|
+
stopOnAbortSignal;
|
|
752
|
+
maxTokens;
|
|
753
|
+
temperature;
|
|
754
|
+
minP;
|
|
755
|
+
topK;
|
|
756
|
+
topP;
|
|
757
|
+
seed;
|
|
758
|
+
xtc;
|
|
759
|
+
grammar;
|
|
760
|
+
trimWhitespaceSuffix;
|
|
761
|
+
tokenBias;
|
|
762
|
+
evaluationPriority;
|
|
763
|
+
functions;
|
|
764
|
+
onFunctionCall;
|
|
765
|
+
documentFunctionParams;
|
|
766
|
+
maxParallelFunctionCalls;
|
|
767
|
+
contextShift;
|
|
768
|
+
customStopTriggers;
|
|
769
|
+
abortOnNonText;
|
|
770
|
+
minimumOverlapPercentageToPreventContextShift;
|
|
771
|
+
functionsEnabled;
|
|
772
|
+
repeatPenaltyEnabled;
|
|
773
|
+
resolvedContextShift;
|
|
774
|
+
resolvedRepeatPenalty;
|
|
775
|
+
dryRepeatPenalty;
|
|
776
|
+
grammarEvaluationState;
|
|
777
|
+
functionNameGrammar;
|
|
778
|
+
functionsGrammar;
|
|
779
|
+
functionsEvaluationState;
|
|
780
|
+
functionSyntaxStartDetectorEnabled = true;
|
|
781
|
+
streamRegulator = new TokenStreamRegulator();
|
|
782
|
+
stopGenerationDetector = new StopGenerationDetector();
|
|
783
|
+
customStopGenerationTriggersDetector = new StopGenerationDetector();
|
|
784
|
+
functionSyntaxStartDetector = new StopGenerationDetector();
|
|
785
|
+
disengageInitiallyEngagedFunctionMode = new StopGenerationDetector();
|
|
786
|
+
ignoreStartTextDetector = new StopGenerationDetector();
|
|
787
|
+
locksToReleaseOnValidGeneration = [];
|
|
788
|
+
resolvedHistory;
|
|
789
|
+
noRawInResolvedHistory;
|
|
790
|
+
res = [];
|
|
791
|
+
pendingTokens = [];
|
|
792
|
+
ignoredStartTextTokens = [];
|
|
793
|
+
prefixTriggerTokens = [];
|
|
794
|
+
resFunctionCalls = [];
|
|
795
|
+
segmentHandler;
|
|
796
|
+
pendingPartialTokens = [];
|
|
797
|
+
functionEvaluationMode = false;
|
|
798
|
+
currentFunctionCallPreviousText = LlamaText([]);
|
|
799
|
+
currentFunctionCallCurrentPartTokens = [];
|
|
800
|
+
functionEvaluationFunctionName = "";
|
|
801
|
+
currentFunctionCallPreviousPartLeftoverText = "";
|
|
802
|
+
removedStartTextToIgnore = false;
|
|
803
|
+
releasedPartiallyFreeTokensBeforeFunctionCallStartSyntax = false;
|
|
804
|
+
generatedTokens = 0;
|
|
805
|
+
isFirstEvaluation = true;
|
|
806
|
+
isRerender = true; // first render is a rerender
|
|
807
|
+
initiallyEngagedFunctionMode = false;
|
|
808
|
+
lastContextWindowHistory;
|
|
809
|
+
lastHistoryCompressionMetadata;
|
|
810
|
+
restartEvaluationIterator = false;
|
|
811
|
+
// context shift loop
|
|
812
|
+
shouldContextShift = false;
|
|
813
|
+
shouldRerender = false;
|
|
814
|
+
skipClosingResponseItemOnRerender = false;
|
|
815
|
+
shouldAbortBecauseOfNonText = false;
|
|
816
|
+
canAvoidReloadingHistory = false;
|
|
817
|
+
contextWindowTokens = [];
|
|
818
|
+
stopGenerationTriggers = [];
|
|
819
|
+
ignoreStartText = [];
|
|
820
|
+
functionCallInitiallyEngaged = false;
|
|
821
|
+
disengageInitiallyEngagedFunctionCall = [];
|
|
822
|
+
userTextSuffix = undefined;
|
|
823
|
+
prefixTriggerDetectors = new Map();
|
|
824
|
+
noPrefixTrigger = undefined;
|
|
825
|
+
responsePrefix = undefined;
|
|
826
|
+
rerenderTriggers = [];
|
|
827
|
+
rerenderTriggerDetector = new StopGenerationDetector();
|
|
828
|
+
rerenderActions = undefined;
|
|
829
|
+
tokens = [];
|
|
830
|
+
// token evaluation loop
|
|
831
|
+
evaluationIterator;
|
|
832
|
+
currentIteration;
|
|
833
|
+
currentIterationReplacementToken;
|
|
834
|
+
currentToken;
|
|
835
|
+
currentTokens = [];
|
|
836
|
+
currentText = "";
|
|
837
|
+
currentQueuedTokenRelease;
|
|
838
|
+
constructor(llamaChat, chatWrapper, history, { onTextChunk, onToken, onResponseChunk, onFunctionCallParamsChunk, budgets, signal, stopOnAbortSignal = false, maxTokens, temperature, minP, topK, topP, seed, xtc, grammar, trimWhitespaceSuffix = defaultTrimWhitespaceSuffix, repeatPenalty = {}, dryRepeatPenalty, tokenBias, evaluationPriority = defaultEvaluationPriority, functions, onFunctionCall, documentFunctionParams, maxParallelFunctionCalls, contextShift = defaultContextShiftOptions, customStopTriggers, abortOnNonText, lastEvaluationContextWindow: { history: lastEvaluationContextWindowHistory, minimumOverlapPercentageToPreventContextShift = 0.5 } = {} } = {}) {
|
|
839
|
+
this.llamaChat = llamaChat;
|
|
840
|
+
this.chatWrapper = chatWrapper;
|
|
841
|
+
this.history = history;
|
|
842
|
+
this.onTextChunk = safeEventCallback(onTextChunk);
|
|
843
|
+
this.onToken = safeEventCallback(onToken);
|
|
844
|
+
this.onResponseChunk = safeEventCallback(onResponseChunk);
|
|
845
|
+
this.onFunctionCallParamsChunk = safeEventCallback(onFunctionCallParamsChunk);
|
|
846
|
+
this.budgets = budgets;
|
|
847
|
+
this.signal = signal;
|
|
848
|
+
this.stopOnAbortSignal = stopOnAbortSignal;
|
|
849
|
+
this.maxTokens = maxTokens;
|
|
850
|
+
this.temperature = temperature;
|
|
851
|
+
this.minP = minP;
|
|
852
|
+
this.topK = topK;
|
|
853
|
+
this.topP = topP;
|
|
854
|
+
this.seed = seed;
|
|
855
|
+
this.xtc = xtc;
|
|
856
|
+
this.grammar = grammar;
|
|
857
|
+
this.trimWhitespaceSuffix = trimWhitespaceSuffix;
|
|
858
|
+
this.tokenBias = tokenBias;
|
|
859
|
+
this.evaluationPriority = evaluationPriority;
|
|
860
|
+
this.functions = functions;
|
|
861
|
+
this.onFunctionCall = safeEventCallback(onFunctionCall);
|
|
862
|
+
this.documentFunctionParams = documentFunctionParams;
|
|
863
|
+
this.maxParallelFunctionCalls = maxParallelFunctionCalls;
|
|
864
|
+
this.contextShift = contextShift;
|
|
865
|
+
this.customStopTriggers = customStopTriggers;
|
|
866
|
+
this.abortOnNonText = abortOnNonText ?? false;
|
|
867
|
+
this.minimumOverlapPercentageToPreventContextShift = minimumOverlapPercentageToPreventContextShift;
|
|
868
|
+
this.functionsEnabled = (this.functions != null && Object.keys(this.functions).length > 0);
|
|
869
|
+
if (this.signal?.aborted)
|
|
870
|
+
throw this.signal.reason;
|
|
871
|
+
if (this.llamaChat.disposed)
|
|
872
|
+
throw new DisposedError();
|
|
873
|
+
this.noRawInResolvedHistory = !this.llamaChat.sequence.isLoadedToMemory;
|
|
874
|
+
this.resolvedHistory = this.noRawInResolvedHistory
|
|
875
|
+
? this.history.map(removeRawFromHistoryItem)
|
|
876
|
+
: this.history.slice();
|
|
877
|
+
this.resolvedContextShift = {
|
|
878
|
+
...defaultContextShiftOptions,
|
|
879
|
+
...removeNullFields(this.contextShift)
|
|
880
|
+
};
|
|
881
|
+
this.resolvedRepeatPenalty = repeatPenalty === false
|
|
882
|
+
? { lastTokens: 0 }
|
|
883
|
+
: {
|
|
884
|
+
...(repeatPenalty ?? {}),
|
|
885
|
+
lastTokens: repeatPenalty?.lastTokens ?? defaultRepeatPenaltyLastTokens
|
|
886
|
+
};
|
|
887
|
+
this.repeatPenaltyEnabled = this.resolvedRepeatPenalty.lastTokens > 0;
|
|
888
|
+
this.dryRepeatPenalty = dryRepeatPenalty;
|
|
889
|
+
this.grammarEvaluationState = this.grammar != null
|
|
890
|
+
? new LlamaGrammarEvaluationState({ model: this.llamaChat.model, grammar: this.grammar })
|
|
891
|
+
: undefined;
|
|
892
|
+
this.functionNameGrammar = this.functionsEnabled
|
|
893
|
+
? new FunctionCallNameGrammar(this.llamaChat.model._llama, this.functions, this.chatWrapper)
|
|
894
|
+
: undefined;
|
|
895
|
+
this.functionsGrammar = undefined;
|
|
896
|
+
this.functionsEvaluationState = undefined;
|
|
897
|
+
this.lastContextWindowHistory = lastEvaluationContextWindowHistory ?? this.resolvedHistory;
|
|
898
|
+
this.lastHistoryCompressionMetadata = this.resolvedContextShift.lastEvaluationMetadata;
|
|
899
|
+
if (this.customStopTriggers != null)
|
|
900
|
+
StopGenerationDetector.resolveStopTriggers(this.customStopTriggers, this.llamaChat.model.tokenizer)
|
|
901
|
+
.map((stopTrigger) => this.customStopGenerationTriggersDetector.addStopTrigger(stopTrigger));
|
|
902
|
+
if (this.grammar != null)
|
|
903
|
+
StopGenerationDetector.resolveStopTriggers(this.grammar.stopGenerationTriggers, this.llamaChat.model.tokenizer)
|
|
904
|
+
.map((stopTrigger) => this.stopGenerationDetector.addStopTrigger(stopTrigger));
|
|
905
|
+
if (this.functions != null && Object.keys(this.functions).length > 0 && !this.abortOnNonText) {
|
|
906
|
+
for (const sectionPrefix of [
|
|
907
|
+
this.chatWrapper.settings.functions?.parallelism?.call?.sectionPrefix ?? "",
|
|
908
|
+
...(this.chatWrapper.settings.functions?.parallelism?.call.sectionPrefixAlternateMatches ?? [])
|
|
909
|
+
])
|
|
910
|
+
this.functionSyntaxStartDetector.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText([
|
|
911
|
+
sectionPrefix,
|
|
912
|
+
this.chatWrapper.settings.functions.call.prefix
|
|
913
|
+
]), this.llamaChat.model.tokenizer));
|
|
914
|
+
}
|
|
915
|
+
const segmentDefinitions = new Map();
|
|
916
|
+
for (const segmentType of allSegmentTypes) {
|
|
917
|
+
const segmentDefinition = getChatWrapperSegmentDefinition(this.chatWrapper.settings, segmentType);
|
|
918
|
+
if (segmentDefinition != null)
|
|
919
|
+
segmentDefinitions.set(segmentType, segmentDefinition);
|
|
920
|
+
}
|
|
921
|
+
const lastModelMessageFullResponse = getLastModelMessageFullResponseFromChatHistory(this.resolvedHistory);
|
|
922
|
+
this.segmentHandler = new SegmentHandler({
|
|
923
|
+
model: this.llamaChat.model,
|
|
924
|
+
onTextChunk: this.onTextChunk,
|
|
925
|
+
onToken: this.onToken,
|
|
926
|
+
onResponseChunk: this.onResponseChunk,
|
|
927
|
+
previousTokens: this.getLastTokens(),
|
|
928
|
+
closeAllSegments: this.chatWrapper.settings.segments?.closeAllSegments,
|
|
929
|
+
segmentDefinitions,
|
|
930
|
+
initialSegmentStack: SegmentHandler.getStackFromModelResponse(lastModelMessageFullResponse),
|
|
931
|
+
initialTokenCounts: this.budgets?.includeCurrentResponse === false
|
|
932
|
+
? new Map()
|
|
933
|
+
: SegmentHandler.getSegmentTokenCounts(lastModelMessageFullResponse, this.llamaChat.model.tokenizer)
|
|
934
|
+
});
|
|
935
|
+
if (this.abortOnNonText) {
|
|
936
|
+
for (const sectionPrefix of [
|
|
937
|
+
this.chatWrapper.settings.functions?.parallelism?.call?.sectionPrefix ?? "",
|
|
938
|
+
...(this.chatWrapper.settings.functions?.parallelism?.call.sectionPrefixAlternateMatches ?? [])
|
|
939
|
+
])
|
|
940
|
+
this.stopGenerationDetector.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText([
|
|
941
|
+
sectionPrefix,
|
|
942
|
+
this.chatWrapper.settings.functions.call.prefix
|
|
943
|
+
]), this.llamaChat.model.tokenizer));
|
|
944
|
+
for (const segmentType of allSegmentTypes) {
|
|
945
|
+
const segmentDefinition = getChatWrapperSegmentDefinition(this.chatWrapper.settings, segmentType);
|
|
946
|
+
if (segmentDefinition != null)
|
|
947
|
+
this.stopGenerationDetector.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText(segmentDefinition.prefix), this.llamaChat.model.tokenizer));
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
this.getPenaltyTokens = this.getPenaltyTokens.bind(this);
|
|
951
|
+
}
|
|
952
|
+
async dispose() {
|
|
953
|
+
await this.evaluationIterator?.return();
|
|
954
|
+
}
|
|
955
|
+
async [Symbol.asyncDispose]() {
|
|
956
|
+
await this.dispose();
|
|
957
|
+
}
|
|
958
|
+
ensureLastHistoryItemIsModel() {
|
|
959
|
+
if (this.resolvedHistory.at(-1)?.type !== "model")
|
|
960
|
+
this.resolvedHistory.push({
|
|
961
|
+
type: "model",
|
|
962
|
+
response: []
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
ensureLastHistoryItemIsUser() {
|
|
966
|
+
if (this.resolvedHistory.at(-1)?.type !== "user")
|
|
967
|
+
this.resolvedHistory.push({
|
|
968
|
+
type: "user",
|
|
969
|
+
text: ""
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
ensureReopenedThoughtSegmentAfterFunctionCallsIfNeeded() {
|
|
973
|
+
if (this.chatWrapper.settings.segments?.thought?.reopenAfterFunctionCalls !== true)
|
|
974
|
+
return;
|
|
975
|
+
const lastModelResponseItem = this.resolvedHistory.at(-1);
|
|
976
|
+
if (lastModelResponseItem == null || lastModelResponseItem.type !== "model")
|
|
977
|
+
return;
|
|
978
|
+
const lastResponse = lastModelResponseItem.response.at(-1);
|
|
979
|
+
if (lastResponse == null)
|
|
980
|
+
return;
|
|
981
|
+
const lastResponseIsFunctionCall = typeof lastResponse !== "string" && lastResponse.type === "functionCall";
|
|
982
|
+
if (!lastResponseIsFunctionCall)
|
|
983
|
+
return;
|
|
984
|
+
const currentResponseSegmentsStack = SegmentHandler.getStackFromModelResponse(lastModelResponseItem.response);
|
|
985
|
+
if (currentResponseSegmentsStack.includes("thought"))
|
|
986
|
+
return;
|
|
987
|
+
const hadThoughtSegments = this.resolvedHistory.some((chatItem) => {
|
|
988
|
+
if (chatItem.type !== "model")
|
|
989
|
+
return false;
|
|
990
|
+
return chatItem.response.some((responseItem) => {
|
|
991
|
+
if (typeof responseItem === "string")
|
|
992
|
+
return false;
|
|
993
|
+
return responseItem.type === "segment" && responseItem.segmentType === "thought";
|
|
994
|
+
});
|
|
995
|
+
});
|
|
996
|
+
if (!hadThoughtSegments)
|
|
997
|
+
return;
|
|
998
|
+
if (this.abortOnNonText)
|
|
999
|
+
this.shouldAbortBecauseOfNonText = true;
|
|
1000
|
+
else
|
|
1001
|
+
this.segmentHandler.openSegment("thought");
|
|
1002
|
+
}
|
|
1003
|
+
ensureNotAborted() {
|
|
1004
|
+
if (this.signal?.aborted && (!this.stopOnAbortSignal || this.res.length === 0))
|
|
1005
|
+
throw this.signal.reason;
|
|
1006
|
+
if (this.llamaChat.disposed)
|
|
1007
|
+
throw new DisposedError();
|
|
1008
|
+
}
|
|
1009
|
+
getPenaltyTokens() {
|
|
1010
|
+
if (this.llamaChat.disposed)
|
|
1011
|
+
return [];
|
|
1012
|
+
let punishTokens = this.res.slice(-this.resolvedRepeatPenalty.lastTokens);
|
|
1013
|
+
if (this.resolvedRepeatPenalty.punishTokensFilter != null)
|
|
1014
|
+
punishTokens = this.resolvedRepeatPenalty.punishTokensFilter(punishTokens);
|
|
1015
|
+
if (this.resolvedRepeatPenalty.penalizeNewLine == null || !this.resolvedRepeatPenalty.penalizeNewLine) {
|
|
1016
|
+
const nlToken = this.llamaChat.model.tokens.nl;
|
|
1017
|
+
if (nlToken != null)
|
|
1018
|
+
punishTokens = punishTokens.filter((token) => token !== nlToken);
|
|
1019
|
+
}
|
|
1020
|
+
return punishTokens;
|
|
1021
|
+
}
|
|
1022
|
+
getResolvedHistoryWithCurrentModelResponse() {
|
|
1023
|
+
return mergeGeneratedResultWithChatHistory("model", this.resolvedHistory, this.segmentHandler.getModelResponseSegments());
|
|
1024
|
+
}
|
|
1025
|
+
getContextWindowsHistoryWithCurrentModelResponse() {
|
|
1026
|
+
return mergeGeneratedResultWithChatHistory("model", this.lastContextWindowHistory, this.segmentHandler.getContextWindowModelResponseSegments());
|
|
1027
|
+
}
|
|
1028
|
+
removeFoundStartIgnoreTextsFromPendingTokens(forceRemove = false) {
|
|
1029
|
+
if (!this.removedStartTextToIgnore && this.res.length === 0 && this.pendingTokens.length > 0 &&
|
|
1030
|
+
this.ignoreStartTextDetector.hasTriggeredStops && (forceRemove || !this.ignoreStartTextDetector.hasInProgressStops)) {
|
|
1031
|
+
this.ignoreStartTextDetector.clearInProgressStops();
|
|
1032
|
+
this.ignoreStartTextDetector.clearTriggeredStops();
|
|
1033
|
+
let mostExhaustiveTriggeredStops = null;
|
|
1034
|
+
let mostExhaustiveTriggeredStopsLeftoverTokens = [];
|
|
1035
|
+
const lastTokensForDetokenizer = resolveLastTokens([
|
|
1036
|
+
this.contextWindowTokens,
|
|
1037
|
+
this.ignoredStartTextTokens,
|
|
1038
|
+
this.prefixTriggerTokens
|
|
1039
|
+
]);
|
|
1040
|
+
const pendingPartialTokens = [];
|
|
1041
|
+
for (let i = 0; i < this.pendingTokens.length; i++) {
|
|
1042
|
+
const currentToken = this.pendingTokens[i];
|
|
1043
|
+
const tokens = [...pendingPartialTokens, currentToken];
|
|
1044
|
+
const text = this.llamaChat.model.detokenize(tokens, false, lastTokensForDetokenizer);
|
|
1045
|
+
if (pendingPartialTokens.length === 0 &&
|
|
1046
|
+
text.endsWith(UNKNOWN_UNICODE_CHAR) &&
|
|
1047
|
+
!this.llamaChat.model.isSpecialToken(currentToken) &&
|
|
1048
|
+
!this.llamaChat.model.isEogToken(currentToken)) {
|
|
1049
|
+
pendingPartialTokens.length = 0;
|
|
1050
|
+
pushAll(pendingPartialTokens, tokens);
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
this.ignoreStartTextDetector.recordGeneration({
|
|
1054
|
+
text: this.llamaChat.model.detokenize(tokens, false, lastTokensForDetokenizer),
|
|
1055
|
+
tokens,
|
|
1056
|
+
startNewChecks: i === 0,
|
|
1057
|
+
triggerMustStartWithGeneration: true
|
|
1058
|
+
});
|
|
1059
|
+
pushAll(lastTokensForDetokenizer, tokens);
|
|
1060
|
+
if (this.ignoreStartTextDetector.hasTriggeredStops) {
|
|
1061
|
+
mostExhaustiveTriggeredStops = this.ignoreStartTextDetector.getTriggeredStops();
|
|
1062
|
+
this.ignoreStartTextDetector.clearTriggeredStops();
|
|
1063
|
+
mostExhaustiveTriggeredStopsLeftoverTokens = this.pendingTokens.slice(i + 1);
|
|
1064
|
+
}
|
|
1065
|
+
else if (!this.ignoreStartTextDetector.hasInProgressStops)
|
|
1066
|
+
break;
|
|
1067
|
+
}
|
|
1068
|
+
if (mostExhaustiveTriggeredStops != null) {
|
|
1069
|
+
const [mostExhaustiveTriggeredStop] = mostExhaustiveTriggeredStops;
|
|
1070
|
+
if (mostExhaustiveTriggeredStop != null) {
|
|
1071
|
+
this.ignoredStartTextTokens = mostExhaustiveTriggeredStop.stopTrigger
|
|
1072
|
+
.map((stopTrigger) => {
|
|
1073
|
+
if (typeof stopTrigger === "string")
|
|
1074
|
+
return this.llamaChat.model.tokenize(stopTrigger, false, "trimLeadingSpace");
|
|
1075
|
+
else
|
|
1076
|
+
return [stopTrigger];
|
|
1077
|
+
})
|
|
1078
|
+
.flat(1);
|
|
1079
|
+
const newPendingTokens = [
|
|
1080
|
+
...mostExhaustiveTriggeredStop.remainingGeneration,
|
|
1081
|
+
mostExhaustiveTriggeredStopsLeftoverTokens
|
|
1082
|
+
]
|
|
1083
|
+
.map((generation) => {
|
|
1084
|
+
if (typeof generation === "string")
|
|
1085
|
+
return this.llamaChat.model.tokenize(generation, false, "trimLeadingSpace");
|
|
1086
|
+
else
|
|
1087
|
+
return generation;
|
|
1088
|
+
})
|
|
1089
|
+
.flat(1);
|
|
1090
|
+
this.pendingTokens.length = 0;
|
|
1091
|
+
pushAll(this.pendingTokens, newPendingTokens);
|
|
1092
|
+
this.removedStartTextToIgnore = true;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
startTokenLoop() {
|
|
1098
|
+
this.ensureNotAborted();
|
|
1099
|
+
this.shouldContextShift = false;
|
|
1100
|
+
}
|
|
1101
|
+
handleRerender() {
|
|
1102
|
+
if (this.shouldRerender) {
|
|
1103
|
+
this.isRerender = true;
|
|
1104
|
+
this.streamRegulator.reset();
|
|
1105
|
+
if (this.rerenderActions === "closeResponseItem" && this.segmentHandler.topOpenSegmentType != null &&
|
|
1106
|
+
!this.skipClosingResponseItemOnRerender) {
|
|
1107
|
+
this.segmentHandler.closeSegment(this.segmentHandler.topOpenSegmentType);
|
|
1108
|
+
this.shouldRerender = false;
|
|
1109
|
+
}
|
|
1110
|
+
this.skipClosingResponseItemOnRerender = false;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
getContextWindowFunctionCallsTokens() {
|
|
1114
|
+
if (this.functionEvaluationMode === false)
|
|
1115
|
+
return [];
|
|
1116
|
+
else if (this.functionEvaluationMode === "prefixOrDisengage")
|
|
1117
|
+
return [
|
|
1118
|
+
...LlamaText(this.currentFunctionCallPreviousText).tokenize(this.llamaChat.model.tokenizer, "trimLeadingSpace"),
|
|
1119
|
+
...this.currentFunctionCallCurrentPartTokens
|
|
1120
|
+
];
|
|
1121
|
+
const text = [];
|
|
1122
|
+
if (this.chatWrapper.settings.functions?.parallelism?.call?.sectionPrefix != null)
|
|
1123
|
+
text.push(this.chatWrapper.settings.functions.parallelism.call.sectionPrefix);
|
|
1124
|
+
for (let i = 0; i < this.resFunctionCalls.length; i++) {
|
|
1125
|
+
const call = this.resFunctionCalls[i];
|
|
1126
|
+
if (i > 0)
|
|
1127
|
+
text.push(this.chatWrapper.settings.functions?.parallelism?.call?.betweenCalls ?? "");
|
|
1128
|
+
text.push(call.raw);
|
|
1129
|
+
}
|
|
1130
|
+
text.push(this.currentFunctionCallPreviousText);
|
|
1131
|
+
return [
|
|
1132
|
+
...LlamaText(text).tokenize(this.llamaChat.model.tokenizer, "trimLeadingSpace"),
|
|
1133
|
+
...this.currentFunctionCallCurrentPartTokens
|
|
1134
|
+
];
|
|
1135
|
+
}
|
|
1136
|
+
async loadContextWindow(resolvedHistory, resolvedContextWindowsHistory, endWithUserText = false, avoidReloadingHistory = false) {
|
|
1137
|
+
const queuedChunkTokens = this.streamRegulator.getAllQueuedChunkTokens();
|
|
1138
|
+
const functionCallsTokens = this.getContextWindowFunctionCallsTokens();
|
|
1139
|
+
if (!avoidReloadingHistory || !this.canAvoidReloadingHistory || this.isRerender || !this.llamaChat.sequence.isLoadedToMemory) {
|
|
1140
|
+
const { history: contextWindowHistory, stopGenerationTriggers, tokens: contextWindowTokens, removeRawFromHistory, newHistoryCompressionMetadata, ignoreStartText, functionCallInitiallyEngaged, disengageInitiallyEngagedFunctionCall, userTextSuffix, prefixTriggers, noPrefixTrigger, rerender, detectFunctionCalls } = await getContextWindow({
|
|
1141
|
+
resolvedHistory: resolvedHistory,
|
|
1142
|
+
resolvedContextShift: this.resolvedContextShift,
|
|
1143
|
+
lastHistoryCompressionMetadata: this.lastHistoryCompressionMetadata,
|
|
1144
|
+
pendingTokensCount: this.prefixTriggerTokens.length + this.pendingTokens.length + queuedChunkTokens.length +
|
|
1145
|
+
functionCallsTokens.length + this.pendingPartialTokens.length,
|
|
1146
|
+
isFirstEvaluation: this.isFirstEvaluation,
|
|
1147
|
+
isRerender: this.isRerender,
|
|
1148
|
+
chatWrapper: this.chatWrapper,
|
|
1149
|
+
lastEvaluationContextWindowHistory: resolvedContextWindowsHistory,
|
|
1150
|
+
minimumOverlapPercentageToPreventContextShift: this.minimumOverlapPercentageToPreventContextShift,
|
|
1151
|
+
sequence: this.llamaChat.sequence,
|
|
1152
|
+
minFreeContextTokens: 1,
|
|
1153
|
+
functions: this.functionsEnabled ? this.functions : undefined,
|
|
1154
|
+
documentFunctionParams: this.documentFunctionParams,
|
|
1155
|
+
endWithUserText
|
|
1156
|
+
});
|
|
1157
|
+
this.ensureNotAborted();
|
|
1158
|
+
this.contextWindowTokens = contextWindowTokens;
|
|
1159
|
+
this.stopGenerationTriggers = stopGenerationTriggers;
|
|
1160
|
+
this.ignoreStartText = ignoreStartText;
|
|
1161
|
+
this.functionCallInitiallyEngaged = functionCallInitiallyEngaged;
|
|
1162
|
+
this.disengageInitiallyEngagedFunctionCall = disengageInitiallyEngagedFunctionCall;
|
|
1163
|
+
this.userTextSuffix = userTextSuffix;
|
|
1164
|
+
if (this.isRerender) {
|
|
1165
|
+
this.prefixTriggerTokens.length = 0;
|
|
1166
|
+
for (const prefixDetector of this.prefixTriggerDetectors.keys()) {
|
|
1167
|
+
prefixDetector.clearInProgressStops();
|
|
1168
|
+
prefixDetector.clearTriggeredStops();
|
|
1169
|
+
}
|
|
1170
|
+
this.prefixTriggerDetectors.clear();
|
|
1171
|
+
for (const trigger of prefixTriggers ?? []) {
|
|
1172
|
+
const segmentBudget = trigger.type === "segment"
|
|
1173
|
+
? this.getSegmentBudget(trigger.segmentType)
|
|
1174
|
+
: null;
|
|
1175
|
+
if (trigger.type === "functionCall" && !this.functionsEnabled)
|
|
1176
|
+
continue;
|
|
1177
|
+
else if (trigger.type === "segment" &&
|
|
1178
|
+
segmentBudget != null &&
|
|
1179
|
+
!this.segmentHandler.isSegmentTypeOpen(trigger.segmentType) &&
|
|
1180
|
+
this.segmentHandler.getSegmentTokensCount(trigger.segmentType) >= segmentBudget)
|
|
1181
|
+
continue;
|
|
1182
|
+
if (this.responsePrefix == null && trigger.type === "response" && trigger.triggers.length > 0 &&
|
|
1183
|
+
(trigger.triggers[0]?.values?.length ?? 0) > 0)
|
|
1184
|
+
this.responsePrefix = LlamaText([trigger.triggers[0] ?? "", trigger.inject ?? ""]);
|
|
1185
|
+
const prefixDetector = new StopGenerationDetector();
|
|
1186
|
+
StopGenerationDetector.resolveStopTriggers(trigger.triggers, this.llamaChat.model.tokenizer)
|
|
1187
|
+
.forEach((stopTrigger) => prefixDetector.addStopTrigger(stopTrigger));
|
|
1188
|
+
this.prefixTriggerDetectors.set(prefixDetector, { inject: trigger.inject, trigger });
|
|
1189
|
+
const inject = trigger.inject;
|
|
1190
|
+
if (inject != null && inject.values.length > 0) {
|
|
1191
|
+
const fullPrefixDetector = new StopGenerationDetector();
|
|
1192
|
+
StopGenerationDetector
|
|
1193
|
+
.resolveStopTriggers(trigger.triggers.map((trigger) => LlamaText([trigger, inject])), this.llamaChat.model.tokenizer)
|
|
1194
|
+
.forEach((stopTrigger) => fullPrefixDetector.addStopTrigger(stopTrigger));
|
|
1195
|
+
this.prefixTriggerDetectors.set(fullPrefixDetector, { trigger });
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
this.noPrefixTrigger = noPrefixTrigger;
|
|
1199
|
+
const noPrefixTriggerSegmentBudget = noPrefixTrigger?.type === "segment"
|
|
1200
|
+
? this.getSegmentBudget(noPrefixTrigger.segmentType)
|
|
1201
|
+
: null;
|
|
1202
|
+
if (this.noPrefixTrigger?.type === "functionCall" && !this.functionsEnabled)
|
|
1203
|
+
this.noPrefixTrigger = undefined;
|
|
1204
|
+
else if (noPrefixTrigger?.type === "segment" &&
|
|
1205
|
+
noPrefixTriggerSegmentBudget != null &&
|
|
1206
|
+
!this.segmentHandler.isSegmentTypeOpen(noPrefixTrigger.segmentType) &&
|
|
1207
|
+
this.segmentHandler.getSegmentTokensCount(noPrefixTrigger.segmentType) >= noPrefixTriggerSegmentBudget)
|
|
1208
|
+
this.noPrefixTrigger = undefined;
|
|
1209
|
+
else if (noPrefixTrigger?.type === "response")
|
|
1210
|
+
this.responsePrefix = noPrefixTrigger.inject;
|
|
1211
|
+
this.rerenderTriggers = rerender?.triggers ?? [];
|
|
1212
|
+
this.rerenderTriggerDetector.clearInProgressStops();
|
|
1213
|
+
this.rerenderTriggerDetector.clearTriggeredStops();
|
|
1214
|
+
this.rerenderTriggerDetector = new StopGenerationDetector();
|
|
1215
|
+
this.rerenderActions = rerender?.action;
|
|
1216
|
+
this.functionSyntaxStartDetectorEnabled = detectFunctionCalls ?? true;
|
|
1217
|
+
if (!this.functionSyntaxStartDetectorEnabled)
|
|
1218
|
+
this.functionSyntaxStartDetector.clearInProgressStops();
|
|
1219
|
+
if (rerender?.triggers != null) {
|
|
1220
|
+
StopGenerationDetector.resolveStopTriggers(rerender.triggers, this.llamaChat.model.tokenizer)
|
|
1221
|
+
.map((stopTrigger) => this.rerenderTriggerDetector.addStopTrigger(stopTrigger));
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
this.lastHistoryCompressionMetadata = newHistoryCompressionMetadata;
|
|
1225
|
+
this.lastContextWindowHistory = contextWindowHistory;
|
|
1226
|
+
this.segmentHandler.resetContextWindow();
|
|
1227
|
+
this.canAvoidReloadingHistory = true;
|
|
1228
|
+
if (removeRawFromHistory && !this.noRawInResolvedHistory) {
|
|
1229
|
+
this.noRawInResolvedHistory = true;
|
|
1230
|
+
this.resolvedHistory = this.resolvedHistory.map(removeRawFromHistoryItem);
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
this.tokens = [
|
|
1234
|
+
...this.contextWindowTokens,
|
|
1235
|
+
...this.ignoredStartTextTokens,
|
|
1236
|
+
...this.prefixTriggerTokens,
|
|
1237
|
+
...this.pendingTokens,
|
|
1238
|
+
...queuedChunkTokens,
|
|
1239
|
+
...functionCallsTokens,
|
|
1240
|
+
...this.pendingPartialTokens
|
|
1241
|
+
];
|
|
1242
|
+
if (avoidReloadingHistory && this.tokens.length >= this.llamaChat.sequence.context.contextSize - 1)
|
|
1243
|
+
return await this.loadContextWindow(resolvedHistory, resolvedContextWindowsHistory, endWithUserText, false);
|
|
1244
|
+
return {
|
|
1245
|
+
userTextSuffix: this.userTextSuffix
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
addIgnoreStartTextTriggersFromChatWrapper() {
|
|
1249
|
+
StopGenerationDetector.resolveStopTriggers(this.ignoreStartText, this.llamaChat.model.tokenizer)
|
|
1250
|
+
.map((stopTrigger) => this.ignoreStartTextDetector.addStopTrigger(stopTrigger));
|
|
1251
|
+
}
|
|
1252
|
+
addStopGenerationTriggersFromChatWrapper() {
|
|
1253
|
+
StopGenerationDetector.resolveStopTriggers(this.stopGenerationTriggers, this.llamaChat.model.tokenizer)
|
|
1254
|
+
.map((stopTrigger) => this.stopGenerationDetector.addStopTrigger(stopTrigger));
|
|
1255
|
+
}
|
|
1256
|
+
initFunctions() {
|
|
1257
|
+
this.initiallyEngagedFunctionMode = this.functionCallInitiallyEngaged;
|
|
1258
|
+
if (this.initiallyEngagedFunctionMode && this.abortOnNonText) {
|
|
1259
|
+
this.shouldAbortBecauseOfNonText = true;
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
if (this.initiallyEngagedFunctionMode) {
|
|
1263
|
+
StopGenerationDetector.resolveStopTriggers(this.disengageInitiallyEngagedFunctionCall, this.llamaChat.model.tokenizer)
|
|
1264
|
+
.map((stopTrigger) => this.disengageInitiallyEngagedFunctionMode.addStopTrigger(stopTrigger));
|
|
1265
|
+
if (this.disengageInitiallyEngagedFunctionMode.hasTriggers) {
|
|
1266
|
+
this.functionEvaluationMode = "prefixOrDisengage";
|
|
1267
|
+
this.functionsGrammar = undefined;
|
|
1268
|
+
this.functionsEvaluationState = undefined;
|
|
1269
|
+
}
|
|
1270
|
+
else {
|
|
1271
|
+
this.functionEvaluationMode = "functionName";
|
|
1272
|
+
}
|
|
1273
|
+
this.restartEvaluationIterator = true;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
async handlePrefixTriggers(loadContextWindow) {
|
|
1277
|
+
const reloadTokens = async () => {
|
|
1278
|
+
this.startTokenLoop();
|
|
1279
|
+
await loadContextWindow();
|
|
1280
|
+
};
|
|
1281
|
+
const injectTokens = async (text, alignStateTokens = false) => {
|
|
1282
|
+
if (text == null)
|
|
1283
|
+
return;
|
|
1284
|
+
const tokens = text.tokenize(this.llamaChat.model.tokenizer, "trimLeadingSpace");
|
|
1285
|
+
if (tokens.length === 0)
|
|
1286
|
+
return;
|
|
1287
|
+
pushAll(this.prefixTriggerTokens, tokens);
|
|
1288
|
+
if (alignStateTokens)
|
|
1289
|
+
await reloadTokens();
|
|
1290
|
+
};
|
|
1291
|
+
if (this.grammar != null) {
|
|
1292
|
+
if (this.responsePrefix != null)
|
|
1293
|
+
await injectTokens(this.responsePrefix, true);
|
|
1294
|
+
return undefined;
|
|
1295
|
+
}
|
|
1296
|
+
if (this.prefixTriggerDetectors.size === 0) {
|
|
1297
|
+
if (this.abortOnNonText && this.noPrefixTrigger != null && this.noPrefixTrigger.type !== "response") {
|
|
1298
|
+
this.shouldAbortBecauseOfNonText = true;
|
|
1299
|
+
const stopRes = this.handleAbortTrigger("model");
|
|
1300
|
+
if (stopRes != null)
|
|
1301
|
+
return stopRes;
|
|
1302
|
+
return undefined;
|
|
1303
|
+
}
|
|
1304
|
+
if (this.noPrefixTrigger?.type === "functionCall" && this.chatWrapper.settings.functions != null) {
|
|
1305
|
+
await injectTokens(this.noPrefixTrigger.inject, true);
|
|
1306
|
+
this.functionEvaluationMode = "functionName";
|
|
1307
|
+
}
|
|
1308
|
+
else if (this.noPrefixTrigger?.type === "segment") {
|
|
1309
|
+
await injectTokens(this.noPrefixTrigger.inject, true);
|
|
1310
|
+
this.segmentHandler.openSegment(this.noPrefixTrigger.segmentType);
|
|
1311
|
+
}
|
|
1312
|
+
else if (this.noPrefixTrigger?.type === "response")
|
|
1313
|
+
await injectTokens(this.noPrefixTrigger.inject, true);
|
|
1314
|
+
return undefined;
|
|
1315
|
+
}
|
|
1316
|
+
const generatedTokens = [];
|
|
1317
|
+
let isFirstToken = true;
|
|
1318
|
+
let continueGeneration = true;
|
|
1319
|
+
let tookInitialCheckpoint = false;
|
|
1320
|
+
for await (const tokens of this.evaluateWithContextShift(loadContextWindow)) {
|
|
1321
|
+
if (!tookInitialCheckpoint && this.llamaChat.sequence.needsCheckpoints) {
|
|
1322
|
+
await this.llamaChat.sequence._takeNamedCheckpoint(internalCheckpoints.chatSequenceStart.name, internalCheckpoints.chatSequenceStart.maxCheckpoints);
|
|
1323
|
+
tookInitialCheckpoint = true;
|
|
1324
|
+
}
|
|
1325
|
+
pushAll(generatedTokens, tokens);
|
|
1326
|
+
for (const [triggerDetector, { trigger, inject }] of [...this.prefixTriggerDetectors.entries()]) {
|
|
1327
|
+
triggerDetector.recordGeneration({
|
|
1328
|
+
text: this.currentText,
|
|
1329
|
+
tokens: this.currentTokens,
|
|
1330
|
+
startNewChecks: isFirstToken,
|
|
1331
|
+
triggerMustStartWithGeneration: true
|
|
1332
|
+
});
|
|
1333
|
+
if (triggerDetector.hasTriggeredStops) {
|
|
1334
|
+
const { firstRemainingGenerationAfterStop, stopTrigger } = StopGenerationDetector.getFirstRemainingGenerationAfterStop(triggerDetector.getTriggeredStops());
|
|
1335
|
+
const remainingTokens = typeof firstRemainingGenerationAfterStop === "string"
|
|
1336
|
+
? firstRemainingGenerationAfterStop === ""
|
|
1337
|
+
? []
|
|
1338
|
+
: this.llamaChat.model.tokenize(firstRemainingGenerationAfterStop, false, "trimLeadingSpace")
|
|
1339
|
+
: (firstRemainingGenerationAfterStop ?? []);
|
|
1340
|
+
const triggerTokens = (stopTrigger == null || remainingTokens.length === 0)
|
|
1341
|
+
? generatedTokens
|
|
1342
|
+
: stopTrigger.flatMap((item) => {
|
|
1343
|
+
if (typeof item === "string")
|
|
1344
|
+
return this.llamaChat.model.tokenize(item, false, "trimLeadingSpace");
|
|
1345
|
+
return [item];
|
|
1346
|
+
});
|
|
1347
|
+
if (this.abortOnNonText && trigger.type !== "response") {
|
|
1348
|
+
this.shouldAbortBecauseOfNonText = true;
|
|
1349
|
+
const stopRes = this.handleAbortTrigger("model");
|
|
1350
|
+
if (stopRes != null)
|
|
1351
|
+
return stopRes;
|
|
1352
|
+
return undefined;
|
|
1353
|
+
}
|
|
1354
|
+
this.streamRegulator.reset();
|
|
1355
|
+
if (trigger.type === "segment") {
|
|
1356
|
+
pushAll(this.prefixTriggerTokens, triggerTokens);
|
|
1357
|
+
if (inject != null)
|
|
1358
|
+
await injectTokens(inject);
|
|
1359
|
+
await reloadTokens();
|
|
1360
|
+
this.segmentHandler.openSegment(trigger.segmentType);
|
|
1361
|
+
}
|
|
1362
|
+
else if (trigger.type === "response") {
|
|
1363
|
+
pushAll(this.prefixTriggerTokens, triggerTokens);
|
|
1364
|
+
if (inject != null)
|
|
1365
|
+
await injectTokens(inject);
|
|
1366
|
+
await reloadTokens();
|
|
1367
|
+
}
|
|
1368
|
+
else if (trigger.type === "functionCall") {
|
|
1369
|
+
if (trigger.replaceTrigger === false)
|
|
1370
|
+
pushAll(this.prefixTriggerTokens, triggerTokens);
|
|
1371
|
+
if (inject != null)
|
|
1372
|
+
await injectTokens(inject);
|
|
1373
|
+
await reloadTokens();
|
|
1374
|
+
this.functionEvaluationMode = "functionName";
|
|
1375
|
+
}
|
|
1376
|
+
else
|
|
1377
|
+
void trigger;
|
|
1378
|
+
this.prefixTriggerDetectors.clear();
|
|
1379
|
+
continueGeneration = false;
|
|
1380
|
+
break;
|
|
1381
|
+
}
|
|
1382
|
+
else if (!triggerDetector.hasInProgressStops)
|
|
1383
|
+
this.prefixTriggerDetectors.delete(triggerDetector);
|
|
1384
|
+
}
|
|
1385
|
+
if (this.prefixTriggerDetectors.size === 0 && continueGeneration) {
|
|
1386
|
+
if (this.abortOnNonText && this.noPrefixTrigger != null && this.noPrefixTrigger.type !== "response") {
|
|
1387
|
+
this.shouldAbortBecauseOfNonText = true;
|
|
1388
|
+
const stopRes = this.handleAbortTrigger("model");
|
|
1389
|
+
if (stopRes != null)
|
|
1390
|
+
return stopRes;
|
|
1391
|
+
return undefined;
|
|
1392
|
+
}
|
|
1393
|
+
this.streamRegulator.reset();
|
|
1394
|
+
continueGeneration = false;
|
|
1395
|
+
if (this.noPrefixTrigger?.type === "functionCall" && this.chatWrapper.settings.functions != null) {
|
|
1396
|
+
await injectTokens(this.noPrefixTrigger.inject, true);
|
|
1397
|
+
this.functionEvaluationMode = "functionName";
|
|
1398
|
+
}
|
|
1399
|
+
else if (this.noPrefixTrigger?.type === "segment") {
|
|
1400
|
+
await injectTokens(this.noPrefixTrigger.inject, true);
|
|
1401
|
+
this.segmentHandler.openSegment(this.noPrefixTrigger.segmentType);
|
|
1402
|
+
}
|
|
1403
|
+
else if (this.noPrefixTrigger?.type === "response")
|
|
1404
|
+
await injectTokens(this.noPrefixTrigger.inject, true);
|
|
1405
|
+
else
|
|
1406
|
+
this.streamRegulator.addChunk({
|
|
1407
|
+
tokens: generatedTokens,
|
|
1408
|
+
text: this.llamaChat.model.detokenize(generatedTokens, false, this.getLastTokens())
|
|
1409
|
+
});
|
|
1410
|
+
}
|
|
1411
|
+
isFirstToken = false;
|
|
1412
|
+
if (!continueGeneration)
|
|
1413
|
+
break;
|
|
1414
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1415
|
+
if (stopRes != null)
|
|
1416
|
+
return stopRes;
|
|
1417
|
+
}
|
|
1418
|
+
return undefined;
|
|
1419
|
+
}
|
|
1420
|
+
async enterFunctionCallingLoop(loadContextWindow) {
|
|
1421
|
+
if (!this.functionsEnabled) {
|
|
1422
|
+
this.functionEvaluationMode = false;
|
|
1423
|
+
return undefined;
|
|
1424
|
+
}
|
|
1425
|
+
while (true) {
|
|
1426
|
+
if (this.functionEvaluationMode === "prefixOrDisengage") {
|
|
1427
|
+
this.functionsGrammar = undefined;
|
|
1428
|
+
this.functionsEvaluationState = undefined;
|
|
1429
|
+
this.currentFunctionCallPreviousText = LlamaText([]);
|
|
1430
|
+
this.currentFunctionCallCurrentPartTokens.length = 0;
|
|
1431
|
+
const prefixTokens = LlamaText(this.chatWrapper.settings.functions.call.prefix)
|
|
1432
|
+
.tokenize(this.llamaChat.model.tokenizer, "trimLeadingSpace");
|
|
1433
|
+
const prefixDetector = new StopGenerationDetector();
|
|
1434
|
+
const prefixDetectorRecordedTokens = [];
|
|
1435
|
+
const afterPrefixLeftoverTokens = [];
|
|
1436
|
+
prefixDetector.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText(this.chatWrapper.settings.functions.call.prefix), this.llamaChat.model.tokenizer));
|
|
1437
|
+
const lastTokensForDetokenizer = this.streamRegulator.getLastQueuedChunkTokens();
|
|
1438
|
+
for (const prefixToken of prefixTokens) {
|
|
1439
|
+
const tokens = [prefixToken];
|
|
1440
|
+
const text = this.llamaChat.model.detokenize(tokens, false, lastTokensForDetokenizer);
|
|
1441
|
+
pushAll(lastTokensForDetokenizer, tokens);
|
|
1442
|
+
const disregardedPossibilities = this.disengageInitiallyEngagedFunctionMode
|
|
1443
|
+
.getDisregardedPossibilitiesCountForAGeneration({
|
|
1444
|
+
text,
|
|
1445
|
+
tokens,
|
|
1446
|
+
startNewChecks: this.currentFunctionCallCurrentPartTokens.length === 0
|
|
1447
|
+
});
|
|
1448
|
+
if (disregardedPossibilities > 0)
|
|
1449
|
+
break;
|
|
1450
|
+
this.currentFunctionCallCurrentPartTokens.push(prefixToken);
|
|
1451
|
+
this.disengageInitiallyEngagedFunctionMode.recordGeneration({
|
|
1452
|
+
text: text,
|
|
1453
|
+
tokens: tokens,
|
|
1454
|
+
startNewChecks: this.currentFunctionCallCurrentPartTokens.length === 1,
|
|
1455
|
+
triggerMustStartWithGeneration: true
|
|
1456
|
+
});
|
|
1457
|
+
if (prefixDetector.hasTriggeredStops)
|
|
1458
|
+
afterPrefixLeftoverTokens.push(prefixToken);
|
|
1459
|
+
else {
|
|
1460
|
+
prefixDetector.recordGeneration({
|
|
1461
|
+
text: text,
|
|
1462
|
+
tokens: tokens,
|
|
1463
|
+
startNewChecks: this.currentFunctionCallCurrentPartTokens.length === 1,
|
|
1464
|
+
triggerMustStartWithGeneration: true
|
|
1465
|
+
});
|
|
1466
|
+
pushAll(prefixDetectorRecordedTokens, tokens);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
let tookInitialCheckpoint = false;
|
|
1470
|
+
for await (const tokens of this.evaluateWithContextShift(loadContextWindow)) {
|
|
1471
|
+
if (!tookInitialCheckpoint && this.llamaChat.sequence.needsCheckpoints) {
|
|
1472
|
+
await this.llamaChat.sequence._takeNamedCheckpoint(internalCheckpoints.chatSequenceStart.name, internalCheckpoints.chatSequenceStart.maxCheckpoints);
|
|
1473
|
+
tookInitialCheckpoint = true;
|
|
1474
|
+
}
|
|
1475
|
+
const stopGenerationTriggerRes = this.handleStopGenerationTrigger("model");
|
|
1476
|
+
if (stopGenerationTriggerRes != null)
|
|
1477
|
+
return stopGenerationTriggerRes;
|
|
1478
|
+
pushAll(this.currentFunctionCallCurrentPartTokens, tokens);
|
|
1479
|
+
this.disengageInitiallyEngagedFunctionMode.recordGeneration({
|
|
1480
|
+
text: this.currentText,
|
|
1481
|
+
tokens: this.currentTokens,
|
|
1482
|
+
startNewChecks: this.currentFunctionCallCurrentPartTokens.length === tokens.length,
|
|
1483
|
+
triggerMustStartWithGeneration: true
|
|
1484
|
+
});
|
|
1485
|
+
if (prefixDetector.hasTriggeredStops)
|
|
1486
|
+
pushAll(afterPrefixLeftoverTokens, tokens);
|
|
1487
|
+
else {
|
|
1488
|
+
prefixDetector.recordGeneration({
|
|
1489
|
+
text: this.currentText,
|
|
1490
|
+
tokens: this.currentTokens,
|
|
1491
|
+
startNewChecks: this.currentFunctionCallCurrentPartTokens.length === tokens.length,
|
|
1492
|
+
triggerMustStartWithGeneration: true
|
|
1493
|
+
});
|
|
1494
|
+
pushAll(prefixDetectorRecordedTokens, this.currentTokens);
|
|
1495
|
+
}
|
|
1496
|
+
if (this.disengageInitiallyEngagedFunctionMode.hasTriggeredStops ||
|
|
1497
|
+
!this.disengageInitiallyEngagedFunctionMode.hasInProgressStops)
|
|
1498
|
+
break;
|
|
1499
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1500
|
+
if (stopRes != null)
|
|
1501
|
+
return stopRes;
|
|
1502
|
+
}
|
|
1503
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1504
|
+
if (stopRes != null)
|
|
1505
|
+
return stopRes;
|
|
1506
|
+
if (this.disengageInitiallyEngagedFunctionMode.hasTriggeredStops) {
|
|
1507
|
+
const lastTokensForDetokenizer = this.streamRegulator.getLastQueuedChunkTokens();
|
|
1508
|
+
for (const token of this.currentFunctionCallCurrentPartTokens) {
|
|
1509
|
+
this.currentToken = token;
|
|
1510
|
+
this.currentTokens = [this.currentToken];
|
|
1511
|
+
this.currentText = this.llamaChat.model.detokenize(this.currentTokens, false, lastTokensForDetokenizer);
|
|
1512
|
+
pushAll(lastTokensForDetokenizer, this.currentTokens);
|
|
1513
|
+
this.currentQueuedTokenRelease = this.streamRegulator.addChunk({
|
|
1514
|
+
tokens: this.currentTokens,
|
|
1515
|
+
text: this.currentText
|
|
1516
|
+
});
|
|
1517
|
+
{
|
|
1518
|
+
const resPromise = this.recordStopGenerationEvaluation();
|
|
1519
|
+
if (resPromise instanceof Promise)
|
|
1520
|
+
await resPromise;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
this.currentFunctionCallCurrentPartTokens.length = 0;
|
|
1524
|
+
this.functionEvaluationMode = false;
|
|
1525
|
+
return undefined;
|
|
1526
|
+
}
|
|
1527
|
+
if (prefixDetector.hasTriggeredStops) {
|
|
1528
|
+
const triggeredStops = prefixDetector.getTriggeredStops();
|
|
1529
|
+
const { firstRemainingGenerationAfterStop, stopTrigger } = StopGenerationDetector.getFirstRemainingGenerationAfterStop(triggeredStops);
|
|
1530
|
+
this.currentFunctionCallPreviousPartLeftoverText = StopGenerationDetector.detokenizeRemainingGeneration(firstRemainingGenerationAfterStop, stopTrigger, this.llamaChat.model.tokenizer) + this.llamaChat.model.detokenize(afterPrefixLeftoverTokens, false, prefixDetectorRecordedTokens);
|
|
1531
|
+
}
|
|
1532
|
+
else
|
|
1533
|
+
this.currentFunctionCallPreviousPartLeftoverText = "";
|
|
1534
|
+
this.functionEvaluationMode = "functionName";
|
|
1535
|
+
this.currentFunctionCallCurrentPartTokens.length = 0;
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
else if (this.functionEvaluationMode === "functionName") {
|
|
1539
|
+
const functionNameGenerationDoneDetector = new StopGenerationDetector();
|
|
1540
|
+
this.stopGenerationDetector.clearInProgressStops();
|
|
1541
|
+
this.customStopGenerationTriggersDetector.clearInProgressStops();
|
|
1542
|
+
this.currentFunctionCallPreviousText = LlamaText(this.chatWrapper.settings.functions.call.prefix);
|
|
1543
|
+
this.currentFunctionCallCurrentPartTokens.length = 0;
|
|
1544
|
+
const functionNameGrammar = this.functionNameGrammar ?? new FunctionCallNameGrammar(this.llamaChat.model._llama, this.functions, this.chatWrapper);
|
|
1545
|
+
this.functionsGrammar = functionNameGrammar;
|
|
1546
|
+
this.functionsEvaluationState = new LlamaGrammarEvaluationState({
|
|
1547
|
+
model: this.llamaChat.model,
|
|
1548
|
+
grammar: this.functionsGrammar
|
|
1549
|
+
});
|
|
1550
|
+
StopGenerationDetector.resolveStopTriggers(this.functionsGrammar.stopGenerationTriggers, this.llamaChat.model.tokenizer)
|
|
1551
|
+
.map((stopTrigger) => functionNameGenerationDoneDetector.addStopTrigger(stopTrigger));
|
|
1552
|
+
if (this.currentFunctionCallPreviousPartLeftoverText !== "") {
|
|
1553
|
+
const validFunctionNames = Object.keys(this.functions);
|
|
1554
|
+
const hasAnyFunctionStartWithLeftover = validFunctionNames.some((functionName) => functionName.startsWith(this.currentFunctionCallPreviousPartLeftoverText));
|
|
1555
|
+
if (hasAnyFunctionStartWithLeftover) {
|
|
1556
|
+
const leftoverTokens = this.llamaChat.model.tokenize(this.currentFunctionCallPreviousPartLeftoverText, false, "trimLeadingSpace");
|
|
1557
|
+
this.currentFunctionCallPreviousPartLeftoverText = "";
|
|
1558
|
+
const lastTokens = [];
|
|
1559
|
+
for (const leftoverToken of leftoverTokens) {
|
|
1560
|
+
const canBeNextToken = LlamaSampler._canBeNextTokenForGrammarEvaluationState(this.llamaChat.model._llama, this.functionsEvaluationState, leftoverToken);
|
|
1561
|
+
if (!canBeNextToken)
|
|
1562
|
+
break;
|
|
1563
|
+
LlamaSampler._acceptTokenOnGrammarEvaluationState(this.llamaChat.model._llama, this.functionsEvaluationState, leftoverToken);
|
|
1564
|
+
this.currentFunctionCallCurrentPartTokens.push(leftoverToken);
|
|
1565
|
+
functionNameGenerationDoneDetector.recordGeneration({
|
|
1566
|
+
text: this.llamaChat.model.detokenize([leftoverToken], false, lastTokens),
|
|
1567
|
+
tokens: [leftoverToken]
|
|
1568
|
+
});
|
|
1569
|
+
lastTokens.push(leftoverToken);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
let tookInitialCheckpoint = false;
|
|
1574
|
+
for await (const tokens of this.evaluateWithContextShift(loadContextWindow)) {
|
|
1575
|
+
if (!tookInitialCheckpoint && this.llamaChat.sequence.needsCheckpoints) {
|
|
1576
|
+
await this.llamaChat.sequence._takeNamedCheckpoint(internalCheckpoints.chatSequenceStart.name, internalCheckpoints.chatSequenceStart.maxCheckpoints);
|
|
1577
|
+
tookInitialCheckpoint = true;
|
|
1578
|
+
}
|
|
1579
|
+
pushAll(this.currentFunctionCallCurrentPartTokens, tokens);
|
|
1580
|
+
functionNameGenerationDoneDetector.recordGeneration({
|
|
1581
|
+
text: this.currentText,
|
|
1582
|
+
tokens: this.currentTokens
|
|
1583
|
+
});
|
|
1584
|
+
if (functionNameGenerationDoneDetector.hasTriggeredStops)
|
|
1585
|
+
break;
|
|
1586
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1587
|
+
if (stopRes != null)
|
|
1588
|
+
return stopRes;
|
|
1589
|
+
}
|
|
1590
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1591
|
+
if (stopRes != null)
|
|
1592
|
+
return stopRes;
|
|
1593
|
+
const functionCallNameText = this.llamaChat.model.detokenize(this.currentFunctionCallCurrentPartTokens);
|
|
1594
|
+
const functionName = functionNameGrammar.parseFunctionName(functionCallNameText);
|
|
1595
|
+
this.functionEvaluationFunctionName = functionName;
|
|
1596
|
+
this.functionEvaluationMode = "params";
|
|
1597
|
+
continue;
|
|
1598
|
+
}
|
|
1599
|
+
else if (this.functionEvaluationMode === "params") {
|
|
1600
|
+
this.currentFunctionCallPreviousText = LlamaText([
|
|
1601
|
+
this.chatWrapper.settings.functions.call.prefix,
|
|
1602
|
+
this.functionEvaluationFunctionName,
|
|
1603
|
+
this.chatWrapper.settings.functions.call.paramsPrefix
|
|
1604
|
+
]);
|
|
1605
|
+
const lastPartTokens = resolveLastTokens([this.currentFunctionCallCurrentPartTokens]);
|
|
1606
|
+
this.currentFunctionCallCurrentPartTokens.length = 0;
|
|
1607
|
+
let params = undefined;
|
|
1608
|
+
let paramsText = "";
|
|
1609
|
+
const functionDefinition = this.functions[this.functionEvaluationFunctionName];
|
|
1610
|
+
if (functionDefinition == null)
|
|
1611
|
+
throw new Error(`Function "${this.functionEvaluationFunctionName}" is not provided in the functions object`);
|
|
1612
|
+
else if (functionDefinition.params == null) {
|
|
1613
|
+
const emptyCallParamsPlaceholder = this.chatWrapper.settings?.functions?.call?.emptyCallParamsPlaceholder;
|
|
1614
|
+
if (emptyCallParamsPlaceholder !== undefined && emptyCallParamsPlaceholder !== "") {
|
|
1615
|
+
params = structuredClone(emptyCallParamsPlaceholder);
|
|
1616
|
+
paramsText = jsonDumps(params);
|
|
1617
|
+
pushAll(this.currentFunctionCallCurrentPartTokens, this.llamaChat.model.tokenize(paramsText));
|
|
1618
|
+
}
|
|
1619
|
+
else {
|
|
1620
|
+
params = undefined;
|
|
1621
|
+
paramsText = "";
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
else {
|
|
1625
|
+
const functionParamsGenerationDoneDetector = new StopGenerationDetector();
|
|
1626
|
+
const functionParamsGrammar = new FunctionCallParamsGrammar(this.llamaChat.model._llama, this.functions, this.chatWrapper, this.functionEvaluationFunctionName, functionDefinition.params);
|
|
1627
|
+
this.functionsGrammar = functionParamsGrammar;
|
|
1628
|
+
this.functionsEvaluationState = new LlamaGrammarEvaluationState({
|
|
1629
|
+
model: this.llamaChat.model,
|
|
1630
|
+
grammar: this.functionsGrammar
|
|
1631
|
+
});
|
|
1632
|
+
StopGenerationDetector.resolveStopTriggers(this.functionsGrammar.stopGenerationTriggers, this.llamaChat.model.tokenizer)
|
|
1633
|
+
.map((stopTrigger) => functionParamsGenerationDoneDetector.addStopTrigger(stopTrigger));
|
|
1634
|
+
if (this.currentFunctionCallCurrentPartTokens.length > 0)
|
|
1635
|
+
this.onFunctionCallParamsChunk?.({
|
|
1636
|
+
callIndex: this.resFunctionCalls.length,
|
|
1637
|
+
functionName: this.functionEvaluationFunctionName,
|
|
1638
|
+
paramsChunk: this.llamaChat.model.detokenize(this.currentFunctionCallCurrentPartTokens, false, lastPartTokens),
|
|
1639
|
+
done: false
|
|
1640
|
+
});
|
|
1641
|
+
let tookInitialCheckpoint = false;
|
|
1642
|
+
for await (const tokens of this.evaluateWithContextShift(loadContextWindow)) {
|
|
1643
|
+
if (!tookInitialCheckpoint && this.llamaChat.sequence.needsCheckpoints) {
|
|
1644
|
+
await this.llamaChat.sequence._takeNamedCheckpoint(internalCheckpoints.chatSequenceStart.name, internalCheckpoints.chatSequenceStart.maxCheckpoints);
|
|
1645
|
+
tookInitialCheckpoint = true;
|
|
1646
|
+
}
|
|
1647
|
+
const hadInProgressTriggers = functionParamsGenerationDoneDetector.hasInProgressStops;
|
|
1648
|
+
functionParamsGenerationDoneDetector.recordGeneration({
|
|
1649
|
+
text: this.currentText,
|
|
1650
|
+
tokens: this.currentTokens
|
|
1651
|
+
});
|
|
1652
|
+
if (!hadInProgressTriggers && functionParamsGenerationDoneDetector.hasInProgressStops &&
|
|
1653
|
+
this.llamaChat.sequence.needsCheckpoints)
|
|
1654
|
+
await this.llamaChat.sequence._takeNamedCheckpoint(internalCheckpoints.chatGrammarEnd.name, internalCheckpoints.chatGrammarEnd.maxCheckpoints);
|
|
1655
|
+
this.onFunctionCallParamsChunk?.({
|
|
1656
|
+
callIndex: this.resFunctionCalls.length,
|
|
1657
|
+
functionName: this.functionEvaluationFunctionName,
|
|
1658
|
+
paramsChunk: this.llamaChat.model.detokenize(tokens, false, resolveLastTokens([lastPartTokens, this.currentFunctionCallCurrentPartTokens])),
|
|
1659
|
+
done: functionParamsGenerationDoneDetector.hasTriggeredStops
|
|
1660
|
+
});
|
|
1661
|
+
pushAll(this.currentFunctionCallCurrentPartTokens, tokens);
|
|
1662
|
+
if (functionParamsGenerationDoneDetector.hasTriggeredStops)
|
|
1663
|
+
break;
|
|
1664
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1665
|
+
if (stopRes != null)
|
|
1666
|
+
return stopRes;
|
|
1667
|
+
}
|
|
1668
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1669
|
+
if (stopRes != null)
|
|
1670
|
+
return stopRes;
|
|
1671
|
+
const functionCallParamsText = this.llamaChat.model.detokenize(this.currentFunctionCallCurrentPartTokens, false, lastPartTokens);
|
|
1672
|
+
const parsedFunctionParams = functionParamsGrammar.parseParams(functionCallParamsText);
|
|
1673
|
+
params = parsedFunctionParams.params;
|
|
1674
|
+
paramsText = parsedFunctionParams.raw;
|
|
1675
|
+
}
|
|
1676
|
+
const functionCallText = LlamaText([
|
|
1677
|
+
this.chatWrapper.settings.functions.call.prefix,
|
|
1678
|
+
this.functionEvaluationFunctionName,
|
|
1679
|
+
this.chatWrapper.settings.functions.call.paramsPrefix,
|
|
1680
|
+
paramsText,
|
|
1681
|
+
this.chatWrapper.settings.functions.call.suffix
|
|
1682
|
+
]);
|
|
1683
|
+
this.resFunctionCalls.push({
|
|
1684
|
+
functionName: this.functionEvaluationFunctionName,
|
|
1685
|
+
params,
|
|
1686
|
+
raw: functionCallText
|
|
1687
|
+
});
|
|
1688
|
+
this.onFunctionCall?.({
|
|
1689
|
+
functionName: this.functionEvaluationFunctionName,
|
|
1690
|
+
params: structuredClone(params),
|
|
1691
|
+
raw: functionCallText.toJSON()
|
|
1692
|
+
});
|
|
1693
|
+
this.currentFunctionCallPreviousText = LlamaText([]);
|
|
1694
|
+
this.currentFunctionCallCurrentPartTokens.length = 0;
|
|
1695
|
+
this.functionEvaluationFunctionName = "";
|
|
1696
|
+
if (this.chatWrapper.settings.functions.parallelism == null || (this.maxParallelFunctionCalls != null && this.maxParallelFunctionCalls <= this.resFunctionCalls.length)) {
|
|
1697
|
+
this.functionEvaluationMode = false;
|
|
1698
|
+
return this.returnFunctionCallResults();
|
|
1699
|
+
}
|
|
1700
|
+
this.functionEvaluationMode = "sectionSuffixOrBetweenCalls";
|
|
1701
|
+
continue;
|
|
1702
|
+
}
|
|
1703
|
+
else if (this.functionEvaluationMode === "sectionSuffixOrBetweenCalls") {
|
|
1704
|
+
const sectionSuffixDetector = new StopGenerationDetector();
|
|
1705
|
+
let isFirstToken = true;
|
|
1706
|
+
this.functionsGrammar = undefined;
|
|
1707
|
+
this.functionsEvaluationState = undefined;
|
|
1708
|
+
this.currentFunctionCallPreviousText = LlamaText([]);
|
|
1709
|
+
this.currentFunctionCallCurrentPartTokens.length = 0;
|
|
1710
|
+
StopGenerationDetector.resolveStopTriggers([
|
|
1711
|
+
...(this.chatWrapper.settings.functions.parallelism?.call?.sectionSuffix != null
|
|
1712
|
+
? [this.chatWrapper.settings.functions.parallelism?.call?.sectionSuffix]
|
|
1713
|
+
: []),
|
|
1714
|
+
LlamaText(new SpecialToken("EOS")),
|
|
1715
|
+
LlamaText(new SpecialToken("EOT"))
|
|
1716
|
+
], this.llamaChat.model.tokenizer)
|
|
1717
|
+
.map((stopTrigger) => sectionSuffixDetector.addStopTrigger(stopTrigger));
|
|
1718
|
+
let tookInitialCheckpoint = false;
|
|
1719
|
+
for await (const tokens of this.evaluateWithContextShift(loadContextWindow)) {
|
|
1720
|
+
if (!tookInitialCheckpoint && this.llamaChat.sequence.needsCheckpoints) {
|
|
1721
|
+
await this.llamaChat.sequence._takeNamedCheckpoint(internalCheckpoints.chatSequenceStart.name, internalCheckpoints.chatSequenceStart.maxCheckpoints);
|
|
1722
|
+
tookInitialCheckpoint = true;
|
|
1723
|
+
}
|
|
1724
|
+
pushAll(this.currentFunctionCallCurrentPartTokens, tokens);
|
|
1725
|
+
sectionSuffixDetector.recordGeneration({
|
|
1726
|
+
text: this.currentText,
|
|
1727
|
+
tokens: this.currentTokens,
|
|
1728
|
+
startNewChecks: isFirstToken,
|
|
1729
|
+
triggerMustStartWithGeneration: true
|
|
1730
|
+
});
|
|
1731
|
+
isFirstToken = false;
|
|
1732
|
+
if (sectionSuffixDetector.hasTriggeredStops || !sectionSuffixDetector.hasInProgressStops)
|
|
1733
|
+
break;
|
|
1734
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1735
|
+
if (stopRes != null)
|
|
1736
|
+
return stopRes;
|
|
1737
|
+
}
|
|
1738
|
+
const stopRes = this.handleAbortTrigger("model") ?? this.handleMaxTokensTrigger("model");
|
|
1739
|
+
if (stopRes != null)
|
|
1740
|
+
return stopRes;
|
|
1741
|
+
if (sectionSuffixDetector.hasTriggeredStops) {
|
|
1742
|
+
this.functionEvaluationMode = false;
|
|
1743
|
+
return this.returnFunctionCallResults();
|
|
1744
|
+
}
|
|
1745
|
+
this.functionEvaluationMode = "functionName";
|
|
1746
|
+
this.initiallyEngagedFunctionMode = false;
|
|
1747
|
+
continue;
|
|
1748
|
+
}
|
|
1749
|
+
break;
|
|
1750
|
+
}
|
|
1751
|
+
return undefined;
|
|
1752
|
+
}
|
|
1753
|
+
releasePartiallyFreeTokensBeforeFunctionCallStart() {
|
|
1754
|
+
if (this.releasedPartiallyFreeTokensBeforeFunctionCallStartSyntax)
|
|
1755
|
+
return;
|
|
1756
|
+
this.stopGenerationDetector.clearInProgressStops();
|
|
1757
|
+
this.customStopGenerationTriggersDetector.clearInProgressStops();
|
|
1758
|
+
pushAll(this.pendingTokens, this.streamRegulator.popFreeChunkTokens());
|
|
1759
|
+
const triggeredStops = this.functionSyntaxStartDetector.getTriggeredStops();
|
|
1760
|
+
const partiallyFreeTokens = this.streamRegulator.getPartiallyFreeChunk(this.llamaChat.model.tokenizer);
|
|
1761
|
+
const queuedTokensBeforeStopTrigger = getQueuedTokensBeforeStopTrigger(triggeredStops, partiallyFreeTokens, this.llamaChat.model.tokenizer);
|
|
1762
|
+
pushAll(this.pendingTokens, queuedTokensBeforeStopTrigger);
|
|
1763
|
+
this.removeFoundStartIgnoreTextsFromPendingTokens(true);
|
|
1764
|
+
this.pushPendingTokensAndCallOnToken();
|
|
1765
|
+
this.streamRegulator.clearQueue();
|
|
1766
|
+
this.releasedPartiallyFreeTokensBeforeFunctionCallStartSyntax = true;
|
|
1767
|
+
}
|
|
1768
|
+
returnFunctionCallResults() {
|
|
1769
|
+
if (this.resFunctionCalls.length > 0) {
|
|
1770
|
+
this.releasePartiallyFreeTokensBeforeFunctionCallStart();
|
|
1771
|
+
this.segmentHandler.onFinishedGeneration();
|
|
1772
|
+
const trimWhitespaceSuffix = this.grammar?.trimWhitespaceSuffix || this.trimWhitespaceSuffix;
|
|
1773
|
+
const responseSegments = this.segmentHandler.getModelResponseSegments(trimWhitespaceSuffix);
|
|
1774
|
+
return {
|
|
1775
|
+
response: responseSegments
|
|
1776
|
+
.filter((segment) => typeof segment === "string")
|
|
1777
|
+
.join(""),
|
|
1778
|
+
fullResponse: responseSegments,
|
|
1779
|
+
lastEvaluation: {
|
|
1780
|
+
contextWindow: mergeGeneratedResultWithChatHistory("model", this.lastContextWindowHistory, this.segmentHandler.getContextWindowModelResponseSegments(trimWhitespaceSuffix)),
|
|
1781
|
+
cleanHistory: mergeGeneratedResultWithChatHistory("model", this.resolvedHistory, responseSegments),
|
|
1782
|
+
contextShiftMetadata: this.lastHistoryCompressionMetadata
|
|
1783
|
+
},
|
|
1784
|
+
functionCalls: this.resFunctionCalls.map((functionCall) => {
|
|
1785
|
+
return {
|
|
1786
|
+
functionName: functionCall.functionName,
|
|
1787
|
+
params: functionCall.params,
|
|
1788
|
+
raw: functionCall.raw.toJSON()
|
|
1789
|
+
};
|
|
1790
|
+
}), // prevent infinite TS type instantiation
|
|
1791
|
+
metadata: {
|
|
1792
|
+
stopReason: "functionCalls"
|
|
1793
|
+
}
|
|
1794
|
+
};
|
|
1795
|
+
}
|
|
1796
|
+
return undefined;
|
|
1797
|
+
}
|
|
1798
|
+
async *evaluateWithContextShift(loadContextWindow) {
|
|
1799
|
+
while (true) {
|
|
1800
|
+
this.startTokenLoop();
|
|
1801
|
+
await loadContextWindow();
|
|
1802
|
+
await this.alignCurrentSequenceStateWithCurrentTokens();
|
|
1803
|
+
await this.createNewEvaluationIterator();
|
|
1804
|
+
while (await this.iterateEvaluation()) {
|
|
1805
|
+
if (this.currentTokens.length === 0)
|
|
1806
|
+
break;
|
|
1807
|
+
if (!this.holdPartialTokensForNextEvaluation())
|
|
1808
|
+
yield this.currentTokens;
|
|
1809
|
+
if (this.shouldAbort)
|
|
1810
|
+
return;
|
|
1811
|
+
if (this.updateShouldContextShift())
|
|
1812
|
+
break;
|
|
1813
|
+
if (this.restartEvaluationIterator) {
|
|
1814
|
+
await this.createNewEvaluationIterator();
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
this.isFirstEvaluation = false;
|
|
1818
|
+
if (this.shouldContextShift)
|
|
1819
|
+
continue;
|
|
1820
|
+
break;
|
|
1821
|
+
}
|
|
1822
|
+
throw new Error("The context size is too small to generate a response");
|
|
1823
|
+
}
|
|
1824
|
+
async alignCurrentSequenceStateWithCurrentTokens() {
|
|
1825
|
+
if (this.tokens.length === 1 && this.llamaChat.sequence.nextTokenIndex !== 0) {
|
|
1826
|
+
await this.llamaChat.sequence.eraseContextTokenRanges([{
|
|
1827
|
+
start: 0,
|
|
1828
|
+
end: this.llamaChat.sequence.nextTokenIndex
|
|
1829
|
+
}]);
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
const lastToken = this.tokens[this.tokens.length - 1];
|
|
1833
|
+
// we need to decode at least one token to generate a response
|
|
1834
|
+
this.tokens.pop();
|
|
1835
|
+
await this.llamaChat.sequence.adaptStateToTokens(this.tokens, false);
|
|
1836
|
+
this.tokens.push(lastToken);
|
|
1837
|
+
this.ensureNotAborted();
|
|
1838
|
+
const firstDifferentIndex = this.llamaChat.sequence.nextTokenIndex;
|
|
1839
|
+
this.tokens.splice(0, firstDifferentIndex);
|
|
1840
|
+
}
|
|
1841
|
+
async evaluateWithoutGeneratingNewTokens() {
|
|
1842
|
+
if (this.evaluationIterator != null)
|
|
1843
|
+
await this.evaluationIterator.return();
|
|
1844
|
+
await this.llamaChat.sequence.evaluateWithoutGeneratingNewTokens(this.tokens, removeNullFields({
|
|
1845
|
+
evaluationPriority: this.evaluationPriority
|
|
1846
|
+
}));
|
|
1847
|
+
}
|
|
1848
|
+
async createNewEvaluationIterator() {
|
|
1849
|
+
if (this.tokens.length === 0) {
|
|
1850
|
+
if (this.evaluationIterator != null)
|
|
1851
|
+
return;
|
|
1852
|
+
const token = this.llamaChat.sequence.contextTokens.at(-1);
|
|
1853
|
+
if (token == null)
|
|
1854
|
+
throw new Error("No tokens to evaluate");
|
|
1855
|
+
this.llamaChat.sequence.model._llama._log(LlamaLogLevel.warn, "Attempted to evaluate with no input, reevaluating the last context sequence token");
|
|
1856
|
+
await this.llamaChat.sequence.eraseContextTokenRanges([{
|
|
1857
|
+
start: this.llamaChat.sequence.contextTokens.length - 1,
|
|
1858
|
+
end: this.llamaChat.sequence.contextTokens.length
|
|
1859
|
+
}]);
|
|
1860
|
+
this.tokens = [token];
|
|
1861
|
+
}
|
|
1862
|
+
if (this.evaluationIterator != null)
|
|
1863
|
+
await this.evaluationIterator.return();
|
|
1864
|
+
this.currentIterationReplacementToken = undefined;
|
|
1865
|
+
this.restartEvaluationIterator = false;
|
|
1866
|
+
this.evaluationIterator = this.llamaChat.sequence.evaluate(this.tokens, removeNullFields({
|
|
1867
|
+
temperature: this.temperature,
|
|
1868
|
+
minP: this.minP,
|
|
1869
|
+
topK: this.topK,
|
|
1870
|
+
topP: this.topP,
|
|
1871
|
+
seed: this.seed,
|
|
1872
|
+
xtc: this.xtc,
|
|
1873
|
+
grammarEvaluationState: () => {
|
|
1874
|
+
if (this.functionEvaluationMode !== false)
|
|
1875
|
+
return this.functionsEvaluationState;
|
|
1876
|
+
return this.grammarEvaluationState;
|
|
1877
|
+
},
|
|
1878
|
+
repeatPenalty: !this.repeatPenaltyEnabled ? undefined : {
|
|
1879
|
+
punishTokens: this.getPenaltyTokens,
|
|
1880
|
+
maxPunishTokens: this.resolvedRepeatPenalty.lastTokens,
|
|
1881
|
+
penalty: this.resolvedRepeatPenalty.penalty,
|
|
1882
|
+
frequencyPenalty: this.resolvedRepeatPenalty.frequencyPenalty,
|
|
1883
|
+
presencePenalty: this.resolvedRepeatPenalty.presencePenalty
|
|
1884
|
+
},
|
|
1885
|
+
dryRepeatPenalty: this.dryRepeatPenalty,
|
|
1886
|
+
tokenBias: this.tokenBias,
|
|
1887
|
+
evaluationPriority: this.evaluationPriority,
|
|
1888
|
+
yieldEogToken: true
|
|
1889
|
+
}));
|
|
1890
|
+
}
|
|
1891
|
+
async iterateEvaluation() {
|
|
1892
|
+
this.currentIteration = await this.evaluationIterator?.next(this.currentIterationReplacementToken);
|
|
1893
|
+
this.currentIterationReplacementToken = undefined;
|
|
1894
|
+
this.ensureNotAborted();
|
|
1895
|
+
this.generatedTokens++;
|
|
1896
|
+
if ((this.currentIteration != null && this.currentIteration?.done !== true) || this.pendingPartialTokens.length !== 0) {
|
|
1897
|
+
this.currentToken = this.currentIteration?.value ?? undefined;
|
|
1898
|
+
this.currentTokens = this.currentToken != null
|
|
1899
|
+
? this.pendingPartialTokens.length === 0
|
|
1900
|
+
? [this.currentToken]
|
|
1901
|
+
: [...this.pendingPartialTokens, this.currentToken]
|
|
1902
|
+
: [...this.pendingPartialTokens];
|
|
1903
|
+
this.pendingPartialTokens.length = 0;
|
|
1904
|
+
this.currentText = this.llamaChat.model.detokenize(this.currentTokens, false, this.getLastTokens());
|
|
1905
|
+
if (this.functionEvaluationMode === false)
|
|
1906
|
+
this.currentQueuedTokenRelease = this.streamRegulator.addChunk({
|
|
1907
|
+
tokens: this.currentTokens,
|
|
1908
|
+
text: this.currentText
|
|
1909
|
+
});
|
|
1910
|
+
else
|
|
1911
|
+
this.currentQueuedTokenRelease = undefined;
|
|
1912
|
+
return true;
|
|
1913
|
+
}
|
|
1914
|
+
return false;
|
|
1915
|
+
}
|
|
1916
|
+
holdPartialTokensForNextEvaluation() {
|
|
1917
|
+
if (this.pendingPartialTokens.length === 0 &&
|
|
1918
|
+
this.currentText.endsWith(UNKNOWN_UNICODE_CHAR) &&
|
|
1919
|
+
this.currentToken != null &&
|
|
1920
|
+
!this.llamaChat.model.isSpecialToken(this.currentToken) &&
|
|
1921
|
+
!this.llamaChat.model.isEogToken(this.currentToken)) {
|
|
1922
|
+
this.pendingPartialTokens.length = 0;
|
|
1923
|
+
pushAll(this.pendingPartialTokens, this.currentTokens);
|
|
1924
|
+
this.streamRegulator.removeChunkIfLast(this.currentQueuedTokenRelease);
|
|
1925
|
+
return true;
|
|
1926
|
+
}
|
|
1927
|
+
return false;
|
|
1928
|
+
}
|
|
1929
|
+
waitOnPartialCharactersOrWhiteSpaceTokens() {
|
|
1930
|
+
if (this.currentText.endsWith(UNKNOWN_UNICODE_CHAR) || ((this.grammar?.trimWhitespaceSuffix || this.trimWhitespaceSuffix) && this.currentText?.trim() === "") || (this.currentText === "" && this.locksToReleaseOnValidGeneration.length > 0 &&
|
|
1931
|
+
!this.llamaChat.model.isSpecialToken(this.currentToken))) {
|
|
1932
|
+
if (this.currentQueuedTokenRelease != null)
|
|
1933
|
+
this.locksToReleaseOnValidGeneration.push(this.currentQueuedTokenRelease.createTextIndexLock(0));
|
|
1934
|
+
}
|
|
1935
|
+
else {
|
|
1936
|
+
while (this.locksToReleaseOnValidGeneration.length > 0)
|
|
1937
|
+
this.locksToReleaseOnValidGeneration.shift().dispose();
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
detectAndHandleFunctionStartSyntax() {
|
|
1941
|
+
if (!this.functionSyntaxStartDetectorEnabled)
|
|
1942
|
+
return;
|
|
1943
|
+
this.functionSyntaxStartDetector.recordGeneration({
|
|
1944
|
+
text: this.currentText,
|
|
1945
|
+
tokens: this.currentTokens,
|
|
1946
|
+
queuedTokenRelease: this.currentQueuedTokenRelease
|
|
1947
|
+
});
|
|
1948
|
+
if (this.currentQueuedTokenRelease != null && this.functionEvaluationMode === false && this.functionsEnabled &&
|
|
1949
|
+
this.functionSyntaxStartDetector.hasTriggeredStops) {
|
|
1950
|
+
if (this.abortOnNonText) {
|
|
1951
|
+
this.shouldAbortBecauseOfNonText = true;
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
this.functionEvaluationMode = "functionName";
|
|
1955
|
+
this.currentQueuedTokenRelease.createTextIndexLock(0);
|
|
1956
|
+
this.stopGenerationDetector.clearTriggeredStops();
|
|
1957
|
+
this.stopGenerationDetector.clearInProgressStops();
|
|
1958
|
+
this.customStopGenerationTriggersDetector.clearTriggeredStops();
|
|
1959
|
+
this.customStopGenerationTriggersDetector.clearInProgressStops();
|
|
1960
|
+
pushAll(this.pendingTokens, this.streamRegulator.popFreeChunkTokens());
|
|
1961
|
+
const triggeredStops = this.functionSyntaxStartDetector.getTriggeredStops();
|
|
1962
|
+
const partiallyFreeTokens = this.streamRegulator.getPartiallyFreeChunk(this.llamaChat.model.tokenizer);
|
|
1963
|
+
const queuedTokensBeforeStopTrigger = getQueuedTokensBeforeStopTrigger(triggeredStops, partiallyFreeTokens, this.llamaChat.model.tokenizer);
|
|
1964
|
+
pushAll(this.pendingTokens, queuedTokensBeforeStopTrigger);
|
|
1965
|
+
const { firstRemainingGenerationAfterStop, stopTrigger } = StopGenerationDetector.getFirstRemainingGenerationAfterStop(triggeredStops);
|
|
1966
|
+
const remainingTextAfterStop = StopGenerationDetector.detokenizeRemainingGeneration(firstRemainingGenerationAfterStop, stopTrigger, this.llamaChat.model.tokenizer);
|
|
1967
|
+
this.currentFunctionCallPreviousPartLeftoverText = remainingTextAfterStop;
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
recordStopGenerationEvaluation() {
|
|
1971
|
+
const hadInProgressStopTrigger = this.stopGenerationDetector.hasInProgressStops;
|
|
1972
|
+
this.rerenderTriggerDetector.recordGeneration({
|
|
1973
|
+
text: this.currentText,
|
|
1974
|
+
tokens: this.currentTokens,
|
|
1975
|
+
queuedTokenRelease: this.currentQueuedTokenRelease
|
|
1976
|
+
});
|
|
1977
|
+
this.stopGenerationDetector.recordGeneration({
|
|
1978
|
+
text: this.currentText,
|
|
1979
|
+
tokens: this.currentTokens,
|
|
1980
|
+
queuedTokenRelease: this.currentQueuedTokenRelease
|
|
1981
|
+
});
|
|
1982
|
+
this.customStopGenerationTriggersDetector.recordGeneration({
|
|
1983
|
+
text: this.currentText,
|
|
1984
|
+
tokens: this.currentTokens,
|
|
1985
|
+
queuedTokenRelease: this.currentQueuedTokenRelease
|
|
1986
|
+
});
|
|
1987
|
+
if (this.llamaChat.model.isEogToken(this.currentToken))
|
|
1988
|
+
this.currentQueuedTokenRelease?.createTokenIndexLock(0);
|
|
1989
|
+
if (this.grammar != null && !hadInProgressStopTrigger && this.stopGenerationDetector.hasInProgressStops &&
|
|
1990
|
+
this.llamaChat.sequence.needsCheckpoints)
|
|
1991
|
+
return this.llamaChat.sequence._takeNamedCheckpoint(internalCheckpoints.chatGrammarEnd.name, internalCheckpoints.chatGrammarEnd.maxCheckpoints);
|
|
1992
|
+
}
|
|
1993
|
+
popStreamRegulatorFreeTokens() {
|
|
1994
|
+
pushAll(this.pendingTokens, this.streamRegulator.popFreeChunkTokens());
|
|
1995
|
+
}
|
|
1996
|
+
handleStopGenerationTrigger(lastHistoryItemType, forceStopReason) {
|
|
1997
|
+
const detectedStopGenerationTrigger = this.stopGenerationDetector.hasTriggeredStops ||
|
|
1998
|
+
this.customStopGenerationTriggersDetector.hasTriggeredStops ||
|
|
1999
|
+
this.llamaChat.model.isEogToken(this.currentToken);
|
|
2000
|
+
if ((detectedStopGenerationTrigger && !this.rerenderTriggerDetector.hasTriggeredStops) || forceStopReason != null) {
|
|
2001
|
+
this.stopGenerationDetector.clearInProgressStops();
|
|
2002
|
+
this.customStopGenerationTriggersDetector.clearInProgressStops();
|
|
2003
|
+
pushAll(this.pendingTokens, this.streamRegulator.popFreeChunkTokens());
|
|
2004
|
+
const triggeredStops = this.stopGenerationDetector.hasTriggeredStops
|
|
2005
|
+
? this.stopGenerationDetector.getTriggeredStops()
|
|
2006
|
+
: this.customStopGenerationTriggersDetector.getTriggeredStops();
|
|
2007
|
+
const partiallyFreeTokens = this.streamRegulator.getPartiallyFreeChunk(this.llamaChat.model.tokenizer);
|
|
2008
|
+
const queuedTokensBeforeStopTrigger = getQueuedTokensBeforeStopTrigger(triggeredStops, partiallyFreeTokens, this.llamaChat.model.tokenizer);
|
|
2009
|
+
pushAll(this.pendingTokens, queuedTokensBeforeStopTrigger);
|
|
2010
|
+
const { firstRemainingGenerationAfterStop } = StopGenerationDetector.getFirstRemainingGenerationAfterStop(triggeredStops);
|
|
2011
|
+
this.removeFoundStartIgnoreTextsFromPendingTokens(true);
|
|
2012
|
+
this.pushPendingTokensAndCallOnToken();
|
|
2013
|
+
this.segmentHandler.onFinishedGeneration();
|
|
2014
|
+
const trimWhitespaceSuffix = this.grammar?.trimWhitespaceSuffix || this.trimWhitespaceSuffix;
|
|
2015
|
+
const responseSegments = this.segmentHandler.getModelResponseSegments(trimWhitespaceSuffix);
|
|
2016
|
+
const response = responseSegments
|
|
2017
|
+
.filter((segment) => typeof segment === "string")
|
|
2018
|
+
.join("");
|
|
2019
|
+
const lastEvaluation = {
|
|
2020
|
+
contextWindow: mergeGeneratedResultWithChatHistory(lastHistoryItemType, this.lastContextWindowHistory, this.segmentHandler.getContextWindowModelResponseSegments(trimWhitespaceSuffix)),
|
|
2021
|
+
cleanHistory: mergeGeneratedResultWithChatHistory(lastHistoryItemType, this.resolvedHistory, responseSegments),
|
|
2022
|
+
contextShiftMetadata: this.lastHistoryCompressionMetadata
|
|
2023
|
+
};
|
|
2024
|
+
const isEogToken = this.llamaChat.model.isEogToken(this.currentToken) || forceStopReason === "eogToken";
|
|
2025
|
+
if (isEogToken || this.stopGenerationDetector.hasTriggeredStops) {
|
|
2026
|
+
return {
|
|
2027
|
+
response,
|
|
2028
|
+
fullResponse: responseSegments,
|
|
2029
|
+
lastEvaluation,
|
|
2030
|
+
metadata: {
|
|
2031
|
+
remainingGenerationAfterStop: firstRemainingGenerationAfterStop,
|
|
2032
|
+
stopReason: isEogToken
|
|
2033
|
+
? "eogToken"
|
|
2034
|
+
: "stopGenerationTrigger"
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
return {
|
|
2039
|
+
response,
|
|
2040
|
+
fullResponse: responseSegments,
|
|
2041
|
+
lastEvaluation,
|
|
2042
|
+
metadata: {
|
|
2043
|
+
remainingGenerationAfterStop: firstRemainingGenerationAfterStop,
|
|
2044
|
+
stopReason: "customStopTrigger",
|
|
2045
|
+
customStopTrigger: triggeredStops[0].stopTrigger
|
|
2046
|
+
}
|
|
2047
|
+
};
|
|
2048
|
+
}
|
|
2049
|
+
return undefined;
|
|
2050
|
+
}
|
|
2051
|
+
spliceIgnoreStartTextDetectedTokens() {
|
|
2052
|
+
if (this.res.length === 0) {
|
|
2053
|
+
this.ignoreStartTextDetector.clearInProgressStops();
|
|
2054
|
+
this.ignoreStartTextDetector.clearTriggeredStops();
|
|
2055
|
+
const lastTokensForDetokenizer = resolveLastTokens([
|
|
2056
|
+
this.contextWindowTokens,
|
|
2057
|
+
this.ignoredStartTextTokens
|
|
2058
|
+
]);
|
|
2059
|
+
this.ignoreStartTextDetector.recordGeneration({
|
|
2060
|
+
text: this.llamaChat.model.detokenize(this.pendingTokens, false, lastTokensForDetokenizer),
|
|
2061
|
+
tokens: this.pendingTokens
|
|
2062
|
+
});
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
isMaxTokensTriggered() {
|
|
2066
|
+
return this.maxTokens != null && this.maxTokens > 0 && this.generatedTokens >= this.maxTokens;
|
|
2067
|
+
}
|
|
2068
|
+
moveFreePendingTokensToRes(removeFoundStartIgnoreTextsFromPendingTokens = true) {
|
|
2069
|
+
if (this.pendingTokens.length > 0 && (this.isMaxTokensTriggered() || !this.ignoreStartTextDetector.hasInProgressStops)) {
|
|
2070
|
+
if (removeFoundStartIgnoreTextsFromPendingTokens)
|
|
2071
|
+
this.removeFoundStartIgnoreTextsFromPendingTokens();
|
|
2072
|
+
this.pushPendingTokensAndCallOnToken();
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
handleMaxTokensTrigger(lastHistoryItemType) {
|
|
2076
|
+
if (this.isMaxTokensTriggered()) {
|
|
2077
|
+
this.segmentHandler.onFinishedGeneration();
|
|
2078
|
+
const trimWhitespaceSuffix = this.grammar?.trimWhitespaceSuffix || this.trimWhitespaceSuffix;
|
|
2079
|
+
const responseSegments = this.segmentHandler.getModelResponseSegments(trimWhitespaceSuffix);
|
|
2080
|
+
return {
|
|
2081
|
+
response: responseSegments
|
|
2082
|
+
.filter((segment) => typeof segment === "string")
|
|
2083
|
+
.join(""),
|
|
2084
|
+
fullResponse: responseSegments,
|
|
2085
|
+
lastEvaluation: {
|
|
2086
|
+
contextWindow: mergeGeneratedResultWithChatHistory(lastHistoryItemType, this.lastContextWindowHistory, this.segmentHandler.getContextWindowModelResponseSegments(trimWhitespaceSuffix)),
|
|
2087
|
+
cleanHistory: mergeGeneratedResultWithChatHistory(lastHistoryItemType, this.resolvedHistory, responseSegments),
|
|
2088
|
+
contextShiftMetadata: this.lastHistoryCompressionMetadata
|
|
2089
|
+
},
|
|
2090
|
+
metadata: {
|
|
2091
|
+
stopReason: "maxTokens"
|
|
2092
|
+
}
|
|
2093
|
+
};
|
|
2094
|
+
}
|
|
2095
|
+
return undefined;
|
|
2096
|
+
}
|
|
2097
|
+
async handleBudgetTriggers() {
|
|
2098
|
+
let shouldReloadEvaluationState = false;
|
|
2099
|
+
if (this.budgets == null)
|
|
2100
|
+
return shouldReloadEvaluationState;
|
|
2101
|
+
for (const segmentType of this.segmentHandler.getOpenSegmentStack().reverse()) {
|
|
2102
|
+
const budget = this.getSegmentBudget(segmentType);
|
|
2103
|
+
if (budget == null)
|
|
2104
|
+
continue;
|
|
2105
|
+
const usedSegmentTokens = this.segmentHandler.getSegmentTokensCount(segmentType);
|
|
2106
|
+
if (usedSegmentTokens >= budget) {
|
|
2107
|
+
this.segmentHandler.closeSegment(segmentType);
|
|
2108
|
+
shouldReloadEvaluationState = true;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
return shouldReloadEvaluationState;
|
|
2112
|
+
}
|
|
2113
|
+
getSegmentBudget(segmentType) {
|
|
2114
|
+
const getBudget = (budget) => (budget == null
|
|
2115
|
+
? Math.ceil(defaultSegmentBudgetSize(this.llamaChat.sequence.contextSize))
|
|
2116
|
+
: budget === Infinity
|
|
2117
|
+
? null
|
|
2118
|
+
: budget);
|
|
2119
|
+
if (this.budgets == null)
|
|
2120
|
+
return null;
|
|
2121
|
+
if (segmentType === "thought")
|
|
2122
|
+
return getBudget(this.budgets.thoughtTokens);
|
|
2123
|
+
else if (segmentType === "comment")
|
|
2124
|
+
return getBudget(this.budgets.commentTokens);
|
|
2125
|
+
void segmentType;
|
|
2126
|
+
return null;
|
|
2127
|
+
}
|
|
2128
|
+
handleShouldRerender() {
|
|
2129
|
+
this.shouldRerender = this.rerenderTriggerDetector.hasTriggeredStops;
|
|
2130
|
+
if (this.abortOnNonText && this.shouldRerender)
|
|
2131
|
+
this.shouldAbortBecauseOfNonText = true;
|
|
2132
|
+
return this.shouldRerender;
|
|
2133
|
+
}
|
|
2134
|
+
updateShouldContextShift() {
|
|
2135
|
+
this.shouldContextShift = this.llamaChat.sequence.nextTokenIndex >= this.llamaChat.context.contextSize - 1;
|
|
2136
|
+
return this.shouldContextShift;
|
|
2137
|
+
}
|
|
2138
|
+
get shouldAbort() {
|
|
2139
|
+
return !!(this.signal?.aborted && this.stopOnAbortSignal) || this.shouldAbortBecauseOfNonText;
|
|
2140
|
+
}
|
|
2141
|
+
handleAbortTrigger(lastHistoryItemType) {
|
|
2142
|
+
if (this.shouldAbort && this.signal?.aborted && this.stopOnAbortSignal) {
|
|
2143
|
+
if (this.res.length === 0)
|
|
2144
|
+
throw this.signal.reason;
|
|
2145
|
+
this.segmentHandler.onFinishedGeneration();
|
|
2146
|
+
const trimWhitespaceSuffix = this.grammar?.trimWhitespaceSuffix || this.trimWhitespaceSuffix;
|
|
2147
|
+
const responseSegments = this.segmentHandler.getModelResponseSegments(trimWhitespaceSuffix);
|
|
2148
|
+
return {
|
|
2149
|
+
response: responseSegments
|
|
2150
|
+
.filter((segment) => typeof segment === "string")
|
|
2151
|
+
.join(""),
|
|
2152
|
+
fullResponse: responseSegments,
|
|
2153
|
+
lastEvaluation: {
|
|
2154
|
+
contextWindow: mergeGeneratedResultWithChatHistory(lastHistoryItemType, this.lastContextWindowHistory, this.segmentHandler.getContextWindowModelResponseSegments(trimWhitespaceSuffix)),
|
|
2155
|
+
cleanHistory: mergeGeneratedResultWithChatHistory(lastHistoryItemType, this.resolvedHistory, responseSegments),
|
|
2156
|
+
contextShiftMetadata: this.lastHistoryCompressionMetadata
|
|
2157
|
+
},
|
|
2158
|
+
metadata: {
|
|
2159
|
+
stopReason: this.shouldAbortBecauseOfNonText
|
|
2160
|
+
? "eogToken"
|
|
2161
|
+
: "abort"
|
|
2162
|
+
}
|
|
2163
|
+
};
|
|
2164
|
+
}
|
|
2165
|
+
return undefined;
|
|
2166
|
+
}
|
|
2167
|
+
pushPendingTokensAndCallOnToken() {
|
|
2168
|
+
if (this.pendingTokens.length === 0)
|
|
2169
|
+
return;
|
|
2170
|
+
this.segmentHandler.processTokens(this.pendingTokens);
|
|
2171
|
+
pushAll(this.res, this.pendingTokens);
|
|
2172
|
+
this.pendingTokens.length = 0;
|
|
2173
|
+
}
|
|
2174
|
+
getLastTokens(maxTokens = maxRecentDetokenizerTokens) {
|
|
2175
|
+
return resolveLastTokens([
|
|
2176
|
+
this.contextWindowTokens,
|
|
2177
|
+
this.ignoredStartTextTokens,
|
|
2178
|
+
this.pendingTokens,
|
|
2179
|
+
this.streamRegulator.getLastQueuedChunkTokens(maxTokens),
|
|
2180
|
+
this.getContextWindowFunctionCallsTokens(),
|
|
2181
|
+
this.pendingPartialTokens
|
|
2182
|
+
], maxTokens);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
class SegmentHandler {
|
|
2186
|
+
model;
|
|
2187
|
+
onToken;
|
|
2188
|
+
onTextChunk;
|
|
2189
|
+
onResponseChunk;
|
|
2190
|
+
_closeAllSegmentsDetector;
|
|
2191
|
+
_segmentDetectors;
|
|
2192
|
+
_segmentsStack = [];
|
|
2193
|
+
_segmentsStackSet = new Set();
|
|
2194
|
+
_ownedSegmentsStackLength = 0;
|
|
2195
|
+
_segments = [];
|
|
2196
|
+
_segmentsStartTokenTrail = [];
|
|
2197
|
+
_segmentTokenCounts;
|
|
2198
|
+
_contextWindowSegments = [];
|
|
2199
|
+
_contextWindowStartTokenTrail = [];
|
|
2200
|
+
_initialTokensTrail;
|
|
2201
|
+
_tokensTrail;
|
|
2202
|
+
_streamRegulator = new TokenStreamRegulator();
|
|
2203
|
+
_segmentDefinitions;
|
|
2204
|
+
constructor({ model, onTextChunk, onToken, onResponseChunk, segmentDefinitions, closeAllSegments, initialSegmentStack, initialTokenCounts, previousTokens }) {
|
|
2205
|
+
this.model = model;
|
|
2206
|
+
this.onTextChunk = onTextChunk;
|
|
2207
|
+
this.onToken = onToken;
|
|
2208
|
+
this.onResponseChunk = onResponseChunk;
|
|
2209
|
+
this._initialTokensTrail = previousTokens.slice(-maxRecentDetokenizerTokens);
|
|
2210
|
+
this._segmentsStartTokenTrail = previousTokens.slice(-maxRecentDetokenizerTokens);
|
|
2211
|
+
this._tokensTrail = previousTokens.slice(-maxRecentDetokenizerTokens);
|
|
2212
|
+
this._closeAllSegmentsDetector = closeAllSegments != null
|
|
2213
|
+
? new StopGenerationDetector()
|
|
2214
|
+
.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText(closeAllSegments), this.model.tokenizer))
|
|
2215
|
+
: undefined;
|
|
2216
|
+
this._segmentDetectors = new Map();
|
|
2217
|
+
this._segmentsStack = initialSegmentStack;
|
|
2218
|
+
this._segmentsStackSet = new Set(initialSegmentStack);
|
|
2219
|
+
this._ownedSegmentsStackLength = initialSegmentStack.length;
|
|
2220
|
+
this._segmentDefinitions = segmentDefinitions;
|
|
2221
|
+
this._segmentTokenCounts = new Map(initialTokenCounts);
|
|
2222
|
+
for (const [segment, { prefix, suffix }] of segmentDefinitions.entries()) {
|
|
2223
|
+
this._segmentDetectors.set(segment, {
|
|
2224
|
+
prefix: new StopGenerationDetector()
|
|
2225
|
+
.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText(prefix), this.model.tokenizer)),
|
|
2226
|
+
suffix: suffix != null
|
|
2227
|
+
? new StopGenerationDetector()
|
|
2228
|
+
.addStopTrigger(StopGenerationDetector.resolveLlamaTextTrigger(LlamaText(suffix), this.model.tokenizer))
|
|
2229
|
+
: undefined
|
|
2230
|
+
});
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
processTokens(tokens) {
|
|
2234
|
+
if (tokens.length === 0)
|
|
2235
|
+
return;
|
|
2236
|
+
let pendingTokens = [];
|
|
2237
|
+
for (const token of tokens) {
|
|
2238
|
+
pendingTokens.push(token);
|
|
2239
|
+
const currentText = this.model.detokenize(pendingTokens, false, this._tokensTrail);
|
|
2240
|
+
if (currentText.endsWith(UNKNOWN_UNICODE_CHAR))
|
|
2241
|
+
continue;
|
|
2242
|
+
pushAll(this._tokensTrail, pendingTokens);
|
|
2243
|
+
this._processTokens(pendingTokens, currentText);
|
|
2244
|
+
pendingTokens = [];
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
onFinishedGeneration() {
|
|
2248
|
+
this._clearDetectors();
|
|
2249
|
+
this._pushCurrentTokens(this._streamRegulator.popFreeChunkTokens());
|
|
2250
|
+
}
|
|
2251
|
+
resetContextWindow() {
|
|
2252
|
+
this._contextWindowSegments.length = 0;
|
|
2253
|
+
this._contextWindowStartTokenTrail.length = 0;
|
|
2254
|
+
pushAll(this._contextWindowStartTokenTrail, this._getTokenTrailFromResult());
|
|
2255
|
+
}
|
|
2256
|
+
openSegment(type) {
|
|
2257
|
+
const now = Date.now();
|
|
2258
|
+
this._segmentsStack.push(type);
|
|
2259
|
+
this._segmentsStackSet.add(type);
|
|
2260
|
+
this._segments.push({ type, tokens: [], ended: false, start: true, startTime: now });
|
|
2261
|
+
this._contextWindowSegments.push({ type, tokens: [], ended: false, start: true, startTime: now });
|
|
2262
|
+
this.onResponseChunk?.({
|
|
2263
|
+
type: "segment",
|
|
2264
|
+
segmentType: type,
|
|
2265
|
+
tokens: [],
|
|
2266
|
+
text: "",
|
|
2267
|
+
segmentStartTime: new Date(now)
|
|
2268
|
+
});
|
|
2269
|
+
}
|
|
2270
|
+
closeSegment(type) {
|
|
2271
|
+
if (!this.isSegmentTypeOpen(type))
|
|
2272
|
+
return;
|
|
2273
|
+
this._closeSegment(type);
|
|
2274
|
+
}
|
|
2275
|
+
getSegmentTokensCount(type) {
|
|
2276
|
+
return this._segmentTokenCounts.get(type) ?? 0;
|
|
2277
|
+
}
|
|
2278
|
+
isSegmentTypeOpen(type) {
|
|
2279
|
+
return this._segmentsStackSet.has(type);
|
|
2280
|
+
}
|
|
2281
|
+
get topOpenSegmentType() {
|
|
2282
|
+
return this._segmentsStack.at(-1);
|
|
2283
|
+
}
|
|
2284
|
+
/**
|
|
2285
|
+
* First segment in the stack is the top most that'll close last.
|
|
2286
|
+
* ```
|
|
2287
|
+
* <segment1>
|
|
2288
|
+
* some text here
|
|
2289
|
+
* <segment2>
|
|
2290
|
+
* some text here
|
|
2291
|
+
* <segment3>
|
|
2292
|
+
* some text here
|
|
2293
|
+
* </segment3>
|
|
2294
|
+
* ```
|
|
2295
|
+
* In that example, the top most segment is `segment1`, and the last open segment is `segment2` (which is the next one to close).
|
|
2296
|
+
* So in that example, this function will return:
|
|
2297
|
+
* ```
|
|
2298
|
+
* ["segment1", "segment2"]
|
|
2299
|
+
* ```
|
|
2300
|
+
*/
|
|
2301
|
+
getOpenSegmentStack() {
|
|
2302
|
+
return this._segmentsStack.slice(this._ownedSegmentsStackLength);
|
|
2303
|
+
}
|
|
2304
|
+
_processTokens(tokens, text) {
|
|
2305
|
+
const queuedTokenRelease = this._streamRegulator.addChunk({
|
|
2306
|
+
tokens,
|
|
2307
|
+
text
|
|
2308
|
+
});
|
|
2309
|
+
const currentType = this._segmentsStack.at(-1);
|
|
2310
|
+
const handleDetector = (stopDetector, action, type) => {
|
|
2311
|
+
if (stopDetector == null)
|
|
2312
|
+
return false;
|
|
2313
|
+
stopDetector.recordGeneration({
|
|
2314
|
+
text,
|
|
2315
|
+
tokens,
|
|
2316
|
+
queuedTokenRelease
|
|
2317
|
+
});
|
|
2318
|
+
if (stopDetector.hasTriggeredStops) {
|
|
2319
|
+
const [leftTokens, leftText] = this._handleTriggeredStopDetector(stopDetector);
|
|
2320
|
+
if (action === "pop")
|
|
2321
|
+
this._closeSegment(type);
|
|
2322
|
+
else if (action === "push") {
|
|
2323
|
+
this.openSegment(type);
|
|
2324
|
+
}
|
|
2325
|
+
else if (action === "reset") {
|
|
2326
|
+
const now = Date.now();
|
|
2327
|
+
while (this._segmentsStack.length > 0) {
|
|
2328
|
+
const segmentType = this._segmentsStack.pop();
|
|
2329
|
+
this._segmentsStackSet.delete(segmentType);
|
|
2330
|
+
const lastSegment = this._segments.at(-1);
|
|
2331
|
+
if (lastSegment != null && !(lastSegment instanceof Array) && lastSegment.type === segmentType) {
|
|
2332
|
+
lastSegment.ended = true;
|
|
2333
|
+
lastSegment.endTime = now;
|
|
2334
|
+
this.onResponseChunk?.({
|
|
2335
|
+
type: "segment",
|
|
2336
|
+
segmentType: segmentType,
|
|
2337
|
+
tokens: [],
|
|
2338
|
+
text: "",
|
|
2339
|
+
segmentStartTime: undefined,
|
|
2340
|
+
segmentEndTime: new Date(now)
|
|
2341
|
+
});
|
|
2342
|
+
}
|
|
2343
|
+
else {
|
|
2344
|
+
this._segments.push({ type: segmentType, tokens: [], ended: true, start: false, endTime: now });
|
|
2345
|
+
this.onResponseChunk?.({
|
|
2346
|
+
type: "segment",
|
|
2347
|
+
segmentType: segmentType,
|
|
2348
|
+
tokens: [],
|
|
2349
|
+
text: "",
|
|
2350
|
+
segmentStartTime: undefined,
|
|
2351
|
+
segmentEndTime: new Date(now)
|
|
2352
|
+
});
|
|
2353
|
+
}
|
|
2354
|
+
const lastContextWindowSegment = this._contextWindowSegments.at(-1);
|
|
2355
|
+
if (lastContextWindowSegment != null && !(lastContextWindowSegment instanceof Array) &&
|
|
2356
|
+
lastContextWindowSegment.type === segmentType)
|
|
2357
|
+
lastContextWindowSegment.ended = true;
|
|
2358
|
+
else
|
|
2359
|
+
this._contextWindowSegments.push({ type: segmentType, tokens: [], ended: true, start: false, endTime: now });
|
|
2360
|
+
}
|
|
2361
|
+
this._ownedSegmentsStackLength = 0;
|
|
2362
|
+
}
|
|
2363
|
+
if (leftTokens.length > 0)
|
|
2364
|
+
this._processTokens(leftTokens, leftText);
|
|
2365
|
+
return true;
|
|
2366
|
+
}
|
|
2367
|
+
return false;
|
|
2368
|
+
};
|
|
2369
|
+
if (currentType != null) {
|
|
2370
|
+
if (handleDetector(this._closeAllSegmentsDetector, "reset", currentType))
|
|
2371
|
+
return;
|
|
2372
|
+
if (handleDetector(this._segmentDetectors.get(currentType)?.suffix, "pop", currentType))
|
|
2373
|
+
return;
|
|
2374
|
+
}
|
|
2375
|
+
else
|
|
2376
|
+
this._closeAllSegmentsDetector?.clearInProgressStops();
|
|
2377
|
+
for (const [type, { prefix, suffix }] of this._segmentDetectors.entries()) {
|
|
2378
|
+
if (!this._segmentsStackSet.has(type)) {
|
|
2379
|
+
if (handleDetector(prefix, "push", type))
|
|
2380
|
+
return;
|
|
2381
|
+
}
|
|
2382
|
+
else
|
|
2383
|
+
prefix.clearInProgressStops();
|
|
2384
|
+
if (this._segmentsStackSet.has(type)) {
|
|
2385
|
+
// `currentType` suffix is already handled above
|
|
2386
|
+
if (type !== currentType && handleDetector(suffix, "pop", type))
|
|
2387
|
+
return;
|
|
2388
|
+
}
|
|
2389
|
+
else
|
|
2390
|
+
suffix?.clearInProgressStops();
|
|
2391
|
+
}
|
|
2392
|
+
this._pushCurrentTokens(this._streamRegulator.popFreeChunkTokens());
|
|
2393
|
+
}
|
|
2394
|
+
_handleTriggeredStopDetector(stopDetector) {
|
|
2395
|
+
this._clearDetectors(stopDetector);
|
|
2396
|
+
stopDetector.clearInProgressStops();
|
|
2397
|
+
const triggeredStops = stopDetector.getTriggeredStops();
|
|
2398
|
+
const freeTokens = this._streamRegulator.popFreeChunkTokens();
|
|
2399
|
+
const partiallyFreeTokens = this._streamRegulator.getPartiallyFreeChunk(this.model.tokenizer);
|
|
2400
|
+
const queuedTokensBeforeStopTrigger = getQueuedTokensBeforeStopTrigger(triggeredStops, partiallyFreeTokens, this.model.tokenizer);
|
|
2401
|
+
const { firstRemainingGenerationAfterStop } = StopGenerationDetector.getFirstRemainingGenerationAfterStop(triggeredStops);
|
|
2402
|
+
const remainingTokens = typeof firstRemainingGenerationAfterStop === "string"
|
|
2403
|
+
? firstRemainingGenerationAfterStop === ""
|
|
2404
|
+
? []
|
|
2405
|
+
: this.model.tokenize(firstRemainingGenerationAfterStop, false)
|
|
2406
|
+
: (firstRemainingGenerationAfterStop ?? []);
|
|
2407
|
+
const remainingText = typeof firstRemainingGenerationAfterStop === "string"
|
|
2408
|
+
? firstRemainingGenerationAfterStop
|
|
2409
|
+
: this.model.detokenize(remainingTokens, false, queuedTokensBeforeStopTrigger.length === 0
|
|
2410
|
+
? this._getTokenTrailFromResult()
|
|
2411
|
+
: queuedTokensBeforeStopTrigger);
|
|
2412
|
+
this._pushCurrentTokens([...freeTokens, ...queuedTokensBeforeStopTrigger]);
|
|
2413
|
+
stopDetector.clearTriggeredStops();
|
|
2414
|
+
this._streamRegulator.reset();
|
|
2415
|
+
return [remainingTokens, remainingText];
|
|
2416
|
+
}
|
|
2417
|
+
_closeSegment(type) {
|
|
2418
|
+
if (type == null)
|
|
2419
|
+
return;
|
|
2420
|
+
const lastSegment = this._segments.at(-1);
|
|
2421
|
+
const now = Date.now();
|
|
2422
|
+
if (lastSegment != null && !(lastSegment instanceof Array) && lastSegment.type === type && this._segmentsStack.at(-1) === type) {
|
|
2423
|
+
if (lastSegment.ended !== true) {
|
|
2424
|
+
lastSegment.ended = true;
|
|
2425
|
+
lastSegment.endTime = now;
|
|
2426
|
+
this.onResponseChunk?.({
|
|
2427
|
+
type: "segment",
|
|
2428
|
+
segmentType: type,
|
|
2429
|
+
tokens: [],
|
|
2430
|
+
text: "",
|
|
2431
|
+
segmentStartTime: undefined,
|
|
2432
|
+
segmentEndTime: new Date(now)
|
|
2433
|
+
});
|
|
2434
|
+
}
|
|
2435
|
+
const lastContextWindowSegment = this._contextWindowSegments.at(-1);
|
|
2436
|
+
if (lastContextWindowSegment != null && !(lastContextWindowSegment instanceof Array) &&
|
|
2437
|
+
lastContextWindowSegment.type === type && this._segmentsStack.at(-1) === type) {
|
|
2438
|
+
if (lastContextWindowSegment.ended !== true) {
|
|
2439
|
+
lastContextWindowSegment.ended = true;
|
|
2440
|
+
lastContextWindowSegment.endTime = now;
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
else
|
|
2444
|
+
this._contextWindowSegments.push({ type, tokens: [], ended: true, start: false, endTime: now });
|
|
2445
|
+
this._segmentsStackSet.delete(this._segmentsStack.pop());
|
|
2446
|
+
if (this._segmentsStack.length < this._ownedSegmentsStackLength)
|
|
2447
|
+
this._ownedSegmentsStackLength = this._segmentsStack.length;
|
|
2448
|
+
return;
|
|
2449
|
+
}
|
|
2450
|
+
const typeIndex = this._segmentsStack.lastIndexOf(type);
|
|
2451
|
+
if (typeIndex < 0)
|
|
2452
|
+
return;
|
|
2453
|
+
for (let i = this._segmentsStack.length - 1; i >= typeIndex; i--) {
|
|
2454
|
+
const segmentType = this._segmentsStack.pop();
|
|
2455
|
+
this._segmentsStackSet.delete(segmentType);
|
|
2456
|
+
if (this._segmentsStack.length < this._ownedSegmentsStackLength)
|
|
2457
|
+
this._ownedSegmentsStackLength = this._segmentsStack.length;
|
|
2458
|
+
this._segments.push({ type: segmentType, tokens: [], ended: true, start: false, endTime: now });
|
|
2459
|
+
this._contextWindowSegments.push({ type: segmentType, tokens: [], ended: true, start: false, endTime: now });
|
|
2460
|
+
this.onResponseChunk?.({
|
|
2461
|
+
type: "segment",
|
|
2462
|
+
segmentType: segmentType,
|
|
2463
|
+
tokens: [],
|
|
2464
|
+
text: "",
|
|
2465
|
+
segmentStartTime: undefined,
|
|
2466
|
+
segmentEndTime: new Date(now)
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
_clearDetectors(skipDetector) {
|
|
2471
|
+
if (this._closeAllSegmentsDetector !== skipDetector) {
|
|
2472
|
+
this._closeAllSegmentsDetector?.clearInProgressStops();
|
|
2473
|
+
this._closeAllSegmentsDetector?.clearTriggeredStops();
|
|
2474
|
+
}
|
|
2475
|
+
for (const { prefix, suffix } of this._segmentDetectors.values()) {
|
|
2476
|
+
if (prefix !== skipDetector) {
|
|
2477
|
+
prefix.clearInProgressStops();
|
|
2478
|
+
prefix.clearTriggeredStops();
|
|
2479
|
+
}
|
|
2480
|
+
if (suffix !== skipDetector) {
|
|
2481
|
+
suffix?.clearInProgressStops();
|
|
2482
|
+
suffix?.clearTriggeredStops();
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
_pushCurrentTokens(tokens) {
|
|
2487
|
+
const lastSegment = this._segments.at(-1);
|
|
2488
|
+
const lastContextWindowSegment = this._contextWindowSegments.at(-1);
|
|
2489
|
+
const type = this._segmentsStack.at(-1);
|
|
2490
|
+
this._segmentTokenCounts.set(type, (this._segmentTokenCounts.get(type) ?? 0) + tokens.length);
|
|
2491
|
+
if (type == null) {
|
|
2492
|
+
if (lastSegment == null) {
|
|
2493
|
+
const text = (this.onResponseChunk != null || this.onTextChunk != null)
|
|
2494
|
+
? this.model.detokenize(tokens, false, this._getTokenTrailFromResult())
|
|
2495
|
+
: "";
|
|
2496
|
+
this._segments.push(tokens);
|
|
2497
|
+
this.onToken?.(tokens.slice());
|
|
2498
|
+
this.onTextChunk?.(text);
|
|
2499
|
+
this.onResponseChunk?.({ type: undefined, segmentType: undefined, tokens: tokens.slice(), text });
|
|
2500
|
+
}
|
|
2501
|
+
else {
|
|
2502
|
+
const text = (this.onResponseChunk != null || this.onTextChunk != null)
|
|
2503
|
+
? this.model.detokenize(tokens, false, this._getTokenTrailFromResult())
|
|
2504
|
+
: "";
|
|
2505
|
+
if (lastSegment instanceof Array)
|
|
2506
|
+
pushAll(lastSegment, tokens);
|
|
2507
|
+
else
|
|
2508
|
+
this._segments.push(tokens);
|
|
2509
|
+
this.onToken?.(tokens.slice());
|
|
2510
|
+
this.onTextChunk?.(text);
|
|
2511
|
+
this.onResponseChunk?.({ type: undefined, segmentType: undefined, tokens: tokens.slice(), text });
|
|
2512
|
+
}
|
|
2513
|
+
if (lastContextWindowSegment == null)
|
|
2514
|
+
this._contextWindowSegments.push(tokens.slice());
|
|
2515
|
+
else {
|
|
2516
|
+
if (lastContextWindowSegment instanceof Array)
|
|
2517
|
+
pushAll(lastContextWindowSegment, tokens);
|
|
2518
|
+
else
|
|
2519
|
+
this._contextWindowSegments.push(tokens.slice());
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
else {
|
|
2523
|
+
const now = Date.now();
|
|
2524
|
+
if (lastSegment == null) {
|
|
2525
|
+
const text = this.onResponseChunk != null
|
|
2526
|
+
? this.model.detokenize(tokens, false, this._getTokenTrailFromResult())
|
|
2527
|
+
: "";
|
|
2528
|
+
this._segments.push({
|
|
2529
|
+
type,
|
|
2530
|
+
tokens,
|
|
2531
|
+
ended: false,
|
|
2532
|
+
start: this._segmentsStack.length > this._ownedSegmentsStackLength,
|
|
2533
|
+
startTime: now
|
|
2534
|
+
});
|
|
2535
|
+
this.onResponseChunk?.({
|
|
2536
|
+
type: "segment",
|
|
2537
|
+
segmentType: type,
|
|
2538
|
+
tokens: tokens.slice(),
|
|
2539
|
+
text,
|
|
2540
|
+
segmentStartTime: new Date(now)
|
|
2541
|
+
});
|
|
2542
|
+
}
|
|
2543
|
+
else {
|
|
2544
|
+
const text = this.onResponseChunk != null
|
|
2545
|
+
? this.model.detokenize(tokens, false, this._getTokenTrailFromResult())
|
|
2546
|
+
: "";
|
|
2547
|
+
if (lastSegment instanceof Array || lastSegment.type !== type) {
|
|
2548
|
+
this._segments.push({
|
|
2549
|
+
type,
|
|
2550
|
+
tokens,
|
|
2551
|
+
ended: false,
|
|
2552
|
+
start: this._segmentsStack.length > this._ownedSegmentsStackLength,
|
|
2553
|
+
startTime: now
|
|
2554
|
+
});
|
|
2555
|
+
this.onResponseChunk?.({
|
|
2556
|
+
type: "segment",
|
|
2557
|
+
segmentType: type,
|
|
2558
|
+
tokens: tokens.slice(),
|
|
2559
|
+
text,
|
|
2560
|
+
segmentStartTime: new Date(now)
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
else {
|
|
2564
|
+
pushAll(lastSegment.tokens, tokens);
|
|
2565
|
+
this.onResponseChunk?.({
|
|
2566
|
+
type: "segment",
|
|
2567
|
+
segmentType: type,
|
|
2568
|
+
tokens: tokens.slice(),
|
|
2569
|
+
text,
|
|
2570
|
+
segmentStartTime: undefined
|
|
2571
|
+
});
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
if (lastContextWindowSegment == null)
|
|
2575
|
+
this._contextWindowSegments.push({
|
|
2576
|
+
type,
|
|
2577
|
+
tokens: tokens.slice(),
|
|
2578
|
+
ended: false,
|
|
2579
|
+
start: this._segmentsStack.length > this._ownedSegmentsStackLength,
|
|
2580
|
+
startTime: now
|
|
2581
|
+
});
|
|
2582
|
+
else {
|
|
2583
|
+
if (lastContextWindowSegment instanceof Array || lastContextWindowSegment.type !== type)
|
|
2584
|
+
this._contextWindowSegments.push({
|
|
2585
|
+
type,
|
|
2586
|
+
tokens: tokens.slice(),
|
|
2587
|
+
ended: false,
|
|
2588
|
+
start: this._segmentsStack.length > this._ownedSegmentsStackLength,
|
|
2589
|
+
startTime: now
|
|
2590
|
+
});
|
|
2591
|
+
else
|
|
2592
|
+
pushAll(lastContextWindowSegment.tokens, tokens);
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
_getTokenTrailFromResult() {
|
|
2597
|
+
const res = [];
|
|
2598
|
+
for (let i = this._segments.length - 1; i >= 0; i--) {
|
|
2599
|
+
const segment = this._segments[i];
|
|
2600
|
+
const segmentTokens = segment instanceof Array
|
|
2601
|
+
? segment
|
|
2602
|
+
: segment.tokens;
|
|
2603
|
+
for (let j = segmentTokens.length - 1; j >= 0; j--) {
|
|
2604
|
+
res.unshift(segmentTokens[j]);
|
|
2605
|
+
if (res.length >= maxRecentDetokenizerTokens)
|
|
2606
|
+
return res;
|
|
2607
|
+
}
|
|
2608
|
+
}
|
|
2609
|
+
for (let i = this._initialTokensTrail.length - 1; i >= 0; i--) {
|
|
2610
|
+
res.unshift(this._initialTokensTrail[i]);
|
|
2611
|
+
if (res.length >= maxRecentDetokenizerTokens)
|
|
2612
|
+
return res;
|
|
2613
|
+
}
|
|
2614
|
+
return res;
|
|
2615
|
+
}
|
|
2616
|
+
getModelResponseSegments(trimWhitespaceSuffix = false) {
|
|
2617
|
+
return this._getModelResponseForSegments(this._segments, this._segmentsStartTokenTrail, trimWhitespaceSuffix);
|
|
2618
|
+
}
|
|
2619
|
+
getContextWindowModelResponseSegments(trimWhitespaceSuffix = false) {
|
|
2620
|
+
return this._getModelResponseForSegments(this._contextWindowSegments, this._contextWindowStartTokenTrail, trimWhitespaceSuffix);
|
|
2621
|
+
}
|
|
2622
|
+
_getModelResponseForSegments(rawSegments, recentTokens, trimWhitespaceSuffix) {
|
|
2623
|
+
let tokenTrail = resolveLastTokens([recentTokens]);
|
|
2624
|
+
return rawSegments.map((rawSegment, index) => {
|
|
2625
|
+
const isLast = index === rawSegments.length - 1;
|
|
2626
|
+
if (rawSegment instanceof Array) {
|
|
2627
|
+
let text = this.model.detokenize(rawSegment, false, tokenTrail);
|
|
2628
|
+
if (isLast && trimWhitespaceSuffix)
|
|
2629
|
+
text = text.trimEnd();
|
|
2630
|
+
tokenTrail = resolveLastTokens([tokenTrail, rawSegment]);
|
|
2631
|
+
return text;
|
|
2632
|
+
}
|
|
2633
|
+
let text = this.model.detokenize(rawSegment.tokens, false, tokenTrail);
|
|
2634
|
+
if (isLast && rawSegment.ended && trimWhitespaceSuffix)
|
|
2635
|
+
text = text.trimEnd();
|
|
2636
|
+
tokenTrail = resolveLastTokens([tokenTrail, rawSegment.tokens]);
|
|
2637
|
+
const segmentDefinition = this._segmentDefinitions.get(rawSegment.type);
|
|
2638
|
+
return {
|
|
2639
|
+
type: "segment",
|
|
2640
|
+
segmentType: rawSegment.type,
|
|
2641
|
+
text,
|
|
2642
|
+
ended: rawSegment.ended,
|
|
2643
|
+
raw: segmentDefinition == null
|
|
2644
|
+
? LlamaText([text]).toJSON()
|
|
2645
|
+
: LlamaText([
|
|
2646
|
+
rawSegment.start
|
|
2647
|
+
? segmentDefinition.prefix
|
|
2648
|
+
: "",
|
|
2649
|
+
text,
|
|
2650
|
+
rawSegment.ended
|
|
2651
|
+
? (segmentDefinition.suffix ?? "")
|
|
2652
|
+
: ""
|
|
2653
|
+
]).toJSON(),
|
|
2654
|
+
startTime: rawSegment.startTime != null
|
|
2655
|
+
? new Date(rawSegment.startTime).toISOString()
|
|
2656
|
+
: undefined,
|
|
2657
|
+
endTime: rawSegment.endTime != null
|
|
2658
|
+
? new Date(rawSegment.endTime).toISOString()
|
|
2659
|
+
: undefined
|
|
2660
|
+
};
|
|
2661
|
+
});
|
|
2662
|
+
}
|
|
2663
|
+
static getStackFromModelResponse(modelResponse) {
|
|
2664
|
+
const stack = [];
|
|
2665
|
+
const stackSet = new Set();
|
|
2666
|
+
for (const item of modelResponse) {
|
|
2667
|
+
if (typeof item === "string" || isChatModelResponseFunctionCall(item))
|
|
2668
|
+
continue;
|
|
2669
|
+
void item.type;
|
|
2670
|
+
if (item.ended && stack.at(-1) === item.segmentType) {
|
|
2671
|
+
stack.pop();
|
|
2672
|
+
stackSet.delete(item.segmentType);
|
|
2673
|
+
}
|
|
2674
|
+
else if (!item.ended && !stackSet.has(item.segmentType)) {
|
|
2675
|
+
stack.push(item.segmentType);
|
|
2676
|
+
stackSet.add(item.segmentType);
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
return stack;
|
|
2680
|
+
}
|
|
2681
|
+
static getSegmentTokenCounts(modelResponse, tokenizer) {
|
|
2682
|
+
const segmentTokenCounts = new Map();
|
|
2683
|
+
for (const item of modelResponse) {
|
|
2684
|
+
if (typeof item === "string") {
|
|
2685
|
+
segmentTokenCounts.set(undefined, (segmentTokenCounts.get(undefined) ?? 0) + tokenizer(item, false, "trimLeadingSpace").length);
|
|
2686
|
+
continue;
|
|
2687
|
+
}
|
|
2688
|
+
else if (isChatModelResponseFunctionCall(item))
|
|
2689
|
+
continue;
|
|
2690
|
+
void item.type;
|
|
2691
|
+
segmentTokenCounts.set(item.segmentType, (segmentTokenCounts.get(item.segmentType) ?? 0) + tokenizer(item.text, false, "trimLeadingSpace").length);
|
|
2692
|
+
}
|
|
2693
|
+
return segmentTokenCounts;
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
//# sourceMappingURL=LlamaChat.js.map
|