promptlayer 1.0.59 → 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/.github/workflows/node.js.yml +1 -0
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/index.d.mts +232 -9
- package/dist/index.d.ts +232 -9
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
- package/src/index.ts +17 -2
- package/src/run-error-tracking.test.ts +146 -0
- package/src/types.ts +308 -9
- package/src/utils/blueprint-builder.test.ts +727 -0
- package/src/utils/blueprint-builder.ts +957 -126
- package/src/utils/errors.test.ts +68 -0
- package/src/utils/errors.ts +62 -0
- package/src/utils/streaming.test.ts +498 -0
- package/src/utils/streaming.ts +471 -43
- package/src/utils/utils.ts +4 -0
- package/tsconfig.json +2 -1
- package/vitest.config.ts +6 -0
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ve=Object.defineProperty,to=Object.defineProperties;var eo=Object.getOwnPropertyDescriptors;var Et=Object.getOwnPropertySymbols;var re=Object.prototype.hasOwnProperty,se=Object.prototype.propertyIsEnumerable;var $t=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e);var ne=(e,t,o)=>t in e?ve(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,h=(e,t)=>{for(var o in t||(t={}))re.call(t,o)&&ne(e,o,t[o]);if(Et)for(var o of Et(t))se.call(t,o)&&ne(e,o,t[o]);return e},F=(e,t)=>to(e,eo(t));var st=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,o)=>(typeof require!="undefined"?require:t)[o]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ot=(e,t)=>{var o={};for(var n in e)re.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(e!=null&&Et)for(var n of Et(e))t.indexOf(n)<0&&se.call(e,n)&&(o[n]=e[n]);return o};var _=(e,t,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(e,t)).next())}),Z=function(e,t){this[0]=e,this[1]=t},At=(e,t,o)=>{var n=(i,l,c,p)=>{try{var m=o[i](l),b=(l=m.value)instanceof Z,y=m.done;Promise.resolve(b?l[0]:l).then(R=>b?n(i==="return"?i:"next",l[1]?{done:R.done,value:R.value}:R,c,p):c({value:R,done:y})).catch(R=>n("throw",R,c,p))}catch(R){p(R)}},r=i=>s[i]=l=>new Promise((c,p)=>n(i,l,c,p)),s={};return o=o.apply(e,t),s[$t("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Ct=(e,t,o)=>(t=e[$t("asyncIterator")])?t.call(e):(e=e[$t("iterator")](),t={},o=(n,r)=>(r=e[n])&&(t[n]=s=>new Promise((i,l,c)=>(s=r.call(e,s),c=s.done,Promise.resolve(s.value).then(p=>i({value:p,done:c}),l)))),o("next"),o("return"),t);import ao from"ably";import{Centrifuge as co}from"centrifuge";import po from"p-retry";var D=(e,t,o,n)=>{let r={id:e,function:{name:t,input:o}};return n&&(r.tool_id=n),r},T=n=>{var r=n,{type:e,item_id:t}=r,o=Ot(r,["type","item_id"]);let s=h({type:e},o);return t&&(s.item_id=t),s},xt=(e,t)=>({input_variables:[],template_format:"f-string",content:e,role:"assistant",function_call:null,name:null,tool_calls:t}),Tt=(e,t)=>({prompt_template:{messages:[e],type:"chat",input_variables:[]},metadata:t}),ie=(e,t)=>{let o=[],n=[];e.type==="content_block_start"?e.content_block.type==="thinking"?o.push(T({type:"thinking",thinking:"",signature:""})):e.content_block.type==="text"?o.push(T({type:"text",text:""})):e.content_block.type==="tool_use"&&n.push(D(e.content_block.id||"",e.content_block.name||"",{})):e.type==="content_block_delta"&&(e.delta.type==="thinking_delta"?o.push(T({type:"thinking",thinking:e.delta.thinking||"",signature:""})):e.delta.type==="text_delta"?o.push(T({type:"text",text:e.delta.text||""})):e.delta.type==="signature_delta"?o.push(T({type:"thinking",thinking:"",signature:e.delta.signature||""})):e.delta.type==="input_json_delta"&&n.push(D("","",e.delta.partial_json)));let r=xt(o,n);return Tt(r,t)},ae=(e,t)=>{let o=[],n=[];for(let s of e.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(T({type:"thinking",thinking:i.text,signature:i.thoughtSignature||""})):o.push(T({type:"text",text:i.text})):i.functionCall&&n.push(D(i.functionCall.id||"",i.functionCall.name||"",i.functionCall.args||{}));let r=xt(o,n);return Tt(r,t)},Wt=(e,t)=>{let o=[],n=[];for(let s of e.choices)if(s.delta){s.delta.content&&o.push(T({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(D(l.id||"",l.function.name||"",l.function.arguments||""))}let r=xt(o,n);return Tt(r,t)},ce=(e,t)=>{var i,l,c,p,m,b,y,R,w,E,A,C,g,O,N,W,B,I,k,J,M,V,K,z,Q,X,v,tt,et,j,ot,at,ct,pt,lt,ut,mt,dt,ft,_t,yt,ht,gt,bt,Rt,wt,S,L,u,d,x,zt,Yt,Vt,Xt,Ht,Zt,Qt,vt,te,ee;let o=[],n=[],r=e==null?void 0:e.type;if(r==="response.reasoning_summary_text.delta"){let a=(i=e==null?void 0:e.delta)!=null?i:"",P=(l=e==null?void 0:e.item_id)!=null?l:"";a&&o.push(T({type:"thinking",item_id:P,thinking:a,signature:""}))}else if(r==="response.reasoning_summary_text.done"){let a=(c=e==null?void 0:e.text)!=null?c:"",P=(p=e==null?void 0:e.item_id)!=null?p:"";a&&o.push(T({type:"thinking",item_id:P,thinking:a,signature:""}))}else if(r==="response.reasoning_summary_part.added"){let a=(m=e==null?void 0:e.part)!=null?m:{},P=(b=e==null?void 0:e.item_id)!=null?b:"";if((a==null?void 0:a.type)==="summary_text"){let f=(y=a==null?void 0:a.text)!=null?y:"";o.push(T({type:"thinking",item_id:P,thinking:f,signature:""}))}}else if(r==="response.reasoning_summary_part.done"){let a=(R=e==null?void 0:e.part)!=null?R:{},P=(w=e==null?void 0:e.item_id)!=null?w:"";if((a==null?void 0:a.type)==="summary_text"){let f=(E=a==null?void 0:a.text)!=null?E:"";f&&o.push(T({type:"thinking",item_id:P,thinking:f,signature:""}))}}else if(r==="response.function_call_arguments.delta"){let a=(A=e==null?void 0:e.item_id)!=null?A:"",P=(C=e==null?void 0:e.delta)!=null?C:"";P&&n.push(D("","",P,a))}else if(r==="response.function_call_arguments.done"){let a=(g=e==null?void 0:e.item_id)!=null?g:"",P=(O=e==null?void 0:e.arguments)!=null?O:"";P&&n.push(D("","",P,a))}else if(r==="response.output_item.added"){let a=(N=e==null?void 0:e.item)!=null?N:{},P=a==null?void 0:a.type,f=(W=a==null?void 0:a.id)!=null?W:"";P==="reasoning"?o.push(T({type:"thinking",thinking:"",signature:"",item_id:f})):P==="function_call"?n.push(D((a==null?void 0:a.call_id)||"",(a==null?void 0:a.name)||"","",f)):P==="message"?o.push(T({type:"text",item_id:f,text:""})):P==="code_interpreter_call"&&o.push(T({type:"code",item_id:f,code:(B=a==null?void 0:a.code)!=null?B:"",container_id:(I=a==null?void 0:a.container_id)!=null?I:""}))}else if(r==="response.content_part.added"){let a=(k=e==null?void 0:e.part)!=null?k:{},P=(J=a==null?void 0:a.type)!=null?J:"output_text",f=(M=e==null?void 0:e.item_id)!=null?M:"";P==="output_text"&&o.push(T({type:"text",item_id:f,text:(V=a==null?void 0:a.text)!=null?V:"",annotations:(a==null?void 0:a.annotations)||[]}))}else if(r==="response.content_part.done"){let a=(K=e==null?void 0:e.part)!=null?K:{},P=(z=a==null?void 0:a.type)!=null?z:"output_text",f=(Q=e==null?void 0:e.item_id)!=null?Q:"";P==="output_text"&&o.push(T({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=(e==null?void 0:e.annotation)||{},P=a==null?void 0:a.type,f=null;P==="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}:P=="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(T({type:"text",item_id:(v=e==null?void 0:e.item_id)!=null?v:"",text:"",annotations:[f]}))}else if(r==="response.code_interpreter_call.in_progress")o.push(T({type:"code",item_id:(tt=e==null?void 0:e.item_id)!=null?tt:"",code:(et=e==null?void 0:e.code)!=null?et:"",container_id:(j=e==null?void 0:e.container_id)!=null?j:""}));else if(r==="response.code_interpreter_call_code.delta")o.push(T({type:"code",item_id:(ot=e==null?void 0:e.item_id)!=null?ot:"",code:(at=e==null?void 0:e.delta)!=null?at:"",container_id:(ct=e==null?void 0:e.container_id)!=null?ct:""}));else if(r==="response.output_text.delta"){let a=(pt=e==null?void 0:e.delta)!=null?pt:"";a&&o.push(T({type:"text",item_id:(lt=e==null?void 0:e.item_id)!=null?lt:"",text:a}))}else if(r==="response.output_text.done"){let a=(ut=e==null?void 0:e.text)!=null?ut:"";a&&o.push(T({type:"text",item_id:(mt=e==null?void 0:e.item_id)!=null?mt:"",text:a}))}else if(r==="response.output_item.done"){let a=(dt=e==null?void 0:e.item)!=null?dt:{},P=a==null?void 0:a.type,f=(ft=a==null?void 0:a.id)!=null?ft:"";if(P==="reasoning"){let G=((_t=a==null?void 0:a.summary)!=null?_t:[]).map(H=>{var $;return($=H==null?void 0:H.text)!=null?$:""}).join("");o.push(T({type:"thinking",item_id:f,thinking:G,signature:""}))}else if(P==="function_call")n.push(D((a==null?void 0:a.call_id)||"",(a==null?void 0:a.name)||"",(a==null?void 0:a.arguments)||"",f));else if(P==="message"){let nt=(yt=a==null?void 0:a.content)!=null?yt:[];for(let G of nt)if((G==null?void 0:G.type)==="output_text"){let H=(ht=G==null?void 0:G.text)!=null?ht:"";H&&o.push(T({type:"text",item_id:f,text:H}))}}else P==="code_interpreter_call"&&o.push(T({type:"code",item_id:f,code:(gt=a==null?void 0:a.code)!=null?gt:"",container_id:(bt=a==null?void 0:a.container_id)!=null?bt:""}))}else if(r==="response.code_interpreter_call_code.done")o.push(T({type:"code",item_id:(Rt=e==null?void 0:e.item_id)!=null?Rt:"",code:(wt=e==null?void 0:e.code)!=null?wt:"",container_id:(S=e==null?void 0:e.container_id)!=null?S:""}));else if(r==="response.code_interpreter_call.interpreting")o.push(T({type:"code",item_id:(L=e==null?void 0:e.item_id)!=null?L:"",code:(u=e==null?void 0:e.code)!=null?u:"",container_id:(d=e==null?void 0:e.container_id)!=null?d:""}));else if(r==="response.code_interpreter_call.completed")o.push(T({type:"code",item_id:(x=e==null?void 0:e.item_id)!=null?x:"",code:(zt=e==null?void 0:e.code)!=null?zt:"",container_id:(Yt=e==null?void 0:e.container_id)!=null?Yt:""}));else if(r==="response.completed"){let a=(Vt=e==null?void 0:e.response)!=null?Vt:{},P=(Xt=a==null?void 0:a.output)!=null?Xt:[];for(let f of P){let nt=f==null?void 0:f.type,G=(Ht=f==null?void 0:f.id)!=null?Ht:"";if(nt==="reasoning"){let $=((Zt=f==null?void 0:f.summary)!=null?Zt:[]).map(rt=>{var oe;return(oe=rt==null?void 0:rt.text)!=null?oe:""}).join("");o.push(T({type:"thinking",item_id:G,thinking:$,signature:""}))}else if(nt==="function_call")n.push(D((f==null?void 0:f.call_id)||"",(f==null?void 0:f.name)||"",(f==null?void 0:f.arguments)||"",G));else if(nt==="message"){let H=(Qt=f==null?void 0:f.content)!=null?Qt:[];for(let $ of H)if(($==null?void 0:$.type)==="output_text"){let rt=(vt=$==null?void 0:$.text)!=null?vt:"";rt&&o.push(T({type:"text",item_id:G,text:rt,annotations:($==null?void 0:$.annotations)||[]}))}}else nt==="code_interpreter_call"&&o.push(T({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=xt(o,n||[]);return Tt(s,t)},pe=(e,t)=>{var s,i,l,c;let o=[],n=[];if("contentBlockDelta"in e){let p=((s=e.contentBlockDelta)==null?void 0:s.delta)||{};if("reasoningContent"in p){let m=((i=p.reasoningContent)==null?void 0:i.text)||"",b=((l=p.reasoningContent)==null?void 0:l.signature)||"";o.push(T({type:"thinking",thinking:m,signature:b}))}else if("text"in p)o.push(T({type:"text",text:p.text||""}));else if("toolUse"in p){let m=p.toolUse||{};n.push(D(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in e){let p=((c=e.contentBlockStart)==null?void 0:c.start)||{};if("toolUse"in p){let m=p.toolUse||{};n.push(D(m.toolUseId||"",m.name||"",""))}}let r=xt(o,n);return Tt(r,t)};var de=["openai","openai.azure"],Pt=e=>{var n,r,s,i,l,c,p,m,b,y,R,w,E,A,C,g,O,N,W,B,I,k,J,M,V,K,z,Q,X,v,tt,et,j,ot,at,ct,pt,lt,ut,mt,dt,ft,_t,yt,ht,gt,bt,Rt,wt;let t={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 S of e){let L=S==null?void 0:S.type;if(L==="response.created"){let u=S.response||{};t.id=(n=u.id)!=null?n:t.id,t.created_at=(r=u.created_at)!=null?r:t.created_at,t.model=(s=u.model)!=null?s:t.model,t.status=(i=u.status)!=null?i:t.status,t.parallel_tool_calls=(l=u.parallel_tool_calls)!=null?l:t.parallel_tool_calls,t.temperature=(c=u.temperature)!=null?c:t.temperature,t.tool_choice=(p=u.tool_choice)!=null?p:t.tool_choice,t.tools=(m=u.tools)!=null?m:t.tools,t.top_p=(b=u.top_p)!=null?b:t.top_p,t.truncation=(y=u.truncation)!=null?y:t.truncation,t.max_output_tokens=(R=u.max_output_tokens)!=null?R:t.max_output_tokens,t.previous_response_id=(w=u.previous_response_id)!=null?w:t.previous_response_id,t.store=(E=u.store)!=null?E:t.store,t.user=(A=u.user)!=null?A:t.user,t.metadata=(C=u.metadata)!=null?C:t.metadata;let d=u.text;d&&(t.text=d);let x=u.reasoning;x&&(t.reasoning=x);continue}if(L==="response.in_progress"){let u=S.response||{};t.status=(g=u.status)!=null?g:t.status;continue}if(L==="response.output_item.added"){let u=S.item||{},d=u.id,x=u.type;x==="reasoning"?o[d]={type:"reasoning",id:d,summary:[],status:(O=u.status)!=null?O:"in_progress"}:x==="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"}:x==="message"?o[d]={type:"message",id:d,role:(W=u.role)!=null?W:"assistant",content:[],status:(B=u.status)!=null?B:"in_progress"}:x==="code_interpreter_call"&&(o[d]={type:"code_interpreter_call",id:d,container_id:u.container_id,code:(I=u.code)!=null?I:"",status:(k=u.status)!=null?k:"in_progress"});continue}if(L==="response.reasoning_summary_part.added"){let u=S.item_id,d=S.part||{};if(u in o&&o[u].type==="reasoning"){let x={type:(J=d.type)!=null?J:"summary_text",text:(M=d.text)!=null?M:""};o[u].summary.push(x)}continue}if(L==="response.reasoning_summary_text.delta"){let u=S.item_id,d=(V=S.delta)!=null?V:"",x=(K=S.summary_index)!=null?K:0;if(u in o&&o[u].type==="reasoning"){for(;o[u].summary.length<=x;)o[u].summary.push({type:"summary_text",text:""});o[u].summary[x].text+=d}continue}if(L==="response.reasoning_summary_text.done"){let u=S.item_id,d=(z=S.text)!=null?z:"",x=(Q=S.summary_index)!=null?Q:0;if(u in o&&o[u].type==="reasoning"){for(;o[u].summary.length<=x;)o[u].summary.push({type:"summary_text",text:""});o[u].summary[x].text=d}continue}if(L==="response.reasoning_summary_part.done"){let u=S.item_id,d=S.part||{};if(u in o&&o[u].type==="reasoning"){let x=(X=S.summary_index)!=null?X:0;x<o[u].summary.length&&(o[u].summary[x]={type:(v=d.type)!=null?v:"summary_text",text:(tt=d.text)!=null?tt:""})}continue}if(L==="response.function_call_arguments.delta"){let u=S.item_id,d=(et=S.delta)!=null?et:"";u in o&&(o[u].arguments=`${o[u].arguments||""}${d}`);continue}if(L==="response.function_call_arguments.done"){let u=S.item_id,d=(j=S.arguments)!=null?j:"";u in o&&(o[u].arguments=d);continue}if(L==="response.content_part.added"){let u=S.part||{},d=Object.values(o).find(x=>x.type==="message");if(d){let x={type:(ot=u.type)!=null?ot:"output_text",text:(at=u.text)!=null?at:"",annotations:(ct=u.annotations)!=null?ct:[]};d.content.push(x)}continue}if(L==="response.output_text.delta"){let u=(pt=S.delta)!=null?pt:"";for(let d of Object.values(o))if(d.type==="message"&&d.content&&d.content.length){let x=d.content[d.content.length-1];x&&x.type==="output_text"&&(x.text=`${x.text||""}${u}`);break}continue}if(L==="response.output_text.done"){let u=(lt=S.text)!=null?lt:"";for(let d of Object.values(o))if(d.type==="message"&&d.content&&d.content.length){let x=d.content[d.content.length-1];x&&x.type==="output_text"&&(x.text=u);break}continue}if(L==="response.output_item.done"){let u=S.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),t.output.push(o[d]));continue}if(L==="response.completed"){let u=S.response||{};t.status=(bt=(gt=u.status)!=null?gt:t.status)!=null?bt:"completed",t.usage=(Rt=u.usage)!=null?Rt:t.usage,t.output=(wt=u.output)!=null?wt:t.output,u.reasoning&&(t.reasoning=u.reasoning);continue}}return t},Gt=e=>{var l,c,p,m,b,y,R,w,E,A;let t=null,o,n={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},r=e.at(-1);if(!r)return n;let s;for(let C of e){if(C.choices.length===0)continue;let g=C.choices[0].delta;g.content&&(t=`${t||""}${g.content||""}`),g.function_call&&(o={name:`${o?o.name:""}${g.function_call.name||""}`,arguments:`${o?o.arguments:""}${g.function_call.arguments||""}`});let O=(l=g.tool_calls)==null?void 0:l[0];if(O){s=s||[];let N=s.at(-1);if(!N||O.id){s.push({id:O.id||"",type:O.type||"function",function:{name:((c=O.function)==null?void 0:c.name)||"",arguments:((p=O.function)==null?void 0:p.arguments)||""}});continue}N.function.name=`${N.function.name}${((m=O.function)==null?void 0:m.name)||""}`,N.function.arguments=`${N.function.arguments}${((b=O.function)==null?void 0:b.arguments)||""}`}}let i=e[0].choices.at(0);return n.choices.push({finish_reason:(y=i==null?void 0:i.finish_reason)!=null?y:"stop",index:(R=i==null?void 0:i.index)!=null?R:0,logprobs:(w=i==null?void 0:i.logprobs)!=null?w:null,message:{role:"assistant",content:t,function_call:o||void 0,tool_calls:s||void 0,refusal:(E=i==null?void 0:i.delta.refusal)!=null?E:null}}),n.id=r.id,n.model=r.model,n.created=r.created,n.system_fingerprint=r.system_fingerprint,n.usage=(A=r.usage)!=null?A:void 0,n},le=e=>{let t={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},o=e.at(-1);if(!o)return t;let n="";for(let r of e)r.choices.length>0&&r.choices[0].text&&(n=`${n}${r.choices[0].text}`);return t.choices[0].text=n,t.id=o.id,t.created=o.created,t.model=o.model,t.system_fingerprint=o.system_fingerprint,t.usage=o.usage,t},Mt=e=>{var c;let t={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(!e.at(-1))return t;let n=null,r="",s="",i="",l="";for(let p of e)if(p.type==="message_start")t=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={}}t.content.push(n),n=null,r="",s="",i="",l=""}else p.type==="message_delta"&&("usage"in p&&p.usage&&(t.usage=F(h({},t.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&&(t.stop_reason=p.delta.stop_reason),"stop_sequence"in p.delta&&p.delta.stop_sequence!==void 0&&(t.stop_sequence=p.delta.stop_sequence)));return t},ue=e=>{let t={completion:"",id:"",model:"",stop_reason:"",type:"completion"},o=e.at(-1);if(!o)return t;let n="";for(let r of e)n=`${n}${r.completion}`;return t.completion=n,t.id=o.id,t.model=o.model,t.stop_reason=o.stop_reason,t},oo=e=>{var i,l,c,p,m,b,y,R,w,E;let t=null,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},n=e.at(-1).data;if(!n)return o;let r;for(let A of e){if(A.data.choices.length===0)continue;let C=A.data.choices[0].delta;C.content&&(t=`${t||""}${C.content||""}`);let g=(i=C.toolCalls)==null?void 0:i[0];if(g){r=r||[];let O=r.at(-1);if(!O||g.id){r.push({id:g.id||"",type:g.type||"function",function:{name:((l=g.function)==null?void 0:l.name)||"",arguments:((c=g.function)==null?void 0:c.arguments)||""}});continue}O.function.name=`${O.function.name}${((p=g.function)==null?void 0:p.name)||""}`,O.function.arguments=`${O.function.arguments}${((m=g.function)==null?void 0:m.arguments)||""}`}}let s=e[0].data.choices.at(0);return o.choices.push({finish_reason:(b=s==null?void 0:s.finish_reason)!=null?b:"stop",index:(y=s==null?void 0:s.index)!=null?y:0,logprobs:(R=s==null?void 0:s.logprobs)!=null?R:null,message:{role:"assistant",content:t,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=(E=n.usage)!=null?E:void 0,o},me=e=>{let t={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},o=[],n=null,r="",s="",i="",l="";for(let c of e)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)t.stopReason=c.messageStop.stopReason;else if("metadata"in c){let p=c.metadata;t.usage=(p==null?void 0:p.usage)||{},t.metrics=(p==null?void 0:p.metrics)||{}}return t.output.message={role:"assistant",content:o},t},no=(e,t,o,n)=>{var i,l;let r=h({},n),s=[];if(e){let c={text:e,thought:!0};s.push(c)}if(t){let c={text:t,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=e=>{var s,i;let{GenerateContentResponse:t}=st("@google/genai");if(!e.length)return new t;let o="",n="",r=[];for(let l of e)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 no(o,n,r,e[e.length-1])},ro=e=>fe(e),so=e=>fe(e),_e=(e,t="openai.chat.completions.create")=>{if(t==="openai.responses.create"||t==="openai.AzureOpenAI.responses.create")return Pt(e);if("completion"in e[0])return e.reduce((o,n)=>F(h({},n),{completion:`${o.completion}${n.completion}`}),{});if(t==="anthropic.messages.create")return Mt(e);if("text"in e[0].choices[0]){let o="";for(let r of e)o=`${o}${r.choices[0].text}`;let n=structuredClone(e.at(-1));return n.choices[0].text=o,n}if("delta"in e[0].choices[0]){let o=Gt(e);return o.choices[0]=h(h({},o.choices[0]),o.choices[0].message),o}return""},io=(e,t)=>{let o=t.model.provider,n=t.model.name;return o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&n.startsWith("claude")?ie(e,t):o==="google"||o==="vertexai"&&n.startsWith("gemini")?ae(e,t):o==="amazon.bedrock"?pe(e,t):o==="mistral"?Wt(e.data,t):o==="openai"||o==="openai.azure"?(t.model.api_type||"chat-completions")==="responses"?ce(e,t):Wt(e,t):null};function ye(e,t,o,n){return At(this,null,function*(){let r={request_id:null,raw_response:null,prompt_blueprint:null},s={},i=n.model.provider;i=="amazon.bedrock"&&(s=e==null?void 0:e.$metadata,e=e==null?void 0:e.stream);let l=[];try{for(var m=Ct(e),b,y,R;b=!(y=yield new Z(m.next())).done;b=!1){let w=y.value;l.push(w),r.raw_response=w,r.prompt_blueprint=io(w,n),yield r}}catch(y){R=[y]}finally{try{b&&(y=m.return)&&(yield new Z(y.call(m)))}finally{if(R)throw R[0]}}let c=o(l);i==="amazon.bedrock"&&(c.ResponseMetadata=s);let p=yield new Z(t({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:Gt},completion:{function_name:"openai.completions.create",stream_function:le}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:Pt},completion:{function_name:"openai.responses.create",stream_function:Pt}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:Mt},completion:{function_name:"anthropic.completions.create",stream_function:ue}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:Gt},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:le}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:Pt},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:Pt}},google:{chat:{function_name:"google.convo.send_message",stream_function:ro},completion:{function_name:"google.model.generate_content",stream_function:so}},"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:Mt},completion:{function_name:"anthropic.completions.create",stream_function:ue}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:oo},completion:{function_name:"",stream_function:null}}};var be="1.0.59",lo=()=>{var e;if(typeof process!="undefined"&&((e=process.versions)!=null&&e.node)){let t=process.versions.node.split(".");return`${t[0]}.${t[1]}`}return"unknown"},uo=lo(),mo=`promptlayer-js/${be} (node ${uo})`,U=()=>({"User-Agent":mo,"X-SDK-Version":be}),Kt="SET_WORKFLOW_COMPLETE";function fo(e,t,o,n){return _(this,null,function*(){let r=yield q(`${e}/workflow-version-execution-results?workflow_version_execution_id=${t}&return_all_outputs=${o}`,h({headers:n},U()));if(!r.ok)throw new Error("Failed to fetch final output");return r.json()})}function Re(e,t,o,n,r){return function(s){return _(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 fo(e,o,n,r),t.resolve(c);else throw new Error(`Unsupported final output code: ${l}`);t.resolve(c)}catch(i){t.reject(i)}})}}function _o(l){return _(this,arguments,function*({token:e,channelName:t,executionId:o,returnAllOutputs:n,headers:r,timeout:s,baseURL:i}){let c=new ao.Realtime(e),p=c.channels.get(t),m={},b=new Promise((R,w)=>{m.resolve=R,m.reject=w}),y=Re(i,m,o,n,r);yield p.subscribe(Kt,y);try{return yield new Promise((R,w)=>{let E=setTimeout(()=>{w(new Error("Workflow execution did not complete properly (timeout)"))},s);b.then(A=>{clearTimeout(E),R(A)}).catch(A=>{clearTimeout(E),w(A)})})}finally{console.log("Closing client"),p.unsubscribe(Kt,y),c.close(),console.log("Closed client")}})}var q=(e,t)=>_(null,null,function*(){return po(()=>_(null,null,function*(){let o=yield fetch(e,t);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=(e,t,o,n=!0)=>_(null,null,function*(){return o.request_response[Symbol.asyncIterator]!==void 0?ho(e,t,o.request_response,o,n):yield xe(e,t,o,n)}),xe=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/track-request`,{method:"POST",headers:h({"Content-Type":"application/json"},U()),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}),Te=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/library-track-metadata`,{method:"POST",headers:h({"Content-Type":"application/json"},U()),body:JSON.stringify(F(h({},o),{api_key:e}))}),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}),Pe=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/library-track-score`,{method:"POST",headers:h({"Content-Type":"application/json"},U()),body:JSON.stringify(F(h({},o),{api_key:e}))}),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}),Se=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/library-track-prompt`,{method:"POST",headers:h({"Content-Type":"application/json"},U()),body:JSON.stringify(F(h({},o),{api_key:e}))}),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}),Ee=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/track-group`,{method:"POST",headers:h({"Content-Type":"application/json"},U()),body:JSON.stringify(F(h({},o),{api_key:e}))}),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}),Oe=(e,t,o=!0)=>_(null,null,function*(){try{let n=yield q(`${t}/create-group`,{method:"POST",headers:h({"Content-Type":"application/json"},U()),body:JSON.stringify({api_key:e})}),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}}),Ae=(e,t,o,n,r=!0)=>_(null,null,function*(){try{let s=new URL(`${t}/prompt-templates/${o}`),i=yield q(s,{method:"POST",headers:h({"Content-Type":"application/json","X-API-KEY":e},U()),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}}),Ce=(e,t,o,n=!0)=>_(null,null,function*(){let r=yield q(`${t}/rest/prompt-templates`,{method:"POST",headers:h({"Content-Type":"application/json","X-API-KEY":e},U()),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}),Ie=(e,t,o,n=!0)=>_(null,null,function*(){var l;let r=new URL(`${t}/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":e},U())}),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:[]}),yo=e=>_(null,null,function*(){let t=new URL(`${e.baseURL}/connection/websocket`);t.protocol=t.protocol==="https:"?"wss:":"ws:";let o=new co(t.toString(),{token:e.token}),n=o.newSubscription(e.channelName);return new Promise((r,s)=>{let i=m=>{p(),r(m)},l=Re(e.baseURL,{resolve:i,reject:s},e.executionId,e.returnAllOutputs,e.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)"))},e.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=>_(null,[p],function*({workflow_name:e,input_variables:t,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:t,metadata:o,workflow_label_name:n,workflow_version_number:r,return_all_outputs:s},b=h({"Content-Type":"application/json","X-API-KEY":i},U());try{let y=yield q(`${c}/workflows/${encodeURIComponent(e)}/run`,{method:"POST",headers:b,body:JSON.stringify(m)});if(y.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield y.json().catch(()=>({}))).error||y.statusText}`};let R=yield y.json();R.warning&&console.warn(`WARNING: ${R.warning}`);let w=R.workflow_version_execution_id;if(!w)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let E=`workflow_updates:${w}`,C=yield(yield q(`${c}/ws-token-request-library?capability=${E}`,{method:"POST",headers:b})).json(),O={token:C.token_details.token,channelName:E,executionId:w,returnAllOutputs:s,headers:b,timeout:l,baseURL:c};return C.messaging_backend==="centrifugo"?yo(O):yield _o(O)}catch(y){throw console.error(`Failed to run workflow: ${y instanceof Error?y.message:y}`),y}});function ho(e,t,o,n,r=!0){return At(this,null,function*(){let s=[];try{for(var c=Ct(o),p,m,b;p=!(m=yield new Z(c.next())).done;p=!1){let y=m.value;yield n.return_pl_id?[y,null]:y,s.push(y)}}catch(m){b=[m]}finally{try{p&&(m=c.return)&&(yield new Z(m.call(c)))}finally{if(b)throw b[0]}}let i=_e(s,n.function_name),l=yield new Z(xe(e,t,F(h({},n),{request_response:i,request_end_time:new Date().toISOString()}),r));if(l&&n.return_pl_id){let y=l[1];yield[s.at(-1),y]}})}var Y=(e,t)=>{try{console.warn(`${t}: ${e.message}`)}catch(o){console.warn(`${t}: ${e}`)}},Ne=(e,t,o=!0)=>_(null,null,function*(){try{let n=yield q(`${e}/track-request`,{method:"POST",headers:h({"Content-Type":"application/json"},U()),body:JSON.stringify(t)}),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{}}),go=(e,t)=>_(null,null,function*(){return yield e.chat.completions.create(t)}),bo=(e,t)=>_(null,null,function*(){return yield e.completions.create(t)}),Le={chat:go,completion:bo},qe=(e,t)=>_(null,null,function*(){var s,i;let o=st("openai").default,n=new o({baseURL:t.baseURL,apiKey:t.apiKey});if(t==null||delete t.apiKey,t==null||delete t.baseURL,((i=(s=e.metadata)==null?void 0:s.model)==null?void 0:i.api_type)==="chat-completions"){let l=Le[e.prompt_template.type];return yield l(n,t)}else return yield n.responses.create(t)}),Ue=(e,t)=>_(null,null,function*(){var s,i;let{AzureOpenAI:o}=st("openai"),n=new o({endpoint:process.env.AZURE_OPENAI_ENDPOINT||t.baseURL,apiVersion:process.env.OPENAI_API_VERSION||t.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||t.apiKey});if(t==null||delete t.baseURL,t==null||delete t.apiVersion,t==null||delete t.apiKey,((i=(s=e.metadata)==null?void 0:s.model)==null?void 0:i.api_type)==="chat-completions"){let l=Le[e.prompt_template.type];return yield l(n,t)}else return yield n.responses.create(t)}),$e=(e,t)=>_(null,null,function*(){return e.messages.create(t)}),Ro=(e,t)=>_(null,null,function*(){return e.completions.create(t)}),We={chat:$e,completion:Ro},Ge=(e,t)=>_(null,null,function*(){let o=st("@anthropic-ai/sdk").default,n=new o({baseURL:t.baseURL,apiKey:t.apiKey}),r=We[e.prompt_template.type];return r(n,t)}),Me=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/log-request`,{method:"POST",headers:h({"Content-Type":"application/json","X-API-KEY":e},U()),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}}),wo=(e,t)=>_(null,null,function*(){var i,l;let o=t==null?void 0:t.history,n=t==null?void 0:t.generationConfig,r=o.length>0?(i=o[o.length-1])==null?void 0:i.parts:"",s=e.chats.create({model:t==null?void 0:t.model,history:(l=o.slice(0,-1))!=null?l:[],config:n});return t!=null&&t.stream?yield s.sendMessageStream({message:r}):yield s.sendMessage({message:r})}),xo=(e,n)=>_(null,null,function*(){var r=n,{stream:t}=r,o=Ot(r,["stream"]);return t?yield e.generateContentStream(h({},o)):yield e.generateContent(h({},o))}),To={chat:wo,completion:xo},jt=(e,t)=>_(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=To[e.prompt_template.type];return yield c(l,t)}),ge=e=>e.replace(/_([a-z])/g,(t,o)=>o.toUpperCase()),It=(e,t=new Set)=>!e||typeof e!="object"?e:Array.isArray(e)?e.map(o=>It(o,t)):Object.fromEntries(Object.entries(e).map(([o,n])=>t.has(o)?[ge(o),n]:[ge(o),It(n,t)])),Ke=(e,t,o={},n=!1)=>{var c,p,m,b,y,R,w,E,A;let r=(m=t==null?void 0:t.client)!=null?m:(p=(c=e.metadata)==null?void 0:c.model)==null?void 0:p.provider,s=(y=(b=e.metadata)==null?void 0:b.model)==null?void 0:y.api_type;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let i=F(h({},e.llm_kwargs||{}),{stream:n});["google","vertexai"].includes(r)&&((w=(R=e.metadata)==null?void 0:R.model)!=null&&w.name.startsWith("gemini"))&&(i=It(i,new Set(["function_declarations","properties"])));let l={baseURL:(A=t==null?void 0:t.base_url)!=null?A:(E=e.provider_base_url)==null?void 0:E.url,apiKey:t==null?void 0:t.api_key};return Object.entries(l).forEach(([C,g])=>{g!==void 0&&(i[C]=g)}),n&&de.includes(r)&&s==="chat-completions"&&(i.stream_options={include_usage:!0}),{provider_type:r,kwargs:i}},je=(e,t)=>{let o=he[e];if(!o)throw new Error(`Unsupported provider type: ${e}`);let n=t.type,r=o[n];if(!r)throw new Error(`Unsupported template type '${t.type}' for provider '${e}'`);return r},Fe=(e,t)=>_(null,null,function*(){var n;let o=(n=e.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(e,t);if(o.name.startsWith("claude")){let{AnthropicVertex:r}=yield import("@anthropic-ai/vertex-sdk"),s=new r({baseURL:t.baseURL});if(e.prompt_template.type==="chat")return $e(s,t);throw new Error(`Unsupported prompt template type '${e.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${o.name}' for Vertex AI request`)}),De=(e,t)=>_(null,null,function*(){let{BedrockRuntimeClient:o,ConverseCommand:n,ConverseStreamCommand:r}=yield import("@aws-sdk/client-bedrock-runtime"),s=new o({credentials:{accessKeyId:(t==null?void 0:t.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(t==null?void 0:t.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(t==null?void 0:t.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(t==null?void 0:t.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(t!=null&&t.stream){delete t.stream;let i=new r(h({},t));return yield s.send(i)}else{t==null||delete t.stream;let i=new n(h({},t));return yield s.send(i)}}),Be=(e,t)=>_(null,null,function*(){let{AnthropicBedrock:o}=yield import("@anthropic-ai/bedrock-sdk"),n=new o({awsAccessKey:t.aws_access_key,awsSecretKey:t.aws_secret_key,awsRegion:t.aws_region,awsSessionToken:t.aws_session_token,baseURL:t.base_url}),r=We[e.prompt_template.type];return r(n,t)}),Je=(e,t)=>_(null,null,function*(){let{Mistral:o}=yield import("@mistralai/mistralai"),n=new o({apiKey:process.env.MISTRAL_API_KEY});return t=It(t,new Set),t!=null&&t.stream?(delete t.stream,yield n.chat.stream(t)):(delete t.stream,yield n.chat.complete(t))}),Ft=e=>{var t,o,n,r,s,i;if(typeof globalThis.process!="undefined")return(n=(o=(t=globalThis.process.env)==null?void 0:t[e])==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,e))==null?void 0:i.trim()};var kt=class{constructor(t,o,n=!0){this.create=()=>Oe(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=t,this.baseURL=o,this.throwOnError=n}};import{SpanKind as St,SpanStatusCode as Dt}from"@opentelemetry/api";import{ExportResultCode as Nt}from"@opentelemetry/core";var Bt=class{constructor(t,o,n){this.apiKey=o,this.baseURL=n,this.enableTracing=t,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(t){return t?Object.fromEntries(Object.entries(t)):{}}spanKindToString(t){return{[St.INTERNAL]:"SpanKind.INTERNAL",[St.SERVER]:"SpanKind.SERVER",[St.CLIENT]:"SpanKind.CLIENT",[St.PRODUCER]:"SpanKind.PRODUCER",[St.CONSUMER]:"SpanKind.CONSUMER"}[t]||"SpanKind.INTERNAL"}statusCodeToString(t){return{[Dt.ERROR]:"StatusCode.ERROR",[Dt.OK]:"StatusCode.OK",[Dt.UNSET]:"StatusCode.UNSET"}[t]||"StatusCode.UNSET"}toNanoseconds(t){return(BigInt(t[0])*BigInt(1e9)+BigInt(t[1])).toString()}export(t){if(!this.enableTracing)return Promise.resolve(Nt.SUCCESS);let o=t.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:F(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||""},U()),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
|