@midscene/android-playground 0.28.2 → 0.28.3-beta-20250910131004.0
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/bin/android-playground +1 -1
- package/dist/es/{index.mjs → bin.mjs} +66 -5
- package/dist/lib/{index.js → bin.js} +67 -5
- package/package.json +7 -5
- package/static/index.html +1 -1
- package/static/static/css/index.4f36ca8d.css +2 -0
- package/static/static/css/index.4f36ca8d.css.map +1 -0
- package/static/static/js/{763.40f17c2d.js → 848.f776e552.js} +73 -58
- package/static/static/js/{763.40f17c2d.js.LICENSE.txt → 848.f776e552.js.LICENSE.txt} +19 -1
- package/static/static/js/{763.40f17c2d.js.map → 848.f776e552.js.map} +1 -1
- package/static/static/js/async/{290.45247363.js → 290.375060b2.js} +2 -2
- package/static/static/js/async/{290.45247363.js.map → 290.375060b2.js.map} +1 -1
- package/static/static/js/async/920.48d269c8.js +2 -0
- package/static/static/js/async/920.48d269c8.js.map +1 -0
- package/static/static/js/index.516c1128.js +21 -0
- package/static/static/js/index.516c1128.js.map +1 -0
- package/static/static/css/index.f652fe09.css +0 -2
- package/static/static/css/index.f652fe09.css.map +0 -1
- package/static/static/js/async/975.693266d2.js +0 -2
- package/static/static/js/async/975.693266d2.js.map +0 -1
- package/static/static/js/index.6da6e8c8.js +0 -15
- package/static/static/js/index.6da6e8c8.js.map +0 -1
- /package/dist/types/{index.d.ts → bin.d.ts} +0 -0
- /package/static/static/js/{index.6da6e8c8.js.LICENSE.txt → index.516c1128.js.LICENSE.txt} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";(self.webpackChunkandroid_playground=self.webpackChunkandroid_playground||[]).push([["290"],{19042:function(t,e,a){let i,r,n;a.d(e,{wrapOpenAI:()=>tE});var s=a(7752),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=W(),a=function(){let t=function(){try{if(void 0!==H&&H.env)return Object.entries(H.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}let x=()=>{let t=V("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},R=t=>{let e=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===e||"127.0.0.1"===e||"::1"===e};async function k(t){let e=[];for await(let a of t)e.push(a);return e}function N(t){if(void 0!==t)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let L=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 M{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 D{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 M}),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"===K("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=D.getDefaultClientConfig();if(this.tracingSampleRate=x(),this.apiUrl=N(t.apiUrl??e.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=N(t.apiKey??e.apiKey),this.webUrl=N(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:L}),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=V("API_KEY"),e=V("ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:e,apiKey:t,webUrl:void 0,hideInputs:"true"===V("HIDE_INPUTS"),hideOutputs:"true"===V("HIDE_OUTPUTS")}}getHostUrl(){if(this.webUrl)return this.webUrl;if(R(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/${B}`};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
|
|
1
|
+
"use strict";(self.webpackChunkandroid_playground=self.webpackChunkandroid_playground||[]).push([["290"],{19042:function(t,e,a){let i,r,n;a.d(e,{wrapOpenAI:()=>tE});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=W(),a=function(){let t=function(){try{if(void 0!==H&&H.env)return Object.entries(H.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}let x=()=>{let t=V("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},R=t=>{let e=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===e||"127.0.0.1"===e||"::1"===e};async function k(t){let e=[];for await(let a of t)e.push(a);return e}function N(t){if(void 0!==t)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let L=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 M{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 D{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 M}),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"===K("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=D.getDefaultClientConfig();if(this.tracingSampleRate=x(),this.apiUrl=N(t.apiUrl??e.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=N(t.apiKey??e.apiKey),this.webUrl=N(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:L}),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=V("API_KEY"),e=V("ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:e,apiKey:t,webUrl:void 0,hideInputs:"true"===V("HIDE_INPUTS"),hideOutputs:"true"===V("HIDE_OUTPUTS")}}getHostUrl(){if(this.webUrl)return this.webUrl;if(R(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/${B}`};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
2
|
`])),a.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
|
|
3
3
|
`,`Content-Type: ${i.payload.type}\r
|
|
4
4
|
\r
|
|
@@ -18,4 +18,4 @@ ${t}`);throw i.statusCode=e.status,i}if(0!==a.commits.length)return a.commits[0]
|
|
|
18
18
|
You can add a handle by creating a public prompt at:
|
|
19
19
|
|
|
20
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 D({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 B="0.3.7";var H=a(73656);let G=()=>"undefined"!=typeof window&&void 0!==window.document,F=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,J=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),q=()=>"undefined"!=typeof Deno,z=()=>void 0!==H&&void 0!==H.versions&&void 0!==H.versions.node&&!q(),Q=()=>i||(i=G()?"browser":z()?"node":F()?"webworker":J()?"jsdom":q()?"deno":"other");function W(){return void 0===r&&(r={library:"langsmith",runtime:Q(),sdk:"langsmith-js",sdk_version:B,...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=K(e);void 0!==a&&(t[e]=a)}return n=t,t}()}),r}function K(t){try{return void 0!==H?H.env?.[t]:void 0}catch(t){return}}function V(t){return K(`LANGSMITH_${t}`)||K(`LANGCHAIN_${t}`)}let Z=t=>void 0!==t?t:!!["TRACING_V2","TRACING"].find(t=>"true"===V(t)),Y=Symbol.for("lc:context_variables");class X{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 X(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 tt{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}),te(t))return void Object.assign(this,{...t});let e=tt.getDefaultConfig(),{metadata:a,...i}=t,r=i.client??tt.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:V("PROJECT")??K("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:K("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:K("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return tt.sharedClient||(tt.sharedClient=new D),tt.sharedClient}createChild(t){let e=this.child_execution_order+1,a=new tt({...t,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:e,child_execution_order:e});Y in this&&(a[Y]=this[Y]);let i=Symbol.for("lc:child_config"),r=t.extra?.[i]??this.extra[i];if(tr(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(ta)?.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=W(),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=Z();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 tt({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 tt({...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=X.fromHeader(a.baggage);o.metadata=t.metadata,o.tags=t.tags}return new tt(o)}toHeaders(t){let e={"langsmith-trace":this.dotted_order,baggage:new X(this.extra?.metadata,this.tags).toHeader()};if(t)for(let[a,i]of Object.entries(e))t.set(a,i);return e}}function te(t){return void 0!==t&&"function"==typeof t.createChild&&"function"==typeof t.postRun}function ta(t){return"object"==typeof t&&null!=t&&"string"==typeof t.name&&"langchain_tracer"===t.name}function ti(t){return Array.isArray(t)&&t.some(t=>ta(t))}function tr(t){return void 0!==t&&"object"==typeof t.callbacks&&(ti(t.callbacks?.handlers)||ti(t.callbacks))}Object.defineProperty(tt,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});let tn=Symbol.for("ls:tracing_async_local_storage"),ts=new class{getStore(){}run(t,e){return e()}},to=new class{getInstance(){return globalThis[tn]??ts}initializeGlobalInstance(t){void 0===globalThis[tn]&&(globalThis[tn]=t)}},tl=Symbol.for("langsmith:traceable:root");function td(t){return"function"==typeof t&&"langsmith:traceable"in t}function tu(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 th=t=>null!=t&&"object"==typeof t&&"function"==typeof t[Symbol.asyncIterator],tc=t=>null!=t&&"object"==typeof t&&"next"in t&&"function"==typeof t.next,tp=(function*(){}).constructor,tm=t=>null!=t&&"function"==typeof t&&t instanceof tp,tf=t=>null!=t&&"object"==typeof t&&"then"in t&&"function"==typeof t.then,tg=t=>null!=t&&"object"==typeof t&&"getReader"in t&&"function"==typeof t.getReader;to.initializeGlobalInstance(new s.A);let t_=t=>{let e,a=t[0];return null==a?{}:t.length>1?{args:t}:tu(a)?a:{input:a}},tb=(t,e)=>{try{return e(t)}catch(e){return console.error("Error occurred during processInputs. Sending raw inputs:",e),t}},ty=(t,e)=>{let a;a=tu(t)?t:{outputs:t};try{return e(a)}catch(t){return console.error("Error occurred during processOutputs. Sending raw outputs:",t),a}},tw=(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]}},tv=(t,e,a,i,r)=>{if(!Z(t.tracingEnabled))return;let[n,s]=tw(e,r);t.attachments=n,t.inputs=tb(s,i);let o=a?.(...e);return null!=o&&(t.extra??={},t.extra.metadata={...o,...t.extra.metadata}),t},tO=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)}})},tS=t=>{if(tg(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(th(t)){let e={current:[]};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=tO(t(...a));return e.current.push(i),i}}return"return"===i||"throw"===i?a.next.bind(a):Reflect.get(t,i,r)}})}:"toJSON"===i?()=>e.current.map(t=>t.toJSON()).reduce((t,e)=>(e?.value&&t.push(e.value),t),[]):Reflect.get(a,i,r)})}if(!Array.isArray(t)&&tc(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 tf(t)?tO(t):t};function tj(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_(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=to.getInstance();for(let t=0;t<n.length;t++)n[t]=tS(n[t]);let[p,m]=(()=>{let[t,...a]=n;if(tr(t))return[tv(tt.fromRunnableConfig(t,o),a,e?.getInvocationParams,u,c),a];if(te(t)&&"callbackManager"in t&&null!=t.callbackManager)return[t,a];if(t===tl||te(t)){let i=tv(t===tl?new tt(o):t.createChild(o),a,e?.getInvocationParams,u,c);return[i,[i,...a]]}let i=l.getStore();if(te(i))return[tv(i.createChild(o),n,e?.getInvocationParams,u,c),n];let r=tv(new tt(o),n,e?.getInvocationParams,u,c);return void 0!==i&&Y in i&&(r[Y]=i[Y]),[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(ty(await o(i),h)),await u()}}function d(t,e){if(tg(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(ty(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(ty(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(th(i)){let t=s.A.snapshot();return d(i,t)}if(!Array.isArray(i)&&"object"==typeof i&&null!=i&&void 0!==r&&th(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(th(a))return e(d(a,s.A.snapshot()));if(!Array.isArray(a)&&"object"==typeof a&&null!=a&&void 0!==r&&th(a[r])){let t=s.A.snapshot();return{...a,[r]:d(a[r],t)}}if(tm(t)&&tc(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(ty(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(ty(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 t$=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},tI=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 tP(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 tE=(t,e)=>{if(td(t.chat.completions.create)||td(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:tj(t.beta.chat.completions.parse.bind(t.beta.chat.completions),{name:"ChatOpenAI",run_type:"llm",aggregator:t$,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:tj(t.chat.completions.create.bind(t.chat.completions),{name:"ChatOpenAI",run_type:"llm",aggregator:t$,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:tP,...e})}},a.completions={...t.completions,create:tj(t.completions.create.bind(t.completions),{name:"OpenAI",run_type:"llm",aggregator:tI,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.
|
|
21
|
+
//# sourceMappingURL=290.375060b2.js.map
|