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