@midscene/ios 0.30.8 → 0.30.9
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/package.json +5 -5
- package/static/index.html +1 -1
- package/static/static/js/{657.5a5fe47b.js → 931.dc961e99.js} +57 -110
- package/static/static/js/{657.5a5fe47b.js.LICENSE.txt → 931.dc961e99.js.LICENSE.txt} +0 -17
- package/static/static/js/{657.5a5fe47b.js.map → 931.dc961e99.js.map} +1 -1
- package/static/static/js/async/659.9afd03db.js +21 -0
- package/static/static/js/async/659.9afd03db.js.map +1 -0
- package/static/static/js/{index.81b3ced1.js → index.c7ba8adb.js} +4 -15
- package/static/static/js/{index.81b3ced1.js.map → index.c7ba8adb.js.map} +1 -1
- package/static/static/js/async/290.dd04c2bc.js +0 -21
- package/static/static/js/async/290.dd04c2bc.js.map +0 -1
- /package/static/static/js/{index.81b3ced1.js.LICENSE.txt → index.c7ba8adb.js.LICENSE.txt} +0 -0
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
"use strict";(self.webpackChunkplayground=self.webpackChunkplayground||[]).push([["290"],{19042:function(t,e,a){let i,r,n;a.d(e,{wrapOpenAI:()=>tf});var s=a(96945),o=a(67774),l=a(32656),d=a(88464);let u=(...t)=>fetch(...t),h=Symbol.for("ls:fetch_implementation"),c=()=>globalThis[h]??u,p=[400,401,403,404,405,406,407,408],m=[409];class f{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in d?this.queue=new d.default({concurrency:this.maxConcurrency}):this.queue=new d({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...e){let a=this.onFailedResponseHook;return this.queue.add(()=>l(()=>t(...e).catch(t=>{if(t instanceof Error)throw t;throw Error(t)}),{async onFailedAttempt(t){if(t.message.startsWith("Cancel")||t.message.startsWith("TimeoutError")||t.message.startsWith("AbortError")||t?.code==="ECONNABORTED")throw t;let e=t?.response,i=e?.status;if(i){if(p.includes(+i))throw t;if(m.includes(+i))return;a&&await a(e)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...a){return t.signal?Promise.race([this.call(e,...a),new Promise((e,a)=>{t.signal?.addEventListener("abort",()=>{a(Error("AbortError"))})})]):this.call(e,...a)}fetch(...t){return this.call(()=>c()(...t).then(t=>t.ok?t:Promise.reject(t)))}}function g(t){return"function"==typeof t?._getType}function _(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}var b=a(46633);function y(t,e){if(!b.Z(t))throw Error(void 0!==e?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`);return t}let w={};function v(t){w[t]||(console.warn(t),w[t]=!0)}function O(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw Error(`Invalid identifier format: ${t}`);let[e,a]=t.split(":"),i=a||"latest";if(e.includes("/")){let[a,r]=e.split("/",2);if(!a||!r)throw Error(`Invalid identifier format: ${t}`);return[a,r,i]}if(!e)throw Error(`Invalid identifier format: ${t}`);return["-",e,i]}a(78970);class S extends Error{constructor(t){super(t),this.name="LangSmithConflictError"}}async function j(t,e,a){let i;if(t.ok){a&&(i=await t.text());return}i=await t.text();let r=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Server response: ${i}`;if(409===t.status)throw new S(r);throw Error(r)}var $={result:"[Circular]"},I=[],P=[];let E=new TextEncoder;function A(t){return E.encode(t)}function T(t,e,a,i){try{let i=JSON.stringify(t,e,a);return A(i)}catch(s){let n;if(!s.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."),A("[Unserializable]");console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),void 0===i&&(i={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),function t(e,a,i,r,n,s,o){if(s+=1,"object"==typeof e&&null!==e){for(l=0;l<r.length;l++)if(r[l]===e)return void C($,e,a,n);if(void 0!==o.depthLimit&&s>o.depthLimit||void 0!==o.edgesLimit&&i+1>o.edgesLimit)return void C("[...]",e,a,n);if(r.push(e),Array.isArray(e))for(l=0;l<e.length;l++)t(e[l],l,l,r,e,s,o);else{var l,d=Object.keys(e);for(l=0;l<d.length;l++){var u=d[l];t(e[u],u,l,r,e,s,o)}}r.pop()}}(t,"",0,[],void 0,0,i);try{var r;n=0===P.length?JSON.stringify(t,e,a):JSON.stringify(t,(r=e,r=void 0!==r?r:function(t,e){return e},function(t,e){if(P.length>0)for(var a=0;a<P.length;a++){var i=P[a];if(i[1]===t&&i[0]===e){e=i[2],P.splice(a,1);break}}return r.call(this,t,e)}),a)}catch(t){return A("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==I.length;){let t=I.pop();4===t.length?Object.defineProperty(t[0],t[1],t[3]):t[0][t[1]]=t[2]}}return A(n)}}function C(t,e,a,i){var r=Object.getOwnPropertyDescriptor(i,a);void 0!==r.get?r.configurable?(Object.defineProperty(i,a,{value:t}),I.push([i,a,e,r])):P.push([e,a,t]):(i[a]=t,I.push([i,a,e]))}function U(t){let e=B(),a=function(){let t=function(){try{if(void 0!==D&&D.env)return Object.entries(D.env).reduce((t,[e,a])=>(t[e]=String(a),t),{});return}catch(t){return}}()||{},e={},a=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[i,r]of Object.entries(t))(i.startsWith("LANGCHAIN_")||i.startsWith("LANGSMITH_"))&&"string"==typeof r&&!a.includes(i)&&!i.toLowerCase().includes("key")&&!i.toLowerCase().includes("secret")&&!i.toLowerCase().includes("token")&&("LANGCHAIN_REVISION_ID"===i?e.revision_id=r:e[i]=r);return e}(),i=t.extra??{},r=i.metadata;return t.extra={...i,runtime:{...e,...i?.runtime},metadata:{...a,...a.revision_id||t.revision_id?{revision_id:t.revision_id??a.revision_id}:{},...r}},t}async function x(t){let e=[];for await(let a of t)e.push(a);return e}function R(t){if(void 0!==t)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let k=async t=>{if(t?.status===429){let e=1e3*parseInt(t.headers.get("retry-after")??"30",10);if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};class N{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(t){let e,a=new Promise(t=>{e=t}),i=T(t.item).length;return this.items.push({action:t.action,payload:t.item,itemPromiseResolve:e,itemPromise:a,size:i}),this.sizeBytes+=i,a}pop(t){if(t<1)throw Error("Number of bytes to pop off may not be less than 1.");let e=[],a=0;for(;a+(this.peek()?.size??0)<t&&this.items.length>0;){let t=this.items.shift();t&&(e.push(t),a+=t.size,this.sizeBytes-=t.size)}if(0===e.length&&this.items.length>0){let t=this.items.shift();e.push(t),a+=t.size,this.sizeBytes-=t.size}return[e.map(t=>({action:t.action,item:t.payload})),()=>e.forEach(t=>t.itemPromiseResolve())]}}class L{constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new N}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:"false"===H("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1});let e=L.getDefaultClientConfig();if(this.tracingSampleRate=(()=>{let t=G("TRACING_SAMPLING_RATE");if(void 0===t)return;let e=parseFloat(t);if(e<0||e>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${e}`);return e})(),this.apiUrl=R(t.apiUrl??e.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=R(t.apiKey??e.apiKey),this.webUrl=R(t.webUrl??e.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=t.timeout_ms??9e4,this.caller=new f(t.callerOptions??{}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.batchIngestCaller=new f({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:k}),this.hideInputs=t.hideInputs??t.anonymizer??e.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??e.hideOutputs,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){let t=G("API_KEY"),e=G("ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:e,apiKey:t,webUrl:void 0,hideInputs:"true"===G("HIDE_INPUTS"),hideOutputs:"true"===G("HIDE_OUTPUTS")}}getHostUrl(){if(this.webUrl)return this.webUrl;if((t=>{let e=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===e||"127.0.0.1"===e||"::1"===e})(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("beta"))return this.webUrl="https://beta.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get headers(){let t={"User-Agent":`langsmith-js/${M}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),t}processInputs(t){return!1===this.hideInputs?t:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(t):t}processOutputs(t){return!1===this.hideOutputs?t:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(t):t}prepareRunCreateOrUpdateInputs(t){let e={...t};return void 0!==e.inputs&&(e.inputs=this.processInputs(e.inputs)),void 0!==e.outputs&&(e.outputs=this.processOutputs(e.outputs)),e}async _getResponse(t,e){let a=e?.toString()??"",i=`${this.apiUrl}${t}?${a}`,r=await this.caller.call(c(),i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(r,`Failed to fetch ${t}`),r}async _get(t,e){return(await this._getResponse(t,e)).json()}async *_getPaginated(t,e=new URLSearchParams,a){let i=Number(e.get("offset"))||0,r=Number(e.get("limit"))||100;for(;;){e.set("offset",String(i)),e.set("limit",String(r));let n=`${this.apiUrl}${t}?${e}`,s=await this.caller.call(c(),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(s,`Failed to fetch ${t}`);let o=a?a(await s.json()):await s.json();if(0===o.length||(yield o,o.length<r))break;i+=o.length}}async *_getCursorPaginatedList(t,e=null,a="POST",i="runs"){let r=e?{...e}:{};for(;;){let e=await this.caller.call(c(),`${this.apiUrl}${t}`,{method:a,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(r)}),n=await e.json();if(!n||!n[i])break;yield n[i];let s=n.cursors;if(!s||!s.next)break;r.cursor=s.next}}_filterForSampling(t,e=!1){if(void 0===this.tracingSampleRate)return t;if(e){let e=[];for(let a of t)this.filteredPostUuids.has(a.id)?this.filteredPostUuids.delete(a.id):e.push(a);return e}{let e=[];for(let a of t)a.id!==a.trace_id&&!this.filteredPostUuids.has(a.trace_id)||Math.random()<this.tracingSampleRate?e.push(a):this.filteredPostUuids.add(a.id);return e}}async _getBatchSizeLimitBytes(){let t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t.batch_ingest_config?.size_limit_bytes??0x1400000}async _getMultiPartSupport(){let t=await this._ensureServerInfo();return t.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue(t){let e=[];for(;this.autoBatchQueue.items.length>0;){let[a,i]=this.autoBatchQueue.pop(t);if(!a.length){i();break}let r=this._processBatch(a,i).catch(console.error);e.push(r)}return Promise.all(e)}async _processBatch(t,e){if(!t.length)return void e();try{let e={runCreates:t.filter(t=>"create"===t.action).map(t=>t.item),runUpdates:t.filter(t=>"update"===t.action).map(t=>t.item)},a=await this._ensureServerInfo();a?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(e):await this.batchIngestRuns(e)}finally{e()}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===t.action&&(t.item=U(t.item));let e=this.autoBatchQueue.push(t);if(this.manualFlushMode)return e;let a=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>a&&this.drainAutoBatchQueue(a),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(a)},this.autoBatchAggregationDelayMs)),e}async _getServerInfo(){let t=await c()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(2500),...this.fetchOptions});return await j(t,"get server info"),t.json()}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let t=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(t)}async createRun(t){if(!this._filterForSampling([t]).length)return;let e={...this.headers,"Content-Type":"application/json"},a=t.project_name;delete t.project_name;let i=this.prepareRunCreateOrUpdateInputs({session_name:a,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==i.trace_id&&void 0!==i.dotted_order)return void this.processRunOperation({action:"create",item:i}).catch(console.error);let r=U(i),n=await this.caller.call(c(),`${this.apiUrl}/runs`,{method:"POST",headers:e,body:T(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(n,"create run",!0)}async batchIngestRuns({runCreates:t,runUpdates:e}){if(void 0===t&&void 0===e)return;let a=t?.map(t=>this.prepareRunCreateOrUpdateInputs(t))??[],i=e?.map(t=>this.prepareRunCreateOrUpdateInputs(t))??[];if(a.length>0&&i.length>0){let t=a.reduce((t,e)=>(e.id&&(t[e.id]=e),t),{}),e=[];for(let a of i)void 0!==a.id&&t[a.id]?t[a.id]={...t[a.id],...a}:e.push(a);a=Object.values(t),i=e}let r={post:this._filterForSampling(a),patch:this._filterForSampling(i,!0)};if(!r.post.length&&!r.patch.length)return;let n={post:[],patch:[]};for(let t of["post","patch"]){let e=r[t].reverse(),a=e.pop();for(;void 0!==a;)n[t].push(a),a=e.pop()}(n.post.length>0||n.patch.length>0)&&await this._postBatchIngestRuns(T(n))}async _postBatchIngestRuns(t){let e={...this.headers,"Content-Type":"application/json",Accept:"application/json"},a=await this.batchIngestCaller.call(c(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:e,body:t,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,"batch create run",!0)}async multipartIngestRuns({runCreates:t,runUpdates:e}){if(void 0===t&&void 0===e)return;let a={},i=[];for(let e of t??[]){let t=this.prepareRunCreateOrUpdateInputs(e);void 0!==t.id&&void 0!==t.attachments&&(a[t.id]=t.attachments),delete t.attachments,i.push(t)}let r=[];for(let t of e??[])r.push(this.prepareRunCreateOrUpdateInputs(t));if(void 0!==i.find(t=>void 0===t.trace_id||void 0===t.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==r.find(t=>void 0===t.trace_id||void 0===t.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&r.length>0){let t=i.reduce((t,e)=>(e.id&&(t[e.id]=e),t),{}),e=[];for(let a of r)void 0!==a.id&&t[a.id]?t[a.id]={...t[a.id],...a}:e.push(a);i=Object.values(t),r=e}if(0===i.length&&0===r.length)return;let n=[],s=[];for(let[t,e]of[["post",i],["patch",r]])for(let i of e){let{inputs:e,outputs:r,events:o,attachments:l,...d}=i,u={inputs:e,outputs:r,events:o},h=T(d);for(let[e,a]of(s.push({name:`${t}.${d.id}`,payload:new Blob([h],{type:`application/json; length=${h.length}`})}),Object.entries(u))){if(void 0===a)continue;let i=T(a);s.push({name:`${t}.${d.id}.${e}`,payload:new Blob([i],{type:`application/json; length=${i.length}`})})}if(void 0!==d.id){let t=a[d.id];if(t)for(let[e,i]of(delete a[d.id],Object.entries(t))){let t,a;if(Array.isArray(i)?[t,a]=i:(t=i.mimeType,a=i.data),e.includes(".")){console.warn(`Skipping attachment '${e}' for run ${d.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}s.push({name:`attachment.${d.id}.${e}`,payload:new Blob([a],{type:`${t}; length=${a.byteLength}`})})}}n.push(`trace=${d.trace_id},id=${d.id}`)}await this._sendMultipartRequest(s,n.join("; "))}async _sendMultipartRequest(t,e){try{let e="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=[];for(let i of t)a.push(new Blob([`--${e}\r
|
|
2
|
-
`])),a.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
|
|
3
|
-
`,`Content-Type: ${i.payload.type}\r
|
|
4
|
-
\r
|
|
5
|
-
`])),a.push(i.payload),a.push(new Blob(["\r\n"]));a.push(new Blob([`--${e}--\r
|
|
6
|
-
`]));let i=new Blob(a),r=await i.arrayBuffer(),n=await this.batchIngestCaller.call(c(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${e}`},body:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(n,"ingest multipart runs",!0)}catch(t){console.warn(`${t.message.trim()}
|
|
7
|
-
|
|
8
|
-
Context: ${e}`)}}async updateRun(t,e){y(t),e.inputs&&(e.inputs=this.processInputs(e.inputs)),e.outputs&&(e.outputs=this.processOutputs(e.outputs));let a={...e,id:t};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order)return void 0!==e.end_time&&void 0===a.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:a}).catch(console.error):void this.processRunOperation({action:"update",item:a}).catch(console.error);let i={...this.headers,"Content-Type":"application/json"},r=await this.caller.call(c(),`${this.apiUrl}/runs/${t}`,{method:"PATCH",headers:i,body:T(e),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,"update run",!0)}async readRun(t,{loadChildRuns:e}={loadChildRuns:!1}){y(t);let a=await this._get(`/runs/${t}`);return e&&a.child_run_ids&&(a=await this._loadChildRuns(a)),a}async getRunUrl({runId:t,run:e,projectOpts:a}){if(void 0!==e){let t;t=e.session_id?e.session_id:a?.projectName?(await this.readProject({projectName:a?.projectName})).id:a?.projectId?a?.projectId:(await this.readProject({projectName:G("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${t}/r/${e.id}?poll=true`}if(void 0!==t){let e=await this.readRun(t);if(!e.app_path)throw Error(`Run ${t} has no app_path`);let a=this.getHostUrl();return`${a}${e.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(t){let e=await x(this.listRuns({id:t.child_run_ids})),a={},i={};for(let t of(e.sort((t,e)=>(t?.dotted_order??"").localeCompare(e?.dotted_order??"")),e)){if(null===t.parent_run_id||void 0===t.parent_run_id)throw Error(`Child run ${t.id} has no parent`);t.parent_run_id in a||(a[t.parent_run_id]=[]),a[t.parent_run_id].push(t),i[t.id]=t}for(let e in t.child_runs=a[t.id]||[],a)e!==t.id&&(i[e].child_runs=a[e]);return t}async *listRuns(t){let{projectId:e,projectName:a,parentRunId:i,traceId:r,referenceExampleId:n,startTime:s,executionOrder:o,isRoot:l,runType:d,error:u,id:h,query:c,filter:p,traceFilter:m,treeFilter:f,limit:g,select:_}=t,b=[];if(e&&(b=Array.isArray(e)?e:[e]),a){let t=Array.isArray(a)?a:[a],e=await Promise.all(t.map(t=>this.readProject({projectName:t}).then(t=>t.id)));b.push(...e)}let y={session:b.length?b:null,run_type:d,reference_example:n,query:c,filter:p,trace_filter:m,tree_filter:f,execution_order:o,parent_run:i,start_time:s?s.toISOString():null,error:u,id:h,limit:g,trace:r,select:_||["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],is_root:l},w=0;for await(let t of this._getCursorPaginatedList("/runs/query",y))if(g){if(w>=g)break;if(t.length+w>g){let e=t.slice(0,g-w);yield*e;break}w+=t.length,yield*t}else yield*t}async getRunStats({id:t,trace:e,parentRun:a,runType:i,projectNames:r,projectIds:n,referenceExampleIds:s,startTime:o,endTime:l,error:d,query:u,filter:h,traceFilter:p,treeFilter:m,isRoot:f,dataSourceType:g}){let _=n||[];r&&(_=[...n||[],...await Promise.all(r.map(t=>this.readProject({projectName:t}).then(t=>t.id)))]);let b=Object.fromEntries(Object.entries({id:t,trace:e,parent_run:a,run_type:i,session:_,reference_example:s,start_time:o,end_time:l,error:d,query:u,filter:h,trace_filter:p,tree_filter:m,is_root:f,data_source_type:g}).filter(([t,e])=>void 0!==e)),y=await this.caller.call(c(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(b),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await y.json()}async shareRun(t,{shareId:e}={}){let a={run_id:t,share_token:e||o.Z()};y(t);let i=await this.caller.call(c(),`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await i.json();if(null===r||!("share_token"in r))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${r.share_token}/r`}async unshareRun(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(e,"unshare run",!0)}async readRunSharedLink(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await e.json();if(null!==a&&"share_token"in a)return`${this.getHostUrl()}/public/${a.share_token}/r`}async listSharedRuns(t,{runIds:e}={}){let a=new URLSearchParams({share_token:t});if(void 0!==e)for(let t of e)a.append("id",t);y(t);let i=await this.caller.call(c(),`${this.apiUrl}/public/${t}/runs${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await i.json()}async readDatasetSharedSchema(t,e){if(!t&&!e)throw Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:e})).id),y(t);let a=await this.caller.call(c(),`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await a.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(t,e){if(!t&&!e)throw Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:e})).id);let a={dataset_id:t};y(t);let i=await this.caller.call(c(),`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await i.json();return r.url=`${this.getHostUrl()}/public/${r.share_token}/d`,r}async unshareDataset(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(e,"unshare dataset",!0)}async readSharedDataset(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await e.json()}async listSharedExamples(t,e){let a={};e?.exampleIds&&(a.id=e.exampleIds);let i=new URLSearchParams;Object.entries(a).forEach(([t,e])=>{Array.isArray(e)?e.forEach(e=>i.append(t,e)):i.append(t,e)});let r=await this.caller.call(c(),`${this.apiUrl}/public/${t}/examples?${i.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();if(!r.ok){if("detail"in n)throw Error(`Failed to list shared examples.
|
|
9
|
-
Status: ${r.status}
|
|
10
|
-
Message: ${n.detail.join("\n")}`);throw Error(`Failed to list shared examples: ${r.status} ${r.statusText}`)}return n.map(t=>({...t,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:e=null,metadata:a=null,upsert:i=!1,projectExtra:r=null,referenceDatasetId:n=null}){let s=`${this.apiUrl}/sessions${i?"?upsert=true":""}`,o=r||{};a&&(o.metadata=a);let l={name:t,extra:o,description:e};null!==n&&(l.reference_dataset_id=n);let d=await this.caller.call(c(),s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(d,"create project"),await d.json()}async updateProject(t,{name:e=null,description:a=null,metadata:i=null,projectExtra:r=null,endTime:n=null}){let s=`${this.apiUrl}/sessions/${t}`,o=r;i&&(o={...o||{},metadata:i});let l={name:e,extra:o,description:a,end_time:n?new Date(n).toISOString():null},d=await this.caller.call(c(),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(d,"update project"),await d.json()}async hasProject({projectId:t,projectName:e}){let a="/sessions",i=new URLSearchParams;if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");if(void 0!==t)y(t),a+=`/${t}`;else if(void 0!==e)i.append("name",e);else throw Error("Must provide projectName or projectId");let r=await this.caller.call(c(),`${this.apiUrl}${a}?${i}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let t=await r.json();if(!r.ok)return!1;if(Array.isArray(t))return t.length>0;return!0}catch(t){return!1}}async readProject({projectId:t,projectName:e,includeStats:a}){let i,r="/sessions",n=new URLSearchParams;if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");if(void 0!==t)y(t),r+=`/${t}`;else if(void 0!==e)n.append("name",e);else throw Error("Must provide projectName or projectId");void 0!==a&&n.append("include_stats",a.toString());let s=await this._get(r,n);if(Array.isArray(s)){if(0===s.length)throw Error(`Project[id=${t}, name=${e}] not found`);i=s[0]}else i=s;return i}async getProjectUrl({projectId:t,projectName:e}){if(void 0===t&&void 0===e)throw Error("Must provide either projectName or projectId");let a=await this.readProject({projectId:t,projectName:e}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${a.id}`}async getDatasetUrl({datasetId:t,datasetName:e}){if(void 0===t&&void 0===e)throw Error("Must provide either datasetName or datasetId");let a=await this.readDataset({datasetId:t,datasetName:e}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${a.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let e of this._getPaginated("/sessions",t))return this._tenantId=e[0].tenant_id,e[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:t,name:e,nameContains:a,referenceDatasetId:i,referenceDatasetName:r,referenceFree:n,metadata:s}={}){let o=new URLSearchParams;if(void 0!==t)for(let e of t)o.append("id",e);if(void 0!==e&&o.append("name",e),void 0!==a&&o.append("name_contains",a),void 0!==i)o.append("reference_dataset",i);else if(void 0!==r){let t=await this.readDataset({datasetName:r});o.append("reference_dataset",t.id)}for await(let t of(void 0!==n&&o.append("reference_free",n.toString()),void 0!==s&&o.append("metadata",JSON.stringify(s)),this._getPaginated("/sessions",o)))yield*t}async deleteProject({projectId:t,projectName:e}){let a;if(void 0===t&&void 0===e)throw Error("Must provide projectName or projectId");if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");y(a=void 0===t?(await this.readProject({projectName:e})).id:t);let i=await this.caller.call(c(),`${this.apiUrl}/sessions/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(i,`delete session ${a} (${e})`,!0)}async uploadCsv({csvFile:t,fileName:e,inputKeys:a,outputKeys:i,description:r,dataType:n,name:s}){let o=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",t,e),a.forEach(t=>{l.append("input_keys",t)}),i.forEach(t=>{l.append("output_keys",t)}),r&&l.append("description",r),n&&l.append("data_type",n),s&&l.append("name",s);let d=await this.caller.call(c(),o,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(d,"upload CSV"),await d.json()}async createDataset(t,{description:e,dataType:a,inputsSchema:i,outputsSchema:r,metadata:n}={}){let s={name:t,description:e,extra:n?{metadata:n}:void 0};a&&(s.data_type=a),i&&(s.inputs_schema_definition=i),r&&(s.outputs_schema_definition=r);let o=await this.caller.call(c(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(o,"create dataset"),await o.json()}async readDataset({datasetId:t,datasetName:e}){let a,i="/datasets",r=new URLSearchParams({limit:"1"});if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t)y(t),i+=`/${t}`;else if(void 0!==e)r.append("name",e);else throw Error("Must provide datasetName or datasetId");let n=await this._get(i,r);if(Array.isArray(n)){if(0===n.length)throw Error(`Dataset[id=${t}, name=${e}] not found`);a=n[0]}else a=n;return a}async hasDataset({datasetId:t,datasetName:e}){try{return await this.readDataset({datasetId:t,datasetName:e}),!0}catch(t){if(t instanceof Error&&t.message.toLocaleLowerCase().includes("not found"))return!1;throw t}}async diffDatasetVersions({datasetId:t,datasetName:e,fromVersion:a,toVersion:i}){let r=t;if(void 0===r&&void 0===e)throw Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");void 0===r&&(r=(await this.readDataset({datasetName:e})).id);let n=new URLSearchParams({from_version:"string"==typeof a?a:a.toISOString(),to_version:"string"==typeof i?i:i.toISOString()});return await this._get(`/datasets/${r}/versions/diff`,n)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:e}){if(void 0!==t);else if(void 0!==e)t=(await this.readDataset({datasetName:e})).id;else throw Error("Must provide datasetName or datasetId");let a=await this._getResponse(`/datasets/${t}/openai_ft`);return(await a.text()).trim().split("\n").map(t=>JSON.parse(t))}async *listDatasets({limit:t=100,offset:e=0,datasetIds:a,datasetName:i,datasetNameContains:r,metadata:n}={}){let s=new URLSearchParams({limit:t.toString(),offset:e.toString()});if(void 0!==a)for(let t of a)s.append("id",t);for await(let t of(void 0!==i&&s.append("name",i),void 0!==r&&s.append("name_contains",r),void 0!==n&&s.append("metadata",JSON.stringify(n)),this._getPaginated("/datasets",s)))yield*t}async updateDataset(t){let{datasetId:e,datasetName:a,...i}=t;if(!e&&!a)throw Error("Must provide either datasetName or datasetId");let r=e??(await this.readDataset({datasetName:a})).id;y(r);let n=await this.caller.call(c(),`${this.apiUrl}/datasets/${r}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"update dataset"),await n.json()}async updateDatasetTag(t){let{datasetId:e,datasetName:a,asOf:i,tag:r}=t;if(!e&&!a)throw Error("Must provide either datasetName or datasetId");let n=e??(await this.readDataset({datasetName:a})).id;y(n);let s=await this.caller.call(c(),`${this.apiUrl}/datasets/${n}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:"string"==typeof i?i:i.toISOString(),tag:r}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(s,"update dataset tags")}async deleteDataset({datasetId:t,datasetName:e}){let a="/datasets",i=t;if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e&&(i=(await this.readDataset({datasetName:e})).id),void 0!==i)y(i),a+=`/${i}`;else throw Error("Must provide datasetName or datasetId");let r=await this.caller.call(c(),this.apiUrl+a,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,`delete ${a}`),await r.json()}async indexDataset({datasetId:t,datasetName:e,tag:a}){let i=t;if(i||e)if(i&&e)throw Error("Must provide either datasetName or datasetId, not both");else i||(i=(await this.readDataset({datasetName:e})).id);else throw Error("Must provide either datasetName or datasetId");y(i);let r=await this.caller.call(c(),`${this.apiUrl}/datasets/${i}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({tag:a}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,"index dataset"),await r.json()}async similarExamples(t,e,a,{filter:i}={}){let r={limit:a,inputs:t};void 0!==i&&(r.filter=i),y(e);let n=await this.caller.call(c(),`${this.apiUrl}/datasets/${e}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"fetch similar examples"),(await n.json()).examples}async createExample(t,e,{datasetId:a,datasetName:i,createdAt:r,exampleId:n,metadata:s,split:o,sourceRunId:l}){let d=a;if(void 0===d&&void 0===i)throw Error("Must provide either datasetName or datasetId");if(void 0!==d&&void 0!==i)throw Error("Must provide either datasetName or datasetId, not both");void 0===d&&(d=(await this.readDataset({datasetName:i})).id);let u=r||new Date,h={dataset_id:d,inputs:t,outputs:e,created_at:u?.toISOString(),id:n,metadata:s,split:o,source_run_id:l},p=await this.caller.call(c(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(h),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(p,"create example"),await p.json()}async createExamples(t){let{inputs:e,outputs:a,metadata:i,sourceRunIds:r,exampleIds:n,datasetId:s,datasetName:o}=t,l=s;if(void 0===l&&void 0===o)throw Error("Must provide either datasetName or datasetId");if(void 0!==l&&void 0!==o)throw Error("Must provide either datasetName or datasetId, not both");void 0===l&&(l=(await this.readDataset({datasetName:o})).id);let d=e.map((e,s)=>({dataset_id:l,inputs:e,outputs:a?a[s]:void 0,metadata:i?i[s]:void 0,split:t.splits?t.splits[s]:void 0,id:n?n[s]:void 0,source_run_id:r?r[s]:void 0})),u=await this.caller.call(c(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(u,"create examples"),await u.json()}async createLLMExample(t,e,a){return this.createExample({input:t},{output:e},a)}async createChatExample(t,e,a){let i=t.map(t=>g(t)?_(t):t),r=g(e)?_(e):e;return this.createExample({input:i},{output:r},a)}async readExample(t){y(t);let e=`/examples/${t}`,{attachment_urls:a,...i}=await this._get(e);return a&&(i.attachments=Object.entries(a).reduce((t,[e,a])=>(t[e.slice(11)]={presigned_url:a.presigned_url,mime_type:a.mime_type},t),{})),i}async *listExamples({datasetId:t,datasetName:e,exampleIds:a,asOf:i,splits:r,inlineS3Urls:n,metadata:s,limit:o,offset:l,filter:d,includeAttachments:u}={}){let h;if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t)h=t;else if(void 0!==e)h=(await this.readDataset({datasetName:e})).id;else throw Error("Must provide a datasetName or datasetId");let c=new URLSearchParams({dataset:h}),p=i?"string"==typeof i?i:i?.toISOString():void 0;if(p&&c.append("as_of",p),c.append("inline_s3_urls",(n??!0).toString()),void 0!==a)for(let t of a)c.append("id",t);if(void 0!==r)for(let t of r)c.append("splits",t);if(void 0!==s){let t=JSON.stringify(s);c.append("metadata",t)}void 0!==o&&c.append("limit",o.toString()),void 0!==l&&c.append("offset",l.toString()),void 0!==d&&c.append("filter",d),!0===u&&["attachment_urls","outputs","metadata"].forEach(t=>c.append("select",t));let m=0;for await(let t of this._getPaginated("/examples",c)){for(let e of t){let{attachment_urls:t,...a}=e;t&&(a.attachments=Object.entries(t).reduce((t,[e,a])=>(t[e.slice(11)]={presigned_url:a.presigned_url,mime_type:a.mime_type||void 0},t),{})),yield a,m++}if(void 0!==o&&m>=o)break}}async deleteExample(t){y(t);let e=`/examples/${t}`,a=await this.caller.call(c(),this.apiUrl+e,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,`delete ${e}`),await a.json()}async updateExample(t,e){y(t);let a=await this.caller.call(c(),`${this.apiUrl}/examples/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(a,"update example"),await a.json()}async updateExamples(t){let e=await this.caller.call(c(),`${this.apiUrl}/examples/bulk`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(e,"update examples"),await e.json()}async readDatasetVersion({datasetId:t,datasetName:e,asOf:a,tag:i}){let r;if(y(r=t||(await this.readDataset({datasetName:e})).id),a&&i||!a&&!i)throw Error("Exactly one of asOf and tag must be specified.");let n=new URLSearchParams;void 0!==a&&n.append("as_of","string"==typeof a?a:a.toISOString()),void 0!==i&&n.append("tag",i);let s=await this.caller.call(c(),`${this.apiUrl}/datasets/${r}/version?${n.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(s,"read dataset version"),await s.json()}async listDatasetSplits({datasetId:t,datasetName:e,asOf:a}){let i;if(void 0===t&&void 0===e)throw Error("Must provide dataset name or ID");if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");y(i=void 0===t?(await this.readDataset({datasetName:e})).id:t);let r=new URLSearchParams,n=a?"string"==typeof a?a:a?.toISOString():void 0;return n&&r.append("as_of",n),await this._get(`/datasets/${i}/splits`,r)}async updateDatasetSplits({datasetId:t,datasetName:e,splitName:a,exampleIds:i,remove:r=!1}){let n;if(void 0===t&&void 0===e)throw Error("Must provide dataset name or ID");if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");y(n=void 0===t?(await this.readDataset({datasetName:e})).id:t);let s={split_name:a,examples:i.map(t=>(y(t),t)),remove:r},o=await this.caller.call(c(),`${this.apiUrl}/datasets/${n}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(o,"update dataset splits",!0)}async evaluateRun(t,e,{sourceInfo:a,loadChildRuns:i,referenceExample:r}={loadChildRuns:!1}){let n;if(v("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof t)n=await this.readRun(t,{loadChildRuns:i});else if("object"==typeof t&&"id"in t)n=t;else throw Error(`Invalid run type: ${typeof t}`);null!==n.reference_example_id&&void 0!==n.reference_example_id&&(r=await this.readExample(n.reference_example_id));let s=await e.evaluateRun(n,r),[o,l]=await this._logEvaluationFeedback(s,n,a);return l[0]}async createFeedback(t,e,{score:a,value:i,correction:r,comment:n,sourceInfo:s,feedbackSourceType:l="api",sourceRunId:d,feedbackId:u,feedbackConfig:h,projectId:p,comparativeExperimentId:m}){if(!t&&!p)throw Error("One of runId or projectId must be provided");if(t&&p)throw Error("Only one of runId or projectId can be provided");let f={type:l??"api",metadata:s??{}};void 0===d||f?.metadata===void 0||f.metadata.__run||(f.metadata.__run={run_id:d}),f?.metadata!==void 0&&f.metadata.__run?.run_id!==void 0&&y(f.metadata.__run.run_id);let g={id:u??o.Z(),run_id:t,key:e,score:a,value:i,correction:r,comment:n,feedback_source:f,comparative_experiment_id:m,feedbackConfig:h,session_id:p},_=`${this.apiUrl}/feedback`,b=await this.caller.call(c(),_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(b,"create feedback",!0),g}async updateFeedback(t,{score:e,value:a,correction:i,comment:r}){let n={};null!=e&&(n.score=e),null!=a&&(n.value=a),null!=i&&(n.correction=i),null!=r&&(n.comment=r),y(t);let s=await this.caller.call(c(),`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(s,"update feedback",!0)}async readFeedback(t){y(t);let e=`/feedback/${t}`;return await this._get(e)}async deleteFeedback(t){y(t);let e=`/feedback/${t}`,a=await this.caller.call(c(),this.apiUrl+e,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,`delete ${e}`),await a.json()}async *listFeedback({runIds:t,feedbackKeys:e,feedbackSourceTypes:a}={}){let i=new URLSearchParams;if(t&&i.append("run",t.join(",")),e)for(let t of e)i.append("key",t);if(a)for(let t of a)i.append("source",t);for await(let t of this._getPaginated("/feedback",i))yield*t}async createPresignedFeedbackToken(t,e,{expiration:a,feedbackConfig:i}={}){let r={run_id:t,feedback_key:e,feedback_config:i};a?"string"==typeof a?r.expires_at=a:(a?.hours||a?.minutes||a?.days)&&(r.expires_in=a):r.expires_in={hours:3};let n=await this.caller.call(c(),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async createComparativeExperiment({name:t,experimentIds:e,referenceDatasetId:a,createdAt:i,description:r,metadata:n,id:s}){if(0===e.length)throw Error("At least one experiment is required");if(a||(a=(await this.readProject({projectId:e[0]})).reference_dataset_id),null==!a)throw Error("A reference dataset is required");let o={id:s,name:t,experiment_ids:e,reference_dataset_id:a,description:r,created_at:(i??new Date)?.toISOString(),extra:{}};n&&(o.extra.metadata=n);let l=await this.caller.call(c(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await l.json()}async *listPresignedFeedbackTokens(t){y(t);let e=new URLSearchParams({run_id:t});for await(let t of this._getPaginated("/feedback/tokens",e))yield*t}_selectEvalResults(t){return"results"in t?t.results:[t]}async _logEvaluationFeedback(t,e,a){let i=this._selectEvalResults(t),r=[];for(let t of i){let i=a||{};t.evaluatorInfo&&(i={...t.evaluatorInfo,...i});let n=null;t.targetRunId?n=t.targetRunId:e&&(n=e.id),r.push(await this.createFeedback(n,t.key,{score:t.score,value:t.value,comment:t.comment,correction:t.correction,sourceInfo:i,sourceRunId:t.sourceRunId,feedbackConfig:t.feedbackConfig,feedbackSourceType:"model"}))}return[i,r]}async logEvaluationFeedback(t,e,a){let[i]=await this._logEvaluationFeedback(t,e,a);return i}async *listAnnotationQueues(t={}){let{queueIds:e,name:a,nameContains:i,limit:r}=t,n=new URLSearchParams;e&&e.forEach((t,e)=>{y(t,`queueIds[${e}]`),n.append("ids",t)}),a&&n.append("name",a),i&&n.append("name_contains",i),n.append("limit",(void 0!==r?Math.min(r,100):100).toString());let s=0;for await(let t of this._getPaginated("/annotation-queues",n))if(yield*t,s++,void 0!==r&&s>=r)break}async createAnnotationQueue(t){let{name:e,description:a,queueId:i}=t,r={name:e,description:a,id:i||o.Z()},n=await this.caller.call(c(),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(r).filter(([t,e])=>void 0!==e))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"create annotation queue"),await n.json()}async readAnnotationQueue(t){let e=await this.listAnnotationQueues({queueIds:[t]}).next();if(e.done)throw Error(`Annotation queue with ID ${t} not found`);return e.value}async updateAnnotationQueue(t,e){let{name:a,description:i}=e,r=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:a,description:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,"update annotation queue")}async deleteAnnotationQueue(t){let e=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(e,"delete annotation queue")}async addRunsToAnnotationQueue(t,e){let a=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(e.map((t,e)=>y(t,`runIds[${e}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,"add runs to annotation queue")}async getRunFromAnnotationQueue(t,e){let a=`/annotation-queues/${y(t,"queueId")}/run`,i=await this.caller.call(c(),`${this.apiUrl}${a}/${e}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(i,"get run from annotation queue"),await i.json()}async deleteRunFromAnnotationQueue(t,e){let a=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}/runs/${y(e,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,"delete run from annotation queue")}async getSizeFromAnnotationQueue(t){let e=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(e,"get size from annotation queue"),await e.json()}async _currentTenantIsOwner(t){let e=await this._getSettings();return"-"==t||e.tenant_handle===t}async _ownerConflictError(t,e){let a=await this._getSettings();return Error(`Cannot ${t} for another tenant.
|
|
11
|
-
|
|
12
|
-
Current tenant: ${a.tenant_handle}
|
|
13
|
-
|
|
14
|
-
Requested tenant: ${e}`)}async _getLatestCommitHash(t){let e=await this.caller.call(c(),`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await e.json();if(!e.ok){let t="string"==typeof a.detail?a.detail:JSON.stringify(a.detail),i=Error(`Error ${e.status}: ${e.statusText}
|
|
15
|
-
${t}`);throw i.statusCode=e.status,i}if(0!==a.commits.length)return a.commits[0].commit_hash}async _likeOrUnlikePrompt(t,e){let[a,i,r]=O(t),n=await this.caller.call(c(),`${this.apiUrl}/likes/${a}/${i}`,{method:"POST",body:JSON.stringify({like:e}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,`${e?"like":"unlike"} prompt`),await n.json()}async _getPromptUrl(t){let[e,a,i]=O(t);if(await this._currentTenantIsOwner(e)){let t=await this._getSettings();return"latest"!==i?`${this.getHostUrl()}/prompts/${a}/${i.substring(0,8)}?organizationId=${t.id}`:`${this.getHostUrl()}/prompts/${a}?organizationId=${t.id}`}return"latest"!==i?`${this.getHostUrl()}/hub/${e}/${a}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${e}/${a}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async *listCommits(t){for await(let e of this._getPaginated(`/commits/${t}/`,new URLSearchParams,t=>t.commits))yield*e}async *listPrompts(t){let e=new URLSearchParams;for await(let a of(e.append("sort_field",t?.sortField??"updated_at"),e.append("sort_direction","desc"),e.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&e.append("is_public",t.isPublic.toString()),t?.query&&e.append("query",t.query),this._getPaginated("/repos",e,t=>t.repos)))yield*a}async getPrompt(t){let[e,a,i]=O(t),r=await this.caller.call(c(),`${this.apiUrl}/repos/${e}/${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===r.status)return null;await j(r,"get prompt");let n=await r.json();return n.repo?n.repo:null}async createPrompt(t,e){let a=await this._getSettings();if(e?.isPublic&&!a.tenant_handle)throw Error(`Cannot create a public prompt without first
|
|
16
|
-
|
|
17
|
-
creating a LangChain Hub handle.
|
|
18
|
-
You can add a handle by creating a public prompt at:
|
|
19
|
-
|
|
20
|
-
https://smith.langchain.com/prompts`);let[i,r,n]=O(t);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let s={repo_handle:r,...e?.description&&{description:e.description},...e?.readme&&{readme:e.readme},...e?.tags&&{tags:e.tags},is_public:!!e?.isPublic},o=await this.caller.call(c(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(o,"create prompt");let{repo:l}=await o.json();return l}async createCommit(t,e,a){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[i,r,n]=O(t),s=a?.parentCommitHash!=="latest"&&a?.parentCommitHash?a?.parentCommitHash:await this._getLatestCommitHash(`${i}/${r}`),o={manifest:JSON.parse(JSON.stringify(e)),parent_commit:s},l=await this.caller.call(c(),`${this.apiUrl}/commits/${i}/${r}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(l,"create commit");let d=await l.json();return this._getPromptUrl(`${i}/${r}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(t,e=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let a=new FormData;for(let t of e){let e=t.id,i=new Blob([T({...t.metadata&&{metadata:t.metadata},...t.split&&{split:t.split}})],{type:"application/json"});if(a.append(e,i),t.inputs){let i=new Blob([T(t.inputs)],{type:"application/json"});a.append(`${e}.inputs`,i)}if(t.outputs){let i=new Blob([T(t.outputs)],{type:"application/json"});a.append(`${e}.outputs`,i)}if(t.attachments)for(let[i,r]of Object.entries(t.attachments)){let t,n;Array.isArray(r)?[t,n]=r:(t=r.mimeType,n=r.data);let s=new Blob([n],{type:`${t}; length=${n.byteLength}`});a.append(`${e}.attachment.${i}`,s)}if(t.attachments_operations){let i=new Blob([T(t.attachments_operations)],{type:"application/json"});a.append(`${e}.attachments_operations`,i)}}let i=await this.caller.call(c(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"PATCH",headers:this.headers,body:a});return await i.json()}async uploadExamplesMultipart(t,e=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let a=new FormData;for(let t of e){let e=(t.id??o.Z()).toString(),i=new Blob([T({created_at:t.created_at,...t.metadata&&{metadata:t.metadata},...t.split&&{split:t.split}})],{type:"application/json"});a.append(e,i);let r=new Blob([T(t.inputs)],{type:"application/json"});if(a.append(`${e}.inputs`,r),t.outputs){let i=new Blob([T(t.outputs)],{type:"application/json"});a.append(`${e}.outputs`,i)}if(t.attachments)for(let[i,r]of Object.entries(t.attachments)){let t,n;Array.isArray(r)?[t,n]=r:(t=r.mimeType,n=r.data);let s=new Blob([n],{type:`${t}; length=${n.byteLength}`});a.append(`${e}.attachment.${i}`,s)}}let i=await this.caller.call(c(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"POST",headers:this.headers,body:a});return await i.json()}async updatePrompt(t,e){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[a,i]=O(t);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("update a prompt",a);let r={};if(e?.description!==void 0&&(r.description=e.description),e?.readme!==void 0&&(r.readme=e.readme),e?.tags!==void 0&&(r.tags=e.tags),e?.isPublic!==void 0&&(r.is_public=e.isPublic),e?.isArchived!==void 0&&(r.is_archived=e.isArchived),0===Object.keys(r).length)throw Error("No valid update options provided");let n=await this.caller.call(c(),`${this.apiUrl}/repos/${a}/${i}`,{method:"PATCH",body:JSON.stringify(r),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"update prompt"),n.json()}async deletePrompt(t){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[e,a,i]=O(t);if(!await this._currentTenantIsOwner(e))throw await this._ownerConflictError("delete a prompt",e);let r=await this.caller.call(c(),`${this.apiUrl}/repos/${e}/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r.json()}async pullPromptCommit(t,e){let[a,i,r]=O(t),n=await this.caller.call(c(),`${this.apiUrl}/commits/${a}/${i}/${r}${e?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(n,"pull prompt commit");let s=await n.json();return{owner:a,repo:i,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples}}async _pullPrompt(t,e){return JSON.stringify((await this.pullPromptCommit(t,{includeModel:e?.includeModel})).manifest)}async pushPrompt(t,e){return(await this.promptExists(t)?e&&Object.keys(e).some(t=>"object"!==t)&&await this.updatePrompt(t,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}):await this.createPrompt(t,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}),e?.object)?await this.createCommit(t,e?.object,{parentCommitHash:e?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,e={}){let{sourceApiUrl:a=this.apiUrl,datasetName:i}=e,[r,n]=this.parseTokenOrUrl(t,a),s=new L({apiUrl:r,apiKey:"placeholder"}),o=await s.readSharedDataset(n),l=i||o.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(t){}let d=await s.listSharedExamples(n),u=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(t=>t.inputs),outputs:d.flatMap(t=>t.outputs?[t.outputs]:[]),datasetId:u.id})}catch(t){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),t}}parseTokenOrUrl(t,e,a=2,i="dataset"){try{return y(t),[e,t]}catch(t){}try{let r=new URL(t).pathname.split("/").filter(t=>""!==t);if(r.length>=a){let t=r[r.length-a];return[e,t]}throw Error(`Invalid public ${i} URL: ${t}`)}catch(e){throw Error(`Invalid public ${i} URL or token: ${t}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()])}}let M="0.3.7";var D=a(73656);function B(){return void 0===r&&(r={library:"langsmith",runtime:i||(i="undefined"!=typeof window&&void 0!==window.document?"browser":void 0===D||void 0===D.versions||void 0===D.versions.node||"undefined"!=typeof Deno?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":"undefined"!=typeof Deno?"deno":"other":"node"),sdk:"langsmith-js",sdk_version:M,...function(){if(void 0!==n)return n;let t={};for(let e of["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"]){let a=H(e);void 0!==a&&(t[e]=a)}return n=t,t}()}),r}function H(t){try{return void 0!==D?D.env?.[t]:void 0}catch(t){return}}function G(t){return H(`LANGSMITH_${t}`)||H(`LANGCHAIN_${t}`)}let F=t=>void 0!==t?t:!!["TRACING_V2","TRACING"].find(t=>"true"===G(t)),J=Symbol.for("lc:context_variables");class q{constructor(t,e){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=t,this.tags=e}static fromHeader(t){let e=t.split(","),a={},i=[];for(let t of e){let[e,r]=t.split("="),n=decodeURIComponent(r);"langsmith-metadata"===e?a=JSON.parse(n):"langsmith-tags"===e&&(i=n.split(","))}return new q(a,i)}toHeader(){let t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),t.join(",")}}class z{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Q(t))return void Object.assign(this,{...t});let e=z.getDefaultConfig(),{metadata:a,...i}=t,r=i.client??z.getSharedClient(),n={...a,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:n},Object.assign(this,{...e,...i,client:r}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let t=function(t,e,a=1){let i=a.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${i}Z`.replace(/[-:.]/g,"")+e}(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+t:this.dotted_order=t}}static getDefaultConfig(){return{id:o.Z(),run_type:"chain",project_name:G("PROJECT")??H("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:H("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:H("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return z.sharedClient||(z.sharedClient=new L),z.sharedClient}createChild(t){let e=this.child_execution_order+1,a=new z({...t,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:e,child_execution_order:e});J in this&&(a[J]=this[J]);let i=Symbol.for("lc:child_config"),r=t.extra?.[i]??this.extra[i];if(V(r)){var n;let t={...r},e="object"==typeof(n=t.callbacks)&&null!=n&&Array.isArray(n.handlers)?t.callbacks.copy?.():void 0;e&&(Object.assign(e,{_parentRunId:a.id}),e.handlers?.find(W)?.updateFromRunTree?.(a),t.callbacks=e),a.extra[i]=t}let s=new Set,o=this;for(;null!=o&&!s.has(o.id);)s.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,e),o=o.parent_run;return this.child_runs.push(a),a}async end(t,e,a=Date.now(),i){this.outputs=this.outputs??t,this.error=this.error??e,this.end_time=this.end_time??a,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(t,e,a=!0){let i,r,n=t.extra??{};if(n.runtime||(n.runtime={}),e)for(let[t,a]of Object.entries(e))n.runtime[t]||(n.runtime[t]=a);return a?(r=t.parent_run?.id,i=[]):(i=t.child_runs.map(t=>this._convertToCreate(t,e,a)),r=void 0),{id:t.id,name:t.name,start_time:t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:n,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:i,parent_run_id:r,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments}}async postRun(t=!0){try{let e=B(),a=await this._convertToCreate(this,e,!0);if(await this.client.createRun(a),!t)for(let t of(v("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await t.postRun(!1)}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(){try{let t={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_id:this.parent_run?.id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments};await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}toJSON(){return this._convertToCreate(this,void 0,!1)}static fromRunnableConfig(t,e){let a,i,r,n=t?.callbacks,s=F();if(n){let t=n?.getParentRunId?.()??"",e=n?.handlers?.find(t=>t?.name=="langchain_tracer");a=e?.getRun?.(t),i=e?.projectName,r=e?.client,s=s||!!e}return a?new z({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:r,tracingEnabled:s,project_name:i,tags:[...new Set((a?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...t?.metadata}}}).createChild(e):new z({...e,client:r,tracingEnabled:s,project_name:i})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,e){let a="get"in t&&"function"==typeof t.get?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,i=a["langsmith-trace"];if(!i||"string"!=typeof i)return;let r=i.trim(),n=r.split(".").map(t=>{let[e,a]=t.split("Z");return{strTime:e,time:Date.parse(e+"Z"),uuid:a}}),s=n[0].uuid,o={...e,name:e?.name??"parent",run_type:e?.run_type??"chain",start_time:e?.start_time??Date.now(),id:n.at(-1)?.uuid,trace_id:s,dotted_order:r};if(a.baggage&&"string"==typeof a.baggage){let t=q.fromHeader(a.baggage);o.metadata=t.metadata,o.tags=t.tags}return new z(o)}toHeaders(t){let e={"langsmith-trace":this.dotted_order,baggage:new q(this.extra?.metadata,this.tags).toHeader()};if(t)for(let[a,i]of Object.entries(e))t.set(a,i);return e}}function Q(t){return void 0!==t&&"function"==typeof t.createChild&&"function"==typeof t.postRun}function W(t){return"object"==typeof t&&null!=t&&"string"==typeof t.name&&"langchain_tracer"===t.name}function K(t){return Array.isArray(t)&&t.some(t=>W(t))}function V(t){return void 0!==t&&"object"==typeof t.callbacks&&(K(t.callbacks?.handlers)||K(t.callbacks))}Object.defineProperty(z,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});let Z=Symbol.for("ls:tracing_async_local_storage"),Y=new class{getStore(){}run(t,e){return e()}},X=new class{getInstance(){return globalThis[Z]??Y}initializeGlobalInstance(t){void 0===globalThis[Z]&&(globalThis[Z]=t)}},tt=Symbol.for("langsmith:traceable:root");function te(t){return"function"==typeof t&&"langsmith:traceable"in t}function ta(t){if("object"!=typeof t||null==t)return!1;let e=Object.getPrototypeOf(t);return(null===e||e===Object.prototype||null===Object.getPrototypeOf(e))&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}let ti=t=>null!=t&&"object"==typeof t&&"function"==typeof t[Symbol.asyncIterator],tr=t=>null!=t&&"object"==typeof t&&"next"in t&&"function"==typeof t.next,tn=(function*(){}).constructor,ts=t=>null!=t&&"object"==typeof t&&"getReader"in t&&"function"==typeof t.getReader;X.initializeGlobalInstance(new s.A);let to=(t,e)=>{let a;a=ta(t)?t:{outputs:t};try{return e(a)}catch(t){return console.error("Error occurred during processOutputs. Sending raw outputs:",t),a}},tl=(t,e,a,i,r)=>{if(!F(t.tracingEnabled))return;let[n,s]=((t,e)=>{if(!e)return[void 0,t];try{let[a,i]=e(...t);return[a,i]}catch(e){return console.error("Error occurred during extractAttachments:",e),[void 0,t]}})(e,r);t.attachments=n,t.inputs=((t,e)=>{try{return e(t)}catch(e){return console.error("Error occurred during processInputs. Sending raw inputs:",e),t}})(s,i);let o=a?.(...e);return null!=o&&(t.extra??={},t.extra.metadata={...o,...t.extra.metadata}),t},td=t=>{let e={current:void 0};return new Proxy(t,{get(a,i,r){if("then"===i){let a=t[i].bind(t);return(t,i=t=>{throw t})=>a(a=>(e.current=["resolve",a],t(a)),t=>(e.current=["reject",t],i(t)))}if("catch"===i){let a=t[i].bind(t);return t=>a(a=>(e.current=["reject",a],t(a)))}return"toJSON"===i?()=>{if(!e.current)return;let[t,a]=e.current??[];return"resolve"===t?a:{error:a}}:Reflect.get(a,i,r)}})},tu=t=>{if(ts(t)){let e=[],a=new TransformStream({start:()=>void 0,transform:(t,a)=>{e.push(t),a.enqueue(t)},flush:()=>void 0}),i=t.pipeThrough(a);return Object.assign(i,{toJSON:()=>e}),i}if(ti(t)){let e=[];return new Proxy(t,{get:(a,i,r)=>i===Symbol.asyncIterator?()=>{let a=t[Symbol.asyncIterator].bind(t)();return new Proxy(a,{get(t,i,r){if("next"===i||"return"===i||"throw"===i){let t=a.next.bind(a);return(...a)=>{let i=td(t(...a));return e.push(i),i}}return"return"===i||"throw"===i?a.next.bind(a):Reflect.get(t,i,r)}})}:"toJSON"===i?()=>e.map(t=>t.toJSON()).reduce((t,e)=>(e?.value&&t.push(e.value),t),[]):Reflect.get(a,i,r)})}if(!Array.isArray(t)&&tr(t)){let e=[];return new Proxy(t,{get(a,i,r){if("next"===i||"return"===i||"throw"===i){let a=t[i]?.bind(t);return(...t)=>{let i=a?.(...t);return null!=i&&e.push(i),i}}return"toJSON"===i?()=>e.reduce((t,e)=>(e.value&&t.push(e.value),t),[]):Reflect.get(a,i,r)}})}return null!=t&&"object"==typeof t&&"then"in t&&"function"==typeof t.then?td(t):t};function th(t,e){let{aggregator:a,argsConfigPath:i,__finalTracedIteratorKey:r,processInputs:n,processOutputs:o,extractAttachments:l,...d}=e??{},u=n??(t=>t),h=o??(t=>t),c=l??((...t)=>[void 0,(t=>{let e=t[0];return null==e?{}:t.length>1?{args:t}:ta(e)?e:{input:e}})(t)]),p=(...n)=>{let o;try{let e;if(i){let[t,a]=i;if(t!==n.length-1||a){if(t<=n.length&&"object"==typeof n[t]&&null!==n[t])if(a){let{[a]:i,...r}=n[t];e=i,n[t]=r}else e=n[t],n.splice(t,1)}else e=n.pop()}o={name:t.name||"<lambda>",...d,...e,tags:[...new Set([...d?.tags??[],...e?.tags??[]])],metadata:{...d?.metadata,...e?.metadata}}}catch(e){console.warn(`Failed to extract runtime config from args for ${d?.name??t.name}`,e),o={name:t.name||"<lambda>",...d}}let l=X.getInstance();for(let t=0;t<n.length;t++)n[t]=tu(n[t]);let[p,m]=(()=>{let[t,...a]=n;if(V(t))return[tl(z.fromRunnableConfig(t,o),a,e?.getInvocationParams,u,c),a];if(Q(t)&&"callbackManager"in t&&null!=t.callbackManager)return[t,a];if(t===tt||Q(t)){let i=tl(t===tt?new z(o):t.createChild(o),a,e?.getInvocationParams,u,c);return[i,[i,...a]]}let i=l.getStore();if(Q(i))return[tl(i.createChild(o),n,e?.getInvocationParams,u,c),n];let r=tl(new z(o),n,e?.getInvocationParams,u,c);return void 0!==i&&J in i&&(r[J]=i[J]),[r,n]})();return l.run(p,()=>{let i,n=p?.postRun();async function o(t){if(void 0!==a)try{return await a(t)}catch(t){console.error("[ERROR]: LangSmith aggregation failed: ",t)}return t}async function*l(t,e){let a=!1,i=[];try{for(;;){let{value:r,done:n}=await (e?e(()=>t.next()):t.next());if(n){a=!0;break}i.push(r),yield r}}catch(t){throw await p?.end(void 0,String(t)),t}finally{a||await p?.end(void 0,"Cancelled"),await p?.end(to(await o(i),h)),await u()}}function d(t,e){if(ts(t)){let a=t.getReader(),i=!1,r=[];return new ReadableStream({async start(t){for(;;){let n=await (e?e(()=>a.read()):a.read());if(n.done){i=!0,await p?.end(to(await o(r),h)),await u(),t.close();break}r.push(n.value),t.enqueue(n.value)}},cancel:async t=>(i||await p?.end(void 0,"Cancelled"),await p?.end(to(await o(r),h)),await u(),a.cancel(t))})}let a=l(t[Symbol.asyncIterator](),e);return t[Symbol.asyncIterator]=()=>a,t}async function u(){let t=e?.on_end;t&&(p?t(p):console.warn("Can not call 'on_end' if currentRunTree is undefined")),await n,await p?.patchRun()}try{i=t(...m)}catch(t){i=Promise.reject(t)}if(ti(i)){let t=s.A.snapshot();return d(i,t)}if(!Array.isArray(i)&&"object"==typeof i&&null!=i&&void 0!==r&&ti(i[r])){let t=s.A.snapshot();return{...i,[r]:d(i[r],t)}}let c=new Promise((e,a)=>{Promise.resolve(i).then(async a=>{if(ti(a))return e(d(a,s.A.snapshot()));if(!Array.isArray(a)&&"object"==typeof a&&null!=a&&void 0!==r&&ti(a[r])){let t=s.A.snapshot();return{...a,[r]:d(a[r],t)}}if(null!=t&&"function"==typeof t&&t instanceof tn&&tr(a)){let t=function(t){let e=[];for(;;){let a=t.next();if(e.push(a),a.done)break}return e}(a);try{await p?.end(to(await o(t.reduce((t,{value:e,done:a})=>(a&&void 0===e||t.push(e),t),[])),h)),await u()}catch(t){console.error("Error occurred during handleEnd:",t)}return function*(){for(let e of t){if(e.done)return e.value;yield e.value}}()}try{await p?.end(to(a,h)),await u()}finally{return a}},async t=>{throw await p?.end(void 0,String(t)),await u(),t}).then(e,a)});return"object"!=typeof i||null===i?c:new Proxy(i,{get:(t,e,a)=>"then"===e||"catch"===e||"finally"===e?c[e].bind(c):Reflect.get(t,e,a)})})};return Object.defineProperty(p,"langsmith:traceable",{value:d}),p}let tc=t=>{if(!t||0===t.length)return{choices:[{message:{role:"assistant",content:""}}]};let e={};for(let a of t)for(let t of a.choices)void 0===e[t.index]&&(e[t.index]=[]),e[t.index].push(t);let a=t[t.length-1];return a.choices=Object.values(e).map(t=>(function(t){let e=t.slice().reverse(),a={role:"assistant",content:""};for(let t of e)if(t.delta.role){a.role=t.delta.role;break}let i={};for(let e of t)if(e.delta.content&&(a.content=a.content.concat(e.delta.content)),e.delta.function_call&&(a.function_call||(a.function_call={name:"",arguments:""}),e.delta.function_call.name&&(a.function_call.name+=e.delta.function_call.name),e.delta.function_call.arguments&&(a.function_call.arguments+=e.delta.function_call.arguments)),e.delta.tool_calls)for(let t of e.delta.tool_calls)i[e.index]||(i[e.index]=[]),i[e.index].push(t);if(Object.keys(i).length>0)for(let[t,e]of(a.tool_calls=[...Array(Object.keys(i).length)],Object.entries(i))){let i=parseInt(t);for(let t of(a.tool_calls[i]={index:i,id:e.find(t=>t.id)?.id||null,type:e.find(t=>t.type)?.type||null},e))t.function&&(a.tool_calls[i].function||(a.tool_calls[i].function={name:"",arguments:""}),t.function.name&&(a.tool_calls[i].function.name+=t.function.name),t.function.arguments&&(a.tool_calls[i].function.arguments+=t.function.arguments))}return{index:t[0].index,finish_reason:e.find(t=>t.finish_reason)||null,message:a}})(t)),a},tp=t=>{if(0===t.length)return{choices:[{text:""}]};let e=[];for(let a of t){let t=a.choices[0].text;null!=t&&e.push(t)}let a=e.join(""),i=t[t.length-1];return i.choices=[{...i.choices[0],text:a}],i};function tm(t){let e={...t},a=t.usage;if(a){let t={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},i={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}};e.usage_metadata={input_tokens:a.prompt_tokens??0,output_tokens:a.completion_tokens??0,total_tokens:a.total_tokens??0,...Object.keys(t).length>0&&{input_token_details:t},...Object.keys(i).length>0&&{output_token_details:i}}}return delete e.usage,e}let tf=(t,e)=>{if(te(t.chat.completions.create)||te(t.completions.create))throw Error("This instance of OpenAI client has been already wrapped once.");let a={...t};return t.beta&&t.beta.chat&&t.beta.chat.completions&&"function"==typeof t.beta.chat.completions.parse&&(a.beta={...t.beta,chat:{...t.beta.chat,completions:{...t.beta.chat.completions,parse:th(t.beta.chat.completions.parse.bind(t.beta.chat.completions),{name:"ChatOpenAI",run_type:"llm",aggregator:tc,argsConfigPath:[1,"langsmithExtra"],getInvocationParams:t=>{if("object"!=typeof t||null==t)return;let e=("string"==typeof t.stop?[t.stop]:t.stop)??void 0;return{ls_provider:"openai",ls_model_type:"chat",ls_model_name:t.model,ls_max_tokens:t.max_tokens??void 0,ls_temperature:t.temperature??void 0,ls_stop:e}},...e})}}}),a.chat={...t.chat,completions:{...t.chat.completions,create:th(t.chat.completions.create.bind(t.chat.completions),{name:"ChatOpenAI",run_type:"llm",aggregator:tc,argsConfigPath:[1,"langsmithExtra"],getInvocationParams:t=>{if("object"!=typeof t||null==t)return;let e=("string"==typeof t.stop?[t.stop]:t.stop)??void 0;return{ls_provider:"openai",ls_model_type:"chat",ls_model_name:t.model,ls_max_tokens:t.max_tokens??void 0,ls_temperature:t.temperature??void 0,ls_stop:e}},processOutputs:tm,...e})}},a.completions={...t.completions,create:th(t.completions.create.bind(t.completions),{name:"OpenAI",run_type:"llm",aggregator:tp,argsConfigPath:[1,"langsmithExtra"],getInvocationParams:t=>{if("object"!=typeof t||null==t)return;let e=("string"==typeof t.stop?[t.stop]:t.stop)??void 0;return{ls_provider:"openai",ls_model_type:"llm",ls_model_name:t.model,ls_max_tokens:t.max_tokens??void 0,ls_temperature:t.temperature??void 0,ls_stop:e}},...e})},a}}}]);
|
|
21
|
-
//# sourceMappingURL=290.dd04c2bc.js.map
|