@easbot/local-model-sdk 0.3.29 → 0.3.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import h from'zod';import {NamedError,Log,errorMeta}from'@easbot/utils';import*as H from'os';import*as N from'path';import N__default from'path';import*as y from'fs';import {streamText}from'ai';var se=Object.defineProperty;var ue=(m,e,n)=>e in m?se(m,e,{enumerable:true,configurable:true,writable:true,value:n}):m[e]=n;var f=(m,e,n)=>ue(m,typeof e!="symbol"?e+"":e,n);var w={"qwen3-0.6b":{modelId:"qwen3-0.6b",huggingFaceId:"onnx-community/Qwen3-0.6B-ONNX",contextLength:32768,device:"cpu",dtype:"q4f16",defaultSettings:{temperature:0,topP:.9,topK:40,maxTokens:32e3,repetitionPenalty:1.1,stopSequences:[]}},"qwen3.5-0.8b":{modelId:"qwen3.5-0.8b",huggingFaceId:"onnx-community/Qwen3.5-0.8B-ONNX",contextLength:32768,dtype:"q4",defaultSettings:{temperature:.7,topP:.9,topK:40,maxTokens:32e3,repetitionPenalty:1.1,stopSequences:[]}},"gemma-3-1b-it":{modelId:"gemma-3-1b-it",huggingFaceId:"onnx-community/gemma-3-1b-it-ONNX",contextLength:32768,dtype:"q4",defaultSettings:{temperature:.7,topP:.9,topK:40,maxTokens:32e3,repetitionPenalty:1.1,stopSequences:[]}}},P={"bge-small-zh-v1.5":{modelId:"bge-small-zh-v1.5",huggingFaceId:"Xenova/bge-small-zh-v1.5",dimensions:512,maxEmbeddingsPerCall:32},"bge-base-zh-v1.5":{modelId:"bge-base-zh-v1.5",huggingFaceId:"Xenova/bge-base-zh-v1.5",dimensions:768,maxEmbeddingsPerCall:32,dtype:"q4"},"bge-large-zh-v1.5":{modelId:"bge-large-zh-v1.5",huggingFaceId:"Xenova/bge-large-zh-v1.5",dimensions:1024,maxEmbeddingsPerCall:32,dtype:"q4"},"all-MiniLM-L6-v2":{modelId:"all-MiniLM-L6-v2",huggingFaceId:"sentence-transformers/all-MiniLM-L6-v2",dimensions:384,maxEmbeddingsPerCall:32,dtype:"q4"}};var l;(d=>(d.NamedError=NamedError,d.ModelNotFoundError=d.NamedError.create("LocalModelNotFoundError",h.object({message:h.string(),modelId:h.string().optional(),huggingFaceId:h.string().optional()})),d.ModelLoadError=d.NamedError.create("LocalModelLoadError",h.object({message:h.string(),modelId:h.string().optional(),huggingFaceId:h.string().optional()})),d.ModelNotInitializedError=d.NamedError.create("LocalModelNotInitializedError",h.object({message:h.string(),modelId:h.string().optional()})),d.GenerationError=d.NamedError.create("LocalGenerationError",h.object({message:h.string(),modelId:h.string().optional()})),d.EmbeddingError=d.NamedError.create("LocalEmbeddingError",h.object({message:h.string(),modelId:h.string().optional()})),d.ProcessingError=d.NamedError.create("LocalProcessingError",h.object({message:h.string(),operation:h.string().optional()})),d.InvalidInputError=d.NamedError.create("LocalInvalidInputError",h.object({message:h.string(),field:h.string().optional(),value:h.unknown().optional()})),d.UnsupportedFeatureError=d.NamedError.create("LocalUnsupportedFeatureError",h.object({message:h.string(),feature:h.string().optional(),allowed:h.array(h.string()).optional()})),d.CacheError=d.NamedError.create("LocalCacheError",h.object({message:h.string(),cacheDir:h.string().optional(),operation:h.string().optional()})),d.AbortedError=d.NamedError.create("LocalAbortedError",h.object({message:h.string()})),d.OutOfMemoryError=d.NamedError.create("LocalOutOfMemoryError",h.object({message:h.string(),modelId:h.string().optional()}))))(l||(l={}));var W=(d=>(d.MODEL_NOT_FOUND="LocalModelNotFoundError",d.MODEL_LOAD_ERROR="LocalModelLoadError",d.MODEL_NOT_INITIALIZED="LocalModelNotInitializedError",d.GENERATION_ERROR="LocalGenerationError",d.EMBEDDING_ERROR="LocalEmbeddingError",d.INVALID_INPUT="LocalInvalidInputError",d.UNSUPPORTED_FEATURE="LocalUnsupportedFeatureError",d.CACHE_ERROR="LocalCacheError",d.PROCESSING_ERROR="LocalProcessingError",d.ABORTED="LocalAbortedError",d.OUT_OF_MEMORY="LocalOutOfMemoryError",d.UNKNOWN_ERROR="UNKNOWN_ERROR",d))(W||{}),x=class{static modelLoadError(e){return e instanceof NamedError?e:new l.ModelLoadError({message:`Model load failed: ${e.message}`},{cause:e})}static generationError(e){return e instanceof NamedError?e:new l.GenerationError({message:`Generation failed: ${e.message}`},{cause:e})}static embeddingError(e){return e instanceof NamedError?e:new l.EmbeddingError({message:`Embedding failed: ${e.message}`},{cause:e})}static validationError(e){return new l.InvalidInputError({message:e})}static abortError(){return new l.AbortedError({message:"Operation aborted"})}static unsupportedFeature(e){return new l.UnsupportedFeatureError({message:`Unsupported feature: ${e}`,feature:e})}};var de=N.join(H.homedir(),".cache","easbot","models"),ge=Log.create({service:"model-cache"}),D=class{constructor(e){f(this,"cacheDir");this.cacheDir=e.cacheDir||de;}getCachePath(e){return N.join(this.cacheDir,e)}isCached(e){try{let n=this.getCachePath(e);return y.existsSync(n)&&y.statSync(n).isDirectory()}catch(n){return ge.debug("Cache check failed; treating as not cached",{modelId:e,error:errorMeta(n)}),false}}async clear(e){try{if(e){let n=this.getCachePath(e);y.existsSync(n)&&await this.removeDirectory(n);}else y.existsSync(this.cacheDir)&&await this.removeDirectory(this.cacheDir);}catch(n){throw new l.CacheError({message:`Failed to clear cache: ${errorMeta(n).message}`,cacheDir:this.cacheDir,operation:"clear"},{cause:n})}}async getCacheSize(e){try{let n=e?this.getCachePath(e):this.cacheDir;return y.existsSync(n)?await this.getDirectorySize(n):0}catch(n){throw new l.CacheError({message:`Failed to get cache size: ${errorMeta(n).message}`,cacheDir:this.cacheDir,operation:"get-size"},{cause:n})}}async getDirectorySize(e){let n=0,t=y.readdirSync(e);for(let r of t){let a=N.join(e,r),o=y.statSync(a);o.isDirectory()?n+=await this.getDirectorySize(a):n+=o.size;}return n}async removeDirectory(e){if(!y.existsSync(e))return;let n=y.readdirSync(e);for(let t of n){let r=N.join(e,t);y.statSync(r).isDirectory()?await this.removeDirectory(r):y.unlinkSync(r);}y.rmdirSync(e);}ensureCacheDir(){try{y.existsSync(this.cacheDir)||y.mkdirSync(this.cacheDir,{recursive:!0});}catch(e){throw new l.CacheError({message:`Failed to create cache directory: ${errorMeta(e).message}`,cacheDir:this.cacheDir,operation:"create-dir"},{cause:e})}}};var b=Log.create({service:"transformers-engine"}),C=null;async function fe(){if(!C){C=(await import('@huggingface/transformers')).env;let e=N.join(H.homedir(),".cache","easbot","models");process.env.HF_HOME||(process.env.HF_HOME=e),C.allowLocalModels=true,C.allowRemoteModels=true,C.useBrowserCache=false,C.useFSCache=true;}return C}var K=null;async function J(){return K||(K=(await import('@huggingface/transformers')).pipeline),K}var z=class{constructor(e){f(this,"pipeline",null);f(this,"tokenizer",null);f(this,"isInitialized",false);f(this,"config");f(this,"modelCache");this.config=e,this.modelCache=new D({cacheDir:e.cacheDir});}async configureEnvironment(){let e=await fe();this.modelCache.ensureCacheDir(),process.env.HF_HOME||(process.env.HF_HOME=this.config.cacheDir),e.cacheDir=this.config.cacheDir,e.allowLocalModels=true,e.allowRemoteModels=true,e.useBrowserCache=false,e.useFSCache=true,e.backends?.onnx&&(e.backends.onnx.logLevel="error"),this.config.verbose&&b.debug("\u73AF\u5883\u914D\u7F6E\u5B8C\u6210",{cacheDir:this.config.cacheDir,hfHome:process.env.HF_HOME,modelId:this.config.modelId,modelType:this.config.modelType});}async initialize(){if(this.isInitialized){this.config.verbose&&b.debug("\u6A21\u578B\u5DF2\u521D\u59CB\u5316\uFF0C\u8DF3\u8FC7\u91CD\u590D\u52A0\u8F7D");return}await this.configureEnvironment();try{this.config.verbose&&b.debug("\u5F00\u59CB\u521D\u59CB\u5316\u6A21\u578B");let e,n,t;if(this.config.modelType==="language"){let o=w[this.config.modelId];if(!o)throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${this.config.modelId}`,modelId:this.config.modelId});e=o.huggingFaceId,n=o.dtype,t=o.device;}else {let o=P[this.config.modelId];if(!o)throw new l.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${this.config.modelId}`,modelId:this.config.modelId});e=o.huggingFaceId,n=o.dtype;}this.config.verbose&&(b.debug("\u52A0\u8F7D\u6A21\u578B",{huggingFaceId:e,dtype:n||"auto"}),this.modelCache.isCached(e)?b.debug("\u4F7F\u7528\u7F13\u5B58\u7684\u6A21\u578B"):b.debug("\u9996\u6B21\u4E0B\u8F7D\u6A21\u578B\uFF0C\u53EF\u80FD\u9700\u8981\u4E00\u4E9B\u65F6\u95F4"));let r={cache_dir:this.config.cacheDir,local_files_only:!0};if(n&&(r.dtype=n),t&&(r.device=t),!this.modelCache.isCached(e))throw this.config.verbose&&b.warn("Local cache not found",{huggingFaceId:e,cacheDir:this.config.cacheDir}),new l.ModelNotFoundError({message:`Model ${e} not found in local cache. Please download to: ${this.config.cacheDir}`,huggingFaceId:e});if(this.config.modelType==="language"){let o=this.config.pipelineType||"text-generation";this.config.verbose&&b.debug("\u52A0\u8F7D\u8BED\u8A00\u6A21\u578B pipeline",{pipelineType:o,huggingFaceId:e});let s=await J();this.pipeline=await s(o,e,r);}else {let o=await J();this.pipeline=await o("feature-extraction",e,r);}this.tokenizer=this.pipeline.tokenizer,this.isInitialized=!0,this.config.verbose&&b.debug("Model initialized successfully",{modelId:this.config.modelId});}catch(e){throw this.config.verbose&&b.error("Model initialization failed",{error:errorMeta(e)}),x.modelLoadError(e instanceof Error?e:new Error(String(e)))}}extractAssistantResponse(e,n){let t=`assistant
1
+ import h from'zod';import {NamedError,Log,errorMeta}from'@easbot/utils';import*as Y from'os';import*as N from'path';import N__default from'path';import*as y from'fs';import {streamText}from'ai';var se=Object.defineProperty;var ue=(m,e,n)=>e in m?se(m,e,{enumerable:true,configurable:true,writable:true,value:n}):m[e]=n;var f=(m,e,n)=>ue(m,typeof e!="symbol"?e+"":e,n);var T={"qwen3-0.6b":{modelId:"qwen3-0.6b",huggingFaceId:"onnx-community/Qwen3-0.6B-ONNX",contextLength:32768,device:"cpu",dtype:"q4f16",defaultSettings:{temperature:0,topP:.9,topK:40,maxTokens:32e3,repetitionPenalty:1.1,stopSequences:[]}},"qwen3.5-0.8b":{modelId:"qwen3.5-0.8b",huggingFaceId:"onnx-community/Qwen3.5-0.8B-ONNX",contextLength:32768,dtype:"q4",defaultSettings:{temperature:.7,topP:.9,topK:40,maxTokens:32e3,repetitionPenalty:1.1,stopSequences:[]}},"gemma-3-1b-it":{modelId:"gemma-3-1b-it",huggingFaceId:"onnx-community/gemma-3-1b-it-ONNX",contextLength:32768,dtype:"q4",defaultSettings:{temperature:.7,topP:.9,topK:40,maxTokens:32e3,repetitionPenalty:1.1,stopSequences:[]}}},P={"bge-small-zh-v1.5":{modelId:"bge-small-zh-v1.5",huggingFaceId:"Xenova/bge-small-zh-v1.5",dimensions:512,maxEmbeddingsPerCall:32},"bge-base-zh-v1.5":{modelId:"bge-base-zh-v1.5",huggingFaceId:"Xenova/bge-base-zh-v1.5",dimensions:768,maxEmbeddingsPerCall:32,dtype:"q4"},"bge-large-zh-v1.5":{modelId:"bge-large-zh-v1.5",huggingFaceId:"Xenova/bge-large-zh-v1.5",dimensions:1024,maxEmbeddingsPerCall:32,dtype:"q4"},"all-MiniLM-L6-v2":{modelId:"all-MiniLM-L6-v2",huggingFaceId:"sentence-transformers/all-MiniLM-L6-v2",dimensions:384,maxEmbeddingsPerCall:32,dtype:"q4"}};var l;(d=>(d.NamedError=NamedError,d.ModelNotFoundError=d.NamedError.create("LocalModelNotFoundError",h.object({message:h.string(),modelId:h.string().optional(),huggingFaceId:h.string().optional()})),d.ModelLoadError=d.NamedError.create("LocalModelLoadError",h.object({message:h.string(),modelId:h.string().optional(),huggingFaceId:h.string().optional()})),d.ModelNotInitializedError=d.NamedError.create("LocalModelNotInitializedError",h.object({message:h.string(),modelId:h.string().optional()})),d.GenerationError=d.NamedError.create("LocalGenerationError",h.object({message:h.string(),modelId:h.string().optional()})),d.EmbeddingError=d.NamedError.create("LocalEmbeddingError",h.object({message:h.string(),modelId:h.string().optional()})),d.ProcessingError=d.NamedError.create("LocalProcessingError",h.object({message:h.string(),operation:h.string().optional()})),d.InvalidInputError=d.NamedError.create("LocalInvalidInputError",h.object({message:h.string(),field:h.string().optional(),value:h.unknown().optional()})),d.UnsupportedFeatureError=d.NamedError.create("LocalUnsupportedFeatureError",h.object({message:h.string(),feature:h.string().optional(),allowed:h.array(h.string()).optional()})),d.CacheError=d.NamedError.create("LocalCacheError",h.object({message:h.string(),cacheDir:h.string().optional(),operation:h.string().optional()})),d.AbortedError=d.NamedError.create("LocalAbortedError",h.object({message:h.string()})),d.OutOfMemoryError=d.NamedError.create("LocalOutOfMemoryError",h.object({message:h.string(),modelId:h.string().optional()}))))(l||(l={}));var J=(d=>(d.MODEL_NOT_FOUND="LocalModelNotFoundError",d.MODEL_LOAD_ERROR="LocalModelLoadError",d.MODEL_NOT_INITIALIZED="LocalModelNotInitializedError",d.GENERATION_ERROR="LocalGenerationError",d.EMBEDDING_ERROR="LocalEmbeddingError",d.INVALID_INPUT="LocalInvalidInputError",d.UNSUPPORTED_FEATURE="LocalUnsupportedFeatureError",d.CACHE_ERROR="LocalCacheError",d.PROCESSING_ERROR="LocalProcessingError",d.ABORTED="LocalAbortedError",d.OUT_OF_MEMORY="LocalOutOfMemoryError",d.UNKNOWN_ERROR="UNKNOWN_ERROR",d))(J||{}),x=class{static modelLoadError(e){return e instanceof NamedError?e:new l.ModelLoadError({message:`Model load failed: ${e.message}`},{cause:e})}static generationError(e){return e instanceof NamedError?e:new l.GenerationError({message:`Generation failed: ${e.message}`},{cause:e})}static embeddingError(e){return e instanceof NamedError?e:new l.EmbeddingError({message:`Embedding failed: ${e.message}`},{cause:e})}static validationError(e){return new l.InvalidInputError({message:e})}static abortError(){return new l.AbortedError({message:"Operation aborted"})}static unsupportedFeature(e){return new l.UnsupportedFeatureError({message:`Unsupported feature: ${e}`,feature:e})}};var de=N.join(Y.homedir(),".cache","easbot","models"),ge=Log.create({service:"local-model-sdk.model-cache"}),D=class{constructor(e){f(this,"cacheDir");this.cacheDir=e.cacheDir||de;}getCachePath(e){return N.join(this.cacheDir,e)}isCached(e){try{let n=this.getCachePath(e);return y.existsSync(n)&&y.statSync(n).isDirectory()}catch(n){return ge.errorDegradable("Cache check failed; treating as not cached",{modelId:e,error:errorMeta(n)}),false}}async clear(e){try{if(e){let n=this.getCachePath(e);y.existsSync(n)&&await this.removeDirectory(n);}else y.existsSync(this.cacheDir)&&await this.removeDirectory(this.cacheDir);}catch(n){throw new l.CacheError({message:`Failed to clear cache: ${errorMeta(n).message}`,cacheDir:this.cacheDir,operation:"clear"},{cause:n})}}async getCacheSize(e){try{let n=e?this.getCachePath(e):this.cacheDir;return y.existsSync(n)?await this.getDirectorySize(n):0}catch(n){throw new l.CacheError({message:`Failed to get cache size: ${errorMeta(n).message}`,cacheDir:this.cacheDir,operation:"get-size"},{cause:n})}}async getDirectorySize(e){let n=0,t=y.readdirSync(e);for(let r of t){let a=N.join(e,r),o=y.statSync(a);o.isDirectory()?n+=await this.getDirectorySize(a):n+=o.size;}return n}async removeDirectory(e){if(!y.existsSync(e))return;let n=y.readdirSync(e);for(let t of n){let r=N.join(e,t);y.statSync(r).isDirectory()?await this.removeDirectory(r):y.unlinkSync(r);}y.rmdirSync(e);}ensureCacheDir(){try{y.existsSync(this.cacheDir)||y.mkdirSync(this.cacheDir,{recursive:!0});}catch(e){throw new l.CacheError({message:`Failed to create cache directory: ${errorMeta(e).message}`,cacheDir:this.cacheDir,operation:"create-dir"},{cause:e})}}};var b=Log.create({service:"local-model-sdk.engine"}),C=null;async function fe(){if(!C){C=(await import('@huggingface/transformers')).env;let e=N.join(Y.homedir(),".cache","easbot","models");process.env.HF_HOME||(process.env.HF_HOME=e),C.allowLocalModels=true,C.allowRemoteModels=true,C.useBrowserCache=false,C.useFSCache=true;}return C}var H=null;async function X(){return H||(H=(await import('@huggingface/transformers')).pipeline),H}var B=class{constructor(e){f(this,"pipeline",null);f(this,"tokenizer",null);f(this,"isInitialized",false);f(this,"config");f(this,"modelCache");this.config=e,this.modelCache=new D({cacheDir:e.cacheDir});}async configureEnvironment(){let e=await fe();this.modelCache.ensureCacheDir(),process.env.HF_HOME||(process.env.HF_HOME=this.config.cacheDir),e.cacheDir=this.config.cacheDir,e.allowLocalModels=true,e.allowRemoteModels=true,e.useBrowserCache=false,e.useFSCache=true,e.backends?.onnx&&(e.backends.onnx.logLevel="error"),this.config.verbose&&b.debug("Environment configured",{cacheDir:this.config.cacheDir,hfHome:process.env.HF_HOME,modelId:this.config.modelId,modelType:this.config.modelType});}async initialize(){if(this.isInitialized){this.config.verbose&&b.debug("Model already initialized, skipping reload");return}await this.configureEnvironment();try{this.config.verbose&&b.debug("Initializing model");let e,n,t;if(this.config.modelType==="language"){let o=T[this.config.modelId];if(!o)throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${this.config.modelId}`,modelId:this.config.modelId});e=o.huggingFaceId,n=o.dtype,t=o.device;}else {let o=P[this.config.modelId];if(!o)throw new l.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${this.config.modelId}`,modelId:this.config.modelId});e=o.huggingFaceId,n=o.dtype;}this.config.verbose&&(b.debug("Loading model",{huggingFaceId:e,dtype:n||"auto"}),this.modelCache.isCached(e)?b.debug("Using cached model"):b.debug("First-time model download, this may take a while"));let r={cache_dir:this.config.cacheDir,local_files_only:!0};if(n&&(r.dtype=n),t&&(r.device=t),!this.modelCache.isCached(e))throw this.config.verbose&&b.warn("Local cache not found",{huggingFaceId:e,cacheDir:this.config.cacheDir}),new l.ModelNotFoundError({message:`Model ${e} not found in local cache. Please download to: ${this.config.cacheDir}`,huggingFaceId:e});if(this.config.modelType==="language"){let o=this.config.pipelineType||"text-generation";this.config.verbose&&b.debug("Loading language model pipeline",{pipelineType:o,huggingFaceId:e});let s=await X();this.pipeline=await s(o,e,r);}else {let o=await X();this.pipeline=await o("feature-extraction",e,r);}this.tokenizer=this.pipeline.tokenizer,this.isInitialized=!0,this.config.verbose&&b.debug("Model initialized successfully",{modelId:this.config.modelId});}catch(e){throw this.config.verbose&&b.error("Model initialization failed",{error:errorMeta(e)}),x.modelLoadError(e instanceof Error?e:new Error(errorMeta(e).message))}}extractAssistantResponse(e,n){let t=`assistant
2
2
  `,r=e.lastIndexOf(t);if(r!==-1){let u=e.slice(r+t.length);return u=u.replace(/<\|im_end\|>$/g,""),u.trim()}let a=`
3
3
  assistant
4
- `,o=e.lastIndexOf(a);return o!==-1?e.slice(o+a.length).trim():(e.startsWith(n)?e.slice(n.length):e).trim()}async generate(e,n){let r=w[this.config.modelId]?.defaultSettings||{temperature:.7,topP:.9,topK:40,maxTokens:2048,repetitionPenalty:1.1,stopSequences:[]},a={temperature:n.temperature??r.temperature,topP:n.topP??r.topP,topK:n.topK??r.topK,maxTokens:n.maxTokens??r.maxTokens,repetitionPenalty:n.repetitionPenalty??r.repetitionPenalty,stopSequences:n.stopSequences??r.stopSequences,abortSignal:n.abortSignal};if(this.config.modelType!=="language")throw new l.UnsupportedFeatureError({message:"Current model does not support text generation",feature:"text-generation"});if(n.abortSignal?.aborted)throw x.abortError();try{this.config.verbose&&b.debug("\u5F00\u59CB\u751F\u6210\u6587\u672C");let o=await this.countTokens([e]),s=await this.pipeline(e,{max_new_tokens:a.maxTokens,temperature:a.temperature,top_p:a.topP,top_k:a.topK,repetition_penalty:a.repetitionPenalty,do_sample:a.temperature>0});if(n.abortSignal?.aborted)throw x.abortError();let u=s[0]?.generated_text||"",i=this.extractAssistantResponse(u,e),g=await this.countTokens([i]);return this.config.verbose&&b.debug("\u751F\u6210\u5B8C\u6210",{completionTokens:g}),{content:i,finishReason:{unified:"stop",raw:void 0},usage:{inputTokens:{total:o,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:g,text:g,reasoning:void 0}}}}catch(o){this.config.verbose&&b.error("Generation failed",{error:errorMeta(o)});let s=o instanceof Error?o:new Error(errorMeta(o).message);throw l.AbortedError.isInstance(o)?o:x.generationError(s)}}async generateStream(e,n,t){let a=w[this.config.modelId]?.defaultSettings||{temperature:.7,topP:.9,topK:40,maxTokens:2048,repetitionPenalty:1.1,stopSequences:[]};if(!this.isInitialized)throw new l.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});if(this.config.modelType!=="language")throw new l.UnsupportedFeatureError({message:"Current model does not support text generation",feature:"text-generation"});if(n.abortSignal?.aborted)throw x.abortError();try{this.config.verbose&&b.debug("\u5F00\u59CB\u6D41\u5F0F\u751F\u6210\u6587\u672C\uFF08\u6A21\u62DF\u6D41\u5F0F\u8F93\u51FA\uFF09");let o=await this.pipeline(e,{max_new_tokens:n.maxTokens??a.maxTokens,temperature:n.temperature??a.temperature,top_p:n.topP??a.topP,top_k:n.topK??a.topK,repetition_penalty:n.repetitionPenalty??a.repetitionPenalty,do_sample:(n.temperature??a.temperature)>0});if(n.abortSignal?.aborted)throw x.abortError();let s=o[0]?.generated_text||"",u=this.extractAssistantResponse(s,e),i=u.split(/(\s+)/);for(let E of i){if(n.abortSignal?.aborted)throw x.abortError();E.length>0&&t({type:"text-delta",delta:E});}t({type:"text-end"});let g=await this.countTokens([e]),p=await this.countTokens([u]);t({type:"finish",finishReason:{unified:"stop",raw:void 0},usage:{inputTokens:{total:g,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:p,text:p,reasoning:void 0}}}),this.config.verbose&&b.debug("\u6D41\u5F0F\u751F\u6210\u5B8C\u6210",{promptTokens:g,completionTokens:p});}catch(o){this.config.verbose&&b.error("Stream generation failed",{error:errorMeta(o)});let s=o instanceof Error?o:new Error(errorMeta(o).message);throw l.AbortedError.isInstance(o)?o:(t({type:"finish",finishReason:{unified:"error",raw:"generation_error"},usage:{inputTokens:{total:0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:0,text:0,reasoning:void 0}}}),x.generationError(s))}}async embed(e,n){if(!this.isInitialized)throw new l.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});if(this.config.modelType!=="embedding")throw new l.UnsupportedFeatureError({message:"Current model does not support embedding inference",feature:"embedding-inference"});if(n?.aborted)throw x.abortError();try{this.config.verbose&&b.debug("\u5F00\u59CB\u63A8\u7406",{textCount:e.length});let t=await this.pipeline(e,{pooling:"mean",normalize:!0});if(n?.aborted)throw x.abortError();let r=[];if(t.dims&&t.dims.length===2){let[a,o]=t.dims,s=Array.from(t.data);for(let u=0;u<a;u++){let i=u*o,g=i+o;r.push(s.slice(i,g));}}else r.push(Array.from(t.data));return this.config.verbose&&b.debug("\u63A8\u7406\u5B8C\u6210",{embeddingCount:r.length}),r}catch(t){this.config.verbose&&b.error("Embedding inference failed",{error:errorMeta(t)});let r=t instanceof Error?t:new Error(errorMeta(t).message);throw l.AbortedError.isInstance(t)?t:x.embeddingError(r)}}async countTokens(e){if(!this.isInitialized)throw new l.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});try{let n=0;for(let t of e){let r=await this.tokenizer(t);n+=r.input_ids.data.length;}return n}catch(n){return this.config.verbose&&b.error("Token counting failed",{error:errorMeta(n)}),e.reduce((t,r)=>t+Math.ceil(r.length/4),0)}}async dispose(){this.config.verbose&&b.debug("\u5378\u8F7D\u6A21\u578B"),this.pipeline=null,this.tokenizer=null,this.isInitialized=false,this.config.verbose&&b.debug("\u6A21\u578B\u5DF2\u5378\u8F7D");}isReady(){return this.isInitialized}};var T=class{static validateTexts(e){if(!Array.isArray(e))throw new l.InvalidInputError({message:"Input must be a string array"});if(e.length===0)throw new l.InvalidInputError({message:"Input array cannot be empty"});for(let n=0;n<e.length;n++){let t=e[n];if(typeof t!="string")throw new l.InvalidInputError({message:`Input array index ${n} is not a string`,field:"texts",value:t});if(t.trim().length===0)throw new l.InvalidInputError({message:`Input array index ${n} is an empty string`})}}static validateMessages(e){if(!Array.isArray(e))throw new l.InvalidInputError({message:"Messages must be an array"});if(e.length===0)throw new l.InvalidInputError({message:"Messages array cannot be empty"});let n=["system","user","assistant","tool"];for(let t=0;t<e.length;t++){let r=e[t];if(!r||typeof r!="object")throw new l.InvalidInputError({message:`Message index ${t} is not a valid object`});if(!r.role)throw new l.InvalidInputError({message:`Message index ${t} missing role field`});if(!n.includes(r.role))throw new l.UnsupportedFeatureError({message:`Message index ${t} role "${r.role}" is not supported; allowed: ${n.join(", ")}`,feature:"message.role",allowed:n});if(!r.content)throw new l.InvalidInputError({message:`Message index ${t} missing content field`});if(typeof r.content=="string"){if(r.content.trim().length===0)throw new l.InvalidInputError({message:`Message index ${t} content is an empty string`})}else if(Array.isArray(r.content)){if(r.content.length===0)throw new l.InvalidInputError({message:`Message index ${t} content array is empty`});let a=["text","file","reasoning","tool-call","tool-result","tool-approval-response"];for(let o=0;o<r.content.length;o++){let s=r.content[o];if(!s||typeof s!="object")throw new l.InvalidInputError({message:`Message index ${t} content part ${o} is not a valid object`});if(!s.type)throw new l.InvalidInputError({message:`Message index ${t} content part ${o} missing type field`});if(!a.includes(s.type))throw new l.UnsupportedFeatureError({message:`Message index ${t} content part ${o} type "${s.type}" is not supported; allowed: ${a.join(", ")}`,feature:"content.part.type",allowed:a})}}else throw new l.InvalidInputError({message:`Message index ${t} content must be a string or an array`})}}static validateGenerateOptions(e){if(e.temperature!==void 0&&(typeof e.temperature!="number"||e.temperature<0||e.temperature>2))throw new l.InvalidInputError({message:"temperature must be a number between 0 and 2",field:"temperature"});if(e.topP!==void 0&&(typeof e.topP!="number"||e.topP<0||e.topP>1))throw new l.InvalidInputError({message:"topP must be a number between 0 and 1",field:"topP"});if(e.topK!==void 0&&(typeof e.topK!="number"||e.topK<1||!Number.isInteger(e.topK)))throw new l.InvalidInputError({message:"topK must be an integer greater than or equal to 1",field:"topK"});if(e.maxTokens!==void 0&&(typeof e.maxTokens!="number"||e.maxTokens<1||!Number.isInteger(e.maxTokens)))throw new l.InvalidInputError({message:"maxTokens must be an integer greater than or equal to 1",field:"maxTokens"});if(e.repetitionPenalty!==void 0&&(typeof e.repetitionPenalty!="number"||e.repetitionPenalty<0))throw new l.InvalidInputError({message:"repetitionPenalty must be a number greater than or equal to 0",field:"repetitionPenalty"})}};var A=class{static createReadableStream(e,n){return new ReadableStream({async start(t){if(n?.aborted){t.error(new l.AbortedError({message:"Operation aborted"}));return}let r=false,a=()=>{r=true;try{t.error(new l.AbortedError({message:"Operation aborted"}));}catch{}};n?.addEventListener("abort",a);try{if(await(async s=>{let u=s.enqueue.bind(s);s.enqueue=i=>{if(!r)try{u(i);}catch{}},await e(s);})(t),!r)try{t.close();}catch{}}catch(o){if(!r)try{let u=o instanceof NamedError?o:new l.GenerationError({message:`Generation failed: ${errorMeta(o).message}`});t.error(u);}catch{}}finally{n?.removeEventListener("abort",a);}},cancel(){}})}static async*streamToAsyncIterator(e){let n=e.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;yield r;}}finally{n.releaseLock();}}};function Q(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var R=class{constructor(e,n,t){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"defaultObjectGenerationMode","json");f(this,"supportedUrls",{});f(this,"engine");f(this,"modelConfig");if(this.provider=e,this.modelId=n,this.engine=t,this.modelConfig=w[n],!this.modelConfig)throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${n}`,modelId:n})}async doGenerate(e){T.validateMessages(e.prompt);let n=this.convertToChatMLFormat(e.prompt),t={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};T.validateGenerateOptions(t),this.engine.isReady()||await this.engine.initialize();let r=await this.engine.generate(n,t);return {content:[{type:"text",text:r.content||""}],finishReason:r.finishReason,usage:r.usage,warnings:[],request:{body:n}}}async doStream(e){T.validateMessages(e.prompt);let n=this.convertToChatMLFormat(e.prompt),t={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};T.validateGenerateOptions(t),this.engine.isReady()||await this.engine.initialize();let r=[];return {stream:A.createReadableStream(async o=>{o.enqueue({type:"stream-start",warnings:r});let s=Q();o.enqueue({type:"response-metadata",id:s,modelId:this.modelId,timestamp:new Date});let u=null,i=false;try{await this.engine.generateStream(n,t,g=>{if(g.type==="text-delta"){let p=g.delta||"";if(p.length===0)return;u||(u=Q(),o.enqueue({type:"text-start",id:u})),o.enqueue({type:"text-delta",id:u,delta:p});}else g.type==="text-end"?u&&(o.enqueue({type:"text-end",id:u}),u=null):g.type==="finish"&&(u&&(o.enqueue({type:"text-end",id:u}),u=null),o.enqueue({type:"finish",finishReason:g.finishReason??{unified:"stop",raw:void 0},usage:g.usage??{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}}}),i=!0);});}catch(g){o.enqueue({type:"error",error:g instanceof Error?g:new Error(String(g))}),u&&o.enqueue({type:"text-end",id:u}),i||o.enqueue({type:"finish",finishReason:{unified:"error",raw:void 0},usage:{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}}});}},e.abortSignal),request:{body:n}}}convertToChatMLFormat(e){let n=[];for(let t of e){let r="";switch(typeof t.content=="string"?r=t.content:Array.isArray(t.content)&&(r=t.content.filter(a=>a.type==="text").map(a=>"text"in a?a.text:"").join(`
4
+ `,o=e.lastIndexOf(a);return o!==-1?e.slice(o+a.length).trim():(e.startsWith(n)?e.slice(n.length):e).trim()}async generate(e,n){let r=T[this.config.modelId]?.defaultSettings||{temperature:.7,topP:.9,topK:40,maxTokens:2048,repetitionPenalty:1.1,stopSequences:[]},a={temperature:n.temperature??r.temperature,topP:n.topP??r.topP,topK:n.topK??r.topK,maxTokens:n.maxTokens??r.maxTokens,repetitionPenalty:n.repetitionPenalty??r.repetitionPenalty,stopSequences:n.stopSequences??r.stopSequences,abortSignal:n.abortSignal};if(this.config.modelType!=="language")throw new l.UnsupportedFeatureError({message:"Current model does not support text generation",feature:"text-generation"});if(n.abortSignal?.aborted)throw x.abortError();try{this.config.verbose&&b.debug("Generating text");let o=await this.countTokens([e]),s=await this.pipeline(e,{max_new_tokens:a.maxTokens,temperature:a.temperature,top_p:a.topP,top_k:a.topK,repetition_penalty:a.repetitionPenalty,do_sample:a.temperature>0});if(n.abortSignal?.aborted)throw x.abortError();let u=s[0]?.generated_text||"",i=this.extractAssistantResponse(u,e),g=await this.countTokens([i]);return this.config.verbose&&b.debug("Generation completed",{completionTokens:g}),{content:i,finishReason:{unified:"stop",raw:void 0},usage:{inputTokens:{total:o,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:g,text:g,reasoning:void 0}}}}catch(o){this.config.verbose&&b.error("Generation failed",{error:errorMeta(o)});let s=o instanceof Error?o:new Error(errorMeta(o).message);throw l.AbortedError.isInstance(o)?o:x.generationError(s)}}async generateStream(e,n,t){let a=T[this.config.modelId]?.defaultSettings||{temperature:.7,topP:.9,topK:40,maxTokens:2048,repetitionPenalty:1.1,stopSequences:[]};if(!this.isInitialized)throw new l.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});if(this.config.modelType!=="language")throw new l.UnsupportedFeatureError({message:"Current model does not support text generation",feature:"text-generation"});if(n.abortSignal?.aborted)throw x.abortError();try{this.config.verbose&&b.debug("Starting streaming text generation (simulated streaming)");let o=await this.pipeline(e,{max_new_tokens:n.maxTokens??a.maxTokens,temperature:n.temperature??a.temperature,top_p:n.topP??a.topP,top_k:n.topK??a.topK,repetition_penalty:n.repetitionPenalty??a.repetitionPenalty,do_sample:(n.temperature??a.temperature)>0});if(n.abortSignal?.aborted)throw x.abortError();let s=o[0]?.generated_text||"",u=this.extractAssistantResponse(s,e),i=u.split(/(\s+)/);for(let E of i){if(n.abortSignal?.aborted)throw x.abortError();E.length>0&&t({type:"text-delta",delta:E});}t({type:"text-end"});let g=await this.countTokens([e]),p=await this.countTokens([u]);t({type:"finish",finishReason:{unified:"stop",raw:void 0},usage:{inputTokens:{total:g,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:p,text:p,reasoning:void 0}}}),this.config.verbose&&b.debug("Streaming generation completed",{promptTokens:g,completionTokens:p});}catch(o){this.config.verbose&&b.error("Stream generation failed",{error:errorMeta(o)});let s=o instanceof Error?o:new Error(errorMeta(o).message);throw l.AbortedError.isInstance(o)?o:(t({type:"finish",finishReason:{unified:"error",raw:"generation_error"},usage:{inputTokens:{total:0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:0,text:0,reasoning:void 0}}}),x.generationError(s))}}async embed(e,n){if(!this.isInitialized)throw new l.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});if(this.config.modelType!=="embedding")throw new l.UnsupportedFeatureError({message:"Current model does not support embedding inference",feature:"embedding-inference"});if(n?.aborted)throw x.abortError();try{this.config.verbose&&b.debug("Starting inference",{textCount:e.length});let t=await this.pipeline(e,{pooling:"mean",normalize:!0});if(n?.aborted)throw x.abortError();let r=[];if(t.dims&&t.dims.length===2){let[a,o]=t.dims,s=Array.from(t.data);for(let u=0;u<a;u++){let i=u*o,g=i+o;r.push(s.slice(i,g));}}else r.push(Array.from(t.data));return this.config.verbose&&b.debug("Inference completed",{embeddingCount:r.length}),r}catch(t){this.config.verbose&&b.error("Embedding inference failed",{error:errorMeta(t)});let r=t instanceof Error?t:new Error(errorMeta(t).message);throw l.AbortedError.isInstance(t)?t:x.embeddingError(r)}}async countTokens(e){if(!this.isInitialized)throw new l.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});try{let n=0;for(let t of e){let r=await this.tokenizer(t);n+=r.input_ids.data.length;}return n}catch(n){return this.config.verbose&&b.error("Token counting failed",{error:errorMeta(n)}),e.reduce((t,r)=>t+Math.ceil(r.length/4),0)}}async dispose(){this.config.verbose&&b.debug("Unloading model"),this.pipeline=null,this.tokenizer=null,this.isInitialized=false,this.config.verbose&&b.debug("Model unloaded");}isReady(){return this.isInitialized}};var w=class{static validateTexts(e){if(!Array.isArray(e))throw new l.InvalidInputError({message:"Input must be a string array"});if(e.length===0)throw new l.InvalidInputError({message:"Input array cannot be empty"});for(let n=0;n<e.length;n++){let t=e[n];if(typeof t!="string")throw new l.InvalidInputError({message:`Input array index ${n} is not a string`,field:"texts",value:t});if(t.trim().length===0)throw new l.InvalidInputError({message:`Input array index ${n} is an empty string`})}}static validateMessages(e){if(!Array.isArray(e))throw new l.InvalidInputError({message:"Messages must be an array"});if(e.length===0)throw new l.InvalidInputError({message:"Messages array cannot be empty"});let n=["system","user","assistant","tool"];for(let t=0;t<e.length;t++){let r=e[t];if(!r||typeof r!="object")throw new l.InvalidInputError({message:`Message index ${t} is not a valid object`});if(!r.role)throw new l.InvalidInputError({message:`Message index ${t} missing role field`});if(!n.includes(r.role))throw new l.UnsupportedFeatureError({message:`Message index ${t} role "${r.role}" is not supported; allowed: ${n.join(", ")}`,feature:"message.role",allowed:n});if(!r.content)throw new l.InvalidInputError({message:`Message index ${t} missing content field`});if(typeof r.content=="string"){if(r.content.trim().length===0)throw new l.InvalidInputError({message:`Message index ${t} content is an empty string`})}else if(Array.isArray(r.content)){if(r.content.length===0)throw new l.InvalidInputError({message:`Message index ${t} content array is empty`});let a=["text","file","reasoning","tool-call","tool-result","tool-approval-response"];for(let o=0;o<r.content.length;o++){let s=r.content[o];if(!s||typeof s!="object")throw new l.InvalidInputError({message:`Message index ${t} content part ${o} is not a valid object`});if(!s.type)throw new l.InvalidInputError({message:`Message index ${t} content part ${o} missing type field`});if(!a.includes(s.type))throw new l.UnsupportedFeatureError({message:`Message index ${t} content part ${o} type "${s.type}" is not supported; allowed: ${a.join(", ")}`,feature:"content.part.type",allowed:a})}}else throw new l.InvalidInputError({message:`Message index ${t} content must be a string or an array`})}}static validateGenerateOptions(e){if(e.temperature!==void 0&&(typeof e.temperature!="number"||e.temperature<0||e.temperature>2))throw new l.InvalidInputError({message:"temperature must be a number between 0 and 2",field:"temperature"});if(e.topP!==void 0&&(typeof e.topP!="number"||e.topP<0||e.topP>1))throw new l.InvalidInputError({message:"topP must be a number between 0 and 1",field:"topP"});if(e.topK!==void 0&&(typeof e.topK!="number"||e.topK<1||!Number.isInteger(e.topK)))throw new l.InvalidInputError({message:"topK must be an integer greater than or equal to 1",field:"topK"});if(e.maxTokens!==void 0&&(typeof e.maxTokens!="number"||e.maxTokens<1||!Number.isInteger(e.maxTokens)))throw new l.InvalidInputError({message:"maxTokens must be an integer greater than or equal to 1",field:"maxTokens"});if(e.repetitionPenalty!==void 0&&(typeof e.repetitionPenalty!="number"||e.repetitionPenalty<0))throw new l.InvalidInputError({message:"repetitionPenalty must be a number greater than or equal to 0",field:"repetitionPenalty"})}};var A=class{static createReadableStream(e,n){return new ReadableStream({async start(t){if(n?.aborted){t.error(new l.AbortedError({message:"Operation aborted"}));return}let r=false,a=()=>{r=true;try{t.error(new l.AbortedError({message:"Operation aborted"}));}catch{}};n?.addEventListener("abort",a);try{if(await(async s=>{let u=s.enqueue.bind(s);s.enqueue=i=>{if(!r)try{u(i);}catch{}},await e(s);})(t),!r)try{t.close();}catch{}}catch(o){if(!r)try{let u=o instanceof NamedError?o:new l.GenerationError({message:`Generation failed: ${errorMeta(o).message}`});t.error(u);}catch{}}finally{n?.removeEventListener("abort",a);}},cancel(){}})}static async*streamToAsyncIterator(e){let n=e.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;yield r;}}finally{n.releaseLock();}}};function ee(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var R=class{constructor(e,n,t){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"defaultObjectGenerationMode","json");f(this,"supportedUrls",{});f(this,"engine");f(this,"modelConfig");if(this.provider=e,this.modelId=n,this.engine=t,this.modelConfig=T[n],!this.modelConfig)throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${n}`,modelId:n})}async doGenerate(e){w.validateMessages(e.prompt);let n=this.convertToChatMLFormat(e.prompt),t={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};w.validateGenerateOptions(t),this.engine.isReady()||await this.engine.initialize();let r=await this.engine.generate(n,t);return {content:[{type:"text",text:r.content||""}],finishReason:r.finishReason,usage:r.usage,warnings:[],request:{body:n}}}async doStream(e){w.validateMessages(e.prompt);let n=this.convertToChatMLFormat(e.prompt),t={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};w.validateGenerateOptions(t),this.engine.isReady()||await this.engine.initialize();let r=[];return {stream:A.createReadableStream(async o=>{o.enqueue({type:"stream-start",warnings:r});let s=ee();o.enqueue({type:"response-metadata",id:s,modelId:this.modelId,timestamp:new Date});let u=null,i=false;try{await this.engine.generateStream(n,t,g=>{if(g.type==="text-delta"){let p=g.delta||"";if(p.length===0)return;u||(u=ee(),o.enqueue({type:"text-start",id:u})),o.enqueue({type:"text-delta",id:u,delta:p});}else g.type==="text-end"?u&&(o.enqueue({type:"text-end",id:u}),u=null):g.type==="finish"&&(u&&(o.enqueue({type:"text-end",id:u}),u=null),o.enqueue({type:"finish",finishReason:g.finishReason??{unified:"stop",raw:void 0},usage:g.usage??{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}}}),i=!0);});}catch(g){o.enqueue({type:"error",error:g instanceof Error?g:new Error(errorMeta(g).message)}),u&&o.enqueue({type:"text-end",id:u}),i||o.enqueue({type:"finish",finishReason:{unified:"error",raw:void 0},usage:{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}}});}},e.abortSignal),request:{body:n}}}convertToChatMLFormat(e){let n=[];for(let t of e){let r="";switch(typeof t.content=="string"?r=t.content:Array.isArray(t.content)&&(r=t.content.filter(a=>a.type==="text").map(a=>"text"in a?a.text:"").join(`
5
5
  `)),t.role){case "system":n.push(`system
6
6
  ${r}`);break;case "user":n.push(`user
7
7
  ${r}`);break;case "assistant":n.push(`assistant
@@ -107,14 +107,14 @@ CRITICAL OUTPUT RULES:
107
107
  `);}switch(e.role){case "system":return null;case "user":return `<|im_start|>user
108
108
  ${n}<|im_end|>`;case "assistant":return `<|im_start|>assistant
109
109
  ${n}<|im_end|>`;case "tool":return `<|im_start|>tool
110
- ${n}<|im_end|>`;default:{let t=e.role;throw new l.UnsupportedFeatureError({message:`Unsupported message role: ${t}`,feature:"message.role",allowed:["system","user","assistant","tool"]})}}}};var v=class{static processThinkTags(e,n){let t={...e};for(;t.contentBuffer.length>0;)if(t.isInThinkTag){let r=t.contentBuffer.indexOf("</think>");if(r===-1){t.contentBuffer.length>0&&n.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:t.contentBuffer}),t.contentBuffer="";break}if(r>0){let a=t.contentBuffer.substring(0,r);a.length>0&&n.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:a});}n.enqueue({type:"reasoning-end",id:"reasoning-0"}),t.reasoningStarted=false,t.isInThinkTag=false,t.contentBuffer=t.contentBuffer.substring(r+8);}else {let r=t.contentBuffer.indexOf("<think>");if(r===-1)break;if(r>0){let a=t.contentBuffer.substring(0,r);t.textStarted||(t.textStarted=true,n.enqueue({type:"text-start",id:"txt-0"})),a.length>0&&n.enqueue({type:"text-delta",id:"txt-0",delta:a}),n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false;}t.isInThinkTag=true,t.contentBuffer=t.contentBuffer.substring(r+7),t.reasoningStarted||(t.reasoningStarted=true,n.enqueue({type:"reasoning-start",id:"reasoning-0"}));}return t}static finishThinkParsing(e,n){let t={...e};return t.contentBuffer.length>0?t.isInThinkTag?(t.contentBuffer.length>0&&n.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:t.contentBuffer}),t.reasoningStarted&&(n.enqueue({type:"reasoning-end",id:"reasoning-0"}),t.reasoningStarted=false)):(t.textStarted||(n.enqueue({type:"text-start",id:"txt-0"}),t.textStarted=true),t.contentBuffer.length>0&&n.enqueue({type:"text-delta",id:"txt-0",delta:t.contentBuffer}),n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false):(t.textStarted&&(n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false),t.reasoningStarted&&!t.isInThinkTag&&(n.enqueue({type:"reasoning-end",id:"reasoning-0"}),t.reasoningStarted=false)),t}static removeThinkTags(e){return e.replace(/<think>[\s\S]*?<\/think>/g,"").trim()}};function he(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var Z=/\{\s*"name"\s*:\s*"([^"]+)"\s*,\s*"parameters"\s*:\s*(\{[\s\S]*?\})\s*\}/g;function ee(m){let e=[];Z.lastIndex=0;let n;for(;(n=Z.exec(m))!==null;){let t=n[1]||"",r=n[2]||"";try{let a=JSON.parse(r);a&&typeof a=="object"&&!Array.isArray(a)&&e.push({name:t,parameters:JSON.stringify(a),index:n.index,length:n[0].length});}catch{}}return {toolCalls:e}}var I=class m{static extractToolCalls(e){let n=ee(e),t=[],r=[],a=0;for(let o of n.toolCalls)o.index>a&&r.push(e.substring(a,o.index)),t.push({name:o.name,parameters:o.parameters}),a=o.index+o.length;return a<e.length&&r.push(e.substring(a)),{toolCalls:t,remainingText:r.join("").trim()}}static processToolCalls(e,n,t){let r={...e},a=ee(r.contentBuffer);if(a.toolCalls.length===0)return r;let o=[],s=0;for(let i of a.toolCalls){let g=r.contentBuffer.substring(s,i.index);if(g.length>0){o.length=0,o.push(g);let d=g;d.trim()&&(r.textStarted||(n.enqueue({type:"text-start",id:"txt-0"}),r.textStarted=true),n.enqueue({type:"text-delta",id:"txt-0",delta:d}),true);}if(t&&t.length>0&&!t.some(c=>c.name===i.name)){o.push(r.contentBuffer.substring(i.index,i.index+i.length)),s=i.index+i.length;continue}r.textStarted&&(n.enqueue({type:"text-end",id:"txt-0"}),r.textStarted=false);let p=he();n.enqueue({type:"tool-input-start",id:p,toolName:i.name}),n.enqueue({type:"tool-input-delta",id:p,delta:i.parameters}),n.enqueue({type:"tool-input-end",id:p}),n.enqueue({type:"tool-call",toolCallId:p,toolName:i.name,input:i.parameters}),r.completedToolCalls.push({id:p,name:i.name,parameters:i.parameters}),s=i.index+i.length;}return s<r.contentBuffer.length&&o.push(r.contentBuffer.substring(s)),r.contentBuffer=o.join(""),r}static finishToolParsing(e,n){let t={...e};return t.contentBuffer.trim().length>0?(t.textStarted||(n.enqueue({type:"text-start",id:"txt-0"}),t.textStarted=true),n.enqueue({type:"text-delta",id:"txt-0",delta:t.contentBuffer}),n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false):t.textStarted&&(n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false),t}static removeToolCalls(e){let{remainingText:n}=m.extractToolCalls(e);return n}};function te(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var q=class{constructor(e,n,t){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"defaultObjectGenerationMode","json");f(this,"supportedUrls",{});f(this,"engine");f(this,"modelConfig");if(this.provider=e,this.modelId=n,this.engine=t,this.modelConfig=w[n],!this.modelConfig)throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${n}`,modelId:n})}async doGenerate(e){T.validateMessages(e.prompt);let n=(e.tools??[]).filter(p=>"inputSchema"in p),t=_.buildEnhancedPrompt(e.prompt,n),r={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};T.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=await this.engine.generate(t,r),o=v.removeThinkTags(a.content||""),{toolCalls:s,remainingText:u}=I.extractToolCalls(o),i=[];u.trim().length>0&&i.push({type:"text",text:u});for(let p of s)i.push({type:"tool-call",toolCallId:te(),toolName:p.name,input:p.parameters});let g=s.length>0?{unified:"tool-calls",raw:void 0}:a.finishReason;return {content:i,finishReason:g,usage:a.usage,warnings:[],request:{body:t}}}async doStream(e){T.validateMessages(e.prompt);let n=(e.tools??[]).filter(s=>"inputSchema"in s),t=_.buildEnhancedPrompt(e.prompt,n),r={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};T.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=[];return {stream:A.createReadableStream(async s=>{s.enqueue({type:"stream-start",warnings:a});let u=te();s.enqueue({type:"response-metadata",id:u,modelId:this.modelId,timestamp:new Date});let i={isInThinkTag:false,reasoningStarted:false,textStarted:false,contentBuffer:""},g={contentBuffer:"",textStarted:false,completedToolCalls:[]},p=false;try{await this.engine.generateStream(t,r,d=>{if(d.type==="text-delta"){let c=d.delta||"";if(c.length===0)return;i.contentBuffer+=c;let E=v.processThinkTags(i,s);i.isInThinkTag=E.isInThinkTag,i.reasoningStarted=E.reasoningStarted,i.textStarted=E.textStarted,g.contentBuffer+=E.contentBuffer,i.contentBuffer="";let O=I.processToolCalls(g,s,n);g.contentBuffer=O.contentBuffer,g.textStarted=O.textStarted,g.completedToolCalls=O.completedToolCalls;}else if(d.type==="text-end"){let c=v.finishThinkParsing(i,s);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let E=I.finishToolParsing(g,s);g.textStarted=E.textStarted,p=!0;}else if(d.type==="finish"){if(!p){let O=v.finishThinkParsing(i,s);i.textStarted=O.textStarted,i.reasoningStarted=O.reasoningStarted;let ie=I.finishToolParsing(g,s);g.textStarted=ie.textStarted,p=!0;}let E=g.completedToolCalls.length>0?{unified:"tool-calls",raw:void 0}:d.finishReason??{unified:"stop",raw:void 0};s.enqueue({type:"finish",finishReason:E,usage:d.usage??{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}}});}});}catch(d){if(s.enqueue({type:"error",error:d instanceof Error?d:new Error(String(d))}),!p){let c=v.finishThinkParsing(i,s);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let E=I.finishToolParsing(g,s);g.textStarted=E.textStarted;}s.enqueue({type:"finish",finishReason:{unified:"error",raw:void 0},usage:{inputTokens:{total:0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:0,text:void 0,reasoning:void 0}}});}},e.abortSignal),request:{body:t}}}};var V=class{constructor(e){f(this,"config");this.config=e;}createBatches(e){let n=[],t=this.config.batchSize;for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async processBatches(e,n,t){if(t?.aborted)throw new l.AbortedError({message:"Operation aborted"});let r=this.createBatches(e),a=[];for(let o=0;o<r.length;o++){if(t?.aborted)throw new l.AbortedError({message:"Operation aborted"});let s=r[o];if(s){try{let u=await n(s);a.push(...u);}catch(u){let i=u instanceof Error?u:void 0,g=i instanceof NamedError;if(l.AbortedError.isInstance(u))throw u;if(g)throw i;let p=errorMeta(u);throw new l.ProcessingError({message:`Batch ${o+1}/${r.length} processing failed: ${p.message}`,operation:"batch-process"},{cause:i})}o<r.length-1&&this.config.delayBetweenBatches&&this.config.delayBetweenBatches>0&&await this.delay(this.config.delayBetweenBatches,t);}}return a}async delay(e,n){return new Promise((t,r)=>{if(n?.aborted){r(new l.AbortedError({message:"Operation aborted"}));return}let a=setTimeout(()=>{n?.removeEventListener("abort",o),t();},e),o=()=>{clearTimeout(a),r(new l.AbortedError({message:"Operation aborted"}));};n?.addEventListener("abort",o);})}};var F=class{constructor(e,n,t){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"maxEmbeddingsPerCall");f(this,"supportsParallelCalls",false);f(this,"engine");f(this,"modelConfig");if(this.provider=e,this.modelId=n,this.engine=t,this.modelConfig=P[n],!this.modelConfig)throw new l.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${n}`,modelId:n});this.maxEmbeddingsPerCall=this.modelConfig.maxEmbeddingsPerCall;}async doEmbed(e){let{values:n,abortSignal:t}=e;if(T.validateTexts(n),t?.aborted)throw new l.AbortedError({message:"Operation aborted"});this.engine.isReady()||await this.engine.initialize();let a=await new V({batchSize:this.maxEmbeddingsPerCall,delayBetweenBatches:0}).processBatches(n,async s=>{if(t?.aborted)throw new l.AbortedError({message:"Operation aborted"});return await this.engine.embed(s,t)},t),o=await this.engine.countTokens(n);return {embeddings:a,usage:{tokens:o},warnings:[]}}};var U=class{constructor(e,n,t,r={}){f(this,"specificationVersion","v3");f(this,"provider","local");f(this,"modelId");f(this,"languageModel");f(this,"options");f(this,"log",Log.create({service:"local-model-sdk",module:"reranking-model"}));this.modelId=e,this.languageModel=new R("local",e,t),this.options={llm:this.languageModel,totalScore:r.totalScore??1,useEnhancedPrompt:true,promptLanguage:r.promptLanguage??"en"},this.log.debug("LocalRerankingModel created",{modelId:e,totalScore:this.options.totalScore,useEnhancedPrompt:this.options.useEnhancedPrompt,promptLanguage:this.options.promptLanguage});}async doRerank(e){let{query:n,documents:t,topN:r,abortSignal:a}=e,o=t.type==="text"?t.values.map((u,i)=>({content:u,id:`doc_${i+1}`})):t.values.map((u,i)=>{let g=u;return {content:typeof g=="string"?g:JSON.stringify(g),id:typeof g?.id=="string"?g.id:`doc_${i+1}`}}),s=r??o.length;if(o.length===0)return {ranking:[],warnings:[]};try{let u=this.buildRerankPrompt(n,o),g=(await this.languageModel.doGenerate({prompt:[{role:"user",content:[{type:"text",text:u}]}],maxOutputTokens:2048,temperature:0,topP:1,topK:1,abortSignal:a})).content.find(c=>c.type==="text"),p=g&&g.type==="text"?g.text:"",d=this.parseRerankResult(p,o,s);return {ranking:d.results.map(c=>({index:c.index,relevanceScore:c.score})),warnings:d.warnings.map(c=>({type:"other",message:c})),response:{timestamp:new Date,modelId:this.modelId}}}catch(u){return this.log.error("Reranking failed",{error:errorMeta(u)}),{ranking:o.map((g,p)=>({index:p,relevanceScore:o.length>1?this.options.totalScore*(1-.9*p/(o.length-1)):this.options.totalScore})),warnings:[{type:"other",message:`Reranking failed, using original order: ${u.message}`}],response:{timestamp:new Date,modelId:this.modelId}}}}buildRerankPrompt(e,n){let t=n.map((r,a)=>{let o=r.id||`doc_${a+1}`,s=r.content.slice(0,300);return `${a+1}. [ID: ${o}] ${s}`}).join(`
110
+ ${n}<|im_end|>`;default:{let t=e.role;throw new l.UnsupportedFeatureError({message:`Unsupported message role: ${t}`,feature:"message.role",allowed:["system","user","assistant","tool"]})}}}};var v=class{static processThinkTags(e,n){let t={...e};for(;t.contentBuffer.length>0;)if(t.isInThinkTag){let r=t.contentBuffer.indexOf("</think>");if(r===-1){t.contentBuffer.length>0&&n.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:t.contentBuffer}),t.contentBuffer="";break}if(r>0){let a=t.contentBuffer.substring(0,r);a.length>0&&n.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:a});}n.enqueue({type:"reasoning-end",id:"reasoning-0"}),t.reasoningStarted=false,t.isInThinkTag=false,t.contentBuffer=t.contentBuffer.substring(r+8);}else {let r=t.contentBuffer.indexOf("<think>");if(r===-1)break;if(r>0){let a=t.contentBuffer.substring(0,r);t.textStarted||(t.textStarted=true,n.enqueue({type:"text-start",id:"txt-0"})),a.length>0&&n.enqueue({type:"text-delta",id:"txt-0",delta:a}),n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false;}t.isInThinkTag=true,t.contentBuffer=t.contentBuffer.substring(r+7),t.reasoningStarted||(t.reasoningStarted=true,n.enqueue({type:"reasoning-start",id:"reasoning-0"}));}return t}static finishThinkParsing(e,n){let t={...e};return t.contentBuffer.length>0?t.isInThinkTag?(t.contentBuffer.length>0&&n.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:t.contentBuffer}),t.reasoningStarted&&(n.enqueue({type:"reasoning-end",id:"reasoning-0"}),t.reasoningStarted=false)):(t.textStarted||(n.enqueue({type:"text-start",id:"txt-0"}),t.textStarted=true),t.contentBuffer.length>0&&n.enqueue({type:"text-delta",id:"txt-0",delta:t.contentBuffer}),n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false):(t.textStarted&&(n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false),t.reasoningStarted&&!t.isInThinkTag&&(n.enqueue({type:"reasoning-end",id:"reasoning-0"}),t.reasoningStarted=false)),t}static removeThinkTags(e){return e.replace(/<think>[\s\S]*?<\/think>/g,"").trim()}};function be(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var te=/\{\s*"name"\s*:\s*"([^"]+)"\s*,\s*"parameters"\s*:\s*(\{[\s\S]*?\})\s*\}/g;function ne(m){let e=[];te.lastIndex=0;let n;for(;(n=te.exec(m))!==null;){let t=n[1]||"",r=n[2]||"";try{let a=JSON.parse(r);a&&typeof a=="object"&&!Array.isArray(a)&&e.push({name:t,parameters:JSON.stringify(a),index:n.index,length:n[0].length});}catch{}}return {toolCalls:e}}var I=class m{static extractToolCalls(e){let n=ne(e),t=[],r=[],a=0;for(let o of n.toolCalls)o.index>a&&r.push(e.substring(a,o.index)),t.push({name:o.name,parameters:o.parameters}),a=o.index+o.length;return a<e.length&&r.push(e.substring(a)),{toolCalls:t,remainingText:r.join("").trim()}}static processToolCalls(e,n,t){let r={...e},a=ne(r.contentBuffer);if(a.toolCalls.length===0)return r;let o=[],s=0;for(let i of a.toolCalls){let g=r.contentBuffer.substring(s,i.index);if(g.length>0){o.length=0,o.push(g);let d=g;d.trim()&&(r.textStarted||(n.enqueue({type:"text-start",id:"txt-0"}),r.textStarted=true),n.enqueue({type:"text-delta",id:"txt-0",delta:d}),true);}if(t&&t.length>0&&!t.some(c=>c.name===i.name)){o.push(r.contentBuffer.substring(i.index,i.index+i.length)),s=i.index+i.length;continue}r.textStarted&&(n.enqueue({type:"text-end",id:"txt-0"}),r.textStarted=false);let p=be();n.enqueue({type:"tool-input-start",id:p,toolName:i.name}),n.enqueue({type:"tool-input-delta",id:p,delta:i.parameters}),n.enqueue({type:"tool-input-end",id:p}),n.enqueue({type:"tool-call",toolCallId:p,toolName:i.name,input:i.parameters}),r.completedToolCalls.push({id:p,name:i.name,parameters:i.parameters}),s=i.index+i.length;}return s<r.contentBuffer.length&&o.push(r.contentBuffer.substring(s)),r.contentBuffer=o.join(""),r}static finishToolParsing(e,n){let t={...e};return t.contentBuffer.trim().length>0?(t.textStarted||(n.enqueue({type:"text-start",id:"txt-0"}),t.textStarted=true),n.enqueue({type:"text-delta",id:"txt-0",delta:t.contentBuffer}),n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false):t.textStarted&&(n.enqueue({type:"text-end",id:"txt-0"}),t.textStarted=false),t}static removeToolCalls(e){let{remainingText:n}=m.extractToolCalls(e);return n}};function re(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var q=class{constructor(e,n,t){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"defaultObjectGenerationMode","json");f(this,"supportedUrls",{});f(this,"engine");f(this,"modelConfig");if(this.provider=e,this.modelId=n,this.engine=t,this.modelConfig=T[n],!this.modelConfig)throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${n}`,modelId:n})}async doGenerate(e){w.validateMessages(e.prompt);let n=(e.tools??[]).filter(p=>"inputSchema"in p),t=_.buildEnhancedPrompt(e.prompt,n),r={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};w.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=await this.engine.generate(t,r),o=v.removeThinkTags(a.content||""),{toolCalls:s,remainingText:u}=I.extractToolCalls(o),i=[];u.trim().length>0&&i.push({type:"text",text:u});for(let p of s)i.push({type:"tool-call",toolCallId:re(),toolName:p.name,input:p.parameters});let g=s.length>0?{unified:"tool-calls",raw:void 0}:a.finishReason;return {content:i,finishReason:g,usage:a.usage,warnings:[],request:{body:t}}}async doStream(e){w.validateMessages(e.prompt);let n=(e.tools??[]).filter(s=>"inputSchema"in s),t=_.buildEnhancedPrompt(e.prompt,n),r={temperature:e.temperature??this.modelConfig.defaultSettings.temperature,topP:e.topP??this.modelConfig.defaultSettings.topP,topK:e.topK??this.modelConfig.defaultSettings.topK,maxTokens:e.maxOutputTokens??this.modelConfig.defaultSettings.maxTokens,repetitionPenalty:this.modelConfig.defaultSettings.repetitionPenalty,stopSequences:this.modelConfig.defaultSettings.stopSequences,abortSignal:e.abortSignal};w.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=[];return {stream:A.createReadableStream(async s=>{s.enqueue({type:"stream-start",warnings:a});let u=re();s.enqueue({type:"response-metadata",id:u,modelId:this.modelId,timestamp:new Date});let i={isInThinkTag:false,reasoningStarted:false,textStarted:false,contentBuffer:""},g={contentBuffer:"",textStarted:false,completedToolCalls:[]},p=false;try{await this.engine.generateStream(t,r,d=>{if(d.type==="text-delta"){let c=d.delta||"";if(c.length===0)return;i.contentBuffer+=c;let E=v.processThinkTags(i,s);i.isInThinkTag=E.isInThinkTag,i.reasoningStarted=E.reasoningStarted,i.textStarted=E.textStarted,g.contentBuffer+=E.contentBuffer,i.contentBuffer="";let O=I.processToolCalls(g,s,n);g.contentBuffer=O.contentBuffer,g.textStarted=O.textStarted,g.completedToolCalls=O.completedToolCalls;}else if(d.type==="text-end"){let c=v.finishThinkParsing(i,s);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let E=I.finishToolParsing(g,s);g.textStarted=E.textStarted,p=!0;}else if(d.type==="finish"){if(!p){let O=v.finishThinkParsing(i,s);i.textStarted=O.textStarted,i.reasoningStarted=O.reasoningStarted;let ie=I.finishToolParsing(g,s);g.textStarted=ie.textStarted,p=!0;}let E=g.completedToolCalls.length>0?{unified:"tool-calls",raw:void 0}:d.finishReason??{unified:"stop",raw:void 0};s.enqueue({type:"finish",finishReason:E,usage:d.usage??{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}}});}});}catch(d){if(s.enqueue({type:"error",error:d instanceof Error?d:new Error(errorMeta(d).message)}),!p){let c=v.finishThinkParsing(i,s);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let E=I.finishToolParsing(g,s);g.textStarted=E.textStarted;}s.enqueue({type:"finish",finishReason:{unified:"error",raw:void 0},usage:{inputTokens:{total:0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:0,text:void 0,reasoning:void 0}}});}},e.abortSignal),request:{body:t}}}};var V=class{constructor(e){f(this,"config");this.config=e;}createBatches(e){let n=[],t=this.config.batchSize;for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async processBatches(e,n,t){if(t?.aborted)throw new l.AbortedError({message:"Operation aborted"});let r=this.createBatches(e),a=[];for(let o=0;o<r.length;o++){if(t?.aborted)throw new l.AbortedError({message:"Operation aborted"});let s=r[o];if(s){try{let u=await n(s);a.push(...u);}catch(u){let i=u instanceof Error?u:void 0,g=i instanceof NamedError;if(l.AbortedError.isInstance(u))throw u;if(g)throw i;let p=errorMeta(u);throw new l.ProcessingError({message:`Batch ${o+1}/${r.length} processing failed: ${p.message}`,operation:"batch-process"},{cause:i})}o<r.length-1&&this.config.delayBetweenBatches&&this.config.delayBetweenBatches>0&&await this.delay(this.config.delayBetweenBatches,t);}}return a}async delay(e,n){return new Promise((t,r)=>{if(n?.aborted){r(new l.AbortedError({message:"Operation aborted"}));return}let a=setTimeout(()=>{n?.removeEventListener("abort",o),t();},e),o=()=>{clearTimeout(a),r(new l.AbortedError({message:"Operation aborted"}));};n?.addEventListener("abort",o);})}};var F=class{constructor(e,n,t){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"maxEmbeddingsPerCall");f(this,"supportsParallelCalls",false);f(this,"engine");f(this,"modelConfig");if(this.provider=e,this.modelId=n,this.engine=t,this.modelConfig=P[n],!this.modelConfig)throw new l.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${n}`,modelId:n});this.maxEmbeddingsPerCall=this.modelConfig.maxEmbeddingsPerCall;}async doEmbed(e){let{values:n,abortSignal:t}=e;if(w.validateTexts(n),t?.aborted)throw new l.AbortedError({message:"Operation aborted"});this.engine.isReady()||await this.engine.initialize();let a=await new V({batchSize:this.maxEmbeddingsPerCall,delayBetweenBatches:0}).processBatches(n,async s=>{if(t?.aborted)throw new l.AbortedError({message:"Operation aborted"});return await this.engine.embed(s,t)},t),o=await this.engine.countTokens(n);return {embeddings:a,usage:{tokens:o},warnings:[]}}};var U=class{constructor(e,n,t,r={}){f(this,"specificationVersion","v3");f(this,"provider","local");f(this,"modelId");f(this,"languageModel");f(this,"options");f(this,"log",Log.create({service:"local-model-sdk.reranking-model"}));this.modelId=e,this.languageModel=new R("local",e,t),this.options={llm:this.languageModel,totalScore:r.totalScore??1,useEnhancedPrompt:true,promptLanguage:r.promptLanguage??"en"},this.log.debug("LocalRerankingModel created",{modelId:e,totalScore:this.options.totalScore,useEnhancedPrompt:this.options.useEnhancedPrompt,promptLanguage:this.options.promptLanguage});}async doRerank(e){let{query:n,documents:t,topN:r,abortSignal:a}=e,o=t.type==="text"?t.values.map((u,i)=>({content:u,id:`doc_${i+1}`})):t.values.map((u,i)=>{let g=u;return {content:typeof g=="string"?g:JSON.stringify(g),id:typeof g?.id=="string"?g.id:`doc_${i+1}`}}),s=r??o.length;if(o.length===0)return {ranking:[],warnings:[]};try{let u=this.buildRerankPrompt(n,o),g=(await this.languageModel.doGenerate({prompt:[{role:"user",content:[{type:"text",text:u}]}],maxOutputTokens:2048,temperature:0,topP:1,topK:1,abortSignal:a})).content.find(c=>c.type==="text"),p=g&&g.type==="text"?g.text:"",d=this.parseRerankResult(p,o,s);return {ranking:d.results.map(c=>({index:c.index,relevanceScore:c.score})),warnings:d.warnings.map(c=>({type:"other",message:c})),response:{timestamp:new Date,modelId:this.modelId}}}catch(u){return this.log.error("Reranking failed",{error:errorMeta(u)}),{ranking:o.map((g,p)=>({index:p,relevanceScore:o.length>1?this.options.totalScore*(1-.9*p/(o.length-1)):this.options.totalScore})),warnings:[{type:"other",message:`Reranking failed, using original order: ${errorMeta(u).message}`}],response:{timestamp:new Date,modelId:this.modelId}}}}buildRerankPrompt(e,n){let t=n.map((r,a)=>{let o=r.id||`doc_${a+1}`,s=r.content.slice(0,300);return `${a+1}. [ID: ${o}] ${s}`}).join(`
111
111
 
112
112
  `);if(this.options.useEnhancedPrompt)if(this.options.promptLanguage==="en"){this.options.totalScore===1?"1.0":String(this.options.totalScore);return ["You are a professional information retrieval reranking expert. Please rank the following documents according to the query.","",`User query: ${e}`,"","Documents to rank:",t,"","Please rank the documents according to the following requirements:","1. Carefully analyze the user's query intent and key information needs","2. Evaluate each document's relevance to the query","3. Consider the document's completeness, accuracy, and usefulness","4. Return ONLY the document numbers (1, 2, 3, ...) in order from MOST relevant to LEAST relevant, separated by commas","5. Most relevant documents MUST be at the front","6. Every document must appear exactly once in your output","","IMPORTANT:","- You MUST actually reorder the documents based on relevance to the query","- Do NOT output the original order unless it happens to be the correct relevance order","- Output format: just the numbers separated by commas, nothing else","","Example output format: 2,5,1,4,3 (where document 2 is most relevant to the query)"].join(`
113
113
  `)}else {this.options.totalScore===1?"1.0":String(this.options.totalScore);return ["\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u4FE1\u606F\u68C0\u7D22\u91CD\u6392\u5E8F\u4E13\u5BB6\u3002\u8BF7\u6839\u636E\u7528\u6237\u67E5\u8BE2\u5BF9\u6587\u6863\u8FDB\u884C\u76F8\u5173\u6027\u6392\u5E8F\u3002","",`\u7528\u6237\u67E5\u8BE2\uFF1A${e}`,"","\u5F85\u6392\u5E8F\u6587\u6863\uFF1A",t,"","\u8BF7\u6309\u7167\u4EE5\u4E0B\u8981\u6C42\u8FDB\u884C\u6392\u5E8F\uFF1A","1. \u4ED4\u7EC6\u5206\u6790\u7528\u6237\u67E5\u8BE2\u7684\u610F\u56FE\u548C\u5173\u952E\u4FE1\u606F\u9700\u6C42","2. \u8BC4\u4F30\u6BCF\u4E2A\u6587\u6863\u4E0E\u67E5\u8BE2\u7684\u76F8\u5173\u6027","3. \u8003\u8651\u6587\u6863\u7684\u5B8C\u6574\u6027\u3001\u51C6\u786E\u6027\u548C\u5B9E\u7528\u6027","4. \u53EA\u8F93\u51FA\u6587\u6863\u7F16\u53F7\uFF081, 2, 3, ...\uFF09\uFF0C\u6309\u201C\u6700\u76F8\u5173\u201D\u5230\u201C\u6700\u4E0D\u76F8\u5173\u201D\u987A\u5E8F\u6392\u5217\uFF0C\u7528\u9017\u53F7\u5206\u9694","5. \u6700\u76F8\u5173\u7684\u6587\u6863\u5FC5\u987B\u6392\u5728\u6700\u524D\u9762","6. \u6BCF\u4E2A\u6587\u6863\u5FC5\u987B\u51FA\u73B0\u4E14\u4EC5\u51FA\u73B0\u4E00\u6B21","","\u91CD\u8981\u63D0\u793A\uFF1A","- \u5FC5\u987B\u6839\u636E\u4E0E\u67E5\u8BE2\u7684\u76F8\u5173\u6027\u5B9E\u9645\u91CD\u65B0\u6392\u5E8F\u6587\u6863","- \u9664\u975E\u539F\u59CB\u987A\u5E8F\u6070\u597D\u5C31\u662F\u6B63\u786E\u7684\u76F8\u5173\u6027\u6392\u5E8F\uFF0C\u5426\u5219\u4E0D\u8981\u8F93\u51FA\u539F\u59CB\u987A\u5E8F","- \u8F93\u51FA\u683C\u5F0F\uFF1A\u4EC5\u5305\u542B\u7528\u9017\u53F7\u5206\u9694\u7684\u7F16\u53F7\uFF0C\u4E0D\u8981\u6709\u5176\u4ED6\u5185\u5BB9","","\u793A\u4F8B\u8F93\u51FA\u683C\u5F0F\uFF1A2,5,1,4,3\uFF08\u5176\u4E2D\u6587\u6863 2 \u4E0E\u67E5\u8BE2\u6700\u76F8\u5173\uFF09"].join(`
114
114
  `)}else return [`\u6839\u636E\u67E5\u8BE2 "${e}" \u5BF9\u4EE5\u4E0B\u7ED3\u679C\u76F8\u5173\u6027\u8FDB\u884C\u6392\u5E8F\uFF0C\u8FD4\u56DE\u6392\u5E8F\u540E\u7684\u7F16\u53F7\uFF08\u7528\u9017\u53F7\u5206\u9694\uFF09\uFF1A`,"",t,"","\u8F93\u51FA\u683C\u5F0F\uFF1A1,2,3,4,5\uFF08\u6700\u76F8\u5173\u7684\u6392\u5728\u6700\u524D\u9762\uFF09"].join(`
115
- `)}parseRerankResult(e,n,t){let r=[];try{let o=e.replaceAll(/<thinking>[\s\S]*?<\/thinking>/gi,"").replaceAll(/<think>[\s\S]*?<\/think>/gi,"").replaceAll(/<answer>[\s\S]*?<\/answer>/gi,"").trim().match(/\d+/g)?.map(c=>Number.parseInt(c,10)-1).filter(c=>c>=0&&c<n.length)||[],s=[],u=new Set;for(let c of o)u.has(c)||(u.add(c),s.push(c));let i=[],g=new Set;for(let c of s)c>=0&&c<n.length&&!g.has(c)&&(g.add(c),i.push({index:c,score:s.length>1?this.options.totalScore*(1-.9*i.length/(s.length-1)):this.options.totalScore}));let p=new Set(s);for(let c=0;c<n.length;c++)if(!p.has(c)){let E=this.options.totalScore*.1;i.push({index:c,score:E});}let d=t?i.slice(0,t):i;return this.log.debug("Parsed rerank results",{extractedNumbers:o,uniqueIndices:s,resultCount:d.length,topK:t}),{results:d,warnings:r}}catch(a){return this.log.error("Failed to parse rerank result",{error:errorMeta(a),text:e}),{results:n.map((s,u)=>({index:u,score:n.length>1?this.options.totalScore*(1-.9*u/(n.length-1)):this.options.totalScore})),warnings:[`Failed to parse rerank result: ${a.message}`]}}}};var $=class{constructor(e,n,t={}){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"languageModel");f(this,"options");f(this,"log",Log.create({service:"local-model-sdk",module:"llm-reranking-model"}));this.modelId=e,this.languageModel=n,this.provider=n.provider||"external",this.options={llm:n,totalScore:t.totalScore??1,useEnhancedPrompt:t.useEnhancedPrompt??false,promptLanguage:t.promptLanguage??"en",modelOptions:t.modelOptions??{temperature:.1,maxTokens:3e4}},this.log.debug("LLMRerankingModel created",{modelId:e,provider:this.provider,totalScore:this.options.totalScore,useEnhancedPrompt:this.options.useEnhancedPrompt,promptLanguage:this.options.promptLanguage});}async doRerank(e){let{query:n,documents:t,topN:r,abortSignal:a}=e,o=t.type==="text"?t.values.map((u,i)=>({content:u,id:`doc_${i+1}`})):t.values.map((u,i)=>{let g=u;return {content:typeof g=="string"?g:JSON.stringify(g),id:typeof g?.id=="string"?g.id:`doc_${i+1}`}}),s=r??o.length;if(o.length===0)return {ranking:[],warnings:[]};try{let u=this.buildRerankPrompt(n,o),i="",g=null;for(let d=0;d<2;d++)try{if(i=await(await streamText({model:this.languageModel,prompt:u,maxOutputTokens:this.options.modelOptions.maxTokens,temperature:this.options.modelOptions.temperature,abortSignal:a})).text,this.log.debug("LLM raw output",{textContent:i,textLength:i?.length,attempt:d}),i&&i.trim().length>0)break;g=new Error("LLM returned empty response");}catch(c){g=c,this.log.warn(`LLM attempt ${d+1} failed: ${g.message}`);}if(!i||i.trim().length===0)throw this.log.warn("LLM returned empty response, using fallback"),g||new Error("LLM returned empty response");let p=this.parseRerankResult(i,o,s);return {ranking:p.results.map(d=>({index:d.index,relevanceScore:d.score})),warnings:p.warnings.map(d=>({type:"other",message:d})),response:{timestamp:new Date,modelId:this.modelId}}}catch(u){return this.log.error("Reranking failed",{error:errorMeta(u)}),{ranking:o.map((g,p)=>({index:p,relevanceScore:o.length>1?this.options.totalScore*(1-.9*p/(o.length-1)):this.options.totalScore})),warnings:[{type:"other",message:`Reranking failed, using original order: ${u.message}`}],response:{timestamp:new Date,modelId:this.modelId}}}}buildRerankPrompt(e,n){let t=n.map((r,a)=>{let o=r.id||`doc_${a+1}`,s=r.content.slice(0,300);return `${a+1}. [ID: ${o}] ${s}`}).join(`
115
+ `)}parseRerankResult(e,n,t){let r=[];try{let o=e.replaceAll(/<thinking>[\s\S]*?<\/thinking>/gi,"").replaceAll(/<think>[\s\S]*?<\/think>/gi,"").replaceAll(/<answer>[\s\S]*?<\/answer>/gi,"").trim().match(/\d+/g)?.map(c=>Number.parseInt(c,10)-1).filter(c=>c>=0&&c<n.length)||[],s=[],u=new Set;for(let c of o)u.has(c)||(u.add(c),s.push(c));let i=[],g=new Set;for(let c of s)c>=0&&c<n.length&&!g.has(c)&&(g.add(c),i.push({index:c,score:s.length>1?this.options.totalScore*(1-.9*i.length/(s.length-1)):this.options.totalScore}));let p=new Set(s);for(let c=0;c<n.length;c++)if(!p.has(c)){let E=this.options.totalScore*.1;i.push({index:c,score:E});}let d=t?i.slice(0,t):i;return this.log.debug("Parsed rerank results",{extractedNumbers:o,uniqueIndices:s,resultCount:d.length,topK:t}),{results:d,warnings:r}}catch(a){return this.log.error("Failed to parse rerank result",{error:errorMeta(a),text:e}),{results:n.map((s,u)=>({index:u,score:n.length>1?this.options.totalScore*(1-.9*u/(n.length-1)):this.options.totalScore})),warnings:[`Failed to parse rerank result: ${errorMeta(a).message}`]}}}};var $=class{constructor(e,n,t={}){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"languageModel");f(this,"options");f(this,"log",Log.create({service:"local-model-sdk.llm-reranking-model"}));this.modelId=e,this.languageModel=n,this.provider=n.provider||"external",this.options={llm:n,totalScore:t.totalScore??1,useEnhancedPrompt:t.useEnhancedPrompt??false,promptLanguage:t.promptLanguage??"en",modelOptions:t.modelOptions??{temperature:.1,maxTokens:3e4}},this.log.debug("LLMRerankingModel created",{modelId:e,provider:this.provider,totalScore:this.options.totalScore,useEnhancedPrompt:this.options.useEnhancedPrompt,promptLanguage:this.options.promptLanguage});}async doRerank(e){let{query:n,documents:t,topN:r,abortSignal:a}=e,o=t.type==="text"?t.values.map((u,i)=>({content:u,id:`doc_${i+1}`})):t.values.map((u,i)=>{let g=u;return {content:typeof g=="string"?g:JSON.stringify(g),id:typeof g?.id=="string"?g.id:`doc_${i+1}`}}),s=r??o.length;if(o.length===0)return {ranking:[],warnings:[]};try{let u=this.buildRerankPrompt(n,o),i="",g=null;for(let d=0;d<2;d++)try{if(i=await(await streamText({model:this.languageModel,prompt:u,maxOutputTokens:this.options.modelOptions.maxTokens,temperature:this.options.modelOptions.temperature,abortSignal:a})).text,this.log.debug("LLM raw output",{textContent:i,textLength:i?.length,attempt:d}),i&&i.trim().length>0)break;g=new Error("LLM returned empty response");}catch(c){g=c,this.log.warn(`LLM attempt ${d+1} failed: ${g.message}`);}if(!i||i.trim().length===0)throw this.log.warn("LLM returned empty response, using fallback"),g||new Error("LLM returned empty response");let p=this.parseRerankResult(i,o,s);return {ranking:p.results.map(d=>({index:d.index,relevanceScore:d.score})),warnings:p.warnings.map(d=>({type:"other",message:d})),response:{timestamp:new Date,modelId:this.modelId}}}catch(u){return this.log.error("Reranking failed",{error:errorMeta(u)}),{ranking:o.map((g,p)=>({index:p,relevanceScore:o.length>1?this.options.totalScore*(1-.9*p/(o.length-1)):this.options.totalScore})),warnings:[{type:"other",message:`Reranking failed, using original order: ${errorMeta(u).message}`}],response:{timestamp:new Date,modelId:this.modelId}}}}buildRerankPrompt(e,n){let t=n.map((r,a)=>{let o=r.id||`doc_${a+1}`,s=r.content.slice(0,300);return `${a+1}. [ID: ${o}] ${s}`}).join(`
116
116
 
117
117
  `);if(this.options.useEnhancedPrompt)if(this.options.promptLanguage==="en"){this.options.totalScore===1?"1.0":String(this.options.totalScore);return ["You are a professional information retrieval reranking expert. Please rank the following documents according to the query.","",`User query: ${e}`,"","Documents to rank:",t,"","Please rank the documents according to the following requirements:","1. Carefully analyze the user's query intent and key information needs","2. Evaluate each document's relevance to the query","3. Consider the document's completeness, accuracy, and usefulness","4. Return ONLY the document numbers (1, 2, 3, ...) in order from MOST relevant to LEAST relevant, separated by commas","5. Most relevant documents MUST be at the front","6. Every document must appear exactly once in your output","","IMPORTANT:","- You MUST actually reorder the documents based on relevance to the query","- Do NOT output the original order unless it happens to be the correct relevance order","- Output format: just the numbers separated by commas, nothing else","","Example output format: 2,5,1,4,3 (where document 2 is most relevant to the query)"].join(`
118
118
  `)}else {this.options.totalScore===1?"1.0":String(this.options.totalScore);return ["\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u4FE1\u606F\u68C0\u7D22\u91CD\u6392\u5E8F\u4E13\u5BB6\u3002\u8BF7\u6839\u636E\u7528\u6237\u67E5\u8BE2\u5BF9\u6587\u6863\u8FDB\u884C\u76F8\u5173\u6027\u6392\u5E8F\u3002","",`\u7528\u6237\u67E5\u8BE2\uFF1A${e}`,"","\u5F85\u6392\u5E8F\u6587\u6863\uFF1A",t,"","\u8BF7\u6309\u7167\u4EE5\u4E0B\u8981\u6C42\u8FDB\u884C\u6392\u5E8F\uFF1A","1. \u4ED4\u7EC6\u5206\u6790\u7528\u6237\u67E5\u8BE2\u7684\u610F\u56FE\u548C\u5173\u952E\u4FE1\u606F\u9700\u6C42","2. \u8BC4\u4F30\u6BCF\u4E2A\u6587\u6863\u4E0E\u67E5\u8BE2\u7684\u76F8\u5173\u6027","3. \u8003\u8651\u6587\u6863\u7684\u5B8C\u6574\u6027\u3001\u51C6\u786E\u6027\u548C\u5B9E\u7528\u6027","4. \u53EA\u8F93\u51FA\u6587\u6863\u7F16\u53F7\uFF081, 2, 3, ...\uFF09\uFF0C\u6309\u201C\u6700\u76F8\u5173\u201D\u5230\u201C\u6700\u4E0D\u76F8\u5173\u201D\u987A\u5E8F\u6392\u5217\uFF0C\u7528\u9017\u53F7\u5206\u9694","5. \u6700\u76F8\u5173\u7684\u6587\u6863\u5FC5\u987B\u6392\u5728\u6700\u524D\u9762","6. \u6BCF\u4E2A\u6587\u6863\u5FC5\u987B\u51FA\u73B0\u4E14\u4EC5\u51FA\u73B0\u4E00\u6B21","","\u91CD\u8981\u63D0\u793A\uFF1A","- \u5FC5\u987B\u6839\u636E\u4E0E\u67E5\u8BE2\u7684\u76F8\u5173\u6027\u5B9E\u9645\u91CD\u65B0\u6392\u5E8F\u6587\u6863","- \u9664\u975E\u539F\u59CB\u987A\u5E8F\u6070\u597D\u5C31\u662F\u6B63\u786E\u7684\u76F8\u5173\u6027\u6392\u5E8F\uFF0C\u5426\u5219\u4E0D\u8981\u8F93\u51FA\u539F\u59CB\u987A\u5E8F","- \u8F93\u51FA\u683C\u5F0F\uFF1A\u4EC5\u5305\u542B\u7528\u9017\u53F7\u5206\u9694\u7684\u7F16\u53F7\uFF0C\u4E0D\u8981\u6709\u5176\u4ED6\u5185\u5BB9","","\u793A\u4F8B\u8F93\u51FA\u683C\u5F0F\uFF1A2,5,1,4,3\uFF08\u5176\u4E2D\u6587\u6863 2 \u4E0E\u67E5\u8BE2\u6700\u76F8\u5173\uFF09"].join(`
119
119
  `)}else return [`\u6839\u636E\u67E5\u8BE2 "${e}" \u5BF9\u4EE5\u4E0B\u7ED3\u679C\u76F8\u5173\u6027\u8FDB\u884C\u6392\u5E8F\uFF0C\u8FD4\u56DE\u6392\u5E8F\u540E\u7684\u7F16\u53F7\uFF08\u7528\u9017\u53F7\u5206\u9694\uFF09\uFF1A`,"",t,"","\u8F93\u51FA\u683C\u5F0F\uFF1A1,2,3,4,5\uFF08\u6700\u76F8\u5173\u7684\u6392\u5728\u6700\u524D\u9762\uFF09"].join(`
120
- `)}parseRerankResult(e,n,t){let r=[];try{let o=e.replaceAll(/<think>[\s\S]*?<\/think>/gi,"").replaceAll(/<thinking>[\s\S]*?<\/thinking>/gi,"").replaceAll(/<answer>[\s\S]*?<\/answer>/gi,"").trim().match(/\d+/g)?.map(c=>Number.parseInt(c,10)-1).filter(c=>c>=0&&c<n.length)||[],s=[],u=new Set;for(let c of o)u.has(c)||(u.add(c),s.push(c));let i=[],g=new Set;for(let c of s)c>=0&&c<n.length&&!g.has(c)&&(g.add(c),i.push({index:c,score:s.length>1?this.options.totalScore*(1-.9*i.length/(s.length-1)):this.options.totalScore}));let p=new Set(s);for(let c=0;c<n.length;c++)p.has(c)||i.push({index:c,score:this.options.totalScore*.1});let d=t?i.slice(0,t):i;return this.log.debug("Parsed rerank results",{extractedNumbers:o,uniqueIndices:s,resultCount:d.length,topK:t}),{results:d,warnings:r}}catch(a){return this.log.error("Failed to parse rerank result",{error:errorMeta(a),text:e}),{results:n.map((s,u)=>({index:u,score:n.length>1?this.options.totalScore*(1-.9*u/(n.length-1)):this.options.totalScore})),warnings:[`Failed to parse rerank result: ${a.message}`]}}}};var L=Log.create({service:"local-model-provider"}),Te={cacheDir:N__default.join(process.env.EASBOT_CACHE_PATH??`${N__default.join(H.homedir(),".cache","easbot")}`,"models"),verbose:false,autoUnloadTimeout:300*1e3,maxCachedModels:3,memoryWarningThreshold:1.5*1024*1024*1024,useEnhancedModel:true},j=class{constructor(e){f(this,"config");f(this,"modelCache");f(this,"engines",new Map);f(this,"modelInfo",new Map);this.config={...Te,...e},this.modelCache=new D({cacheDir:this.config.cacheDir});}languageModel(e,n){if(!w[e])throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${e}`,modelId:e});let t=this.getOrCreateEngine(e,"language");return n?.useEnhancedModel??this.config.useEnhancedModel?(this.config.verbose&&L.debug("\u521B\u5EFA\u589E\u5F3A\u8BED\u8A00\u6A21\u578B",{modelId:e}),new q("local",e,t)):(this.config.verbose&&L.debug("\u521B\u5EFA\u57FA\u7840\u8BED\u8A00\u6A21\u578B",{modelId:e}),new R("local",e,t))}embeddingModel(e){if(!P[e])throw new l.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${e}`,modelId:e});let n=this.getOrCreateEngine(e,"embedding");return new F("local",e,n)}chat(e,n){return this.languageModel(e,n)}rerankingModel(e,n){if(this.config.verbose&&L.debug("\u521B\u5EFA\u91CD\u6392\u5E8F\u6A21\u578B",{modelId:e,hasExternalLlm:!!n?.llm}),n?.llm)return new $(e,n.llm,n);if(!w[e])throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${e}`,modelId:e});let t=this.getOrCreateEngine(e,"language");return new U(e,this.config,t,n)}getOrCreateEngine(e,n){let t=`${n}:${e}`;if(this.engines.has(t)){let a=this.modelInfo.get(t);return a&&(a.lastUsed=Date.now(),a.useCount++),this.config.verbose&&L.debug("\u590D\u7528\u5DF2\u52A0\u8F7D\u7684\u6A21\u578B",{engineKey:t}),this.engines.get(t)}this.engines.size>=this.config.maxCachedModels&&this.evictLeastRecentlyUsed(),this.config.verbose&&L.debug("\u521B\u5EFA\u65B0\u5F15\u64CE",{engineKey:t});let r=new z({modelId:e,modelType:n,cacheDir:this.config.cacheDir,verbose:this.config.verbose});return this.engines.set(t,r),this.modelInfo.set(t,{modelId:e,modelType:n,isLoaded:false,lastUsed:Date.now(),useCount:1}),r}evictLeastRecentlyUsed(){let e=null,n=Number.POSITIVE_INFINITY;for(let[t,r]of this.modelInfo.entries())r.lastUsed<n&&(n=r.lastUsed,e=t);if(e){this.config.verbose&&L.debug("\u6DD8\u6C70\u6A21\u578B",{engineKey:e});let t=this.engines.get(e);t&&t.dispose().catch(r=>{L.error("\u5378\u8F7D\u6A21\u578B\u5931\u8D25",{error:r});}),this.engines.delete(e),this.modelInfo.delete(e);}}getLoadedModels(){return Array.from(this.modelInfo.values())}async dispose(){this.config.verbose&&L.debug("\u5378\u8F7D\u6240\u6709\u6A21\u578B");let e=Array.from(this.engines.values()).map(n=>n.dispose());await Promise.all(e),this.engines.clear(),this.modelInfo.clear(),this.config.verbose&&L.debug("\u6240\u6709\u6A21\u578B\u5DF2\u5378\u8F7D");}};function we(m){let e=new j(m);return Object.assign((t,r)=>e.languageModel(t,r),{languageModel:(t,r)=>e.languageModel(t,r),chat:(t,r)=>e.chat(t,r),embeddingModel:t=>e.embeddingModel(t),rerankingModel:(t,r)=>e.rerankingModel(t,r)})}var Le="0.1.0",ke="@easbot/local-model-sdk",ve="Complete local model SDK for EASBot - Transformers.js + ONNX implementation";export{W as ErrorCode,x as ErrorHandler,$ as LLMRerankingModel,F as LocalEmbeddingModel,q as LocalEnhancedLanguageModel,R as LocalLanguageModel,l as LocalModelErrors,j as LocalModelProvider,U as LocalRerankingModel,ve as SDK_DESCRIPTION,ke as SDK_NAME,P as SUPPORTED_EMBEDDING_MODELS,w as SUPPORTED_LANGUAGE_MODELS,Le as VERSION,we as createLocal};
120
+ `)}parseRerankResult(e,n,t){let r=[];try{let o=e.replaceAll(/<think>[\s\S]*?<\/think>/gi,"").replaceAll(/<thinking>[\s\S]*?<\/thinking>/gi,"").replaceAll(/<answer>[\s\S]*?<\/answer>/gi,"").trim().match(/\d+/g)?.map(c=>Number.parseInt(c,10)-1).filter(c=>c>=0&&c<n.length)||[],s=[],u=new Set;for(let c of o)u.has(c)||(u.add(c),s.push(c));let i=[],g=new Set;for(let c of s)c>=0&&c<n.length&&!g.has(c)&&(g.add(c),i.push({index:c,score:s.length>1?this.options.totalScore*(1-.9*i.length/(s.length-1)):this.options.totalScore}));let p=new Set(s);for(let c=0;c<n.length;c++)p.has(c)||i.push({index:c,score:this.options.totalScore*.1});let d=t?i.slice(0,t):i;return this.log.debug("Parsed rerank results",{extractedNumbers:o,uniqueIndices:s,resultCount:d.length,topK:t}),{results:d,warnings:r}}catch(a){return this.log.error("Failed to parse rerank result",{error:errorMeta(a),text:e}),{results:n.map((s,u)=>({index:u,score:n.length>1?this.options.totalScore*(1-.9*u/(n.length-1)):this.options.totalScore})),warnings:[`Failed to parse rerank result: ${errorMeta(a).message}`]}}}};var k=Log.create({service:"local-model-sdk.provider"}),ke={cacheDir:N__default.join(process.env.EASBOT_CACHE_PATH??`${N__default.join(Y.homedir(),".cache","easbot")}`,"models"),verbose:false,autoUnloadTimeout:300*1e3,maxCachedModels:3,memoryWarningThreshold:1.5*1024*1024*1024,useEnhancedModel:true},W=class{constructor(e){f(this,"config");f(this,"modelCache");f(this,"engines",new Map);f(this,"modelInfo",new Map);this.config={...ke,...e},this.modelCache=new D({cacheDir:this.config.cacheDir});}languageModel(e,n){if(!T[e])throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${e}`,modelId:e});let t=this.getOrCreateEngine(e,"language");return n?.useEnhancedModel??this.config.useEnhancedModel?(this.config.verbose&&k.debug("Creating enhanced language model",{modelId:e}),new q("local",e,t)):(this.config.verbose&&k.debug("Creating base language model",{modelId:e}),new R("local",e,t))}embeddingModel(e){if(!P[e])throw new l.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${e}`,modelId:e});let n=this.getOrCreateEngine(e,"embedding");return new F("local",e,n)}chat(e,n){return this.languageModel(e,n)}rerankingModel(e,n){if(this.config.verbose&&k.debug("Creating reranking model",{modelId:e,hasExternalLlm:!!n?.llm}),n?.llm)return new $(e,n.llm,n);if(!T[e])throw new l.ModelNotFoundError({message:`Unsupported Language Model ID: ${e}`,modelId:e});let t=this.getOrCreateEngine(e,"language");return new U(e,this.config,t,n)}getOrCreateEngine(e,n){let t=`${n}:${e}`;if(this.engines.has(t)){let a=this.modelInfo.get(t);return a&&(a.lastUsed=Date.now(),a.useCount++),this.config.verbose&&k.debug("Reusing loaded model",{engineKey:t}),this.engines.get(t)}this.engines.size>=this.config.maxCachedModels&&this.evictLeastRecentlyUsed(),this.config.verbose&&k.debug("Creating new engine",{engineKey:t});let r=new B({modelId:e,modelType:n,cacheDir:this.config.cacheDir,verbose:this.config.verbose});return this.engines.set(t,r),this.modelInfo.set(t,{modelId:e,modelType:n,isLoaded:false,lastUsed:Date.now(),useCount:1}),r}evictLeastRecentlyUsed(){let e=null,n=Number.POSITIVE_INFINITY;for(let[t,r]of this.modelInfo.entries())r.lastUsed<n&&(n=r.lastUsed,e=t);if(e){this.config.verbose&&k.debug("Evicting model",{engineKey:e});let t=this.engines.get(e);t&&t.dispose().catch(r=>{k.error("Failed to unload model",{error:errorMeta(r)});}),this.engines.delete(e),this.modelInfo.delete(e);}}getLoadedModels(){return Array.from(this.modelInfo.values())}async dispose(){this.config.verbose&&k.debug("Unloading all models");let e=Array.from(this.engines.values()).map(n=>n.dispose());await Promise.all(e),this.engines.clear(),this.modelInfo.clear(),this.config.verbose&&k.debug("All models unloaded");}};function ve(m){let e=new W(m);return Object.assign((t,r)=>e.languageModel(t,r),{languageModel:(t,r)=>e.languageModel(t,r),chat:(t,r)=>e.chat(t,r),embeddingModel:t=>e.embeddingModel(t),rerankingModel:(t,r)=>e.rerankingModel(t,r)})}var Ie="0.1.0",Pe="@easbot/local-model-sdk",Ce="Complete local model SDK for EASBot - Transformers.js + ONNX implementation";export{J as ErrorCode,x as ErrorHandler,$ as LLMRerankingModel,F as LocalEmbeddingModel,q as LocalEnhancedLanguageModel,R as LocalLanguageModel,l as LocalModelErrors,W as LocalModelProvider,U as LocalRerankingModel,Ce as SDK_DESCRIPTION,Pe as SDK_NAME,P as SUPPORTED_EMBEDDING_MODELS,T as SUPPORTED_LANGUAGE_MODELS,Ie as VERSION,ve as createLocal};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/local-model-sdk",
3
- "version": "0.3.29",
3
+ "version": "0.3.32",
4
4
  "description": "Complete local model SDK for EASBot - Transformers.js + ONNX implementation supporting both Language Model (text generation) and Embedding (text embedding) with full AI SDK v3 compatibility",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -54,8 +54,8 @@
54
54
  "ai": "^6.0.253",
55
55
  "onnxruntime-node": "^1.25.1",
56
56
  "zod": "^4.4.3",
57
- "@easbot/types": "0.3.29",
58
- "@easbot/utils": "0.3.29"
57
+ "@easbot/types": "0.3.32",
58
+ "@easbot/utils": "0.3.32"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@ai-sdk/openai-compatible": "2.0.70",