ohlcv-ai 1.0.7 → 1.0.9

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.d.ts CHANGED
@@ -311,10 +311,18 @@ export declare type DeepSeekStreamCallback = (chunk: string, isEnd: boolean) =>
311
311
 
312
312
  export declare function estimateCost(model: OpenAIModel, inputTokens: number, outputTokens?: number): CostEstimate;
313
313
 
314
+ export declare function getAllDeepSeekModels(): DeepSeekModel[];
315
+
316
+ export declare function getAllModels(): Model[];
317
+
314
318
  export declare function getAllOpenAIModels(): OpenAIModel[];
315
319
 
316
320
  export declare function getAudioModelsOpenAI(): OpenAIModel[];
317
321
 
322
+ export declare function getAvailableAliYunModelTypes(): AliYunModelType[];
323
+
324
+ export declare function getAvailableDeepSeekModelTypes(): DeepSeekModelType[];
325
+
318
326
  export declare function getAvailableOpenAIModelTypes(): OpenAIModelType[];
319
327
 
320
328
  export declare function getChatModels(): OpenAIModel[];
@@ -323,12 +331,20 @@ export declare function getCompletionModels(): OpenAIModel[];
323
331
 
324
332
  export declare function getCostEfficientModels(): OpenAIModel[];
325
333
 
334
+ export declare function getDeepSeekModel(type: DeepSeekModelType): DeepSeekModel | undefined;
335
+
336
+ export declare function getDeepSeekModelByName(name: string): DeepSeekModel | undefined;
337
+
326
338
  export declare function getEmbeddingModels(): OpenAIModel[];
327
339
 
328
340
  export declare function getHighContextModels(): OpenAIModel[];
329
341
 
330
342
  export declare function getLatestModels(): OpenAIModel[];
331
343
 
344
+ export declare function getModel(type: AliYunModelType): Model | undefined;
345
+
346
+ export declare function getModelByName(name: string): Model | undefined;
347
+
332
348
  export declare function getMultimodalModelsOpenAI(): OpenAIModel[];
333
349
 
334
350
  export declare function getOpenAIModel(type: OpenAIModelType): OpenAIModel | undefined;
@@ -605,6 +621,12 @@ export declare enum OpenAIModelType {
605
621
 
606
622
  export declare type OpenAIStreamCallback = (chunk: string, isEnd: boolean) => void;
607
623
 
624
+ export declare function stringToAliYunModelType(modelString: string): AliYunModelType | null;
625
+
626
+ export declare function stringToDeepSeekModelType(modelString: string): DeepSeekModelType | null;
627
+
628
+ export declare function stringToOpenAIModelType(modelString: string): OpenAIModelType | null;
629
+
608
630
  export declare function suggestModel(requirements: {
609
631
  taskType: 'chat' | 'completion' | 'embedding' | 'image' | 'audio';
610
632
  budget?: number;
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var v=(o=>(o.QWEN_TURBO="qwen-turbo",o.QWEN_PLUS="qwen-plus",o.QWEN_MAX="qwen-max",o.QWEN_MAX_LONGCONTEXT="qwen-max-longcontext",o.QWEN_2_5B="qwen2.5-0.5b",o.QWEN_2_5B_INSTRUCT="qwen2.5-0.5b-instruct",o.QWEN_2_5B_7B="qwen2.5-7b",o.QWEN_2_5B_7B_INSTRUCT="qwen2.5-7b-instruct",o.QWEN_2_5B_14B="qwen2.5-14b",o.QWEN_2_5B_14B_INSTRUCT="qwen2.5-14b-instruct",o.QWEN_2_5B_32B="qwen2.5-32b",o.QWEN_2_5B_32B_INSTRUCT="qwen2.5-32b-instruct",o.QWEN_2_5B_72B="qwen2.5-72b",o.QWEN_2_5B_72B_INSTRUCT="qwen2.5-72b-instruct",o.QWEN_2_5B_CODER="qwen2.5-coder",o.QWEN_2_5B_CODER_7B="qwen2.5-coder-7b",o.QWEN_2_5B_CODER_14B="qwen2.5-coder-14b",o.QWEN_2_5B_CODER_32B="qwen2.5-coder-32b",o.QWEN_VL_LITE="qwen-vl-lite",o.QWEN_VL_PLUS="qwen-vl-plus",o.QWEN_VL_MAX="qwen-vl-max",o.QWEN_AUDIO_TURBO="qwen-audio-turbo",o.QWEN_AUDIO_CHAT="qwen-audio-chat",o.QWEN_MATH_7B="qwen-math-7b",o.LLAMA2_7B_CHAT_V2="llama2-7b-chat-v2",o.BAICHUAN2_7B_CHAT_V1="baichuan2-7b-chat-v1",o.QWEN_FINANCIAL="qwen-financial",o.QWEN_FINANCIAL_14B="qwen-financial-14b",o.QWEN_FINANCIAL_32B="qwen-financial-32b",o.QWEN_MEDICAL="qwen-medical",o.QWEN_MEDICAL_14B="qwen-medical-14b",o.QWEN_MEDICAL_32B="qwen-medical-32b",o.QWEN_OMNI="qwen-omni",o.QWEN_OMNI_PRO="qwen-omni-pro",o))(v||{});const x=new Map([["qwen-turbo",{name:"qwen-turbo",displayName:"Qwen-Turbo",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions","https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"],format:"openai",description:"Lightweight version, fast response speed, suitable for general conversation scenarios",maxTokens:2e3,contextLength:8e3,capabilities:["text-generation","chat"]}],["qwen-plus",{name:"qwen-plus",displayName:"Qwen-Plus",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"],format:"openai",description:"Enhanced version, suitable for complex tasks and long text processing",maxTokens:6e3,contextLength:32e3,capabilities:["text-generation","chat","reasoning"]}],["qwen-max",{name:"qwen-max",displayName:"Qwen-Max",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"],format:"openai",description:"Maximum version, strongest capabilities, suitable for high-demand professional tasks",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","chat","reasoning","coding","analysis"]}],["qwen-max-longcontext",{name:"qwen-max-longcontext",displayName:"Qwen-Max-LongContext",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"],format:"openai",description:"Supports 128K long context, suitable for long document processing",maxTokens:8e3,contextLength:128e3,capabilities:["text-generation","chat","document-analysis"]}],["qwen2.5-0.5b",{name:"qwen2.5-0.5b",displayName:"Qwen2.5-0.5B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Ultra-lightweight 0.5B parameter model for edge devices",maxTokens:4e3,contextLength:32e3,capabilities:["text-generation","chat"]}],["qwen2.5-0.5b-instruct",{name:"qwen2.5-0.5b-instruct",displayName:"Qwen2.5-0.5B-Instruct",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Instruction-tuned 0.5B model for specific tasks",maxTokens:4e3,contextLength:32e3,capabilities:["instruction-following","chat"]}],["qwen2.5-7b",{name:"qwen2.5-7b",displayName:"Qwen2.5-7B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"7B parameter base model, balanced performance and efficiency",maxTokens:6e3,contextLength:32e3,capabilities:["text-generation","reasoning"]}],["qwen2.5-7b-instruct",{name:"qwen2.5-7b-instruct",displayName:"Qwen2.5-7B-Instruct",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Instruction-tuned 7B model for chat and tasks",maxTokens:6e3,contextLength:32e3,capabilities:["chat","instruction-following","coding"]}],["qwen2.5-14b",{name:"qwen2.5-14b",displayName:"Qwen2.5-14B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"14B parameter model with enhanced capabilities",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","analysis","reasoning"]}],["qwen2.5-32b",{name:"qwen2.5-32b",displayName:"Qwen2.5-32B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"32B parameter high-performance model",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","complex-reasoning","analysis"]}],["qwen2.5-72b",{name:"qwen2.5-72b",displayName:"Qwen2.5-72B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"72B parameter state-of-the-art model",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","expert-analysis","research"]}],["qwen2.5-coder",{name:"qwen2.5-coder",displayName:"Qwen2.5-Coder",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized code generation model",maxTokens:8e3,contextLength:32e3,capabilities:["code-generation","code-explanation","debugging"]}],["qwen2.5-coder-7b",{name:"qwen2.5-coder-7b",displayName:"Qwen2.5-Coder-7B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"7B parameter code generation model",maxTokens:8e3,contextLength:32e3,capabilities:["code-generation","programming"]}],["qwen2.5-coder-14b",{name:"qwen2.5-coder-14b",displayName:"Qwen2.5-Coder-14B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"14B parameter advanced code generation model",maxTokens:8e3,contextLength:32e3,capabilities:["code-generation","code-review","optimization"]}],["qwen-vl-lite",{name:"qwen-vl-lite",displayName:"Qwen-VL-Lite",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Lightweight vision-language model for basic image understanding",maxTokens:2e3,contextLength:8e3,capabilities:["image-understanding","visual-qa"]}],["qwen-vl-plus",{name:"qwen-vl-plus",displayName:"Qwen-VL-Plus",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Vision-language model supporting image understanding",maxTokens:4e3,contextLength:32e3,capabilities:["image-understanding","document-analysis","visual-reasoning"]}],["qwen-vl-max",{name:"qwen-vl-max",displayName:"Qwen-VL-Max",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Most powerful vision-language model",maxTokens:8e3,contextLength:32e3,capabilities:["image-understanding","video-analysis","multimodal-reasoning"]}],["qwen-audio-turbo",{name:"qwen-audio-turbo",displayName:"Qwen-Audio-Turbo",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Fast audio processing and speech-to-text model",maxTokens:2e3,contextLength:8e3,capabilities:["speech-recognition","audio-analysis"]}],["qwen-audio-chat",{name:"qwen-audio-chat",displayName:"Qwen-Audio-Chat",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Audio conversation and processing model",maxTokens:4e3,contextLength:32e3,capabilities:["audio-chat","voice-assistant","speech-synthesis"]}],["qwen-math-7b",{name:"qwen-math-7b",displayName:"Qwen-Math-7B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized for mathematical reasoning and problem solving",maxTokens:4e3,contextLength:32e3,capabilities:["mathematical-reasoning","problem-solving"]}],["llama2-7b-chat-v2",{name:"llama2-7b-chat-v2",displayName:"LLaMA2-7B-Chat",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Meta's LLaMA2-7B model",maxTokens:2e3,contextLength:8e3,capabilities:["chat","text-generation"]}],["baichuan2-7b-chat-v1",{name:"baichuan2-7b-chat-v1",displayName:"Baichuan2-7B-Chat",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Baichuan AI's Baichuan2-7B model",maxTokens:2e3,contextLength:8e3,capabilities:["chat","chinese-nlp"]}],["qwen-financial",{name:"qwen-financial",displayName:"Qwen-Financial",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized for financial analysis and market insights",maxTokens:6e3,contextLength:32e3,capabilities:["financial-analysis","market-prediction","risk-assessment"]}],["qwen-medical",{name:"qwen-medical",displayName:"Qwen-Medical",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized for medical consultation and health analysis",maxTokens:6e3,contextLength:32e3,capabilities:["medical-consultation","health-analysis","diagnostic-support"]}],["qwen-omni",{name:"qwen-omni",displayName:"Qwen-Omni",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Omnidirectional multimodal model supporting text, image, audio",maxTokens:8e3,contextLength:64e3,capabilities:["text-generation","image-understanding","audio-processing","multimodal"]}],["qwen-omni-pro",{name:"qwen-omni-pro",displayName:"Qwen-Omni-Pro",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Professional omnidirectional multimodal model with advanced capabilities",maxTokens:16e3,contextLength:128e3,capabilities:["text-generation","multimodal","complex-reasoning","expert-analysis"]}]]);class _{constructor(e){if(this.apiKey=e.apiKey,this.modelType=e.modelType||v.QWEN_TURBO,this.timeout=e.timeout||3e4,!this.apiKey)throw new Error("API Key cannot be empty");if(!x.get(this.modelType))throw new Error(`Unsupported model type: ${this.modelType}`)}async chat(e,t){const s=[];t?.systemPrompt&&s.push({role:"system",content:t.systemPrompt}),s.push({role:"user",content:e});const a=await this.chatCompletion(s,{temperature:t?.temperature,maxTokens:t?.maxTokens,stream:!1});return this.extractContent(a)}async chatCompletion(e,t){const s=t?.modelType||this.modelType,a=x.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=t?.temperature??.7,n=t?.maxTokens??1e3,r=t?.stream??!1,m=a.endpoint,p=a.format==="openai"?this.buildOpenAIRequest(a.name,e,i,n,r):this.buildDashScopeRequest(a.name,e,i,n);try{return await this.makeRequest(m,p,r)}catch(d){throw new Error(`Aliyun AI request failed: ${d.message}`)}}async chatStream(e,t,s){const a=s?.modelType||this.modelType,i=x.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);if(i.format!=="openai")throw new Error("Streaming conversation only supports OpenAI format models");const n=s?.temperature??.7,r=s?.maxTokens??1e3,m=this.buildOpenAIRequest(i.name,e,n,r,!0);try{await this.makeStreamRequest(i.endpoint,m,t)}catch(c){throw new Error(`Streaming request failed: ${c.message}`)}}setModel(e){if(!x.get(e))throw new Error(`Unsupported model type: ${e}`);this.modelType=e}getCurrentModel(){const e=x.get(this.modelType);if(!e)throw new Error(`Model configuration does not exist: ${this.modelType}`);return{name:e.name,displayName:e.displayName,description:e.description}}async testConnection(){try{const e=await this.chat('Hello, respond with "OK" if you can hear me.');return{success:!0,model:this.modelType,response:e}}catch(e){return{success:!1,model:this.modelType,error:e.message}}}buildOpenAIRequest(e,t,s,a,i){return{model:e,messages:t,temperature:s,max_tokens:a,stream:i}}buildDashScopeRequest(e,t,s,a){return{model:e,input:{messages:t},parameters:{temperature:s,max_tokens:a,result_format:"message"}}}async makeRequest(e,t,s){const a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const n=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json; charset=utf-8",Accept:"application/json"},body:JSON.stringify(t),signal:a.signal});if(clearTimeout(i),!n.ok){const r=await n.text();throw new Error(`HTTP ${n.status}: ${r}`)}return s?n.body:await n.json()}catch(n){throw clearTimeout(i),n.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):n}}async makeStreamRequest(e,t,s){const a=await this.makeRequest(e,t,!0);if(!a)throw new Error("Failed to get streaming response");const i=a.getReader(),n=new TextDecoder("utf-8");let r="";try{for(;;){const{done:m,value:c}=await i.read();if(m){s("",!0);break}r+=n.decode(c,{stream:!0});const p=r.split(`
2
- `);r=p.pop()||"";for(const d of p)if(d.startsWith("data: ")){const l=d.slice(6);if(l==="[DONE]"){s("",!0);return}try{const h=JSON.parse(l);h.choices?.[0]?.delta?.content&&s(h.choices[0].delta.content,!1)}catch{}}}}finally{i.releaseLock()}}extractContent(e){if(e.choices?.[0]?.message?.content)return e.choices[0].message.content;if(e.output?.choices?.[0]?.message?.content)return e.output.choices[0].message.content;if(e.output?.text)return e.output.text;throw new Error("Unable to parse response content")}async predictingOHLCV(e,t,s,a){const i=t||"Based on these OHLCV data, predict the next period",n=s||1;if(!Number.isInteger(n)||n<=0)throw new Error(`Invalid count parameter: ${n}. Must be a positive integer.`);const r=50;if(n>r)throw new Error(`Count parameter too large: ${n}. Maximum allowed is ${r}. Please reduce the count or split your request.`);const m=n===1?"Return EXACTLY 1 OHLCV object for the next period.":`Return EXACTLY ${n} consecutive OHLCV objects for the next ${n} periods.`,c=`You are a professional financial data analysis AI. The user will give you an array of OHLCV (Open, High, Low, Close, Volume) data.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var k=(t=>(t.QWEN_TURBO="qwen-turbo",t.QWEN_PLUS="qwen-plus",t.QWEN_MAX="qwen-max",t.QWEN_MAX_LONGCONTEXT="qwen-max-longcontext",t.QWEN_2_5B="qwen2.5-0.5b",t.QWEN_2_5B_INSTRUCT="qwen2.5-0.5b-instruct",t.QWEN_2_5B_7B="qwen2.5-7b",t.QWEN_2_5B_7B_INSTRUCT="qwen2.5-7b-instruct",t.QWEN_2_5B_14B="qwen2.5-14b",t.QWEN_2_5B_14B_INSTRUCT="qwen2.5-14b-instruct",t.QWEN_2_5B_32B="qwen2.5-32b",t.QWEN_2_5B_32B_INSTRUCT="qwen2.5-32b-instruct",t.QWEN_2_5B_72B="qwen2.5-72b",t.QWEN_2_5B_72B_INSTRUCT="qwen2.5-72b-instruct",t.QWEN_2_5B_CODER="qwen2.5-coder",t.QWEN_2_5B_CODER_7B="qwen2.5-coder-7b",t.QWEN_2_5B_CODER_14B="qwen2.5-coder-14b",t.QWEN_2_5B_CODER_32B="qwen2.5-coder-32b",t.QWEN_VL_LITE="qwen-vl-lite",t.QWEN_VL_PLUS="qwen-vl-plus",t.QWEN_VL_MAX="qwen-vl-max",t.QWEN_AUDIO_TURBO="qwen-audio-turbo",t.QWEN_AUDIO_CHAT="qwen-audio-chat",t.QWEN_MATH_7B="qwen-math-7b",t.LLAMA2_7B_CHAT_V2="llama2-7b-chat-v2",t.BAICHUAN2_7B_CHAT_V1="baichuan2-7b-chat-v1",t.QWEN_FINANCIAL="qwen-financial",t.QWEN_FINANCIAL_14B="qwen-financial-14b",t.QWEN_FINANCIAL_32B="qwen-financial-32b",t.QWEN_MEDICAL="qwen-medical",t.QWEN_MEDICAL_14B="qwen-medical-14b",t.QWEN_MEDICAL_32B="qwen-medical-32b",t.QWEN_OMNI="qwen-omni",t.QWEN_OMNI_PRO="qwen-omni-pro",t))(k||{});const b=new Map([["qwen-turbo",{name:"qwen-turbo",displayName:"Qwen-Turbo",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions","https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"],format:"openai",description:"Lightweight version, fast response speed, suitable for general conversation scenarios",maxTokens:2e3,contextLength:8e3,capabilities:["text-generation","chat"]}],["qwen-plus",{name:"qwen-plus",displayName:"Qwen-Plus",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"],format:"openai",description:"Enhanced version, suitable for complex tasks and long text processing",maxTokens:6e3,contextLength:32e3,capabilities:["text-generation","chat","reasoning"]}],["qwen-max",{name:"qwen-max",displayName:"Qwen-Max",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"],format:"openai",description:"Maximum version, strongest capabilities, suitable for high-demand professional tasks",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","chat","reasoning","coding","analysis"]}],["qwen-max-longcontext",{name:"qwen-max-longcontext",displayName:"Qwen-Max-LongContext",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",endpoints:["https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"],format:"openai",description:"Supports 128K long context, suitable for long document processing",maxTokens:8e3,contextLength:128e3,capabilities:["text-generation","chat","document-analysis"]}],["qwen2.5-0.5b",{name:"qwen2.5-0.5b",displayName:"Qwen2.5-0.5B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Ultra-lightweight 0.5B parameter model for edge devices",maxTokens:4e3,contextLength:32e3,capabilities:["text-generation","chat"]}],["qwen2.5-0.5b-instruct",{name:"qwen2.5-0.5b-instruct",displayName:"Qwen2.5-0.5B-Instruct",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Instruction-tuned 0.5B model for specific tasks",maxTokens:4e3,contextLength:32e3,capabilities:["instruction-following","chat"]}],["qwen2.5-7b",{name:"qwen2.5-7b",displayName:"Qwen2.5-7B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"7B parameter base model, balanced performance and efficiency",maxTokens:6e3,contextLength:32e3,capabilities:["text-generation","reasoning"]}],["qwen2.5-7b-instruct",{name:"qwen2.5-7b-instruct",displayName:"Qwen2.5-7B-Instruct",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Instruction-tuned 7B model for chat and tasks",maxTokens:6e3,contextLength:32e3,capabilities:["chat","instruction-following","coding"]}],["qwen2.5-14b",{name:"qwen2.5-14b",displayName:"Qwen2.5-14B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"14B parameter model with enhanced capabilities",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","analysis","reasoning"]}],["qwen2.5-32b",{name:"qwen2.5-32b",displayName:"Qwen2.5-32B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"32B parameter high-performance model",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","complex-reasoning","analysis"]}],["qwen2.5-72b",{name:"qwen2.5-72b",displayName:"Qwen2.5-72B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"72B parameter state-of-the-art model",maxTokens:8e3,contextLength:32e3,capabilities:["text-generation","expert-analysis","research"]}],["qwen2.5-coder",{name:"qwen2.5-coder",displayName:"Qwen2.5-Coder",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized code generation model",maxTokens:8e3,contextLength:32e3,capabilities:["code-generation","code-explanation","debugging"]}],["qwen2.5-coder-7b",{name:"qwen2.5-coder-7b",displayName:"Qwen2.5-Coder-7B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"7B parameter code generation model",maxTokens:8e3,contextLength:32e3,capabilities:["code-generation","programming"]}],["qwen2.5-coder-14b",{name:"qwen2.5-coder-14b",displayName:"Qwen2.5-Coder-14B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"14B parameter advanced code generation model",maxTokens:8e3,contextLength:32e3,capabilities:["code-generation","code-review","optimization"]}],["qwen-vl-lite",{name:"qwen-vl-lite",displayName:"Qwen-VL-Lite",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Lightweight vision-language model for basic image understanding",maxTokens:2e3,contextLength:8e3,capabilities:["image-understanding","visual-qa"]}],["qwen-vl-plus",{name:"qwen-vl-plus",displayName:"Qwen-VL-Plus",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Vision-language model supporting image understanding",maxTokens:4e3,contextLength:32e3,capabilities:["image-understanding","document-analysis","visual-reasoning"]}],["qwen-vl-max",{name:"qwen-vl-max",displayName:"Qwen-VL-Max",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Most powerful vision-language model",maxTokens:8e3,contextLength:32e3,capabilities:["image-understanding","video-analysis","multimodal-reasoning"]}],["qwen-audio-turbo",{name:"qwen-audio-turbo",displayName:"Qwen-Audio-Turbo",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Fast audio processing and speech-to-text model",maxTokens:2e3,contextLength:8e3,capabilities:["speech-recognition","audio-analysis"]}],["qwen-audio-chat",{name:"qwen-audio-chat",displayName:"Qwen-Audio-Chat",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Audio conversation and processing model",maxTokens:4e3,contextLength:32e3,capabilities:["audio-chat","voice-assistant","speech-synthesis"]}],["qwen-math-7b",{name:"qwen-math-7b",displayName:"Qwen-Math-7B",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized for mathematical reasoning and problem solving",maxTokens:4e3,contextLength:32e3,capabilities:["mathematical-reasoning","problem-solving"]}],["llama2-7b-chat-v2",{name:"llama2-7b-chat-v2",displayName:"LLaMA2-7B-Chat",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Meta's LLaMA2-7B model",maxTokens:2e3,contextLength:8e3,capabilities:["chat","text-generation"]}],["baichuan2-7b-chat-v1",{name:"baichuan2-7b-chat-v1",displayName:"Baichuan2-7B-Chat",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Baichuan AI's Baichuan2-7B model",maxTokens:2e3,contextLength:8e3,capabilities:["chat","chinese-nlp"]}],["qwen-financial",{name:"qwen-financial",displayName:"Qwen-Financial",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized for financial analysis and market insights",maxTokens:6e3,contextLength:32e3,capabilities:["financial-analysis","market-prediction","risk-assessment"]}],["qwen-medical",{name:"qwen-medical",displayName:"Qwen-Medical",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Specialized for medical consultation and health analysis",maxTokens:6e3,contextLength:32e3,capabilities:["medical-consultation","health-analysis","diagnostic-support"]}],["qwen-omni",{name:"qwen-omni",displayName:"Qwen-Omni",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Omnidirectional multimodal model supporting text, image, audio",maxTokens:8e3,contextLength:64e3,capabilities:["text-generation","image-understanding","audio-processing","multimodal"]}],["qwen-omni-pro",{name:"qwen-omni-pro",displayName:"Qwen-Omni-Pro",endpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",format:"openai",description:"Professional omnidirectional multimodal model with advanced capabilities",maxTokens:16e3,contextLength:128e3,capabilities:["text-generation","multimodal","complex-reasoning","expert-analysis"]}]]);function N(t){return b.get(t)}function P(){return Array.from(b.values())}function O(t){for(const e of b.values())if(e.name===t)return e}function q(){return Array.from(b.keys())}function S(t){const e=Object.values(k);for(const o of e)if(o===t)return o;return null}class _{constructor(e){if(this.apiKey=e.apiKey,this.modelType=e.modelType||k.QWEN_TURBO,this.timeout=e.timeout||3e4,!this.apiKey)throw new Error("API Key cannot be empty");if(!b.get(this.modelType))throw new Error(`Unsupported model type: ${this.modelType}`)}async chat(e,o){const s=[];o?.systemPrompt&&s.push({role:"system",content:o.systemPrompt}),s.push({role:"user",content:e});const a=await this.chatCompletion(s,{temperature:o?.temperature,maxTokens:o?.maxTokens,stream:!1});return this.extractContent(a)}async chatCompletion(e,o){const s=o?.modelType||this.modelType,a=b.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=o?.temperature??.7,n=o?.maxTokens??1e3,r=o?.stream??!1,p=a.endpoint,m=a.format==="openai"?this.buildOpenAIRequest(a.name,e,i,n,r):this.buildDashScopeRequest(a.name,e,i,n);try{return await this.makeRequest(p,m,r)}catch(d){throw new Error(`Aliyun AI request failed: ${d.message}`)}}async chatStream(e,o,s){const a=s?.modelType||this.modelType,i=b.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);if(i.format!=="openai")throw new Error("Streaming conversation only supports OpenAI format models");const n=s?.temperature??.7,r=s?.maxTokens??1e3,p=this.buildOpenAIRequest(i.name,e,n,r,!0);try{await this.makeStreamRequest(i.endpoint,p,o)}catch(c){throw new Error(`Streaming request failed: ${c.message}`)}}setModel(e){if(!b.get(e))throw new Error(`Unsupported model type: ${e}`);this.modelType=e}getCurrentModel(){const e=b.get(this.modelType);if(!e)throw new Error(`Model configuration does not exist: ${this.modelType}`);return{name:e.name,displayName:e.displayName,description:e.description}}async testConnection(){try{const e=await this.chat('Hello, respond with "OK" if you can hear me.');return{success:!0,model:this.modelType,response:e}}catch(e){return{success:!1,model:this.modelType,error:e.message}}}buildOpenAIRequest(e,o,s,a,i){return{model:e,messages:o,temperature:s,max_tokens:a,stream:i}}buildDashScopeRequest(e,o,s,a){return{model:e,input:{messages:o},parameters:{temperature:s,max_tokens:a,result_format:"message"}}}async makeRequest(e,o,s){const a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const n=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json; charset=utf-8",Accept:"application/json"},body:JSON.stringify(o),signal:a.signal});if(clearTimeout(i),!n.ok){const r=await n.text();throw new Error(`HTTP ${n.status}: ${r}`)}return s?n.body:await n.json()}catch(n){throw clearTimeout(i),n.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):n}}async makeStreamRequest(e,o,s){const a=await this.makeRequest(e,o,!0);if(!a)throw new Error("Failed to get streaming response");const i=a.getReader(),n=new TextDecoder("utf-8");let r="";try{for(;;){const{done:p,value:c}=await i.read();if(p){s("",!0);break}r+=n.decode(c,{stream:!0});const m=r.split(`
2
+ `);r=m.pop()||"";for(const d of m)if(d.startsWith("data: ")){const l=d.slice(6);if(l==="[DONE]"){s("",!0);return}try{const u=JSON.parse(l);u.choices?.[0]?.delta?.content&&s(u.choices[0].delta.content,!1)}catch{}}}}finally{i.releaseLock()}}extractContent(e){if(e.choices?.[0]?.message?.content)return e.choices[0].message.content;if(e.output?.choices?.[0]?.message?.content)return e.output.choices[0].message.content;if(e.output?.text)return e.output.text;throw new Error("Unable to parse response content")}async predictingOHLCV(e,o,s,a){const i=o||"Based on these OHLCV data, predict the next period",n=s||1;if(!Number.isInteger(n)||n<=0)throw new Error(`Invalid count parameter: ${n}. Must be a positive integer.`);const r=50;if(n>r)throw new Error(`Count parameter too large: ${n}. Maximum allowed is ${r}. Please reduce the count or split your request.`);const p=n===1?"Return EXACTLY 1 OHLCV object for the next period.":`Return EXACTLY ${n} consecutive OHLCV objects for the next ${n} periods.`,c=`You are a professional financial data analysis AI. The user will give you an array of OHLCV (Open, High, Low, Close, Volume) data.
3
3
  Your task: ${i}
4
4
  CRITICAL RULES:
5
- 1. ${m}
5
+ 1. ${p}
6
6
  2. Return ONLY a JSON array of OHLCV objects, NO explanations, comments, or other text
7
7
  3. The OHLCV array format must match: [{open, high, low, close, volume}, ...]
8
8
  4. All numbers must be valid numbers
@@ -17,13 +17,13 @@ ${n===1?`Example of valid response for 1 period:
17
17
  {"open": 117.5, "high": 120.0, "low": 116.0, "close": 119.0, "volume": 1400000}
18
18
  ${n>2?`,
19
19
  ... ${n-2} more OHLCV objects following the same pattern`:""}
20
- ]`}`,p=JSON.stringify(e,null,2),d=`Here is the historical OHLCV data (${e.length} periods):
21
- ${p}
22
- Please process this data according to the system instructions. Remember to return EXACTLY ${n} OHLCV object(s) in a JSON array with no additional text.`,l=[{role:"system",content:c},{role:"user",content:d}];try{const h=n*50+100,y=Math.max(a?.maxTokens||1e3,h),E=await this.chatCompletion(l,{temperature:a?.temperature||.3,maxTokens:y,stream:!1,modelType:a?.modelType}),b=this.extractContent(E),g=this.parseOHLCVResponse(b);if(g.length!==n)throw new Error(`AI returned ${g.length} OHLCV objects, but expected ${n}.`);return g}catch(h){throw new Error(`OHLCV analysis failed: ${h.message}`)}}parseOHLCVResponse(e){try{const t=JSON.parse(e);if(!Array.isArray(t))throw new Error("Response is not in array format");return t.map((a,i)=>{if(typeof a!="object"||a===null)throw new Error(`Element ${i} is not a valid object`);const{open:n,high:r,low:m,close:c,volume:p}=a,d=["open","high","low","close","volume"];for(const l of d)if(typeof a[l]!="number"||isNaN(a[l]))throw new Error(`Element ${i} field ${l} is not a valid number`);if(r<m)throw new Error(`Element ${i}: high cannot be lower than low`);if(c<m||c>r)throw new Error(`Element ${i}: close must be between low and high`);return{open:Number(n),high:Number(r),low:Number(m),close:Number(c),volume:Number(p)}})}catch(t){const s=e.match(/\[[\s\S]*\]/);if(s)return this.parseOHLCVResponse(s[0]);throw new Error(`Unable to parse AI returned OHLCV data: ${t}
23
- Original content: ${e.substring(0,200)}...`)}}}function N(o,e){return new _({apiKey:o,modelType:e})}var T=(o=>(o.DEEPSEEK_CHAT="deepseek-chat",o.DEEPSEEK_CHAT_LITE="deepseek-chat-lite",o.DEEPSEEK_CHAT_PRO="deepseek-chat-pro",o.DEEPSEEK_CHAT_MAX="deepseek-chat-max",o.DEEPSEEK_CODER="deepseek-coder",o.DEEPSEEK_CODER_LITE="deepseek-coder-lite",o.DEEPSEEK_CODER_PRO="deepseek-coder-pro",o.DEEPSEEK_MATH="deepseek-math",o.DEEPSEEK_MATH_PRO="deepseek-math-pro",o.DEEPSEEK_REASONER="deepseek-reasoner",o.DEEPSEEK_REASONER_PRO="deepseek-reasoner-pro",o.DEEPSEEK_VISION="deepseek-vision",o.DEEPSEEK_VISION_PRO="deepseek-vision-pro",o.DEEPSEEK_FINANCE="deepseek-finance",o.DEEPSEEK_LAW="deepseek-law",o.DEEPSEEK_MEDICAL="deepseek-medical",o.DEEPSEEK_RESEARCH="deepseek-research",o.DEEPSEEK_OMNI="deepseek-omni",o.DEEPSEEK_OMNI_PRO="deepseek-omni-pro",o.DEEPSEEK_LLM="deepseek-llm",o.DEEPSEEK_LLM_67B="deepseek-llm-67b",o.DEEPSEEK_LLM_131B="deepseek-llm-131b",o))(T||{});const k=new Map([["deepseek-chat",{name:"deepseek-chat",displayName:"DeepSeek Chat",endpoint:"https://api.deepseek.com/v1/chat/completions",endpoints:["https://api.deepseek.com/v1/chat/completions"],format:"openai",description:"General purpose chat model for everyday conversations and tasks",maxTokens:4096,contextLength:16e3,capabilities:["chat","text-generation","reasoning"],version:"2025-01"}],["deepseek-chat-lite",{name:"deepseek-chat-lite",displayName:"DeepSeek Chat Lite",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Lightweight chat model optimized for speed and efficiency",maxTokens:2048,contextLength:8e3,capabilities:["chat","text-generation"],version:"2025-01"}],["deepseek-chat-pro",{name:"deepseek-chat-pro",displayName:"DeepSeek Chat Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Professional chat model with enhanced reasoning capabilities",maxTokens:8192,contextLength:32e3,capabilities:["chat","text-generation","complex-reasoning","analysis"],version:"2025-01"}],["deepseek-chat-max",{name:"deepseek-chat-max",displayName:"DeepSeek Chat Max",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Maximum capability chat model for most demanding tasks",maxTokens:16384,contextLength:64e3,capabilities:["chat","text-generation","expert-analysis","research"],version:"2025-01"}],["deepseek-coder",{name:"deepseek-coder",displayName:"DeepSeek Coder",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized model for code generation and programming tasks",maxTokens:16384,contextLength:64e3,capabilities:["code-generation","programming","debugging","code-review"],version:"2025-01"}],["deepseek-coder-lite",{name:"deepseek-coder-lite",displayName:"DeepSeek Coder Lite",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Lightweight code generation model",maxTokens:4096,contextLength:16e3,capabilities:["code-generation","programming"],version:"2025-01"}],["deepseek-coder-pro",{name:"deepseek-coder-pro",displayName:"DeepSeek Coder Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Professional code generation model with advanced features",maxTokens:32768,contextLength:128e3,capabilities:["code-generation","programming","system-design","architecture"],version:"2025-01"}],["deepseek-math",{name:"deepseek-math",displayName:"DeepSeek Math",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized model for mathematical reasoning and problem solving",maxTokens:8192,contextLength:32e3,capabilities:["mathematical-reasoning","problem-solving","calculations"],version:"2025-01"}],["deepseek-math-pro",{name:"deepseek-math-pro",displayName:"DeepSeek Math Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Advanced mathematical reasoning model for complex problems",maxTokens:16384,contextLength:64e3,capabilities:["mathematical-reasoning","advanced-calculus","statistics"],version:"2025-01"}],["deepseek-reasoner",{name:"deepseek-reasoner",displayName:"DeepSeek Reasoner",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Dedicated reasoning model for logical analysis",maxTokens:8192,contextLength:32e3,capabilities:["logical-reasoning","analysis","decision-making"],version:"2025-01"}],["deepseek-reasoner-pro",{name:"deepseek-reasoner-pro",displayName:"DeepSeek Reasoner Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Advanced reasoning model for complex logical problems",maxTokens:16384,contextLength:64e3,capabilities:["complex-reasoning","scientific-analysis","research"],version:"2025-01"}],["deepseek-vision",{name:"deepseek-vision",displayName:"DeepSeek Vision",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Vision model for image understanding and analysis",maxTokens:4096,contextLength:16e3,capabilities:["image-understanding","visual-qa","document-analysis"],version:"2025-01"}],["deepseek-vision-pro",{name:"deepseek-vision-pro",displayName:"DeepSeek Vision Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Advanced vision model for complex visual tasks",maxTokens:8192,contextLength:32e3,capabilities:["image-understanding","video-analysis","visual-reasoning"],version:"2025-01"}],["deepseek-finance",{name:"deepseek-finance",displayName:"DeepSeek Finance",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for financial analysis, market prediction, and investment insights",maxTokens:8192,contextLength:32e3,capabilities:["financial-analysis","market-prediction","risk-assessment","investment-advice"],version:"2025-01"}],["deepseek-law",{name:"deepseek-law",displayName:"DeepSeek Law",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for legal analysis, contract review, and legal research",maxTokens:16384,contextLength:64e3,capabilities:["legal-analysis","contract-review","legal-research"],version:"2025-01"}],["deepseek-medical",{name:"deepseek-medical",displayName:"DeepSeek Medical",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for medical consultation, diagnosis support, and health analysis",maxTokens:8192,contextLength:32e3,capabilities:["medical-consultation","diagnostic-support","health-analysis"],version:"2025-01"}],["deepseek-research",{name:"deepseek-research",displayName:"DeepSeek Research",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for academic research and scientific analysis",maxTokens:32768,contextLength:128e3,capabilities:["academic-research","scientific-analysis","paper-writing"],version:"2025-01"}],["deepseek-omni",{name:"deepseek-omni",displayName:"DeepSeek Omni",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Multimodal model supporting text, image, and audio",maxTokens:16384,contextLength:64e3,capabilities:["text-generation","image-understanding","audio-processing","multimodal"],version:"2025-01"}],["deepseek-omni-pro",{name:"deepseek-omni-pro",displayName:"DeepSeek Omni Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Professional multimodal model with advanced capabilities",maxTokens:32768,contextLength:128e3,capabilities:["text-generation","multimodal","complex-reasoning","expert-analysis"],version:"2025-01"}],["deepseek-llm",{name:"deepseek-llm",displayName:"DeepSeek LLM",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Base large language model",maxTokens:4096,contextLength:16e3,capabilities:["text-generation"],version:"2024-12"}]]);class C{constructor(e){if(this.apiKey=e.apiKey,this.modelType=e.modelType||T.DEEPSEEK_CHAT,this.timeout=e.timeout||3e4,this.baseURL=e.baseURL||"https://api.deepseek.com",!this.apiKey)throw new Error("API Key cannot be empty");if(!k.get(this.modelType))throw new Error(`Unsupported model type: ${this.modelType}`)}async chat(e,t){const s=[];t?.systemPrompt&&s.push({role:"system",content:t.systemPrompt}),s.push({role:"user",content:e});const a=await this.chatCompletion(s,{temperature:t?.temperature,maxTokens:t?.maxTokens,stream:!1,modelType:t?.modelType,topP:t?.topP,frequencyPenalty:t?.frequencyPenalty,presencePenalty:t?.presencePenalty,stop:t?.stop,tools:t?.tools,toolChoice:t?.toolChoice});return this.extractContent(a)}async chatCompletion(e,t){const s=t?.modelType||this.modelType,a=k.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=t?.temperature??.7,n=t?.maxTokens??2e3,r=t?.stream??!1,m=t?.topP??1,c=t?.frequencyPenalty??0,p=t?.presencePenalty??0,d=t?.stop,l=t?.tools,h=t?.toolChoice,y=a.endpoint,E=this.buildOpenAIRequest(a.name,e,i,n,r,m,c,p,d,l,h);try{return await this.makeRequest(y,E,r)}catch(b){throw new Error(`DeepSeek AI request failed: ${b.message}`)}}async chatStream(e,t,s){const a=s?.modelType||this.modelType,i=k.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);const n=s?.temperature??.7,r=s?.maxTokens??2e3,m=s?.topP??1,c=s?.frequencyPenalty??0,p=s?.presencePenalty??0,d=this.buildOpenAIRequest(i.name,e,n,r,!0,m,c,p,s?.stop,s?.tools,s?.toolChoice);try{await this.makeStreamRequest(i.endpoint,d,t)}catch(l){throw new Error(`Streaming request failed: ${l.message}`)}}async predictingOHLCV(e,t,s,a){const i=t||"Based on these OHLCV data, predict the next period",n=s||1;if(!Number.isInteger(n)||n<=0)throw new Error(`Invalid count parameter: ${n}. Must be a positive integer.`);const r=50;if(n>r)throw new Error(`Count parameter too large: ${n}. Maximum allowed is ${r}.`);const m=n===1?"Return EXACTLY 1 OHLCV object for the next period.":`Return EXACTLY ${n} consecutive OHLCV objects for the next ${n} periods.`,c=`You are a professional financial data analysis AI. The user will give you an array of OHLCV (Open, High, Low, Close, Volume) data.
20
+ ]`}`,m=JSON.stringify(e,null,2),d=`Here is the historical OHLCV data (${e.length} periods):
21
+ ${m}
22
+ Please process this data according to the system instructions. Remember to return EXACTLY ${n} OHLCV object(s) in a JSON array with no additional text.`,l=[{role:"system",content:c},{role:"user",content:d}];try{const u=n*50+100,x=Math.max(a?.maxTokens||1e3,u),T=await this.chatCompletion(l,{temperature:a?.temperature||.3,maxTokens:x,stream:!1,modelType:a?.modelType}),E=this.extractContent(T),f=this.parseOHLCVResponse(E);if(f.length!==n)throw new Error(`AI returned ${f.length} OHLCV objects, but expected ${n}.`);return f}catch(u){throw new Error(`OHLCV analysis failed: ${u.message}`)}}parseOHLCVResponse(e){try{const o=JSON.parse(e);if(!Array.isArray(o))throw new Error("Response is not in array format");return o.map((a,i)=>{if(typeof a!="object"||a===null)throw new Error(`Element ${i} is not a valid object`);const{open:n,high:r,low:p,close:c,volume:m}=a,d=["open","high","low","close","volume"];for(const l of d)if(typeof a[l]!="number"||isNaN(a[l]))throw new Error(`Element ${i} field ${l} is not a valid number`);if(r<p)throw new Error(`Element ${i}: high cannot be lower than low`);if(c<p||c>r)throw new Error(`Element ${i}: close must be between low and high`);return{open:Number(n),high:Number(r),low:Number(p),close:Number(c),volume:Number(m)}})}catch(o){const s=e.match(/\[[\s\S]*\]/);if(s)return this.parseOHLCVResponse(s[0]);throw new Error(`Unable to parse AI returned OHLCV data: ${o}
23
+ Original content: ${e.substring(0,200)}...`)}}}function A(t,e){return new _({apiKey:t,modelType:e})}var v=(t=>(t.DEEPSEEK_CHAT="deepseek-chat",t.DEEPSEEK_CHAT_LITE="deepseek-chat-lite",t.DEEPSEEK_CHAT_PRO="deepseek-chat-pro",t.DEEPSEEK_CHAT_MAX="deepseek-chat-max",t.DEEPSEEK_CODER="deepseek-coder",t.DEEPSEEK_CODER_LITE="deepseek-coder-lite",t.DEEPSEEK_CODER_PRO="deepseek-coder-pro",t.DEEPSEEK_MATH="deepseek-math",t.DEEPSEEK_MATH_PRO="deepseek-math-pro",t.DEEPSEEK_REASONER="deepseek-reasoner",t.DEEPSEEK_REASONER_PRO="deepseek-reasoner-pro",t.DEEPSEEK_VISION="deepseek-vision",t.DEEPSEEK_VISION_PRO="deepseek-vision-pro",t.DEEPSEEK_FINANCE="deepseek-finance",t.DEEPSEEK_LAW="deepseek-law",t.DEEPSEEK_MEDICAL="deepseek-medical",t.DEEPSEEK_RESEARCH="deepseek-research",t.DEEPSEEK_OMNI="deepseek-omni",t.DEEPSEEK_OMNI_PRO="deepseek-omni-pro",t.DEEPSEEK_LLM="deepseek-llm",t.DEEPSEEK_LLM_67B="deepseek-llm-67b",t.DEEPSEEK_LLM_131B="deepseek-llm-131b",t))(v||{});const y=new Map([["deepseek-chat",{name:"deepseek-chat",displayName:"DeepSeek Chat",endpoint:"https://api.deepseek.com/v1/chat/completions",endpoints:["https://api.deepseek.com/v1/chat/completions"],format:"openai",description:"General purpose chat model for everyday conversations and tasks",maxTokens:4096,contextLength:16e3,capabilities:["chat","text-generation","reasoning"],version:"2025-01"}],["deepseek-chat-lite",{name:"deepseek-chat-lite",displayName:"DeepSeek Chat Lite",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Lightweight chat model optimized for speed and efficiency",maxTokens:2048,contextLength:8e3,capabilities:["chat","text-generation"],version:"2025-01"}],["deepseek-chat-pro",{name:"deepseek-chat-pro",displayName:"DeepSeek Chat Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Professional chat model with enhanced reasoning capabilities",maxTokens:8192,contextLength:32e3,capabilities:["chat","text-generation","complex-reasoning","analysis"],version:"2025-01"}],["deepseek-chat-max",{name:"deepseek-chat-max",displayName:"DeepSeek Chat Max",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Maximum capability chat model for most demanding tasks",maxTokens:16384,contextLength:64e3,capabilities:["chat","text-generation","expert-analysis","research"],version:"2025-01"}],["deepseek-coder",{name:"deepseek-coder",displayName:"DeepSeek Coder",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized model for code generation and programming tasks",maxTokens:16384,contextLength:64e3,capabilities:["code-generation","programming","debugging","code-review"],version:"2025-01"}],["deepseek-coder-lite",{name:"deepseek-coder-lite",displayName:"DeepSeek Coder Lite",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Lightweight code generation model",maxTokens:4096,contextLength:16e3,capabilities:["code-generation","programming"],version:"2025-01"}],["deepseek-coder-pro",{name:"deepseek-coder-pro",displayName:"DeepSeek Coder Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Professional code generation model with advanced features",maxTokens:32768,contextLength:128e3,capabilities:["code-generation","programming","system-design","architecture"],version:"2025-01"}],["deepseek-math",{name:"deepseek-math",displayName:"DeepSeek Math",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized model for mathematical reasoning and problem solving",maxTokens:8192,contextLength:32e3,capabilities:["mathematical-reasoning","problem-solving","calculations"],version:"2025-01"}],["deepseek-math-pro",{name:"deepseek-math-pro",displayName:"DeepSeek Math Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Advanced mathematical reasoning model for complex problems",maxTokens:16384,contextLength:64e3,capabilities:["mathematical-reasoning","advanced-calculus","statistics"],version:"2025-01"}],["deepseek-reasoner",{name:"deepseek-reasoner",displayName:"DeepSeek Reasoner",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Dedicated reasoning model for logical analysis",maxTokens:8192,contextLength:32e3,capabilities:["logical-reasoning","analysis","decision-making"],version:"2025-01"}],["deepseek-reasoner-pro",{name:"deepseek-reasoner-pro",displayName:"DeepSeek Reasoner Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Advanced reasoning model for complex logical problems",maxTokens:16384,contextLength:64e3,capabilities:["complex-reasoning","scientific-analysis","research"],version:"2025-01"}],["deepseek-vision",{name:"deepseek-vision",displayName:"DeepSeek Vision",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Vision model for image understanding and analysis",maxTokens:4096,contextLength:16e3,capabilities:["image-understanding","visual-qa","document-analysis"],version:"2025-01"}],["deepseek-vision-pro",{name:"deepseek-vision-pro",displayName:"DeepSeek Vision Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Advanced vision model for complex visual tasks",maxTokens:8192,contextLength:32e3,capabilities:["image-understanding","video-analysis","visual-reasoning"],version:"2025-01"}],["deepseek-finance",{name:"deepseek-finance",displayName:"DeepSeek Finance",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for financial analysis, market prediction, and investment insights",maxTokens:8192,contextLength:32e3,capabilities:["financial-analysis","market-prediction","risk-assessment","investment-advice"],version:"2025-01"}],["deepseek-law",{name:"deepseek-law",displayName:"DeepSeek Law",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for legal analysis, contract review, and legal research",maxTokens:16384,contextLength:64e3,capabilities:["legal-analysis","contract-review","legal-research"],version:"2025-01"}],["deepseek-medical",{name:"deepseek-medical",displayName:"DeepSeek Medical",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for medical consultation, diagnosis support, and health analysis",maxTokens:8192,contextLength:32e3,capabilities:["medical-consultation","diagnostic-support","health-analysis"],version:"2025-01"}],["deepseek-research",{name:"deepseek-research",displayName:"DeepSeek Research",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Specialized for academic research and scientific analysis",maxTokens:32768,contextLength:128e3,capabilities:["academic-research","scientific-analysis","paper-writing"],version:"2025-01"}],["deepseek-omni",{name:"deepseek-omni",displayName:"DeepSeek Omni",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Multimodal model supporting text, image, and audio",maxTokens:16384,contextLength:64e3,capabilities:["text-generation","image-understanding","audio-processing","multimodal"],version:"2025-01"}],["deepseek-omni-pro",{name:"deepseek-omni-pro",displayName:"DeepSeek Omni Pro",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Professional multimodal model with advanced capabilities",maxTokens:32768,contextLength:128e3,capabilities:["text-generation","multimodal","complex-reasoning","expert-analysis"],version:"2025-01"}],["deepseek-llm",{name:"deepseek-llm",displayName:"DeepSeek LLM",endpoint:"https://api.deepseek.com/v1/chat/completions",format:"openai",description:"Base large language model",maxTokens:4096,contextLength:16e3,capabilities:["text-generation"],version:"2024-12"}]]);function $(t){return y.get(t)}function R(){return Array.from(y.values())}function D(t){for(const e of y.values())if(e.name===t)return e}function I(){return Array.from(y.keys())}function B(t){const e=Object.values(v);for(const o of e)if(o===t)return o;return null}class C{constructor(e){if(this.apiKey=e.apiKey,this.modelType=e.modelType||v.DEEPSEEK_CHAT,this.timeout=e.timeout||3e4,this.baseURL=e.baseURL||"https://api.deepseek.com",!this.apiKey)throw new Error("API Key cannot be empty");if(!y.get(this.modelType))throw new Error(`Unsupported model type: ${this.modelType}`)}async chat(e,o){const s=[];o?.systemPrompt&&s.push({role:"system",content:o.systemPrompt}),s.push({role:"user",content:e});const a=await this.chatCompletion(s,{temperature:o?.temperature,maxTokens:o?.maxTokens,stream:!1,modelType:o?.modelType,topP:o?.topP,frequencyPenalty:o?.frequencyPenalty,presencePenalty:o?.presencePenalty,stop:o?.stop,tools:o?.tools,toolChoice:o?.toolChoice});return this.extractContent(a)}async chatCompletion(e,o){const s=o?.modelType||this.modelType,a=y.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=o?.temperature??.7,n=o?.maxTokens??2e3,r=o?.stream??!1,p=o?.topP??1,c=o?.frequencyPenalty??0,m=o?.presencePenalty??0,d=o?.stop,l=o?.tools,u=o?.toolChoice,x=a.endpoint,T=this.buildOpenAIRequest(a.name,e,i,n,r,p,c,m,d,l,u);try{return await this.makeRequest(x,T,r)}catch(E){throw new Error(`DeepSeek AI request failed: ${E.message}`)}}async chatStream(e,o,s){const a=s?.modelType||this.modelType,i=y.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);const n=s?.temperature??.7,r=s?.maxTokens??2e3,p=s?.topP??1,c=s?.frequencyPenalty??0,m=s?.presencePenalty??0,d=this.buildOpenAIRequest(i.name,e,n,r,!0,p,c,m,s?.stop,s?.tools,s?.toolChoice);try{await this.makeStreamRequest(i.endpoint,d,o)}catch(l){throw new Error(`Streaming request failed: ${l.message}`)}}async predictingOHLCV(e,o,s,a){const i=o||"Based on these OHLCV data, predict the next period",n=s||1;if(!Number.isInteger(n)||n<=0)throw new Error(`Invalid count parameter: ${n}. Must be a positive integer.`);const r=50;if(n>r)throw new Error(`Count parameter too large: ${n}. Maximum allowed is ${r}.`);const p=n===1?"Return EXACTLY 1 OHLCV object for the next period.":`Return EXACTLY ${n} consecutive OHLCV objects for the next ${n} periods.`,c=`You are a professional financial data analysis AI. The user will give you an array of OHLCV (Open, High, Low, Close, Volume) data.
24
24
  Your task: ${i}
25
25
  CRITICAL RULES:
26
- 1. ${m}
26
+ 1. ${p}
27
27
  2. Return ONLY a JSON array of OHLCV objects, NO explanations, comments, or other text
28
28
  3. The OHLCV array format must match: [{open, high, low, close, volume}, ...]
29
29
  4. All numbers must be valid numbers
@@ -39,15 +39,15 @@ ${n===1?`Example of valid response for 1 period:
39
39
  {"open": 117.5, "high": 120.0, "low": 116.0, "close": 119.0, "volume": 1400000}
40
40
  ${n>2?`,
41
41
  ... ${n-2} more OHLCV objects following the same pattern`:""}
42
- ]`}`,p=JSON.stringify(e,null,2),d=`Here is the historical OHLCV data (${e.length} periods):
43
- ${p}
44
- Please process this data according to the system instructions. Remember to return EXACTLY ${n} OHLCV object(s) in a JSON array with no additional text.`,l=[{role:"system",content:c},{role:"user",content:d}];try{const h=n*50+100,y=Math.max(a?.maxTokens||2e3,h),E=await this.chatCompletion(l,{temperature:a?.temperature||.3,maxTokens:y,stream:!1,modelType:a?.modelType||T.DEEPSEEK_FINANCE,topP:a?.topP,frequencyPenalty:a?.frequencyPenalty,presencePenalty:a?.presencePenalty}),b=this.extractContent(E),g=this.parseOHLCVResponse(b);if(g.length!==n)throw new Error(`AI returned ${g.length} OHLCV objects, but expected ${n}.`);return g}catch(h){throw new Error(`OHLCV analysis failed: ${h.message}`)}}setModel(e){if(!k.get(e))throw new Error(`Unsupported model type: ${e}`);this.modelType=e}getCurrentModel(){const e=k.get(this.modelType);if(!e)throw new Error(`Model configuration does not exist: ${this.modelType}`);return{name:e.name,displayName:e.displayName,description:e.description}}async testConnection(){try{const e=await this.chat('Hello, respond with "OK" if you can hear me.');return{success:!0,model:this.modelType,response:e}}catch(e){return{success:!1,model:this.modelType,error:e.message}}}buildOpenAIRequest(e,t,s,a,i,n,r,m,c,p,d){const l={model:e,messages:t,temperature:s,max_tokens:a,stream:i};return n!==void 0&&(l.top_p=n),r!==void 0&&(l.frequency_penalty=r),m!==void 0&&(l.presence_penalty=m),c&&(l.stop=c),p&&(l.tools=p),d&&(l.tool_choice=d),l}async makeRequest(e,t,s){const a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const n=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json; charset=utf-8",Accept:"application/json"},body:JSON.stringify(t),signal:a.signal});if(clearTimeout(i),!n.ok){const r=await n.text();throw new Error(`HTTP ${n.status}: ${r}`)}return s?n.body:await n.json()}catch(n){throw clearTimeout(i),n.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):n}}async makeStreamRequest(e,t,s){const a=await this.makeRequest(e,t,!0);if(!a)throw new Error("Failed to get streaming response");const i=a.getReader(),n=new TextDecoder("utf-8");let r="";try{for(;;){const{done:m,value:c}=await i.read();if(m){s("",!0);break}r+=n.decode(c,{stream:!0});const p=r.split(`
45
- `);r=p.pop()||"";for(const d of p)if(d.startsWith("data: ")){const l=d.slice(6);if(l==="[DONE]"){s("",!0);return}try{const h=JSON.parse(l);h.choices?.[0]?.delta?.content&&s(h.choices[0].delta.content,!1)}catch{}}}}finally{i.releaseLock()}}extractContent(e){if(e.choices?.[0]?.message?.content)return e.choices[0].message.content;if(e.output?.choices?.[0]?.message?.content)return e.output.choices[0].message.content;if(e.output?.text)return e.output.text;if(e.choices?.[0]?.delta?.content)return e.choices[0].delta.content;throw new Error("Unable to parse response content")}parseOHLCVResponse(e){try{const t=JSON.parse(e);if(!Array.isArray(t))throw new Error("Response is not in array format");return t.map((a,i)=>{if(typeof a!="object"||a===null)throw new Error(`Element ${i} is not a valid object`);const{open:n,high:r,low:m,close:c,volume:p}=a,d=["open","high","low","close","volume"];for(const l of d)if(typeof a[l]!="number"||isNaN(a[l]))throw new Error(`Element ${i} field ${l} is not a valid number`);if(r<m)throw new Error(`Element ${i}: high cannot be lower than low`);if(c<m||c>r)throw new Error(`Element ${i}: close must be between low and high`);return{open:Number(n),high:Number(r),low:Number(m),close:Number(c),volume:Number(p)}})}catch(t){const s=e.match(/\[[\s\S]*\]/);if(s)return this.parseOHLCVResponse(s[0]);throw new Error(`Unable to parse AI returned OHLCV data: ${t}
46
- Original content: ${e.substring(0,200)}...`)}}}function P(o,e){return new C({apiKey:o,modelType:e})}var f=(o=>(o.GPT4="gpt-4",o.GPT4_0314="gpt-4-0314",o.GPT4_0613="gpt-4-0613",o.GPT4_32K="gpt-4-32k",o.GPT4_32K_0314="gpt-4-32k-0314",o.GPT4_32K_0613="gpt-4-32k-0613",o.GPT4_TURBO="gpt-4-turbo",o.GPT4_TURBO_PREVIEW="gpt-4-turbo-preview",o.GPT4_TURBO_2024_04_09="gpt-4-turbo-2024-04-09",o.GPT4_OMNI="gpt-4o",o.GPT4_OMNI_2024_05_13="gpt-4o-2024-05-13",o.GPT4_OMNI_MINI="gpt-4o-mini",o.GPT4_OMNI_MINI_2024_07_18="gpt-4o-mini-2024-07-18",o.GPT3_5_TURBO="gpt-3.5-turbo",o.GPT3_5_TURBO_0125="gpt-3.5-turbo-0125",o.GPT3_5_TURBO_1106="gpt-3.5-turbo-1106",o.GPT3_5_TURBO_INSTRUCT="gpt-3.5-turbo-instruct",o.GPT3_5_TURBO_16K="gpt-3.5-turbo-16k",o.GPT3_5_TURBO_16K_0613="gpt-3.5-turbo-16k-0613",o.DAVINCI_002="davinci-002",o.BABBAGE_002="babbage-002",o.TEXT_DAVINCI_003="text-davinci-003",o.TEXT_DAVINCI_002="text-davinci-002",o.TEXT_DAVINCI_001="text-davinci-001",o.TEXT_CURIE_001="text-curie-001",o.TEXT_BABBAGE_001="text-babbage-001",o.TEXT_ADA_001="text-ada-001",o.TEXT_EMBEDDING_ADA_002="text-embedding-ada-002",o.TEXT_EMBEDDING_3_SMALL="text-embedding-3-small",o.TEXT_EMBEDDING_3_LARGE="text-embedding-3-large",o.DALL_E_2="dall-e-2",o.DALL_E_3="dall-e-3",o.WHISPER_1="whisper-1",o.TTS_1="tts-1",o.TTS_1_HD="tts-1-hd",o.MODERATION_LATEST="text-moderation-latest",o.MODERATION_STABLE="text-moderation-stable",o.GPT3_5_TURBO_FINETUNED="ft:gpt-3.5-turbo-0125:personal:",o.GPT4_FINETUNED="ft:gpt-4-0125-preview:personal:",o.GPT4_VISION_PREVIEW="gpt-4-vision-preview",o))(f||{});const u=new Map([["gpt-4",{name:"gpt-4",displayName:"GPT-4",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Powerful multi-purpose model for complex tasks",maxTokens:8192,contextLength:8192,capabilities:["chat","text-generation","reasoning","analysis"],inputCostPer1KTokens:.03,outputCostPer1KTokens:.06,supportedFeatures:["chat","function-calling"]}],["gpt-4-turbo",{name:"gpt-4-turbo",displayName:"GPT-4 Turbo",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Enhanced GPT-4 with 128K context, knowledge cutoff April 2023",maxTokens:4096,contextLength:128e3,capabilities:["chat","text-generation","reasoning","analysis","vision"],inputCostPer1KTokens:.01,outputCostPer1KTokens:.03,supportedFeatures:["chat","function-calling","vision","json-mode"]}],["gpt-4o",{name:"gpt-4o",displayName:"GPT-4o",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Versatile model supporting text, images, audio with fast response",maxTokens:4096,contextLength:128e3,capabilities:["chat","text-generation","vision","audio-processing","multimodal"],inputCostPer1KTokens:.005,outputCostPer1KTokens:.015,supportedFeatures:["chat","function-calling","vision","audio","json-mode"]}],["gpt-4o-mini",{name:"gpt-4o-mini",displayName:"GPT-4o Mini",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Compact and efficient version of GPT-4o with lower cost",maxTokens:16384,contextLength:128e3,capabilities:["chat","text-generation","vision"],inputCostPer1KTokens:15e-5,outputCostPer1KTokens:6e-4,supportedFeatures:["chat","function-calling","vision","json-mode"]}],["gpt-3.5-turbo",{name:"gpt-3.5-turbo",displayName:"GPT-3.5 Turbo",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Fast and cost-effective, suitable for most conversational tasks",maxTokens:4096,contextLength:16385,capabilities:["chat","text-generation","code-generation"],inputCostPer1KTokens:5e-4,outputCostPer1KTokens:.0015,supportedFeatures:["chat","function-calling"]}],["gpt-3.5-turbo-instruct",{name:"gpt-3.5-turbo-instruct",displayName:"GPT-3.5 Turbo Instruct",endpoint:"https://api.openai.com/v1/completions",format:"openai",description:"Instruction-tuned version for text completion tasks",maxTokens:4096,contextLength:4097,capabilities:["text-completion","instruction-following"],inputCostPer1KTokens:.0015,outputCostPer1KTokens:.002,supportedFeatures:["completions"]}],["text-embedding-ada-002",{name:"text-embedding-ada-002",displayName:"Text Embedding Ada 002",endpoint:"https://api.openai.com/v1/embeddings",format:"openai",description:"Text embedding model, 1536 dimensions, suitable for retrieval and similarity",contextLength:8191,capabilities:["embeddings","semantic-search"],inputCostPer1KTokens:1e-4,supportedFeatures:["embeddings"]}],["text-embedding-3-small",{name:"text-embedding-3-small",displayName:"Text Embedding 3 Small",endpoint:"https://api.openai.com/v1/embeddings",format:"openai",description:"Small text embedding model, 1536 dimensions, balance of performance and cost",contextLength:8191,capabilities:["embeddings","semantic-search"],inputCostPer1KTokens:2e-5,supportedFeatures:["embeddings"]}],["dall-e-3",{name:"dall-e-3",displayName:"DALL-E 3",endpoint:"https://api.openai.com/v1/images/generations",format:"openai",description:"Advanced image generation model producing high-quality, high-resolution images",capabilities:["image-generation","creative-design"],inputCostPer1KTokens:.04,supportedFeatures:["image-generation","variations","edits"]}],["whisper-1",{name:"whisper-1",displayName:"Whisper",endpoint:"https://api.openai.com/v1/audio/transcriptions",format:"openai",description:"Speech recognition model supporting multilingual transcription and translation",capabilities:["speech-recognition","audio-transcription","translation"],inputCostPer1KTokens:.006,supportedFeatures:["transcriptions","translations"]}],["tts-1-hd",{name:"tts-1-hd",displayName:"TTS-1 HD",endpoint:"https://api.openai.com/v1/audio/speech",format:"openai",description:"High-quality text-to-speech with multiple voice options",capabilities:["speech-synthesis","text-to-speech"],inputCostPer1KTokens:.015,supportedFeatures:["speech","voice-selection"]}],["text-moderation-latest",{name:"text-moderation-latest",displayName:"Moderation Latest",endpoint:"https://api.openai.com/v1/moderations",format:"openai",description:"Content moderation model for detecting harmful content",capabilities:["content-moderation","safety"],inputCostPer1KTokens:1e-4,supportedFeatures:["moderation"]}]]);function O(o){return u.get(o)}function w(){return Array.from(u.values())}function q(o){for(const e of u.values())if(e.name===o)return e}function S(){return Array.from(u.keys())}function $(){return w().filter(o=>o.capabilities.includes("chat"))}function R(){return w().filter(o=>o.capabilities.includes("text-completion"))}function A(){return w().filter(o=>o.capabilities.includes("embeddings"))}function I(){return w().filter(o=>o.capabilities.includes("vision")||o.capabilities.includes("image-generation"))}function D(){return w().filter(o=>o.capabilities.includes("audio-processing")||o.capabilities.includes("speech-recognition")||o.capabilities.includes("speech-synthesis"))}function B(){return w().filter(o=>o.capabilities.includes("multimodal"))}function H(){const o=["gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","dall-e-3"];return w().filter(e=>o.includes(e.name))}function K(){return w().filter(o=>o.inputCostPer1KTokens&&o.inputCostPer1KTokens<.001).sort((o,e)=>(o.inputCostPer1KTokens||0)-(e.inputCostPer1KTokens||0))}function V(){return w().filter(o=>o.contextLength&&o.contextLength>=128e3).sort((o,e)=>(e.contextLength||0)-(o.contextLength||0))}function U(o,e,t=0){const s=(o.inputCostPer1KTokens||0)/1e3*e,a=(o.outputCostPer1KTokens||0)/1e3*t;return{inputTokens:e,outputTokens:t,inputCost:s,outputCost:a,totalCost:s+a}}function Q(o){let e=w();switch(o.taskType){case"chat":e=e.filter(t=>t.capabilities.includes("chat"));break;case"completion":e=e.filter(t=>t.capabilities.includes("text-completion"));break;case"embedding":e=e.filter(t=>t.capabilities.includes("embeddings"));break;case"image":e=e.filter(t=>t.capabilities.includes("image-generation")||t.capabilities.includes("vision"));break;case"audio":e=e.filter(t=>t.capabilities.includes("speech-recognition")||t.capabilities.includes("speech-synthesis"));break}return o.contextLength&&(e=e.filter(t=>t.contextLength&&t.contextLength>=o.contextLength)),o.features&&o.features.length>0&&(e=e.filter(t=>o.features.every(s=>t.supportedFeatures?.includes(s)||t.capabilities.includes(s)))),o.budget&&e.sort((t,s)=>(t.inputCostPer1KTokens||0)-(s.inputCostPer1KTokens||0)),e.slice(0,5)}class L{constructor(e){if(this.apiKey=e.apiKey,this.modelType=e.modelType||f.GPT3_5_TURBO,this.timeout=e.timeout||3e4,this.organization=e.organization,this.baseURL=e.baseURL||"https://api.openai.com/v1",!this.apiKey)throw new Error("API Key cannot be empty");if(!u.get(this.modelType))throw new Error(`Unsupported model type: ${this.modelType}`)}async chat(e,t){const s=[];t?.systemPrompt&&s.push({role:"system",content:t.systemPrompt}),s.push({role:"user",content:e});const a=await this.chatCompletion(s,{temperature:t?.temperature,maxTokens:t?.maxTokens,stream:!1,topP:t?.topP,frequencyPenalty:t?.frequencyPenalty,presencePenalty:t?.presencePenalty,stop:t?.stop});return this.extractContent(a)}async chatCompletion(e,t){const s=t?.modelType||this.modelType,a=u.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=t?.temperature??.7,n=t?.maxTokens??1e3,r=t?.stream??!1,m=a.endpoint,c=this.buildOpenAIRequest(a.name,e,i,n,r,t);try{return await this.makeRequest(m,c,r)}catch(p){throw new Error(`OpenAI request failed: ${p.message}`)}}async chatStream(e,t,s){const a=s?.modelType||this.modelType,i=u.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);const n=s?.temperature??.7,r=s?.maxTokens??1e3,m=this.buildOpenAIRequest(i.name,e,n,r,!0,s);try{await this.makeStreamRequest(i.endpoint,m,t)}catch(c){throw new Error(`Streaming request failed: ${c.message}`)}}async generateImage(e,t){const s=t?.modelType||f.DALL_E_3;if(s!==f.DALL_E_2&&s!==f.DALL_E_3)throw new Error("Image generation only supports DALL-E models");const a=u.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,prompt:e,n:t?.n||1,size:t?.size||"1024x1024",quality:t?.quality||"standard",style:t?.style||"vivid",response_format:t?.responseFormat||"url"};try{const n=await this.makeRequest(a.endpoint,i,!1);if(n.data&&Array.isArray(n.data))return n.data.map(r=>t?.responseFormat==="b64_json"?r.b64_json:r.url);throw new Error("Invalid response format from image generation")}catch(n){throw new Error(`Image generation failed: ${n.message}`)}}async createEmbeddings(e,t){const s=t?.modelType||f.TEXT_EMBEDDING_ADA_002,a=u.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,input:e};t?.dimensions&&a.name===f.TEXT_EMBEDDING_3_SMALL&&(i.dimensions=t.dimensions);try{const n=await this.makeRequest(a.endpoint,i,!1);if(n.data&&Array.isArray(n.data))return n.data.map(r=>r.embedding);throw new Error("Invalid response format from embeddings")}catch(n){throw new Error(`Embedding creation failed: ${n.message}`)}}async transcribeAudio(e,t){const s=t?.modelType||f.WHISPER_1,a=u.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=new FormData;if(typeof e=="string")throw new Error("File path/Base64 support requires additional implementation");i.append("file",e),i.append("model",a.name),t?.language&&i.append("language",t.language),t?.prompt&&i.append("prompt",t.prompt),t?.responseFormat&&i.append("response_format",t.responseFormat),t?.temperature!==void 0&&i.append("temperature",t.temperature.toString());try{const n=await this.makeFormDataRequest(a.endpoint,i,!1);return n.text||n.transcription||""}catch(n){throw new Error(`Audio transcription failed: ${n.message}`)}}async textToSpeech(e,t){const s=t?.modelType||f.TTS_1_HD,a=u.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,input:e,voice:t?.voice||"alloy",response_format:t?.responseFormat||"mp3",speed:t?.speed||1};try{return await this.makeRequest(a.endpoint,i,!1,!0)}catch(n){throw new Error(`Text-to-speech conversion failed: ${n.message}`)}}async moderateContent(e,t){const s=t?.modelType||f.MODERATION_LATEST,a=u.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,input:e};try{return(await this.makeRequest(a.endpoint,i,!1)).results||[]}catch(n){throw new Error(`Content moderation failed: ${n.message}`)}}setModel(e){if(!u.get(e))throw new Error(`Unsupported model type: ${e}`);this.modelType=e}getCurrentModel(){const e=u.get(this.modelType);if(!e)throw new Error(`Model configuration does not exist: ${this.modelType}`);return{name:e.name,displayName:e.displayName,description:e.description}}async testConnection(){try{const e=await this.chat('Hello, respond with "OK" if you can hear me.');return{success:!0,model:this.modelType,response:e}}catch(e){return{success:!1,model:this.modelType,error:e.message}}}estimateCost(e,t=0,s){const a=s||this.modelType,i=u.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);const n=(i.inputCostPer1KTokens||0)/1e3*e,r=(i.outputCostPer1KTokens||0)/1e3*t;return{inputCost:n,outputCost:r,totalCost:n+r}}buildOpenAIRequest(e,t,s,a,i,n){const r={model:e,messages:t,temperature:s,max_tokens:a,stream:i};return n?.topP!==void 0&&(r.top_p=n.topP),n?.frequencyPenalty!==void 0&&(r.frequency_penalty=n.frequencyPenalty),n?.presencePenalty!==void 0&&(r.presence_penalty=n.presencePenalty),n?.stop!==void 0&&(r.stop=n.stop),r}async makeRequest(e,t,s,a=!1){const i=new AbortController,n=setTimeout(()=>i.abort(),this.timeout);try{const r=e.startsWith("http")?e:`${this.baseURL}${e}`,m={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};this.organization&&(m["OpenAI-Organization"]=this.organization);const c=await fetch(r,{method:"POST",headers:m,body:JSON.stringify(t),signal:i.signal});if(clearTimeout(n),!c.ok){const p=await c.text();try{const d=JSON.parse(p);throw new Error(`HTTP ${c.status}: ${d.error?.message||p}`)}catch{throw new Error(`HTTP ${c.status}: ${p}`)}}return a?await c.arrayBuffer():s?c.body:await c.json()}catch(r){throw clearTimeout(n),r.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):r}}async makeFormDataRequest(e,t,s){const a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const n=e.startsWith("http")?e:`${this.baseURL}${e}`,r={Authorization:`Bearer ${this.apiKey}`};this.organization&&(r["OpenAI-Organization"]=this.organization);const m=await fetch(n,{method:"POST",headers:r,body:t,signal:a.signal});if(clearTimeout(i),!m.ok){const c=await m.text();try{const p=JSON.parse(c);throw new Error(`HTTP ${m.status}: ${p.error?.message||c}`)}catch{throw new Error(`HTTP ${m.status}: ${c}`)}}return s?m.body:await m.json()}catch(n){throw clearTimeout(i),n.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):n}}async makeStreamRequest(e,t,s){const a=await this.makeRequest(e,t,!0);if(!a)throw new Error("Failed to get streaming response");const i=a.getReader(),n=new TextDecoder("utf-8");let r="";try{for(;;){const{done:m,value:c}=await i.read();if(m){s("",!0);break}r+=n.decode(c,{stream:!0});const p=r.split(`
47
- `);r=p.pop()||"";for(const d of p)if(d.startsWith("data: ")){const l=d.slice(6);if(l==="[DONE]"){s("",!0);return}try{const h=JSON.parse(l);h.choices?.[0]?.delta?.content&&s(h.choices[0].delta.content,!1)}catch{}}}}finally{i.releaseLock()}}extractContent(e){if(e.choices?.[0]?.message?.content)return e.choices[0].message.content;if(e.data?.[0]?.b64_json)return e.data[0].b64_json;if(e.data?.[0]?.url)return e.data[0].url;if(e.text)return e.text;throw new Error("Unable to parse response content")}async analyzeOHLCV(e,t,s,a){const i=t||"Based on these OHLCV data, predict the next period",n=s||1;if(!Number.isInteger(n)||n<=0)throw new Error(`Invalid count parameter: ${n}. Must be a positive integer.`);const r=50;if(n>r)throw new Error(`Count parameter too large: ${n}. Maximum allowed is ${r}. Please reduce the count or split your request.`);const m=n===1?"Return EXACTLY 1 OHLCV object for the next period.":`Return EXACTLY ${n} consecutive OHLCV objects for the next ${n} periods.`,c=`You are a professional financial data analysis AI. The user will give you an array of OHLCV (Open, High, Low, Close, Volume) data.
42
+ ]`}`,m=JSON.stringify(e,null,2),d=`Here is the historical OHLCV data (${e.length} periods):
43
+ ${m}
44
+ Please process this data according to the system instructions. Remember to return EXACTLY ${n} OHLCV object(s) in a JSON array with no additional text.`,l=[{role:"system",content:c},{role:"user",content:d}];try{const u=n*50+100,x=Math.max(a?.maxTokens||2e3,u),T=await this.chatCompletion(l,{temperature:a?.temperature||.3,maxTokens:x,stream:!1,modelType:a?.modelType||v.DEEPSEEK_FINANCE,topP:a?.topP,frequencyPenalty:a?.frequencyPenalty,presencePenalty:a?.presencePenalty}),E=this.extractContent(T),f=this.parseOHLCVResponse(E);if(f.length!==n)throw new Error(`AI returned ${f.length} OHLCV objects, but expected ${n}.`);return f}catch(u){throw new Error(`OHLCV analysis failed: ${u.message}`)}}setModel(e){if(!y.get(e))throw new Error(`Unsupported model type: ${e}`);this.modelType=e}getCurrentModel(){const e=y.get(this.modelType);if(!e)throw new Error(`Model configuration does not exist: ${this.modelType}`);return{name:e.name,displayName:e.displayName,description:e.description}}async testConnection(){try{const e=await this.chat('Hello, respond with "OK" if you can hear me.');return{success:!0,model:this.modelType,response:e}}catch(e){return{success:!1,model:this.modelType,error:e.message}}}buildOpenAIRequest(e,o,s,a,i,n,r,p,c,m,d){const l={model:e,messages:o,temperature:s,max_tokens:a,stream:i};return n!==void 0&&(l.top_p=n),r!==void 0&&(l.frequency_penalty=r),p!==void 0&&(l.presence_penalty=p),c&&(l.stop=c),m&&(l.tools=m),d&&(l.tool_choice=d),l}async makeRequest(e,o,s){const a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const n=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json; charset=utf-8",Accept:"application/json"},body:JSON.stringify(o),signal:a.signal});if(clearTimeout(i),!n.ok){const r=await n.text();throw new Error(`HTTP ${n.status}: ${r}`)}return s?n.body:await n.json()}catch(n){throw clearTimeout(i),n.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):n}}async makeStreamRequest(e,o,s){const a=await this.makeRequest(e,o,!0);if(!a)throw new Error("Failed to get streaming response");const i=a.getReader(),n=new TextDecoder("utf-8");let r="";try{for(;;){const{done:p,value:c}=await i.read();if(p){s("",!0);break}r+=n.decode(c,{stream:!0});const m=r.split(`
45
+ `);r=m.pop()||"";for(const d of m)if(d.startsWith("data: ")){const l=d.slice(6);if(l==="[DONE]"){s("",!0);return}try{const u=JSON.parse(l);u.choices?.[0]?.delta?.content&&s(u.choices[0].delta.content,!1)}catch{}}}}finally{i.releaseLock()}}extractContent(e){if(e.choices?.[0]?.message?.content)return e.choices[0].message.content;if(e.output?.choices?.[0]?.message?.content)return e.output.choices[0].message.content;if(e.output?.text)return e.output.text;if(e.choices?.[0]?.delta?.content)return e.choices[0].delta.content;throw new Error("Unable to parse response content")}parseOHLCVResponse(e){try{const o=JSON.parse(e);if(!Array.isArray(o))throw new Error("Response is not in array format");return o.map((a,i)=>{if(typeof a!="object"||a===null)throw new Error(`Element ${i} is not a valid object`);const{open:n,high:r,low:p,close:c,volume:m}=a,d=["open","high","low","close","volume"];for(const l of d)if(typeof a[l]!="number"||isNaN(a[l]))throw new Error(`Element ${i} field ${l} is not a valid number`);if(r<p)throw new Error(`Element ${i}: high cannot be lower than low`);if(c<p||c>r)throw new Error(`Element ${i}: close must be between low and high`);return{open:Number(n),high:Number(r),low:Number(p),close:Number(c),volume:Number(m)}})}catch(o){const s=e.match(/\[[\s\S]*\]/);if(s)return this.parseOHLCVResponse(s[0]);throw new Error(`Unable to parse AI returned OHLCV data: ${o}
46
+ Original content: ${e.substring(0,200)}...`)}}}function H(t,e){return new C({apiKey:t,modelType:e})}var g=(t=>(t.GPT4="gpt-4",t.GPT4_0314="gpt-4-0314",t.GPT4_0613="gpt-4-0613",t.GPT4_32K="gpt-4-32k",t.GPT4_32K_0314="gpt-4-32k-0314",t.GPT4_32K_0613="gpt-4-32k-0613",t.GPT4_TURBO="gpt-4-turbo",t.GPT4_TURBO_PREVIEW="gpt-4-turbo-preview",t.GPT4_TURBO_2024_04_09="gpt-4-turbo-2024-04-09",t.GPT4_OMNI="gpt-4o",t.GPT4_OMNI_2024_05_13="gpt-4o-2024-05-13",t.GPT4_OMNI_MINI="gpt-4o-mini",t.GPT4_OMNI_MINI_2024_07_18="gpt-4o-mini-2024-07-18",t.GPT3_5_TURBO="gpt-3.5-turbo",t.GPT3_5_TURBO_0125="gpt-3.5-turbo-0125",t.GPT3_5_TURBO_1106="gpt-3.5-turbo-1106",t.GPT3_5_TURBO_INSTRUCT="gpt-3.5-turbo-instruct",t.GPT3_5_TURBO_16K="gpt-3.5-turbo-16k",t.GPT3_5_TURBO_16K_0613="gpt-3.5-turbo-16k-0613",t.DAVINCI_002="davinci-002",t.BABBAGE_002="babbage-002",t.TEXT_DAVINCI_003="text-davinci-003",t.TEXT_DAVINCI_002="text-davinci-002",t.TEXT_DAVINCI_001="text-davinci-001",t.TEXT_CURIE_001="text-curie-001",t.TEXT_BABBAGE_001="text-babbage-001",t.TEXT_ADA_001="text-ada-001",t.TEXT_EMBEDDING_ADA_002="text-embedding-ada-002",t.TEXT_EMBEDDING_3_SMALL="text-embedding-3-small",t.TEXT_EMBEDDING_3_LARGE="text-embedding-3-large",t.DALL_E_2="dall-e-2",t.DALL_E_3="dall-e-3",t.WHISPER_1="whisper-1",t.TTS_1="tts-1",t.TTS_1_HD="tts-1-hd",t.MODERATION_LATEST="text-moderation-latest",t.MODERATION_STABLE="text-moderation-stable",t.GPT3_5_TURBO_FINETUNED="ft:gpt-3.5-turbo-0125:personal:",t.GPT4_FINETUNED="ft:gpt-4-0125-preview:personal:",t.GPT4_VISION_PREVIEW="gpt-4-vision-preview",t))(g||{});const h=new Map([["gpt-4",{name:"gpt-4",displayName:"GPT-4",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Powerful multi-purpose model for complex tasks",maxTokens:8192,contextLength:8192,capabilities:["chat","text-generation","reasoning","analysis"],inputCostPer1KTokens:.03,outputCostPer1KTokens:.06,supportedFeatures:["chat","function-calling"]}],["gpt-4-turbo",{name:"gpt-4-turbo",displayName:"GPT-4 Turbo",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Enhanced GPT-4 with 128K context, knowledge cutoff April 2023",maxTokens:4096,contextLength:128e3,capabilities:["chat","text-generation","reasoning","analysis","vision"],inputCostPer1KTokens:.01,outputCostPer1KTokens:.03,supportedFeatures:["chat","function-calling","vision","json-mode"]}],["gpt-4o",{name:"gpt-4o",displayName:"GPT-4o",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Versatile model supporting text, images, audio with fast response",maxTokens:4096,contextLength:128e3,capabilities:["chat","text-generation","vision","audio-processing","multimodal"],inputCostPer1KTokens:.005,outputCostPer1KTokens:.015,supportedFeatures:["chat","function-calling","vision","audio","json-mode"]}],["gpt-4o-mini",{name:"gpt-4o-mini",displayName:"GPT-4o Mini",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Compact and efficient version of GPT-4o with lower cost",maxTokens:16384,contextLength:128e3,capabilities:["chat","text-generation","vision"],inputCostPer1KTokens:15e-5,outputCostPer1KTokens:6e-4,supportedFeatures:["chat","function-calling","vision","json-mode"]}],["gpt-3.5-turbo",{name:"gpt-3.5-turbo",displayName:"GPT-3.5 Turbo",endpoint:"https://api.openai.com/v1/chat/completions",format:"openai",description:"Fast and cost-effective, suitable for most conversational tasks",maxTokens:4096,contextLength:16385,capabilities:["chat","text-generation","code-generation"],inputCostPer1KTokens:5e-4,outputCostPer1KTokens:.0015,supportedFeatures:["chat","function-calling"]}],["gpt-3.5-turbo-instruct",{name:"gpt-3.5-turbo-instruct",displayName:"GPT-3.5 Turbo Instruct",endpoint:"https://api.openai.com/v1/completions",format:"openai",description:"Instruction-tuned version for text completion tasks",maxTokens:4096,contextLength:4097,capabilities:["text-completion","instruction-following"],inputCostPer1KTokens:.0015,outputCostPer1KTokens:.002,supportedFeatures:["completions"]}],["text-embedding-ada-002",{name:"text-embedding-ada-002",displayName:"Text Embedding Ada 002",endpoint:"https://api.openai.com/v1/embeddings",format:"openai",description:"Text embedding model, 1536 dimensions, suitable for retrieval and similarity",contextLength:8191,capabilities:["embeddings","semantic-search"],inputCostPer1KTokens:1e-4,supportedFeatures:["embeddings"]}],["text-embedding-3-small",{name:"text-embedding-3-small",displayName:"Text Embedding 3 Small",endpoint:"https://api.openai.com/v1/embeddings",format:"openai",description:"Small text embedding model, 1536 dimensions, balance of performance and cost",contextLength:8191,capabilities:["embeddings","semantic-search"],inputCostPer1KTokens:2e-5,supportedFeatures:["embeddings"]}],["dall-e-3",{name:"dall-e-3",displayName:"DALL-E 3",endpoint:"https://api.openai.com/v1/images/generations",format:"openai",description:"Advanced image generation model producing high-quality, high-resolution images",capabilities:["image-generation","creative-design"],inputCostPer1KTokens:.04,supportedFeatures:["image-generation","variations","edits"]}],["whisper-1",{name:"whisper-1",displayName:"Whisper",endpoint:"https://api.openai.com/v1/audio/transcriptions",format:"openai",description:"Speech recognition model supporting multilingual transcription and translation",capabilities:["speech-recognition","audio-transcription","translation"],inputCostPer1KTokens:.006,supportedFeatures:["transcriptions","translations"]}],["tts-1-hd",{name:"tts-1-hd",displayName:"TTS-1 HD",endpoint:"https://api.openai.com/v1/audio/speech",format:"openai",description:"High-quality text-to-speech with multiple voice options",capabilities:["speech-synthesis","text-to-speech"],inputCostPer1KTokens:.015,supportedFeatures:["speech","voice-selection"]}],["text-moderation-latest",{name:"text-moderation-latest",displayName:"Moderation Latest",endpoint:"https://api.openai.com/v1/moderations",format:"openai",description:"Content moderation model for detecting harmful content",capabilities:["content-moderation","safety"],inputCostPer1KTokens:1e-4,supportedFeatures:["moderation"]}]]);function K(t){return h.get(t)}function w(){return Array.from(h.values())}function V(t){for(const e of h.values())if(e.name===t)return e}function U(){return Array.from(h.keys())}function M(){return w().filter(t=>t.capabilities.includes("chat"))}function Q(){return w().filter(t=>t.capabilities.includes("text-completion"))}function j(){return w().filter(t=>t.capabilities.includes("embeddings"))}function W(){return w().filter(t=>t.capabilities.includes("vision")||t.capabilities.includes("image-generation"))}function F(){return w().filter(t=>t.capabilities.includes("audio-processing")||t.capabilities.includes("speech-recognition")||t.capabilities.includes("speech-synthesis"))}function G(){return w().filter(t=>t.capabilities.includes("multimodal"))}function X(){const t=["gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-3.5-turbo","text-embedding-3-small","dall-e-3"];return w().filter(e=>t.includes(e.name))}function z(){return w().filter(t=>t.inputCostPer1KTokens&&t.inputCostPer1KTokens<.001).sort((t,e)=>(t.inputCostPer1KTokens||0)-(e.inputCostPer1KTokens||0))}function J(){return w().filter(t=>t.contextLength&&t.contextLength>=128e3).sort((t,e)=>(e.contextLength||0)-(t.contextLength||0))}function Z(t,e,o=0){const s=(t.inputCostPer1KTokens||0)/1e3*e,a=(t.outputCostPer1KTokens||0)/1e3*o;return{inputTokens:e,outputTokens:o,inputCost:s,outputCost:a,totalCost:s+a}}function Y(t){let e=w();switch(t.taskType){case"chat":e=e.filter(o=>o.capabilities.includes("chat"));break;case"completion":e=e.filter(o=>o.capabilities.includes("text-completion"));break;case"embedding":e=e.filter(o=>o.capabilities.includes("embeddings"));break;case"image":e=e.filter(o=>o.capabilities.includes("image-generation")||o.capabilities.includes("vision"));break;case"audio":e=e.filter(o=>o.capabilities.includes("speech-recognition")||o.capabilities.includes("speech-synthesis"));break}return t.contextLength&&(e=e.filter(o=>o.contextLength&&o.contextLength>=t.contextLength)),t.features&&t.features.length>0&&(e=e.filter(o=>t.features.every(s=>o.supportedFeatures?.includes(s)||o.capabilities.includes(s)))),t.budget&&e.sort((o,s)=>(o.inputCostPer1KTokens||0)-(s.inputCostPer1KTokens||0)),e.slice(0,5)}function ee(t){const e=Object.values(g);for(const o of e)if(o===t)return o;return null}class L{constructor(e){if(this.apiKey=e.apiKey,this.modelType=e.modelType||g.GPT3_5_TURBO,this.timeout=e.timeout||3e4,this.organization=e.organization,this.baseURL=e.baseURL||"https://api.openai.com/v1",!this.apiKey)throw new Error("API Key cannot be empty");if(!h.get(this.modelType))throw new Error(`Unsupported model type: ${this.modelType}`)}async chat(e,o){const s=[];o?.systemPrompt&&s.push({role:"system",content:o.systemPrompt}),s.push({role:"user",content:e});const a=await this.chatCompletion(s,{temperature:o?.temperature,maxTokens:o?.maxTokens,stream:!1,topP:o?.topP,frequencyPenalty:o?.frequencyPenalty,presencePenalty:o?.presencePenalty,stop:o?.stop});return this.extractContent(a)}async chatCompletion(e,o){const s=o?.modelType||this.modelType,a=h.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=o?.temperature??.7,n=o?.maxTokens??1e3,r=o?.stream??!1,p=a.endpoint,c=this.buildOpenAIRequest(a.name,e,i,n,r,o);try{return await this.makeRequest(p,c,r)}catch(m){throw new Error(`OpenAI request failed: ${m.message}`)}}async chatStream(e,o,s){const a=s?.modelType||this.modelType,i=h.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);const n=s?.temperature??.7,r=s?.maxTokens??1e3,p=this.buildOpenAIRequest(i.name,e,n,r,!0,s);try{await this.makeStreamRequest(i.endpoint,p,o)}catch(c){throw new Error(`Streaming request failed: ${c.message}`)}}async generateImage(e,o){const s=o?.modelType||g.DALL_E_3;if(s!==g.DALL_E_2&&s!==g.DALL_E_3)throw new Error("Image generation only supports DALL-E models");const a=h.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,prompt:e,n:o?.n||1,size:o?.size||"1024x1024",quality:o?.quality||"standard",style:o?.style||"vivid",response_format:o?.responseFormat||"url"};try{const n=await this.makeRequest(a.endpoint,i,!1);if(n.data&&Array.isArray(n.data))return n.data.map(r=>o?.responseFormat==="b64_json"?r.b64_json:r.url);throw new Error("Invalid response format from image generation")}catch(n){throw new Error(`Image generation failed: ${n.message}`)}}async createEmbeddings(e,o){const s=o?.modelType||g.TEXT_EMBEDDING_ADA_002,a=h.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,input:e};o?.dimensions&&a.name===g.TEXT_EMBEDDING_3_SMALL&&(i.dimensions=o.dimensions);try{const n=await this.makeRequest(a.endpoint,i,!1);if(n.data&&Array.isArray(n.data))return n.data.map(r=>r.embedding);throw new Error("Invalid response format from embeddings")}catch(n){throw new Error(`Embedding creation failed: ${n.message}`)}}async transcribeAudio(e,o){const s=o?.modelType||g.WHISPER_1,a=h.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i=new FormData;if(typeof e=="string")throw new Error("File path/Base64 support requires additional implementation");i.append("file",e),i.append("model",a.name),o?.language&&i.append("language",o.language),o?.prompt&&i.append("prompt",o.prompt),o?.responseFormat&&i.append("response_format",o.responseFormat),o?.temperature!==void 0&&i.append("temperature",o.temperature.toString());try{const n=await this.makeFormDataRequest(a.endpoint,i,!1);return n.text||n.transcription||""}catch(n){throw new Error(`Audio transcription failed: ${n.message}`)}}async textToSpeech(e,o){const s=o?.modelType||g.TTS_1_HD,a=h.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,input:e,voice:o?.voice||"alloy",response_format:o?.responseFormat||"mp3",speed:o?.speed||1};try{return await this.makeRequest(a.endpoint,i,!1,!0)}catch(n){throw new Error(`Text-to-speech conversion failed: ${n.message}`)}}async moderateContent(e,o){const s=o?.modelType||g.MODERATION_LATEST,a=h.get(s);if(!a)throw new Error(`Unsupported model type: ${s}`);const i={model:a.name,input:e};try{return(await this.makeRequest(a.endpoint,i,!1)).results||[]}catch(n){throw new Error(`Content moderation failed: ${n.message}`)}}setModel(e){if(!h.get(e))throw new Error(`Unsupported model type: ${e}`);this.modelType=e}getCurrentModel(){const e=h.get(this.modelType);if(!e)throw new Error(`Model configuration does not exist: ${this.modelType}`);return{name:e.name,displayName:e.displayName,description:e.description}}async testConnection(){try{const e=await this.chat('Hello, respond with "OK" if you can hear me.');return{success:!0,model:this.modelType,response:e}}catch(e){return{success:!1,model:this.modelType,error:e.message}}}estimateCost(e,o=0,s){const a=s||this.modelType,i=h.get(a);if(!i)throw new Error(`Unsupported model type: ${a}`);const n=(i.inputCostPer1KTokens||0)/1e3*e,r=(i.outputCostPer1KTokens||0)/1e3*o;return{inputCost:n,outputCost:r,totalCost:n+r}}buildOpenAIRequest(e,o,s,a,i,n){const r={model:e,messages:o,temperature:s,max_tokens:a,stream:i};return n?.topP!==void 0&&(r.top_p=n.topP),n?.frequencyPenalty!==void 0&&(r.frequency_penalty=n.frequencyPenalty),n?.presencePenalty!==void 0&&(r.presence_penalty=n.presencePenalty),n?.stop!==void 0&&(r.stop=n.stop),r}async makeRequest(e,o,s,a=!1){const i=new AbortController,n=setTimeout(()=>i.abort(),this.timeout);try{const r=e.startsWith("http")?e:`${this.baseURL}${e}`,p={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};this.organization&&(p["OpenAI-Organization"]=this.organization);const c=await fetch(r,{method:"POST",headers:p,body:JSON.stringify(o),signal:i.signal});if(clearTimeout(n),!c.ok){const m=await c.text();try{const d=JSON.parse(m);throw new Error(`HTTP ${c.status}: ${d.error?.message||m}`)}catch{throw new Error(`HTTP ${c.status}: ${m}`)}}return a?await c.arrayBuffer():s?c.body:await c.json()}catch(r){throw clearTimeout(n),r.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):r}}async makeFormDataRequest(e,o,s){const a=new AbortController,i=setTimeout(()=>a.abort(),this.timeout);try{const n=e.startsWith("http")?e:`${this.baseURL}${e}`,r={Authorization:`Bearer ${this.apiKey}`};this.organization&&(r["OpenAI-Organization"]=this.organization);const p=await fetch(n,{method:"POST",headers:r,body:o,signal:a.signal});if(clearTimeout(i),!p.ok){const c=await p.text();try{const m=JSON.parse(c);throw new Error(`HTTP ${p.status}: ${m.error?.message||c}`)}catch{throw new Error(`HTTP ${p.status}: ${c}`)}}return s?p.body:await p.json()}catch(n){throw clearTimeout(i),n.name==="AbortError"?new Error(`Request timeout (${this.timeout}ms)`):n}}async makeStreamRequest(e,o,s){const a=await this.makeRequest(e,o,!0);if(!a)throw new Error("Failed to get streaming response");const i=a.getReader(),n=new TextDecoder("utf-8");let r="";try{for(;;){const{done:p,value:c}=await i.read();if(p){s("",!0);break}r+=n.decode(c,{stream:!0});const m=r.split(`
47
+ `);r=m.pop()||"";for(const d of m)if(d.startsWith("data: ")){const l=d.slice(6);if(l==="[DONE]"){s("",!0);return}try{const u=JSON.parse(l);u.choices?.[0]?.delta?.content&&s(u.choices[0].delta.content,!1)}catch{}}}}finally{i.releaseLock()}}extractContent(e){if(e.choices?.[0]?.message?.content)return e.choices[0].message.content;if(e.data?.[0]?.b64_json)return e.data[0].b64_json;if(e.data?.[0]?.url)return e.data[0].url;if(e.text)return e.text;throw new Error("Unable to parse response content")}async analyzeOHLCV(e,o,s,a){const i=o||"Based on these OHLCV data, predict the next period",n=s||1;if(!Number.isInteger(n)||n<=0)throw new Error(`Invalid count parameter: ${n}. Must be a positive integer.`);const r=50;if(n>r)throw new Error(`Count parameter too large: ${n}. Maximum allowed is ${r}. Please reduce the count or split your request.`);const p=n===1?"Return EXACTLY 1 OHLCV object for the next period.":`Return EXACTLY ${n} consecutive OHLCV objects for the next ${n} periods.`,c=`You are a professional financial data analysis AI. The user will give you an array of OHLCV (Open, High, Low, Close, Volume) data.
48
48
  Your task: ${i}
49
49
  CRITICAL RULES:
50
- 1. ${m}
50
+ 1. ${p}
51
51
  2. Return ONLY a JSON array of OHLCV objects, NO explanations, comments, or other text
52
52
  3. The OHLCV array format must match: [{open, high, low, close, volume}, ...]
53
53
  4. All numbers must be valid numbers
@@ -62,7 +62,7 @@ ${n===1?`Example of valid response for 1 period:
62
62
  {"open": 117.5, "high": 120.0, "low": 116.0, "close": 119.0, "volume": 1400000}
63
63
  ${n>2?`,
64
64
  ... ${n-2} more OHLCV objects following the same pattern`:""}
65
- ]`}`,p=JSON.stringify(e,null,2),d=`Here is the historical OHLCV data (${e.length} periods):
66
- ${p}
67
- Please process this data according to the system instructions. Remember to return EXACTLY ${n} OHLCV object(s) in a JSON array with no additional text.`,l=[{role:"system",content:c},{role:"user",content:d}];try{const h=n*50+100,y=Math.max(a?.maxTokens||1e3,h),E=await this.chatCompletion(l,{temperature:a?.temperature||.3,maxTokens:y,stream:!1,modelType:a?.modelType,topP:a?.topP,frequencyPenalty:a?.frequencyPenalty,presencePenalty:a?.presencePenalty,stop:a?.stop}),b=this.extractContent(E),g=this.parseOHLCVResponse(b);if(g.length!==n)throw new Error(`AI returned ${g.length} OHLCV objects, but expected ${n}.`);return g}catch(h){throw new Error(`OHLCV analysis failed: ${h.message}`)}}parseOHLCVResponse(e){try{const t=JSON.parse(e);if(!Array.isArray(t))throw new Error("Response is not in array format");return t.map((a,i)=>{if(typeof a!="object"||a===null)throw new Error(`Element ${i} is not a valid object`);const{open:n,high:r,low:m,close:c,volume:p}=a,d=["open","high","low","close","volume"];for(const l of d)if(typeof a[l]!="number"||isNaN(a[l]))throw new Error(`Element ${i} field ${l} is not a valid number`);if(r<m)throw new Error(`Element ${i}: high cannot be lower than low`);if(c<m||c>r)throw new Error(`Element ${i}: close must be between low and high`);return{open:Number(n),high:Number(r),low:Number(m),close:Number(c),volume:Number(p)}})}catch(t){const s=e.match(/\[[\s\S]*\]/);if(s)return this.parseOHLCVResponse(s[0]);throw new Error(`Unable to parse AI returned OHLCV data: ${t}
68
- Original content: ${e.substring(0,200)}...`)}}}function j(o,e){return new L({apiKey:o,modelType:e})}exports.ALIYUN_MODELS=x;exports.AliYunModelType=v;exports.AliyunAI=_;exports.DEEPSEEK_MODELS=k;exports.DeepSeekAI=C;exports.DeepSeekModelType=T;exports.OPENAI_MODELS=u;exports.OpenAI=L;exports.OpenAIModelType=f;exports.createAliyunAI=N;exports.createDeepSeekAI=P;exports.createOpenAI=j;exports.estimateCost=U;exports.getAllOpenAIModels=w;exports.getAudioModelsOpenAI=D;exports.getAvailableOpenAIModelTypes=S;exports.getChatModels=$;exports.getCompletionModels=R;exports.getCostEfficientModels=K;exports.getEmbeddingModels=A;exports.getHighContextModels=V;exports.getLatestModels=H;exports.getMultimodalModelsOpenAI=B;exports.getOpenAIModel=O;exports.getOpenAIModelByName=q;exports.getVisionModelsOpenAI=I;exports.suggestModel=Q;
65
+ ]`}`,m=JSON.stringify(e,null,2),d=`Here is the historical OHLCV data (${e.length} periods):
66
+ ${m}
67
+ Please process this data according to the system instructions. Remember to return EXACTLY ${n} OHLCV object(s) in a JSON array with no additional text.`,l=[{role:"system",content:c},{role:"user",content:d}];try{const u=n*50+100,x=Math.max(a?.maxTokens||1e3,u),T=await this.chatCompletion(l,{temperature:a?.temperature||.3,maxTokens:x,stream:!1,modelType:a?.modelType,topP:a?.topP,frequencyPenalty:a?.frequencyPenalty,presencePenalty:a?.presencePenalty,stop:a?.stop}),E=this.extractContent(T),f=this.parseOHLCVResponse(E);if(f.length!==n)throw new Error(`AI returned ${f.length} OHLCV objects, but expected ${n}.`);return f}catch(u){throw new Error(`OHLCV analysis failed: ${u.message}`)}}parseOHLCVResponse(e){try{const o=JSON.parse(e);if(!Array.isArray(o))throw new Error("Response is not in array format");return o.map((a,i)=>{if(typeof a!="object"||a===null)throw new Error(`Element ${i} is not a valid object`);const{open:n,high:r,low:p,close:c,volume:m}=a,d=["open","high","low","close","volume"];for(const l of d)if(typeof a[l]!="number"||isNaN(a[l]))throw new Error(`Element ${i} field ${l} is not a valid number`);if(r<p)throw new Error(`Element ${i}: high cannot be lower than low`);if(c<p||c>r)throw new Error(`Element ${i}: close must be between low and high`);return{open:Number(n),high:Number(r),low:Number(p),close:Number(c),volume:Number(m)}})}catch(o){const s=e.match(/\[[\s\S]*\]/);if(s)return this.parseOHLCVResponse(s[0]);throw new Error(`Unable to parse AI returned OHLCV data: ${o}
68
+ Original content: ${e.substring(0,200)}...`)}}}function te(t,e){return new L({apiKey:t,modelType:e})}exports.ALIYUN_MODELS=b;exports.AliYunModelType=k;exports.AliyunAI=_;exports.DEEPSEEK_MODELS=y;exports.DeepSeekAI=C;exports.DeepSeekModelType=v;exports.OPENAI_MODELS=h;exports.OpenAI=L;exports.OpenAIModelType=g;exports.createAliyunAI=A;exports.createDeepSeekAI=H;exports.createOpenAI=te;exports.estimateCost=Z;exports.getAllDeepSeekModels=R;exports.getAllModels=P;exports.getAllOpenAIModels=w;exports.getAudioModelsOpenAI=F;exports.getAvailableAliYunModelTypes=q;exports.getAvailableDeepSeekModelTypes=I;exports.getAvailableOpenAIModelTypes=U;exports.getChatModels=M;exports.getCompletionModels=Q;exports.getCostEfficientModels=z;exports.getDeepSeekModel=$;exports.getDeepSeekModelByName=D;exports.getEmbeddingModels=j;exports.getHighContextModels=J;exports.getLatestModels=X;exports.getModel=N;exports.getModelByName=O;exports.getMultimodalModelsOpenAI=G;exports.getOpenAIModel=K;exports.getOpenAIModelByName=V;exports.getVisionModelsOpenAI=W;exports.stringToAliYunModelType=S;exports.stringToDeepSeekModelType=B;exports.stringToOpenAIModelType=ee;exports.suggestModel=Y;