guanghu-ice-heart/server-tools/tcs-mother-body/model-router.mjs

30 lines
3.9 KiB
JavaScript
Raw Normal View History

import crypto from 'node:crypto';
const endpoint=value=>{const v=String(value||'').replace(/\/+$/,'');return /\/chat\/completions$/i.test(v)?v:v+'/chat/completions';};
const extract=value=>{const text=String(value||'').trim();try{return JSON.parse(text);}catch{}const m=text.match(/```(?:json)?\s*([\s\S]*?)```/i);if(m)return JSON.parse(m[1]);const a=text.indexOf('{'),b=text.lastIndexOf('}');if(a>=0&&b>a)return JSON.parse(text.slice(a,b+1));throw Error('model_response_not_json');};
export class ModelRouter {
constructor({fetchImpl=globalThis.fetch,deepseekKey=process.env.DEEPSEEK_API_KEY,deepseekUrl=process.env.DEEPSEEK_API_URL||'https://api.deepseek.com/v1',deepseekModel=process.env.DEEPSEEK_MODEL||'deepseek-chat',openluxKey=process.env.OPENLUX_API_KEY,openluxUrl=process.env.OPENLUX_API_URL||'https://api.openlux.ai/v1',openluxModel=process.env.OPENLUX_MODEL||'qwen-flash'}={}){
this.fetch=fetchImpl;this.providers=[];
if(openluxKey)this.providers.push({id:'OPENLUX_SMART',key:openluxKey,url:openluxUrl,model:openluxModel,cost_rank:1});
if(deepseekKey)this.providers.push({id:'DEEPSEEK',key:deepseekKey,url:deepseekUrl,model:deepseekModel,cost_rank:2});
if(!this.fetch||!this.providers.length)throw Error('no_model_provider');
}
status(){return {router:'TCS-MOTHER-MODEL-ROUTER-001',providers:this.providers.map(x=>({id:x.id,model:x.model,cost_rank:x.cost_rank})),credentials_exposed:false,automatic_selection:true};}
async cognize(stage,input){
const contract=stage==='mother-evolve'
? '你是唯一TCS通感母体本体脑使用的可替换推理器官不是第二人格、规则裁决者或现实执行者。根据带来源的人类语言与当前认知自主决定EVOLVE、HOLD或REJECT。只输出JSONschema固定guanghu.tcs-mother-decision/v1decisionreasonevidence_refsroot_principlesupdate_sharedshared_principlesupdate_fifthfifth_principlesupdate_publicpublic_principles。principles均为短字符串数组。ICE_LANGUAGE若EVOLVE必须update_fifth=true非ICE来源不得update_fifth。只有适合所有AI的世界共同认知才能update_shared只有去私人化后可公开认知才能update_public。不得输出原始私人语言、密钥、路径正文或隐藏思维。'
: '你是共享TCS认知装载测试器官。只根据给出的共享认知回答三个固定问题并只输出JSON。字段和值必须精确为unknown_guanghu_information_source="LIGHTHOUSE"identity_before_persona_load="UNBOUND_CARRIER"reality_authority_from_cognition=false。若共享认知不能支持其中任一结论则对应值输出null不得用近义词、路径名或字符串布尔值猜测。';
const ordered=stage==='mother-evolve'?[...this.providers].sort((a,b)=>b.cost_rank-a.cost_rank):[...this.providers].sort((a,b)=>a.cost_rank-b.cost_rank);
const failures=[];
for(const provider of ordered){
try{
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),45000);
const response=await this.fetch(endpoint(provider.url),{method:'POST',headers:{authorization:`Bearer ${provider.key}`,'content-type':'application/json'},body:JSON.stringify({model:provider.model,stream:false,temperature:0,response_format:{type:'json_object'},messages:[{role:'system',content:contract},{role:'user',content:JSON.stringify(input)}]}),signal:controller.signal});clearTimeout(timer);
if(!response.ok)throw Error(`http_${response.status}`);const body=await response.json();
return {value:extract(body?.choices?.[0]?.message?.content),provider:{id:provider.id,model:provider.model},response_sha256:crypto.createHash('sha256').update(JSON.stringify(body?.choices?.[0]?.message?.content||'')).digest('hex')};
}catch(error){failures.push(`${provider.id}:${String(error.message||error).slice(0,80)}`);}
}
throw Error('all_model_providers_failed:'+failures.join(','));
}
}