promptlayer 1.0.60 → 1.0.61
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/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/index.d.mts +229 -9
- package/dist/index.d.ts +229 -9
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/types.ts +302 -9
- package/src/utils/blueprint-builder.test.ts +727 -0
- package/src/utils/blueprint-builder.ts +957 -126
- package/src/utils/streaming.test.ts +498 -0
- package/src/utils/streaming.ts +471 -43
- package/src/utils/utils.ts +4 -0
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var to=Object.defineProperty,eo=Object.defineProperties;var oo=Object.getOwnPropertyDescriptors;var Pt=Object.getOwnPropertySymbols;var re=Object.prototype.hasOwnProperty,se=Object.prototype.propertyIsEnumerable;var $t=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t);var ne=(t,e,o)=>e in t?to(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,h=(t,e)=>{for(var o in e||(e={}))re.call(e,o)&&ne(t,o,e[o]);if(Pt)for(var o of Pt(e))se.call(e,o)&&ne(t,o,e[o]);return t},D=(t,e)=>eo(t,oo(e));var it=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(e,o)=>(typeof require!="undefined"?require:e)[o]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var St=(t,e)=>{var o={};for(var n in t)re.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&Pt)for(var n of Pt(t))e.indexOf(n)<0&&se.call(t,n)&&(o[n]=t[n]);return o};var y=(t,e,o)=>new Promise((n,r)=>{var s=c=>{try{l(o.next(c))}catch(p){r(p)}},i=c=>{try{l(o.throw(c))}catch(p){r(p)}},l=c=>c.done?n(c.value):Promise.resolve(c.value).then(s,i);l((o=o.apply(t,e)).next())}),v=function(t,e){this[0]=t,this[1]=e},It=(t,e,o)=>{var n=(i,l,c,p)=>{try{var m=o[i](l),g=(l=m.value)instanceof v,_=m.done;Promise.resolve(g?l[0]:l).then(b=>g?n(i==="return"?i:"next",l[1]?{done:b.done,value:b.value}:b,c,p):c({value:b,done:_})).catch(b=>n("throw",b,c,p))}catch(b){p(b)}},r=i=>s[i]=l=>new Promise((c,p)=>n(i,l,c,p)),s={};return o=o.apply(t,e),s[$t("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var At=(t,e,o)=>(e=t[$t("asyncIterator")])?e.call(t):(t=t[$t("iterator")](),e={},o=(n,r)=>(r=t[n])&&(e[n]=s=>new Promise((i,l,c)=>(s=r.call(t,s),c=s.done,Promise.resolve(s.value).then(p=>i({value:p,done:c}),l)))),o("next"),o("return"),e);import co from"ably";import{Centrifuge as po}from"centrifuge";import lo from"p-retry";var F=(t,e,o,n)=>{let r={id:t,function:{name:e,input:o}};return n&&(r.tool_id=n),r},E=n=>{var r=n,{type:t,item_id:e}=r,o=St(r,["type","item_id"]);let s=h({type:t},o);return e&&(s.item_id=e),s},Tt=(t,e)=>({input_variables:[],template_format:"f-string",content:t,role:"assistant",function_call:null,name:null,tool_calls:e}),Et=(t,e)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:e}),ie=(t,e)=>{let o=[],n=[];t.type==="content_block_start"?t.content_block.type==="thinking"?o.push(E({type:"thinking",thinking:"",signature:""})):t.content_block.type==="text"?o.push(E({type:"text",text:""})):t.content_block.type==="tool_use"&&n.push(F(t.content_block.id||"",t.content_block.name||"",{})):t.type==="content_block_delta"&&(t.delta.type==="thinking_delta"?o.push(E({type:"thinking",thinking:t.delta.thinking||"",signature:""})):t.delta.type==="text_delta"?o.push(E({type:"text",text:t.delta.text||""})):t.delta.type==="signature_delta"?o.push(E({type:"thinking",thinking:"",signature:t.delta.signature||""})):t.delta.type==="input_json_delta"&&n.push(F("","",t.delta.partial_json)));let r=Tt(o,n);return Et(r,e)},ae=(t,e)=>{let o=[],n=[];for(let s of t.candidates)if(s.content&&s.content.parts&&Array.isArray(s.content.parts))for(let i of s.content.parts)i.text?i.thought===!0?o.push(E({type:"thinking",thinking:i.text,signature:i.thoughtSignature||""})):o.push(E({type:"text",text:i.text})):i.functionCall&&n.push(F(i.functionCall.id||"",i.functionCall.name||"",i.functionCall.args||{}));let r=Tt(o,n);return Et(r,e)},Wt=(t,e)=>{let o=[],n=[];for(let s of t.choices)if(s.delta){s.delta.content&&o.push(E({type:"text",text:s.delta.content}));let i=s.delta.tool_calls||s.delta.toolCalls;if(i&&Array.isArray(i))for(let l of i)l.function&&n.push(F(l.id||"",l.function.name||"",l.function.arguments||""))}let r=Tt(o,n);return Et(r,e)},ce=(t,e)=>{var i,l,c,p,m,g,_,b,w,P,I,A,R,S,N,M,B,C,k,V,K,H,j,J,tt,X,z,et,ot,L,Z,nt,ct,pt,lt,ut,mt,dt,ft,_t,yt,ht,gt,Rt,bt,wt,O,U,u,d,T,Jt,zt,Yt,Ht,Xt,Zt,Qt,vt,te,ee;let o=[],n=[],r=t==null?void 0:t.type;if(r==="response.reasoning_summary_text.delta"){let a=(i=t==null?void 0:t.delta)!=null?i:"",x=(l=t==null?void 0:t.item_id)!=null?l:"";a&&o.push(E({type:"thinking",item_id:x,thinking:a,signature:""}))}else if(r==="response.reasoning_summary_text.done"){let a=(c=t==null?void 0:t.text)!=null?c:"",x=(p=t==null?void 0:t.item_id)!=null?p:"";a&&o.push(E({type:"thinking",item_id:x,thinking:a,signature:""}))}else if(r==="response.reasoning_summary_part.added"){let a=(m=t==null?void 0:t.part)!=null?m:{},x=(g=t==null?void 0:t.item_id)!=null?g:"";if((a==null?void 0:a.type)==="summary_text"){let f=(_=a==null?void 0:a.text)!=null?_:"";o.push(E({type:"thinking",item_id:x,thinking:f,signature:""}))}}else if(r==="response.reasoning_summary_part.done"){let a=(b=t==null?void 0:t.part)!=null?b:{},x=(w=t==null?void 0:t.item_id)!=null?w:"";if((a==null?void 0:a.type)==="summary_text"){let f=(P=a==null?void 0:a.text)!=null?P:"";f&&o.push(E({type:"thinking",item_id:x,thinking:f,signature:""}))}}else if(r==="response.function_call_arguments.delta"){let a=(I=t==null?void 0:t.item_id)!=null?I:"",x=(A=t==null?void 0:t.delta)!=null?A:"";x&&n.push(F("","",x,a))}else if(r==="response.function_call_arguments.done"){let a=(R=t==null?void 0:t.item_id)!=null?R:"",x=(S=t==null?void 0:t.arguments)!=null?S:"";x&&n.push(F("","",x,a))}else if(r==="response.output_item.added"){let a=(N=t==null?void 0:t.item)!=null?N:{},x=a==null?void 0:a.type,f=(M=a==null?void 0:a.id)!=null?M:"";x==="reasoning"?o.push(E({type:"thinking",thinking:"",signature:"",item_id:f})):x==="function_call"?n.push(F((a==null?void 0:a.call_id)||"",(a==null?void 0:a.name)||"","",f)):x==="message"?o.push(E({type:"text",item_id:f,text:""})):x==="code_interpreter_call"&&o.push(E({type:"code",item_id:f,code:(B=a==null?void 0:a.code)!=null?B:"",container_id:(C=a==null?void 0:a.container_id)!=null?C:""}))}else if(r==="response.content_part.added"){let a=(k=t==null?void 0:t.part)!=null?k:{},x=(V=a==null?void 0:a.type)!=null?V:"output_text",f=(K=t==null?void 0:t.item_id)!=null?K:"";x==="output_text"&&o.push(E({type:"text",item_id:f,text:(H=a==null?void 0:a.text)!=null?H:"",annotations:(a==null?void 0:a.annotations)||[]}))}else if(r==="response.content_part.done"){let a=(j=t==null?void 0:t.part)!=null?j:{},x=(J=a==null?void 0:a.type)!=null?J:"output_text",f=(tt=t==null?void 0:t.item_id)!=null?tt:"";x==="output_text"&&o.push(E({type:"text",item_id:f,text:(X=a==null?void 0:a.text)!=null?X:"",annotations:(a==null?void 0:a.annotations)||[]}))}else if(r==="response.output_text.annotation.added"){let a=(t==null?void 0:t.annotation)||{},x=a==null?void 0:a.type,f=null;x==="url_citation"?f={type:"url_citation",title:a==null?void 0:a.title,url:a==null?void 0:a.url,start_index:a==null?void 0:a.start_index,end_index:a==null?void 0:a.end_index}:x=="file_citation"?f={type:"file_citation",index:a==null?void 0:a.index,file_id:a==null?void 0:a.file_id,filename:a==null?void 0:a.filename}:f=a,o.push(E({type:"text",item_id:(z=t==null?void 0:t.item_id)!=null?z:"",text:"",annotations:[f]}))}else if(r==="response.code_interpreter_call.in_progress")o.push(E({type:"code",item_id:(et=t==null?void 0:t.item_id)!=null?et:"",code:(ot=t==null?void 0:t.code)!=null?ot:"",container_id:(L=t==null?void 0:t.container_id)!=null?L:""}));else if(r==="response.code_interpreter_call_code.delta")o.push(E({type:"code",item_id:(Z=t==null?void 0:t.item_id)!=null?Z:"",code:(nt=t==null?void 0:t.delta)!=null?nt:"",container_id:(ct=t==null?void 0:t.container_id)!=null?ct:""}));else if(r==="response.output_text.delta"){let a=(pt=t==null?void 0:t.delta)!=null?pt:"";a&&o.push(E({type:"text",item_id:(lt=t==null?void 0:t.item_id)!=null?lt:"",text:a}))}else if(r==="response.output_text.done"){let a=(ut=t==null?void 0:t.text)!=null?ut:"";a&&o.push(E({type:"text",item_id:(mt=t==null?void 0:t.item_id)!=null?mt:"",text:a}))}else if(r==="response.output_item.done"){let a=(dt=t==null?void 0:t.item)!=null?dt:{},x=a==null?void 0:a.type,f=(ft=a==null?void 0:a.id)!=null?ft:"";if(x==="reasoning"){let G=((_t=a==null?void 0:a.summary)!=null?_t:[]).map(Q=>{var W;return(W=Q==null?void 0:Q.text)!=null?W:""}).join("");o.push(E({type:"thinking",item_id:f,thinking:G,signature:""}))}else if(x==="function_call")n.push(F((a==null?void 0:a.call_id)||"",(a==null?void 0:a.name)||"",(a==null?void 0:a.arguments)||"",f));else if(x==="message"){let rt=(yt=a==null?void 0:a.content)!=null?yt:[];for(let G of rt)if((G==null?void 0:G.type)==="output_text"){let Q=(ht=G==null?void 0:G.text)!=null?ht:"";Q&&o.push(E({type:"text",item_id:f,text:Q}))}}else x==="code_interpreter_call"&&o.push(E({type:"code",item_id:f,code:(gt=a==null?void 0:a.code)!=null?gt:"",container_id:(Rt=a==null?void 0:a.container_id)!=null?Rt:""}))}else if(r==="response.code_interpreter_call_code.done")o.push(E({type:"code",item_id:(bt=t==null?void 0:t.item_id)!=null?bt:"",code:(wt=t==null?void 0:t.code)!=null?wt:"",container_id:(O=t==null?void 0:t.container_id)!=null?O:""}));else if(r==="response.code_interpreter_call.interpreting")o.push(E({type:"code",item_id:(U=t==null?void 0:t.item_id)!=null?U:"",code:(u=t==null?void 0:t.code)!=null?u:"",container_id:(d=t==null?void 0:t.container_id)!=null?d:""}));else if(r==="response.code_interpreter_call.completed")o.push(E({type:"code",item_id:(T=t==null?void 0:t.item_id)!=null?T:"",code:(Jt=t==null?void 0:t.code)!=null?Jt:"",container_id:(zt=t==null?void 0:t.container_id)!=null?zt:""}));else if(r==="response.completed"){let a=(Yt=t==null?void 0:t.response)!=null?Yt:{},x=(Ht=a==null?void 0:a.output)!=null?Ht:[];for(let f of x){let rt=f==null?void 0:f.type,G=(Xt=f==null?void 0:f.id)!=null?Xt:"";if(rt==="reasoning"){let W=((Zt=f==null?void 0:f.summary)!=null?Zt:[]).map(st=>{var oe;return(oe=st==null?void 0:st.text)!=null?oe:""}).join("");o.push(E({type:"thinking",item_id:G,thinking:W,signature:""}))}else if(rt==="function_call")n.push(F((f==null?void 0:f.call_id)||"",(f==null?void 0:f.name)||"",(f==null?void 0:f.arguments)||"",G));else if(rt==="message"){let Q=(Qt=f==null?void 0:f.content)!=null?Qt:[];for(let W of Q)if((W==null?void 0:W.type)==="output_text"){let st=(vt=W==null?void 0:W.text)!=null?vt:"";st&&o.push(E({type:"text",item_id:G,text:st,annotations:(W==null?void 0:W.annotations)||[]}))}}else rt==="code_interpreter_call"&&o.push(E({type:"code",item_id:G,code:(te=f==null?void 0:f.code)!=null?te:"",container_id:(ee=f==null?void 0:f.container_id)!=null?ee:""}))}}let s=Tt(o,n||[]);return Et(s,e)},pe=(t,e)=>{var s,i,l,c;let o=[],n=[];if("contentBlockDelta"in t){let p=((s=t.contentBlockDelta)==null?void 0:s.delta)||{};if("reasoningContent"in p){let m=((i=p.reasoningContent)==null?void 0:i.text)||"",g=((l=p.reasoningContent)==null?void 0:l.signature)||"";o.push(E({type:"thinking",thinking:m,signature:g}))}else if("text"in p)o.push(E({type:"text",text:p.text||""}));else if("toolUse"in p){let m=p.toolUse||{};n.push(F(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in t){let p=((c=t.contentBlockStart)==null?void 0:c.start)||{};if("toolUse"in p){let m=p.toolUse||{};n.push(F(m.toolUseId||"",m.name||"",""))}}let r=Tt(o,n);return Et(r,e)};var de=["openai","openai.azure"],xt=t=>{var n,r,s,i,l,c,p,m,g,_,b,w,P,I,A,R,S,N,M,B,C,k,V,K,H,j,J,tt,X,z,et,ot,L,Z,nt,ct,pt,lt,ut,mt,dt,ft,_t,yt,ht,gt,Rt,bt,wt;let e={id:null,object:"response",created_at:null,status:null,error:null,incomplete_details:null,instructions:null,max_output_tokens:null,model:null,output:[],parallel_tool_calls:!0,previous_response_id:null,reasoning:{},store:!0,temperature:1,text:void 0,tool_choice:"auto",tools:[],top_p:1,truncation:"disabled",usage:null,user:null,metadata:{}},o={};for(let O of t){let U=O==null?void 0:O.type;if(U==="response.created"){let u=O.response||{};e.id=(n=u.id)!=null?n:e.id,e.created_at=(r=u.created_at)!=null?r:e.created_at,e.model=(s=u.model)!=null?s:e.model,e.status=(i=u.status)!=null?i:e.status,e.parallel_tool_calls=(l=u.parallel_tool_calls)!=null?l:e.parallel_tool_calls,e.temperature=(c=u.temperature)!=null?c:e.temperature,e.tool_choice=(p=u.tool_choice)!=null?p:e.tool_choice,e.tools=(m=u.tools)!=null?m:e.tools,e.top_p=(g=u.top_p)!=null?g:e.top_p,e.truncation=(_=u.truncation)!=null?_:e.truncation,e.max_output_tokens=(b=u.max_output_tokens)!=null?b:e.max_output_tokens,e.previous_response_id=(w=u.previous_response_id)!=null?w:e.previous_response_id,e.store=(P=u.store)!=null?P:e.store,e.user=(I=u.user)!=null?I:e.user,e.metadata=(A=u.metadata)!=null?A:e.metadata;let d=u.text;d&&(e.text=d);let T=u.reasoning;T&&(e.reasoning=T);continue}if(U==="response.in_progress"){let u=O.response||{};e.status=(R=u.status)!=null?R:e.status;continue}if(U==="response.output_item.added"){let u=O.item||{},d=u.id,T=u.type;T==="reasoning"?o[d]={type:"reasoning",id:d,summary:[],status:(S=u.status)!=null?S:"in_progress"}:T==="function_call"?o[d]={type:"function_call",id:d,call_id:u.call_id,name:u.name,arguments:"",status:(N=u.status)!=null?N:"in_progress"}:T==="message"?o[d]={type:"message",id:d,role:(M=u.role)!=null?M:"assistant",content:[],status:(B=u.status)!=null?B:"in_progress"}:T==="code_interpreter_call"&&(o[d]={type:"code_interpreter_call",id:d,container_id:u.container_id,code:(C=u.code)!=null?C:"",status:(k=u.status)!=null?k:"in_progress"});continue}if(U==="response.reasoning_summary_part.added"){let u=O.item_id,d=O.part||{};if(u in o&&o[u].type==="reasoning"){let T={type:(V=d.type)!=null?V:"summary_text",text:(K=d.text)!=null?K:""};o[u].summary.push(T)}continue}if(U==="response.reasoning_summary_text.delta"){let u=O.item_id,d=(H=O.delta)!=null?H:"",T=(j=O.summary_index)!=null?j:0;if(u in o&&o[u].type==="reasoning"){for(;o[u].summary.length<=T;)o[u].summary.push({type:"summary_text",text:""});o[u].summary[T].text+=d}continue}if(U==="response.reasoning_summary_text.done"){let u=O.item_id,d=(J=O.text)!=null?J:"",T=(tt=O.summary_index)!=null?tt:0;if(u in o&&o[u].type==="reasoning"){for(;o[u].summary.length<=T;)o[u].summary.push({type:"summary_text",text:""});o[u].summary[T].text=d}continue}if(U==="response.reasoning_summary_part.done"){let u=O.item_id,d=O.part||{};if(u in o&&o[u].type==="reasoning"){let T=(X=O.summary_index)!=null?X:0;T<o[u].summary.length&&(o[u].summary[T]={type:(z=d.type)!=null?z:"summary_text",text:(et=d.text)!=null?et:""})}continue}if(U==="response.function_call_arguments.delta"){let u=O.item_id,d=(ot=O.delta)!=null?ot:"";u in o&&(o[u].arguments=`${o[u].arguments||""}${d}`);continue}if(U==="response.function_call_arguments.done"){let u=O.item_id,d=(L=O.arguments)!=null?L:"";u in o&&(o[u].arguments=d);continue}if(U==="response.content_part.added"){let u=O.part||{},d=Object.values(o).find(T=>T.type==="message");if(d){let T={type:(Z=u.type)!=null?Z:"output_text",text:(nt=u.text)!=null?nt:"",annotations:(ct=u.annotations)!=null?ct:[]};d.content.push(T)}continue}if(U==="response.output_text.delta"){let u=(pt=O.delta)!=null?pt:"";for(let d of Object.values(o))if(d.type==="message"&&d.content&&d.content.length){let T=d.content[d.content.length-1];T&&T.type==="output_text"&&(T.text=`${T.text||""}${u}`);break}continue}if(U==="response.output_text.done"){let u=(lt=O.text)!=null?lt:"";for(let d of Object.values(o))if(d.type==="message"&&d.content&&d.content.length){let T=d.content[d.content.length-1];T&&T.type==="output_text"&&(T.text=u);break}continue}if(U==="response.output_item.done"){let u=O.item||{},d=u.id;d in o&&(o[d].status=(ut=u.status)!=null?ut:"completed",u.type==="reasoning"?o[d].summary=(mt=u.summary)!=null?mt:o[d].summary:u.type==="function_call"?(o[d].arguments=(dt=u.arguments)!=null?dt:o[d].arguments,o[d].call_id=(ft=u.call_id)!=null?ft:o[d].call_id,o[d].name=(_t=u.name)!=null?_t:o[d].name):u.type==="message"&&(o[d].content=(yt=u.content)!=null?yt:o[d].content,o[d].role=(ht=u.role)!=null?ht:o[d].role),e.output.push(o[d]));continue}if(U==="response.completed"){let u=O.response||{};e.status=(Rt=(gt=u.status)!=null?gt:e.status)!=null?Rt:"completed",e.usage=(bt=u.usage)!=null?bt:e.usage,e.output=(wt=u.output)!=null?wt:e.output,u.reasoning&&(e.reasoning=u.reasoning);continue}}return e},Mt=t=>{var l,c,p,m,g,_,b,w,P,I;let e=null,o,n={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},r=t.at(-1);if(!r)return n;let s;for(let A of t){if(A.choices.length===0)continue;let R=A.choices[0].delta;R.content&&(e=`${e||""}${R.content||""}`),R.function_call&&(o={name:`${o?o.name:""}${R.function_call.name||""}`,arguments:`${o?o.arguments:""}${R.function_call.arguments||""}`});let S=(l=R.tool_calls)==null?void 0:l[0];if(S){s=s||[];let N=s.at(-1);if(!N||S.id){s.push({id:S.id||"",type:S.type||"function",function:{name:((c=S.function)==null?void 0:c.name)||"",arguments:((p=S.function)==null?void 0:p.arguments)||""}});continue}N.function.name=`${N.function.name}${((m=S.function)==null?void 0:m.name)||""}`,N.function.arguments=`${N.function.arguments}${((g=S.function)==null?void 0:g.arguments)||""}`}}let i=t[0].choices.at(0);return n.choices.push({finish_reason:(_=i==null?void 0:i.finish_reason)!=null?_:"stop",index:(b=i==null?void 0:i.index)!=null?b:0,logprobs:(w=i==null?void 0:i.logprobs)!=null?w:null,message:{role:"assistant",content:e,function_call:o||void 0,tool_calls:s||void 0,refusal:(P=i==null?void 0:i.delta.refusal)!=null?P:null}}),n.id=r.id,n.model=r.model,n.created=r.created,n.system_fingerprint=r.system_fingerprint,n.usage=(I=r.usage)!=null?I:void 0,n},le=t=>{let e={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},o=t.at(-1);if(!o)return e;let n="";for(let r of t)r.choices.length>0&&r.choices[0].text&&(n=`${n}${r.choices[0].text}`);return e.choices[0].text=n,e.id=o.id,e.created=o.created,e.model=o.model,e.system_fingerprint=o.system_fingerprint,e.usage=o.usage,e},Gt=t=>{var c;let e={id:"",model:"",content:[],role:"assistant",type:"message",stop_reason:"stop_sequence",stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,server_tool_use:null,service_tier:null}};if(!t.at(-1))return e;let n=null,r="",s="",i="",l="";for(let p of t)if(p.type==="message_start")e=h({},p.message);else if(p.type==="content_block_start")n=h({},p.content_block),n.type==="thinking"?(r="",s=""):n.type==="text"?i="":(n.type==="tool_use"||n.type==="server_tool_use")&&(l="");else if(p.type==="content_block_delta"&&n!==null){if(n.type==="thinking")"signature"in p.delta&&(r=p.delta.signature||""),"thinking"in p.delta&&(s+=p.delta.thinking||"");else if(n.type==="text")"text"in p.delta&&(i+=p.delta.text||"");else if((n.type==="tool_use"||n.type==="server_tool_use")&&p.delta.type==="input_json_delta"){let m=p.delta;l+=m.partial_json||""}}else if(p.type==="content_block_stop"&&n!==null){if(n.type==="thinking")n.signature=r,n.thinking=s;else if(n.type==="text")n.text=i,n.citations=null;else if(n.type==="tool_use"||n.type==="server_tool_use")try{n.input=l?JSON.parse(l):{}}catch(m){n.input={}}e.content.push(n),n=null,r="",s="",i="",l=""}else p.type==="message_delta"&&("usage"in p&&p.usage&&(e.usage=D(h({},e.usage),{output_tokens:(c=p.usage.output_tokens)!=null?c:0})),"delta"in p&&p.delta&&("stop_reason"in p.delta&&p.delta.stop_reason!==void 0&&(e.stop_reason=p.delta.stop_reason),"stop_sequence"in p.delta&&p.delta.stop_sequence!==void 0&&(e.stop_sequence=p.delta.stop_sequence)));return e},ue=t=>{let e={completion:"",id:"",model:"",stop_reason:"",type:"completion"},o=t.at(-1);if(!o)return e;let n="";for(let r of t)n=`${n}${r.completion}`;return e.completion=n,e.id=o.id,e.model=o.model,e.stop_reason=o.stop_reason,e},no=t=>{var i,l,c,p,m,g,_,b,w,P;let e=null,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},n=t.at(-1).data;if(!n)return o;let r;for(let I of t){if(I.data.choices.length===0)continue;let A=I.data.choices[0].delta;A.content&&(e=`${e||""}${A.content||""}`);let R=(i=A.toolCalls)==null?void 0:i[0];if(R){r=r||[];let S=r.at(-1);if(!S||R.id){r.push({id:R.id||"",type:R.type||"function",function:{name:((l=R.function)==null?void 0:l.name)||"",arguments:((c=R.function)==null?void 0:c.arguments)||""}});continue}S.function.name=`${S.function.name}${((p=R.function)==null?void 0:p.name)||""}`,S.function.arguments=`${S.function.arguments}${((m=R.function)==null?void 0:m.arguments)||""}`}}let s=t[0].data.choices.at(0);return o.choices.push({finish_reason:(g=s==null?void 0:s.finish_reason)!=null?g:"stop",index:(_=s==null?void 0:s.index)!=null?_:0,logprobs:(b=s==null?void 0:s.logprobs)!=null?b:null,message:{role:"assistant",content:e,tool_calls:r||void 0,refusal:(w=s==null?void 0:s.delta.refusal)!=null?w:null}}),o.id=n.id,o.model=n.model,o.created=n.created,o.usage=(P=n.usage)!=null?P:void 0,o},me=t=>{let e={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},o=[],n=null,r="",s="",i="",l="";for(let c of t)if("contentBlockStart"in c){let p=c.contentBlockStart;if("start"in p&&"toolUse"in p.start){let m=p.start.toolUse;n={toolUse:{toolUseId:m.toolUseId,name:m.name}},r=""}}else if("contentBlockDelta"in c){let p=c.contentBlockDelta.delta;if("text"in p)s+=p.text;else if("reasoningContent"in p){let m=p.reasoningContent;"text"in m?l+=m.text:"signature"in m&&(i+=m.signature)}else if("toolUse"in p&&"input"in p.toolUse){let m=p.toolUse.input;if(r+=m,!m.trim())continue}}else if("contentBlockStop"in c)if(n&&r){try{n.toolUse.input=JSON.parse(r)}catch(p){n.toolUse.input={}}o.push(n),n=null,r=""}else s?(o.push({text:s}),s=""):l&&i&&(o.push({reasoningContent:{reasoningText:{text:l,signature:i}}}),l="",i="");else if("messageStop"in c)e.stopReason=c.messageStop.stopReason;else if("metadata"in c){let p=c.metadata;e.usage=(p==null?void 0:p.usage)||{},e.metrics=(p==null?void 0:p.metrics)||{}}return e.output.message={role:"assistant",content:o},e},ro=(t,e,o,n)=>{var i,l;let r=h({},n),s=[];if(t){let c={text:t,thought:!0};s.push(c)}if(e){let c={text:e,thought:null};s.push(c)}for(let c of o){let p={function_call:c};s.push(p)}return s.length>0&&((l=(i=r.candidates)==null?void 0:i[0])!=null&&l.content)&&(r.candidates[0].content.parts=s),r},fe=t=>{var s,i;let{GenerateContentResponse:e}=it("@google/genai");if(!t.length)return new e;let o="",n="",r=[];for(let l of t)if(l.candidates&&((i=(s=l.candidates[0])==null?void 0:s.content)!=null&&i.parts))for(let c of l.candidates[0].content.parts)c.text?c.thought===!0?o+=c.text:n+=c.text:c.functionCall&&r.push(c.functionCall);return ro(o,n,r,t[t.length-1])},so=t=>fe(t),io=t=>fe(t),_e=(t,e="openai.chat.completions.create")=>{if(e==="openai.responses.create"||e==="openai.AzureOpenAI.responses.create")return xt(t);if("completion"in t[0])return t.reduce((o,n)=>D(h({},n),{completion:`${o.completion}${n.completion}`}),{});if(e==="anthropic.messages.create")return Gt(t);if("text"in t[0].choices[0]){let o="";for(let r of t)o=`${o}${r.choices[0].text}`;let n=structuredClone(t.at(-1));return n.choices[0].text=o,n}if("delta"in t[0].choices[0]){let o=Mt(t);return o.choices[0]=h(h({},o.choices[0]),o.choices[0].message),o}return""},ao=(t,e)=>{let o=e.model.provider,n=e.model.name;return o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&n.startsWith("claude")?ie(t,e):o==="google"||o==="vertexai"&&n.startsWith("gemini")?ae(t,e):o==="amazon.bedrock"?pe(t,e):o==="mistral"?Wt(t.data,e):o==="openai"||o==="openai.azure"?(e.model.api_type||"chat-completions")==="responses"?ce(t,e):Wt(t,e):null};function ye(t,e,o,n){return It(this,null,function*(){let r={request_id:null,raw_response:null,prompt_blueprint:null},s={},i=n.model.provider;i=="amazon.bedrock"&&(s=t==null?void 0:t.$metadata,t=t==null?void 0:t.stream);let l=[];try{for(var m=At(t),g,_,b;g=!(_=yield new v(m.next())).done;g=!1){let w=_.value;l.push(w),r.raw_response=w,r.prompt_blueprint=ao(w,n),yield r}}catch(_){b=[_]}finally{try{g&&(_=m.return)&&(yield new v(_.call(m)))}finally{if(b)throw b[0]}}let c=o(l);i==="amazon.bedrock"&&(c.ResponseMetadata=s);let p=yield new v(e({request_response:c}));r.request_id=p.request_id,r.prompt_blueprint=p.prompt_blueprint,yield r})}var he={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:Mt},completion:{function_name:"openai.completions.create",stream_function:le}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:xt},completion:{function_name:"openai.responses.create",stream_function:xt}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:Gt},completion:{function_name:"anthropic.completions.create",stream_function:ue}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:Mt},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:le}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:xt},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:xt}},google:{chat:{function_name:"google.convo.send_message",stream_function:so},completion:{function_name:"google.model.generate_content",stream_function:io}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:me},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:me}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:Gt},completion:{function_name:"anthropic.completions.create",stream_function:ue}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:no},completion:{function_name:"",stream_function:null}}};var Re="1.0.60",uo=()=>{var t;if(typeof process!="undefined"&&((t=process.versions)!=null&&t.node)){let e=process.versions.node.split(".");return`${e[0]}.${e[1]}`}return"unknown"},mo=uo(),fo=`promptlayer-js/${Re} (node ${mo})`,$=()=>({"User-Agent":fo,"X-SDK-Version":Re}),Kt="SET_WORKFLOW_COMPLETE";function _o(t,e,o,n){return y(this,null,function*(){let r=yield q(`${t}/workflow-version-execution-results?workflow_version_execution_id=${e}&return_all_outputs=${o}`,h({headers:n},$()));if(!r.ok)throw new Error("Failed to fetch final output");return r.json()})}function be(t,e,o,n,r){return function(s){return y(this,null,function*(){if(s.name===Kt)try{let i=JSON.parse(s.data),l=i.result_code,c;if(l==="OK"||l==null)c=i.final_output;else if(l==="EXCEEDS_SIZE_LIMIT")c=yield _o(t,o,n,r),e.resolve(c);else throw new Error(`Unsupported final output code: ${l}`);e.resolve(c)}catch(i){e.reject(i)}})}}function yo(l){return y(this,arguments,function*({token:t,channelName:e,executionId:o,returnAllOutputs:n,headers:r,timeout:s,baseURL:i}){let c=new co.Realtime(t),p=c.channels.get(e),m={},g=new Promise((b,w)=>{m.resolve=b,m.reject=w}),_=be(i,m,o,n,r);yield p.subscribe(Kt,_);try{return yield new Promise((b,w)=>{let P=setTimeout(()=>{w(new Error("Workflow execution did not complete properly (timeout)"))},s);g.then(I=>{clearTimeout(P),b(I)}).catch(I=>{clearTimeout(P),w(I)})})}finally{console.log("Closing client"),p.unsubscribe(Kt,_),c.close(),console.log("Closed client")}})}var q=(t,e)=>y(null,null,function*(){return lo(()=>y(null,null,function*(){let o=yield fetch(t,e);if(o.status>=500&&o.status<600||o.status===429)throw new Error(`Server error: ${o.status} ${o.statusText}`);return o}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:o=>{console.info(`PromptLayer API request attempt ${o.attemptNumber} failed. ${o.retriesLeft} retries left.`)}})}),we=(t,e,o,n=!0)=>y(null,null,function*(){return o.request_response[Symbol.asyncIterator]!==void 0?go(t,e,o.request_response,o,n):yield Te(t,e,o,n)}),Te=(t,e,o,n=!0)=>y(null,null,function*(){try{let r=yield q(`${e}/track-request`,{method:"POST",headers:h({"Content-Type":"application/json"},$()),body:JSON.stringify(o)}),s=yield r.json();if(r.status!==200){let i=s.message||s.error||"Failed to log request";if(n)throw new Error(i);Y(s,"WARNING: While logging your request, PromptLayer experienced the following error:")}if(s&&o.return_pl_id)return[o.request_response,s.request_id]}catch(r){if(n)throw r;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${r}`)}return o.request_response}),Ee=(t,e,o,n=!0)=>y(null,null,function*(){try{let r=yield q(`${e}/library-track-metadata`,{method:"POST",headers:h({"Content-Type":"application/json"},$()),body:JSON.stringify(D(h({},o),{api_key:t}))}),s=yield r.json();if(r.status!==200){let i=s.message||s.error||"Failed to track metadata";if(n)throw new Error(i);return Y(s,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(r){if(n)throw r;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${r}`),!1}return!0}),xe=(t,e,o,n=!0)=>y(null,null,function*(){try{let r=yield q(`${e}/library-track-score`,{method:"POST",headers:h({"Content-Type":"application/json"},$()),body:JSON.stringify(D(h({},o),{api_key:t}))}),s=yield r.json();if(r.status!==200){let i=s.message||s.error||"Failed to track score";if(n)throw new Error(i);return Y(s,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}}catch(r){if(n)throw r;return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${r}`),!1}return!0}),Oe=(t,e,o,n=!0)=>y(null,null,function*(){try{let r=yield q(`${e}/library-track-prompt`,{method:"POST",headers:h({"Content-Type":"application/json"},$()),body:JSON.stringify(D(h({},o),{api_key:t}))}),s=yield r.json();if(r.status!==200){let i=s.message||s.error||"Failed to track prompt";if(n)throw new Error(i);return Y(s,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(r){if(n)throw r;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${r}`),!1}return!0}),Pe=(t,e,o,n=!0)=>y(null,null,function*(){try{let r=yield q(`${e}/track-group`,{method:"POST",headers:h({"Content-Type":"application/json"},$()),body:JSON.stringify(D(h({},o),{api_key:t}))}),s=yield r.json();if(r.status!==200){let i=s.message||s.error||"Failed to track group";if(n)throw new Error(i);return Y(s,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(r){if(n)throw r;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${r}`),!1}return!0}),Se=(t,e,o=!0)=>y(null,null,function*(){try{let n=yield q(`${e}/create-group`,{method:"POST",headers:h({"Content-Type":"application/json"},$()),body:JSON.stringify({api_key:t})}),r=yield n.json();if(n.status!==200){let s=r.message||r.error||"Failed to create group";if(o)throw new Error(s);return Y(r,"WARNING: While creating a group PromptLayer had the following error"),!1}return r.id}catch(n){if(o)throw n;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${n}`),!1}}),Ie=(t,e,o,n,r=!0)=>y(null,null,function*(){try{let s=new URL(`${e}/prompt-templates/${o}`),i=yield q(s,{method:"POST",headers:h({"Content-Type":"application/json","X-API-KEY":t},$()),body:JSON.stringify(n)}),l=yield i.json();if(i.status!==200){let c=l.message||l.error||"Failed to fetch prompt template";if(r)throw new Error(c);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${c}`),null}return l.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${l.warning}`),l}catch(s){if(r)throw s;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${s}`),null}}),Ae=(t,e,o,n=!0)=>y(null,null,function*(){let r=yield q(`${e}/rest/prompt-templates`,{method:"POST",headers:h({"Content-Type":"application/json","X-API-KEY":t},$()),body:JSON.stringify({prompt_template:h({},o),prompt_version:h({},o),release_labels:o.release_labels?o.release_labels:void 0})}),s=yield r.json();if(r.status!==200&&r.status!==201){let i=s.message||s.error||"Failed to publish prompt template";if(n)throw new Error(i);Y(s,"WARNING: While publishing a prompt template PromptLayer had the following error")}return s}),Ce=(t,e,o,n=!0)=>y(null,null,function*(){var l;let r=new URL(`${e}/prompt-templates`);Object.entries(o||{}).forEach(([c,p])=>r.searchParams.append(c,p.toString()));let s=yield q(r,{headers:h({"Content-Type":"application/json","X-API-KEY":t},$())}),i=yield s.json();if(s.status!==200){let c=i.message||i.error||"Failed to fetch prompt templates";if(n)throw new Error(c);return Y(i,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(l=i.items)!=null?l:[]}),ho=t=>y(null,null,function*(){let e=new URL(`${t.baseURL}/connection/websocket`);e.protocol=e.protocol==="https:"?"wss:":"ws:";let o=new po(e.toString(),{token:t.token}),n=o.newSubscription(t.channelName);return new Promise((r,s)=>{let i=m=>{p(),r(m)},l=be(t.baseURL,{resolve:i,reject:s},t.executionId,t.returnAllOutputs,t.headers);n.on("publication",m=>{l({name:m.data.message_name,data:m.data.data})});let c=setTimeout(()=>{s(new Error("Workflow execution did not complete properly (timeout)"))},t.timeout),p=()=>{clearTimeout(c),n.unsubscribe(),o.disconnect()};n.on("error",m=>{p(),s(`Centrifugo subscription error: ${m}`)}),o.on("error",m=>{p(),s(`Centrifugo client error: ${m}`)}),n.subscribe(),o.connect()})}),ke=p=>y(null,[p],function*({workflow_name:t,input_variables:e,metadata:o={},workflow_label_name:n=null,workflow_version_number:r=null,return_all_outputs:s=!1,api_key:i,timeout:l=36e5,baseURL:c}){let m={input_variables:e,metadata:o,workflow_label_name:n,workflow_version_number:r,return_all_outputs:s},g=h({"Content-Type":"application/json","X-API-KEY":i},$());try{let _=yield q(`${c}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:g,body:JSON.stringify(m)});if(_.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield _.json().catch(()=>({}))).error||_.statusText}`};let b=yield _.json();b.warning&&console.warn(`WARNING: ${b.warning}`);let w=b.workflow_version_execution_id;if(!w)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let P=`workflow_updates:${w}`,A=yield(yield q(`${c}/ws-token-request-library?capability=${P}`,{method:"POST",headers:g})).json(),S={token:A.token_details.token,channelName:P,executionId:w,returnAllOutputs:s,headers:g,timeout:l,baseURL:c};return A.messaging_backend==="centrifugo"?ho(S):yield yo(S)}catch(_){throw console.error(`Failed to run workflow: ${_ instanceof Error?_.message:_}`),_}});function go(t,e,o,n,r=!0){return It(this,null,function*(){let s=[];try{for(var c=At(o),p,m,g;p=!(m=yield new v(c.next())).done;p=!1){let _=m.value;yield n.return_pl_id?[_,null]:_,s.push(_)}}catch(m){g=[m]}finally{try{p&&(m=c.return)&&(yield new v(m.call(c)))}finally{if(g)throw g[0]}}let i=_e(s,n.function_name),l=yield new v(Te(t,e,D(h({},n),{request_response:i,request_end_time:new Date().toISOString()}),r));if(l&&n.return_pl_id){let _=l[1];yield[s.at(-1),_]}})}var Y=(t,e)=>{try{console.warn(`${e}: ${t.message}`)}catch(o){console.warn(`${e}: ${t}`)}},Ne=(t,e,o=!0)=>y(null,null,function*(){try{let n=yield q(`${t}/track-request`,{method:"POST",headers:h({"Content-Type":"application/json"},$()),body:JSON.stringify(e)}),r=yield n.json();if(n.status!==200){let s=r.message||r.error||"Failed to track request";if(o)throw new Error(s);Y(r,"WARNING: While logging your request, PromptLayer experienced the following error:")}return r}catch(n){if(o)throw n;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${n}`)}return{}}),Ro=(t,e)=>y(null,null,function*(){return yield t.chat.completions.create(e)}),bo=(t,e)=>y(null,null,function*(){return yield t.completions.create(e)}),Le={chat:Ro,completion:bo},Ue=(t,e)=>y(null,null,function*(){var s,i;let o=it("openai").default,n=new o({baseURL:e.baseURL,apiKey:e.apiKey});if(e==null||delete e.apiKey,e==null||delete e.baseURL,((i=(s=t.metadata)==null?void 0:s.model)==null?void 0:i.api_type)==="chat-completions"){let l=Le[t.prompt_template.type];return yield l(n,e)}else return yield n.responses.create(e)}),qe=(t,e)=>y(null,null,function*(){var s,i;let{AzureOpenAI:o}=it("openai"),n=new o({endpoint:process.env.AZURE_OPENAI_ENDPOINT||e.baseURL,apiVersion:process.env.OPENAI_API_VERSION||e.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||e.apiKey});if(e==null||delete e.baseURL,e==null||delete e.apiVersion,e==null||delete e.apiKey,((i=(s=t.metadata)==null?void 0:s.model)==null?void 0:i.api_type)==="chat-completions"){let l=Le[t.prompt_template.type];return yield l(n,e)}else return yield n.responses.create(e)}),$e=(t,e)=>y(null,null,function*(){return t.messages.create(e)}),wo=(t,e)=>y(null,null,function*(){return t.completions.create(e)}),We={chat:$e,completion:wo},Me=(t,e)=>y(null,null,function*(){let o=it("@anthropic-ai/sdk").default,n=new o({baseURL:e.baseURL,apiKey:e.apiKey}),r=We[t.prompt_template.type];return r(n,e)}),Ge=(t,e,o,n=!0)=>y(null,null,function*(){try{let r=yield q(`${e}/log-request`,{method:"POST",headers:h({"Content-Type":"application/json","X-API-KEY":t},$()),body:JSON.stringify(o)}),s=yield r.json();if(r.status!==201){let i=s.message||s.error||"Failed to log request";if(n)throw new Error(i);return Y(s,"WARNING: While logging your request PromptLayer had the following error"),null}return s}catch(r){if(n)throw r;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${r}`),null}}),To=(t,e)=>y(null,null,function*(){var i,l;let o=e==null?void 0:e.history,n=e==null?void 0:e.generationConfig,r=o.length>0?(i=o[o.length-1])==null?void 0:i.parts:"",s=t.chats.create({model:e==null?void 0:e.model,history:(l=o.slice(0,-1))!=null?l:[],config:n});return e!=null&&e.stream?yield s.sendMessageStream({message:r}):yield s.sendMessage({message:r})}),Eo=(t,n)=>y(null,null,function*(){var r=n,{stream:e}=r,o=St(r,["stream"]);return e?yield t.generateContentStream(h({},o)):yield t.generateContent(h({},o))}),xo={chat:To,completion:Eo},jt=(t,e)=>y(null,null,function*(){let{GoogleGenAI:o}=yield import("@google/genai"),n=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,r=process.env.VERTEX_AI_PROJECT_ID||process.env.GOOGLE_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT,s=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,i={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:r,scopes:["https://www.googleapis.com/auth/cloud-platform"]},l=n?new o({apiKey:n}):new o({vertexai:!0,project:r,location:s,googleAuthOptions:i}),c=xo[t.prompt_template.type];return yield c(l,e)}),ge=t=>t.replace(/_([a-z])/g,(e,o)=>o.toUpperCase()),Ct=(t,e=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(o=>Ct(o,e)):Object.fromEntries(Object.entries(t).map(([o,n])=>e.has(o)?[ge(o),n]:[ge(o),Ct(n,e)])),Ke=(t,e,o={},n=!1)=>{var c,p,m,g,_,b,w,P,I;let r=(m=e==null?void 0:e.client)!=null?m:(p=(c=t.metadata)==null?void 0:c.model)==null?void 0:p.provider,s=(_=(g=t.metadata)==null?void 0:g.model)==null?void 0:_.api_type;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let i=D(h({},t.llm_kwargs||{}),{stream:n});["google","vertexai"].includes(r)&&((w=(b=t.metadata)==null?void 0:b.model)!=null&&w.name.startsWith("gemini"))&&(i=Ct(i,new Set(["function_declarations","properties"])));let l={baseURL:(I=e==null?void 0:e.base_url)!=null?I:(P=t.provider_base_url)==null?void 0:P.url,apiKey:e==null?void 0:e.api_key};return Object.entries(l).forEach(([A,R])=>{R!==void 0&&(i[A]=R)}),n&&de.includes(r)&&s==="chat-completions"&&(i.stream_options={include_usage:!0}),{provider_type:r,kwargs:i}},je=(t,e)=>{let o=he[t];if(!o)throw new Error(`Unsupported provider type: ${t}`);let n=e.type,r=o[n];if(!r)throw new Error(`Unsupported template type '${e.type}' for provider '${t}'`);return r},De=(t,e)=>y(null,null,function*(){var n;let o=(n=t.metadata)==null?void 0:n.model;if(!o)throw new Error("Model metadata not found in prompt blueprint");if(o.name.startsWith("gemini"))return jt(t,e);if(o.name.startsWith("claude")){let{AnthropicVertex:r}=yield import("@anthropic-ai/vertex-sdk"),s=new r({baseURL:e.baseURL});if(t.prompt_template.type==="chat")return $e(s,e);throw new Error(`Unsupported prompt template type '${t.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${o.name}' for Vertex AI request`)}),Fe=(t,e)=>y(null,null,function*(){let{BedrockRuntimeClient:o,ConverseCommand:n,ConverseStreamCommand:r}=yield import("@aws-sdk/client-bedrock-runtime"),s=new o({credentials:{accessKeyId:(e==null?void 0:e.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(e==null?void 0:e.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(e==null?void 0:e.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(e==null?void 0:e.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(e!=null&&e.stream){delete e.stream;let i=new r(h({},e));return yield s.send(i)}else{e==null||delete e.stream;let i=new n(h({},e));return yield s.send(i)}}),Be=(t,e)=>y(null,null,function*(){let{AnthropicBedrock:o}=yield import("@anthropic-ai/bedrock-sdk"),n=new o({awsAccessKey:e.aws_access_key,awsSecretKey:e.aws_secret_key,awsRegion:e.aws_region,awsSessionToken:e.aws_session_token,baseURL:e.base_url}),r=We[t.prompt_template.type];return r(n,e)}),Ve=(t,e)=>y(null,null,function*(){let{Mistral:o}=yield import("@mistralai/mistralai"),n=new o({apiKey:process.env.MISTRAL_API_KEY});return e=Ct(e,new Set),e!=null&&e.stream?(delete e.stream,yield n.chat.stream(e)):(delete e.stream,yield n.chat.complete(e))}),Dt=t=>{var e,o,n,r,s,i;if(typeof globalThis.process!="undefined")return(n=(o=(e=globalThis.process.env)==null?void 0:e[t])==null?void 0:o.trim())!=null?n:void 0;if(typeof globalThis.Deno!="undefined")return(i=(s=(r=globalThis.Deno.env)==null?void 0:r.get)==null?void 0:s.call(r,t))==null?void 0:i.trim()};var kt=class{constructor(e,o,n=!0){this.create=()=>Se(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=e,this.baseURL=o,this.throwOnError=n}};import{SpanKind as Ot,SpanStatusCode as Ft}from"@opentelemetry/api";import{ExportResultCode as Nt}from"@opentelemetry/core";var Bt=class{constructor(e,o,n){this.apiKey=o,this.baseURL=n,this.enableTracing=e,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(e){return e?Object.fromEntries(Object.entries(e)):{}}spanKindToString(e){return{[Ot.INTERNAL]:"SpanKind.INTERNAL",[Ot.SERVER]:"SpanKind.SERVER",[Ot.CLIENT]:"SpanKind.CLIENT",[Ot.PRODUCER]:"SpanKind.PRODUCER",[Ot.CONSUMER]:"SpanKind.CONSUMER"}[e]||"SpanKind.INTERNAL"}statusCodeToString(e){return{[Ft.ERROR]:"StatusCode.ERROR",[Ft.OK]:"StatusCode.OK",[Ft.UNSET]:"StatusCode.UNSET"}[e]||"StatusCode.UNSET"}toNanoseconds(e){return(BigInt(e[0])*BigInt(1e9)+BigInt(e[1])).toString()}export(e){if(!this.enableTracing)return Promise.resolve(Nt.SUCCESS);let o=e.map(n=>{var r;return{name:n.name,context:{trace_id:n.spanContext().traceId,span_id:n.spanContext().spanId,trace_state:((r=n.spanContext().traceState)==null?void 0:r.serialize())||""},kind:this.spanKindToString(n.kind),parent_id:n.parentSpanId||null,start_time:this.toNanoseconds(n.startTime),end_time:this.toNanoseconds(n.endTime),status:{status_code:this.statusCodeToString(n.status.code),description:n.status.message},attributes:this.attributesToObject(n.attributes),events:n.events.map(s=>({name:s.name,timestamp:this.toNanoseconds(s.time),attributes:this.attributesToObject(s.attributes)})),links:n.links.map(s=>({context:s.context,attributes:this.attributesToObject(s.attributes)})),resource:{attributes:D(h({},n.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return q(this.url,{method:"POST",headers:h({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},$()),body:JSON.stringify({spans:o})}).then(n=>n.ok?Nt.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
-
HTTP error! status: ${
|
|
1
|
+
var Do=Object.defineProperty,Fo=Object.defineProperties;var Bo=Object.getOwnPropertyDescriptors;var He=Object.getOwnPropertySymbols;var Gn=Object.prototype.hasOwnProperty,Kn=Object.prototype.propertyIsEnumerable;var ln=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t);var $n=(t,n,e)=>n in t?Do(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e,E=(t,n)=>{for(var e in n||(n={}))Gn.call(n,e)&&$n(t,e,n[e]);if(He)for(var e of He(n))Kn.call(n,e)&&$n(t,e,n[e]);return t},Y=(t,n)=>Fo(t,Bo(n));var Tt=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(n,e)=>(typeof require!="undefined"?require:n)[e]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Xe=(t,n)=>{var e={};for(var o in t)Gn.call(t,o)&&n.indexOf(o)<0&&(e[o]=t[o]);if(t!=null&&He)for(var o of He(t))n.indexOf(o)<0&&Kn.call(t,o)&&(e[o]=t[o]);return e};var S=(t,n,e)=>new Promise((o,r)=>{var i=u=>{try{d(e.next(u))}catch(_){r(_)}},l=u=>{try{d(e.throw(u))}catch(_){r(_)}},d=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,l);d((e=e.apply(t,n)).next())}),_t=function(t,n){this[0]=t,this[1]=n},Ze=(t,n,e)=>{var o=(l,d,u,_)=>{try{var m=e[l](d),b=(d=m.value)instanceof _t,R=m.done;Promise.resolve(b?d[0]:d).then(x=>b?o(l==="return"?l:"next",d[1]?{done:x.done,value:x.value}:x,u,_):u({value:x,done:R})).catch(x=>o("throw",x,u,_))}catch(x){_(x)}},r=l=>i[l]=d=>new Promise((u,_)=>o(l,d,u,_)),i={};return e=e.apply(t,n),i[ln("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var Qe=(t,n,e)=>(n=t[ln("asyncIterator")])?n.call(t):(t=t[ln("iterator")](),n={},e=(o,r)=>(r=t[o])&&(n[o]=i=>new Promise((l,d,u)=>(i=r.call(t,i),u=i.done,Promise.resolve(i.value).then(_=>l({value:_,done:u}),d)))),e("next"),e("return"),n);import ns from"ably";import{Centrifuge as os}from"centrifuge";import ss from"p-retry";var Dn={png:"image/png",webp:"image/webp",jpeg:"image/jpeg",jpg:"image/jpeg",gif:"image/gif",url:"image/png"},st=(t,n,e,o)=>E({id:t,type:"function",function:{name:n,arguments:typeof e=="string"?e:JSON.stringify(e)}},o?{tool_id:o}:{}),y=o=>{var r=o,{type:t,item_id:n}=r,e=Xe(r,["type","item_id"]);let i=E({type:t},e);return n&&(i.id=n),i},Et=(t,n)=>({role:"assistant",input_variables:[],template_format:"f-string",content:t,tool_calls:n}),Ot=(t,n)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:n});function Fn(t){var n,e,o,r;return E(E({type:"url_citation",url:(n=t.url)!=null?n:"",title:(e=t.title)!=null?e:"",start_index:(o=t.start_index)!=null?o:0,end_index:(r=t.end_index)!=null?r:0},t.cited_text!=null?{cited_text:t.cited_text}:{}),t.encrypted_index!=null?{encrypted_index:t.encrypted_index}:{})}var zn=(t,n,e)=>{var l,d,u,_,m,b,R,x,O,T,h,w,f,g,I,M,W,C,N,j,q,B,$,X,K,Z,J,rt,at,D,nt,it,mt,ft,gt,yt,ht,bt,Rt,xt;let o=[],r=[];if(Array.isArray(t.content)){for(let L of t.content){if(!L||typeof L!="object")continue;let V=L.type;if(V==="text"){let v=(l=L.text)!=null?l:"",lt=(u=(d=L.citations)!=null?d:L.annotations)!=null?u:[],tt=[];for(let et of lt)et&&typeof et=="object"&&tt.push(Fn(et));o.push(y(E({type:"text",text:v},tt.length>0?{annotations:tt}:{})))}else if(V==="thinking")o.push(y({type:"thinking",thinking:(_=L.thinking)!=null?_:"",signature:(m=L.signature)!=null?m:""}));else if(V==="tool_use")r.push(st((b=L.id)!=null?b:"",(R=L.name)!=null?R:"",(x=L.input)!=null?x:{}));else if(V==="server_tool_use")o.push(y({type:"server_tool_use",id:(O=L.id)!=null?O:"",name:(T=L.name)!=null?T:"",input:(h=L.input)!=null?h:{}}));else if(V==="web_search_tool_result"){let v=(w=L.content)!=null?w:[],lt=[];for(let tt of v)if(tt&&typeof tt=="object"&&tt.type==="web_search_result"){let et=tt;lt.push({type:"web_search_result",url:et.url,title:et.title,encrypted_content:et.encrypted_content,page_age:et.page_age})}o.push(y({type:"web_search_tool_result",tool_use_id:(f=L.tool_use_id)!=null?f:"",content:lt}))}else V==="bash_code_execution_tool_result"&&o.push(y({type:"bash_code_execution_tool_result",tool_use_id:(g=L.tool_use_id)!=null?g:"",content:(I=L.content)!=null?I:{}}))}let ot=Et(o,r);return Ot(ot,n)}if(t.type==="content_block_start")if(((M=t.content_block)==null?void 0:M.type)==="thinking")o.push(y({type:"thinking",thinking:"",signature:""}));else if(((W=t.content_block)==null?void 0:W.type)==="text")o.push(y({type:"text",text:""}));else if(((C=t.content_block)==null?void 0:C.type)==="tool_use")r.push(st((N=t.content_block.id)!=null?N:"",(j=t.content_block.name)!=null?j:"",{}));else if(((q=t.content_block)==null?void 0:q.type)==="server_tool_use")o.push(y({type:"server_tool_use",id:(B=t.content_block.id)!=null?B:"",name:($=t.content_block.name)!=null?$:"",input:(X=t.content_block.input)!=null?X:{}}));else if(((K=t.content_block)==null?void 0:K.type)==="web_search_tool_result"){let ot=(Z=t.content_block.content)!=null?Z:[],L=[];for(let V of ot)if(V&&typeof V=="object"&&V.type==="web_search_result"){let v=V;L.push({type:"web_search_result",url:v.url,title:v.title,encrypted_content:v.encrypted_content,page_age:v.page_age})}o.push(y({type:"web_search_tool_result",tool_use_id:(J=t.content_block.tool_use_id)!=null?J:"",content:L}))}else((rt=t.content_block)==null?void 0:rt.type)==="bash_code_execution_tool_result"&&o.push(y({type:"bash_code_execution_tool_result",tool_use_id:(at=t.content_block.tool_use_id)!=null?at:"",content:(D=t.content_block.content)!=null?D:{}}));else if(t.type==="content_block_delta"){if(((nt=t.delta)==null?void 0:nt.type)==="thinking_delta")o.push(y({type:"thinking",thinking:(it=t.delta.thinking)!=null?it:"",signature:""}));else if(((mt=t.delta)==null?void 0:mt.type)==="text_delta")o.push(y({type:"text",text:(ft=t.delta.text)!=null?ft:""}));else if(((gt=t.delta)==null?void 0:gt.type)==="signature_delta")o.push(y({type:"thinking",thinking:"",signature:(yt=t.delta.signature)!=null?yt:""}));else if(((ht=t.delta)==null?void 0:ht.type)==="input_json_delta")(e==null?void 0:e[t.index])==="server_tool_use"?o.push(y({type:"server_tool_use",id:"",name:"",input:(bt=t.delta.partial_json)!=null?bt:{}})):r.push(st("","",(Rt=t.delta.partial_json)!=null?Rt:""));else if(((xt=t.delta)==null?void 0:xt.type)==="citations_delta"&&t.delta.citation){let ot=t.delta.citation,L=[Fn(ot)];o.push(y({type:"text",text:"",annotations:L}))}}let i=Et(o,r);return Ot(i,n)},zo=t=>typeof t=="string"&&t.startsWith("image/");function Bn(t){var e,o,r,i;let n=t.web;return n&&typeof n=="object"?{uri:(e=n.uri)!=null?e:"",title:(o=n.title)!=null?o:""}:{uri:(r=t.uri)!=null?r:"",title:(i=t.title)!=null?i:""}}function Vo(t){if(!t||typeof t!="object")return;let n=t.content,e=n==null?void 0:n.parts;if(!Array.isArray(e))return;let o=[];for(let r of e)r&&typeof r=="object"&&typeof r.text=="string"&&o.push(r.text);return o.length>0?o.join(""):void 0}function Jo(t){var o,r,i,l;if(!t||typeof t!="object")return[];let n=(o=t.citations)!=null?o:[],e=[];for(let d of n){if(!d||typeof d!="object")continue;let u=(r=d.uri)!=null?r:"";if(!u)continue;let _=(i=d.startIndex)!=null?i:0,m=(l=d.endIndex)!=null?l:0;e.push({type:"url_citation",url:u,title:u,start_index:_,end_index:m})}return e}function Yo(t,n){if(!t||typeof t!="object")return[];let e=t.groundingMetadata,o=t.citationMetadata,r=Ho(e,n),i=Jo(o);return[...r,...i]}function Ho(t,n){var d,u,_,m,b,R,x,O,T;let e=t&&typeof t=="object"?(d=t.groundingChunks)!=null?d:[]:[],o=t&&typeof t=="object"?(u=t.groundingSupports)!=null?u:[]:[];function r(h,w,f){let g=h.text;if(g!=null&&g!=="")return g;if(n!=null&&f>w)return n.slice(w,f)||void 0}if(o.length>0&&e.length>0){let h=[],w=new Set;for(let f of o){if(!f||typeof f!="object")continue;let g=(_=f.segment)!=null?_:{},I=(m=f.groundingChunkIndices)!=null?m:[],M=(b=g.startIndex)!=null?b:0,W=(R=g.endIndex)!=null?R:0,C=r(g,M,W);for(let N of I){if(typeof N!="number"||N>=e.length)continue;let j=e[N];if(!j||typeof j!="object")continue;let q=j.maps;if(q&&typeof q=="object"){let K=(x=q.uri)!=null?x:"",Z=(O=q.title)!=null?O:"",J=q.placeId;(K||Z)&&h.push(E(Y(E({type:"map_citation",url:K,title:Z||K},J!=null?{place_id:J}:{}),{start_index:M,end_index:W}),C!=null?{cited_text:C}:{}));continue}let B=j.retrievedContext;if(B&&typeof B=="object"){let K=(T=B.title)!=null?T:"";K&&!w.has(K)&&(w.add(K),h.push({type:"file_citation",file_id:K,filename:K,index:N}));continue}let{uri:$,title:X}=Bn(j);$&&h.push(E({type:"url_citation",url:$,title:X||$,start_index:M,end_index:W},C!=null?{cited_text:C}:{}))}}return h}if(!t||typeof t!="object")return[];let i=[],l=new Set;return e.forEach((h,w)=>{var C,N,j;if(!h||typeof h!="object")return;let f=h,g=f.maps;if(g&&typeof g=="object"){let q=(C=g.uri)!=null?C:"",B=(N=g.title)!=null?N:"",$=g.placeId;(q||B)&&i.push(Y(E({type:"map_citation",url:q,title:B||q},$!=null?{place_id:$}:{}),{start_index:0,end_index:0}));return}let I=f.retrievedContext;if(I&&typeof I=="object"){let q=(j=I.title)!=null?j:"";q&&!l.has(q)&&(l.add(q),i.push({type:"file_citation",file_id:q,filename:q,index:w}));return}let{uri:M,title:W}=Bn(f);M&&i.push({type:"url_citation",url:M,title:W||M,start_index:0,end_index:0})}),i}var Vn=(t,n)=>{var u,_,m,b,R,x,O,T,h;let e=[],o=[];for(let w of(u=t.candidates)!=null?u:[])if(w.content&&w.content.parts&&Array.isArray(w.content.parts))for(let f of w.content.parts)if(f.text!=null)f.thought===!0?e.push(y({type:"thinking",thinking:f.text,signature:(_=f.thoughtSignature)!=null?_:""})):e.push(y(E({type:"text",text:f.text},f.thoughtSignature?{thought_signature:f.thoughtSignature}:{})));else if(f.functionCall)o.push(st(f.functionCall.id||"",f.functionCall.name||"",f.functionCall.args||{}));else if(f.executableCode){let g=f.executableCode;e.push(y(E({type:"code",code:(m=g.code)!=null?m:""},g.language!=null?{language:g.language}:{})))}else if(f.codeExecutionResult){let g=f.codeExecutionResult;e.push(y({type:"code_execution_result",output:(b=g.output)!=null?b:"",outcome:(R=g.outcome)!=null?R:"OUTCOME_OK"}))}else{let g=f.inlineData;if(g&&f.thought!==!0){let I=(x=g.mimeType)!=null?x:"image/png",M=(O=g.data)!=null?O:"";if(zo(I)&&M){let W={};f.thoughtSignature&&(W.thought_signature=f.thoughtSignature),f.aspectRatio!=null&&(W.aspect_ratio=f.aspectRatio),f.imageSize!=null&&(W.image_size=f.imageSize),e.push(y(E({type:"output_media",url:M,mime_type:I,media_type:"image"},Object.keys(W).length?{provider_metadata:W}:{})))}}}let r=(T=t.candidates)==null?void 0:T[0],i=Vo(r),l=Yo(r,i);if(l.length>0)for(let w=0;w<e.length;w++){let f=e[w];if(f&&typeof f=="object"&&f.type==="text"){let g=(h=f.annotations)!=null?h:[];e[w]=Y(E({},f),{annotations:[...g,...l]})}}let d=Et(e,o);return Ot(d,n)},cn=(t,n)=>{let e=[],o=[];for(let i of t.choices)if(i.delta){i.delta.content&&e.push(y({type:"text",text:i.delta.content}));let l=i.delta.tool_calls||i.delta.toolCalls;if(l&&Array.isArray(l))for(let d of l)d.function&&o.push(st(d.id||"",d.function.name||"",d.function.arguments||""))}let r=Et(e,o);return Ot(r,n)},Jn=(t,n)=>{var l,d,u,_,m,b,R,x,O,T,h,w,f,g,I,M,W,C,N,j,q,B,$,X,K,Z,J,rt,at,D,nt,it,mt,ft,gt,yt,ht,bt,Rt,xt,ot,L,V,v,lt,tt,et,Pt,kt,St,Ct,It,Nt,qt,Lt,Mt,Ut,Wt,jt,$t,Gt,Kt,Dt,Ft,Bt,zt,Vt,Jt,Yt,Ht,Xt,Zt,Qt,vt,te,ee,ne,oe,se,re,ae,ie,le,ce,pe,ue,de,_e,me,fe,ge,ye,he,be,Re,xe,we,Te,Ee,Oe,Ae,Pe,ke,Se,Ce,Ie,Ne,qe,Le,Me,Ue,We,je,$e,Ge,Ke,De,Fe,Be,ze,Ve,Je,A,U,a,c,P,ct,bn,Rn,xn,wn,Tn,En,On,An,Pn,kn,Sn,Cn,In,Nn,qn,Ln,Mn,Un,Wn,jn;let e=[],o=[],r=t==null?void 0:t.type;if(r==="response.reasoning_summary_text.delta"){let s=(l=t==null?void 0:t.delta)!=null?l:"",k=(d=t==null?void 0:t.item_id)!=null?d:"";s&&e.push(y({type:"thinking",item_id:k,thinking:s,signature:""}))}else if(r==="response.reasoning_summary_text.done"){let s=(u=t==null?void 0:t.text)!=null?u:"",k=(_=t==null?void 0:t.item_id)!=null?_:"";s&&e.push(y({type:"thinking",item_id:k,thinking:s,signature:""}))}else if(r==="response.reasoning_summary_part.added"){let s=(m=t==null?void 0:t.part)!=null?m:{},k=(b=t==null?void 0:t.item_id)!=null?b:"";if((s==null?void 0:s.type)==="summary_text"){let p=(R=s==null?void 0:s.text)!=null?R:"";e.push(y({type:"thinking",item_id:k,thinking:p,signature:""}))}}else if(r==="response.reasoning_summary_part.done"){let s=(x=t==null?void 0:t.part)!=null?x:{},k=(O=t==null?void 0:t.item_id)!=null?O:"";if((s==null?void 0:s.type)==="summary_text"){let p=(T=s==null?void 0:s.text)!=null?T:"";p&&e.push(y({type:"thinking",item_id:k,thinking:p,signature:""}))}}else if(r==="response.function_call_arguments.delta"){let s=(h=t==null?void 0:t.item_id)!=null?h:"",k=(w=t==null?void 0:t.delta)!=null?w:"";k&&o.push(st("","",k,s))}else if(r==="response.function_call_arguments.done"){let s=(f=t==null?void 0:t.item_id)!=null?f:"",k=(g=t==null?void 0:t.arguments)!=null?g:"";k&&o.push(st("","",k,s))}else if(r==="response.output_item.added"){let s=(I=t==null?void 0:t.item)!=null?I:{},k=s==null?void 0:s.type,p=(M=s==null?void 0:s.id)!=null?M:"";k==="reasoning"?e.push(y({type:"thinking",thinking:"",signature:"",item_id:p})):k==="function_call"?o.push(st((s==null?void 0:s.call_id)||"",(s==null?void 0:s.name)||"","",p)):k==="message"?e.push(y({type:"text",item_id:p,text:""})):k==="code_interpreter_call"?e.push(y({type:"code",item_id:p,code:(W=s==null?void 0:s.code)!=null?W:"",container_id:(C=s==null?void 0:s.container_id)!=null?C:""})):k==="image_generation_call"?e.push(y({type:"output_media",item_id:p,url:"",mime_type:"image/png",media_type:"image"})):k==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:p,server_label:(N=s==null?void 0:s.server_label)!=null?N:"",tools:(j=s==null?void 0:s.tools)!=null?j:[]})):k==="mcp_call"?e.push(y({type:"mcp_call",item_id:p,name:(q=s==null?void 0:s.name)!=null?q:"",server_label:(B=s==null?void 0:s.server_label)!=null?B:"",arguments:($=s==null?void 0:s.arguments)!=null?$:"",output:s==null?void 0:s.output,error:s==null?void 0:s.error,approval_request_id:s==null?void 0:s.approval_request_id})):k==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:p,name:(X=s==null?void 0:s.name)!=null?X:"",arguments:(K=s==null?void 0:s.arguments)!=null?K:"",server_label:(Z=s==null?void 0:s.server_label)!=null?Z:""})):k==="shell_call"?e.push(y({type:"shell_call",item_id:p,call_id:(J=s==null?void 0:s.call_id)!=null?J:"",action:(rt=s==null?void 0:s.action)!=null?rt:{},status:(at=s==null?void 0:s.status)!=null?at:"in_progress"})):k==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:p,call_id:(D=s==null?void 0:s.call_id)!=null?D:"",output:(nt=s==null?void 0:s.output)!=null?nt:[],status:(it=s==null?void 0:s.status)!=null?it:"in_progress"})):k==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:p,call_id:(mt=s==null?void 0:s.call_id)!=null?mt:"",operation:(ft=s==null?void 0:s.operation)!=null?ft:{},status:(gt=s==null?void 0:s.status)!=null?gt:"in_progress"})):k==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(yt=s==null?void 0:s.call_id)!=null?yt:"",output:(ht=s==null?void 0:s.output)!=null?ht:"",status:(bt=s==null?void 0:s.status)!=null?bt:"in_progress"}))}else if(r==="response.content_part.added"){let s=(Rt=t==null?void 0:t.part)!=null?Rt:{},k=(xt=s==null?void 0:s.type)!=null?xt:"output_text",p=(ot=t==null?void 0:t.item_id)!=null?ot:"";k==="output_text"&&e.push(y({type:"text",item_id:p,text:(L=s==null?void 0:s.text)!=null?L:"",annotations:(s==null?void 0:s.annotations)||[]}))}else if(r==="response.content_part.done"){let s=(V=t==null?void 0:t.part)!=null?V:{},k=(v=s==null?void 0:s.type)!=null?v:"output_text",p=(lt=t==null?void 0:t.item_id)!=null?lt:"";k==="output_text"&&e.push(y({type:"text",item_id:p,text:(tt=s==null?void 0:s.text)!=null?tt:"",annotations:(s==null?void 0:s.annotations)||[]}))}else if(r==="response.output_text.annotation.added"){let s=(t==null?void 0:t.annotation)||{},k=s==null?void 0:s.type,p=null;k==="url_citation"?p={type:"url_citation",title:(et=s==null?void 0:s.title)!=null?et:"",url:(Pt=s==null?void 0:s.url)!=null?Pt:"",start_index:(kt=s==null?void 0:s.start_index)!=null?kt:0,end_index:(St=s==null?void 0:s.end_index)!=null?St:0}:k==="file_citation"?p={type:"file_citation",index:(Ct=s==null?void 0:s.index)!=null?Ct:0,file_id:(It=s==null?void 0:s.file_id)!=null?It:"",filename:(Nt=s==null?void 0:s.filename)!=null?Nt:""}:p=s,e.push(y({type:"text",item_id:(qt=t==null?void 0:t.item_id)!=null?qt:"",text:"",annotations:[p]}))}else if(r==="response.code_interpreter_call.in_progress")e.push(y({type:"code",item_id:(Lt=t==null?void 0:t.item_id)!=null?Lt:"",code:(Mt=t==null?void 0:t.code)!=null?Mt:"",container_id:(Ut=t==null?void 0:t.container_id)!=null?Ut:""}));else if(r==="response.code_interpreter_call_code.delta")e.push(y({type:"code",item_id:(Wt=t==null?void 0:t.item_id)!=null?Wt:"",code:(jt=t==null?void 0:t.delta)!=null?jt:"",container_id:($t=t==null?void 0:t.container_id)!=null?$t:""}));else if(r==="response.output_text.delta"){let s=(Gt=t==null?void 0:t.delta)!=null?Gt:"";s&&e.push(y({type:"text",item_id:(Kt=t==null?void 0:t.item_id)!=null?Kt:"",text:s}))}else if(r==="response.output_text.done")e.push(y({type:"text",item_id:(Dt=t==null?void 0:t.item_id)!=null?Dt:"",text:(Ft=t==null?void 0:t.text)!=null?Ft:""}));else if(r==="response.output_item.done"){let s=(Bt=t==null?void 0:t.item)!=null?Bt:{},k=s==null?void 0:s.type,p=(zt=s==null?void 0:s.id)!=null?zt:"";if(k==="reasoning"){let G=((Vt=s==null?void 0:s.summary)!=null?Vt:[]).map(pt=>{var z;return(z=pt==null?void 0:pt.text)!=null?z:""}).join("");e.push(y({type:"thinking",item_id:p,thinking:G,signature:""}))}else if(k==="function_call")o.push(st((s==null?void 0:s.call_id)||"",(s==null?void 0:s.name)||"",(s==null?void 0:s.arguments)||"",p));else if(k==="message"){let F=(Jt=s==null?void 0:s.content)!=null?Jt:[];for(let G of F)(G==null?void 0:G.type)==="output_text"&&e.push(y({type:"text",item_id:p,text:(Yt=G==null?void 0:G.text)!=null?Yt:""}))}else if(k==="code_interpreter_call")e.push(y({type:"code",item_id:p,code:(Ht=s==null?void 0:s.code)!=null?Ht:"",container_id:(Xt=s==null?void 0:s.container_id)!=null?Xt:""}));else if(k==="image_generation_call"){let F=(Zt=s==null?void 0:s.result)!=null?Zt:"",pt=((Qt=s==null?void 0:s.output_format)!=null?Qt:"png")==="webp"?"image/webp":"image/png",z={};for(let dt of["revised_prompt","background","size","quality","output_format"])(s==null?void 0:s[dt])!=null&&(z[dt]=s[dt]);e.push(y(E({type:"output_media",item_id:p,url:F,mime_type:pt,media_type:"image"},Object.keys(z).length?{provider_metadata:z}:{})))}else k==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:p,server_label:(vt=s==null?void 0:s.server_label)!=null?vt:"",tools:(te=s==null?void 0:s.tools)!=null?te:[],error:s==null?void 0:s.error})):k==="mcp_call"?e.push(y({type:"mcp_call",item_id:p,name:(ee=s==null?void 0:s.name)!=null?ee:"",server_label:(ne=s==null?void 0:s.server_label)!=null?ne:"",arguments:(oe=s==null?void 0:s.arguments)!=null?oe:"",output:s==null?void 0:s.output,error:s==null?void 0:s.error,approval_request_id:s==null?void 0:s.approval_request_id})):k==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:p,name:(se=s==null?void 0:s.name)!=null?se:"",arguments:(re=s==null?void 0:s.arguments)!=null?re:"",server_label:(ae=s==null?void 0:s.server_label)!=null?ae:""})):k==="shell_call"?e.push(y({type:"shell_call",item_id:p,call_id:(ie=s==null?void 0:s.call_id)!=null?ie:"",action:(le=s==null?void 0:s.action)!=null?le:{},status:(ce=s==null?void 0:s.status)!=null?ce:"completed"})):k==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:p,call_id:(pe=s==null?void 0:s.call_id)!=null?pe:"",output:(ue=s==null?void 0:s.output)!=null?ue:[],status:(de=s==null?void 0:s.status)!=null?de:"completed"})):k==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:p,call_id:(_e=s==null?void 0:s.call_id)!=null?_e:"",operation:(me=s==null?void 0:s.operation)!=null?me:{},status:(fe=s==null?void 0:s.status)!=null?fe:"completed"})):k==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(ge=s==null?void 0:s.call_id)!=null?ge:"",output:(ye=s==null?void 0:s.output)!=null?ye:"",status:(he=s==null?void 0:s.status)!=null?he:"completed"}))}else if(r==="response.code_interpreter_call_code.done")e.push(y({type:"code",item_id:(be=t==null?void 0:t.item_id)!=null?be:"",code:(Re=t==null?void 0:t.code)!=null?Re:"",container_id:(xe=t==null?void 0:t.container_id)!=null?xe:""}));else if(r==="response.code_interpreter_call.interpreting")e.push(y({type:"code",item_id:(we=t==null?void 0:t.item_id)!=null?we:"",code:(Te=t==null?void 0:t.code)!=null?Te:"",container_id:(Ee=t==null?void 0:t.container_id)!=null?Ee:""}));else if(r==="response.code_interpreter_call.completed")e.push(y({type:"code",item_id:(Oe=t==null?void 0:t.item_id)!=null?Oe:"",code:(Ae=t==null?void 0:t.code)!=null?Ae:"",container_id:(Pe=t==null?void 0:t.container_id)!=null?Pe:""}));else if(r==="response.image_generation_call.in_progress")e.push(y({type:"output_media",item_id:(ke=t==null?void 0:t.item_id)!=null?ke:"",url:"",mime_type:"image/png",media_type:"image"}));else if(r==="response.image_generation_call.generating")e.push(y({type:"output_media",item_id:(Se=t==null?void 0:t.item_id)!=null?Se:"",url:"",mime_type:"image/png",media_type:"image"}));else if(r==="response.image_generation_call.partial_image"){let k=((Ce=t==null?void 0:t.output_format)!=null?Ce:"png")==="webp"?"image/webp":"image/png",p={};for(let F of["background","size","quality","output_format"])(t==null?void 0:t[F])!=null&&(p[F]=t[F]);e.push(y(E({type:"output_media",item_id:(Ie=t==null?void 0:t.item_id)!=null?Ie:"",url:(Ne=t==null?void 0:t.partial_image_b64)!=null?Ne:"",mime_type:k,media_type:"image"},Object.keys(p).length?{provider_metadata:p}:{})))}else if(r==="response.shell_call_command.added")e.push(y({type:"shell_call",action:{command:(qe=t==null?void 0:t.command)!=null?qe:""}}));else if(r==="response.shell_call_command.delta")e.push(y({type:"shell_call",action:{command:(Le=t==null?void 0:t.delta)!=null?Le:""}}));else if(r==="response.shell_call_command.done")e.push(y({type:"shell_call",action:{command:(Me=t==null?void 0:t.command)!=null?Me:""}}));else if(r==="response.shell_call_output_content.delta")e.push(y({type:"shell_call_output",item_id:(Ue=t==null?void 0:t.item_id)!=null?Ue:"",output:[(We=t==null?void 0:t.delta)!=null?We:{}]}));else if(r==="response.shell_call_output_content.done")e.push(y({type:"shell_call_output",item_id:(je=t==null?void 0:t.item_id)!=null?je:"",output:($e=t==null?void 0:t.output)!=null?$e:[]}));else if(r==="response.apply_patch_call_operation_diff.delta")e.push(y({type:"apply_patch_call",item_id:(Ge=t==null?void 0:t.item_id)!=null?Ge:"",operation:{diff:(Ke=t==null?void 0:t.delta)!=null?Ke:""}}));else if(r==="response.apply_patch_call_operation_diff.done")e.push(y({type:"apply_patch_call",item_id:(De=t==null?void 0:t.item_id)!=null?De:"",operation:{diff:(Fe=t==null?void 0:t.diff)!=null?Fe:""}}));else if(r==="response.completed"){let s=(Be=t==null?void 0:t.response)!=null?Be:{},k=(ze=s==null?void 0:s.output)!=null?ze:[];for(let p of k){let F=p==null?void 0:p.type,G=(Ve=p==null?void 0:p.id)!=null?Ve:"";if(F==="reasoning"){let z=((Je=p==null?void 0:p.summary)!=null?Je:[]).map(dt=>{var wt;return(wt=dt==null?void 0:dt.text)!=null?wt:""}).join("");e.push(y({type:"thinking",item_id:G,thinking:z,signature:""}))}else if(F==="function_call")o.push(st((p==null?void 0:p.call_id)||"",(p==null?void 0:p.name)||"",(p==null?void 0:p.arguments)||"",G));else if(F==="message"){let pt=(A=p==null?void 0:p.content)!=null?A:[];for(let z of pt)(z==null?void 0:z.type)==="output_text"&&e.push(y({type:"text",item_id:G,text:(U=z==null?void 0:z.text)!=null?U:"",annotations:(z==null?void 0:z.annotations)||[]}))}else if(F==="code_interpreter_call")e.push(y({type:"code",item_id:G,code:(a=p==null?void 0:p.code)!=null?a:"",container_id:(c=p==null?void 0:p.container_id)!=null?c:""}));else if(F==="image_generation_call"){let pt=(P=p==null?void 0:p.result)!=null?P:"",dt=((ct=p==null?void 0:p.output_format)!=null?ct:"png")==="webp"?"image/webp":"image/png",wt={};for(let an of["revised_prompt","background","size","quality","output_format"])(p==null?void 0:p[an])!=null&&(wt[an]=p[an]);e.push(y(E({type:"output_media",item_id:G,url:pt,mime_type:dt,media_type:"image"},Object.keys(wt).length?{provider_metadata:wt}:{})))}else F==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:G,server_label:(bn=p==null?void 0:p.server_label)!=null?bn:"",tools:(Rn=p==null?void 0:p.tools)!=null?Rn:[],error:p==null?void 0:p.error})):F==="mcp_call"?e.push(y({type:"mcp_call",item_id:G,name:(xn=p==null?void 0:p.name)!=null?xn:"",server_label:(wn=p==null?void 0:p.server_label)!=null?wn:"",arguments:(Tn=p==null?void 0:p.arguments)!=null?Tn:"",output:p==null?void 0:p.output,error:p==null?void 0:p.error,approval_request_id:p==null?void 0:p.approval_request_id})):F==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:G,name:(En=p==null?void 0:p.name)!=null?En:"",arguments:(On=p==null?void 0:p.arguments)!=null?On:"",server_label:(An=p==null?void 0:p.server_label)!=null?An:""})):F==="shell_call"?e.push(y({type:"shell_call",item_id:G,call_id:(Pn=p==null?void 0:p.call_id)!=null?Pn:"",action:(kn=p==null?void 0:p.action)!=null?kn:{},status:(Sn=p==null?void 0:p.status)!=null?Sn:"completed"})):F==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:G,call_id:(Cn=p==null?void 0:p.call_id)!=null?Cn:"",output:(In=p==null?void 0:p.output)!=null?In:[],status:(Nn=p==null?void 0:p.status)!=null?Nn:"completed"})):F==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:G,call_id:(qn=p==null?void 0:p.call_id)!=null?qn:"",operation:(Ln=p==null?void 0:p.operation)!=null?Ln:{},status:(Mn=p==null?void 0:p.status)!=null?Mn:"completed"})):F==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:G,call_id:(Un=p==null?void 0:p.call_id)!=null?Un:"",output:(Wn=p==null?void 0:p.output)!=null?Wn:"",status:(jn=p==null?void 0:p.status)!=null?jn:"completed"}))}}let i=Et(e,o||[]);return Ot(i,n)},Yn=(t,n)=>{var i,l,d,u;let e=[],o=[];if("contentBlockDelta"in t){let _=((i=t.contentBlockDelta)==null?void 0:i.delta)||{};if("reasoningContent"in _){let m=((l=_.reasoningContent)==null?void 0:l.text)||"",b=((d=_.reasoningContent)==null?void 0:d.signature)||"";e.push(y({type:"thinking",thinking:m,signature:b}))}else if("text"in _)e.push(y({type:"text",text:_.text||""}));else if("toolUse"in _){let m=_.toolUse||{};o.push(st(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in t){let _=((u=t.contentBlockStart)==null?void 0:u.start)||{};if("toolUse"in _){let m=_.toolUse||{};o.push(st(m.toolUseId||"",m.name||"",""))}}let r=Et(e,o);return Ot(r,n)},Xo=["size","quality","background","output_format"],Hn=(t,n)=>{var i,l,d,u,_,m,b;let e=[],o=(i=t==null?void 0:t.type)!=null?i:"";if(o==="image_generation.partial_image"){let R=(l=t==null?void 0:t.b64_json)!=null?l:"";if(R){let x=(d=t==null?void 0:t.output_format)!=null?d:"png",O=(u=Dn[x])!=null?u:"image/png",T={},h=t==null?void 0:t.partial_image_index;h!=null&&(T.partial_image_index=h),e.push(y(E({type:"output_media",url:R,mime_type:O,media_type:"image"},Object.keys(T).length?{provider_metadata:T}:{})))}}else if(o==="image_generation.completed"){let R=(_=t==null?void 0:t.b64_json)!=null?_:"",x=(m=t==null?void 0:t.output_format)!=null?m:"png",O=(b=Dn[x])!=null?b:"image/png",T={};for(let h of Xo)(t==null?void 0:t[h])!=null&&(T[h]=t[h]);e.push(y(E({type:"output_media",url:R,mime_type:O,media_type:"image"},Object.keys(T).length?{provider_metadata:T}:{})))}return{prompt_template:{type:"completion",content:e,input_variables:[]},metadata:n}};var to=["openai","openai.azure"],ve=t=>{var r,i,l,d,u,_,m,b,R,x,O,T,h,w,f,g,I,M,W,C,N,j,q,B,$,X,K,Z,J,rt,at,D,nt,it,mt,ft,gt,yt,ht,bt,Rt,xt,ot,L,V,v,lt,tt,et,Pt,kt,St,Ct,It,Nt,qt,Lt,Mt,Ut,Wt,jt,$t,Gt,Kt,Dt,Ft,Bt,zt,Vt,Jt,Yt,Ht,Xt,Zt,Qt,vt,te,ee,ne,oe,se,re,ae,ie,le,ce,pe,ue,de,_e,me,fe,ge,ye,he,be,Re,xe,we,Te,Ee,Oe,Ae,Pe,ke,Se,Ce,Ie,Ne,qe,Le,Me,Ue,We,je,$e,Ge,Ke,De,Fe,Be,ze,Ve,Je;let n={id:null,object:"response",created_at:null,status:null,error:null,incomplete_details:null,instructions:null,max_output_tokens:null,model:null,output:[],parallel_tool_calls:!0,previous_response_id:null,reasoning:{},store:!0,temperature:1,text:void 0,tool_choice:"auto",tools:[],top_p:1,truncation:"disabled",usage:null,user:null,metadata:{}},e={},o={};for(let A of t){let U=A==null?void 0:A.type;if(U==="response.created"){let a=A.response||{};n.id=(r=a.id)!=null?r:n.id,n.created_at=(i=a.created_at)!=null?i:n.created_at,n.model=(l=a.model)!=null?l:n.model,n.status=(d=a.status)!=null?d:n.status,n.parallel_tool_calls=(u=a.parallel_tool_calls)!=null?u:n.parallel_tool_calls,n.temperature=(_=a.temperature)!=null?_:n.temperature,n.tool_choice=(m=a.tool_choice)!=null?m:n.tool_choice,n.tools=(b=a.tools)!=null?b:n.tools,n.top_p=(R=a.top_p)!=null?R:n.top_p,n.truncation=(x=a.truncation)!=null?x:n.truncation,n.max_output_tokens=(O=a.max_output_tokens)!=null?O:n.max_output_tokens,n.previous_response_id=(T=a.previous_response_id)!=null?T:n.previous_response_id,n.store=(h=a.store)!=null?h:n.store,n.user=(w=a.user)!=null?w:n.user,n.metadata=(f=a.metadata)!=null?f:n.metadata;let c=a.text;c&&(n.text=c);let P=a.reasoning;P&&(n.reasoning=P);continue}if(U==="response.in_progress"){let a=A.response||{};n.status=(g=a.status)!=null?g:n.status;continue}if(U==="response.output_item.added"){let a=A.item||{},c=a.id,P=a.type,ct=A.output_index;ct!=null&&c&&(o[ct]=c),P==="reasoning"?e[c]={type:"reasoning",id:c,summary:[],status:(I=a.status)!=null?I:"in_progress"}:P==="function_call"?e[c]={type:"function_call",id:c,call_id:a.call_id,name:a.name,arguments:"",status:(M=a.status)!=null?M:"in_progress"}:P==="message"?e[c]={type:"message",id:c,role:(W=a.role)!=null?W:"assistant",content:[],status:(C=a.status)!=null?C:"in_progress"}:P==="code_interpreter_call"?e[c]={type:"code_interpreter_call",id:c,container_id:a.container_id,code:(N=a.code)!=null?N:"",status:(j=a.status)!=null?j:"in_progress"}:P==="image_generation_call"?e[c]={type:"image_generation_call",id:c,status:(q=a.status)!=null?q:"in_progress",revised_prompt:(B=a.revised_prompt)!=null?B:"",result:($=a.result)!=null?$:"",background:a.background,size:a.size,quality:a.quality,output_format:a.output_format}:P==="web_search_call"?e[c]={type:"web_search_call",id:c,status:(X=a.status)!=null?X:"in_progress"}:P==="file_search_call"?e[c]={type:"file_search_call",id:c,status:(K=a.status)!=null?K:"in_progress"}:P==="mcp_list_tools"?e[c]={type:"mcp_list_tools",id:c,server_label:(Z=a.server_label)!=null?Z:"",tools:(J=a.tools)!=null?J:[],error:(rt=a.error)!=null?rt:null}:P==="mcp_call"?e[c]={type:"mcp_call",id:c,name:(at=a.name)!=null?at:"",server_label:(D=a.server_label)!=null?D:"",arguments:(nt=a.arguments)!=null?nt:"",output:(it=a.output)!=null?it:null,error:(mt=a.error)!=null?mt:null,approval_request_id:(ft=a.approval_request_id)!=null?ft:null,status:(gt=a.status)!=null?gt:"in_progress"}:P==="mcp_approval_request"?e[c]={type:"mcp_approval_request",id:c,name:(yt=a.name)!=null?yt:"",arguments:(ht=a.arguments)!=null?ht:"",server_label:(bt=a.server_label)!=null?bt:""}:P==="shell_call"?e[c]={type:"shell_call",id:c,call_id:(Rt=a.call_id)!=null?Rt:"",action:(xt=a.action)!=null?xt:{},status:(ot=a.status)!=null?ot:"in_progress"}:P==="shell_call_output"?e[c]={type:"shell_call_output",id:c,call_id:(L=a.call_id)!=null?L:"",output:(V=a.output)!=null?V:[],status:(v=a.status)!=null?v:"in_progress"}:P==="apply_patch_call"?e[c]={type:"apply_patch_call",id:c,call_id:(lt=a.call_id)!=null?lt:"",operation:(tt=a.operation)!=null?tt:{},status:(et=a.status)!=null?et:"in_progress"}:P==="apply_patch_call_output"&&(e[c]={type:"apply_patch_call_output",id:c,call_id:(Pt=a.call_id)!=null?Pt:"",output:(kt=a.output)!=null?kt:"",status:(St=a.status)!=null?St:"in_progress"});continue}if(U==="response.reasoning_summary_part.added"){let a=A.item_id,c=A.part||{};if(a in e&&e[a].type==="reasoning"){let P={type:(Ct=c.type)!=null?Ct:"summary_text",text:(It=c.text)!=null?It:""};e[a].summary.push(P)}continue}if(U==="response.reasoning_summary_text.delta"){let a=A.item_id,c=(Nt=A.delta)!=null?Nt:"",P=(qt=A.summary_index)!=null?qt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=P;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[P].text+=c}continue}if(U==="response.reasoning_summary_text.done"){let a=A.item_id,c=(Lt=A.text)!=null?Lt:"",P=(Mt=A.summary_index)!=null?Mt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=P;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[P].text=c}continue}if(U==="response.reasoning_summary_part.done"){let a=A.item_id,c=A.part||{};if(a in e&&e[a].type==="reasoning"){let P=(Ut=A.summary_index)!=null?Ut:0;P<e[a].summary.length&&(e[a].summary[P]={type:(Wt=c.type)!=null?Wt:"summary_text",text:(jt=c.text)!=null?jt:""})}continue}if(U==="response.function_call_arguments.delta"){let a=A.item_id,c=($t=A.delta)!=null?$t:"";a in e&&(e[a].arguments=`${e[a].arguments||""}${c}`);continue}if(U==="response.function_call_arguments.done"){let a=A.item_id,c=(Gt=A.arguments)!=null?Gt:"";a in e&&(e[a].arguments=c);continue}if(U==="response.content_part.added"){let a=A.part||{},c=Object.values(e).find(P=>P.type==="message");if(c){let P={type:(Kt=a.type)!=null?Kt:"output_text",text:(Dt=a.text)!=null?Dt:"",annotations:(Ft=a.annotations)!=null?Ft:[]};c.content.push(P)}continue}if(U==="response.output_text.delta"){let a=(Bt=A.delta)!=null?Bt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let P=c.content[c.content.length-1];P&&P.type==="output_text"&&(P.text=`${P.text||""}${a}`);break}continue}if(U==="response.output_text.done"){let a=(zt=A.text)!=null?zt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let P=c.content[c.content.length-1];P&&P.type==="output_text"&&(P.text=a);break}continue}if(U==="response.output_item.done"){let a=A.item||{},c=a.id;c in e&&(e[c].status=(Vt=a.status)!=null?Vt:"completed",a.type==="reasoning"?e[c].summary=(Jt=a.summary)!=null?Jt:e[c].summary:a.type==="function_call"?(e[c].arguments=(Yt=a.arguments)!=null?Yt:e[c].arguments,e[c].call_id=(Ht=a.call_id)!=null?Ht:e[c].call_id,e[c].name=(Xt=a.name)!=null?Xt:e[c].name):a.type==="message"?(e[c].content=(Zt=a.content)!=null?Zt:e[c].content,e[c].role=(Qt=a.role)!=null?Qt:e[c].role):a.type==="image_generation_call"?(e[c].result=(vt=a.result)!=null?vt:e[c].result,e[c].revised_prompt=(te=a.revised_prompt)!=null?te:e[c].revised_prompt,e[c].background=(ee=a.background)!=null?ee:e[c].background,e[c].size=(ne=a.size)!=null?ne:e[c].size,e[c].quality=(oe=a.quality)!=null?oe:e[c].quality,e[c].output_format=(se=a.output_format)!=null?se:e[c].output_format):a.type==="code_interpreter_call"?(e[c].code=(re=a.code)!=null?re:e[c].code,e[c].container_id=(ae=a.container_id)!=null?ae:e[c].container_id):a.type==="mcp_list_tools"?(e[c].tools=(ie=a.tools)!=null?ie:e[c].tools,e[c].error=(le=a.error)!=null?le:e[c].error):a.type==="mcp_call"?(e[c].name=(ce=a.name)!=null?ce:e[c].name,e[c].arguments=(pe=a.arguments)!=null?pe:e[c].arguments,e[c].output=(ue=a.output)!=null?ue:e[c].output,e[c].error=(de=a.error)!=null?de:e[c].error,e[c].server_label=(_e=a.server_label)!=null?_e:e[c].server_label):a.type==="mcp_approval_request"?(e[c].name=(me=a.name)!=null?me:e[c].name,e[c].arguments=(fe=a.arguments)!=null?fe:e[c].arguments,e[c].server_label=(ge=a.server_label)!=null?ge:e[c].server_label):a.type==="shell_call"?(e[c].action=(ye=a.action)!=null?ye:e[c].action,e[c].call_id=(he=a.call_id)!=null?he:e[c].call_id):a.type==="shell_call_output"?(e[c].output=(be=a.output)!=null?be:e[c].output,e[c].call_id=(Re=a.call_id)!=null?Re:e[c].call_id):a.type==="apply_patch_call"?(e[c].operation=(xe=a.operation)!=null?xe:e[c].operation,e[c].call_id=(we=a.call_id)!=null?we:e[c].call_id):a.type==="apply_patch_call_output"?(e[c].output=(Te=a.output)!=null?Te:e[c].output,e[c].call_id=(Ee=a.call_id)!=null?Ee:e[c].call_id):(a.type==="web_search_call"||a.type==="file_search_call")&&(e[c].action=a.action),n.output.push(e[c]));continue}if(U==="response.image_generation_call.in_progress"){let a=A.item_id;a in e&&(e[a].status="in_progress");continue}if(U==="response.image_generation_call.generating"){let a=A.item_id;a in e&&(e[a].status="generating");continue}if(U==="response.image_generation_call.partial_image"){let a=A.item_id;a in e&&(e[a].result=(Oe=A.partial_image_b64)!=null?Oe:e[a].result,e[a].background=(Ae=A.background)!=null?Ae:e[a].background,e[a].size=(Pe=A.size)!=null?Pe:e[a].size,e[a].quality=(ke=A.quality)!=null?ke:e[a].quality,e[a].output_format=(Se=A.output_format)!=null?Se:e[a].output_format);continue}if(U==="response.shell_call_command.added"){let a=o[A.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[A.command_index]=(Ce=A.command)!=null?Ce:"",e[a].action=c}continue}if(U==="response.shell_call_command.delta"){let a=o[A.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]);let P=(Ie=A.command_index)!=null?Ie:0;c.commands[P]=((Ne=c.commands[P])!=null?Ne:"")+((qe=A.delta)!=null?qe:""),e[a].action=c}continue}if(U==="response.shell_call_command.done"){let a=o[A.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[A.command_index]=(Le=A.command)!=null?Le:"",e[a].action=c}continue}if(U==="response.shell_call_output_content.delta"){let a=A.item_id;if(a&&a in e){e[a].output||(e[a].output=[]);let c=(Me=A.command_index)!=null?Me:0,P=(Ue=e[a].output[c])!=null?Ue:{stdout:"",stderr:""},ct=(We=A.delta)!=null?We:{};ct.stdout&&(P.stdout=((je=P.stdout)!=null?je:"")+ct.stdout),ct.stderr&&(P.stderr=(($e=P.stderr)!=null?$e:"")+ct.stderr),e[a].output[c]=P}continue}if(U==="response.shell_call_output_content.done"){let a=A.item_id;a&&a in e&&(e[a].output=(Ge=A.output)!=null?Ge:e[a].output);continue}if(U==="response.apply_patch_call_operation_diff.delta"){let a=A.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=((Ke=c.diff)!=null?Ke:"")+((De=A.delta)!=null?De:""),e[a].operation=c}continue}if(U==="response.apply_patch_call_operation_diff.done"){let a=A.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=(Fe=A.diff)!=null?Fe:c.diff,e[a].operation=c}continue}if(U==="response.completed"){let a=A.response||{};n.status=(ze=(Be=a.status)!=null?Be:n.status)!=null?ze:"completed",n.usage=(Ve=a.usage)!=null?Ve:n.usage,n.output=(Je=a.output)!=null?Je:n.output,a.reasoning&&(n.reasoning=a.reasoning);continue}}return n},pn=t=>{var d,u,_,m,b,R,x,O,T,h;let n=null,e,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},r=t.at(-1);if(!r)return o;let i;for(let w of t){if(w.choices.length===0)continue;let f=w.choices[0].delta;f.content&&(n=`${n||""}${f.content||""}`),f.function_call&&(e={name:`${e?e.name:""}${f.function_call.name||""}`,arguments:`${e?e.arguments:""}${f.function_call.arguments||""}`});let g=(d=f.tool_calls)==null?void 0:d[0];if(g){i=i||[];let I=i.at(-1);if(!I||g.id){i.push({id:g.id||"",type:g.type||"function",function:{name:((u=g.function)==null?void 0:u.name)||"",arguments:((_=g.function)==null?void 0:_.arguments)||""}});continue}I.function.name=`${I.function.name}${((m=g.function)==null?void 0:m.name)||""}`,I.function.arguments=`${I.function.arguments}${((b=g.function)==null?void 0:b.arguments)||""}`}}let l=t[0].choices.at(0);return o.choices.push({finish_reason:(R=l==null?void 0:l.finish_reason)!=null?R:"stop",index:(x=l==null?void 0:l.index)!=null?x:0,logprobs:(O=l==null?void 0:l.logprobs)!=null?O:null,message:{role:"assistant",content:n,function_call:e||void 0,tool_calls:i||void 0,refusal:(T=l==null?void 0:l.delta.refusal)!=null?T:null}}),o.id=r.id,o.model=r.model,o.created=r.created,o.system_fingerprint=r.system_fingerprint,o.usage=(h=r.usage)!=null?h:void 0,o},Xn=t=>{let n={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},e=t.at(-1);if(!e)return n;let o="";for(let r of t)r.choices.length>0&&r.choices[0].text&&(o=`${o}${r.choices[0].text}`);return n.choices[0].text=o,n.id=e.id,n.created=e.created,n.model=e.model,n.system_fingerprint=e.system_fingerprint,n.usage=e.usage,n},un=t=>{var m,b,R,x,O,T;let n={id:"",model:"",content:[],role:"assistant",type:"message",stop_reason:"stop_sequence",stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,server_tool_use:null,service_tier:null}};if(!t.at(-1))return n;let o=null,r=null,i="",l="",d="",u="",_={};for(let h of t)if(h.type==="message_start")n=E({},h.message);else if(h.type==="content_block_start")o=E({},h.content_block),r="index"in h&&typeof h.index=="number"?h.index:null,o.type==="thinking"?(i="",l=""):o.type==="text"?d="":(o.type==="tool_use"||o.type==="server_tool_use")&&(u="");else if(h.type==="content_block_delta"){let w=h.delta,f="index"in h&&typeof h.index=="number"?h.index:null;if((w==null?void 0:w.type)==="citations_delta"){let g=w.citation;if(g&&typeof g=="object"&&g.type==="web_search_result_location"&&f!==null){let I=E(E({type:"url_citation",url:(m=g.url)!=null?m:"",title:(b=g.title)!=null?b:"",start_index:(R=g.start_index)!=null?R:0,end_index:(x=g.end_index)!=null?x:0},g.cited_text!=null?{cited_text:g.cited_text}:{}),g.encrypted_index!=null?{encrypted_index:g.encrypted_index}:{});_[f]||(_[f]=[]),_[f].push(I)}}else o!==null&&(o.type==="thinking"?(w&&"signature"in w&&(i=w.signature||""),w&&"thinking"in w&&(l+=w.thinking||"")):o.type==="text"?w&&"text"in w&&(d+=w.text||""):(o.type==="tool_use"||o.type==="server_tool_use")&&(w==null?void 0:w.type)==="input_json_delta"&&(u+=w.partial_json||""))}else if(h.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=i,o.thinking=l;else if(o.type==="text")o.text=d,o.citations=null,r!==null&&((O=_[r])!=null&&O.length)&&(o.annotations=_[r]);else if(o.type==="tool_use"||o.type==="server_tool_use")try{o.input=u?JSON.parse(u):{}}catch(w){o.input={}}n.content.push(o),o=null,r=null,i="",l="",d="",u=""}else h.type==="message_delta"&&("usage"in h&&h.usage&&(n.usage=Y(E({},n.usage),{output_tokens:(T=h.usage.output_tokens)!=null?T:0})),"delta"in h&&h.delta&&("stop_reason"in h.delta&&h.delta.stop_reason!==void 0&&(n.stop_reason=h.delta.stop_reason),"stop_sequence"in h.delta&&h.delta.stop_sequence!==void 0&&(n.stop_sequence=h.delta.stop_sequence)));return n},Zn=t=>{let n={completion:"",id:"",model:"",stop_reason:"",type:"completion"},e=t.at(-1);if(!e)return n;let o="";for(let r of t)o=`${o}${r.completion}`;return n.completion=o,n.id=e.id,n.model=e.model,n.stop_reason=e.stop_reason,n},Zo=t=>{var l,d,u,_,m,b,R,x,O,T;let n=null,e={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=t.at(-1).data;if(!o)return e;let r;for(let h of t){if(h.data.choices.length===0)continue;let w=h.data.choices[0].delta;w.content&&(n=`${n||""}${w.content||""}`);let f=(l=w.toolCalls)==null?void 0:l[0];if(f){r=r||[];let g=r.at(-1);if(!g||f.id){r.push({id:f.id||"",type:f.type||"function",function:{name:((d=f.function)==null?void 0:d.name)||"",arguments:((u=f.function)==null?void 0:u.arguments)||""}});continue}g.function.name=`${g.function.name}${((_=f.function)==null?void 0:_.name)||""}`,g.function.arguments=`${g.function.arguments}${((m=f.function)==null?void 0:m.arguments)||""}`}}let i=t[0].data.choices.at(0);return e.choices.push({finish_reason:(b=i==null?void 0:i.finish_reason)!=null?b:"stop",index:(R=i==null?void 0:i.index)!=null?R:0,logprobs:(x=i==null?void 0:i.logprobs)!=null?x:null,message:{role:"assistant",content:n,tool_calls:r||void 0,refusal:(O=i==null?void 0:i.delta.refusal)!=null?O:null}}),e.id=o.id,e.model=o.model,e.created=o.created,e.usage=(T=o.usage)!=null?T:void 0,e},Qn=t=>{let n={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},e=[],o=null,r="",i="",l="",d="";for(let u of t)if("contentBlockStart"in u){let _=u.contentBlockStart;if("start"in _&&"toolUse"in _.start){let m=_.start.toolUse;o={toolUse:{toolUseId:m.toolUseId,name:m.name}},r=""}}else if("contentBlockDelta"in u){let _=u.contentBlockDelta.delta;if("text"in _)i+=_.text;else if("reasoningContent"in _){let m=_.reasoningContent;"text"in m?d+=m.text:"signature"in m&&(l+=m.signature)}else if("toolUse"in _&&"input"in _.toolUse){let m=_.toolUse.input;if(r+=m,!m.trim())continue}}else if("contentBlockStop"in u)if(o&&r){try{o.toolUse.input=JSON.parse(r)}catch(_){o.toolUse.input={}}e.push(o),o=null,r=""}else i?(e.push({text:i}),i=""):d&&l&&(e.push({reasoningContent:{reasoningText:{text:d,signature:l}}}),d="",l="");else if("messageStop"in u)n.stopReason=u.messageStop.stopReason;else if("metadata"in u){let _=u.metadata;n.usage=(_==null?void 0:_.usage)||{},n.metrics=(_==null?void 0:_.metrics)||{}}return n.output.message={role:"assistant",content:e},n},Qo=(t,n,e,o,r,i,l,d,u)=>{var R,x,O;let _=E({},l),m=[];if(t){let T={text:t,thought:!0};d&&(T.thoughtSignature=d),m.push(T)}if(n){let T={text:n,thought:null};u&&(T.thoughtSignature=u),m.push(T)}for(let T of r)m.push({executableCode:T});for(let T of i)m.push({codeExecutionResult:T});for(let T of o)m.push({inlineData:T});for(let T of e)m.push({functionCall:T});m.length>0&&((x=(R=_.candidates)==null?void 0:R[0])!=null&&x.content)&&(_.candidates[0].content.parts=m);let b=(O=l==null?void 0:l.candidates)==null?void 0:O[0];return b&&(_.candidates||(_.candidates=[]),_.candidates[0]||(_.candidates[0]={content:{parts:[]}}),b.groundingMetadata!=null&&(_.candidates[0].groundingMetadata=b.groundingMetadata),b.urlContextMetadata!=null&&(_.candidates[0].urlContextMetadata=b.urlContextMetadata),b.citationMetadata!=null&&(_.candidates[0].citationMetadata=b.citationMetadata)),_},eo=t=>{var m,b,R,x,O,T,h;let{GenerateContentResponse:n}=Tt("@google/genai");if(!t.length)return new n;let e="",o="",r=[],i=[],l=[],d=[],u=null,_=null;for(let w of t)if(w.candidates&&((b=(m=w.candidates[0])==null?void 0:m.content)!=null&&b.parts))for(let f of w.candidates[0].content.parts)if(f.text!=null)f.thought===!0?(e+=f.text,f.thoughtSignature&&(u=f.thoughtSignature)):(o+=f.text,f.thoughtSignature&&(_=f.thoughtSignature));else if(f.functionCall)r.push(f.functionCall);else if(f.inlineData){let g=f.inlineData;i.push({data:(R=g.data)!=null?R:"",mimeType:(x=g.mimeType)!=null?x:"image/png"})}else f.executableCode?l.push({code:(O=f.executableCode.code)!=null?O:"",language:f.executableCode.language}):f.codeExecutionResult&&d.push({output:(T=f.codeExecutionResult.output)!=null?T:"",outcome:(h=f.codeExecutionResult.outcome)!=null?h:"OUTCOME_OK"});return Qo(e,o,r,i,l,d,t[t.length-1],u,_)},vo=t=>eo(t),ts=t=>eo(t),es=["size","quality","background","output_format"],dn=t=>{var i,l,d,u,_;let n={created:null,data:[],usage:null},e={},o="png";for(let m of t){let b=(i=m==null?void 0:m.type)!=null?i:"";if(b==="image_generation.partial_image"){let R=m.b64_json;if(R!=null){let x=(l=m.partial_image_index)!=null?l:0;e[x]=R}}else if(b==="image_generation.completed"){let R=m.b64_json;if(R!=null){let x=(d=m.partial_image_index)!=null?d:0;e[x]=R}n.created=(u=m.created_at)!=null?u:n.created,n.usage=(_=m.usage)!=null?_:n.usage;for(let x of es)m[x]!=null&&(n[x]=m[x]);m.output_format&&(o=m.output_format)}}n.output_format||(n.output_format=o);let r=Object.keys(e).map(Number).sort((m,b)=>m-b);return r.length>0&&(n.data=r.map(m=>({b64_json:e[m]}))),n},no=(t,n="openai.chat.completions.create")=>{if(n==="openai.responses.create"||n==="openai.AzureOpenAI.responses.create")return ve(t);if(n==="openai.images.generate"||n==="openai.AzureOpenAI.images.generate")return dn(t);if("completion"in t[0])return t.reduce((e,o)=>Y(E({},o),{completion:`${e.completion}${o.completion}`}),{});if(n==="anthropic.messages.create")return un(t);if("text"in t[0].choices[0]){let e="";for(let r of t)e=`${e}${r.choices[0].text}`;let o=structuredClone(t.at(-1));return o.choices[0].text=e,o}if("delta"in t[0].choices[0]){let e=pn(t);return e.choices[0]=E(E({},e.choices[0]),e.choices[0].message),e}return""},vn=(t,n,e)=>{let o=n.model.provider,r=n.model.name;if(o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&r.startsWith("claude"))return zn(t,n,e==null?void 0:e.anthropicBlockTypeByIndex);if(o==="google"||o==="vertexai"&&r.startsWith("gemini"))return Vn(t,n);if(o==="amazon.bedrock")return Yn(t,n);if(o==="mistral")return cn(t.data,n);if(o==="openai"||o==="openai.azure"){let i=n.model.api_type||"chat-completions";return i==="responses"?Jn(t,n):i==="images"?Hn(t,n):cn(t,n)}return null};function oo(t,n,e,o){return Ze(this,null,function*(){var R,x,O;let r={request_id:null,raw_response:null,prompt_blueprint:null},i={},l=o.model.provider;l=="amazon.bedrock"&&(i=t==null?void 0:t.$metadata,t=t==null?void 0:t.stream);let d=[],u=l==="anthropic"||l==="anthropic.bedrock"||l==="vertexai"&&((O=(x=(R=o.model)==null?void 0:R.name)==null?void 0:x.startsWith)==null?void 0:O.call(x,"claude")),_={};try{for(var T=Qe(t),h,w,f;h=!(w=yield new _t(T.next())).done;h=!1){let g=w.value;d.push(g),u&&(g==null?void 0:g.type)==="content_block_start"&&g.content_block&&(_[g.index]=g.content_block.type),r.raw_response=g,r.prompt_blueprint=vn(g,o,{anthropicBlockTypeByIndex:_}),yield r}}catch(w){f=[w]}finally{try{h&&(w=T.return)&&(yield new _t(w.call(T)))}finally{if(f)throw f[0]}}let m=e(d);l==="amazon.bedrock"&&(m.ResponseMetadata=i),r.raw_response=m,r.prompt_blueprint=vn(m,o),yield r;let b=yield new _t(n({request_response:m}));r.request_id=b.request_id,r.prompt_blueprint=b.prompt_blueprint,yield r})}var so={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:pn},completion:{function_name:"openai.completions.create",stream_function:Xn}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:ve}},"openai:images":{completion:{function_name:"openai.images.generate",stream_function:dn}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:un},completion:{function_name:"anthropic.completions.create",stream_function:Zn}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:pn},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:Xn}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ve},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ve}},"openai.azure:images":{completion:{function_name:"openai.AzureOpenAI.images.generate",stream_function:dn}},google:{chat:{function_name:"google.convo.send_message",stream_function:vo},completion:{function_name:"google.model.generate_content",stream_function:ts}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:Qn},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:Qn}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:un},completion:{function_name:"anthropic.completions.create",stream_function:Zn}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:Zo},completion:{function_name:"",stream_function:null}}};var ao="1.0.61",rs=()=>{var t;if(typeof process!="undefined"&&((t=process.versions)!=null&&t.node)){let n=process.versions.node.split(".");return`${n[0]}.${n[1]}`}return"unknown"},as=rs(),is=`promptlayer-js/${ao} (node ${as})`,Q=()=>({"User-Agent":is,"X-SDK-Version":ao}),_n="SET_WORKFLOW_COMPLETE";function ls(t,n,e,o){return S(this,null,function*(){let r=yield H(`${t}/workflow-version-execution-results?workflow_version_execution_id=${n}&return_all_outputs=${e}`,E({headers:o},Q()));if(!r.ok)throw new Error("Failed to fetch final output");return r.json()})}function io(t,n,e,o,r){return function(i){return S(this,null,function*(){if(i.name===_n)try{let l=JSON.parse(i.data),d=l.result_code,u;if(d==="OK"||d==null)u=l.final_output;else if(d==="EXCEEDS_SIZE_LIMIT")u=yield ls(t,e,o,r),n.resolve(u);else throw new Error(`Unsupported final output code: ${d}`);n.resolve(u)}catch(l){n.reject(l)}})}}function cs(d){return S(this,arguments,function*({token:t,channelName:n,executionId:e,returnAllOutputs:o,headers:r,timeout:i,baseURL:l}){let u=new ns.Realtime(t),_=u.channels.get(n),m={},b=new Promise((x,O)=>{m.resolve=x,m.reject=O}),R=io(l,m,e,o,r);yield _.subscribe(_n,R);try{return yield new Promise((x,O)=>{let T=setTimeout(()=>{O(new Error("Workflow execution did not complete properly (timeout)"))},i);b.then(h=>{clearTimeout(T),x(h)}).catch(h=>{clearTimeout(T),O(h)})})}finally{console.log("Closing client"),_.unsubscribe(_n,R),u.close(),console.log("Closed client")}})}var H=(t,n)=>S(null,null,function*(){return ss(()=>S(null,null,function*(){let e=yield fetch(t,n);if(e.status>=500&&e.status<600||e.status===429)throw new Error(`Server error: ${e.status} ${e.statusText}`);return e}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:e=>{console.info(`PromptLayer API request attempt ${e.attemptNumber} failed. ${e.retriesLeft} retries left.`)}})}),lo=(t,n,e,o=!0)=>S(null,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?us(t,n,e.request_response,e,o):yield co(t,n,e,o)}),co=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/track-request`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(e)}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);ut(i,"WARNING: While logging your request, PromptLayer experienced the following error:")}if(i&&e.return_pl_id)return[e.request_response,i.request_id]}catch(r){if(o)throw r;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${r}`)}return e.request_response}),po=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/library-track-metadata`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track metadata";if(o)throw new Error(l);return ut(i,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${r}`),!1}return!0}),uo=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/library-track-score`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track score";if(o)throw new Error(l);return ut(i,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${r}`),!1}return!0}),_o=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/library-track-prompt`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track prompt";if(o)throw new Error(l);return ut(i,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${r}`),!1}return!0}),mo=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/track-group`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track group";if(o)throw new Error(l);return ut(i,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${r}`),!1}return!0}),fo=(t,n,e=!0)=>S(null,null,function*(){try{let o=yield H(`${n}/create-group`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify({api_key:t})}),r=yield o.json();if(o.status!==200){let i=r.message||r.error||"Failed to create group";if(e)throw new Error(i);return ut(r,"WARNING: While creating a group PromptLayer had the following error"),!1}return r.id}catch(o){if(e)throw o;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${o}`),!1}}),go=(t,n,e,o,r=!0)=>S(null,null,function*(){try{let i=new URL(`${n}/prompt-templates/${e}`),l=yield H(i,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":t},Q()),body:JSON.stringify(o)}),d=yield l.json();if(l.status!==200){let u=d.message||d.error||"Failed to fetch prompt template";if(r)throw new Error(u);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${u}`),null}return d.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${d.warning}`),d}catch(i){if(r)throw i;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${i}`),null}}),yo=(t,n,e,o=!0)=>S(null,null,function*(){let r=yield H(`${n}/rest/prompt-templates`,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":t},Q()),body:JSON.stringify({prompt_template:E({},e),prompt_version:E({},e),release_labels:e.release_labels?e.release_labels:void 0})}),i=yield r.json();if(r.status!==200&&r.status!==201){let l=i.message||i.error||"Failed to publish prompt template";if(o)throw new Error(l);ut(i,"WARNING: While publishing a prompt template PromptLayer had the following error")}return i}),ho=(t,n,e,o=!0)=>S(null,null,function*(){var d;let r=new URL(`${n}/prompt-templates`);Object.entries(e||{}).forEach(([u,_])=>r.searchParams.append(u,_.toString()));let i=yield H(r,{headers:E({"Content-Type":"application/json","X-API-KEY":t},Q())}),l=yield i.json();if(i.status!==200){let u=l.message||l.error||"Failed to fetch prompt templates";if(o)throw new Error(u);return ut(l,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(d=l.items)!=null?d:[]}),ps=t=>S(null,null,function*(){let n=new URL(`${t.baseURL}/connection/websocket`);n.protocol=n.protocol==="https:"?"wss:":"ws:";let e=new os(n.toString(),{token:t.token}),o=e.newSubscription(t.channelName);return new Promise((r,i)=>{let l=m=>{_(),r(m)},d=io(t.baseURL,{resolve:l,reject:i},t.executionId,t.returnAllOutputs,t.headers);o.on("publication",m=>{d({name:m.data.message_name,data:m.data.data})});let u=setTimeout(()=>{i(new Error("Workflow execution did not complete properly (timeout)"))},t.timeout),_=()=>{clearTimeout(u),o.unsubscribe(),e.disconnect()};o.on("error",m=>{_(),i(`Centrifugo subscription error: ${m}`)}),e.on("error",m=>{_(),i(`Centrifugo client error: ${m}`)}),o.subscribe(),e.connect()})}),bo=_=>S(null,[_],function*({workflow_name:t,input_variables:n,metadata:e={},workflow_label_name:o=null,workflow_version_number:r=null,return_all_outputs:i=!1,api_key:l,timeout:d=36e5,baseURL:u}){let m={input_variables:n,metadata:e,workflow_label_name:o,workflow_version_number:r,return_all_outputs:i},b=E({"Content-Type":"application/json","X-API-KEY":l},Q());try{let R=yield H(`${u}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:b,body:JSON.stringify(m)});if(R.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield R.json().catch(()=>({}))).error||R.statusText}`};let x=yield R.json();x.warning&&console.warn(`WARNING: ${x.warning}`);let O=x.workflow_version_execution_id;if(!O)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let T=`workflow_updates:${O}`,w=yield(yield H(`${u}/ws-token-request-library?capability=${T}`,{method:"POST",headers:b})).json(),g={token:w.token_details.token,channelName:T,executionId:O,returnAllOutputs:i,headers:b,timeout:d,baseURL:u};return w.messaging_backend==="centrifugo"?ps(g):yield cs(g)}catch(R){throw console.error(`Failed to run workflow: ${R instanceof Error?R.message:R}`),R}});function us(t,n,e,o,r=!0){return Ze(this,null,function*(){let i=[];try{for(var u=Qe(e),_,m,b;_=!(m=yield new _t(u.next())).done;_=!1){let R=m.value;yield o.return_pl_id?[R,null]:R,i.push(R)}}catch(m){b=[m]}finally{try{_&&(m=u.return)&&(yield new _t(m.call(u)))}finally{if(b)throw b[0]}}let l=no(i,o.function_name),d=yield new _t(co(t,n,Y(E({},o),{request_response:l,request_end_time:new Date().toISOString()}),r));if(d&&o.return_pl_id){let R=d[1];yield[i.at(-1),R]}})}var ut=(t,n)=>{try{console.warn(`${n}: ${t.message}`)}catch(e){console.warn(`${n}: ${t}`)}},Ro=(t,n,e=!0)=>S(null,null,function*(){try{let o=yield H(`${t}/track-request`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(n)}),r=yield o.json();if(o.status!==200){let i=r.message||r.error||"Failed to track request";if(e)throw new Error(i);ut(r,"WARNING: While logging your request, PromptLayer experienced the following error:")}return r}catch(o){if(e)throw o;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${o}`)}return{}}),ds=(t,n)=>S(null,null,function*(){return yield t.chat.completions.create(n)}),_s=(t,n)=>S(null,null,function*(){return yield t.completions.create(n)}),xo={chat:ds,completion:_s},wo=(t,n)=>S(null,null,function*(){var i,l;let e=Tt("openai").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey});n==null||delete n.apiKey,n==null||delete n.baseURL;let r=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(r==="chat-completions"){let d=xo[t.prompt_template.type];return yield d(o,n)}else return r==="images"?yield o.images.generate(n):yield o.responses.create(n)}),To=(t,n)=>S(null,null,function*(){var i,l;let{AzureOpenAI:e}=Tt("openai"),o=new e({endpoint:process.env.AZURE_OPENAI_ENDPOINT||n.baseURL,apiVersion:process.env.OPENAI_API_VERSION||n.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||n.apiKey});n==null||delete n.baseURL,n==null||delete n.apiVersion,n==null||delete n.apiKey;let r=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(r==="chat-completions"){let d=xo[t.prompt_template.type];return yield d(o,n)}else return r==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Eo=(t,n)=>S(null,null,function*(){return t.messages.create(n)}),ms=(t,n)=>S(null,null,function*(){return t.completions.create(n)}),Oo={chat:Eo,completion:ms},Ao=(t,n)=>S(null,null,function*(){let e=Tt("@anthropic-ai/sdk").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey}),r=Oo[t.prompt_template.type];return r(o,n)}),Po=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/log-request`,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":t},Q()),body:JSON.stringify(e)}),i=yield r.json();if(r.status!==201){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);return ut(i,"WARNING: While logging your request PromptLayer had the following error"),null}return i}catch(r){if(o)throw r;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${r}`),null}}),fs=(t,n)=>S(null,null,function*(){var l,d;let e=n==null?void 0:n.history,o=n==null?void 0:n.generationConfig,r=e.length>0?(l=e[e.length-1])==null?void 0:l.parts:"",i=t.chats.create({model:n==null?void 0:n.model,history:(d=e.slice(0,-1))!=null?d:[],config:o});return n!=null&&n.stream?yield i.sendMessageStream({message:r}):yield i.sendMessage({message:r})}),gs=(t,o)=>S(null,null,function*(){var r=o,{stream:n}=r,e=Xe(r,["stream"]);return n?yield t.generateContentStream(E({},e)):yield t.generateContent(E({},e))}),ys={chat:fs,completion:gs},mn=(t,n)=>S(null,null,function*(){let{GoogleGenAI:e}=yield import("@google/genai"),o=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,r=process.env.VERTEX_AI_PROJECT_ID||process.env.GOOGLE_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT,i=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,l={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:r,scopes:["https://www.googleapis.com/auth/cloud-platform"]},d=o?new e({apiKey:o}):new e({vertexai:!0,project:r,location:i,googleAuthOptions:l}),u=ys[t.prompt_template.type];return yield u(d,n)}),ro=t=>t.replace(/_([a-z])/g,(n,e)=>e.toUpperCase()),tn=(t,n=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(e=>tn(e,n)):Object.fromEntries(Object.entries(t).map(([e,o])=>n.has(e)?[ro(e),o]:[ro(e),tn(o,n)])),ko=(t,n,e={},o=!1)=>{var u,_,m,b,R,x,O,T,h;let r=(m=n==null?void 0:n.client)!=null?m:(_=(u=t.metadata)==null?void 0:u.model)==null?void 0:_.provider,i=(R=(b=t.metadata)==null?void 0:b.model)==null?void 0:R.api_type;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let l=Y(E({},t.llm_kwargs||{}),{stream:o});["google","vertexai"].includes(r)&&((O=(x=t.metadata)==null?void 0:x.model)!=null&&O.name.startsWith("gemini"))&&(l=tn(l,new Set(["function_declarations","properties"])));let d={baseURL:(h=n==null?void 0:n.base_url)!=null?h:(T=t.provider_base_url)==null?void 0:T.url,apiKey:n==null?void 0:n.api_key};return Object.entries(d).forEach(([w,f])=>{f!==void 0&&(l[w]=f)}),o&&to.includes(r)&&i==="chat-completions"&&(l.stream_options={include_usage:!0}),{provider_type:r,kwargs:l}},So=(t,n)=>{let e=so[t];if(!e)throw new Error(`Unsupported provider type: ${t}`);let o=n.type,r=e[o];if(!r)throw new Error(`Unsupported template type '${n.type}' for provider '${t}'`);return r},Co=(t,n)=>S(null,null,function*(){var o;let e=(o=t.metadata)==null?void 0:o.model;if(!e)throw new Error("Model metadata not found in prompt blueprint");if(e.name.startsWith("gemini"))return mn(t,n);if(e.name.startsWith("claude")){let{AnthropicVertex:r}=yield import("@anthropic-ai/vertex-sdk"),i=new r({baseURL:n.baseURL});if(t.prompt_template.type==="chat")return Eo(i,n);throw new Error(`Unsupported prompt template type '${t.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${e.name}' for Vertex AI request`)}),Io=(t,n)=>S(null,null,function*(){let{BedrockRuntimeClient:e,ConverseCommand:o,ConverseStreamCommand:r}=yield import("@aws-sdk/client-bedrock-runtime"),i=new e({credentials:{accessKeyId:(n==null?void 0:n.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(n==null?void 0:n.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(n==null?void 0:n.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(n==null?void 0:n.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(n!=null&&n.stream){delete n.stream;let l=new r(E({},n));return yield i.send(l)}else{n==null||delete n.stream;let l=new o(E({},n));return yield i.send(l)}}),No=(t,n)=>S(null,null,function*(){let{AnthropicBedrock:e}=yield import("@anthropic-ai/bedrock-sdk"),o=new e({awsAccessKey:n.aws_access_key,awsSecretKey:n.aws_secret_key,awsRegion:n.aws_region,awsSessionToken:n.aws_session_token,baseURL:n.base_url}),r=Oo[t.prompt_template.type];return r(o,n)}),qo=(t,n)=>S(null,null,function*(){let{Mistral:e}=yield import("@mistralai/mistralai"),o=new e({apiKey:process.env.MISTRAL_API_KEY});return n=tn(n,new Set),n!=null&&n.stream?(delete n.stream,yield o.chat.stream(n)):(delete n.stream,yield o.chat.complete(n))}),fn=t=>{var n,e,o,r,i,l;if(typeof globalThis.process!="undefined")return(o=(e=(n=globalThis.process.env)==null?void 0:n[t])==null?void 0:e.trim())!=null?o:void 0;if(typeof globalThis.Deno!="undefined")return(l=(i=(r=globalThis.Deno.env)==null?void 0:r.get)==null?void 0:i.call(r,t))==null?void 0:l.trim()};var en=class{constructor(n,e,o=!0){this.create=()=>fo(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};import{SpanKind as Ye,SpanStatusCode as gn}from"@opentelemetry/api";import{ExportResultCode as nn}from"@opentelemetry/core";var yn=class{constructor(n,e,o){this.apiKey=e,this.baseURL=o,this.enableTracing=n,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(n){return n?Object.fromEntries(Object.entries(n)):{}}spanKindToString(n){return{[Ye.INTERNAL]:"SpanKind.INTERNAL",[Ye.SERVER]:"SpanKind.SERVER",[Ye.CLIENT]:"SpanKind.CLIENT",[Ye.PRODUCER]:"SpanKind.PRODUCER",[Ye.CONSUMER]:"SpanKind.CONSUMER"}[n]||"SpanKind.INTERNAL"}statusCodeToString(n){return{[gn.ERROR]:"StatusCode.ERROR",[gn.OK]:"StatusCode.OK",[gn.UNSET]:"StatusCode.UNSET"}[n]||"StatusCode.UNSET"}toNanoseconds(n){return(BigInt(n[0])*BigInt(1e9)+BigInt(n[1])).toString()}export(n){if(!this.enableTracing)return Promise.resolve(nn.SUCCESS);let e=n.map(o=>{var r;return{name:o.name,context:{trace_id:o.spanContext().traceId,span_id:o.spanContext().spanId,trace_state:((r=o.spanContext().traceState)==null?void 0:r.serialize())||""},kind:this.spanKindToString(o.kind),parent_id:o.parentSpanId||null,start_time:this.toNanoseconds(o.startTime),end_time:this.toNanoseconds(o.endTime),status:{status_code:this.statusCodeToString(o.status.code),description:o.status.message},attributes:this.attributesToObject(o.attributes),events:o.events.map(i=>({name:i.name,timestamp:this.toNanoseconds(i.time),attributes:this.attributesToObject(i.attributes)})),links:o.links.map(i=>({context:i.context,attributes:this.attributesToObject(i.attributes)})),resource:{attributes:Y(E({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return H(this.url,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},Q()),body:JSON.stringify({spans:e})}).then(o=>o.ok?nn.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
+
HTTP error! status: ${o.status}`),nn.FAILED)).catch(o=>(console.error("Error exporting spans:",o),nn.FAILED))}shutdown(){return Promise.resolve()}},Lo=yn;import*as Mo from"@opentelemetry/api";import{SimpleSpanProcessor as hs}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as bs}from"@opentelemetry/sdk-trace-node";var At=(t="promptlayer-tracer")=>Mo.trace.getTracer(t),Uo=(t,n,e)=>{let o=new bs,r=new Lo(t,n,e),i=new hs(r);o.addSpanProcessor(i),o.register()};var Rs=At(),hn=(t,n,e,o="",r="openai")=>{let i={construct:(l,d)=>{let u=Reflect.construct(l,d);return Object.defineProperties(u,{function_name:{value:o,writable:!0},provider:{value:r}}),new Proxy(u,i)},get:(l,d,u)=>{let _=l[d],m=`${Reflect.get(l,"function_name")}.${d.toString()}`;return typeof _=="object"?(Object.defineProperties(_,{function_name:{value:m,writable:!0},provider:{value:r}}),new Proxy(_,i)):typeof _=="function"?(...b)=>{var w,f,g,I,M,W;let R=new Date().toISOString(),x=Reflect.get(l,"provider"),O=(w=b[0])==null?void 0:w.return_pl_id,T=(f=b[0])==null?void 0:f.pl_tags,h=(g=b[0])==null?void 0:g.pl_warn_on_error;return(I=b[0])==null||delete I.return_pl_id,(M=b[0])==null||delete M.pl_tags,(W=b[0])==null||delete W.pl_warn_on_error,Rs.startActiveSpan(`${x}.${m}`,C=>S(null,null,function*(){try{C.setAttribute("function_input",JSON.stringify(b));let N=Reflect.apply(_,l,b),j=C.spanContext().spanId;return N instanceof Promise?new Promise((q,B)=>{N.then($=>S(null,null,function*(){let X=yield lo(t,n,{api_key:t,provider_type:x,function_name:m,request_start_time:R,request_end_time:new Date().toISOString(),request_response:$,kwargs:b[0],return_pl_id:O,tags:T,span_id:j},!h);C.setAttribute("function_output",JSON.stringify(X)),C.setAttribute("response_status","success"),C.end(),q(X)})).catch($=>{C.recordException($),C.setAttribute("response_status","error"),C.end(),B($)})}):(C.setAttribute("function_output",JSON.stringify(N)),C.setAttribute("response_status","success"),C.end(),N)}catch(N){throw C.recordException(N),C.setAttribute("response_status","error"),C.end(),N}}))}:Reflect.get(l,d,u)}};return new Proxy(e,i)};import*as on from"@opentelemetry/api";var jo=(t,n,e)=>function(...o){let r=At(),i=l=>{try{e&&Object.entries(e).forEach(([u,_])=>{l.setAttribute(u,_)}),l.setAttribute("function_input",JSON.stringify(o));let d=n(...o);return d instanceof Promise?d.then(u=>(l.setAttribute("function_output",JSON.stringify(u)),l.setStatus({code:on.SpanStatusCode.OK}),u)).catch(u=>{throw Wo(l,u,o),u}).finally(()=>l.end()):(l.setAttribute("function_output",JSON.stringify(d)),l.setStatus({code:on.SpanStatusCode.OK}),l.end(),d)}catch(d){throw Wo(l,d,o),d}};return r.startActiveSpan(t,i)},Wo=(t,n,e)=>{t.setAttribute("function_input",JSON.stringify(e)),t.setStatus({code:on.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),t.end()};var sn=class{constructor(n,e,o=!0){this.get=(n,e)=>go(this.apiKey,this.baseURL,n,e,this.throwOnError);this.publish=n=>yo(this.apiKey,this.baseURL,n,this.throwOnError);this.all=n=>ho(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var xs=(t,n,e,o=!0)=>{if(!(e.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[r,i]of Object.entries(e.metadata))if(typeof r!="string"||typeof i!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return po(t,n,e,o)},ws=(t,n,e,o=!0)=>{if(typeof e.score!="number")throw new Error("Score must be a number");if(e.score<0||e.score>100)throw new Error("Score must be a number between 0 and 100.");return uo(t,n,e,o)},Ts=(t,n,e,o=!0)=>{if(!(e.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return _o(t,n,e,o)},Es=(t,n,e,o=!0)=>mo(t,n,e,o),rn=class{constructor(n,e,o=!0){this.group=n=>Es(this.apiKey,this.baseURL,n,this.throwOnError);this.metadata=n=>xs(this.apiKey,this.baseURL,n,this.throwOnError);this.prompt=n=>Ts(this.apiKey,this.baseURL,n,this.throwOnError);this.score=n=>ws(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};function Os(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function As(t){return t&&typeof t=="object"&&t.constructor?t.constructor.name:""}function $o(t){let n=Os(t),e=As(t),o=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();return n===429||/ratelimit/i.test(e)?"PROVIDER_RATE_LIMIT":/timeout/i.test(e)?"PROVIDER_TIMEOUT":n===401||/authentication/i.test(e)?"PROVIDER_AUTH_ERROR":o.includes("quota")?"PROVIDER_QUOTA_LIMIT":o.includes("timeout")||o.includes("timed out")?"PROVIDER_TIMEOUT":n!==void 0?"PROVIDER_ERROR":"UNKNOWN_ERROR"}import*as Ko from"@opentelemetry/api";var Ps={openai:wo,anthropic:Ao,"openai.azure":To,google:mn,vertexai:Co,"amazon.bedrock":Io,"anthropic.bedrock":No,mistral:qo},ks=t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=["status","value","error_message","raw_error_message","is_output_node"];return Object.values(t).every(o=>typeof o!="object"||o===null?!1:n.every(r=>r in o))},Go=class{constructor({apiKey:n=fn("PROMPTLAYER_API_KEY"),baseURL:e=fn("PROMPTLAYER_BASE_URL"),enableTracing:o=!1,throwOnError:r=!0}={}){if(n===void 0)throw new Error("PromptLayer API key not provided. Please set the PROMPTLAYER_API_KEY environment variable or pass the api_key parameter.");this.apiKey=n,this.baseURL=e||"https://api.promptlayer.com",this.enableTracing=o,this.throwOnError=r,this.templates=new sn(n,this.baseURL,this.throwOnError),this.group=new en(n,this.baseURL,this.throwOnError),this.track=new rn(n,this.baseURL,this.throwOnError),this.wrapWithSpan=jo,o&&Uo(o,n,this.baseURL)}get Anthropic(){try{let n=Tt("@anthropic-ai/sdk").default;return hn(this.apiKey,this.baseURL,n,"anthropic","anthropic")}catch(n){console.error("To use the Anthropic module, you must install the @anthropic-ai/sdk package.")}}get OpenAI(){try{let n=Tt("openai").default;return hn(this.apiKey,this.baseURL,n,"openai","openai")}catch(n){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(R){return S(this,arguments,function*({promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:r,tags:i,metadata:l,groupId:d,modelParameterOverrides:u,stream:_=!1,provider:m,model:b}){return At().startActiveSpan("PromptLayer Run",O=>S(this,null,function*(){try{let T={promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:r,tags:i,metadata:l,groupId:d,modelParameterOverrides:u,stream:_};O.setAttribute("function_input",JSON.stringify(T));let h=r,w={label:o,version:e,metadata_filters:l,provider:m,model:b,model_parameter_overrides:u};r&&(w.input_variables=r);let f=yield this.templates.get(n,w);if(!f)throw new Error(`Cannot proceed: prompt template '${n}' could not be fetched. Check the warnings above for the actual error.`);let g=f.prompt_template;if(!f.llm_kwargs){let D=`Prompt '${n}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashboard.`;if(this.throwOnError)throw new Error(D);console.warn(`WARNING: ${D}`)}let I=f.metadata;if(!I)throw new Error(`Prompt '${n}' does not have any metadata associated with it.`);let M=I.model;if(!M)throw new Error(`Prompt '${n}' does not have a model parameters associated with it.`);let W=f.custom_provider,C=new Date().toISOString(),{provider_type:N,kwargs:j}=ko(f,W,u,_),q=N;if(N==="openai"||N==="openai.azure"){let D=M.api_type;q=`${N}:${D}`}M.name.startsWith("gemini")?q="google":M.name.startsWith("claude")&&(q="anthropic");let B=So(q,g),{function_name:$,stream_function:X}=B,K=Ps[N];if(!K)throw new Error(`No request function found for provider: ${N}`);let Z=D=>{let nt=new Date().toISOString();return Ro(this.baseURL,E({function_name:$,provider_type:N,args:[],kwargs:j,tags:i,request_start_time:C,request_end_time:nt,api_key:this.apiKey,metadata:l,prompt_id:f.id,prompt_version:f.version,prompt_input_variables:h,group_id:d,return_prompt_blueprint:!0,span_id:O.spanContext().spanId},D),this.throwOnError)},J;try{J=yield K(f,j)}catch(D){let nt=$o(D),it=D instanceof Error?D.message:String(D);throw yield Z({request_response:{},status:"ERROR",error_type:nt,error_message:it}),D}if(_)return oo(J,Z,X,l||f.metadata);let rt=yield Z({request_response:J}),at={request_id:rt.request_id,raw_response:J,prompt_blueprint:rt.prompt_blueprint};return O.setAttribute("function_output",JSON.stringify(at)),at}catch(T){throw O.setStatus({code:Ko.SpanStatusCode.ERROR,message:T instanceof Error?T.message:"Unknown error"}),T}finally{O.end()}}))})}runWorkflow(d){return S(this,arguments,function*({workflowName:n,inputVariables:e={},metadata:o={},workflowLabelName:r=null,workflowVersion:i=null,returnAllOutputs:l=!1}){try{let u=yield bo({workflow_name:n,input_variables:e,metadata:o,workflow_label_name:r,workflow_version_number:i,return_all_outputs:l,api_key:this.apiKey,baseURL:this.baseURL});if(!l&&ks(u)){let m=Object.values(u).filter(R=>R.is_output_node===!0);if(m.length===0)throw new Error(JSON.stringify(u,null,2));if(!m.some(R=>R.status==="SUCCESS"))throw new Error(JSON.stringify(u,null,2))}return u}catch(u){throw u instanceof Error?(console.error("Error running workflow:",u.message),new Error(`Error running workflow: ${u.message}`)):(console.error("Unknown error running workflow:",u),new Error("Unknown error running workflow"))}})}logRequest(n){return S(this,null,function*(){return Po(this.apiKey,this.baseURL,n,this.throwOnError)})}};export{Go as PromptLayer};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|