promptlayer 1.0.55 → 1.0.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/index.d.mts +8 -2
- package/dist/index.d.ts +8 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/types.ts +8 -0
- package/src/utils/blueprint-builder.ts +142 -15
- package/src/utils/streaming.ts +8 -0
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Ie=Object.defineProperty,ke=Object.defineProperties;var Le=Object.getOwnPropertyDescriptors;var ct=Object.getOwnPropertySymbols;var $t=Object.prototype.hasOwnProperty,Wt=Object.prototype.propertyIsEnumerable;var qt=(e,t)=>{if(t=Symbol[e])return t;throw Error("Symbol."+e+" is not defined")};var Ut=(e,t,n)=>t in e?Ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,P=(e,t)=>{for(var n in t||(t={}))$t.call(t,n)&&Ut(e,n,t[n]);if(ct)for(var n of ct(t))Wt.call(t,n)&&Ut(e,n,t[n]);return e},K=(e,t)=>ke(e,Le(t));var nt=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var lt=(e,t)=>{var n={};for(var o in e)$t.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&ct)for(var o of ct(e))t.indexOf(o)<0&&Wt.call(e,o)&&(n[o]=e[o]);return n};var f=(e,t,n)=>new Promise((o,r)=>{var s=i=>{try{l(n.next(i))}catch(c){r(c)}},a=i=>{try{l(n.throw(i))}catch(c){r(c)}},l=i=>i.done?o(i.value):Promise.resolve(i.value).then(s,a);l((n=n.apply(e,t)).next())}),V=function(e,t){this[0]=e,this[1]=t},pt=(e,t,n)=>{var o=(a,l,i,c)=>{try{var m=n[a](l),h=(l=m.value)instanceof V,_=m.done;Promise.resolve(h?l[0]:l).then(g=>h?o(a==="return"?a:"next",l[1]?{done:g.done,value:g.value}:g,i,c):i({value:g,done:_})).catch(g=>o("throw",g,i,c))}catch(g){c(g)}},r=a=>s[a]=l=>new Promise((i,c)=>o(a,l,i,c)),s={};return n=n.apply(e,t),s[Symbol.asyncIterator]=()=>s,r("next"),r("throw"),r("return"),s};var ut=(e,t,n)=>(t=e[qt("asyncIterator")])?t.call(e):(e=e[qt("iterator")](),t={},n=(o,r)=>(r=e[o])&&(t[o]=s=>new Promise((a,l,i)=>(s=r.call(e,s),i=s.done,Promise.resolve(s.value).then(c=>a({value:c,done:i}),l)))),n("next"),n("return"),t);import Ge from"ably";import{Centrifuge as Me}from"centrifuge";import Ke from"p-retry";var B=(e,t,n,o)=>{let r={id:e,function:{name:t,input:n}};return o&&(r.tool_id=o),r},I=o=>{var r=o,{type:e,item_id:t}=r,n=lt(r,["type","item_id"]);let s=P({type:e},n);return t&&(s.item_id=t),s},rt=(e,t)=>({input_variables:[],template_format:"f-string",content:e,role:"assistant",function_call:null,name:null,tool_calls:t}),st=(e,t)=>({prompt_template:{messages:[e],type:"chat",input_variables:[]},metadata:t}),Gt=(e,t)=>{let n=[],o=[];e.type==="content_block_start"?e.content_block.type==="thinking"?n.push(I({type:"thinking",thinking:"",signature:""})):e.content_block.type==="text"?n.push(I({type:"text",text:""})):e.content_block.type==="tool_use"&&o.push(B(e.content_block.id||"",e.content_block.name||"",{})):e.type==="content_block_delta"&&(e.delta.type==="thinking_delta"?n.push(I({type:"thinking",thinking:e.delta.thinking||"",signature:""})):e.delta.type==="text_delta"?n.push(I({type:"text",text:e.delta.text||""})):e.delta.type==="signature_delta"?n.push(I({type:"thinking",thinking:"",signature:e.delta.signature||""})):e.delta.type==="input_json_delta"&&o.push(B("","",e.delta.partial_json)));let r=rt(n,o);return st(r,t)},Mt=(e,t)=>{let n=[],o=[];for(let s of e.candidates)if(s.content&&s.content.parts&&Array.isArray(s.content.parts))for(let a of s.content.parts)a.text?a.thought===!0?n.push(I({type:"thinking",thinking:a.text,signature:a.thoughtSignature||""})):n.push(I({type:"text",text:a.text})):a.functionCall&&o.push(B(a.functionCall.id||"",a.functionCall.name||"",a.functionCall.args||{}));let r=rt(n,o);return st(r,t)},gt=(e,t)=>{let n=[],o=[];for(let s of e.choices)if(s.delta){s.delta.content&&n.push(I({type:"text",text:s.delta.content}));let a=s.delta.tool_calls||s.delta.toolCalls;if(a&&Array.isArray(a))for(let l of a)l.function&&o.push(B(l.id||"",l.function.name||"",l.function.arguments||""))}let r=rt(n,o);return st(r,t)},Kt=(e,t)=>{var a,l,i,c,m,h,_,g,b,x,E,O,y,T,L,$,j,A,k,F,W,z,G,D,X,Y,v,H,Z,M,tt;let n=[],o=[],r=e==null?void 0:e.type;if(r==="response.reasoning_summary_text.delta"){let p=(a=e==null?void 0:e.delta)!=null?a:"",w=(l=e==null?void 0:e.item_id)!=null?l:"";p&&n.push(I({type:"thinking",item_id:w,thinking:p,signature:""}))}else if(r==="response.reasoning_summary_text.done"){let p=(i=e==null?void 0:e.text)!=null?i:"",w=(c=e==null?void 0:e.item_id)!=null?c:"";p&&n.push(I({type:"thinking",item_id:w,thinking:p,signature:""}))}else if(r==="response.reasoning_summary_part.added"){let p=(m=e==null?void 0:e.part)!=null?m:{},w=(h=e==null?void 0:e.item_id)!=null?h:"";if((p==null?void 0:p.type)==="summary_text"){let C=(_=p==null?void 0:p.text)!=null?_:"";n.push(I({type:"thinking",item_id:w,thinking:C,signature:""}))}}else if(r==="response.reasoning_summary_part.done"){let p=(g=e==null?void 0:e.part)!=null?g:{},w=(b=e==null?void 0:e.item_id)!=null?b:"";if((p==null?void 0:p.type)==="summary_text"){let C=(x=p==null?void 0:p.text)!=null?x:"";C&&n.push(I({type:"thinking",item_id:w,thinking:C,signature:""}))}}else if(r==="response.function_call_arguments.delta"){let p=(E=e==null?void 0:e.item_id)!=null?E:"",w=(O=e==null?void 0:e.delta)!=null?O:"";w&&o.push(B("","",w,p))}else if(r==="response.function_call_arguments.done"){let p=(y=e==null?void 0:e.item_id)!=null?y:"",w=(T=e==null?void 0:e.arguments)!=null?T:"";w&&o.push(B("","",w,p))}else if(r==="response.output_item.added"){let p=(L=e==null?void 0:e.item)!=null?L:{},w=p==null?void 0:p.type,C=($=p==null?void 0:p.id)!=null?$:"";w==="reasoning"?n.push(I({type:"thinking",thinking:"",signature:"",item_id:C})):w==="function_call"?o.push(B((p==null?void 0:p.call_id)||"",(p==null?void 0:p.name)||"","",C)):w==="message"&&n.push(I({type:"text",item_id:C,text:""}))}else if(r==="response.content_part.added"){let p=(j=e==null?void 0:e.part)!=null?j:{},w=(A=p==null?void 0:p.type)!=null?A:"output_text",C=(k=e==null?void 0:e.item_id)!=null?k:"";w==="output_text"&&n.push(I({type:"text",item_id:C,text:(F=p==null?void 0:p.text)!=null?F:"",annotations:(p==null?void 0:p.annotations)||[]}))}else if(r==="response.output_text.annotation.added"){let p=(e==null?void 0:e.annotation)||{},w=p==null?void 0:p.type,C=null;w==="url_citation"?C={type:"url_citation",title:p==null?void 0:p.title,url:p==null?void 0:p.url,start_index:p==null?void 0:p.start_index,end_index:p==null?void 0:p.end_index}:w=="file_citation"?C={type:"file_citation",index:p==null?void 0:p.index,file_id:p==null?void 0:p.file_id,filename:p==null?void 0:p.filename}:C=p,n.push(I({type:"text",item_id:(W=e==null?void 0:e.item_id)!=null?W:"",text:"",annotations:[C]}))}else if(r==="response.output_text.delta"){let p=(z=e==null?void 0:e.delta)!=null?z:"";p&&n.push(I({type:"text",item_id:(G=e==null?void 0:e.item_id)!=null?G:"",text:p}))}else if(r==="response.output_text.done"){let p=(D=e==null?void 0:e.text)!=null?D:"";p&&n.push(I({type:"text",item_id:(X=e==null?void 0:e.item_id)!=null?X:"",text:p}))}else if(r==="response.output_item.done"){let p=(Y=e==null?void 0:e.item)!=null?Y:{},w=p==null?void 0:p.type,C=(v=p==null?void 0:p.id)!=null?v:"";if(w==="reasoning"){let et=(H=p==null?void 0:p.summary)!=null?H:[];for(let N of et)if((N==null?void 0:N.type)==="summary_text"){let Q=(Z=N==null?void 0:N.text)!=null?Z:"";Q&&n.push(I({type:"thinking",item_id:C,thinking:Q,signature:""}))}}else if(w==="function_call")o.push(B((p==null?void 0:p.call_id)||"",(p==null?void 0:p.name)||"",(p==null?void 0:p.arguments)||"",C));else if(w==="message"){let et=(M=p==null?void 0:p.content)!=null?M:[];for(let N of et)if((N==null?void 0:N.type)==="output_text"){let Q=(tt=N==null?void 0:N.text)!=null?tt:"";Q&&n.push(I({type:"text",item_id:C,text:Q}))}}}let s=rt(n,o||[]);return st(s,t)},jt=(e,t)=>{var s,a,l,i;let n=[],o=[];if("contentBlockDelta"in e){let c=((s=e.contentBlockDelta)==null?void 0:s.delta)||{};if("reasoningContent"in c){let m=((a=c.reasoningContent)==null?void 0:a.text)||"",h=((l=c.reasoningContent)==null?void 0:l.signature)||"";n.push(I({type:"thinking",thinking:m,signature:h}))}else if("text"in c)n.push(I({type:"text",text:c.text||""}));else if("toolUse"in c){let m=c.toolUse||{};o.push(B(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in e){let c=((i=e.contentBlockStart)==null?void 0:i.start)||{};if("toolUse"in c){let m=c.toolUse||{};o.push(B(m.toolUseId||"",m.name||"",""))}}let r=rt(n,o);return st(r,t)};var Jt=["openai","openai.azure"],at=e=>{var o,r,s,a,l,i,c,m,h,_,g,b,x,E,O,y,T,L,$,j,A,k,F,W,z,G,D,X,Y,v,H,Z,M,tt,p,w,C,et,N,Q,Ot,At,Ct,It,kt,Lt,Nt;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:{}},n={};for(let S of e){let U=S==null?void 0:S.type;if(U==="response.created"){let u=S.response||{};t.id=(o=u.id)!=null?o: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=(a=u.status)!=null?a:t.status,t.parallel_tool_calls=(l=u.parallel_tool_calls)!=null?l:t.parallel_tool_calls,t.temperature=(i=u.temperature)!=null?i:t.temperature,t.tool_choice=(c=u.tool_choice)!=null?c:t.tool_choice,t.tools=(m=u.tools)!=null?m:t.tools,t.top_p=(h=u.top_p)!=null?h:t.top_p,t.truncation=(_=u.truncation)!=null?_:t.truncation,t.max_output_tokens=(g=u.max_output_tokens)!=null?g:t.max_output_tokens,t.previous_response_id=(b=u.previous_response_id)!=null?b:t.previous_response_id,t.store=(x=u.store)!=null?x:t.store,t.user=(E=u.user)!=null?E:t.user,t.metadata=(O=u.metadata)!=null?O:t.metadata;let d=u.text;d&&(t.text=d);let R=u.reasoning;R&&(t.reasoning=R);continue}if(U==="response.in_progress"){let u=S.response||{};t.status=(y=u.status)!=null?y:t.status;continue}if(U==="response.output_item.added"){let u=S.item||{},d=u.id,R=u.type;R==="reasoning"?n[d]={type:"reasoning",id:d,summary:[],status:(T=u.status)!=null?T:"in_progress"}:R==="function_call"?n[d]={type:"function_call",id:d,call_id:u.call_id,name:u.name,arguments:"",status:(L=u.status)!=null?L:"in_progress"}:R==="message"&&(n[d]={type:"message",id:d,role:($=u.role)!=null?$:"assistant",content:[],status:(j=u.status)!=null?j:"in_progress"});continue}if(U==="response.reasoning_summary_part.added"){let u=S.item_id,d=S.part||{};if(u in n&&n[u].type==="reasoning"){let R={type:(A=d.type)!=null?A:"summary_text",text:(k=d.text)!=null?k:""};n[u].summary.push(R)}continue}if(U==="response.reasoning_summary_text.delta"){let u=S.item_id,d=(F=S.delta)!=null?F:"",R=(W=S.summary_index)!=null?W:0;if(u in n&&n[u].type==="reasoning"){for(;n[u].summary.length<=R;)n[u].summary.push({type:"summary_text",text:""});n[u].summary[R].text+=d}continue}if(U==="response.reasoning_summary_text.done"){let u=S.item_id,d=(z=S.text)!=null?z:"",R=(G=S.summary_index)!=null?G:0;if(u in n&&n[u].type==="reasoning"){for(;n[u].summary.length<=R;)n[u].summary.push({type:"summary_text",text:""});n[u].summary[R].text=d}continue}if(U==="response.reasoning_summary_part.done"){let u=S.item_id,d=S.part||{};if(u in n&&n[u].type==="reasoning"){let R=(D=S.summary_index)!=null?D:0;R<n[u].summary.length&&(n[u].summary[R]={type:(X=d.type)!=null?X:"summary_text",text:(Y=d.text)!=null?Y:""})}continue}if(U==="response.function_call_arguments.delta"){let u=S.item_id,d=(v=S.delta)!=null?v:"";u in n&&(n[u].arguments=`${n[u].arguments||""}${d}`);continue}if(U==="response.function_call_arguments.done"){let u=S.item_id,d=(H=S.arguments)!=null?H:"";u in n&&(n[u].arguments=d);continue}if(U==="response.content_part.added"){let u=S.part||{},d=Object.values(n).find(R=>R.type==="message");if(d){let R={type:(Z=u.type)!=null?Z:"output_text",text:(M=u.text)!=null?M:"",annotations:(tt=u.annotations)!=null?tt:[]};d.content.push(R)}continue}if(U==="response.output_text.delta"){let u=(p=S.delta)!=null?p:"";for(let d of Object.values(n))if(d.type==="message"&&d.content&&d.content.length){let R=d.content[d.content.length-1];R&&R.type==="output_text"&&(R.text=`${R.text||""}${u}`);break}continue}if(U==="response.output_text.done"){let u=(w=S.text)!=null?w:"";for(let d of Object.values(n))if(d.type==="message"&&d.content&&d.content.length){let R=d.content[d.content.length-1];R&&R.type==="output_text"&&(R.text=u);break}continue}if(U==="response.output_item.done"){let u=S.item||{},d=u.id;d in n&&(n[d].status=(C=u.status)!=null?C:"completed",u.type==="reasoning"?n[d].summary=(et=u.summary)!=null?et:n[d].summary:u.type==="function_call"?(n[d].arguments=(N=u.arguments)!=null?N:n[d].arguments,n[d].call_id=(Q=u.call_id)!=null?Q:n[d].call_id,n[d].name=(Ot=u.name)!=null?Ot:n[d].name):u.type==="message"&&(n[d].content=(At=u.content)!=null?At:n[d].content,n[d].role=(Ct=u.role)!=null?Ct:n[d].role),t.output.push(n[d]));continue}if(U==="response.completed"){let u=S.response||{};t.status=(kt=(It=u.status)!=null?It:t.status)!=null?kt:"completed",t.usage=(Lt=u.usage)!=null?Lt:t.usage,t.output=(Nt=u.output)!=null?Nt:t.output,u.reasoning&&(t.reasoning=u.reasoning);continue}}return t},bt=e=>{var l,i,c,m,h,_,g,b,x,E;let t=null,n,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},r=e.at(-1);if(!r)return o;let s;for(let O of e){if(O.choices.length===0)continue;let y=O.choices[0].delta;y.content&&(t=`${t||""}${y.content||""}`),y.function_call&&(n={name:`${n?n.name:""}${y.function_call.name||""}`,arguments:`${n?n.arguments:""}${y.function_call.arguments||""}`});let T=(l=y.tool_calls)==null?void 0:l[0];if(T){s=s||[];let L=s.at(-1);if(!L||T.id){s.push({id:T.id||"",type:T.type||"function",function:{name:((i=T.function)==null?void 0:i.name)||"",arguments:((c=T.function)==null?void 0:c.arguments)||""}});continue}L.function.name=`${L.function.name}${((m=T.function)==null?void 0:m.name)||""}`,L.function.arguments=`${L.function.arguments}${((h=T.function)==null?void 0:h.arguments)||""}`}}let a=e[0].choices.at(0);return o.choices.push({finish_reason:(_=a==null?void 0:a.finish_reason)!=null?_:"stop",index:(g=a==null?void 0:a.index)!=null?g:0,logprobs:(b=a==null?void 0:a.logprobs)!=null?b:null,message:{role:"assistant",content:t,function_call:n||void 0,tool_calls:s||void 0,refusal:(x=a==null?void 0:a.delta.refusal)!=null?x:null}}),o.id=r.id,o.model=r.model,o.created=r.created,o.system_fingerprint=r.system_fingerprint,o.usage=(E=r.usage)!=null?E:void 0,o},Ft=e=>{let t={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},n=e.at(-1);if(!n)return t;let o="";for(let r of e)r.choices.length>0&&r.choices[0].text&&(o=`${o}${r.choices[0].text}`);return t.choices[0].text=o,t.id=n.id,t.created=n.created,t.model=n.model,t.system_fingerprint=n.system_fingerprint,t.usage=n.usage,t},Rt=e=>{var i;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 o=null,r="",s="",a="",l="";for(let c of e)if(c.type==="message_start")t=P({},c.message);else if(c.type==="content_block_start")o=P({},c.content_block),o.type==="thinking"?(r="",s=""):o.type==="text"?a="":(o.type==="tool_use"||o.type==="server_tool_use")&&(l="");else if(c.type==="content_block_delta"&&o!==null){if(o.type==="thinking")"signature"in c.delta&&(r=c.delta.signature||""),"thinking"in c.delta&&(s+=c.delta.thinking||"");else if(o.type==="text")"text"in c.delta&&(a+=c.delta.text||"");else if((o.type==="tool_use"||o.type==="server_tool_use")&&c.delta.type==="input_json_delta"){let m=c.delta;l+=m.partial_json||""}}else if(c.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=r,o.thinking=s;else if(o.type==="text")o.text=a,o.citations=null;else if(o.type==="tool_use"||o.type==="server_tool_use")try{o.input=l?JSON.parse(l):{}}catch(m){o.input={}}t.content.push(o),o=null,r="",s="",a="",l=""}else c.type==="message_delta"&&("usage"in c&&c.usage&&(t.usage=K(P({},t.usage),{output_tokens:(i=c.usage.output_tokens)!=null?i:0})),"delta"in c&&c.delta&&("stop_reason"in c.delta&&c.delta.stop_reason!==void 0&&(t.stop_reason=c.delta.stop_reason),"stop_sequence"in c.delta&&c.delta.stop_sequence!==void 0&&(t.stop_sequence=c.delta.stop_sequence)));return t},Dt=e=>{let t={completion:"",id:"",model:"",stop_reason:"",type:"completion"},n=e.at(-1);if(!n)return t;let o="";for(let r of e)o=`${o}${r.completion}`;return t.completion=o,t.id=n.id,t.model=n.model,t.stop_reason=n.stop_reason,t},Ne=e=>{var a,l,i,c,m,h,_,g,b,x;let t=null,n={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=e.at(-1).data;if(!o)return n;let r;for(let E of e){if(E.data.choices.length===0)continue;let O=E.data.choices[0].delta;O.content&&(t=`${t||""}${O.content||""}`);let y=(a=O.toolCalls)==null?void 0:a[0];if(y){r=r||[];let T=r.at(-1);if(!T||y.id){r.push({id:y.id||"",type:y.type||"function",function:{name:((l=y.function)==null?void 0:l.name)||"",arguments:((i=y.function)==null?void 0:i.arguments)||""}});continue}T.function.name=`${T.function.name}${((c=y.function)==null?void 0:c.name)||""}`,T.function.arguments=`${T.function.arguments}${((m=y.function)==null?void 0:m.arguments)||""}`}}let s=e[0].data.choices.at(0);return n.choices.push({finish_reason:(h=s==null?void 0:s.finish_reason)!=null?h:"stop",index:(_=s==null?void 0:s.index)!=null?_:0,logprobs:(g=s==null?void 0:s.logprobs)!=null?g:null,message:{role:"assistant",content:t,tool_calls:r||void 0,refusal:(b=s==null?void 0:s.delta.refusal)!=null?b:null}}),n.id=o.id,n.model=o.model,n.created=o.created,n.usage=(x=o.usage)!=null?x:void 0,n},Bt=e=>{let t={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},n=[],o=null,r="",s="",a="",l="";for(let i of e)if("contentBlockStart"in i){let c=i.contentBlockStart;if("start"in c&&"toolUse"in c.start){let m=c.start.toolUse;o={toolUse:{toolUseId:m.toolUseId,name:m.name}},r=""}}else if("contentBlockDelta"in i){let c=i.contentBlockDelta.delta;if("text"in c)s+=c.text;else if("reasoningContent"in c){let m=c.reasoningContent;"text"in m?l+=m.text:"signature"in m&&(a+=m.signature)}else if("toolUse"in c&&"input"in c.toolUse){let m=c.toolUse.input;if(r+=m,!m.trim())continue}}else if("contentBlockStop"in i)if(o&&r){try{o.toolUse.input=JSON.parse(r)}catch(c){o.toolUse.input={}}n.push(o),o=null,r=""}else s?(n.push({text:s}),s=""):l&&a&&(n.push({reasoningContent:{reasoningText:{text:l,signature:a}}}),l="",a="");else if("messageStop"in i)t.stopReason=i.messageStop.stopReason;else if("metadata"in i){let c=i.metadata;t.usage=(c==null?void 0:c.usage)||{},t.metrics=(c==null?void 0:c.metrics)||{}}return t.output.message={role:"assistant",content:n},t},qe=(e,t,n,o)=>{var a,l;let r=P({},o),s=[];if(e){let i={text:e,thought:!0};s.push(i)}if(t){let i={text:t,thought:null};s.push(i)}for(let i of n){let c={function_call:i};s.push(c)}return s.length>0&&((l=(a=r.candidates)==null?void 0:a[0])!=null&&l.content)&&(r.candidates[0].content.parts=s),r},zt=e=>{var s,a;let{GenerateContentResponse:t}=nt("@google/genai");if(!e.length)return new t;let n="",o="",r=[];for(let l of e)if(l.candidates&&((a=(s=l.candidates[0])==null?void 0:s.content)!=null&&a.parts))for(let i of l.candidates[0].content.parts)i.text?i.thought===!0?n+=i.text:o+=i.text:i.functionCall&&r.push(i.functionCall);return qe(n,o,r,e[e.length-1])},Ue=e=>zt(e),$e=e=>zt(e),Yt=(e,t="openai.chat.completions.create")=>{if(t==="openai.responses.create"||t==="openai.AzureOpenAI.responses.create")return at(e);if("completion"in e[0])return e.reduce((n,o)=>K(P({},o),{completion:`${n.completion}${o.completion}`}),{});if(t==="anthropic.messages.create")return Rt(e);if("text"in e[0].choices[0]){let n="";for(let r of e)n=`${n}${r.choices[0].text}`;let o=structuredClone(e.at(-1));return o.choices[0].text=n,o}if("delta"in e[0].choices[0]){let n=bt(e);return n.choices[0]=P(P({},n.choices[0]),n.choices[0].message),n}return""},We=(e,t)=>{let n=t.model.provider,o=t.model.name;return n==="anthropic"||n==="anthropic.bedrock"||n==="vertexai"&&o.startsWith("claude")?Gt(e,t):n==="google"||n==="vertexai"&&o.startsWith("gemini")?Mt(e,t):n==="amazon.bedrock"?jt(e,t):n==="mistral"?gt(e.data,t):n==="openai"||n==="openai.azure"?(t.model.api_type||"chat-completions")==="responses"?Kt(e,t):gt(e,t):null};function Vt(e,t,n,o){return pt(this,null,function*(){let r={request_id:null,raw_response:null,prompt_blueprint:null},s={},a=o.model.provider;a=="amazon.bedrock"&&(s=e==null?void 0:e.$metadata,e=e==null?void 0:e.stream);let l=[];try{for(var m=ut(e),h,_,g;h=!(_=yield new V(m.next())).done;h=!1){let b=_.value;l.push(b),r.raw_response=b,r.prompt_blueprint=We(b,o),yield r}}catch(_){g=[_]}finally{try{h&&(_=m.return)&&(yield new V(_.call(m)))}finally{if(g)throw g[0]}}let i=n(l);a==="amazon.bedrock"&&(i.ResponseMetadata=s);let c=yield new V(t({request_response:i}));r.request_id=c.request_id,r.prompt_blueprint=c.prompt_blueprint,yield r})}var Xt={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:bt},completion:{function_name:"openai.completions.create",stream_function:Ft}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:at},completion:{function_name:"openai.responses.create",stream_function:at}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:Rt},completion:{function_name:"anthropic.completions.create",stream_function:Dt}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:bt},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:Ft}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:at},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:at}},google:{chat:{function_name:"google.convo.send_message",stream_function:Ue},completion:{function_name:"google.model.generate_content",stream_function:$e}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:Bt},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:Bt}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:Rt},completion:{function_name:"anthropic.completions.create",stream_function:Dt}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:Ne},completion:{function_name:"",stream_function:null}}};var wt="SET_WORKFLOW_COMPLETE";function je(e,t,n,o){return f(this,null,function*(){let r=yield q(`${e}/workflow-version-execution-results?workflow_version_execution_id=${t}&return_all_outputs=${n}`,{headers:o});if(!r.ok)throw new Error("Failed to fetch final output");return r.json()})}function Ht(e,t,n,o,r){return function(s){return f(this,null,function*(){if(s.name===wt)try{let a=JSON.parse(s.data),l=a.result_code,i;if(l==="OK"||l==null)i=a.final_output;else if(l==="EXCEEDS_SIZE_LIMIT")i=yield je(e,n,o,r),t.resolve(i);else throw new Error(`Unsupported final output code: ${l}`);t.resolve(i)}catch(a){t.reject(a)}})}}function Fe(l){return f(this,arguments,function*({token:e,channelName:t,executionId:n,returnAllOutputs:o,headers:r,timeout:s,baseURL:a}){let i=new Ge.Realtime(e),c=i.channels.get(t),m={},h=new Promise((g,b)=>{m.resolve=g,m.reject=b}),_=Ht(a,m,n,o,r);yield c.subscribe(wt,_);try{return yield new Promise((g,b)=>{let x=setTimeout(()=>{b(new Error("Workflow execution did not complete properly (timeout)"))},s);h.then(E=>{clearTimeout(x),g(E)}).catch(E=>{clearTimeout(x),b(E)})})}finally{console.log("Closing client"),c.unsubscribe(wt,_),i.close(),console.log("Closed client")}})}var q=(e,t)=>f(void 0,null,function*(){return Ke(()=>f(void 0,null,function*(){let n=yield fetch(e,t);if(n.status>=500&&n.status<600||n.status===429)throw new Error(`Server error: ${n.status} ${n.statusText}`);return n}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:n=>{console.info(`PromptLayer API request attempt ${n.attemptNumber} failed. ${n.retriesLeft} retries left.`)}})}),Zt=(e,t,n,o=!0)=>f(void 0,null,function*(){return n.request_response[Symbol.asyncIterator]!==void 0?Be(e,t,n.request_response,n,o):yield Qt(e,t,n,o)}),Qt=(e,t,n,o=!0)=>f(void 0,null,function*(){try{let r=yield q(`${t}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),s=yield r.json();if(r.status!==200){let a=s.message||s.error||"Failed to log request";if(o)throw new Error(a);J(s,"WARNING: While logging your request, PromptLayer experienced the following error:")}if(s&&n.return_pl_id)return[n.request_response,s.request_id]}catch(r){if(o)throw r;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${r}`)}return n.request_response}),te=(e,t,n,o=!0)=>f(void 0,null,function*(){try{let r=yield q(`${t}/library-track-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K(P({},n),{api_key:e}))}),s=yield r.json();if(r.status!==200){let a=s.message||s.error||"Failed to track metadata";if(o)throw new Error(a);return J(s,"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}),ee=(e,t,n,o=!0)=>f(void 0,null,function*(){try{let r=yield q(`${t}/library-track-score`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K(P({},n),{api_key:e}))}),s=yield r.json();if(r.status!==200){let a=s.message||s.error||"Failed to track score";if(o)throw new Error(a);return J(s,"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}),ne=(e,t,n,o=!0)=>f(void 0,null,function*(){try{let r=yield q(`${t}/library-track-prompt`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K(P({},n),{api_key:e}))}),s=yield r.json();if(r.status!==200){let a=s.message||s.error||"Failed to track prompt";if(o)throw new Error(a);return J(s,"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}),oe=(e,t,n,o=!0)=>f(void 0,null,function*(){try{let r=yield q(`${t}/track-group`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K(P({},n),{api_key:e}))}),s=yield r.json();if(r.status!==200){let a=s.message||s.error||"Failed to track group";if(o)throw new Error(a);return J(s,"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}),re=(e,t,n=!0)=>f(void 0,null,function*(){try{let o=yield q(`${t}/create-group`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e})}),r=yield o.json();if(o.status!==200){let s=r.message||r.error||"Failed to create group";if(n)throw new Error(s);return J(r,"WARNING: While creating a group PromptLayer had the following error"),!1}return r.id}catch(o){if(n)throw o;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${o}`),!1}}),se=(e,t,n,o,r=!0)=>f(void 0,null,function*(){try{let s=new URL(`${t}/prompt-templates/${n}`),a=yield q(s,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":e},body:JSON.stringify(o)}),l=yield a.json();if(a.status!==200){let i=l.message||l.error||"Failed to fetch prompt template";if(r)throw new Error(i);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${i}`),null}return l.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${l.warning}`),l}catch(s){if(r)throw s;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${s}`),null}}),ae=(e,t,n,o=!0)=>f(void 0,null,function*(){let r=yield q(`${t}/rest/prompt-templates`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":e},body:JSON.stringify({prompt_template:P({},n),prompt_version:P({},n),release_labels:n.release_labels?n.release_labels:void 0})}),s=yield r.json();if(r.status!==200&&r.status!==201){let a=s.message||s.error||"Failed to publish prompt template";if(o)throw new Error(a);J(s,"WARNING: While publishing a prompt template PromptLayer had the following error")}return s}),ie=(e,t,n,o=!0)=>f(void 0,null,function*(){var l;let r=new URL(`${t}/prompt-templates`);Object.entries(n||{}).forEach(([i,c])=>r.searchParams.append(i,c.toString()));let s=yield q(r,{headers:{"Content-Type":"application/json","X-API-KEY":e}}),a=yield s.json();if(s.status!==200){let i=a.message||a.error||"Failed to fetch prompt templates";if(o)throw new Error(i);return J(a,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(l=a.items)!=null?l:[]}),De=e=>f(void 0,null,function*(){let t=new URL(`${e.baseURL}/connection/websocket`);t.protocol=t.protocol==="https:"?"wss:":"ws:";let n=new Me(t.toString(),{token:e.token}),o=n.newSubscription(e.channelName);return new Promise((r,s)=>{let a=m=>{c(),r(m)},l=Ht(e.baseURL,{resolve:a,reject:s},e.executionId,e.returnAllOutputs,e.headers);o.on("publication",m=>{l({name:m.data.message_name,data:m.data.data})});let i=setTimeout(()=>{s(new Error("Workflow execution did not complete properly (timeout)"))},e.timeout),c=()=>{clearTimeout(i),o.unsubscribe(),n.disconnect()};o.on("error",m=>{c(),s(`Centrifugo subscription error: ${m}`)}),n.on("error",m=>{c(),s(`Centrifugo client error: ${m}`)}),o.subscribe(),n.connect()})}),ce=c=>f(void 0,[c],function*({workflow_name:e,input_variables:t,metadata:n={},workflow_label_name:o=null,workflow_version_number:r=null,return_all_outputs:s=!1,api_key:a,timeout:l=36e5,baseURL:i}){let m={input_variables:t,metadata:n,workflow_label_name:o,workflow_version_number:r,return_all_outputs:s},h={"X-API-KEY":a,"Content-Type":"application/json"};try{let _=yield q(`${i}/workflows/${encodeURIComponent(e)}/run`,{method:"POST",headers:h,body:JSON.stringify(m)});if(_.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield _.json().catch(()=>({}))).error||_.statusText}`};let g=yield _.json();g.warning&&console.warn(`WARNING: ${g.warning}`);let b=g.workflow_version_execution_id;if(!b)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let x=`workflow_updates:${b}`,O=yield(yield q(`${i}/ws-token-request-library?capability=${x}`,{method:"POST",headers:h})).json(),T={token:O.token_details.token,channelName:x,executionId:b,returnAllOutputs:s,headers:h,timeout:l,baseURL:i};return O.messaging_backend==="centrifugo"?De(T):yield Fe(T)}catch(_){throw console.error(`Failed to run workflow: ${_ instanceof Error?_.message:_}`),_}});function Be(e,t,n,o,r=!0){return pt(this,null,function*(){let s=[];try{for(var i=ut(n),c,m,h;c=!(m=yield new V(i.next())).done;c=!1){let _=m.value;yield o.return_pl_id?[_,null]:_,s.push(_)}}catch(m){h=[m]}finally{try{c&&(m=i.return)&&(yield new V(m.call(i)))}finally{if(h)throw h[0]}}let a=Yt(s,o.function_name),l=yield new V(Qt(e,t,K(P({},o),{request_response:a,request_end_time:new Date().toISOString()}),r));if(l&&o.return_pl_id){let _=l[1];yield[s.at(-1),_]}})}var J=(e,t)=>{try{console.warn(`${t}: ${e.message}`)}catch(n){console.warn(`${t}: ${e}`)}},le=(e,t,n=!0)=>f(void 0,null,function*(){try{let o=yield q(`${e}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=yield o.json();if(o.status!==200){let s=r.message||r.error||"Failed to track request";if(n)throw new Error(s);J(r,"WARNING: While logging your request, PromptLayer experienced the following error:")}return r}catch(o){if(n)throw o;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${o}`)}return{}}),Je=(e,t)=>f(void 0,null,function*(){return yield e.chat.completions.create(t)}),ze=(e,t)=>f(void 0,null,function*(){return yield e.completions.create(t)}),pe={chat:Je,completion:ze},ue=(e,t)=>f(void 0,null,function*(){var s,a;let n=nt("openai").default,o=new n({baseURL:t.baseURL,apiKey:t.apiKey});if(t==null||delete t.apiKey,t==null||delete t.baseURL,((a=(s=e.metadata)==null?void 0:s.model)==null?void 0:a.api_type)==="chat-completions"){let l=pe[e.prompt_template.type];return yield l(o,t)}else return yield o.responses.create(t)}),me=(e,t)=>f(void 0,null,function*(){var s,a;let{AzureOpenAI:n}=nt("openai"),o=new n({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,((a=(s=e.metadata)==null?void 0:s.model)==null?void 0:a.api_type)==="chat-completions"){let l=pe[e.prompt_template.type];return yield l(o,t)}else return yield o.responses.create(t)}),de=(e,t)=>f(void 0,null,function*(){return e.messages.create(t)}),Ye=(e,t)=>f(void 0,null,function*(){return e.completions.create(t)}),fe={chat:de,completion:Ye},_e=(e,t)=>f(void 0,null,function*(){let n=nt("@anthropic-ai/sdk").default,o=new n({baseURL:t.baseURL,apiKey:t.apiKey}),r=fe[e.prompt_template.type];return r(o,t)}),ye=(e,t,n,o=!0)=>f(void 0,null,function*(){try{let r=yield q(`${t}/log-request`,{method:"POST",headers:{"X-API-KEY":e,"Content-Type":"application/json"},body:JSON.stringify(n)}),s=yield r.json();if(r.status!==201){let a=s.message||s.error||"Failed to log request";if(o)throw new Error(a);return J(s,"WARNING: While logging your request PromptLayer had the following error"),null}return s}catch(r){if(o)throw r;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${r}`),null}}),Ve=(e,t)=>f(void 0,null,function*(){var a,l;let n=t==null?void 0:t.history,o=t==null?void 0:t.generationConfig,r=n.length>0?(a=n[n.length-1])==null?void 0:a.parts:"",s=e.chats.create({model:t==null?void 0:t.model,history:(l=n.slice(0,-1))!=null?l:[],config:o});return t!=null&&t.stream?yield s.sendMessageStream({message:r}):yield s.sendMessage({message:r})}),Xe=(e,o)=>f(void 0,null,function*(){var r=o,{stream:t}=r,n=lt(r,["stream"]);return t?yield e.generateContentStream(P({},n)):yield e.generateContent(P({},n))}),ve={chat:Ve,completion:Xe},xt=(e,t)=>f(void 0,null,function*(){let{GoogleGenAI:n}=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,s=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,a={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:r,scopes:["https://www.googleapis.com/auth/cloud-platform"]},l=o?new n({apiKey:o}):new n({vertexai:!0,project:r,location:s,googleAuthOptions:a}),i=ve[e.prompt_template.type];return yield i(l,t)}),vt=e=>e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase()),mt=(e,t=new Set)=>!e||typeof e!="object"?e:Array.isArray(e)?e.map(n=>mt(n,t)):Object.fromEntries(Object.entries(e).map(([n,o])=>t.has(n)?[vt(n),o]:[vt(n),mt(o,t)])),he=(e,t,n={},o=!1)=>{var i,c,m,h,_,g,b,x,E;let r=(m=t==null?void 0:t.client)!=null?m:(c=(i=e.metadata)==null?void 0:i.model)==null?void 0:c.provider,s=(_=(h=e.metadata)==null?void 0:h.model)==null?void 0:_.api_type;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let a=K(P({},e.llm_kwargs||{}),{stream:o});["google","vertexai"].includes(r)&&((b=(g=e.metadata)==null?void 0:g.model)!=null&&b.name.startsWith("gemini"))&&(a=mt(a,new Set(["function_declarations","properties"])));let l={baseURL:(E=t==null?void 0:t.base_url)!=null?E:(x=e.provider_base_url)==null?void 0:x.url,apiKey:t==null?void 0:t.api_key};return Object.entries(l).forEach(([O,y])=>{y!==void 0&&(a[O]=y)}),o&&Jt.includes(r)&&s==="chat-completions"&&(a.stream_options={include_usage:!0}),{provider_type:r,kwargs:a}},ge=(e,t)=>{let n=Xt[e];if(!n)throw new Error(`Unsupported provider type: ${e}`);let o=t.type,r=n[o];if(!r)throw new Error(`Unsupported template type '${t.type}' for provider '${e}'`);return r},be=(e,t)=>f(void 0,null,function*(){var o;let n=(o=e.metadata)==null?void 0:o.model;if(!n)throw new Error("Model metadata not found in prompt blueprint");if(n.name.startsWith("gemini"))return xt(e,t);if(n.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 de(s,t);throw new Error(`Unsupported prompt template type '${e.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${n.name}' for Vertex AI request`)}),Re=(e,t)=>f(void 0,null,function*(){let{BedrockRuntimeClient:n,ConverseCommand:o,ConverseStreamCommand:r}=yield import("@aws-sdk/client-bedrock-runtime"),s=new n({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 a=new r(P({},t));return yield s.send(a)}else{t==null||delete t.stream;let a=new o(P({},t));return yield s.send(a)}}),we=(e,t)=>f(void 0,null,function*(){let{AnthropicBedrock:n}=yield import("@anthropic-ai/bedrock-sdk"),o=new n({awsAccessKey:t.aws_access_key,awsSecretKey:t.aws_secret_key,awsRegion:t.aws_region,awsSessionToken:t.aws_session_token,baseURL:t.base_url}),r=fe[e.prompt_template.type];return r(o,t)}),xe=(e,t)=>f(void 0,null,function*(){let{Mistral:n}=yield import("@mistralai/mistralai"),o=new n({apiKey:process.env.MISTRAL_API_KEY});return t=mt(t,new Set),t!=null&&t.stream?(delete t.stream,yield o.chat.stream(t)):(delete t.stream,yield o.chat.complete(t))}),Tt=e=>{var t,n,o,r,s,a;if(typeof globalThis.process!="undefined")return(o=(n=(t=globalThis.process.env)==null?void 0:t[e])==null?void 0:n.trim())!=null?o:void 0;if(typeof globalThis.Deno!="undefined")return(a=(s=(r=globalThis.Deno.env)==null?void 0:r.get)==null?void 0:s.call(r,e))==null?void 0:a.trim()};var dt=class{constructor(t,n,o=!0){this.create=()=>re(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=t,this.baseURL=n,this.throwOnError=o}};import{SpanKind as it,SpanStatusCode as Pt}from"@opentelemetry/api";import{ExportResultCode as ft}from"@opentelemetry/core";var St=class{constructor(t,n,o){this.apiKey=n,this.baseURL=o,this.enableTracing=t,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(t){return t?Object.fromEntries(Object.entries(t)):{}}spanKindToString(t){return{[it.INTERNAL]:"SpanKind.INTERNAL",[it.SERVER]:"SpanKind.SERVER",[it.CLIENT]:"SpanKind.CLIENT",[it.PRODUCER]:"SpanKind.PRODUCER",[it.CONSUMER]:"SpanKind.CONSUMER"}[t]||"SpanKind.INTERNAL"}statusCodeToString(t){return{[Pt.ERROR]:"StatusCode.ERROR",[Pt.OK]:"StatusCode.OK",[Pt.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(ft.SUCCESS);let n=t.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(s=>({name:s.name,timestamp:this.toNanoseconds(s.time),attributes:this.attributesToObject(s.attributes)})),links:o.links.map(s=>({context:s.context,attributes:this.attributesToObject(s.attributes)})),resource:{attributes:K(P({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return q(this.url,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey||""},body:JSON.stringify({spans:n})}).then(o=>o.ok?ft.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
-
HTTP error! status: ${
|
|
1
|
+
var Ze=Object.defineProperty,Qe=Object.defineProperties;var ve=Object.getOwnPropertyDescriptors;var St=Object.getOwnPropertySymbols;var ne=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var Ut=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e);var oe=(e,t,o)=>t in e?Ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,O=(e,t)=>{for(var o in t||(t={}))ne.call(t,o)&&oe(e,o,t[o]);if(St)for(var o of St(t))re.call(t,o)&&oe(e,o,t[o]);return e},j=(e,t)=>Qe(e,ve(t));var rt=(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 Et=(e,t)=>{var o={};for(var n in e)ne.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(e!=null&&St)for(var n of St(e))t.indexOf(n)<0&&re.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())}),H=function(e,t){this[0]=e,this[1]=t},Ot=(e,t,o)=>{var n=(i,l,c,p)=>{try{var m=o[i](l),g=(l=m.value)instanceof H,y=m.done;Promise.resolve(g?l[0]:l).then(b=>g?n(i==="return"?i:"next",l[1]?{done:b.done,value:b.value}:b,c,p):c({value:b,done:y})).catch(b=>n("throw",b,c,p))}catch(b){p(b)}},r=i=>s[i]=l=>new Promise((c,p)=>n(i,l,c,p)),s={};return o=o.apply(e,t),s[Ut("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var At=(e,t,o)=>(t=e[Ut("asyncIterator")])?t.call(e):(e=e[Ut("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 so from"ably";import{Centrifuge as io}from"centrifuge";import ao from"p-retry";var F=(e,t,o,n)=>{let r={id:e,function:{name:t,input:o}};return n&&(r.tool_id=n),r},x=n=>{var r=n,{type:e,item_id:t}=r,o=Et(r,["type","item_id"]);let s=O({type:e},o);return t&&(s.item_id=t),s},wt=(e,t)=>({input_variables:[],template_format:"f-string",content:e,role:"assistant",function_call:null,name:null,tool_calls:t}),xt=(e,t)=>({prompt_template:{messages:[e],type:"chat",input_variables:[]},metadata:t}),se=(e,t)=>{let o=[],n=[];e.type==="content_block_start"?e.content_block.type==="thinking"?o.push(x({type:"thinking",thinking:"",signature:""})):e.content_block.type==="text"?o.push(x({type:"text",text:""})):e.content_block.type==="tool_use"&&n.push(F(e.content_block.id||"",e.content_block.name||"",{})):e.type==="content_block_delta"&&(e.delta.type==="thinking_delta"?o.push(x({type:"thinking",thinking:e.delta.thinking||"",signature:""})):e.delta.type==="text_delta"?o.push(x({type:"text",text:e.delta.text||""})):e.delta.type==="signature_delta"?o.push(x({type:"thinking",thinking:"",signature:e.delta.signature||""})):e.delta.type==="input_json_delta"&&n.push(F("","",e.delta.partial_json)));let r=wt(o,n);return xt(r,t)},ie=(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(x({type:"thinking",thinking:i.text,signature:i.thoughtSignature||""})):o.push(x({type:"text",text:i.text})):i.functionCall&&n.push(F(i.functionCall.id||"",i.functionCall.name||"",i.functionCall.args||{}));let r=wt(o,n);return xt(r,t)},$t=(e,t)=>{let o=[],n=[];for(let s of e.choices)if(s.delta){s.delta.content&&o.push(x({type:"text",text:s.delta.content}));let i=s.delta.tool_calls||s.delta.toolCalls;if(i&&Array.isArray(i))for(let l of i)l.function&&n.push(F(l.id||"",l.function.name||"",l.function.arguments||""))}let r=wt(o,n);return xt(r,t)},ae=(e,t)=>{var i,l,c,p,m,g,y,b,R,S,A,C,h,E,L,$,D,I,k,B,G,Y,M,J,Z,V,Q,v,tt,K,et,it,at,ct,pt,lt,ut,mt,dt,ft,_t,yt,ht,gt,bt,Rt,P,N,u,d,w,Jt,zt,Yt,Vt,Xt,Ht,Zt,Qt,vt,te;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:"",T=(l=e==null?void 0:e.item_id)!=null?l:"";a&&o.push(x({type:"thinking",item_id:T,thinking:a,signature:""}))}else if(r==="response.reasoning_summary_text.done"){let a=(c=e==null?void 0:e.text)!=null?c:"",T=(p=e==null?void 0:e.item_id)!=null?p:"";a&&o.push(x({type:"thinking",item_id:T,thinking:a,signature:""}))}else if(r==="response.reasoning_summary_part.added"){let a=(m=e==null?void 0:e.part)!=null?m:{},T=(g=e==null?void 0:e.item_id)!=null?g:"";if((a==null?void 0:a.type)==="summary_text"){let f=(y=a==null?void 0:a.text)!=null?y:"";o.push(x({type:"thinking",item_id:T,thinking:f,signature:""}))}}else if(r==="response.reasoning_summary_part.done"){let a=(b=e==null?void 0:e.part)!=null?b:{},T=(R=e==null?void 0:e.item_id)!=null?R:"";if((a==null?void 0:a.type)==="summary_text"){let f=(S=a==null?void 0:a.text)!=null?S:"";f&&o.push(x({type:"thinking",item_id:T,thinking:f,signature:""}))}}else if(r==="response.function_call_arguments.delta"){let a=(A=e==null?void 0:e.item_id)!=null?A:"",T=(C=e==null?void 0:e.delta)!=null?C:"";T&&n.push(F("","",T,a))}else if(r==="response.function_call_arguments.done"){let a=(h=e==null?void 0:e.item_id)!=null?h:"",T=(E=e==null?void 0:e.arguments)!=null?E:"";T&&n.push(F("","",T,a))}else if(r==="response.output_item.added"){let a=(L=e==null?void 0:e.item)!=null?L:{},T=a==null?void 0:a.type,f=($=a==null?void 0:a.id)!=null?$:"";T==="reasoning"?o.push(x({type:"thinking",thinking:"",signature:"",item_id:f})):T==="function_call"?n.push(F((a==null?void 0:a.call_id)||"",(a==null?void 0:a.name)||"","",f)):T==="message"?o.push(x({type:"text",item_id:f,text:""})):T==="code_interpreter_call"&&o.push(x({type:"code",item_id:f,code:(D=a==null?void 0:a.code)!=null?D:"",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:{},T=(B=a==null?void 0:a.type)!=null?B:"output_text",f=(G=e==null?void 0:e.item_id)!=null?G:"";T==="output_text"&&o.push(x({type:"text",item_id:f,text:(Y=a==null?void 0:a.text)!=null?Y:"",annotations:(a==null?void 0:a.annotations)||[]}))}else if(r==="response.content_part.done"){let a=(M=e==null?void 0:e.part)!=null?M:{},T=(J=a==null?void 0:a.type)!=null?J:"output_text",f=(Z=e==null?void 0:e.item_id)!=null?Z:"";T==="output_text"&&o.push(x({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.output_text.annotation.added"){let a=(e==null?void 0:e.annotation)||{},T=a==null?void 0:a.type,f=null;T==="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}:T=="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(x({type:"text",item_id:(Q=e==null?void 0:e.item_id)!=null?Q:"",text:"",annotations:[f]}))}else if(r==="response.code_interpreter_call.in_progress")o.push(x({type:"code",item_id:(v=e==null?void 0:e.item_id)!=null?v:"",code:(tt=e==null?void 0:e.code)!=null?tt:"",container_id:(K=e==null?void 0:e.container_id)!=null?K:""}));else if(r==="response.code_interpreter_call_code.delta")o.push(x({type:"code",item_id:(et=e==null?void 0:e.item_id)!=null?et:"",code:(it=e==null?void 0:e.delta)!=null?it:"",container_id:(at=e==null?void 0:e.container_id)!=null?at:""}));else if(r==="response.output_text.delta"){let a=(ct=e==null?void 0:e.delta)!=null?ct:"";a&&o.push(x({type:"text",item_id:(pt=e==null?void 0:e.item_id)!=null?pt:"",text:a}))}else if(r==="response.output_text.done"){let a=(lt=e==null?void 0:e.text)!=null?lt:"";a&&o.push(x({type:"text",item_id:(ut=e==null?void 0:e.item_id)!=null?ut:"",text:a}))}else if(r==="response.output_item.done"){let a=(mt=e==null?void 0:e.item)!=null?mt:{},T=a==null?void 0:a.type,f=(dt=a==null?void 0:a.id)!=null?dt:"";if(T==="reasoning"){let W=((ft=a==null?void 0:a.summary)!=null?ft:[]).map(X=>{var U;return(U=X==null?void 0:X.text)!=null?U:""}).join("");o.push(x({type:"thinking",item_id:f,thinking:W,signature:""}))}else if(T==="function_call")n.push(F((a==null?void 0:a.call_id)||"",(a==null?void 0:a.name)||"",(a==null?void 0:a.arguments)||"",f));else if(T==="message"){let ot=(_t=a==null?void 0:a.content)!=null?_t:[];for(let W of ot)if((W==null?void 0:W.type)==="output_text"){let X=(yt=W==null?void 0:W.text)!=null?yt:"";X&&o.push(x({type:"text",item_id:f,text:X}))}}else T==="code_interpreter_call"&&o.push(x({type:"code",item_id:f,code:(ht=a==null?void 0:a.code)!=null?ht:"",container_id:(gt=a==null?void 0:a.container_id)!=null?gt:""}))}else if(r==="response.code_interpreter_call_code.done")o.push(x({type:"code",item_id:(bt=e==null?void 0:e.item_id)!=null?bt:"",code:(Rt=e==null?void 0:e.code)!=null?Rt:"",container_id:(P=e==null?void 0:e.container_id)!=null?P:""}));else if(r==="response.code_interpreter_call.interpreting")o.push(x({type:"code",item_id:(N=e==null?void 0:e.item_id)!=null?N:"",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(x({type:"code",item_id:(w=e==null?void 0:e.item_id)!=null?w:"",code:(Jt=e==null?void 0:e.code)!=null?Jt:"",container_id:(zt=e==null?void 0:e.container_id)!=null?zt:""}));else if(r==="response.completed"){let a=(Yt=e==null?void 0:e.response)!=null?Yt:{},T=(Vt=a==null?void 0:a.output)!=null?Vt:[];for(let f of T){let ot=f==null?void 0:f.type,W=(Xt=f==null?void 0:f.id)!=null?Xt:"";if(ot==="reasoning"){let U=((Ht=f==null?void 0:f.summary)!=null?Ht:[]).map(nt=>{var ee;return(ee=nt==null?void 0:nt.text)!=null?ee:""}).join("");o.push(x({type:"thinking",item_id:W,thinking:U,signature:""}))}else if(ot==="function_call")n.push(F((f==null?void 0:f.call_id)||"",(f==null?void 0:f.name)||"",(f==null?void 0:f.arguments)||"",W));else if(ot==="message"){let X=(Zt=f==null?void 0:f.content)!=null?Zt:[];for(let U of X)if((U==null?void 0:U.type)==="output_text"){let nt=(Qt=U==null?void 0:U.text)!=null?Qt:"";nt&&o.push(x({type:"text",item_id:W,text:nt,annotations:(U==null?void 0:U.annotations)||[]}))}}else ot==="code_interpreter_call"&&o.push(x({type:"code",item_id:W,code:(vt=f==null?void 0:f.code)!=null?vt:"",container_id:(te=f==null?void 0:f.container_id)!=null?te:""}))}}let s=wt(o,n||[]);return xt(s,t)},ce=(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)||"",g=((l=p.reasoningContent)==null?void 0:l.signature)||"";o.push(x({type:"thinking",thinking:m,signature:g}))}else if("text"in p)o.push(x({type:"text",text:p.text||""}));else if("toolUse"in p){let m=p.toolUse||{};n.push(F(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in e){let p=((c=e.contentBlockStart)==null?void 0:c.start)||{};if("toolUse"in p){let m=p.toolUse||{};n.push(F(m.toolUseId||"",m.name||"",""))}}let r=wt(o,n);return xt(r,t)};var me=["openai","openai.azure"],Tt=e=>{var n,r,s,i,l,c,p,m,g,y,b,R,S,A,C,h,E,L,$,D,I,k,B,G,Y,M,J,Z,V,Q,v,tt,K,et,it,at,ct,pt,lt,ut,mt,dt,ft,_t,yt,ht,gt,bt,Rt;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 P of e){let N=P==null?void 0:P.type;if(N==="response.created"){let u=P.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=(g=u.top_p)!=null?g:t.top_p,t.truncation=(y=u.truncation)!=null?y:t.truncation,t.max_output_tokens=(b=u.max_output_tokens)!=null?b:t.max_output_tokens,t.previous_response_id=(R=u.previous_response_id)!=null?R:t.previous_response_id,t.store=(S=u.store)!=null?S: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 w=u.reasoning;w&&(t.reasoning=w);continue}if(N==="response.in_progress"){let u=P.response||{};t.status=(h=u.status)!=null?h:t.status;continue}if(N==="response.output_item.added"){let u=P.item||{},d=u.id,w=u.type;w==="reasoning"?o[d]={type:"reasoning",id:d,summary:[],status:(E=u.status)!=null?E:"in_progress"}:w==="function_call"?o[d]={type:"function_call",id:d,call_id:u.call_id,name:u.name,arguments:"",status:(L=u.status)!=null?L:"in_progress"}:w==="message"?o[d]={type:"message",id:d,role:($=u.role)!=null?$:"assistant",content:[],status:(D=u.status)!=null?D:"in_progress"}:w==="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(N==="response.reasoning_summary_part.added"){let u=P.item_id,d=P.part||{};if(u in o&&o[u].type==="reasoning"){let w={type:(B=d.type)!=null?B:"summary_text",text:(G=d.text)!=null?G:""};o[u].summary.push(w)}continue}if(N==="response.reasoning_summary_text.delta"){let u=P.item_id,d=(Y=P.delta)!=null?Y:"",w=(M=P.summary_index)!=null?M:0;if(u in o&&o[u].type==="reasoning"){for(;o[u].summary.length<=w;)o[u].summary.push({type:"summary_text",text:""});o[u].summary[w].text+=d}continue}if(N==="response.reasoning_summary_text.done"){let u=P.item_id,d=(J=P.text)!=null?J:"",w=(Z=P.summary_index)!=null?Z:0;if(u in o&&o[u].type==="reasoning"){for(;o[u].summary.length<=w;)o[u].summary.push({type:"summary_text",text:""});o[u].summary[w].text=d}continue}if(N==="response.reasoning_summary_part.done"){let u=P.item_id,d=P.part||{};if(u in o&&o[u].type==="reasoning"){let w=(V=P.summary_index)!=null?V:0;w<o[u].summary.length&&(o[u].summary[w]={type:(Q=d.type)!=null?Q:"summary_text",text:(v=d.text)!=null?v:""})}continue}if(N==="response.function_call_arguments.delta"){let u=P.item_id,d=(tt=P.delta)!=null?tt:"";u in o&&(o[u].arguments=`${o[u].arguments||""}${d}`);continue}if(N==="response.function_call_arguments.done"){let u=P.item_id,d=(K=P.arguments)!=null?K:"";u in o&&(o[u].arguments=d);continue}if(N==="response.content_part.added"){let u=P.part||{},d=Object.values(o).find(w=>w.type==="message");if(d){let w={type:(et=u.type)!=null?et:"output_text",text:(it=u.text)!=null?it:"",annotations:(at=u.annotations)!=null?at:[]};d.content.push(w)}continue}if(N==="response.output_text.delta"){let u=(ct=P.delta)!=null?ct:"";for(let d of Object.values(o))if(d.type==="message"&&d.content&&d.content.length){let w=d.content[d.content.length-1];w&&w.type==="output_text"&&(w.text=`${w.text||""}${u}`);break}continue}if(N==="response.output_text.done"){let u=(pt=P.text)!=null?pt:"";for(let d of Object.values(o))if(d.type==="message"&&d.content&&d.content.length){let w=d.content[d.content.length-1];w&&w.type==="output_text"&&(w.text=u);break}continue}if(N==="response.output_item.done"){let u=P.item||{},d=u.id;d in o&&(o[d].status=(lt=u.status)!=null?lt:"completed",u.type==="reasoning"?o[d].summary=(ut=u.summary)!=null?ut:o[d].summary:u.type==="function_call"?(o[d].arguments=(mt=u.arguments)!=null?mt:o[d].arguments,o[d].call_id=(dt=u.call_id)!=null?dt:o[d].call_id,o[d].name=(ft=u.name)!=null?ft:o[d].name):u.type==="message"&&(o[d].content=(_t=u.content)!=null?_t:o[d].content,o[d].role=(yt=u.role)!=null?yt:o[d].role),t.output.push(o[d]));continue}if(N==="response.completed"){let u=P.response||{};t.status=(gt=(ht=u.status)!=null?ht:t.status)!=null?gt:"completed",t.usage=(bt=u.usage)!=null?bt:t.usage,t.output=(Rt=u.output)!=null?Rt:t.output,u.reasoning&&(t.reasoning=u.reasoning);continue}}return t},Wt=e=>{var l,c,p,m,g,y,b,R,S,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 h=C.choices[0].delta;h.content&&(t=`${t||""}${h.content||""}`),h.function_call&&(o={name:`${o?o.name:""}${h.function_call.name||""}`,arguments:`${o?o.arguments:""}${h.function_call.arguments||""}`});let E=(l=h.tool_calls)==null?void 0:l[0];if(E){s=s||[];let L=s.at(-1);if(!L||E.id){s.push({id:E.id||"",type:E.type||"function",function:{name:((c=E.function)==null?void 0:c.name)||"",arguments:((p=E.function)==null?void 0:p.arguments)||""}});continue}L.function.name=`${L.function.name}${((m=E.function)==null?void 0:m.name)||""}`,L.function.arguments=`${L.function.arguments}${((g=E.function)==null?void 0:g.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:(b=i==null?void 0:i.index)!=null?b:0,logprobs:(R=i==null?void 0:i.logprobs)!=null?R:null,message:{role:"assistant",content:t,function_call:o||void 0,tool_calls:s||void 0,refusal:(S=i==null?void 0:i.delta.refusal)!=null?S: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},pe=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},Gt=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=O({},p.message);else if(p.type==="content_block_start")n=O({},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=j(O({},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},le=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},to=e=>{var i,l,c,p,m,g,y,b,R,S;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 h=(i=C.toolCalls)==null?void 0:i[0];if(h){r=r||[];let E=r.at(-1);if(!E||h.id){r.push({id:h.id||"",type:h.type||"function",function:{name:((l=h.function)==null?void 0:l.name)||"",arguments:((c=h.function)==null?void 0:c.arguments)||""}});continue}E.function.name=`${E.function.name}${((p=h.function)==null?void 0:p.name)||""}`,E.function.arguments=`${E.function.arguments}${((m=h.function)==null?void 0:m.arguments)||""}`}}let s=e[0].data.choices.at(0);return o.choices.push({finish_reason:(g=s==null?void 0:s.finish_reason)!=null?g:"stop",index:(y=s==null?void 0:s.index)!=null?y:0,logprobs:(b=s==null?void 0:s.logprobs)!=null?b:null,message:{role:"assistant",content:t,tool_calls:r||void 0,refusal:(R=s==null?void 0:s.delta.refusal)!=null?R:null}}),o.id=n.id,o.model=n.model,o.created=n.created,o.usage=(S=n.usage)!=null?S:void 0,o},ue=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},eo=(e,t,o,n)=>{var i,l;let r=O({},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},de=e=>{var s,i;let{GenerateContentResponse:t}=rt("@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 eo(o,n,r,e[e.length-1])},oo=e=>de(e),no=e=>de(e),fe=(e,t="openai.chat.completions.create")=>{if(t==="openai.responses.create"||t==="openai.AzureOpenAI.responses.create")return Tt(e);if("completion"in e[0])return e.reduce((o,n)=>j(O({},n),{completion:`${o.completion}${n.completion}`}),{});if(t==="anthropic.messages.create")return Gt(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=Wt(e);return o.choices[0]=O(O({},o.choices[0]),o.choices[0].message),o}return""},ro=(e,t)=>{let o=t.model.provider,n=t.model.name;return o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&n.startsWith("claude")?se(e,t):o==="google"||o==="vertexai"&&n.startsWith("gemini")?ie(e,t):o==="amazon.bedrock"?ce(e,t):o==="mistral"?$t(e.data,t):o==="openai"||o==="openai.azure"?(t.model.api_type||"chat-completions")==="responses"?ae(e,t):$t(e,t):null};function _e(e,t,o,n){return Ot(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=At(e),g,y,b;g=!(y=yield new H(m.next())).done;g=!1){let R=y.value;l.push(R),r.raw_response=R,r.prompt_blueprint=ro(R,n),yield r}}catch(y){b=[y]}finally{try{g&&(y=m.return)&&(yield new H(y.call(m)))}finally{if(b)throw b[0]}}let c=o(l);i==="amazon.bedrock"&&(c.ResponseMetadata=s);let p=yield new H(t({request_response:c}));r.request_id=p.request_id,r.prompt_blueprint=p.prompt_blueprint,yield r})}var ye={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:Wt},completion:{function_name:"openai.completions.create",stream_function:pe}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:Tt},completion:{function_name:"openai.responses.create",stream_function:Tt}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:Gt},completion:{function_name:"anthropic.completions.create",stream_function:le}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:Wt},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:pe}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:Tt},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:Tt}},google:{chat:{function_name:"google.convo.send_message",stream_function:oo},completion:{function_name:"google.model.generate_content",stream_function:no}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:ue},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:ue}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:Gt},completion:{function_name:"anthropic.completions.create",stream_function:le}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:to},completion:{function_name:"",stream_function:null}}};var Mt="SET_WORKFLOW_COMPLETE";function co(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}`,{headers:n});if(!r.ok)throw new Error("Failed to fetch final output");return r.json()})}function ge(e,t,o,n,r){return function(s){return _(this,null,function*(){if(s.name===Mt)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 co(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 po(l){return _(this,arguments,function*({token:e,channelName:t,executionId:o,returnAllOutputs:n,headers:r,timeout:s,baseURL:i}){let c=new so.Realtime(e),p=c.channels.get(t),m={},g=new Promise((b,R)=>{m.resolve=b,m.reject=R}),y=ge(i,m,o,n,r);yield p.subscribe(Mt,y);try{return yield new Promise((b,R)=>{let S=setTimeout(()=>{R(new Error("Workflow execution did not complete properly (timeout)"))},s);g.then(A=>{clearTimeout(S),b(A)}).catch(A=>{clearTimeout(S),R(A)})})}finally{console.log("Closing client"),p.unsubscribe(Mt,y),c.close(),console.log("Closed client")}})}var q=(e,t)=>_(null,null,function*(){return ao(()=>_(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.`)}})}),be=(e,t,o,n=!0)=>_(null,null,function*(){return o.request_response[Symbol.asyncIterator]!==void 0?uo(e,t,o.request_response,o,n):yield Re(e,t,o,n)}),Re=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),s=yield r.json();if(r.status!==200){let i=s.message||s.error||"Failed to log request";if(n)throw new Error(i);z(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}),we=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/library-track-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j(O({},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 z(s,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(r){if(n)throw r;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${r}`),!1}return!0}),xe=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/library-track-score`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j(O({},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 z(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}),Te=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/library-track-prompt`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j(O({},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 z(s,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(r){if(n)throw r;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${r}`),!1}return!0}),Pe=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/track-group`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j(O({},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 z(s,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(r){if(n)throw r;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${r}`),!1}return!0}),Se=(e,t,o=!0)=>_(null,null,function*(){try{let n=yield q(`${t}/create-group`,{method:"POST",headers:{"Content-Type":"application/json"},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 z(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}}),Ee=(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:{"Content-Type":"application/json","X-API-KEY":e},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}}),Oe=(e,t,o,n=!0)=>_(null,null,function*(){let r=yield q(`${t}/rest/prompt-templates`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":e},body:JSON.stringify({prompt_template:O({},o),prompt_version:O({},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);z(s,"WARNING: While publishing a prompt template PromptLayer had the following error")}return s}),Ae=(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:{"Content-Type":"application/json","X-API-KEY":e}}),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 z(i,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(l=i.items)!=null?l:[]}),lo=e=>_(null,null,function*(){let t=new URL(`${e.baseURL}/connection/websocket`);t.protocol=t.protocol==="https:"?"wss:":"ws:";let o=new io(t.toString(),{token:e.token}),n=o.newSubscription(e.channelName);return new Promise((r,s)=>{let i=m=>{p(),r(m)},l=ge(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()})}),Ce=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},g={"X-API-KEY":i,"Content-Type":"application/json"};try{let y=yield q(`${c}/workflows/${encodeURIComponent(e)}/run`,{method:"POST",headers:g,body:JSON.stringify(m)});if(y.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield y.json().catch(()=>({}))).error||y.statusText}`};let b=yield y.json();b.warning&&console.warn(`WARNING: ${b.warning}`);let R=b.workflow_version_execution_id;if(!R)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let S=`workflow_updates:${R}`,C=yield(yield q(`${c}/ws-token-request-library?capability=${S}`,{method:"POST",headers:g})).json(),E={token:C.token_details.token,channelName:S,executionId:R,returnAllOutputs:s,headers:g,timeout:l,baseURL:c};return C.messaging_backend==="centrifugo"?lo(E):yield po(E)}catch(y){throw console.error(`Failed to run workflow: ${y instanceof Error?y.message:y}`),y}});function uo(e,t,o,n,r=!0){return Ot(this,null,function*(){let s=[];try{for(var c=At(o),p,m,g;p=!(m=yield new H(c.next())).done;p=!1){let y=m.value;yield n.return_pl_id?[y,null]:y,s.push(y)}}catch(m){g=[m]}finally{try{p&&(m=c.return)&&(yield new H(m.call(c)))}finally{if(g)throw g[0]}}let i=fe(s,n.function_name),l=yield new H(Re(e,t,j(O({},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 z=(e,t)=>{try{console.warn(`${t}: ${e.message}`)}catch(o){console.warn(`${t}: ${e}`)}},Ie=(e,t,o=!0)=>_(null,null,function*(){try{let n=yield q(`${e}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},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);z(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{}}),mo=(e,t)=>_(null,null,function*(){return yield e.chat.completions.create(t)}),fo=(e,t)=>_(null,null,function*(){return yield e.completions.create(t)}),ke={chat:mo,completion:fo},Le=(e,t)=>_(null,null,function*(){var s,i;let o=rt("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=ke[e.prompt_template.type];return yield l(n,t)}else return yield n.responses.create(t)}),Ne=(e,t)=>_(null,null,function*(){var s,i;let{AzureOpenAI:o}=rt("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=ke[e.prompt_template.type];return yield l(n,t)}else return yield n.responses.create(t)}),qe=(e,t)=>_(null,null,function*(){return e.messages.create(t)}),_o=(e,t)=>_(null,null,function*(){return e.completions.create(t)}),Ue={chat:qe,completion:_o},$e=(e,t)=>_(null,null,function*(){let o=rt("@anthropic-ai/sdk").default,n=new o({baseURL:t.baseURL,apiKey:t.apiKey}),r=Ue[e.prompt_template.type];return r(n,t)}),We=(e,t,o,n=!0)=>_(null,null,function*(){try{let r=yield q(`${t}/log-request`,{method:"POST",headers:{"X-API-KEY":e,"Content-Type":"application/json"},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 z(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}}),yo=(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})}),ho=(e,n)=>_(null,null,function*(){var r=n,{stream:t}=r,o=Et(r,["stream"]);return t?yield e.generateContentStream(O({},o)):yield e.generateContent(O({},o))}),go={chat:yo,completion:ho},Kt=(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=go[e.prompt_template.type];return yield c(l,t)}),he=e=>e.replace(/_([a-z])/g,(t,o)=>o.toUpperCase()),Ct=(e,t=new Set)=>!e||typeof e!="object"?e:Array.isArray(e)?e.map(o=>Ct(o,t)):Object.fromEntries(Object.entries(e).map(([o,n])=>t.has(o)?[he(o),n]:[he(o),Ct(n,t)])),Ge=(e,t,o={},n=!1)=>{var c,p,m,g,y,b,R,S,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=(g=e.metadata)==null?void 0:g.model)==null?void 0:y.api_type;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let i=j(O({},e.llm_kwargs||{}),{stream:n});["google","vertexai"].includes(r)&&((R=(b=e.metadata)==null?void 0:b.model)!=null&&R.name.startsWith("gemini"))&&(i=Ct(i,new Set(["function_declarations","properties"])));let l={baseURL:(A=t==null?void 0:t.base_url)!=null?A:(S=e.provider_base_url)==null?void 0:S.url,apiKey:t==null?void 0:t.api_key};return Object.entries(l).forEach(([C,h])=>{h!==void 0&&(i[C]=h)}),n&&me.includes(r)&&s==="chat-completions"&&(i.stream_options={include_usage:!0}),{provider_type:r,kwargs:i}},Me=(e,t)=>{let o=ye[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},Ke=(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 Kt(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 qe(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`)}),je=(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(O({},t));return yield s.send(i)}else{t==null||delete t.stream;let i=new n(O({},t));return yield s.send(i)}}),Fe=(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=Ue[e.prompt_template.type];return r(n,t)}),De=(e,t)=>_(null,null,function*(){let{Mistral:o}=yield import("@mistralai/mistralai"),n=new o({apiKey:process.env.MISTRAL_API_KEY});return t=Ct(t,new Set),t!=null&&t.stream?(delete t.stream,yield n.chat.stream(t)):(delete t.stream,yield n.chat.complete(t))}),jt=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 It=class{constructor(t,o,n=!0){this.create=()=>Se(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=t,this.baseURL=o,this.throwOnError=n}};import{SpanKind as Pt,SpanStatusCode as Ft}from"@opentelemetry/api";import{ExportResultCode as kt}from"@opentelemetry/core";var Dt=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{[Pt.INTERNAL]:"SpanKind.INTERNAL",[Pt.SERVER]:"SpanKind.SERVER",[Pt.CLIENT]:"SpanKind.CLIENT",[Pt.PRODUCER]:"SpanKind.PRODUCER",[Pt.CONSUMER]:"SpanKind.CONSUMER"}[t]||"SpanKind.INTERNAL"}statusCodeToString(t){return{[Ft.ERROR]:"StatusCode.ERROR",[Ft.OK]:"StatusCode.OK",[Ft.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(kt.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:j(O({},n.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return q(this.url,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey||""},body:JSON.stringify({spans:o})}).then(n=>n.ok?kt.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
+
HTTP error! status: ${n.status}`),kt.FAILED)).catch(n=>(console.error("Error exporting spans:",n),kt.FAILED))}shutdown(){return Promise.resolve()}},Be=Dt;import*as Je from"@opentelemetry/api";import{SimpleSpanProcessor as bo}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Ro}from"@opentelemetry/sdk-trace-node";var st=(e="promptlayer-tracer")=>Je.trace.getTracer(e),ze=(e,t,o)=>{let n=new Ro,r=new Be(e,t,o),s=new bo(r);n.addSpanProcessor(s),n.register()};var wo=st(),Bt=(e,t,o,n="",r="openai")=>{let s={construct:(i,l)=>{let c=Reflect.construct(i,l);return Object.defineProperties(c,{function_name:{value:n,writable:!0},provider:{value:r}}),new Proxy(c,s)},get:(i,l,c)=>{let p=i[l],m=`${Reflect.get(i,"function_name")}.${l.toString()}`;return typeof p=="object"?(Object.defineProperties(p,{function_name:{value:m,writable:!0},provider:{value:r}}),new Proxy(p,s)):typeof p=="function"?(...g)=>{var C,h,E,L,$,D;let y=new Date().toISOString(),b=Reflect.get(i,"provider"),R=(C=g[0])==null?void 0:C.return_pl_id,S=(h=g[0])==null?void 0:h.pl_tags,A=(E=g[0])==null?void 0:E.pl_warn_on_error;return(L=g[0])==null||delete L.return_pl_id,($=g[0])==null||delete $.pl_tags,(D=g[0])==null||delete D.pl_warn_on_error,wo.startActiveSpan(`${b}.${m}`,I=>_(null,null,function*(){try{I.setAttribute("function_input",JSON.stringify(g));let k=Reflect.apply(p,i,g),B=I.spanContext().spanId;return k instanceof Promise?new Promise((G,Y)=>{k.then(M=>_(null,null,function*(){let J=yield be(e,t,{api_key:e,provider_type:b,function_name:m,request_start_time:y,request_end_time:new Date().toISOString(),request_response:M,kwargs:g[0],return_pl_id:R,tags:S,span_id:B},!A);I.setAttribute("function_output",JSON.stringify(J)),I.setAttribute("response_status","success"),I.end(),G(J)})).catch(M=>{I.recordException(M),I.setAttribute("response_status","error"),I.end(),Y(M)})}):(I.setAttribute("function_output",JSON.stringify(k)),I.setAttribute("response_status","success"),I.end(),k)}catch(k){throw I.recordException(k),I.setAttribute("response_status","error"),I.end(),k}}))}:Reflect.get(i,l,c)}};return new Proxy(o,s)};import*as Lt from"@opentelemetry/api";var Ve=(e,t,o)=>function(...n){let r=st(),s=i=>{try{o&&Object.entries(o).forEach(([c,p])=>{i.setAttribute(c,p)}),i.setAttribute("function_input",JSON.stringify(n));let l=t(...n);return l instanceof Promise?l.then(c=>(i.setAttribute("function_output",JSON.stringify(c)),i.setStatus({code:Lt.SpanStatusCode.OK}),c)).catch(c=>{throw Ye(i,c,n),c}).finally(()=>i.end()):(i.setAttribute("function_output",JSON.stringify(l)),i.setStatus({code:Lt.SpanStatusCode.OK}),i.end(),l)}catch(l){throw Ye(i,l,n),l}};return r.startActiveSpan(e,s)},Ye=(e,t,o)=>{e.setAttribute("function_input",JSON.stringify(o)),e.setStatus({code:Lt.SpanStatusCode.ERROR,message:t instanceof Error?t.message:"Unknown error"}),e.end()};var Nt=class{constructor(t,o,n=!0){this.get=(t,o)=>Ee(this.apiKey,this.baseURL,t,o,this.throwOnError);this.publish=t=>Oe(this.apiKey,this.baseURL,t,this.throwOnError);this.all=t=>Ae(this.apiKey,this.baseURL,t,this.throwOnError);this.apiKey=t,this.baseURL=o,this.throwOnError=n}};var xo=(e,t,o,n=!0)=>{if(!(o.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[r,s]of Object.entries(o.metadata))if(typeof r!="string"||typeof s!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return we(e,t,o,n)},To=(e,t,o,n=!0)=>{if(typeof o.score!="number")throw new Error("Score must be a number");if(o.score<0||o.score>100)throw new Error("Score must be a number between 0 and 100.");return xe(e,t,o,n)},Po=(e,t,o,n=!0)=>{if(!(o.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return Te(e,t,o,n)},So=(e,t,o,n=!0)=>Pe(e,t,o,n),qt=class{constructor(t,o,n=!0){this.group=t=>So(this.apiKey,this.baseURL,t,this.throwOnError);this.metadata=t=>xo(this.apiKey,this.baseURL,t,this.throwOnError);this.prompt=t=>Po(this.apiKey,this.baseURL,t,this.throwOnError);this.score=t=>To(this.apiKey,this.baseURL,t,this.throwOnError);this.apiKey=t,this.baseURL=o,this.throwOnError=n}};import*as He from"@opentelemetry/api";var Eo={openai:Le,anthropic:$e,"openai.azure":Ne,google:Kt,vertexai:Ke,"amazon.bedrock":je,"anthropic.bedrock":Fe,mistral:De},Oo=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=["status","value","error_message","raw_error_message","is_output_node"];return Object.values(e).every(n=>typeof n!="object"||n===null?!1:t.every(r=>r in n))},Xe=class{constructor({apiKey:t=jt("PROMPTLAYER_API_KEY"),baseURL:o=jt("PROMPTLAYER_BASE_URL"),enableTracing:n=!1,throwOnError:r=!0}={}){if(t===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=t,this.baseURL=o||"https://api.promptlayer.com",this.enableTracing=n,this.throwOnError=r,this.templates=new Nt(t,this.baseURL,this.throwOnError),this.group=new It(t,this.baseURL,this.throwOnError),this.track=new qt(t,this.baseURL,this.throwOnError),this.wrapWithSpan=Ve,n&&ze(n,t,this.baseURL)}get Anthropic(){try{let t=rt("@anthropic-ai/sdk").default;return Bt(this.apiKey,this.baseURL,t,"anthropic","anthropic")}catch(t){console.error("To use the Anthropic module, you must install the @anthropic-ai/sdk package.")}}get OpenAI(){try{let t=rt("openai").default;return Bt(this.apiKey,this.baseURL,t,"openai","openai")}catch(t){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(y){return _(this,arguments,function*({promptName:t,promptVersion:o,promptReleaseLabel:n,inputVariables:r,tags:s,metadata:i,groupId:l,modelParameterOverrides:c,stream:p=!1,provider:m,model:g}){return st().startActiveSpan("PromptLayer Run",R=>_(this,null,function*(){try{let S={promptName:t,promptVersion:o,promptReleaseLabel:n,inputVariables:r,tags:s,metadata:i,groupId:l,modelParameterOverrides:c,stream:p};R.setAttribute("function_input",JSON.stringify(S));let A=r,C={label:n,version:o,metadata_filters:i,provider:m,model:g,model_parameter_overrides:c};r&&(C.input_variables=r);let h=yield this.templates.get(t,C);if(!h)throw new Error(`Cannot proceed: prompt template '${t}' could not be fetched. Check the warnings above for the actual error.`);let E=h.prompt_template;if(!h.llm_kwargs){let K=`Prompt '${t}' 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(K);console.warn(`WARNING: ${K}`)}let L=h.metadata;if(!L)throw new Error(`Prompt '${t}' does not have any metadata associated with it.`);let $=L.model;if(!$)throw new Error(`Prompt '${t}' does not have a model parameters associated with it.`);let D=h.custom_provider,I=new Date().toISOString(),{provider_type:k,kwargs:B}=Ge(h,D,c,p),G=k;if(k==="openai"||k==="openai.azure"){let K=$.api_type;G=`${k}:${K}`}$.name.startsWith("gemini")?G="google":$.name.startsWith("claude")&&(G="anthropic");let Y=Me(G,E),{function_name:M,stream_function:J}=Y,Z=Eo[k];if(!Z)throw new Error(`No request function found for provider: ${k}`);let V=yield Z(h,B),Q=K=>{let et=new Date().toISOString();return Ie(this.baseURL,O({function_name:M,provider_type:k,args:[],kwargs:B,tags:s,request_start_time:I,request_end_time:et,api_key:this.apiKey,metadata:i,prompt_id:h.id,prompt_version:h.version,prompt_input_variables:A,group_id:l,return_prompt_blueprint:!0,span_id:R.spanContext().spanId},K),this.throwOnError)};if(p)return _e(V,Q,J,i||h.metadata);let v=yield Q({request_response:V}),tt={request_id:v.request_id,raw_response:V,prompt_blueprint:v.prompt_blueprint};return R.setAttribute("function_output",JSON.stringify(tt)),tt}catch(S){throw R.setStatus({code:He.SpanStatusCode.ERROR,message:S instanceof Error?S.message:"Unknown error"}),S}finally{R.end()}}))})}runWorkflow(l){return _(this,arguments,function*({workflowName:t,inputVariables:o={},metadata:n={},workflowLabelName:r=null,workflowVersion:s=null,returnAllOutputs:i=!1}){try{let c=yield Ce({workflow_name:t,input_variables:o,metadata:n,workflow_label_name:r,workflow_version_number:s,return_all_outputs:i,api_key:this.apiKey,baseURL:this.baseURL});if(!i&&Oo(c)){let m=Object.values(c).filter(y=>y.is_output_node===!0);if(m.length===0)throw new Error(JSON.stringify(c,null,2));if(!m.some(y=>y.status==="SUCCESS"))throw new Error(JSON.stringify(c,null,2))}return c}catch(c){throw c instanceof Error?(console.error("Error running workflow:",c.message),new Error(`Error running workflow: ${c.message}`)):(console.error("Unknown error running workflow:",c),new Error("Unknown error running workflow"))}})}logRequest(t){return _(this,null,function*(){return We(this.apiKey,this.baseURL,t,this.throwOnError)})}};export{Xe as PromptLayer};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|