import {validateContribution,mergeContributions} from './contributions.mjs'; export {validateContribution,mergeContributions,normalizeContribution,contributionIdentity} from './contributions.mjs'; export const profiles = { chat: {name:'Chat léger', subtitle:'Quelques questions, chaque jour', class:'small', effort:'low', mode:'requests', requests:8, hours:1, cadence:12, parallel:1, people:1, context:500, output:300, cache:10, days:365, mix:'fr', customLow:50, customCentral:55, customHigh:60, water:'site'}, dev: {name:'Développeur', subtitle:'Un assistant dans le quotidien', class:'medium', effort:'medium', mode:'requests', requests:50, hours:2, cadence:20, parallel:1, people:1, context:8000, output:700, cache:60, days:220, mix:'fr', customLow:50, customCentral:55, customHigh:60, water:'site'}, agent: {name:'Agents autonomes', subtitle:'Plusieurs heures, effort élevé', class:'frontier', effort:'high', mode:'hours', requests:60, hours:4, cadence:20, parallel:2, people:1, context:20000, output:1200, cache:75, days:220, mix:'us', customLow:350, customCentral:400, customHigh:500, water:'site'}, team: {name:'Équipe de 10', subtitle:'Dix développeurs accompagnés', class:'medium', effort:'medium', mode:'requests', requests:50, hours:2, cadence:20, parallel:1, people:10, context:8000, output:700, cache:60, days:220, mix:'fr', customLow:50, customCentral:55, customHigh:60, water:'site'} }; export const zero = () => [0,0,0]; export const add = (a,b) => a.map((x,i)=>x+b[i]); export const scale = (a,n) => a.map(x=>x*n); export function ordered(a) {return Array.isArray(a) && a.length===3 && a.every(x=>Number.isFinite(x)&&x>=0) && a[0]<=a[1] && a[1]<=a[2];} export function tokenEnergy(t, cls, factors) { const f = factors.token_factors.classes[cls]; if (!f) throw new Error('Classe inconnue'); const write=t.cache_write===undefined?0:t.cache_write; for(const value of [t.input,write,t.cache,t.output])if(!Number.isSafeInteger(value)||value<0)throw new Error('Compte de tokens invalide ou inconnu.'); // Cache creation is processed as new input, not as a discounted cache read. // This is a documented accounting hypothesis, not measured write overhead. return [0,1,2].map(i => ((t.input+write)*f.input[i]+t.cache*f.cache[i]+t.output*f.output[i])/1000); } export function impact(wh,mix,water,factors) { return {wh, carbon:wh.map((x,i)=>x*mix[i]/1000), water:wh.map((x,i)=>x*factors.water[water][i])}; } export function equivalences(result,factors) { const e=factors.equivalences; return { car: result.carbon.map((x,i)=>x/e.car_g_per_km.values[2-i]), oven: result.wh.map((x,i)=>x/e.oven_W.values[2-i]*60), budget:result.carbon.map(x=>x/e.annual_budget_g.value*100) }; } export function simulate(p,factors) { for (const k of ['requests','hours','cadence','parallel','people','context','output','cache','days','customLow','customCentral','customHigh']) { if (!Number.isFinite(p[k]) || p[k]<0) throw new Error(`Valeur invalide : ${k}`); } if(p.cache>100||p.days>366||p.parallel<1||p.people<1) throw new Error('Cache 0–100 %, jours 0–366, effectif et agents ≥ 1.'); const mix=p.mix==='custom'?[p.customLow,p.customCentral,p.customHigh]:factors.mixes[p.mix]?.values; if(!ordered(mix)) throw new Error('Mix personnalisé : bas ≤ central ≤ haut requis.'); const energyScale=p.energyScale??1; if(!Number.isFinite(energyScale)||energyScale<=0||energyScale>10)throw new Error('Facteur énergétique personnalisé : valeur > 0 et ≤ 10 requise.'); const counts=[]; const annual=[]; const daily=[0,1,2].map(i=>{ const q={...p}; for(const [key,values] of Object.entries(p.scenarioRanges||{})) { if(!Array.isArray(values)||values.length!==3||!['requests','hours','cadence','context','output','cache','class','effort'].includes(key))throw new Error('Correspondance de scénario invalide'); q[key]=values[i]; } for(const key of ['requests','hours','cadence','context','output','cache'])if(!Number.isFinite(q[key])||q[key]<0)throw new Error('Valeur de scénario invalide'); if(q.cache>100)throw new Error('Cache de scénario invalide'); const f=factors.token_factors.classes[q.class],r=factors.reasoning[q.effort]; if(!f||!r)throw new Error('Classe ou effort inconnu'); const n=(q.mode==='hours'?q.hours*q.cadence:q.requests)*q.parallel*q.people, ratio=q.cache/100; counts.push(n); // Reasoning affects only simulated generated tokens, never real logged output. const wh=n*(q.context*(1-ratio)*f.input[i]+q.context*ratio*f.cache[i]+q.output*r[i]*f.output[i])/1000*energyScale; annual.push(wh*q.days);return wh; }); if(!ordered(daily))throw new Error('Les scénarios de consommation doivent rester ordonnés.'); return {daily:impact(daily,mix,p.water,factors), annual:impact(annual,mix,p.water,factors), requests:counts[1],requestRange:counts}; } export function reductions(p,factors) { const base=simulate(p,factors).annual.wh; const variants=[ ['Réduire le raisonnement', {...p,effort:p.effort==='high'?'medium':'low'}], ['Choisir une classe plus petite', {...p,class:p.class==='frontier'?'medium':'small'}], ['Mieux réutiliser le cache', {...p,cache:Math.min(95,p.cache+25)}], ['Réduire les agents parallèles', {...p,parallel:Math.max(1,Math.floor(p.parallel/2))}], ['Supprimer le contexte inutile', {...p,context:Math.floor(p.context/2)}] ]; return variants.map(([label,params])=>{ if(p.scenarioRanges){params.scenarioRanges={...p.scenarioRanges};for(const key of Object.keys(params.scenarioRanges))if(params[key]!==p[key])delete params.scenarioRanges[key];} const after=simulate(params,factors).annual.wh; return {label, params, saving:base.map((x,i)=>x-after[i]), percent:base.map((x,i)=>x?(x-after[i])/x*100:0)}; }).filter(x=>x.saving[1]>0 && x.saving.every(v=>v>=0)).slice(0,3); } export function aggregate(rows, contributions, factors) { const keys=['input','cache_write','cache','output']; const byPhase={},byType={input:zero(),cache_write:zero(),cache:zero(),output:zero(),external:zero()}; const tokenCounts={input:0,cache_write:0,cache:0,output:0,reasoning:0},externalTokenCounts={input:0,cache_write:0,cache:0,output:0}; let total=zero(),missing=0,pending=0,externalRequests=0,externalAggregates=0,legacyWriteUnknown=0; const timeline=[],seen=new Set(); function addTypes(t,cls,counts){for(const k of keys){const value=t[k]??0;byType[k]=add(byType[k],tokenEnergy({input:0,cache_write:0,cache:0,output:0,[k]:value},cls,factors));counts[k]+=value;}} for(const row of rows){ const key=`${row.conversation_id}/${row.message_id}`;if(seen.has(key))continue;seen.add(key); const legacy=row.cache_write_tokens===undefined; const t={input:row.input_new_tokens,cache_write:legacy?0:row.cache_write_tokens,cache:row.cache_read_tokens,output:row.output_tokens}; if(Object.values(t).some(n=>!Number.isSafeInteger(n)||n<0)){missing++;continue;} if(legacy)legacyWriteUnknown++; const wh=tokenEnergy(t,'frontier',factors);total=add(total,wh);byPhase[row.phase]=add(byPhase[row.phase]||zero(),wh);addTypes(t,'frontier',tokenCounts); tokenCounts.reasoning+=row.reasoning_tokens??0;timeline.push({timestamp:row.timestamp,wh,kind:'session'}); } for(const c of mergeContributions(contributions,[])){ if(c.status==='pending'){pending++;continue;} const wh=c.mode==='wh'?c.wh:tokenEnergy(c.tokens,c.class,factors); total=add(total,wh);byPhase[c.phase]=add(byPhase[c.phase]||zero(),wh); if(c.mode==='wh')byType.external=add(byType.external,wh);else {addTypes(c.tokens,c.class,externalTokenCounts);if(c.tokens.cache_write===undefined)legacyWriteUnknown++;} externalRequests+=c.requests??0;externalAggregates++; timeline.push({timestamp:c.cutoff?new Date(c.cutoff).toISOString():`${c.date}T00:00:00Z`,wh,kind:'external',contribution_id:c.id}); } let cumulative=zero();timeline.sort((a,b)=>a.timestamp.localeCompare(b.timestamp)); for(const point of timeline){cumulative=add(cumulative,point.wh);point.cumulative=cumulative;} const combinedTokenCounts=Object.fromEntries(keys.map(k=>[k,tokenCounts[k]+externalTokenCounts[k]])); return {total,byPhase,byType,tokenCounts,externalTokenCounts,combinedTokenCounts,timeline,missing,pending,legacyWriteUnknown,externalRequests,externalAggregates,messageCount:seen.size}; }