@easbot/local-model-sdk 0.3.28 → 0.3.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/index.cjs +26 -26
- package/dist/index.d.cts +1145 -25
- package/dist/index.d.ts +1145 -25
- package/dist/index.mjs +26 -26
- package/package.json +6 -5
package/README.en.md
CHANGED
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
'use strict';var G=require('os'),D=require('path'),b=require('fs'),utils=require('@easbot/utils'),ai=require('ai');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var G__namespace=/*#__PURE__*/_interopNamespace(G);var D__namespace=/*#__PURE__*/_interopNamespace(D);var b__namespace=/*#__PURE__*/_interopNamespace(b);var ee=Object.defineProperty;var te=(p,e,t)=>e in p?ee(p,e,{enumerable:true,configurable:true,writable:true,value:t}):p[e]=t;var g=(p,e,t)=>te(p,typeof e!="symbol"?e+"":e,t);var M=(f=>(f.MODEL_NOT_FOUND="MODEL_NOT_FOUND",f.MODEL_LOAD_ERROR="MODEL_LOAD_ERROR",f.MODEL_NOT_INITIALIZED="MODEL_NOT_INITIALIZED",f.GENERATION_ERROR="GENERATION_ERROR",f.EMBEDDING_ERROR="EMBEDDING_ERROR",f.INVALID_INPUT="INVALID_INPUT",f.UNSUPPORTED_FEATURE="UNSUPPORTED_FEATURE",f.CACHE_ERROR="CACHE_ERROR",f.PROCESSING_ERROR="PROCESSING_ERROR",f.ABORTED="ABORTED",f.OUT_OF_MEMORY="OUT_OF_MEMORY",f.UNKNOWN_ERROR="UNKNOWN_ERROR",f))(M||{});var L={"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:[]}}},k={"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 u=class p extends Error{constructor(t,n,r){super(t);g(this,"code",n);g(this,"cause",r);this.name="LocalModelError",Error.captureStackTrace&&Error.captureStackTrace(this,p);}},T=class{static modelLoadError(e){return new u(`\u6A21\u578B\u52A0\u8F7D\u5931\u8D25: ${e.message}`,"MODEL_LOAD_ERROR",e)}static generationError(e){return new u(`\u751F\u6210\u5931\u8D25: ${e.message}`,"GENERATION_ERROR",e)}static embeddingError(e){return new u(`\u5D4C\u5165\u5931\u8D25: ${e.message}`,"EMBEDDING_ERROR",e)}static validationError(e){return new u(e,"INVALID_INPUT")}static abortError(){return new u("\u64CD\u4F5C\u5DF2\u4E2D\u6B62","ABORTED")}static unsupportedFeature(e){return new u(`\u4E0D\u652F\u6301\u7684\u529F\u80FD: ${e}`,"UNSUPPORTED_FEATURE")}};var ne=D__namespace.join(G__namespace.homedir(),".cache","easbot","models"),I=class{constructor(e){g(this,"cacheDir");this.cacheDir=e.cacheDir||ne;}getCachePath(e){return D__namespace.join(this.cacheDir,e)}isCached(e){try{let t=this.getCachePath(e);return b__namespace.existsSync(t)&&b__namespace.statSync(t).isDirectory()}catch{return false}}async clear(e){try{if(e){let t=this.getCachePath(e);b__namespace.existsSync(t)&&await this.removeDirectory(t);}else b__namespace.existsSync(this.cacheDir)&&await this.removeDirectory(this.cacheDir);}catch(t){throw new u(`\u6E05\u7406\u7F13\u5B58\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,"CACHE_ERROR",t instanceof Error?t:void 0)}}async getCacheSize(e){try{let t=e?this.getCachePath(e):this.cacheDir;return b__namespace.existsSync(t)?await this.getDirectorySize(t):0}catch(t){throw new u(`\u83B7\u53D6\u7F13\u5B58\u5927\u5C0F\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,"CACHE_ERROR",t instanceof Error?t:void 0)}}async getDirectorySize(e){let t=0,n=b__namespace.readdirSync(e);for(let r of n){let a=D__namespace.join(e,r),o=b__namespace.statSync(a);o.isDirectory()?t+=await this.getDirectorySize(a):t+=o.size;}return t}async removeDirectory(e){if(!b__namespace.existsSync(e))return;let t=b__namespace.readdirSync(e);for(let n of t){let r=D__namespace.join(e,n);b__namespace.statSync(r).isDirectory()?await this.removeDirectory(r):b__namespace.unlinkSync(r);}b__namespace.rmdirSync(e);}ensureCacheDir(){try{b__namespace.existsSync(this.cacheDir)||b__namespace.mkdirSync(this.cacheDir,{recursive:!0});}catch(e){throw new u(`\u521B\u5EFA\u7F13\u5B58\u76EE\u5F55\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`,"CACHE_ERROR",e instanceof Error?e:void 0)}}};var h=utils.Log.create({service:"transformers-engine"}),P=null;async function oe(){if(!P){P=(await import('@huggingface/transformers')).env;let e=D__namespace.join(G__namespace.homedir(),".cache","easbot","models");process.env.HF_HOME||(process.env.HF_HOME=e),P.allowLocalModels=true,P.allowRemoteModels=true,P.useBrowserCache=false,P.useFSCache=true;}return P}var V=null;async function z(){return V||(V=(await import('@huggingface/transformers')).pipeline),V}var F=class{constructor(e){g(this,"pipeline",null);g(this,"tokenizer",null);g(this,"isInitialized",false);g(this,"config");g(this,"modelCache");this.config=e,this.modelCache=new I({cacheDir:e.cacheDir});}async configureEnvironment(){let e=await oe();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&&h.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&&h.debug("\u6A21\u578B\u5DF2\u521D\u59CB\u5316\uFF0C\u8DF3\u8FC7\u91CD\u590D\u52A0\u8F7D");return}await this.configureEnvironment();try{this.config.verbose&&h.debug("\u5F00\u59CB\u521D\u59CB\u5316\u6A21\u578B");let e,t,n;if(this.config.modelType==="language"){let o=L[this.config.modelId];if(!o)throw new u(`\u4E0D\u652F\u6301\u7684 Language Model ID: ${this.config.modelId}`,"MODEL_NOT_FOUND");e=o.huggingFaceId,t=o.dtype,n=o.device;}else {let o=k[this.config.modelId];if(!o)throw new u(`\u4E0D\u652F\u6301\u7684 Embedding Model ID: ${this.config.modelId}`,"MODEL_NOT_FOUND");e=o.huggingFaceId,t=o.dtype;}this.config.verbose&&(h.debug("\u52A0\u8F7D\u6A21\u578B",{huggingFaceId:e,dtype:t||"auto"}),this.modelCache.isCached(e)?h.debug("\u4F7F\u7528\u7F13\u5B58\u7684\u6A21\u578B"):h.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(t&&(r.dtype=t),n&&(r.device=n),!this.modelCache.isCached(e))throw this.config.verbose&&h.warn("\u672C\u5730\u7F13\u5B58\u4E0D\u5B58\u5728",{huggingFaceId:e,cacheDir:this.config.cacheDir}),new u(`\u6A21\u578B ${e} \u672A\u627E\u5230\u672C\u5730\u7F13\u5B58\u3002\u8BF7\u5148\u4E0B\u8F7D\u6A21\u578B\u5230: ${this.config.cacheDir}`,"MODEL_NOT_FOUND");if(this.config.modelType==="language"){let o=this.config.pipelineType||"text-generation";this.config.verbose&&h.debug("\u52A0\u8F7D\u8BED\u8A00\u6A21\u578B pipeline",{pipelineType:o,huggingFaceId:e});let l=await z();this.pipeline=await l(o,e,r);}else {let o=await z();this.pipeline=await o("feature-extraction",e,r);}this.tokenizer=this.pipeline.tokenizer,this.isInitialized=!0,this.config.verbose&&h.debug("\u6A21\u578B\u521D\u59CB\u5316\u6210\u529F",{modelId:this.config.modelId});}catch(e){throw this.config.verbose&&h.error("\u6A21\u578B\u521D\u59CB\u5316\u5931\u8D25",{error:e}),T.modelLoadError(e instanceof Error?e:new Error(String(e)))}}extractAssistantResponse(e,t){let n=`assistant
|
|
2
|
-
`,r=e.lastIndexOf(
|
|
1
|
+
'use strict';var h=require('zod'),utils=require('@easbot/utils'),W=require('os'),A=require('path'),y=require('fs'),ai=require('ai');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var h__default=/*#__PURE__*/_interopDefault(h);var W__namespace=/*#__PURE__*/_interopNamespace(W);var A__namespace=/*#__PURE__*/_interopNamespace(A);var y__namespace=/*#__PURE__*/_interopNamespace(y);var ie=Object.defineProperty;var se=(m,e,n)=>e in m?ie(m,e,{enumerable:true,configurable:true,writable:true,value:n}):m[e]=n;var f=(m,e,n)=>se(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:[]}}},I={"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"}};exports.LocalModelErrors=void 0;(d=>(d.NamedError=utils.NamedError,d.ModelNotFoundError=d.NamedError.create("LocalModelNotFoundError",h__default.default.object({message:h__default.default.string(),modelId:h__default.default.string().optional(),huggingFaceId:h__default.default.string().optional()})),d.ModelLoadError=d.NamedError.create("LocalModelLoadError",h__default.default.object({message:h__default.default.string(),modelId:h__default.default.string().optional(),huggingFaceId:h__default.default.string().optional()})),d.ModelNotInitializedError=d.NamedError.create("LocalModelNotInitializedError",h__default.default.object({message:h__default.default.string(),modelId:h__default.default.string().optional()})),d.GenerationError=d.NamedError.create("LocalGenerationError",h__default.default.object({message:h__default.default.string(),modelId:h__default.default.string().optional()})),d.EmbeddingError=d.NamedError.create("LocalEmbeddingError",h__default.default.object({message:h__default.default.string(),modelId:h__default.default.string().optional()})),d.ProcessingError=d.NamedError.create("LocalProcessingError",h__default.default.object({message:h__default.default.string(),operation:h__default.default.string().optional()})),d.InvalidInputError=d.NamedError.create("LocalInvalidInputError",h__default.default.object({message:h__default.default.string(),field:h__default.default.string().optional(),value:h__default.default.unknown().optional()})),d.UnsupportedFeatureError=d.NamedError.create("LocalUnsupportedFeatureError",h__default.default.object({message:h__default.default.string(),feature:h__default.default.string().optional(),allowed:h__default.default.array(h__default.default.string()).optional()})),d.CacheError=d.NamedError.create("LocalCacheError",h__default.default.object({message:h__default.default.string(),cacheDir:h__default.default.string().optional(),operation:h__default.default.string().optional()})),d.AbortedError=d.NamedError.create("LocalAbortedError",h__default.default.object({message:h__default.default.string()})),d.OutOfMemoryError=d.NamedError.create("LocalOutOfMemoryError",h__default.default.object({message:h__default.default.string(),modelId:h__default.default.string().optional()}))))(exports.LocalModelErrors||(exports.LocalModelErrors={}));var K=(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))(K||{}),E=class{static modelLoadError(e){return e instanceof utils.NamedError?e:new exports.LocalModelErrors.ModelLoadError({message:`Model load failed: ${e.message}`},{cause:e})}static generationError(e){return e instanceof utils.NamedError?e:new exports.LocalModelErrors.GenerationError({message:`Generation failed: ${e.message}`},{cause:e})}static embeddingError(e){return e instanceof utils.NamedError?e:new exports.LocalModelErrors.EmbeddingError({message:`Embedding failed: ${e.message}`},{cause:e})}static validationError(e){return new exports.LocalModelErrors.InvalidInputError({message:e})}static abortError(){return new exports.LocalModelErrors.AbortedError({message:"Operation aborted"})}static unsupportedFeature(e){return new exports.LocalModelErrors.UnsupportedFeatureError({message:`Unsupported feature: ${e}`,feature:e})}};var le=A__namespace.join(W__namespace.homedir(),".cache","easbot","models"),de=utils.Log.create({service:"model-cache"}),O=class{constructor(e){f(this,"cacheDir");this.cacheDir=e.cacheDir||le;}getCachePath(e){return A__namespace.join(this.cacheDir,e)}isCached(e){try{let n=this.getCachePath(e);return y__namespace.existsSync(n)&&y__namespace.statSync(n).isDirectory()}catch(n){return de.debug("Cache check failed; treating as not cached",{modelId:e,error:utils.errorMeta(n)}),false}}async clear(e){try{if(e){let n=this.getCachePath(e);y__namespace.existsSync(n)&&await this.removeDirectory(n);}else y__namespace.existsSync(this.cacheDir)&&await this.removeDirectory(this.cacheDir);}catch(n){throw new exports.LocalModelErrors.CacheError({message:`Failed to clear cache: ${utils.errorMeta(n).message}`,cacheDir:this.cacheDir,operation:"clear"},{cause:n})}}async getCacheSize(e){try{let n=e?this.getCachePath(e):this.cacheDir;return y__namespace.existsSync(n)?await this.getDirectorySize(n):0}catch(n){throw new exports.LocalModelErrors.CacheError({message:`Failed to get cache size: ${utils.errorMeta(n).message}`,cacheDir:this.cacheDir,operation:"get-size"},{cause:n})}}async getDirectorySize(e){let n=0,t=y__namespace.readdirSync(e);for(let r of t){let a=A__namespace.join(e,r),o=y__namespace.statSync(a);o.isDirectory()?n+=await this.getDirectorySize(a):n+=o.size;}return n}async removeDirectory(e){if(!y__namespace.existsSync(e))return;let n=y__namespace.readdirSync(e);for(let t of n){let r=A__namespace.join(e,t);y__namespace.statSync(r).isDirectory()?await this.removeDirectory(r):y__namespace.unlinkSync(r);}y__namespace.rmdirSync(e);}ensureCacheDir(){try{y__namespace.existsSync(this.cacheDir)||y__namespace.mkdirSync(this.cacheDir,{recursive:!0});}catch(e){throw new exports.LocalModelErrors.CacheError({message:`Failed to create cache directory: ${utils.errorMeta(e).message}`,cacheDir:this.cacheDir,operation:"create-dir"},{cause:e})}}};var b=utils.Log.create({service:"transformers-engine"}),P=null;async function ce(){if(!P){P=(await import('@huggingface/transformers')).env;let e=A__namespace.join(W__namespace.homedir(),".cache","easbot","models");process.env.HF_HOME||(process.env.HF_HOME=e),P.allowLocalModels=true,P.allowRemoteModels=true,P.useBrowserCache=false,P.useFSCache=true;}return P}var j=null;async function H(){return j||(j=(await import('@huggingface/transformers')).pipeline),j}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 O({cacheDir:e.cacheDir});}async configureEnvironment(){let e=await ce();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=T[this.config.modelId];if(!o)throw new exports.LocalModelErrors.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=I[this.config.modelId];if(!o)throw new exports.LocalModelErrors.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 exports.LocalModelErrors.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 H();this.pipeline=await s(o,e,r);}else {let o=await H();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:utils.errorMeta(e)}),E.modelLoadError(e instanceof Error?e:new Error(String(e)))}}extractAssistantResponse(e,n){let t=`assistant
|
|
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(t)?e.slice(t.length):e).trim()}async generate(e,t){let r=L[this.config.modelId]?.defaultSettings||{temperature:.7,topP:.9,topK:40,maxTokens:2048,repetitionPenalty:1.1,stopSequences:[]},a={temperature:t.temperature??r.temperature,topP:t.topP??r.topP,topK:t.topK??r.topK,maxTokens:t.maxTokens??r.maxTokens,repetitionPenalty:t.repetitionPenalty??r.repetitionPenalty,stopSequences:t.stopSequences??r.stopSequences,abortSignal:t.abortSignal};if(this.config.modelType!=="language")throw new u("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6587\u672C\u751F\u6210","UNSUPPORTED_FEATURE");if(t.abortSignal?.aborted)throw T.abortError();try{this.config.verbose&&h.debug("\u5F00\u59CB\u751F\u6210\u6587\u672C");let o=await this.countTokens([e]),l=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(t.abortSignal?.aborted)throw T.abortError();let s=l[0]?.generated_text||"",i=this.extractAssistantResponse(s,e),d=await this.countTokens([i]);return this.config.verbose&&h.debug("\u751F\u6210\u5B8C\u6210",{completionTokens:d}),{content:i,finishReason:{unified:"stop",raw:void 0},usage:{inputTokens:{total:o,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:d,text:d,reasoning:void 0}}}}catch(o){throw this.config.verbose&&h.error("\u751F\u6210\u5931\u8D25",{error:o}),o instanceof u&&o.code==="ABORTED"?o:T.generationError(o instanceof Error?o:new Error(String(o)))}}async generateStream(e,t,n){let a=L[this.config.modelId]?.defaultSettings||{temperature:.7,topP:.9,topK:40,maxTokens:2048,repetitionPenalty:1.1,stopSequences:[]};if(!this.isInitialized)throw new u("\u6A21\u578B\u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize() \u65B9\u6CD5","MODEL_NOT_INITIALIZED");if(this.config.modelType!=="language")throw new u("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6587\u672C\u751F\u6210","UNSUPPORTED_FEATURE");if(t.abortSignal?.aborted)throw T.abortError();try{this.config.verbose&&h.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:t.maxTokens??a.maxTokens,temperature:t.temperature??a.temperature,top_p:t.topP??a.topP,top_k:t.topK??a.topK,repetition_penalty:t.repetitionPenalty??a.repetitionPenalty,do_sample:(t.temperature??a.temperature)>0});if(t.abortSignal?.aborted)throw T.abortError();let l=o[0]?.generated_text||"",s=this.extractAssistantResponse(l,e),i=s.split(/(\s+)/);for(let S of i){if(t.abortSignal?.aborted)throw T.abortError();S.length>0&&n({type:"text-delta",delta:S});}n({type:"text-end"});let d=await this.countTokens([e]),m=await this.countTokens([s]);n({type:"finish",finishReason:{unified:"stop",raw:void 0},usage:{inputTokens:{total:d,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:m,text:m,reasoning:void 0}}}),this.config.verbose&&h.debug("\u6D41\u5F0F\u751F\u6210\u5B8C\u6210",{promptTokens:d,completionTokens:m});}catch(o){throw this.config.verbose&&h.error("\u6D41\u5F0F\u751F\u6210\u5931\u8D25",{error:o}),o instanceof u&&o.code==="ABORTED"?o:(n({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}}}),T.generationError(o instanceof Error?o:new Error(String(o))))}}async embed(e,t){if(!this.isInitialized)throw new u("\u6A21\u578B\u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize() \u65B9\u6CD5","MODEL_NOT_INITIALIZED");if(this.config.modelType!=="embedding")throw new u("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u5D4C\u5165\u63A8\u7406","UNSUPPORTED_FEATURE");if(t?.aborted)throw T.abortError();try{this.config.verbose&&h.debug("\u5F00\u59CB\u63A8\u7406",{textCount:e.length});let n=await this.pipeline(e,{pooling:"mean",normalize:!0});if(t?.aborted)throw T.abortError();let r=[];if(n.dims&&n.dims.length===2){let[a,o]=n.dims,l=Array.from(n.data);for(let s=0;s<a;s++){let i=s*o,d=i+o;r.push(l.slice(i,d));}}else r.push(Array.from(n.data));return this.config.verbose&&h.debug("\u63A8\u7406\u5B8C\u6210",{embeddingCount:r.length}),r}catch(n){throw this.config.verbose&&h.error("\u63A8\u7406\u5931\u8D25",{error:n}),n instanceof u&&n.code==="ABORTED"?n:T.embeddingError(n instanceof Error?n:new Error(String(n)))}}async countTokens(e){if(!this.isInitialized)throw new u("\u6A21\u578B\u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 initialize() \u65B9\u6CD5","MODEL_NOT_INITIALIZED");try{let t=0;for(let n of e){let r=await this.tokenizer(n);t+=r.input_ids.data.length;}return t}catch(t){return this.config.verbose&&h.error("\u8BA1\u7B97 token \u5931\u8D25",{error:t}),e.reduce((n,r)=>n+Math.ceil(r.length/4),0)}}async dispose(){this.config.verbose&&h.debug("\u5378\u8F7D\u6A21\u578B"),this.pipeline=null,this.tokenizer=null,this.isInitialized=false,this.config.verbose&&h.debug("\u6A21\u578B\u5DF2\u5378\u8F7D");}isReady(){return this.isInitialized}};var E=class{static validateTexts(e){if(!Array.isArray(e))throw new u("\u8F93\u5165\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4","INVALID_INPUT");if(e.length===0)throw new u("\u8F93\u5165\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A","INVALID_INPUT");for(let t=0;t<e.length;t++){let n=e[t];if(typeof n!="string")throw new u(`\u8F93\u5165\u6570\u7EC4\u7D22\u5F15 ${t} \u4E0D\u662F\u5B57\u7B26\u4E32\u7C7B\u578B`,"INVALID_INPUT");if(n.trim().length===0)throw new u(`\u8F93\u5165\u6570\u7EC4\u7D22\u5F15 ${t} \u662F\u7A7A\u5B57\u7B26\u4E32`,"INVALID_INPUT")}}static validateMessages(e){if(!Array.isArray(e))throw new u("\u6D88\u606F\u5FC5\u987B\u662F\u6570\u7EC4","INVALID_INPUT");if(e.length===0)throw new u("\u6D88\u606F\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A","INVALID_INPUT");for(let t=0;t<e.length;t++){let n=e[t];if(!n||typeof n!="object")throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u4E0D\u662F\u6709\u6548\u5BF9\u8C61`,"INVALID_INPUT");if(!n.role)throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7F3A\u5C11 role \u5B57\u6BB5`,"INVALID_INPUT");let r=["system","user","assistant","tool"];if(!r.includes(n.role))throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7684 role "${n.role}" \u4E0D\u652F\u6301\uFF0C\u53EA\u652F\u6301 ${r.join("\u3001")}`,"UNSUPPORTED_FEATURE");if(!n.content)throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7F3A\u5C11 content \u5B57\u6BB5`,"INVALID_INPUT");if(typeof n.content=="string"){if(n.content.trim().length===0)throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7684 content \u662F\u7A7A\u5B57\u7B26\u4E32`,"INVALID_INPUT")}else if(Array.isArray(n.content)){if(n.content.length===0)throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7684 content \u6570\u7EC4\u4E3A\u7A7A`,"INVALID_INPUT");for(let a=0;a<n.content.length;a++){let o=n.content[a];if(!o||typeof o!="object")throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7684 content part ${a} \u4E0D\u662F\u6709\u6548\u5BF9\u8C61`,"INVALID_INPUT");if(!o.type)throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7684 content part ${a} \u7F3A\u5C11 type \u5B57\u6BB5`,"INVALID_INPUT");let l=["text","file","reasoning","tool-call","tool-result","tool-approval-response"];if(!l.includes(o.type))throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7684 content part ${a} \u7C7B\u578B "${o.type}" \u4E0D\u652F\u6301\uFF0C\u53EA\u652F\u6301 ${l.join("\u3001")}`,"UNSUPPORTED_FEATURE")}}else throw new u(`\u6D88\u606F\u7D22\u5F15 ${t} \u7684 content \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u6570\u7EC4`,"INVALID_INPUT")}}static validateGenerateOptions(e){if(e.temperature!==void 0&&(typeof e.temperature!="number"||e.temperature<0||e.temperature>2))throw new u("temperature \u5FC5\u987B\u662F 0 \u5230 2 \u4E4B\u95F4\u7684\u6570\u5B57","INVALID_INPUT");if(e.topP!==void 0&&(typeof e.topP!="number"||e.topP<0||e.topP>1))throw new u("topP \u5FC5\u987B\u662F 0 \u5230 1 \u4E4B\u95F4\u7684\u6570\u5B57","INVALID_INPUT");if(e.topK!==void 0&&(typeof e.topK!="number"||e.topK<1||!Number.isInteger(e.topK)))throw new u("topK \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570","INVALID_INPUT");if(e.maxTokens!==void 0&&(typeof e.maxTokens!="number"||e.maxTokens<1||!Number.isInteger(e.maxTokens)))throw new u("maxTokens \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570","INVALID_INPUT");if(e.repetitionPenalty!==void 0&&(typeof e.repetitionPenalty!="number"||e.repetitionPenalty<0))throw new u("repetitionPenalty \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 0 \u7684\u6570\u5B57","INVALID_INPUT")}};var C=class{static createReadableStream(e,t){return new ReadableStream({async start(n){if(t?.aborted){n.error(new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED"));return}let r=false,a=()=>{r=true;try{n.error(new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED"));}catch{}};t?.addEventListener("abort",a);try{if(await(async l=>{let s=l.enqueue.bind(l);l.enqueue=i=>{if(!r)try{s(i);}catch{}},await e(l);})(n),!r)try{n.close();}catch{}}catch(o){if(!r)try{n.error(o instanceof u?o:new u(`\u751F\u6210\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`,"GENERATION_ERROR",o instanceof Error?o:void 0));}catch{}}finally{t?.removeEventListener("abort",a);}},cancel(){}})}static async*streamToAsyncIterator(e){let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;yield r;}}finally{t.releaseLock();}}};function H(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var O=class{constructor(e,t,n){g(this,"specificationVersion","v3");g(this,"provider");g(this,"modelId");g(this,"defaultObjectGenerationMode","json");g(this,"supportedUrls",{});g(this,"engine");g(this,"modelConfig");if(this.provider=e,this.modelId=t,this.engine=n,this.modelConfig=L[t],!this.modelConfig)throw new u(`\u4E0D\u652F\u6301\u7684\u6A21\u578B ID: ${t}`,"MODEL_NOT_FOUND")}async doGenerate(e){E.validateMessages(e.prompt);let t=this.convertToChatMLFormat(e.prompt),n={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};E.validateGenerateOptions(n),this.engine.isReady()||await this.engine.initialize();let r=await this.engine.generate(t,n);return {content:[{type:"text",text:r.content||""}],finishReason:r.finishReason,usage:r.usage,warnings:[],request:{body:t}}}async doStream(e){E.validateMessages(e.prompt);let t=this.convertToChatMLFormat(e.prompt),n={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};E.validateGenerateOptions(n),this.engine.isReady()||await this.engine.initialize();let r=[];return {stream:C.createReadableStream(async o=>{o.enqueue({type:"stream-start",warnings:r});let l=H();o.enqueue({type:"response-metadata",id:l,modelId:this.modelId,timestamp:new Date});let s=null,i=false;try{await this.engine.generateStream(t,n,d=>{if(d.type==="text-delta"){let m=d.delta||"";if(m.length===0)return;s||(s=H(),o.enqueue({type:"text-start",id:s})),o.enqueue({type:"text-delta",id:s,delta:m});}else d.type==="text-end"?s&&(o.enqueue({type:"text-end",id:s}),s=null):d.type==="finish"&&(s&&(o.enqueue({type:"text-end",id:s}),s=null),o.enqueue({type:"finish",finishReason:d.finishReason??{unified:"stop",raw:void 0},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}}}),i=!0);});}catch(d){o.enqueue({type:"error",error:d instanceof Error?d:new Error(String(d))}),s&&o.enqueue({type:"text-end",id:s}),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:t}}}convertToChatMLFormat(e){let t=[];for(let n of e){let r="";switch(typeof n.content=="string"?r=n.content:Array.isArray(n.content)&&(r=n.content.filter(a=>a.type==="text").map(a=>"text"in a?a.text:"").join(`
|
|
5
|
-
`)),
|
|
6
|
-
${r}`);break;case "user":
|
|
7
|
-
${r}`);break;case "assistant":
|
|
8
|
-
${r}`);break;default:
|
|
9
|
-
${r}`);break}}return
|
|
10
|
-
`),t.join(`
|
|
11
|
-
`)}};var N=class p{static buildEnhancedPrompt(e,t){let n=[];n.push(p.buildSystemPrompt(t));for(let r of e){let a=p.formatMessage(r);a&&n.push(a);}return n.push(`<|im_start|>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=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 exports.LocalModelErrors.UnsupportedFeatureError({message:"Current model does not support text generation",feature:"text-generation"});if(n.abortSignal?.aborted)throw E.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 E.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:utils.errorMeta(o)});let s=o instanceof Error?o:new Error(utils.errorMeta(o).message);throw exports.LocalModelErrors.AbortedError.isInstance(o)?o:E.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 exports.LocalModelErrors.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});if(this.config.modelType!=="language")throw new exports.LocalModelErrors.UnsupportedFeatureError({message:"Current model does not support text generation",feature:"text-generation"});if(n.abortSignal?.aborted)throw E.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 E.abortError();let s=o[0]?.generated_text||"",u=this.extractAssistantResponse(s,e),i=u.split(/(\s+)/);for(let M of i){if(n.abortSignal?.aborted)throw E.abortError();M.length>0&&t({type:"text-delta",delta:M});}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:utils.errorMeta(o)});let s=o instanceof Error?o:new Error(utils.errorMeta(o).message);throw exports.LocalModelErrors.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}}}),E.generationError(s))}}async embed(e,n){if(!this.isInitialized)throw new exports.LocalModelErrors.ModelNotInitializedError({message:"Model not initialized; please call initialize() first",modelId:this.config.modelId});if(this.config.modelType!=="embedding")throw new exports.LocalModelErrors.UnsupportedFeatureError({message:"Current model does not support embedding inference",feature:"embedding-inference"});if(n?.aborted)throw E.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 E.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:utils.errorMeta(t)});let r=t instanceof Error?t:new Error(utils.errorMeta(t).message);throw exports.LocalModelErrors.AbortedError.isInstance(t)?t:E.embeddingError(r)}}async countTokens(e){if(!this.isInitialized)throw new exports.LocalModelErrors.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:utils.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 x=class{static validateTexts(e){if(!Array.isArray(e))throw new exports.LocalModelErrors.InvalidInputError({message:"Input must be a string array"});if(e.length===0)throw new exports.LocalModelErrors.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 exports.LocalModelErrors.InvalidInputError({message:`Input array index ${n} is not a string`,field:"texts",value:t});if(t.trim().length===0)throw new exports.LocalModelErrors.InvalidInputError({message:`Input array index ${n} is an empty string`})}}static validateMessages(e){if(!Array.isArray(e))throw new exports.LocalModelErrors.InvalidInputError({message:"Messages must be an array"});if(e.length===0)throw new exports.LocalModelErrors.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 exports.LocalModelErrors.InvalidInputError({message:`Message index ${t} is not a valid object`});if(!r.role)throw new exports.LocalModelErrors.InvalidInputError({message:`Message index ${t} missing role field`});if(!n.includes(r.role))throw new exports.LocalModelErrors.UnsupportedFeatureError({message:`Message index ${t} role "${r.role}" is not supported; allowed: ${n.join(", ")}`,feature:"message.role",allowed:n});if(!r.content)throw new exports.LocalModelErrors.InvalidInputError({message:`Message index ${t} missing content field`});if(typeof r.content=="string"){if(r.content.trim().length===0)throw new exports.LocalModelErrors.InvalidInputError({message:`Message index ${t} content is an empty string`})}else if(Array.isArray(r.content)){if(r.content.length===0)throw new exports.LocalModelErrors.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 exports.LocalModelErrors.InvalidInputError({message:`Message index ${t} content part ${o} is not a valid object`});if(!s.type)throw new exports.LocalModelErrors.InvalidInputError({message:`Message index ${t} content part ${o} missing type field`});if(!a.includes(s.type))throw new exports.LocalModelErrors.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 exports.LocalModelErrors.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 exports.LocalModelErrors.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 exports.LocalModelErrors.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 exports.LocalModelErrors.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 exports.LocalModelErrors.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 exports.LocalModelErrors.InvalidInputError({message:"repetitionPenalty must be a number greater than or equal to 0",field:"repetitionPenalty"})}};var D=class{static createReadableStream(e,n){return new ReadableStream({async start(t){if(n?.aborted){t.error(new exports.LocalModelErrors.AbortedError({message:"Operation aborted"}));return}let r=false,a=()=>{r=true;try{t.error(new exports.LocalModelErrors.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 utils.NamedError?o:new exports.LocalModelErrors.GenerationError({message:`Generation failed: ${utils.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 X(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var C=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 exports.LocalModelErrors.ModelNotFoundError({message:`Unsupported Language Model ID: ${n}`,modelId:n})}async doGenerate(e){x.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};x.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){x.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};x.validateGenerateOptions(t),this.engine.isReady()||await this.engine.initialize();let r=[];return {stream:D.createReadableStream(async o=>{o.enqueue({type:"stream-start",warnings:r});let s=X();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=X(),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(`
|
|
5
|
+
`)),t.role){case "system":n.push(`system
|
|
6
|
+
${r}`);break;case "user":n.push(`user
|
|
7
|
+
${r}`);break;case "assistant":n.push(`assistant
|
|
8
|
+
${r}`);break;default:n.push(`${String(t.role)}
|
|
9
|
+
${r}`);break}}return n.push(`assistant
|
|
12
10
|
`),n.join(`
|
|
11
|
+
`)}};var N=class m{static buildEnhancedPrompt(e,n){let t=[];t.push(m.buildSystemPrompt(n));for(let r of e){let a=m.formatMessage(r);a&&t.push(a);}return t.push(`<|im_start|>assistant
|
|
12
|
+
`),t.join(`
|
|
13
13
|
`)}static buildSystemPrompt(e){return e&&e.length>0?`<|im_start|>system
|
|
14
14
|
Environment: ipython
|
|
15
15
|
|
|
16
16
|
You have access to the following functions:
|
|
17
17
|
|
|
18
|
-
${
|
|
18
|
+
${m.formatToolsDefinition(e)}
|
|
19
19
|
|
|
20
20
|
FUNCTION CALLING INSTRUCTIONS:
|
|
21
21
|
|
|
@@ -101,20 +101,20 @@ CRITICAL OUTPUT RULES:
|
|
|
101
101
|
2. If you use <think> tags, ALWAYS use them as a COMPLETE PAIR: <think>content</think>
|
|
102
102
|
3. Your response must be clean, natural text without any formatting markers
|
|
103
103
|
4. Do NOT include any part of the conversation format in your output
|
|
104
|
-
<|im_end|>`}static formatToolsDefinition(e){return e.map(
|
|
104
|
+
<|im_end|>`}static formatToolsDefinition(e){return e.map(n=>{let t=n.inputSchema;return JSON.stringify({name:n.name,description:n.description||"No description",parameters:t},null,2)}).join(`
|
|
105
105
|
|
|
106
|
-
`)}static formatMessage(e){let
|
|
106
|
+
`)}static formatMessage(e){let n="";if(typeof e.content=="string")n=e.content;else if(Array.isArray(e.content)){let t=[];for(let r of e.content)if(r.type==="text")t.push("text"in r?r.text:"");else if(r.type==="tool-call"){let a={name:r.toolName,parameters:r.args||{}};t.push(JSON.stringify(a));}else if(r.type==="tool-result"){let a=r.result;t.push(typeof a=="string"?a:JSON.stringify(a));}n=t.join(`
|
|
107
107
|
`);}switch(e.role){case "system":return null;case "user":return `<|im_start|>user
|
|
108
|
-
${
|
|
109
|
-
${
|
|
110
|
-
${t}<|im_end|>`;default:{let n=e.role;throw new u(`\u4E0D\u652F\u6301\u7684\u6D88\u606F\u89D2\u8272: ${n}`,"UNSUPPORTED_FEATURE")}}}};var x=class{static processThinkTags(e,t){let n={...e};for(;n.contentBuffer.length>0;)if(n.isInThinkTag){let r=n.contentBuffer.indexOf("</think>");if(r===-1){n.contentBuffer.length>0&&t.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:n.contentBuffer}),n.contentBuffer="";break}if(r>0){let a=n.contentBuffer.substring(0,r);a.length>0&&t.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:a});}t.enqueue({type:"reasoning-end",id:"reasoning-0"}),n.reasoningStarted=false,n.isInThinkTag=false,n.contentBuffer=n.contentBuffer.substring(r+8);}else {let r=n.contentBuffer.indexOf("<think>");if(r===-1)break;if(r>0){let a=n.contentBuffer.substring(0,r);n.textStarted||(n.textStarted=true,t.enqueue({type:"text-start",id:"txt-0"})),a.length>0&&t.enqueue({type:"text-delta",id:"txt-0",delta:a}),t.enqueue({type:"text-end",id:"txt-0"}),n.textStarted=false;}n.isInThinkTag=true,n.contentBuffer=n.contentBuffer.substring(r+7),n.reasoningStarted||(n.reasoningStarted=true,t.enqueue({type:"reasoning-start",id:"reasoning-0"}));}return n}static finishThinkParsing(e,t){let n={...e};return n.contentBuffer.length>0?n.isInThinkTag?(n.contentBuffer.length>0&&t.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:n.contentBuffer}),n.reasoningStarted&&(t.enqueue({type:"reasoning-end",id:"reasoning-0"}),n.reasoningStarted=false)):(n.textStarted||(t.enqueue({type:"text-start",id:"txt-0"}),n.textStarted=true),n.contentBuffer.length>0&&t.enqueue({type:"text-delta",id:"txt-0",delta:n.contentBuffer}),t.enqueue({type:"text-end",id:"txt-0"}),n.textStarted=false):(n.textStarted&&(t.enqueue({type:"text-end",id:"txt-0"}),n.textStarted=false),n.reasoningStarted&&!n.isInThinkTag&&(t.enqueue({type:"reasoning-end",id:"reasoning-0"}),n.reasoningStarted=false)),n}static removeThinkTags(e){return e.replace(/<think>[\s\S]*?<\/think>/g,"").trim()}};function ae(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var W=/\{\s*"name"\s*:\s*"([^"]+)"\s*,\s*"parameters"\s*:\s*(\{[\s\S]*?\})\s*\}/g;function J(p){let e=[];W.lastIndex=0;let t;for(;(t=W.exec(p))!==null;){let n=t[1]||"",r=t[2]||"";try{let a=JSON.parse(r);a&&typeof a=="object"&&!Array.isArray(a)&&e.push({name:n,parameters:JSON.stringify(a),index:t.index,length:t[0].length});}catch{}}return {toolCalls:e}}var R=class p{static extractToolCalls(e){let t=J(e),n=[],r=[],a=0;for(let o of t.toolCalls)o.index>a&&r.push(e.substring(a,o.index)),n.push({name:o.name,parameters:o.parameters}),a=o.index+o.length;return a<e.length&&r.push(e.substring(a)),{toolCalls:n,remainingText:r.join("").trim()}}static processToolCalls(e,t,n){let r={...e},a=J(r.contentBuffer);if(a.toolCalls.length===0)return r;let o=[],l=0;for(let i of a.toolCalls){let d=r.contentBuffer.substring(l,i.index);if(d.length>0){o.length=0,o.push(d);let f=d;f.trim()&&(r.textStarted||(t.enqueue({type:"text-start",id:"txt-0"}),r.textStarted=true),t.enqueue({type:"text-delta",id:"txt-0",delta:f}),true);}if(n&&n.length>0&&!n.some(c=>c.name===i.name)){o.push(r.contentBuffer.substring(i.index,i.index+i.length)),l=i.index+i.length;continue}r.textStarted&&(t.enqueue({type:"text-end",id:"txt-0"}),r.textStarted=false);let m=ae();t.enqueue({type:"tool-input-start",id:m,toolName:i.name}),t.enqueue({type:"tool-input-delta",id:m,delta:i.parameters}),t.enqueue({type:"tool-input-end",id:m}),t.enqueue({type:"tool-call",toolCallId:m,toolName:i.name,input:i.parameters}),r.completedToolCalls.push({id:m,name:i.name,parameters:i.parameters}),l=i.index+i.length;}return l<r.contentBuffer.length&&o.push(r.contentBuffer.substring(l)),r.contentBuffer=o.join(""),r}static finishToolParsing(e,t){let n={...e};return n.contentBuffer.trim().length>0?(n.textStarted||(t.enqueue({type:"text-start",id:"txt-0"}),n.textStarted=true),t.enqueue({type:"text-delta",id:"txt-0",delta:n.contentBuffer}),t.enqueue({type:"text-end",id:"txt-0"}),n.textStarted=false):n.textStarted&&(t.enqueue({type:"text-end",id:"txt-0"}),n.textStarted=false),n}static removeToolCalls(e){let{remainingText:t}=p.extractToolCalls(e);return t}};function Y(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var A=class{constructor(e,t,n){g(this,"specificationVersion","v3");g(this,"provider");g(this,"modelId");g(this,"defaultObjectGenerationMode","json");g(this,"supportedUrls",{});g(this,"engine");g(this,"modelConfig");if(this.provider=e,this.modelId=t,this.engine=n,this.modelConfig=L[t],!this.modelConfig)throw new u(`\u4E0D\u652F\u6301\u7684\u6A21\u578B ID: ${t}`,"MODEL_NOT_FOUND")}async doGenerate(e){E.validateMessages(e.prompt);let t=(e.tools??[]).filter(m=>"inputSchema"in m),n=N.buildEnhancedPrompt(e.prompt,t),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};E.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=await this.engine.generate(n,r),o=x.removeThinkTags(a.content||""),{toolCalls:l,remainingText:s}=R.extractToolCalls(o),i=[];s.trim().length>0&&i.push({type:"text",text:s});for(let m of l)i.push({type:"tool-call",toolCallId:Y(),toolName:m.name,input:m.parameters});let d=l.length>0?{unified:"tool-calls",raw:void 0}:a.finishReason;return {content:i,finishReason:d,usage:a.usage,warnings:[],request:{body:n}}}async doStream(e){E.validateMessages(e.prompt);let t=(e.tools??[]).filter(l=>"inputSchema"in l),n=N.buildEnhancedPrompt(e.prompt,t),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};E.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=[];return {stream:C.createReadableStream(async l=>{l.enqueue({type:"stream-start",warnings:a});let s=Y();l.enqueue({type:"response-metadata",id:s,modelId:this.modelId,timestamp:new Date});let i={isInThinkTag:false,reasoningStarted:false,textStarted:false,contentBuffer:""},d={contentBuffer:"",textStarted:false,completedToolCalls:[]},m=false;try{await this.engine.generateStream(n,r,f=>{if(f.type==="text-delta"){let c=f.delta||"";if(c.length===0)return;i.contentBuffer+=c;let S=x.processThinkTags(i,l);i.isInThinkTag=S.isInThinkTag,i.reasoningStarted=S.reasoningStarted,i.textStarted=S.textStarted,d.contentBuffer+=S.contentBuffer,i.contentBuffer="";let v=R.processToolCalls(d,l,t);d.contentBuffer=v.contentBuffer,d.textStarted=v.textStarted,d.completedToolCalls=v.completedToolCalls;}else if(f.type==="text-end"){let c=x.finishThinkParsing(i,l);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let S=R.finishToolParsing(d,l);d.textStarted=S.textStarted,m=!0;}else if(f.type==="finish"){if(!m){let v=x.finishThinkParsing(i,l);i.textStarted=v.textStarted,i.reasoningStarted=v.reasoningStarted;let Q=R.finishToolParsing(d,l);d.textStarted=Q.textStarted,m=!0;}let S=d.completedToolCalls.length>0?{unified:"tool-calls",raw:void 0}:f.finishReason??{unified:"stop",raw:void 0};l.enqueue({type:"finish",finishReason:S,usage:f.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(f){if(l.enqueue({type:"error",error:f instanceof Error?f:new Error(String(f))}),!m){let c=x.finishThinkParsing(i,l);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let S=R.finishToolParsing(d,l);d.textStarted=S.textStarted;}l.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:n}}}};var $=class{constructor(e){g(this,"config");this.config=e;}createBatches(e){let t=[],n=this.config.batchSize;for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}async processBatches(e,t,n){if(n?.aborted)throw new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED");let r=this.createBatches(e),a=[];for(let o=0;o<r.length;o++){if(n?.aborted)throw new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED");let l=r[o];if(l){try{let s=await t(l);a.push(...s);}catch(s){throw s instanceof u&&s.code==="ABORTED"?s:new u(`\u6279\u6B21 ${o+1}/${r.length} \u5904\u7406\u5931\u8D25: ${s instanceof Error?s.message:String(s)}`,"PROCESSING_ERROR",s instanceof Error?s:void 0)}o<r.length-1&&this.config.delayBetweenBatches&&this.config.delayBetweenBatches>0&&await this.delay(this.config.delayBetweenBatches,n);}}return a}async delay(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED"));return}let a=setTimeout(()=>{t?.removeEventListener("abort",o),n();},e),o=()=>{clearTimeout(a),r(new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED"));};t?.addEventListener("abort",o);})}};var _=class{constructor(e,t,n){g(this,"specificationVersion","v3");g(this,"provider");g(this,"modelId");g(this,"maxEmbeddingsPerCall");g(this,"supportsParallelCalls",false);g(this,"engine");g(this,"modelConfig");if(this.provider=e,this.modelId=t,this.engine=n,this.modelConfig=k[t],!this.modelConfig)throw new u(`\u4E0D\u652F\u6301\u7684\u6A21\u578B ID: ${t}`,"MODEL_NOT_FOUND");this.maxEmbeddingsPerCall=this.modelConfig.maxEmbeddingsPerCall;}async doEmbed(e){let{values:t,abortSignal:n}=e;if(E.validateTexts(t),n?.aborted)throw new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED");this.engine.isReady()||await this.engine.initialize();let a=await new $({batchSize:this.maxEmbeddingsPerCall,delayBetweenBatches:0}).processBatches(t,async l=>{if(n?.aborted)throw new u("\u64CD\u4F5C\u5DF2\u53D6\u6D88","ABORTED");return await this.engine.embed(l,n)},n),o=await this.engine.countTokens(t);return {embeddings:a,usage:{tokens:o},warnings:[]}}};var U=class{constructor(e,t,n,r={}){g(this,"specificationVersion","v3");g(this,"provider","local");g(this,"modelId");g(this,"languageModel");g(this,"options");g(this,"log",utils.Log.create({service:"local-model-sdk",module:"reranking-model"}));this.modelId=e,this.languageModel=new O("local",e,n),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:t,documents:n,topN:r,abortSignal:a}=e,o=n.type==="text"?n.values.map((s,i)=>({content:s,id:`doc_${i+1}`})):n.values.map((s,i)=>{let d=s;return {content:typeof d=="string"?d:JSON.stringify(d),id:typeof d?.id=="string"?d.id:`doc_${i+1}`}}),l=r??o.length;if(o.length===0)return {ranking:[],warnings:[]};try{let s=this.buildRerankPrompt(t,o),d=(await this.languageModel.doGenerate({prompt:[{role:"user",content:[{type:"text",text:s}]}],maxOutputTokens:2048,temperature:0,topP:1,topK:1,abortSignal:a})).content.find(c=>c.type==="text"),m=d&&d.type==="text"?d.text:"",f=this.parseRerankResult(m,o,l);return {ranking:f.results.map(c=>({index:c.index,relevanceScore:c.score})),warnings:f.warnings.map(c=>({type:"other",message:c})),response:{timestamp:new Date,modelId:this.modelId}}}catch(s){return this.log.error("Reranking failed",{error:s.message}),{ranking:o.map((d,m)=>({index:m,relevanceScore:o.length>1?this.options.totalScore*(1-.9*m/(o.length-1)):this.options.totalScore})),warnings:[{type:"other",message:`Reranking failed, using original order: ${s.message}`}],response:{timestamp:new Date,modelId:this.modelId}}}}buildRerankPrompt(e,t){let n=t.map((r,a)=>{let o=r.id||`doc_${a+1}`,l=r.content.slice(0,300);return `${a+1}. [ID: ${o}] ${l}`}).join(`
|
|
111
|
-
|
|
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:",
|
|
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",
|
|
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`,"",
|
|
115
|
-
`)}parseRerankResult(e,t
|
|
116
|
-
|
|
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:",
|
|
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",
|
|
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`,"",
|
|
120
|
-
`)}parseRerankResult(e,t
|
|
108
|
+
${n}<|im_end|>`;case "assistant":return `<|im_start|>assistant
|
|
109
|
+
${n}<|im_end|>`;case "tool":return `<|im_start|>tool
|
|
110
|
+
${n}<|im_end|>`;default:{let t=e.role;throw new exports.LocalModelErrors.UnsupportedFeatureError({message:`Unsupported message role: ${t}`,feature:"message.role",allowed:["system","user","assistant","tool"]})}}}};var k=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 pe(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var Q=/\{\s*"name"\s*:\s*"([^"]+)"\s*,\s*"parameters"\s*:\s*(\{[\s\S]*?\})\s*\}/g;function Z(m){let e=[];Q.lastIndex=0;let n;for(;(n=Q.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 v=class m{static extractToolCalls(e){let n=Z(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=Z(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=pe();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 ee(){return `${Date.now()}-${Math.random().toString(36).substring(2,9)}`}var _=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 exports.LocalModelErrors.ModelNotFoundError({message:`Unsupported Language Model ID: ${n}`,modelId:n})}async doGenerate(e){x.validateMessages(e.prompt);let n=(e.tools??[]).filter(p=>"inputSchema"in p),t=N.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};x.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=await this.engine.generate(t,r),o=k.removeThinkTags(a.content||""),{toolCalls:s,remainingText:u}=v.extractToolCalls(o),i=[];u.trim().length>0&&i.push({type:"text",text:u});for(let p of s)i.push({type:"tool-call",toolCallId:ee(),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){x.validateMessages(e.prompt);let n=(e.tools??[]).filter(s=>"inputSchema"in s),t=N.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};x.validateGenerateOptions(r),this.engine.isReady()||await this.engine.initialize();let a=[];return {stream:D.createReadableStream(async s=>{s.enqueue({type:"stream-start",warnings:a});let u=ee();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 M=k.processThinkTags(i,s);i.isInThinkTag=M.isInThinkTag,i.reasoningStarted=M.reasoningStarted,i.textStarted=M.textStarted,g.contentBuffer+=M.contentBuffer,i.contentBuffer="";let R=v.processToolCalls(g,s,n);g.contentBuffer=R.contentBuffer,g.textStarted=R.textStarted,g.completedToolCalls=R.completedToolCalls;}else if(d.type==="text-end"){let c=k.finishThinkParsing(i,s);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let M=v.finishToolParsing(g,s);g.textStarted=M.textStarted,p=!0;}else if(d.type==="finish"){if(!p){let R=k.finishThinkParsing(i,s);i.textStarted=R.textStarted,i.reasoningStarted=R.reasoningStarted;let ae=v.finishToolParsing(g,s);g.textStarted=ae.textStarted,p=!0;}let M=g.completedToolCalls.length>0?{unified:"tool-calls",raw:void 0}:d.finishReason??{unified:"stop",raw:void 0};s.enqueue({type:"finish",finishReason:M,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=k.finishThinkParsing(i,s);i.textStarted=c.textStarted,i.reasoningStarted=c.reasoningStarted;let M=v.finishToolParsing(g,s);g.textStarted=M.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 z=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 exports.LocalModelErrors.AbortedError({message:"Operation aborted"});let r=this.createBatches(e),a=[];for(let o=0;o<r.length;o++){if(t?.aborted)throw new exports.LocalModelErrors.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 utils.NamedError;if(exports.LocalModelErrors.AbortedError.isInstance(u))throw u;if(g)throw i;let p=utils.errorMeta(u);throw new exports.LocalModelErrors.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 exports.LocalModelErrors.AbortedError({message:"Operation aborted"}));return}let a=setTimeout(()=>{n?.removeEventListener("abort",o),t();},e),o=()=>{clearTimeout(a),r(new exports.LocalModelErrors.AbortedError({message:"Operation aborted"}));};n?.addEventListener("abort",o);})}};var q=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=I[n],!this.modelConfig)throw new exports.LocalModelErrors.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${n}`,modelId:n});this.maxEmbeddingsPerCall=this.modelConfig.maxEmbeddingsPerCall;}async doEmbed(e){let{values:n,abortSignal:t}=e;if(x.validateTexts(n),t?.aborted)throw new exports.LocalModelErrors.AbortedError({message:"Operation aborted"});this.engine.isReady()||await this.engine.initialize();let a=await new z({batchSize:this.maxEmbeddingsPerCall,delayBetweenBatches:0}).processBatches(n,async s=>{if(t?.aborted)throw new exports.LocalModelErrors.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 F=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",utils.Log.create({service:"local-model-sdk",module:"reranking-model"}));this.modelId=e,this.languageModel=new C("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:utils.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(`
|
|
111
|
+
|
|
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
|
+
`)}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
|
+
`)}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 M=this.options.totalScore*.1;i.push({index:c,score:M});}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:utils.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 U=class{constructor(e,n,t={}){f(this,"specificationVersion","v3");f(this,"provider");f(this,"modelId");f(this,"languageModel");f(this,"options");f(this,"log",utils.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 ai.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:utils.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(`
|
|
116
|
+
|
|
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
|
+
`)}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
|
+
`)}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:utils.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 w=utils.Log.create({service:"local-model-provider"}),xe={cacheDir:A__namespace.default.join(process.env.EASBOT_CACHE_PATH??`${A__namespace.default.join(W__namespace.homedir(),".cache","easbot")}`,"models"),verbose:false,autoUnloadTimeout:300*1e3,maxCachedModels:3,memoryWarningThreshold:1.5*1024*1024*1024,useEnhancedModel:true},V=class{constructor(e){f(this,"config");f(this,"modelCache");f(this,"engines",new Map);f(this,"modelInfo",new Map);this.config={...xe,...e},this.modelCache=new O({cacheDir:this.config.cacheDir});}languageModel(e,n){if(!T[e])throw new exports.LocalModelErrors.ModelNotFoundError({message:`Unsupported Language Model ID: ${e}`,modelId:e});let t=this.getOrCreateEngine(e,"language");return n?.useEnhancedModel??this.config.useEnhancedModel?(this.config.verbose&&w.debug("\u521B\u5EFA\u589E\u5F3A\u8BED\u8A00\u6A21\u578B",{modelId:e}),new _("local",e,t)):(this.config.verbose&&w.debug("\u521B\u5EFA\u57FA\u7840\u8BED\u8A00\u6A21\u578B",{modelId:e}),new C("local",e,t))}embeddingModel(e){if(!I[e])throw new exports.LocalModelErrors.ModelNotFoundError({message:`Unsupported Embedding Model ID: ${e}`,modelId:e});let n=this.getOrCreateEngine(e,"embedding");return new q("local",e,n)}chat(e,n){return this.languageModel(e,n)}rerankingModel(e,n){if(this.config.verbose&&w.debug("\u521B\u5EFA\u91CD\u6392\u5E8F\u6A21\u578B",{modelId:e,hasExternalLlm:!!n?.llm}),n?.llm)return new U(e,n.llm,n);if(!T[e])throw new exports.LocalModelErrors.ModelNotFoundError({message:`Unsupported Language Model ID: ${e}`,modelId:e});let t=this.getOrCreateEngine(e,"language");return new F(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&&w.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&&w.debug("\u521B\u5EFA\u65B0\u5F15\u64CE",{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&&w.debug("\u6DD8\u6C70\u6A21\u578B",{engineKey:e});let t=this.engines.get(e);t&&t.dispose().catch(r=>{w.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&&w.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&&w.debug("\u6240\u6709\u6A21\u578B\u5DF2\u5378\u8F7D");}};function Te(m){let e=new V(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 we="0.1.0",Le="@easbot/local-model-sdk",ke="Complete local model SDK for EASBot - Transformers.js + ONNX implementation";exports.ErrorCode=K;exports.ErrorHandler=E;exports.LLMRerankingModel=U;exports.LocalEmbeddingModel=q;exports.LocalEnhancedLanguageModel=_;exports.LocalLanguageModel=C;exports.LocalModelProvider=V;exports.LocalRerankingModel=F;exports.SDK_DESCRIPTION=ke;exports.SDK_NAME=Le;exports.SUPPORTED_EMBEDDING_MODELS=I;exports.SUPPORTED_LANGUAGE_MODELS=T;exports.VERSION=we;exports.createLocal=Te;
|