opik 1.10.50 → 1.10.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/chunk-I6XLGWCQ.js +10 -0
- package/dist/index.cjs +37 -37
- package/dist/index.d.cts +505 -167
- package/dist/index.d.ts +505 -167
- package/dist/index.js +31 -40
- package/dist/typeHelpers-Y42JGES6.js +1 -0
- package/package.json +3 -2
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import {formatDistanceToNow}from'date-fns';import {diffStringsUnified}from'jest-diff';import {link}from'ansi-escapes';import {Logger}from'tslog';import mt from'mustache';import lt from'nunjucks';import {z as z$1}from'zod';var Q=Object.create;var I=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var L=(r,t)=>(t=Symbol[r])?t:Symbol.for("Symbol."+r),v=r=>{throw TypeError(r)};var tt=(r,t,e)=>t in r?I(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e;var B=(r,t)=>I(r,"name",{value:t,configurable:true});var Pt=(r,t)=>{for(var e in t)I(r,e,{get:t[e],enumerable:true});};var bt=r=>{var t;return [,,,Q((t=r==null?void 0:r[L("metadata")])!=null?t:null)]},F=["class","method","getter","setter","accessor","field","value","get","set"],V=r=>r!==void 0&&typeof r!="function"?v("Function expected"):r,et=(r,t,e,i,o)=>({kind:F[r],name:t,metadata:i,addInitializer:n=>e._?v("Already initialized"):o.push(V(n||null))}),rt=(r,t)=>tt(t,L("metadata"),r[3]),wt=(r,t,e,i)=>{for(var o=0,n=r[t>>1],s=n&&n.length;o<s;o++)t&1?n[o].call(e):i=n[o].call(e,i);return i},kt=(r,t,e,i,o,n)=>{var s,p,d,f,h,a=t&7,O=!!(t&8),c=!!(t&16),w=a>3?r.length+1:a?O?1:2:0,l=F[a+5],k=a>3&&(r[w-1]=[]),C=r[w]||(r[w]=[]),u=a&&(!c&&!O&&(o=o.prototype),a<5&&(a>3||!c)&&X(a<4?o:{get[e](){return Z(this,n)},set[e](g){return U(this,n,g)}},e));a?c&&a<4&&B(n,(a>2?"set ":a>1?"get ":"")+e):B(o,e);for(var D=i.length-1;D>=0;D--)f=et(a,e,d={},r[3],C),a&&(f.static=O,f.private=c,h=f.access={has:c?g=>it(o,g):g=>e in g},a^3&&(h.get=c?g=>(a^1?Z:ot)(g,o,a^4?n:u.get):g=>g[e]),a>2&&(h.set=c?(g,$)=>U(g,o,$,a^4?n:u.set):(g,$)=>g[e]=$)),p=(0, i[D])(a?a<4?c?n:u[l]:a>4?void 0:{get:u.get,set:u.set}:o,f),d._=1,a^4||p===void 0?V(p)&&(a>4?k.unshift(p):a?c?n=p:u[l]=p:o=p):typeof p!="object"||p===null?v("Object expected"):(V(s=p.get)&&(u.get=s),V(s=p.set)&&(u.set=s),V(s=p.init)&&k.unshift(s));return a||rt(r,o),u&&I(o,e,u),c?a^4?n:u:o};var N=(r,t,e)=>t.has(r)||v("Cannot "+e),it=(r,t)=>Object(t)!==t?v('Cannot use the "in" operator on this value'):r.has(t),Z=(r,t,e)=>(N(r,t,"read from private field"),e?e.call(r):t.get(r));var U=(r,t,e,i)=>(N(r,t,"write to private field"),i?i.call(r,e):t.set(r,e),e),ot=(r,t,e)=>(N(r,t,"access private method"),e);var pt={SILLY:0,TRACE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,FATAL:6};function Ot(r,t=r){return link(t,r)}var y=new Logger({hideLogPositionForProduction:true,prettyLogTemplate:"{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}} {{logLevelName}} "}),at=r=>{y.settings.minLevel=pt[r];},Tt=()=>{y.settings.minLevel=100;};at(process.env.OPIK_LOG_LEVEL||"INFO");var T={MUSTACHE:"mustache",JINJA2:"jinja2"},S={Text:"text",Chat:"chat"};var m=class r extends Error{constructor(t){super(t),this.name="PromptValidationError",Object.setPrototypeOf(this,r.prototype);}},J=class r extends Error{constructor(t,e,i){let o=`Prompt '${t}' has template_structure='${e}' but attempted to access as '${i}'. Template structure is immutable after creation.`;super(o),this.name="PromptTemplateStructureMismatch",this.promptName=t,this.existingStructure=e,this.attemptedStructure=i,Object.setPrototypeOf(this,r.prototype);}};function ct(r){try{let e=mt.parse(r).filter(i=>{let o=i[0];return o==="name"||o==="#"||o==="&"||o==="^"}).map(i=>i[1].split(".")[0]);return new Set(e)}catch(t){throw new m(`Invalid Mustache template syntax: ${t instanceof Error?t.message:String(t)}`)}}function q(r,t,e){if(e!=="mustache")return;let i=ct(r),o=new Set(Object.keys(t)),n=new Set([...i].filter(s=>!o.has(s)));if(n.size>0){let s=[];throw s.push(`Missing required variables: ${[...n].join(", ")}`),s.push(`Template placeholders: {${[...i].join(", ")}}`),s.push(`Provided variables: {${[...o].join(", ")}}`),new m(`Template variables validation failed:
|
|
2
|
+
${s.join(`
|
|
3
|
+
`)}`)}}function b(r,t,e){try{switch(q(r,t,e),e){case "mustache":return mt.render(r,t,{},{escape:i=>i});case "jinja2":return lt.renderString(r,t);default:return r}}catch(i){if(i instanceof m)throw i;let o=i instanceof Error?i.message:String(i);throw new m(`Failed to format prompt template: ${o}`)}}function W(r){let t=[];for(let e=0;e<r.length;e++){let i=r[e];if(t.push(`Message ${e+1} [${i.role}]:`),typeof i.content=="string")t.push(K(i.content));else if(Array.isArray(i.content))for(let o=0;o<i.content.length;o++){let n=i.content[o];if(t.push(` Part ${o+1}:`),t.push(` Type: ${n.type}`),n.type==="text"&&"text"in n){let s=n;t.push(K(String(s.text),4)),z(s,["type","text"],t,4);}else if(n.type==="image_url"&&"image_url"in n){let s=n,p=s.image_url;t.push(` URL: ${p.url}`),R(p,["url"],t,4),z(s,["type","image_url"],t,4);}else if(n.type==="video_url"&&"video_url"in n){let s=n,p=s.video_url;t.push(` URL: ${p.url}`),R(p,["url"],t,4),z(s,["type","video_url"],t,4);}else t.push(" [Difference found in unrecognized content type]");}e<r.length-1&&t.push("");}return t.join(`
|
|
4
|
+
`)}function z(r,t,e,i=4){let o=Object.keys(r).filter(n=>!t.includes(n));if(o.length>0)for(let n of o.sort()){let s=r[n];e.push(`${" ".repeat(i)}${n}: ${G(s)}`);}}function R(r,t,e,i=4){let o=Object.keys(r).filter(n=>!t.includes(n));if(o.length>0)for(let n of o.sort()){let s=r[n];e.push(`${" ".repeat(i)}${n}: ${G(s)}`);}}function G(r){return r===null?"null":r===void 0?"undefined":typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)||typeof r=="object"?JSON.stringify(r):String(r)}function K(r,t=2){let e=" ".repeat(t);return r.split(`
|
|
5
|
+
`).map(i=>`${e}${i}`).join(`
|
|
6
|
+
`)}var A=class r{constructor(t){this.id=t.versionId,this.name=t.name,this.prompt=t.prompt,this.commit=t.commit,this.type=t.type,this.metadata=t.metadata,this.changeDescription=t.changeDescription,this.tags=t.tags,this.createdAt=t.createdAt,this.createdBy=t.createdBy;}format(t){return b(this.prompt,t,this.type)}getVersionAge(){return this.createdAt?formatDistanceToNow(new Date(this.createdAt),{addSuffix:true}):"Unknown"}getVersionInfo(){let t=[`[${this.commit}]`];if(this.createdAt){let e=new Date(this.createdAt);t.push(e.toISOString().split("T")[0]);}return this.createdBy&&t.push(`by ${this.createdBy}`),this.changeDescription&&t.push(`- ${this.changeDescription}`),t.join(" ")}compareTo(t){let e=`Current version [${this.commit}]`,i=`Other version [${t.commit}]`,o=this.prompt,n=t.prompt;this.isChatPrompt(this.prompt)&&(o=this.formatChatPromptString(this.prompt)),this.isChatPrompt(t.prompt)&&(n=this.formatChatPromptString(t.prompt));let s=diffStringsUnified(n,o,{aAnnotation:i,bAnnotation:e,includeChangeCounts:true,contextLines:3,expand:false});return y.info(`
|
|
7
|
+
Prompt version comparison:
|
|
8
|
+
${s}`),s}isChatPrompt(t){try{let e=JSON.parse(t);return Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&"role"in e[0]&&"content"in e[0]}catch{return false}}formatChatPromptString(t){try{let e=JSON.parse(t);return W(e)}catch{return t}}static fromApiResponse(t,e){var i;if(!e.template)throw new m("Invalid API response: missing required field 'template'");if(!e.commit)throw new m("Invalid API response: missing required field 'commit'");if(!e.promptId)throw new m("Invalid API response: missing required field 'promptId'");if(!e.id)throw new m("Invalid API response: missing required field 'id'");return new r({name:t,prompt:e.template,commit:e.commit,promptId:e.promptId,versionId:e.id,type:(i=e.type)!=null?i:T.MUSTACHE,metadata:e.metadata,changeDescription:e.changeDescription,tags:e.tags,createdAt:e.createdAt?new Date(e.createdAt):void 0,createdBy:e.createdBy})}};var x=class{constructor(t,e){var i,o;this.id=t.promptId,this.versionId=t.versionId,this.commit=t.commit,this.type=(i=t.type)!=null?i:"mustache",this.changeDescription=t.changeDescription,this.templateStructure=(o=t.templateStructure)!=null?o:"text",this._name=t.name,this._description=t.description,this._tags=t.tags?[...t.tags]:[],this._metadata=t.metadata,this.opik=e;}get name(){return this._name}get description(){return this._description}get tags(){return Object.freeze([...this._tags])}get metadata(){if(this._metadata)return structuredClone(this._metadata)}async updateProperties(t){var e,i,o,n;return await this.opik.api.prompts.updatePrompt(this.id,{name:(e=t.name)!=null?e:this._name,description:t.description,tags:t.tags},this.opik.api.requestOptions),this._name=(i=t.name)!=null?i:this._name,this._description=(o=t.description)!=null?o:this._description,this._tags=(n=t.tags)!=null?n:this._tags,this}async delete(){await this.opik.deletePrompts([this.id]);}async getVersions(t){var e;y.debug("Getting versions for prompt",{promptId:this.id,name:this.name});try{let i=[],o=1,n=100;for(;;){let p=(e=(await this.opik.api.prompts.getPromptVersions(this.id,{page:o,size:n,search:t==null?void 0:t.search,sorting:t==null?void 0:t.sorting,filters:t==null?void 0:t.filters},this.opik.api.requestOptions)).content)!=null?e:[];if(i.push(...p),p.length<n)break;o++;}return y.debug("Successfully retrieved prompt versions",{promptId:this.id,name:this.name,totalVersions:i.length}),i.map(s=>A.fromApiResponse(this.name,s))}catch(i){throw y.error("Failed to get prompt versions",{promptId:this.id,name:this.name,error:i}),i}}async restoreVersion(t){y.debug("Restoring prompt version",{promptId:this.id,name:this.name,versionId:t.id,versionCommit:t.commit});try{let e=await this.opik.api.prompts.restorePromptVersion(this.id,t.id,this.opik.api.requestOptions);return y.debug("Successfully restored prompt version",{promptId:this.id,name:this.name,restoredVersionId:e.id,restoredCommit:e.commit}),e}catch(e){throw y.error("Failed to restore prompt version",{promptId:this.id,name:this.name,versionId:t.id,versionCommit:t.commit,error:e}),e}}async retrieveVersionByCommit(t){try{return await this.opik.api.prompts.retrievePromptVersion({name:this.name,commit:t},this.opik.api.requestOptions)}catch(e){if(e&&typeof e=="object"&&"statusCode"in e&&e.statusCode===404)return null;throw y.error("Failed to retrieve prompt version",{promptName:this.name,commit:t,error:e}),e}}};var _=class r extends x{constructor(t,e){super({...t,templateStructure:S.Text},e),this.prompt=t.prompt;}get template(){return this.prompt}format(t){return b(this.prompt,t,this.type)}static fromApiResponse(t,e,i){var n;if(!e.template)throw new m("Invalid API response: missing required field 'template'");if(!e.commit)throw new m("Invalid API response: missing required field 'commit'");if(!e.promptId)throw new m("Invalid API response: missing required field 'promptId'");if(!e.id)throw new m("Invalid API response: missing required field 'id' (version ID)");let o=(n=e.type)!=null?n:T.MUSTACHE;if(o!=="mustache"&&o!=="jinja2")throw new m(`Invalid API response: unknown prompt type '${o}'`);return new r({promptId:e.promptId,versionId:e.id,name:t.name,prompt:e.template,commit:e.commit,metadata:e.metadata,type:o,changeDescription:e.changeDescription,description:t.description,tags:t.tags},i)}async useVersion(t){var i;let e=await this.restoreVersion(t);return r.fromApiResponse({name:this.name,description:this.description,tags:Array.from((i=this.tags)!=null?i:[])},e,this.opik)}async getVersion(t){var i;let e=await this.retrieveVersionByCommit(t);return e?r.fromApiResponse({name:this.name,description:this.description,tags:Array.from((i=this.tags)!=null?i:[])},e,this.opik):null}};var M=class{constructor(t,e="mustache",i=false){this.messages=t,this.templateType=e,this.validatePlaceholders=i;}format(t,e){let i={vision:true,video:true,...e},o=[];for(let n of this.messages){let s=n.role;if(!s)continue;let p=n.content,d;if(typeof p=="string")d=b(p,t,this.templateType);else if(Array.isArray(p))d=this.renderContentParts(p,t,i);else throw new m(`Invalid message content type. Expected string or array of content parts, got: ${typeof p}`);o.push({role:s,content:d});}return o}renderContentParts(t,e,i){var s,p,d,f,h,a,O;let o=[],n=false;for(let c of t){if(!c||typeof c!="object")continue;switch(c.type){case "text":{let k=b(c.text||"",e,this.templateType);o.push({type:"text",text:k});break}case "image_url":{if(i.vision===false)n=true,o.push({type:"text",text:"<<<image>>><<</image>>>"});else {let l=c,k=((s=l.image_url)==null?void 0:s.url)||"",C=b(k,e,this.templateType);if(C){let u={type:"image_url",image_url:{url:C}};(p=l.image_url)!=null&&p.detail&&(u.image_url.detail=l.image_url.detail),o.push(u);}}break}case "video_url":{if(i.video===false)n=true,o.push({type:"text",text:"<<<video>>><<</video>>>"});else {let l=c,k=((d=l.video_url)==null?void 0:d.url)||"",C=b(k,e,this.templateType);if(C){let u={type:"video_url",video_url:{url:C}};(f=l.video_url)!=null&&f.mime_type&&(u.video_url.mime_type=l.video_url.mime_type),(h=l.video_url)!=null&&h.duration&&(u.video_url.duration=l.video_url.duration),(a=l.video_url)!=null&&a.format&&(u.video_url.format=l.video_url.format),(O=l.video_url)!=null&&O.detail&&(u.video_url.detail=l.video_url.detail),o.push(u);}}break}default:o.push(c);}}if(n){let c=[];for(let w of o)if(w.type==="text"){let l=w.text;l&&c.push(l);}else c.push(JSON.stringify(w));return c.join(`
|
|
9
|
+
|
|
10
|
+
`)}return o.length===1&&o[0].type==="text"?o[0].text:o}};var j=class r extends x{constructor(t,e){super({...t,templateStructure:S.Chat},e),this.messages=t.messages,this.chatTemplate=new M(t.messages,this.type);}get template(){return structuredClone(this.messages)}format(t,e){return this.chatTemplate.format(t,e)}static fromApiResponse(t,e,i){var s;if(!e.template)throw new m("Invalid API response: missing required field 'template'");if(!e.commit)throw new m("Invalid API response: missing required field 'commit'");if(!e.promptId)throw new m("Invalid API response: missing required field 'promptId'");if(!e.id)throw new m("Invalid API response: missing required field 'id' (version ID)");let o;try{if(o=JSON.parse(e.template),!Array.isArray(o))throw new m("Invalid chat prompt template: expected array of messages")}catch(p){throw p instanceof m?p:new m(`Failed to parse chat prompt template: ${p instanceof Error?p.message:String(p)}`)}let n=(s=e.type)!=null?s:T.MUSTACHE;if(n!=="mustache"&&n!=="jinja2")throw new m(`Invalid API response: unknown prompt type '${n}'`);return new r({promptId:e.promptId,versionId:e.id,name:t.name,messages:o,commit:e.commit,metadata:e.metadata,type:n,changeDescription:e.changeDescription,description:t.description,tags:t.tags},i)}async useVersion(t){var i;let e=await this.restoreVersion(t);return r.fromApiResponse({name:this.name,description:this.description,tags:Array.from((i=this.tags)!=null?i:[])},e,this.opik)}async getVersion(t){var i;let e=await this.retrieveVersionByCommit(t);return e?r.fromApiResponse({name:this.name,description:this.description,tags:Array.from((i=this.tags)!=null?i:[])},e,this.opik):null}};function Pe(r){let t=r._def.description;if(!t)throw new TypeError("Schema must have a .describe() name \u2014 e.g. z.object({...}).describe('MyConfig')");return t}function H(r){let t=r,e=false;return (t instanceof z$1.ZodOptional||t instanceof z$1.ZodNullable)&&(t=t.unwrap(),e=true),{inner:t,isOptional:e}}function gt(r){var e;let{inner:t}=H(r);if(t instanceof z$1.ZodString)return "string";if(t instanceof z$1.ZodBoolean)return "boolean";if(t instanceof z$1.ZodNumber)return ((e=t._def.checks)!=null?e:[]).some(o=>o.kind==="int")?"integer":"float";if(t instanceof z$1.ZodArray||t instanceof z$1.ZodRecord||t instanceof z$1.ZodObject)return "string";if(t instanceof z$1.ZodEffects){let i=Object.create(null);if(Object.setPrototypeOf(i,_.prototype),t.safeParse(i).success||(Object.setPrototypeOf(i,j.prototype),t.safeParse(i).success))return "prompt";if(Object.setPrototypeOf(i,A.prototype),t.safeParse(i).success)return "prompt_commit"}throw new TypeError(`Unsupported Zod type: ${t.constructor.name}`)}function E(r,t){let e=new Map;for(let[i,o]of Object.entries(r.shape)){let n=o,{inner:s,isOptional:p}=H(n),d=gt(n),f=n._def.description,h=s instanceof z$1.ZodArray||s instanceof z$1.ZodRecord||s instanceof z$1.ZodObject;e.set(i,{prefixedKey:`${t}.${i}`,backendType:d,description:f,isOptional:p||n.isOptional(),isJsonEncoded:h});}return e}function Y(r,t){let e=t!=null?t:yt(r);if(e==="boolean")return r?"true":"false";if(e==="integer"||e==="float"){if(!Number.isFinite(r))throw new TypeError(`Cannot serialize non-finite number: ${r}`);return String(r)}if(e==="string")return Array.isArray(r)||typeof r=="object"&&r!==null?JSON.stringify(r):r;if(e==="prompt"){let i=r;if(!i.commit)throw new TypeError("Cannot serialize prompt without a commit");return i.commit}if(e==="prompt_commit")return r.commit;throw new TypeError(`Unsupported backend type: ${e}`)}function be(r,t,e){let i=E(r,e),o=[];for(let[n,s]of i.entries()){let p=t[n];if(p==null){o.push({key:s.prefixedKey,value:void 0,type:"string",description:s.description});continue}o.push({key:s.prefixedKey,value:Y(p,s.backendType),type:s.backendType,description:s.description});}return o}function ht(r,t){if(r==null)return null;switch(t){case "boolean":return r.toLowerCase()==="true";case "integer":return Math.trunc(Number(r));case "float":return Number(r);case "string":case "prompt":case "prompt_commit":return r;default:return r}}function we(r,t,e,i,o){var p;let n=E(r,e),s={};for(let[d,f]of n.entries()){let h=t[f.prefixedKey];if(h!==void 0)if((f.backendType==="prompt"||f.backendType==="prompt_commit")&&o)s[d]=o[f.prefixedKey];else {let a=ht(h.value,(p=h.type)!=null?p:f.backendType);s[d]=f.isJsonEncoded&&typeof a=="string"?JSON.parse(a):a;}else s[d]=i[d];}return s}function ke(r,t,e,i){let o=E(r,i);for(let[n,s]of o.entries()){let p=t[n],d=e.getRawValue(s.prefixedKey);if(p==null){if(d!==void 0)return false;continue}let f=Y(p,s.backendType);if(d===void 0||d!==f)return false}return true}function yt(r){if(typeof r=="boolean")return "boolean";if(typeof r=="number")return Number.isInteger(r)?"integer":"float";if(typeof r=="string")return "string";if(r instanceof x)return "prompt";if(r instanceof A)return "prompt_commit";if(Array.isArray(r)||typeof r=="object"&&r!==null)return "string";throw new TypeError(`Unsupported value type: ${typeof r}`)}export{Pt as a,bt as b,rt as c,wt as d,kt as e,Ot as f,y as g,at as h,Tt as i,T as j,S as k,J as l,b as m,A as n,_ as o,j as p,Pe as q,gt as r,E as s,Y as t,be as u,ht as v,we as w,ke as x};
|