promptlayer 1.0.51 → 1.0.52

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