@bivelio/savings-layer 0.4.36 → 0.5.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/dist/adapters/ai-sdk.js +87 -78
- package/dist/adapters/anthropic-sdk.d.ts +13 -0
- package/dist/adapters/anthropic-sdk.js +115 -102
- package/dist/adapters/langchain.js +67 -58
- package/dist/adapters/mastra.js +80 -71
- package/dist/gateway/bin.js +749 -754
- package/dist/index.d.ts +86 -1253
- package/dist/index.js +1441 -1447
- package/package.json +1 -1
|
@@ -1,111 +1,124 @@
|
|
|
1
|
-
import {createSavingsLayer,LicenseError
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
"
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
1
|
+
import {createSavingsLayer,LicenseError}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var Se={stop:"stop",end_turn:"stop",STOP:"stop",length:"length",max_tokens:"length",MAX_TOKENS:"length",tool_calls:"tool_calls",tool_use:"tool_calls",content_filter:"content_filter",other:"other"},Ae={
|
|
2
|
+
stop_sequence:"stop",eos:"stop",eos_token:"stop",model_context_window_exceeded:"length",function_call:"tool_calls",refusal:"content_filter",SAFETY:"content_filter",RECITATION:"content_filter",BLOCKLIST:"\
|
|
3
|
+
content_filter",PROHIBITED_CONTENT:"content_filter",SPII:"content_filter",IMAGE_SAFETY:"content_filter",IMAGE_PROHIBITED_CONTENT:"content_filter",IMAGE_RECITATION:"content_filter"},ke=/^content_filter\s*:\s*(.*?)\s*$/;
|
|
4
|
+
function B(t,e){let n=typeof e=="string"&&e!==""?e:void 0;if(typeof t!="string"||t==="")return n!==void 0?{finishReasonDetail:n}:{};let r=Se[t];if(r!==void 0)return {finishReason:r,...n!==void 0?{finishReasonDetail:n}:
|
|
5
|
+
{}};let o=ke.exec(t);if(o!==null){let s=n??(o[1]!==void 0&&o[1]!==""?o[1]:void 0);return {finishReason:"content_filter",...s!==void 0?{finishReasonDetail:s}:{}}}return {finishReason:Ae[t]??"other",finishReasonDetail:n??
|
|
6
|
+
t}}var O=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:0;function V(t){if(!Array.isArray(t))return null;let e={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,iteraciones:0};for(let n of t){if(n===
|
|
7
|
+
null||typeof n!="object")continue;let r=n;if(r.type!=="compaction")continue;e.iteraciones++,e.input+=O(r.input_tokens),e.output+=O(r.output_tokens),e.cacheRead+=O(r.cache_read_input_tokens);let o=r.cache_creation,
|
|
8
|
+
a=O(o?.ephemeral_5m_input_tokens),s=O(o?.ephemeral_1h_input_tokens),i=typeof r.cache_creation_input_tokens=="number"?O(r.cache_creation_input_tokens):a+s;e.cacheWrite+=i,e.cacheWrite1h+=Math.min(s,i);}
|
|
9
|
+
return e.iteraciones>0?e:null}function H(t,e,n){let r=t??{},o=V(r.iterations),a=G(r.cache_read_input_tokens,o?.cacheRead),s=G(r.cache_creation_input_tokens,o?.cacheWrite),i=r.cache_creation?.ephemeral_1h_input_tokens,u=typeof i=="\
|
|
10
|
+
number"||(o?.cacheWrite1h??0)>0?Math.min(Math.max(0,(typeof i=="number"?i:0)+(o?.cacheWrite1h??0)),s??0):void 0,d=(r.input_tokens??0)+(o?.input??0)+(s??0)+(a??0),f=(e??0)+(o?.output??0),h=typeof r.input_tokens!=
|
|
11
|
+
"number",m=typeof e!="number";return {usage:{inputTokens:d,outputTokens:f,...a!=null?{cachedInputTokens:a}:{},...s!=null?{cacheWriteInputTokens:s}:{},...u!==void 0?{cacheWrite1hInputTokens:u}:{},...n||
|
|
12
|
+
m||o?{}:{reasoningTokens:0},...h||m?{complete:false}:{}},entradaAusente:h,salidaAusente:m}}function G(t,e){return e?(t??0)+e:t}function K(t){let e=t?.service_tier;return typeof e=="string"&&e!==""?e:void 0}
|
|
13
|
+
function z(t,e){let n=Object.fromEntries(Object.entries(e??{}).filter(([,o])=>o!=null)),r=t?.cache_creation||e?.cache_creation?{...t?.cache_creation??{},...e?.cache_creation??{}}:void 0;return {...t??{},
|
|
14
|
+
...n,...r?{cache_creation:r}:{}}}function Y(t){return t==="thinking"||t==="redacted_thinking"}function Z(t,e){return B(t,Ce(t,e))}var De=new Set([null,"cyber","general_harms"]);function X(t){if(t.stopReason!==
|
|
15
|
+
"refusal")return false;let e=t.stopDetails;if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=e;if(n.type!=="refusal"||!("category"in n))return false;let r=n.category;return !(r!==null&&typeof r!=
|
|
16
|
+
"string"||!De.has(r)||t.bloques!==0||t.outputTokens!==0||Array.isArray(t.iterations)&&t.iterations.length>1)}function Ce(t,e){if(t!=="refusal"||e===null||typeof e!="object"||Array.isArray(e))return;let n=e.
|
|
17
|
+
category;return typeof n=="string"&&n!==""?n:void 0}var Pe=["claude-opus-5-5","claude-sonnet-5-5","claude-fable-5-1","claude-mythos-5-1"],Te=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5"];function Oe(t){return /claude-[a-z]+-\d[a-z0-9-]*/.exec(t.toLowerCase())?.[0]}function Q(t,e){let n=Oe(t);return n===void 0?false:e.some(r=>n===r||n.startsWith(`${r}-`))}function ee(t){return Q(t,Pe)}function te(t){
|
|
18
|
+
return Q(t,Te)}var Me={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function Ee(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.protocol!==
|
|
19
|
+
"https:"||e.port!==""?null:Me[e.hostname.toLowerCase()]??null}catch{return null}}function ne(t){return Ee(t)!==null?"oficial":"no-oficial"}var re=Symbol.for("@bivelio/savings-layer:provider-origin");var I=class{decoder;resto="";crPendiente=false;alPrincipio=true;datos="";evento="";ultimoId;push(e){let n=typeof e=="string"?e:(this.decoder??=new TextDecoder("utf-8")).decode(e,{stream:true});return this.procesar(
|
|
15
20
|
n)}end(){let e=[];if(this.decoder){let n=this.decoder.decode();n!==""&&e.push(...this.procesar(n));}return this.resto!==""&&(this.linea(this.resto,e),this.resto=""),this.despachar(e),this.crPendiente=false,
|
|
16
21
|
e}procesar(e){let n=[];if(e==="")return n;let r=e;if(this.alPrincipio&&(this.alPrincipio=false,r.charCodeAt(0)===65279&&(r=r.slice(1)),r===""))return n;let o=0;this.crPendiente&&(this.crPendiente=false,r.charCodeAt(
|
|
17
|
-
0)===10&&(o=1));let
|
|
18
|
-
crPendiente=true),o++,
|
|
19
|
-
|
|
20
|
-
`;break;case "event":this.evento=
|
|
21
|
-
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var
|
|
22
|
-
nothing more was sent.",
|
|
23
|
-
completada:false,...r!==void 0?{origen:r}:{}}}function
|
|
24
|
-
e.model&&
|
|
25
|
-
|
|
26
|
-
let i=await
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
let
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
22
|
+
0)===10&&(o=1));let a=o;for(;o<r.length;){let s=r.charCodeAt(o);if(s!==10&&s!==13){o++;continue}this.linea(this.resto+r.slice(a,o),n),this.resto="",s===13&&(o+1<r.length?r.charCodeAt(o+1)===10&&o++:this.
|
|
23
|
+
crPendiente=true),o++,a=o;}return this.resto+=r.slice(a),n}linea(e,n){if(e===""){this.despachar(n);return}if(e.charCodeAt(0)===58)return;let r=e.indexOf(":"),o,a;switch(r===-1?(o=e,a=""):(o=e.slice(0,r),
|
|
24
|
+
a=e.slice(r+1),a.charCodeAt(0)===32&&(a=a.slice(1))),o){case "data":this.datos+=a+`
|
|
25
|
+
`;break;case "event":this.evento=a;break;case "id":a.includes("\0")||(this.ultimoId=a);break;}}despachar(e){if(this.datos===""){this.evento="";return}e.push({event:this.evento===""?"message":
|
|
26
|
+
this.evento,data:this.datos.slice(0,-1),...this.ultimoId!==void 0?{id:this.ultimoId}:{}}),this.datos="",this.evento="";}};var oe=new Set;function se(t,e,n){t===true||oe.has(e)||(oe.add(e),console.warn(n));}var je="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",Ie="[bvsala] internal: the layer asked for a second model call within one framework call;\
|
|
27
|
+
nothing more was sent.",Ue="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function F(t,e,n,r){return {renderizado:t,generar:e,...n?{transmitir:n}:{},invocada:false,
|
|
28
|
+
completada:false,...r!==void 0?{origen:r}:{}}}function qe(t,e){if(t===e)return true;try{return ie(t)===ie(e)}catch{return false}}function ae(t,e){let n=t??[],r=e??[];return n.length===r.length&&n.every((o,a)=>qe(o,r[a]))}function Ne(t,e){return t.model===
|
|
29
|
+
e.model&&ae(t.messages,e.messages)&&ae(t.tools,e.tools)}function ce(t,e){let n=o=>{let a=e.getStore();if(!a)throw new Error(Ue);if(a.invocada)throw new Error(Ie);if(!Ne(o,a.renderizado))throw new Error(
|
|
30
|
+
je);return a.invocada=true,a},r={id:`bivelio-adapter:${t}`,async generate(o,a){return n(o).generar(a?.signal)},async*generateStream(o,a){let s=n(o);if(s.transmitir){yield*s.transmitir(a?.signal);return}
|
|
31
|
+
let i=await s.generar(a?.signal);i.text!==""&&(yield {type:"text",delta:i.text}),yield {type:"done",response:i};}};return Object.defineProperty(r,re,{value:()=>e.getStore()?.origen}),r}function le(){return new AsyncLocalStorage}
|
|
32
|
+
function ie(t){return JSON.stringify($(t))}function $(t){if(Array.isArray(t))return t.map($);if(t&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=$(t[n]);return e}return t}var Fe=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
|
|
33
|
+
ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function ue(t,e){return e instanceof LicenseError||t.errorDelMarco&&t.errorDelMarco.error===e?false:t.invocada&&
|
|
34
|
+
t.completada}var de="[bvsala] the model answered, but the savings layer failed while accounting for it; the answer is returned unchanged, without a savings report and without a usage record.";function fe(t,e){
|
|
35
|
+
let n=le(),r={};for(let s of Fe)e[s]!==void 0&&(r[s]=e[s]);let o=createSavingsLayer({...r,provider:ce(t,n)}),a=(s,i)=>se(e.silenceWarnings,`${t}:${s}`,i);return {ejecutar(s,i){return n.run(i,()=>o.generate(s))},async generar(s,i){
|
|
36
|
+
try{let u=await n.run(i,()=>o.generate(s));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(ue(i,u))return a("sin-informe",de),{tipo:"sin-informe"};throw u}},async transmitir(s,i,u){
|
|
37
|
+
let f=n.run(i,()=>o.generateStream(s,u?{signal:u}:{})).result;i.resultado=f,f.catch(()=>{});let h;try{h=await Promise.race([i.abierta.then(()=>"abierta"),f.then(()=>"resuelta")]);}catch(_){if(ue(i,_))return a(
|
|
38
|
+
"sin-informe",de),{tipo:"sin-informe"};throw _}if(h==="abierta")return {tipo:"abierto"};let m=await f;return i.invocada?{tipo:"entero",result:m}:{tipo:"atajo",result:m}},informe(s){let i=JSON.parse(JSON.
|
|
39
|
+
stringify(s));if(e.onReport)try{e.onReport(i);}catch{a("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return i},avisar:a,close(){o.close();}}}function pe(){
|
|
40
|
+
let t;return {abierta:new Promise(n=>{t=n;}),abrir:t}}var L=class{pendientes=[];esperando;terminada=false;fallo;push(e){if(this.terminada||this.fallo)return;let n=this.esperando;if(n){this.esperando=void 0,n.resolver({value:e,done:false});return}this.pendientes.
|
|
35
41
|
push(e);}end(){if(this.terminada||this.fallo)return;this.terminada=true;let e=this.esperando;e&&this.pendientes.length===0&&(this.esperando=void 0,e.resolver({value:void 0,done:true}));}fail(e){if(this.terminada||
|
|
36
42
|
this.fallo)return;this.fallo={error:e};let n=this.esperando;n&&this.pendientes.length===0&&(this.esperando=void 0,n.rechazar(e));}get cerrada(){return this.terminada||this.fallo!==void 0}[Symbol.asyncIterator](){
|
|
37
43
|
return {next:()=>this.pendientes.length>0?Promise.resolve({value:this.pendientes.shift(),done:false}):this.fallo?Promise.reject(this.fallo.error):this.terminada?Promise.resolve({value:void 0,done:true}):new Promise(
|
|
38
|
-
(e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};var
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
44
|
+
(e,n)=>{this.esperando={resolver:e,rechazar:n};}),return:()=>(this.terminada=true,this.pendientes.length=0,Promise.resolve({value:void 0,done:true}))}}};var Je=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
|
|
45
|
+
4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
|
|
46
|
+
1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
|
|
47
|
+
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),We=new TextEncoder;function R(t,e){return t>>>e|t<<32-e}function ge(t){let e=We.encode(t),n=e.length*
|
|
48
|
+
8,r=(e.length+8>>6)+1,o=new Uint8Array(r*64);o.set(e),o[e.length]=128;let a=new DataView(o.buffer);a.setUint32(o.length-8,Math.floor(n/4294967296)),a.setUint32(o.length-4,n>>>0);let s=new Uint32Array(
|
|
49
|
+
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let d=0;d<o.length;d+=64){for(let p=0;p<16;p++)i[p]=a.getUint32(d+p*4);for(let p=16;p<
|
|
50
|
+
64;p++){let D=i[p-15],S=i[p-2],A=R(D,7)^R(D,18)^D>>>3,C=R(S,17)^R(S,19)^S>>>10;i[p]=i[p-16]+A+i[p-7]+C|0;}let f=s[0],h=s[1],m=s[2],_=s[3],l=s[4],v=s[5],b=s[6],w=s[7];for(let p=0;p<64;p++){let D=R(l,6)^
|
|
51
|
+
R(l,11)^R(l,25),S=l&v^~l&b,A=w+D+S+Je[p]+i[p]|0,C=R(f,2)^R(f,13)^R(f,22),P=f&h^f&m^h&m,k=C+P|0;w=b,b=v,v=l,l=_+A|0,_=m,m=h,h=f,f=A+k|0;}s[0]=s[0]+f|0,s[1]=s[1]+h|0,s[2]=s[2]+m|0,s[3]=s[3]+_|0,s[4]=s[4]+
|
|
52
|
+
l|0,s[5]=s[5]+v|0,s[6]=s[6]+b|0,s[7]=s[7]+w|0;}let u="";for(let d=0;d<8;d++)u+=(s[d]>>>0).toString(16).padStart(8,"0");return u}var Be={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};function Ve(t,e,n={}){let r=o=>t?.[o]!==
|
|
53
|
+
false&&e?.[o]!==false;return {...Be,exactCache:r("exactCache")&&n.sinReutilizar!==true,singleflight:r("singleflight")&&n.sinReutilizar!==true,deterministicResolvers:r("deterministicResolvers")&&n.sinResolvers!==
|
|
54
|
+
true}}function Ge(t,e){let n=t.readOnlyTools;if(typeof n=="function")try{return n(e)===!0}catch{return false}return Array.isArray(n)?n.includes(e):false}function me(t,e){let n=e.delProveedor!==true&&Ge(t,e.nombre);
|
|
55
|
+
return {id:e.nombre,intents:[],risk:n?"read":"write",...e.parametros!==void 0&&e.parametros!==null&&typeof e.parametros=="object"?{parameters:e.parametros}:{},...typeof e.descripcion=="string"?{description:e.
|
|
56
|
+
descripcion}:{}}}function j(t,e,n){if(t===null)return null;switch(typeof t){case "string":case "boolean":return t;case "number":return Number.isFinite(t)?t:String(t);case "bigint":return `${t.toString()}n`;case "\
|
|
57
|
+
undefined":case "function":case "symbol":return}let r=t;if(r instanceof Uint8Array)return e.push(r),{$bytes:e.length-1};if(r instanceof ArrayBuffer)return e.push(new Uint8Array(r)),{$bytes:e.length-1};if(ArrayBuffer.
|
|
58
|
+
isView(r))return e.push(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),{$bytes:e.length-1};if(r instanceof URL)return {$url:r.href};if(r instanceof Date)return {$date:Number.isNaN(r.getTime())?"inv\
|
|
59
|
+
alid":r.toISOString()};if(n.has(r))return "$cycle";n.add(r);try{if(Array.isArray(r))return r.map(a=>{let s=j(a,e,n);return s===void 0?null:s});if(r instanceof Map)return {$map:[...r.entries()].map(a=>j(
|
|
60
|
+
a,e,n))};if(r instanceof Set)return {$set:[...r.values()].map(a=>j(a,e,n))};let o={};for(let a of Object.keys(r).sort()){let s=j(r[a],e,n);s!==void 0&&(o[a]=s);}return o}finally{n.delete(r);}}async function he(t){
|
|
61
|
+
let e=globalThis.crypto?.subtle;if(e){let r=new Uint8Array(await e.digest("SHA-256",t));return Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")}let n="";for(let r=0;r<t.length;r+=32768)n+=String.
|
|
62
|
+
fromCharCode(...t.subarray(r,r+32768));return ge(n)}async function He(t){try{let e=[],n=JSON.stringify(j(t,e,new WeakSet))??"null",r=await Promise.all(e.map(he)),o=new TextEncoder().encode(`${n}|${r.join(
|
|
63
|
+
",")}`);return await he(o)}catch{return null}}async function ye(t,e){let n=await He(e.proyeccion),r=`${e.context?.authorizationScope??"default"}|bvsala-adapter:${n??"none"}`;return {model:e.model,messages:e.
|
|
64
|
+
messages,...e.tools.length>0?{tools:e.tools}:{},...typeof e.temperature=="number"?{temperature:e.temperature}:{},...typeof e.seed=="number"?{seed:e.seed}:{},context:{...e.context??{},authorizationScope:r},
|
|
65
|
+
savings:Ve(t.savings,e.savings,{...e.restricciones,...n===null?{sinReutilizar:true}:{}})}}function ve(t,e){if(!(!t&&!e))return {...t??{},...e??{}}}function be(t){if(!t||typeof t!="object")return {};let e=t,
|
|
66
|
+
n={};return e.context&&typeof e.context=="object"&&(n.context=e.context),e.savings&&typeof e.savings=="object"&&(n.savings=e.savings),n}var J="[bvsala] could not read the request body; nothing was sent.";function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ye(t){if((t.method??"GET").toUpperCase()!=="POST")return false;
|
|
67
|
+
try{return new URL(t.url).pathname.replace(/\/+$/,"").endsWith("/v1/messages")}catch{return false}}function M(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.filter(g):[]}function U(t){
|
|
54
68
|
return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
55
|
-
`)}function
|
|
56
|
-
m",content:typeof n=="string"?n:
|
|
57
|
-
i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:
|
|
58
|
-
l_result"&&e.push({role:"tool",content:typeof
|
|
59
|
-
ool_result"))&&e.push({role:"user",content:
|
|
60
|
-
let n={};for(let[r,o]of Object.entries(t))r==="stream"||r==="metadata"||r==="messages"||r==="system"||(n[r]=o);return n.system=typeof t.system=="string"?"$text":
|
|
61
|
-
t.messages)?t.messages:[]).filter(
|
|
62
|
-
|
|
63
|
-
y"||r.type==="tool")&&
|
|
64
|
-
forwards your request unchanged, so the API will reject it: use \`tool_choice: {type: "auto"}\` with \`strict: true\` tools, or \`output_config.format\` for a fixed JSON shape. See https://platform.claude
|
|
65
|
-
|
|
66
|
-
push({clave:`muestreo:${e}`,mensaje:`[bvsala] Model "${e}" rejects a non-default ${o.map(
|
|
67
|
-
drop the parameter for this model. See https://platform.claude.com/docs/en/models/sonnet-5-5/overview`}),n}var
|
|
68
|
-
this.bloquesVistos+=1,
|
|
69
|
-
this.id=typeof e.id=="string"?e.id:void 0;for(let n of
|
|
70
|
-
id=="string"?{id:n.id}:{},name:String(n.name??""),arguments:
|
|
71
|
-
e.usage:void 0,this.usoDelta=this.usoInicio,this.vioDelta=true,this.vioStop=true;}evento(e){let n;try{n=JSON.parse(e.data);}catch{return}if(!
|
|
72
|
-
message_start":{let o=
|
|
73
|
-
this.bloque(o),o.type==="tool_use"&&typeof n.index=="number"&&this.herramientas.set(n.index,{...typeof o.id=="string"?{id:o.id}:{},name:String(o.name??""),json:""});return}case "content_block_delta":{let o=
|
|
69
|
+
`)}function Re(t){if(typeof t=="string")return t;try{return JSON.stringify(t??{})}catch{return "{}"}}function Ze(t){let e=[],n=t.system;(typeof n=="string"?n!=="":Array.isArray(n))&&e.push({role:"syste\
|
|
70
|
+
m",content:typeof n=="string"?n:U(M(n))});for(let r of Array.isArray(t.messages)?t.messages:[]){if(!g(r))continue;let o=M(r.content);if(r.role==="assistant"){let s=o.filter(i=>i.type==="tool_use").map(
|
|
71
|
+
i=>({...typeof i.id=="string"?{id:i.id}:{},name:String(i.name??""),arguments:Re(i.input)}));e.push({role:"assistant",content:U(o),...s.length>0?{toolCalls:s}:{}});continue}for(let s of o)s.type==="too\
|
|
72
|
+
l_result"&&e.push({role:"tool",content:typeof s.content=="string"?s.content:U(M(s.content)),...typeof s.tool_use_id=="string"?{toolCallId:s.tool_use_id}:{}});let a=U(o);(a!==""||!o.some(s=>s.type==="t\
|
|
73
|
+
ool_result"))&&e.push({role:"user",content:a});}return e}function xe(t){let e={};for(let[n,r]of Object.entries(t))n==="id"||n==="tool_use_id"||n==="text"&&t.type==="text"||(e[n]=r);return e}function Xe(t,e){
|
|
74
|
+
let n={};for(let[r,o]of Object.entries(t))r==="stream"||r==="metadata"||r==="messages"||r==="system"||(n[r]=o);return n.system=typeof t.system=="string"?"$text":M(t.system).map(xe),n.messages=(Array.isArray(
|
|
75
|
+
t.messages)?t.messages:[]).filter(g).map(r=>({role:r.role,content:M(r.content).map(xe)})),e&&(n["anthropic-beta"]=e),n}function Qe(t){let e=t.tool_choice;return g(e)&&(e.type==="any"||e.type==="tool")||
|
|
76
|
+
g(t.output_config)&&t.output_config.format!==void 0?true:t.output_format!==void 0}function et(t){let e=typeof t.model=="string"?t.model:"";if(e==="")return [];let n=[],r=t.tool_choice;g(r)&&(r.type==="an\
|
|
77
|
+
y"||r.type==="tool")&&ee(e)&&n.push({clave:`tool-choice-forzado:${e}`,mensaje:`[bvsala] Model "${e}" rejects a forced \`tool_choice\` (\`any\` or \`tool\`) with a 400, with or without thinking. This adapter\
|
|
78
|
+
forwards your request unchanged, so the API will reject it: use \`tool_choice: {type: "auto"}\` with \`strict: true\` tools, or \`output_config.format\` for a fixed JSON shape. See https://platform.claude.\
|
|
79
|
+
com/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use`});let o=["temperature","top_p","top_k"].filter(a=>typeof t[a]=="number"&&!(a==="temperature"&&t[a]===1));return o.length>0&&te(e)&&
|
|
80
|
+
n.push({clave:`muestreo:${e}`,mensaje:`[bvsala] Model "${e}" rejects a non-default ${o.map(a=>`\`${a}\``).join(", ")} with a 400. This adapter forwards your request unchanged, so the API will reject i\
|
|
81
|
+
t: drop the parameter for this model. See https://platform.claude.com/docs/en/models/sonnet-5-5/overview`}),n}var q=class{id;texto="";razono=false;reproducible=true;parada;detallesDeParada;bloquesVistos=0;usoInicio;usoDelta;vioDelta=false;vioStop=false;error;herramientas=new Map;toolCallsJson=[];bloque(e){
|
|
82
|
+
this.bloquesVistos+=1,Y(e.type)?(this.razono=true,this.reproducible=false):e.type==="text"?Array.isArray(e.citations)&&e.citations.length>0&&(this.reproducible=false):e.type!=="tool_use"&&(this.reproducible=false);}json(e){
|
|
83
|
+
this.id=typeof e.id=="string"?e.id:void 0;for(let n of M(e.content))this.bloque(n),n.type==="text"&&typeof n.text=="string"&&(this.texto+=n.text),n.type==="tool_use"&&this.toolCallsJson.push({...typeof n.
|
|
84
|
+
id=="string"?{id:n.id}:{},name:String(n.name??""),arguments:Re(n.input)});this.parada=typeof e.stop_reason=="string"?e.stop_reason:void 0,this.detallesDeParada=e.stop_details,this.usoInicio=g(e.usage)?
|
|
85
|
+
e.usage:void 0,this.usoDelta=this.usoInicio,this.vioDelta=true,this.vioStop=true;}evento(e){let n;try{n=JSON.parse(e.data);}catch{return}if(!g(n))return;switch(e.event!=="message"?e.event:String(n.type??e.event)){case "\
|
|
86
|
+
message_start":{let o=g(n.message)?n.message:{};typeof o.id=="string"&&(this.id=o.id),g(o.usage)&&(this.usoInicio=o.usage);return}case "content_block_start":{let o=g(n.content_block)?n.content_block:{};
|
|
87
|
+
this.bloque(o),o.type==="tool_use"&&typeof n.index=="number"&&this.herramientas.set(n.index,{...typeof o.id=="string"?{id:o.id}:{},name:String(o.name??""),json:""});return}case "content_block_delta":{let o=g(
|
|
74
88
|
n.delta)?n.delta:{};if(o.type==="text_delta"&&typeof o.text=="string")return this.texto+=o.text,o.text===""?void 0:o.text;if(o.type==="input_json_delta"&&typeof o.partial_json=="string"&&typeof n.index==
|
|
75
|
-
"number"){let
|
|
76
|
-
stop_reason=="string"&&(this.parada=o.stop_reason),"stop_details"in o&&(this.detallesDeParada=o.stop_details),
|
|
77
|
-
true;return;case "error":{let o=
|
|
78
|
-
[...this.herramientas.entries()].sort((e,n)=>e[0]-n[0]).map(([,e])=>({...e.id?{id:e.id}:{},name:e.name,arguments:
|
|
79
|
-
n=this.vioDelta?
|
|
80
|
-
return {text:this.texto,...o.length>0?{toolCalls:o}:{},...this.parada
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
"
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
event: ${i}
|
|
89
|
+
"number"){let a=this.herramientas.get(n.index);a&&(a.json+=o.partial_json);}o.type==="citations_delta"&&(this.reproducible=false);return}case "message_delta":{this.vioDelta=true;let o=g(n.delta)?n.delta:{};typeof o.
|
|
90
|
+
stop_reason=="string"&&(this.parada=o.stop_reason),"stop_details"in o&&(this.detallesDeParada=o.stop_details),g(n.usage)&&(this.usoDelta=z(this.usoDelta,n.usage));return}case "message_stop":this.vioStop=
|
|
91
|
+
true;return;case "error":{let o=g(n.error)?n.error:{};this.error=`${String(o.type??"error")}: ${String(o.message??"")}`;return}default:return}}get toolCalls(){return this.toolCallsJson.length>0?this.toolCallsJson:
|
|
92
|
+
[...this.herramientas.entries()].sort((e,n)=>e[0]-n[0]).map(([,e])=>({...e.id?{id:e.id}:{},name:e.name,arguments:tt(e.json)})).filter(e=>e.name!=="")}respuesta(){let e=z(this.usoInicio,this.usoDelta),
|
|
93
|
+
n=this.vioDelta?H(e,this.usoDelta?.output_tokens,this.razono).usage:{inputTokens:0,outputTokens:0,complete:false},r=e.iterations;Array.isArray(r)&&r.length>1&&(n.complete=false);let o=this.toolCalls,a=K(e);
|
|
94
|
+
return {text:this.texto,...o.length>0?{toolCalls:o}:{},...Z(this.parada,this.detallesDeParada),...this.vioDelta&&X({stopReason:this.parada,stopDetails:this.detallesDeParada,bloques:this.bloquesVistos,outputTokens:this.
|
|
95
|
+
usoDelta?.output_tokens,iterations:r})?{unbilledRefusal:true}:{},...a?{servedServiceTier:a}:{},usage:n,...this.reproducible&&this.parada==="end_turn"?{}:{replayable:false}}}};function tt(t){try{return JSON.
|
|
96
|
+
stringify(JSON.parse(t===""?"{}":t))}catch{return t}}function nt(t,e){let n=[];return t.text!==""&&n.push({type:"text",text:t.text}),(t.toolCalls??[]).forEach((r,o)=>{let a={};try{a=JSON.parse(r.arguments||
|
|
97
|
+
"{}");}catch{a={};}n.push({type:"tool_use",id:r.id??`toolu_bvsala_${t.requestId}_${o}`,name:r.name,input:a});}),{id:`msg_bvsala_${t.requestId}`,type:"message",role:"assistant",model:e,content:n,stop_reason:(t.
|
|
98
|
+
toolCalls?.length??0)>0?"tool_use":"end_turn",stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}function _e(t,e,n){let r=nt(t,e),o={"request-id":`bvsala_${t.requestId}`};if(!n)return new Response(
|
|
99
|
+
JSON.stringify(r),{status:200,headers:{...o,"content-type":"application/json"}});let a=(i,u)=>`event: ${i}
|
|
87
100
|
data: ${JSON.stringify(u)}
|
|
88
101
|
|
|
89
|
-
`,a
|
|
90
|
-
block_start",index:u,content_block:{type:"text",text:""}}),a
|
|
91
|
-
ntent_block_start",index:u,content_block:{type:"tool_use",id:i.id,name:i.name,input:{}}}),a
|
|
92
|
-
stringify(i.input)}})),a
|
|
93
|
-
a
|
|
94
|
-
status}`);this.respuesta=n;}respuesta};function
|
|
95
|
-
r.keys().next().value);};return {middleware:async(
|
|
96
|
-
|
|
97
|
-
name??""),descripcion:typeof c.description=="string"?c.description:void 0,parametros:c.input_schema,delProveedor:c.input_schema===void 0&&typeof c.type=="string"&&c.type!=="custom"})),l=await
|
|
98
|
-
anthropic/${String(d.model??"")}`,messages:
|
|
99
|
-
pic-beta")),restricciones:{sinResolvers:
|
|
100
|
-
|
|
101
|
-
return
|
|
102
|
-
"atajo"?(o(`msg_bvsala_${
|
|
103
|
-
if(
|
|
104
|
-
c},
|
|
105
|
-
result.requestId}`,c),
|
|
106
|
-
|
|
107
|
-
{type:"done",response:
|
|
108
|
-
plication/json"))return t.clone().json().then(l=>{
|
|
109
|
-
l stream had no body; nothing was measured.")),t;let
|
|
110
|
-
{async pull(l){let v;try{v=await
|
|
111
|
-
"[bvsala] the stream was cancelled by its reader; nothing was measured.")),
|
|
102
|
+
`,s=a("message_start",{type:"message_start",message:{...r,content:[],stop_reason:null,stop_sequence:null}});return r.content.forEach((i,u)=>{i.type==="text"?(s+=a("content_block_start",{type:"content_\
|
|
103
|
+
block_start",index:u,content_block:{type:"text",text:""}}),s+=a("content_block_delta",{type:"content_block_delta",index:u,delta:{type:"text_delta",text:i.text}})):(s+=a("content_block_start",{type:"co\
|
|
104
|
+
ntent_block_start",index:u,content_block:{type:"tool_use",id:i.id,name:i.name,input:{}}}),s+=a("content_block_delta",{type:"content_block_delta",index:u,delta:{type:"input_json_delta",partial_json:JSON.
|
|
105
|
+
stringify(i.input)}})),s+=a("content_block_stop",{type:"content_block_stop",index:u});}),s+=a("message_delta",{type:"message_delta",delta:{stop_reason:r.stop_reason,stop_sequence:null},usage:{output_tokens:0}}),
|
|
106
|
+
s+=a("message_stop",{type:"message_stop"}),new Response(s,{status:200,headers:{...o,"content-type":"text/event-stream"}})}var N=class extends Error{constructor(n){super(`[bvsala] provider responded ${n.
|
|
107
|
+
status}`);this.respuesta=n;}respuesta};function Ot(t){let e=fe("anthropic-sdk",t),n=Math.max(1,Math.floor(t.reportCacheSize??1e3)),r=new Map,o=(s,i)=>{if(s)for(r.delete(s),r.set(s,i);r.size>n;)r.delete(
|
|
108
|
+
r.keys().next().value);};return {middleware:async(s,i,u)=>{if(!Ye(s))return i(s);if(typeof s.body!="string")throw new Error(J);let d;try{let c=JSON.parse(s.body);if(!g(c))throw new Error(J);d=c;}catch{throw new Error(
|
|
109
|
+
J)}for(let c of et(d))e.avisar(c.clave,c.mensaje);let f=u.options,h=be(f?.bivelio),m=t.context?.({body:d,requestOptions:f}),_=(Array.isArray(d.tools)?d.tools:[]).filter(g).map(c=>me(t,{nombre:String(c.
|
|
110
|
+
name??""),descripcion:typeof c.description=="string"?c.description:void 0,parametros:c.input_schema,delProveedor:c.input_schema===void 0&&typeof c.type=="string"&&c.type!=="custom"})),l=await ye(t,{model:`\
|
|
111
|
+
anthropic/${String(d.model??"")}`,messages:Ze(d),tools:_,temperature:typeof d.temperature=="number"?d.temperature:void 0,context:ve(m,h.context),savings:h.savings,proyeccion:Xe(d,s.headers.get("anthro\
|
|
112
|
+
pic-beta")),restricciones:{sinResolvers:Qe(d)}}),v={model:l.model,messages:l.messages,...l.tools?{tools:l.tools}:{}},b=ne(s.url),w=async c=>{let y;try{y=await i(s);}catch(x){throw c.errorDelMarco={error:x},
|
|
113
|
+
x}if(!y.ok){let x=new N(y);throw c.errorDelMarco={error:x},x}return c.completada=true,y},p=c=>{if(c instanceof N)return c.respuesta;throw c};if(d.stream!==true){let c,y,x=F(v,async()=>{c=await w(x);let E=new q;
|
|
114
|
+
return E.json(await c.clone().json()),y=E.id,E.respuesta()},void 0,b),T;try{T=await e.generar(l,x);}catch(E){return p(E)}if(T.tipo==="sin-informe")return c;let W=e.informe(T.result.report);return T.tipo===
|
|
115
|
+
"atajo"?(o(`msg_bvsala_${T.result.requestId}`,W),_e(T.result,d.model,false)):(o(y,W),c)}let{abierta:D,abrir:S}=pe(),A,C,P=Object.assign(F(v,async()=>{let c=await w(P),y=new L;C=we(c,y,e,P,o),S();for await(let x of y)
|
|
116
|
+
if(x.type==="done")return x.response;throw new Error("[bvsala] the model stream ended before completion; nothing was measured.")},()=>{let c=new L;return w(P).then(y=>{A=we(y,c,e,P,o),S();},y=>c.fail(y)),
|
|
117
|
+
c},b),{abierta:D}),k;try{k=await e.transmitir(l,P,s.signal??void 0);}catch(c){return p(c)}if(k.tipo==="abierto")return A??C;if(k.tipo==="atajo"){let c=e.informe(k.result.report);return o(`msg_bvsala_${k.
|
|
118
|
+
result.requestId}`,c),_e(k.result,d.model,true)}return A??C},reportFor(s){let i=typeof s=="string"?s:s?.id;return typeof i=="string"?r.get(i):void 0},close(){e.close();}}}function we(t,e,n,r,o){let a=new q,
|
|
119
|
+
s,i=async()=>{try{let l=await r.resultado;o(a.id,n.informe(l.report));}catch{}},u=()=>{e.cerrada||(a.error?e.fail(new Error(`[bvsala] provider stream error: ${a.error}`)):a.vioDelta||a.vioStop?(e.push(
|
|
120
|
+
{type:"done",response:a.respuesta()}),e.end(),s=i()):e.fail(new Error("[bvsala] the model stream ended before completion; nothing was measured.")));};if((t.headers.get("content-type")??"").includes("ap\
|
|
121
|
+
plication/json"))return t.clone().json().then(l=>{a.json(g(l)?l:{}),a.texto!==""&&e.push({type:"text",delta:a.texto}),u();},l=>e.fail(l)),t;let d=t.body;if(!d)return e.fail(new Error("[bvsala] the mode\
|
|
122
|
+
l stream had no body; nothing was measured.")),t;let f=d.getReader(),h=new I,m=l=>{for(let v of l){let b=a.evento(v);b!==void 0&&e.push({type:"text",delta:b}),(a.vioStop||a.error)&&u();}},_=new ReadableStream(
|
|
123
|
+
{async pull(l){let v;try{v=await f.read();}catch(w){e.fail(w),l.error(w);return}if(v.done){m(h.end()),u(),await s,l.close();return}let b=v.value;l.enqueue(b),m(h.push(b));},cancel(l){return e.fail(new Error(
|
|
124
|
+
"[bvsala] the stream was cancelled by its reader; nothing was measured.")),f.cancel(l)}});return new Response(_,{status:t.status,statusText:t.statusText,headers:t.headers})}export{Ot as anthropicSavings};
|
|
@@ -1,60 +1,69 @@
|
|
|
1
|
-
import {createMiddleware}from'langchain';import {AIMessage}from'@langchain/core/messages';import {toJsonSchema}from'@langchain/core/utils/json_schema';import {createSavingsLayer,LicenseError
|
|
2
|
-
"https:"||n.port!==""?null:
|
|
3
|
-
|
|
4
|
-
completada:false,...r!==void 0?{origen:r}:{}}}async function
|
|
5
|
-
e)===
|
|
6
|
-
function
|
|
7
|
-
return t(o).generar(
|
|
8
|
-
yield {type:"done",response:i};}};return Object.defineProperty(r,
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
let u=t.run(i,()=>o.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
"
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
1
|
+
import {createMiddleware}from'langchain';import {AIMessage}from'@langchain/core/messages';import {toJsonSchema}from'@langchain/core/utils/json_schema';import {createSavingsLayer,LicenseError}from'@bivelio/savings-layer';import {AsyncLocalStorage}from'async_hooks';var Y={"api.anthropic.com":"anthropic","api.openai.com":"openai","generativelanguage.googleapis.com":"google"};function ee(e){if(typeof e!="string")return null;try{let n=new URL(e);return n.protocol!==
|
|
2
|
+
"https:"||n.port!==""?null:Y[n.hostname.toLowerCase()]??null}catch{return null}}function C(e){return ee(e)!==null?"oficial":"no-oficial"}var T=Symbol.for("@bivelio/savings-layer:provider-origin");var E=new Set;function j(e,n,t){e===true||E.has(n)||(E.add(n),console.warn(t));}var te="[bvsala] internal: the layer changed a request this adapter must forward unchanged; nothing was sent.",re="[bvsala] internal: the layer asked for a second model call within one framework call;\
|
|
3
|
+
nothing more was sent.",oe="[bvsala] internal: the layer called the model outside a framework call; nothing was sent.";function q(e,n,t,r){return {renderizado:e,generar:n,...{},invocada:false,
|
|
4
|
+
completada:false,...r!==void 0?{origen:r}:{}}}async function $(e,n){try{let t=await n();return e.completada=!0,t}catch(t){throw e.errorDelMarco={error:t},t}}function ae(e,n){if(e===n)return true;try{return U(
|
|
5
|
+
e)===U(n)}catch{return false}}function I(e,n){let t=e??[],r=n??[];return t.length===r.length&&t.every((o,s)=>ae(o,r[s]))}function se(e,n){return e.model===n.model&&I(e.messages,n.messages)&&I(e.tools,n.tools)}
|
|
6
|
+
function z(e,n){let t=o=>{let s=n.getStore();if(!s)throw new Error(oe);if(s.invocada)throw new Error(re);if(!se(o,s.renderizado))throw new Error(te);return s.invocada=true,s},r={id:`bivelio-adapter:${e}`,
|
|
7
|
+
async generate(o,s){return t(o).generar(s?.signal)},async*generateStream(o,s){let a=t(o);if(a.transmitir){yield*a.transmitir(s?.signal);return}let i=await a.generar(s?.signal);i.text!==""&&(yield {type:"\
|
|
8
|
+
text",delta:i.text}),yield {type:"done",response:i};}};return Object.defineProperty(r,T,{value:()=>n.getStore()?.origen}),r}function N(){return new AsyncLocalStorage}function U(e){return JSON.stringify(L(e))}function L(e){
|
|
9
|
+
if(Array.isArray(e))return e.map(L);if(e&&typeof e=="object"){let n={};for(let t of Object.keys(e).sort())n[t]=L(e[t]);return n}return e}var le=["licenseKey","licenseServerUrl","serviceAccountKey","licenseRefresh","licenseRevocation","licensePollIntervalSeconds","licenseFetch","metering","meteringUrl","meteringFetch","costModels","defa\
|
|
10
|
+
ultCostModel","exactCache","exactCacheTtlMs","resolvers","exactTokenizer","silenceWarnings","failOpen"];function F(e,n){return n instanceof LicenseError||e.errorDelMarco&&e.errorDelMarco.error===n?false:e.invocada&&
|
|
11
|
+
e.completada}var J="[bvsala] the model answered, but the savings layer failed while accounting for it; the answer is returned unchanged, without a savings report and without a usage record.";function V(e,n){
|
|
12
|
+
let t=N(),r={};for(let a of le)n[a]!==void 0&&(r[a]=n[a]);let o=createSavingsLayer({...r,provider:z(e,t)}),s=(a,i)=>j(n.silenceWarnings,`${e}:${a}`,i);return {ejecutar(a,i){return t.run(i,()=>o.generate(a))},async generar(a,i){
|
|
13
|
+
try{let u=await t.run(i,()=>o.generate(a));return i.invocada?{tipo:"vivo",result:u}:{tipo:"atajo",result:u}}catch(u){if(F(i,u))return s("sin-informe",J),{tipo:"sin-informe"};throw u}},async transmitir(a,i,u){
|
|
14
|
+
let d=t.run(i,()=>o.generateStream(a,u?{signal:u}:{})).result;i.resultado=d,d.catch(()=>{});let p;try{p=await Promise.race([i.abierta.then(()=>"abierta"),d.then(()=>"resuelta")]);}catch(h){if(F(i,h))return s(
|
|
15
|
+
"sin-informe",J),{tipo:"sin-informe"};throw h}if(p==="abierta")return {tipo:"abierto"};let g=await d;return i.invocada?{tipo:"entero",result:g}:{tipo:"atajo",result:g}},informe(a){let i=JSON.parse(JSON.
|
|
16
|
+
stringify(a));if(n.onReport)try{n.onReport(i);}catch{s("onreport","[bvsala] `onReport` threw; the error was caught and the model call was not affected.");}return i},avisar:s,close(){o.close();}}}var ue=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,
|
|
17
|
+
4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,
|
|
18
|
+
1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,
|
|
19
|
+
1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),de=new TextEncoder;function x(e,n){return e>>>n|e<<32-n}function B(e){let n=de.encode(e),t=n.length*
|
|
20
|
+
8,r=(n.length+8>>6)+1,o=new Uint8Array(r*64);o.set(n),o[n.length]=128;let s=new DataView(o.buffer);s.setUint32(o.length-8,Math.floor(t/4294967296)),s.setUint32(o.length-4,t>>>0);let a=new Uint32Array(
|
|
21
|
+
[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let f=0;f<o.length;f+=64){for(let c=0;c<16;c++)i[c]=s.getUint32(f+c*4);for(let c=16;c<
|
|
22
|
+
64;c++){let b=i[c-15],y=i[c-2],w=x(b,7)^x(b,18)^b>>>3,S=x(y,17)^x(y,19)^y>>>10;i[c]=i[c-16]+w+i[c-7]+S|0;}let d=a[0],p=a[1],g=a[2],h=a[3],m=a[4],R=a[5],A=a[6],v=a[7];for(let c=0;c<64;c++){let b=x(m,6)^
|
|
23
|
+
x(m,11)^x(m,25),y=m&R^~m&A,w=v+b+y+ue[c]+i[c]|0,S=x(d,2)^x(d,13)^x(d,22),Z=d&p^d&g^p&g,Q=S+Z|0;v=A,A=R,R=m,m=h+w|0,h=g,g=p,p=d,d=w+Q|0;}a[0]=a[0]+d|0,a[1]=a[1]+p|0,a[2]=a[2]+g|0,a[3]=a[3]+h|0,a[4]=a[4]+
|
|
24
|
+
m|0,a[5]=a[5]+R|0,a[6]=a[6]+A|0,a[7]=a[7]+v|0;}let u="";for(let f=0;f<8;f++)u+=(a[f]>>>0).toString(16).padStart(8,"0");return u}var fe={router:false,compression:false,elision:false,serialization:false,toolDiscovery:false,modelCascade:"off",outputCodebook:false,deferrable:false,semanticCache:false,verification:false};function pe(e,n,t={}){let r=o=>e?.[o]!==
|
|
25
|
+
false&&n?.[o]!==false;return {...fe,exactCache:r("exactCache")&&t.sinReutilizar!==true,singleflight:r("singleflight")&&t.sinReutilizar!==true,deterministicResolvers:r("deterministicResolvers")&&t.sinResolvers!==
|
|
26
|
+
true}}function ge(e,n){let t=e.readOnlyTools;if(typeof t=="function")try{return t(n)===!0}catch{return false}return Array.isArray(t)?t.includes(n):false}function M(e,n){let t=n.delProveedor!==true&&ge(e,n.nombre);
|
|
27
|
+
return {id:n.nombre,intents:[],risk:t?"read":"write",...n.parametros!==void 0&&n.parametros!==null&&typeof n.parametros=="object"?{parameters:n.parametros}:{},...typeof n.descripcion=="string"?{description:n.
|
|
28
|
+
descripcion}:{}}}function D(e,n,t){if(e===null)return null;switch(typeof e){case "string":case "boolean":return e;case "number":return Number.isFinite(e)?e:String(e);case "bigint":return `${e.toString()}n`;case "\
|
|
29
|
+
undefined":case "function":case "symbol":return}let r=e;if(r instanceof Uint8Array)return n.push(r),{$bytes:n.length-1};if(r instanceof ArrayBuffer)return n.push(new Uint8Array(r)),{$bytes:n.length-1};if(ArrayBuffer.
|
|
30
|
+
isView(r))return n.push(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),{$bytes:n.length-1};if(r instanceof URL)return {$url:r.href};if(r instanceof Date)return {$date:Number.isNaN(r.getTime())?"inv\
|
|
31
|
+
alid":r.toISOString()};if(t.has(r))return "$cycle";t.add(r);try{if(Array.isArray(r))return r.map(s=>{let a=D(s,n,t);return a===void 0?null:a});if(r instanceof Map)return {$map:[...r.entries()].map(s=>D(
|
|
32
|
+
s,n,t))};if(r instanceof Set)return {$set:[...r.values()].map(s=>D(s,n,t))};let o={};for(let s of Object.keys(r).sort()){let a=D(r[s],n,t);a!==void 0&&(o[s]=a);}return o}finally{t.delete(r);}}async function W(e){
|
|
33
|
+
let n=globalThis.crypto?.subtle;if(n){let r=new Uint8Array(await n.digest("SHA-256",e));return Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")}let t="";for(let r=0;r<e.length;r+=32768)t+=String.
|
|
34
|
+
fromCharCode(...e.subarray(r,r+32768));return B(t)}async function me(e){try{let n=[],t=JSON.stringify(D(e,n,new WeakSet))??"null",r=await Promise.all(n.map(W)),o=new TextEncoder().encode(`${t}|${r.join(
|
|
35
|
+
",")}`);return await W(o)}catch{return null}}async function K(e,n){let t=await me(n.proyeccion),r=`${n.context?.authorizationScope??"default"}|bvsala-adapter:${t??"none"}`;return {model:n.model,messages:n.
|
|
36
|
+
messages,...n.tools.length>0?{tools:n.tools}:{},...typeof n.temperature=="number"?{temperature:n.temperature}:{},...typeof n.seed=="number"?{seed:n.seed}:{},context:{...n.context??{},authorizationScope:r},
|
|
37
|
+
savings:pe(e.savings,n.savings,{...n.restricciones,...t===null?{sinReutilizar:true}:{}})}}function l(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function H(e){let n=e;try{if(typeof n.getType=="function")return n.getType();if(typeof n._getType=="function")return n._getType()}catch{}
|
|
38
|
+
return typeof n.type=="string"?n.type:""}function _(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>l(n)&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
|
|
39
|
+
`):""}function X(e){if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return "{}"}}function P(e){return (Array.isArray(e.tool_calls)?e.tool_calls:[]).filter(l).map(t=>({...typeof t.id==
|
|
40
|
+
"string"?{id:t.id}:{},name:String(t.name??""),arguments:X(t.args)}))}function he(e,n){let t=[],r=_(e?.content);r!==""&&t.push({role:"system",content:r});for(let o of n){if(!l(o))continue;let s=H(o);if(s===
|
|
41
|
+
"system")t.push({role:"system",content:_(o.content)});else if(s==="human")t.push({role:"user",content:_(o.content)});else if(s==="ai"){let a=P(o);t.push({role:"assistant",content:_(o.content),...a.length>
|
|
42
|
+
0?{toolCalls:a}:{}});}else s==="tool"&&t.push({role:"tool",content:typeof o.content=="string"?o.content:X(o.content),...typeof o.tool_call_id=="string"?{toolCallId:o.tool_call_id}:{},...typeof o.name==
|
|
43
|
+
"string"?{name:o.name}:{}});}return t}function G(e){if(!l(e))return e;let n=e.content,t=H(e),r={};for(let[o,s]of Object.entries(l(e.additional_kwargs)?e.additional_kwargs:{}))o==="tool_calls"||o==="fun\
|
|
44
|
+
ction_call"||o.startsWith("__")||(r[o]=s);return {type:t,name:e.name,content:t==="tool"?n:typeof n=="string"?"$text":Array.isArray(n)?n.map(o=>l(o)&&o.type==="text"?{...o,text:void 0,id:void 0}:o):n,tool_calls:P(
|
|
45
|
+
e).map(o=>({name:o.name,arguments:o.arguments})),status:e.status,additional_kwargs:r}}function be(e,n){let t=[],r=[];for(let o of n){if(!l(o))continue;if(typeof o.name=="string"&&"schema"in o){let a,i=true;
|
|
46
|
+
try{a=toJsonSchema(o.schema);}catch{i=false;}let u=M(e,{nombre:o.name,descripcion:typeof o.description=="string"?o.description:void 0,parametros:a});t.push(i?u:{...u,risk:"write"}),r.push({name:o.name,description:o.
|
|
47
|
+
description,parametros:a,returnDirect:o.returnDirect});continue}let s=l(o.function)?o.function:void 0;if(o.type==="function"&&s&&typeof s.name=="string"){t.push(M(e,{nombre:s.name,descripcion:typeof s.
|
|
48
|
+
description=="string"?s.description:void 0,parametros:s.parameters})),r.push(o);continue}t.push(M(e,{nombre:String(o.name??o.type??"server-tool"),delProveedor:true})),r.push(o);}return {tools:t,definiciones:r}}
|
|
49
|
+
function O(e){try{let n=e._llmType?.();return typeof n=="string"?n:""}catch{return ""}}function we(e){if(typeof e=="string")return e.replace(":","/");let n=e,t=n._defaultConfig;if(t&&typeof t=="object"&&
|
|
41
50
|
typeof t.model=="string"&&t.model!=="")return t.model.includes("/")?t.model:typeof t.modelProvider=="string"&&t.modelProvider!==""?`${t.modelProvider}/${t.model}`:t.model;let r=typeof n.model=="string"?
|
|
42
|
-
n.model:typeof n.modelName=="string"?n.modelName:"";if(r.includes("/"))return r;let o=
|
|
43
|
-
identifyingParams.call(e),r=
|
|
44
|
-
invocationParams?.({})??null}catch{return null}}function
|
|
45
|
-
void 0}function
|
|
46
|
-
output_token_details:{},i=
|
|
47
|
-
void 0?{cacheWriteInputTokens:
|
|
51
|
+
n.model:typeof n.modelName=="string"?n.modelName:"";if(r.includes("/"))return r;let o=O(e);return o!==""?`${o}/${r}`:r}function Se(e){if(!l(e))return;try{if(typeof e.identifyingParams=="function"){let t=e.
|
|
52
|
+
identifyingParams.call(e),r=l(t)?t.baseURL:void 0;if(typeof r=="string"&&r!=="")return C(r)}}catch{}let n=e.apiUrl;if(O(e)==="anthropic"&&typeof n=="string"&&n!=="")return C(n)}function Re(e){try{return e.
|
|
53
|
+
invocationParams?.({})??null}catch{return null}}function Ae(e){let n=e.toolChoice;return n==="required"||l(n)?true:e.responseFormat!==void 0}function k(e){return typeof e=="number"&&Number.isFinite(e)?e:
|
|
54
|
+
void 0}function ke(e,n){let t=l(e.usage_metadata)?e.usage_metadata:void 0,r=k(t?.input_tokens),o=k(t?.output_tokens),s=l(t?.input_token_details)?t.input_token_details:{},a=l(t?.output_token_details)?t.
|
|
55
|
+
output_token_details:{},i=k(s.cache_read),u=k(s.cache_creation),f=k(a.reasoning),d=r!==void 0&&(i??0)+(u??0)<=r;return {inputTokens:r??0,outputTokens:o??0,...i!==void 0?{cachedInputTokens:i}:{},...u!==
|
|
56
|
+
void 0?{cacheWriteInputTokens:u}:{},...f!==void 0?{reasoningTokens:f}:{},...n&&r!==void 0&&o!==void 0&&d?{}:{complete:false}}}function De(e){let n=l(e.response_metadata)?e.response_metadata:{},t=n.finish_reason??
|
|
48
57
|
n.stop_reason??n.finishReason;switch(t){case "end_turn":case "stop":case "STOP":return "stop";case "max_tokens":case "length":case "MAX_TOKENS":return "length";case "tool_use":case "tool_calls":return "tool_call\
|
|
49
|
-
s";default:return typeof t=="string"?t:void 0}}function
|
|
50
|
-
length>0||Array.isArray(r.annotations)&&r.annotations.length>0)return false}let t=
|
|
51
|
-
let t=
|
|
52
|
-
toolCalls??[]).map((t,r)=>{let o={};try{let
|
|
53
|
-
output_tokens:0,total_tokens:0},response_metadata:n?{bivelio:{savingsReport:n}}:{}})}var
|
|
54
|
-
a provider bill; its calls are reported as unmeasured.";function
|
|
55
|
-
|
|
56
|
-
[],{tools:h,definiciones:
|
|
57
|
-
modelo:
|
|
58
|
-
sinReutilizar:
|
|
59
|
-
tipo==="sin-informe")return
|
|
60
|
-
|
|
58
|
+
s";default:return typeof t=="string"?t:void 0}}function _e(e,n){if(n!=="stop")return false;if(Array.isArray(e.content)){for(let r of e.content)if(!l(r)||r.type!=="text"||Array.isArray(r.citations)&&r.citations.
|
|
59
|
+
length>0||Array.isArray(r.annotations)&&r.annotations.length>0)return false}let t=l(e.additional_kwargs)?e.additional_kwargs:{};return !("reasoning"in t||"reasoning_content"in t||"audio"in t)}function Me(e,n){
|
|
60
|
+
let t=De(e),r=P(e);return {text:_(e.content),...r.length>0?{toolCalls:r}:{},...t?{finishReason:t}:{},usage:ke(e,n),..._e(e,t)?{}:{replayable:false}}}function Ce(e,n){return new AIMessage({content:e.text,tool_calls:(e.
|
|
61
|
+
toolCalls??[]).map((t,r)=>{let o={};try{let s=JSON.parse(t.arguments||"{}");l(s)&&(o=s);}catch{o={};}return {id:t.id??`bvsala-${e.requestId}-${r}`,name:t.name,args:o,type:"tool_call"}}),usage_metadata:{input_tokens:0,
|
|
62
|
+
output_tokens:0,total_tokens:0},response_metadata:n?{bivelio:{savingsReport:n}}:{}})}var Le="[bvsala] this LangChain model has its own `cache` set, so a usage counter can be a cached copy rather than \
|
|
63
|
+
a provider bill; its calls are reported as unmeasured.";function Xe(e){let n=V("langchain",e),t=e.reportInMetadata!==false,r=createMiddleware({name:"BivelioSavings",wrapModelCall:async(o,s)=>{let a=o,i=a.model,u=O(i),
|
|
64
|
+
f=l(i)&&i.cache!==void 0&&i.cache!==null&&i.cache!==false;f&&n.avisar("cache-del-modelo",Le);let d=!u.toLowerCase().includes("fake")&&!f,p=e.modelId?e.modelId(i):we(i),g=Array.isArray(a.messages)?a.messages:
|
|
65
|
+
[],{tools:h,definiciones:m}=be(e,Array.isArray(a.tools)?a.tools:[]),R=Ae(a),A=k(i?.temperature),v=await K(e,{model:p,messages:he(a.systemMessage,g),tools:h,temperature:A,context:e.context?.(o),proyeccion:{
|
|
66
|
+
modelo:p,parametros:Re(i),sistema:G(a.systemMessage),mensajes:g.map(G),herramientas:m,toolChoice:a.toolChoice,responseFormat:a.responseFormat,modelSettings:a.modelSettings},restricciones:{sinResolvers:R,
|
|
67
|
+
sinReutilizar:a.responseFormat!==void 0}}),c,b=q({model:v.model,messages:v.messages,...v.tools?{tools:v.tools}:{}},async()=>(c=await $(b,async()=>s(o)),Me(c,d)),void 0,Se(i)),y=await n.generar(v,b);if(y.
|
|
68
|
+
tipo==="sin-informe")return c;let w=n.informe(y.result.report);if(y.tipo==="atajo")return Ce(y.result,t?w:void 0);let S=c;return t&&(S.response_metadata={...S.response_metadata??{},bivelio:{savingsReport:w}}),
|
|
69
|
+
S}});return Object.assign(r,{close:()=>n.close()})}function Ze(e){let n=e?.response_metadata,t=l(n)?n.bivelio:void 0,r=l(t)?t.savingsReport:void 0;if(!(!l(r)||typeof r.requestId!="string"))return r}export{Ze as getSavingsReportFromMessage,Xe as savingsAgentMiddleware};
|