Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@nlux/langchain

Package Overview
Dependencies
Maintainers
1
Versions
124
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nlux/langchain - npm Package Compare versions

Comparing version 2.0.12-alpha to 2.1.0-beta

2

cjs/langchain.js

@@ -1,1 +0,1 @@

"use strict";var e=Object.defineProperty,t=(t,r,s)=>((t,r,s)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s)(t,"symbol"!=typeof r?r+"":r,s);class r extends Error{constructor(e={}){super(e.message),t(this,"exceptionId"),t(this,"message"),t(this,"source"),t(this,"type"),this.message=e.message??"",this.source=e.source,this.type=this.constructor.name,this.exceptionId=e.exceptionId}}class s extends r{}const o=e=>{"string"!=typeof e?e&&"function"==typeof e.toString?console.warn(`[nlux] ${e.toString()}`):console.warn("[nlux]"):console.warn(`[nlux] ${e}`)},n=[],a=e=>{const t=/\/.*\/(invoke|stream)$/g.exec(e);if(!t||t.length<2)return;const r=t[1];return"invoke"===r||"stream"===r?r:void 0},i=e=>{const t=a(e.url),r=e.dataTransferMode,s=t?"stream"===t?"stream":"fetch":void 0;const i=s??e.dataTransferMode??u.defaultDataTransferMode;var h;return r&&s&&r!==s&&(h=`The data transfer mode provided to LangServe adapter does not match the LangServe runnable URL action. When you provide a runnable URL that ends with '/${t}', the data transfer mode is automatically set to '${s}' and the 'dataTransferMode' option should not be provided or should be set to '${s}'`,n.includes(h)||(n.push(h),o(h))),i},h=e=>{const t=e.url;return/\/.*\/(invoke|stream)$/g.test(t)?t.replace(/\/(invoke|stream)$/g,""):t},c=e=>{const t=h(e).replace(/\/$/,""),r=(e=>{const t=e.url,r=a(t);return r||("fetch"===i(e)?"invoke":"stream")})(e);return`${t}/${r}`};class u{constructor(e){this.__instanceId=`${this.info.id}-${"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}`,this.__options={...e},this.theDataTransferModeToUse=i(e),this.theHeadersToUse=e.headers||{},this.theUseInputSchemaOptionToUse="boolean"!=typeof e.useInputSchema||e.useInputSchema,this.theEndpointUrlToUse=c(e),this.theRunnableNameToUse=(e=>h(e).replace(/\/$/,"").split("/").pop()||"langserve-runnable")(e),this.theInputSchemaUrlToUse=((e,t)=>`${h(e).replace(/\/$/,"")}/input_schema`)(e),this.init()}get dataTransferMode(){return this.theDataTransferModeToUse}get endpointUrl(){return this.theEndpointUrlToUse}get headers(){return this.theHeadersToUse}get id(){return this.__instanceId}get info(){return{id:"langserve-adapter",capabilities:{chat:!0,fileUpload:!1,textToSpeech:!1,speechToText:!1}}}get inputPreProcessor(){return this.__options.inputPreProcessor}get inputSchema(){return this.theInputSchemaToUse}get outputPreProcessor(){return this.__options.outputPreProcessor}get runnableName(){return this.theRunnableNameToUse}get useInputSchema(){return this.theUseInputSchemaOptionToUse}get inputSchemaUrl(){return this.theInputSchemaUrlToUse}async fetchSchema(e){try{const t=await fetch(e),r=await t.json();return"object"==typeof r&&r?r:void o(`LangServe adapter is unable process schema loaded from: ${e}`)}catch(t){return void o(`LangServe adapter is unable to fetch schema from: ${e}`)}}init(){!this.inputPreProcessor&&this.useInputSchema&&this.fetchSchema(this.inputSchemaUrl).then((e=>{this.theInputSchemaToUse=e}))}getDisplayableMessageFromAiOutput(e){return this.outputPreProcessor?this.outputPreProcessor(e):e}getRequestBody(e,t){if(this.inputPreProcessor){const r=this.inputPreProcessor(e,t);return JSON.stringify({input:r})}if(this.inputSchema){const t=((e,t,r,s)=>{if(!r||"object"!=typeof r.properties)return e;if("object"!=typeof r||!r)return o(`LangServer adapter cannot process the input schema fetched for runnable "${s}". The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string as input.`),e;if("string"===r.type)return e;if("object"===r.type){const t="object"==typeof r.properties&&r.properties?r.properties:{},s=Object.keys(t).filter((e=>e&&"string"==typeof r.properties[e].type)).map((e=>e));if(1===s.length){const t=s[0];return{[t]:e}}o('LangServer adapter cannot find a valid property to match to user input inside the "${runnableName}" input schema. The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string accepted as part of input schema.')}})(e,0,this.inputSchema,this.runnableName);if(void 0!==t)return JSON.stringify({input:t})}return JSON.stringify({input:e})}}u.defaultDataTransferMode="stream";class p extends u{constructor(e){super(e)}async fetchText(e,t){const r=this.getRequestBody(e,t.conversationHistory),s=await fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:r});if(!s.ok)throw new Error(`LangServe runnable returned status code: ${s.status}`);const o=await s.json();if("object"!=typeof o||!o||void 0===o.output)throw new Error('Invalid response from LangServe runnable: Response is not an object or does not contain an "output" property');const n="object"==typeof o&&o?o.output:void 0;return this.getDisplayableMessageFromAiOutput(n)}streamText(e,t,r){throw new s({source:this.constructor.name,message:"Cannot stream text from the fetch adapter!"})}}const d=e=>{const t=/^event:\s+(?<event>[\w]+)((\r?)\n(\r?)data: (?<data>(.|\n)*))?/gm.exec(e);if(!t)return;const{event:r,data:s}=t.groups||{};if(r&&("data"===r||"end"===r))try{return{event:r,data:s?JSON.parse(s):void 0}}catch(e){return o(`LangServe stream adapter failed to parse data for chunk event "${r}" | Data: ${s}`),{event:r,data:void 0}}},m=e=>{if(!e)return[];const t=/(((?<=^)|(?<=\n))event:\s+(\w+))/g,r=[];let s=t.exec(e);for(;s;)r.push(s.index),s=t.exec(e);const o=(t,s)=>{const o=r[s+1]||e.length;return e.substring(t,o)};try{return r.map(o).map(d).filter((e=>void 0!==e)).map((e=>e))}catch(e){return e instanceof Error?e:[]}},l=e=>{if("object"==typeof e&&null!==e){const t=e;if(t.message&&"string"==typeof t.message&&t.message.toLowerCase().includes("connection error"))return"connection-error"}return null};class f extends u{constructor(e){super(e)}async fetchText(e,t){throw new s({source:this.constructor.name,message:"Cannot fetch text using the stream adapter!"})}streamText(e,t,n){const a=this.getRequestBody(e,n.conversationHistory);fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:a}).then((async e=>{if(!e.ok)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});if(!e.body)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});const s=e.body.getReader(),n=new TextDecoder;let a=!1;for(;!a;){const{value:e,done:r}=await s.read();if(r){a=!0;continue}const i=n.decode(e),h=m(i);if(Array.isArray(h))for(const e of h){if("data"===e.event&&void 0!==e.data){const r=this.getDisplayableMessageFromAiOutput(e.data);"string"==typeof r&&r&&t.next(r)}if("end"===e.event){t.complete(),a=!0;break}}h instanceof Error&&(o(h),t.error(h),a=!0)}})).catch((e=>{o(e),t.error(new s({source:this.constructor.name,message:e.message,exceptionId:l(e)??void 0}))}))}}class g{constructor(e){e&&(this.theDataTransferMode=e.theDataTransferMode,this.theHeaders=e.theHeaders,this.theInputPreProcessor=e.theInputPreProcessor,this.theOutputPreProcessor=e.theOutputPreProcessor,this.theUrl=e.theUrl)}create(){if(!this.theUrl)throw new s({source:this.constructor.name,message:"Unable to create LangServe adapter. URL is missing. Make sure you are calling withUrl() before calling create()."});const e={url:this.theUrl,dataTransferMode:this.theDataTransferMode,headers:this.theHeaders,inputPreProcessor:this.theInputPreProcessor,outputPreProcessor:this.theOutputPreProcessor,useInputSchema:this.theUseInputSchema};return"stream"===i(e)?new f(e):new p(e)}withDataTransferMode(e){if(void 0!==this.theDataTransferMode)throw new s({source:this.constructor.name,message:"Cannot set the data loading mode more than once"});return this.theDataTransferMode=e,this}withHeaders(e){if(void 0!==this.theHeaders)throw new s({source:this.constructor.name,message:"Cannot set the headers option more than once"});return this.theHeaders=e,this}withInputPreProcessor(e){if(void 0!==this.theInputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the input pre-processor option more than once"});return this.theInputPreProcessor=e,this}withInputSchema(e){if(void 0!==this.theUseInputSchema)throw new s({source:this.constructor.name,message:"Cannot set the input schema option more than once"});return this.theUseInputSchema=e,this}withOutputPreProcessor(e){if(void 0!==this.theOutputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the output pre-processor option more than once"});return this.theOutputPreProcessor=e,this}withUrl(e){if(void 0!==this.theUrl)throw new s({source:this.constructor.name,message:"Cannot set the runnable URL option more than once"});return this.theUrl=e,this}}exports.createChatAdapter=function(){return new g};
"use strict";var e=Object.defineProperty,t=(t,r,s)=>((t,r,s)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s)(t,"symbol"!=typeof r?r+"":r,s);class r extends Error{constructor(e={}){super(e.message),t(this,"exceptionId"),t(this,"message"),t(this,"source"),t(this,"type"),this.message=e.message??"",this.source=e.source,this.type=this.constructor.name,this.exceptionId=e.exceptionId}}class s extends r{}const o=e=>{"string"!=typeof e?e&&"function"==typeof e.toString?console.warn(`[nlux] ${e.toString()}`):console.warn("[nlux]"):console.warn(`[nlux] ${e}`)},n=[],a=e=>{const t=/\/.*\/(invoke|stream)$/g.exec(e);if(!t||t.length<2)return;const r=t[1];return"invoke"===r||"stream"===r?r:void 0},i=e=>{const t=a(e.url),r=e.dataTransferMode,s=t?"stream"===t?"stream":"fetch":void 0;const i=s??e.dataTransferMode??u.defaultDataTransferMode;var h;return r&&s&&r!==s&&(h=`The data transfer mode provided to LangServe adapter does not match the LangServe runnable URL action. When you provide a runnable URL that ends with '/${t}', the data transfer mode is automatically set to '${s}' and the 'dataTransferMode' option should not be provided or should be set to '${s}'`,n.includes(h)||(n.push(h),o(h))),i},h=e=>{const t=e.url;return/\/.*\/(invoke|stream)$/g.test(t)?t.replace(/\/(invoke|stream)$/g,""):t},c=e=>{const t=h(e).replace(/\/$/,""),r=(e=>{const t=e.url,r=a(t);return r||("fetch"===i(e)?"invoke":"stream")})(e);return`${t}/${r}`};class u{constructor(e){this.__instanceId=`${this.info.id}-${"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}`,this.__options={...e},this.theDataTransferModeToUse=i(e),this.theHeadersToUse=e.headers||{},this.theUseInputSchemaOptionToUse="boolean"!=typeof e.useInputSchema||e.useInputSchema,this.theEndpointUrlToUse=c(e),this.theRunnableNameToUse=(e=>h(e).replace(/\/$/,"").split("/").pop()||"langserve-runnable")(e),this.theInputSchemaUrlToUse=((e,t)=>`${h(e).replace(/\/$/,"")}/input_schema`)(e),this.init()}get dataTransferMode(){return this.theDataTransferModeToUse}get endpointUrl(){return this.theEndpointUrlToUse}get headers(){return this.theHeadersToUse}get id(){return this.__instanceId}get info(){return{id:"langserve-adapter",capabilities:{chat:!0,fileUpload:!1,textToSpeech:!1,speechToText:!1}}}get inputPreProcessor(){return this.__options.inputPreProcessor}get inputSchema(){return this.theInputSchemaToUse}get outputPreProcessor(){return this.__options.outputPreProcessor}get runnableName(){return this.theRunnableNameToUse}get useInputSchema(){return this.theUseInputSchemaOptionToUse}get inputSchemaUrl(){return this.theInputSchemaUrlToUse}async fetchSchema(e){try{const t=await fetch(e),r=await t.json();return"object"==typeof r&&r?r:void o(`LangServe adapter is unable process schema loaded from: ${e}`)}catch(t){return void o(`LangServe adapter is unable to fetch schema from: ${e}`)}}init(){this.useInputSchema&&this.fetchSchema(this.inputSchemaUrl).then((e=>{this.theInputSchemaToUse=e}))}preProcessAiStreamedChunk(e,t){if(this.outputPreProcessor)return this.outputPreProcessor(e);if("string"==typeof e)return e;const r=e?.content;if("string"==typeof r)return r;o("LangServe adapter is unable to process the chunk from the runnable. Returning empty string. You may want to implement an output pre-processor to handle chunks of custom responses.")}preProcessAiUnifiedMessage(e,t){if(this.outputPreProcessor)return this.outputPreProcessor(e);if("string"==typeof e)return e;const r=e?.content;if("string"==typeof r)return r;o("LangServe adapter is unable to process the response from the runnable. Returning empty string. You may want to implement an output pre-processor to handle custom responses.")}getRequestBody(e,t){if(this.inputPreProcessor){const r=this.inputPreProcessor(e,t);return JSON.stringify({input:r})}if(this.inputSchema){const t=((e,t,r,s)=>{const n=r;if(!n||"object"!=typeof n.properties)return e;if("object"!=typeof n||!n)return o(`LangServer adapter cannot process the input schema fetched for runnable "${s}". The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string as input.`),e;if("string"===n.type)return e;if("object"===n.type){const t="object"==typeof n.properties&&n.properties?n.properties:{},r=Object.keys(t).filter((e=>e&&"string"==typeof t[e].type)).map((e=>e));if(1===r.length){const t=r[0];return{[t]:e}}o('LangServer adapter cannot find a valid property to match to user input inside the "${runnableName}" input schema. The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string accepted as part of input schema.')}})(e,0,this.inputSchema,this.runnableName);if(void 0!==t)return JSON.stringify({input:t})}return JSON.stringify({input:e})}}u.defaultDataTransferMode="stream";class p extends u{constructor(e){super(e)}async fetchText(e,t){const r=this.getRequestBody(e,t.conversationHistory),s=await fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:r});if(!s.ok)throw new Error(`LangServe runnable returned status code: ${s.status}`);const o=await s.json();if("object"!=typeof o||!o||void 0===o.output)throw new Error('Invalid response from LangServe runnable: Response is not an object or does not contain an "output" property');return"object"==typeof o&&o?o.output:void 0}streamText(e,t,r){throw new s({source:this.constructor.name,message:"Cannot stream text from the fetch adapter!"})}}const d=e=>{const t=/^event:\s+(?<event>[\w]+)((\r?)\n(\r?)data: (?<data>(.|\n)*))?/gm.exec(e);if(!t)return;const{event:r,data:s}=t.groups||{};if(r&&("data"===r||"end"===r))try{return{event:r,data:s?JSON.parse(s):void 0}}catch(e){return o(`LangServe stream adapter failed to parse data for chunk event "${r}" | Data: ${s}`),{event:r,data:void 0}}},m=e=>{if(!e)return[];const t=/(((?<=^)|(?<=\n))event:\s+(\w+))/g,r=[];let s=t.exec(e);for(;s;)r.push(s.index),s=t.exec(e);const o=(t,s)=>{const o=r[s+1]||e.length;return e.substring(t,o)};try{return r.map(o).map(d).filter((e=>void 0!==e)).map((e=>e))}catch(e){return e instanceof Error?e:[]}},f=e=>{if("object"==typeof e&&null!==e){const t=e;if(t.message&&"string"==typeof t.message&&t.message.toLowerCase().includes("connection error"))return"connection-error"}return null};class l extends u{constructor(e){super(e)}async fetchText(e,t){throw new s({source:this.constructor.name,message:"Cannot fetch text using the stream adapter!"})}streamText(e,t,n){const a=this.getRequestBody(e,n.conversationHistory);fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:a}).then((async e=>{if(!e.ok)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});if(!e.body)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});const s=e.body.getReader(),n=new TextDecoder;let a=!1;for(;!a;){const{value:e,done:r}=await s.read();if(r){a=!0;continue}const i=n.decode(e),h=m(i);if(Array.isArray(h))for(const e of h)if("data"===e.event&&void 0!==e.data&&t.next(e.data),"end"===e.event){t.complete(),a=!0;break}h instanceof Error&&(o(h),t.error(h),a=!0)}})).catch((e=>{o(e),t.error(new s({source:this.constructor.name,message:e.message,exceptionId:f(e)??void 0}))}))}}class g{constructor(e){e&&(this.theDataTransferMode=e.theDataTransferMode,this.theHeaders=e.theHeaders,this.theInputPreProcessor=e.theInputPreProcessor,this.theOutputPreProcessor=e.theOutputPreProcessor,this.theUrl=e.theUrl)}create(){if(!this.theUrl)throw new s({source:this.constructor.name,message:"Unable to create LangServe adapter. URL is missing. Make sure you are calling withUrl() before calling create()."});const e={url:this.theUrl,dataTransferMode:this.theDataTransferMode,headers:this.theHeaders,inputPreProcessor:this.theInputPreProcessor,outputPreProcessor:this.theOutputPreProcessor,useInputSchema:this.theUseInputSchema};return"stream"===i(e)?new l(e):new p(e)}withDataTransferMode(e){if(void 0!==this.theDataTransferMode)throw new s({source:this.constructor.name,message:"Cannot set the data loading mode more than once"});return this.theDataTransferMode=e,this}withHeaders(e){if(void 0!==this.theHeaders)throw new s({source:this.constructor.name,message:"Cannot set the headers option more than once"});return this.theHeaders=e,this}withInputPreProcessor(e){if(void 0!==this.theInputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the input pre-processor option more than once"});return this.theInputPreProcessor=e,this}withInputSchema(e){if(void 0!==this.theUseInputSchema)throw new s({source:this.constructor.name,message:"Cannot set the input schema option more than once"});return this.theUseInputSchema=e,this}withOutputPreProcessor(e){if(void 0!==this.theOutputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the output pre-processor option more than once"});return this.theOutputPreProcessor=e,this}withUrl(e){if(void 0!==this.theUrl)throw new s({source:this.constructor.name,message:"Cannot set the runnable URL option more than once"});return this.theUrl=e,this}}exports.createChatAdapter=()=>new g;

@@ -1,1 +0,1 @@

var e=Object.defineProperty,t=(t,r,s)=>((t,r,s)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s)(t,"symbol"!=typeof r?r+"":r,s);class r extends Error{constructor(e={}){super(e.message),t(this,"exceptionId"),t(this,"message"),t(this,"source"),t(this,"type"),this.message=e.message??"",this.source=e.source,this.type=this.constructor.name,this.exceptionId=e.exceptionId}}class s extends r{}const o=e=>{"string"!=typeof e?e&&"function"==typeof e.toString?console.warn(`[nlux] ${e.toString()}`):console.warn("[nlux]"):console.warn(`[nlux] ${e}`)},n=[],a=e=>{const t=/\/.*\/(invoke|stream)$/g.exec(e);if(!t||t.length<2)return;const r=t[1];return"invoke"===r||"stream"===r?r:void 0},i=e=>{const t=a(e.url),r=e.dataTransferMode,s=t?"stream"===t?"stream":"fetch":void 0;const i=s??e.dataTransferMode??u.defaultDataTransferMode;var h;return r&&s&&r!==s&&(h=`The data transfer mode provided to LangServe adapter does not match the LangServe runnable URL action. When you provide a runnable URL that ends with '/${t}', the data transfer mode is automatically set to '${s}' and the 'dataTransferMode' option should not be provided or should be set to '${s}'`,n.includes(h)||(n.push(h),o(h))),i},h=e=>{const t=e.url;return/\/.*\/(invoke|stream)$/g.test(t)?t.replace(/\/(invoke|stream)$/g,""):t},c=e=>{const t=h(e).replace(/\/$/,""),r=(e=>{const t=e.url,r=a(t);return r||("fetch"===i(e)?"invoke":"stream")})(e);return`${t}/${r}`};class u{constructor(e){this.__instanceId=`${this.info.id}-${"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}`,this.__options={...e},this.theDataTransferModeToUse=i(e),this.theHeadersToUse=e.headers||{},this.theUseInputSchemaOptionToUse="boolean"!=typeof e.useInputSchema||e.useInputSchema,this.theEndpointUrlToUse=c(e),this.theRunnableNameToUse=(e=>h(e).replace(/\/$/,"").split("/").pop()||"langserve-runnable")(e),this.theInputSchemaUrlToUse=((e,t)=>`${h(e).replace(/\/$/,"")}/input_schema`)(e),this.init()}get dataTransferMode(){return this.theDataTransferModeToUse}get endpointUrl(){return this.theEndpointUrlToUse}get headers(){return this.theHeadersToUse}get id(){return this.__instanceId}get info(){return{id:"langserve-adapter",capabilities:{chat:!0,fileUpload:!1,textToSpeech:!1,speechToText:!1}}}get inputPreProcessor(){return this.__options.inputPreProcessor}get inputSchema(){return this.theInputSchemaToUse}get outputPreProcessor(){return this.__options.outputPreProcessor}get runnableName(){return this.theRunnableNameToUse}get useInputSchema(){return this.theUseInputSchemaOptionToUse}get inputSchemaUrl(){return this.theInputSchemaUrlToUse}async fetchSchema(e){try{const t=await fetch(e),r=await t.json();return"object"==typeof r&&r?r:void o(`LangServe adapter is unable process schema loaded from: ${e}`)}catch(t){return void o(`LangServe adapter is unable to fetch schema from: ${e}`)}}init(){!this.inputPreProcessor&&this.useInputSchema&&this.fetchSchema(this.inputSchemaUrl).then((e=>{this.theInputSchemaToUse=e}))}getDisplayableMessageFromAiOutput(e){return this.outputPreProcessor?this.outputPreProcessor(e):e}getRequestBody(e,t){if(this.inputPreProcessor){const r=this.inputPreProcessor(e,t);return JSON.stringify({input:r})}if(this.inputSchema){const t=((e,t,r,s)=>{if(!r||"object"!=typeof r.properties)return e;if("object"!=typeof r||!r)return o(`LangServer adapter cannot process the input schema fetched for runnable "${s}". The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string as input.`),e;if("string"===r.type)return e;if("object"===r.type){const t="object"==typeof r.properties&&r.properties?r.properties:{},s=Object.keys(t).filter((e=>e&&"string"==typeof r.properties[e].type)).map((e=>e));if(1===s.length){const t=s[0];return{[t]:e}}o('LangServer adapter cannot find a valid property to match to user input inside the "${runnableName}" input schema. The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string accepted as part of input schema.')}})(e,0,this.inputSchema,this.runnableName);if(void 0!==t)return JSON.stringify({input:t})}return JSON.stringify({input:e})}}u.defaultDataTransferMode="stream";class p extends u{constructor(e){super(e)}async fetchText(e,t){const r=this.getRequestBody(e,t.conversationHistory),s=await fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:r});if(!s.ok)throw new Error(`LangServe runnable returned status code: ${s.status}`);const o=await s.json();if("object"!=typeof o||!o||void 0===o.output)throw new Error('Invalid response from LangServe runnable: Response is not an object or does not contain an "output" property');const n="object"==typeof o&&o?o.output:void 0;return this.getDisplayableMessageFromAiOutput(n)}streamText(e,t,r){throw new s({source:this.constructor.name,message:"Cannot stream text from the fetch adapter!"})}}const d=e=>{const t=/^event:\s+(?<event>[\w]+)((\r?)\n(\r?)data: (?<data>(.|\n)*))?/gm.exec(e);if(!t)return;const{event:r,data:s}=t.groups||{};if(r&&("data"===r||"end"===r))try{return{event:r,data:s?JSON.parse(s):void 0}}catch(e){return o(`LangServe stream adapter failed to parse data for chunk event "${r}" | Data: ${s}`),{event:r,data:void 0}}},m=e=>{if(!e)return[];const t=/(((?<=^)|(?<=\n))event:\s+(\w+))/g,r=[];let s=t.exec(e);for(;s;)r.push(s.index),s=t.exec(e);const o=(t,s)=>{const o=r[s+1]||e.length;return e.substring(t,o)};try{return r.map(o).map(d).filter((e=>void 0!==e)).map((e=>e))}catch(e){return e instanceof Error?e:[]}},l=e=>{if("object"==typeof e&&null!==e){const t=e;if(t.message&&"string"==typeof t.message&&t.message.toLowerCase().includes("connection error"))return"connection-error"}return null};class f extends u{constructor(e){super(e)}async fetchText(e,t){throw new s({source:this.constructor.name,message:"Cannot fetch text using the stream adapter!"})}streamText(e,t,n){const a=this.getRequestBody(e,n.conversationHistory);fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:a}).then((async e=>{if(!e.ok)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});if(!e.body)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});const s=e.body.getReader(),n=new TextDecoder;let a=!1;for(;!a;){const{value:e,done:r}=await s.read();if(r){a=!0;continue}const i=n.decode(e),h=m(i);if(Array.isArray(h))for(const e of h){if("data"===e.event&&void 0!==e.data){const r=this.getDisplayableMessageFromAiOutput(e.data);"string"==typeof r&&r&&t.next(r)}if("end"===e.event){t.complete(),a=!0;break}}h instanceof Error&&(o(h),t.error(h),a=!0)}})).catch((e=>{o(e),t.error(new s({source:this.constructor.name,message:e.message,exceptionId:l(e)??void 0}))}))}}class g{constructor(e){e&&(this.theDataTransferMode=e.theDataTransferMode,this.theHeaders=e.theHeaders,this.theInputPreProcessor=e.theInputPreProcessor,this.theOutputPreProcessor=e.theOutputPreProcessor,this.theUrl=e.theUrl)}create(){if(!this.theUrl)throw new s({source:this.constructor.name,message:"Unable to create LangServe adapter. URL is missing. Make sure you are calling withUrl() before calling create()."});const e={url:this.theUrl,dataTransferMode:this.theDataTransferMode,headers:this.theHeaders,inputPreProcessor:this.theInputPreProcessor,outputPreProcessor:this.theOutputPreProcessor,useInputSchema:this.theUseInputSchema};return"stream"===i(e)?new f(e):new p(e)}withDataTransferMode(e){if(void 0!==this.theDataTransferMode)throw new s({source:this.constructor.name,message:"Cannot set the data loading mode more than once"});return this.theDataTransferMode=e,this}withHeaders(e){if(void 0!==this.theHeaders)throw new s({source:this.constructor.name,message:"Cannot set the headers option more than once"});return this.theHeaders=e,this}withInputPreProcessor(e){if(void 0!==this.theInputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the input pre-processor option more than once"});return this.theInputPreProcessor=e,this}withInputSchema(e){if(void 0!==this.theUseInputSchema)throw new s({source:this.constructor.name,message:"Cannot set the input schema option more than once"});return this.theUseInputSchema=e,this}withOutputPreProcessor(e){if(void 0!==this.theOutputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the output pre-processor option more than once"});return this.theOutputPreProcessor=e,this}withUrl(e){if(void 0!==this.theUrl)throw new s({source:this.constructor.name,message:"Cannot set the runnable URL option more than once"});return this.theUrl=e,this}}const v=function(){return new g};export{v as createChatAdapter};
var e=Object.defineProperty,t=(t,r,s)=>((t,r,s)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s)(t,"symbol"!=typeof r?r+"":r,s);class r extends Error{constructor(e={}){super(e.message),t(this,"exceptionId"),t(this,"message"),t(this,"source"),t(this,"type"),this.message=e.message??"",this.source=e.source,this.type=this.constructor.name,this.exceptionId=e.exceptionId}}class s extends r{}const o=e=>{"string"!=typeof e?e&&"function"==typeof e.toString?console.warn(`[nlux] ${e.toString()}`):console.warn("[nlux]"):console.warn(`[nlux] ${e}`)},n=[],a=e=>{const t=/\/.*\/(invoke|stream)$/g.exec(e);if(!t||t.length<2)return;const r=t[1];return"invoke"===r||"stream"===r?r:void 0},i=e=>{const t=a(e.url),r=e.dataTransferMode,s=t?"stream"===t?"stream":"fetch":void 0;const i=s??e.dataTransferMode??u.defaultDataTransferMode;var h;return r&&s&&r!==s&&(h=`The data transfer mode provided to LangServe adapter does not match the LangServe runnable URL action. When you provide a runnable URL that ends with '/${t}', the data transfer mode is automatically set to '${s}' and the 'dataTransferMode' option should not be provided or should be set to '${s}'`,n.includes(h)||(n.push(h),o(h))),i},h=e=>{const t=e.url;return/\/.*\/(invoke|stream)$/g.test(t)?t.replace(/\/(invoke|stream)$/g,""):t},c=e=>{const t=h(e).replace(/\/$/,""),r=(e=>{const t=e.url,r=a(t);return r||("fetch"===i(e)?"invoke":"stream")})(e);return`${t}/${r}`};class u{constructor(e){this.__instanceId=`${this.info.id}-${"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}`,this.__options={...e},this.theDataTransferModeToUse=i(e),this.theHeadersToUse=e.headers||{},this.theUseInputSchemaOptionToUse="boolean"!=typeof e.useInputSchema||e.useInputSchema,this.theEndpointUrlToUse=c(e),this.theRunnableNameToUse=(e=>h(e).replace(/\/$/,"").split("/").pop()||"langserve-runnable")(e),this.theInputSchemaUrlToUse=((e,t)=>`${h(e).replace(/\/$/,"")}/input_schema`)(e),this.init()}get dataTransferMode(){return this.theDataTransferModeToUse}get endpointUrl(){return this.theEndpointUrlToUse}get headers(){return this.theHeadersToUse}get id(){return this.__instanceId}get info(){return{id:"langserve-adapter",capabilities:{chat:!0,fileUpload:!1,textToSpeech:!1,speechToText:!1}}}get inputPreProcessor(){return this.__options.inputPreProcessor}get inputSchema(){return this.theInputSchemaToUse}get outputPreProcessor(){return this.__options.outputPreProcessor}get runnableName(){return this.theRunnableNameToUse}get useInputSchema(){return this.theUseInputSchemaOptionToUse}get inputSchemaUrl(){return this.theInputSchemaUrlToUse}async fetchSchema(e){try{const t=await fetch(e),r=await t.json();return"object"==typeof r&&r?r:void o(`LangServe adapter is unable process schema loaded from: ${e}`)}catch(t){return void o(`LangServe adapter is unable to fetch schema from: ${e}`)}}init(){this.useInputSchema&&this.fetchSchema(this.inputSchemaUrl).then((e=>{this.theInputSchemaToUse=e}))}preProcessAiStreamedChunk(e,t){if(this.outputPreProcessor)return this.outputPreProcessor(e);if("string"==typeof e)return e;const r=e?.content;if("string"==typeof r)return r;o("LangServe adapter is unable to process the chunk from the runnable. Returning empty string. You may want to implement an output pre-processor to handle chunks of custom responses.")}preProcessAiUnifiedMessage(e,t){if(this.outputPreProcessor)return this.outputPreProcessor(e);if("string"==typeof e)return e;const r=e?.content;if("string"==typeof r)return r;o("LangServe adapter is unable to process the response from the runnable. Returning empty string. You may want to implement an output pre-processor to handle custom responses.")}getRequestBody(e,t){if(this.inputPreProcessor){const r=this.inputPreProcessor(e,t);return JSON.stringify({input:r})}if(this.inputSchema){const t=((e,t,r,s)=>{const n=r;if(!n||"object"!=typeof n.properties)return e;if("object"!=typeof n||!n)return o(`LangServer adapter cannot process the input schema fetched for runnable "${s}". The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string as input.`),e;if("string"===n.type)return e;if("object"===n.type){const t="object"==typeof n.properties&&n.properties?n.properties:{},r=Object.keys(t).filter((e=>e&&"string"==typeof t[e].type)).map((e=>e));if(1===r.length){const t=r[0];return{[t]:e}}o('LangServer adapter cannot find a valid property to match to user input inside the "${runnableName}" input schema. The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string accepted as part of input schema.')}})(e,0,this.inputSchema,this.runnableName);if(void 0!==t)return JSON.stringify({input:t})}return JSON.stringify({input:e})}}u.defaultDataTransferMode="stream";class p extends u{constructor(e){super(e)}async fetchText(e,t){const r=this.getRequestBody(e,t.conversationHistory),s=await fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:r});if(!s.ok)throw new Error(`LangServe runnable returned status code: ${s.status}`);const o=await s.json();if("object"!=typeof o||!o||void 0===o.output)throw new Error('Invalid response from LangServe runnable: Response is not an object or does not contain an "output" property');return"object"==typeof o&&o?o.output:void 0}streamText(e,t,r){throw new s({source:this.constructor.name,message:"Cannot stream text from the fetch adapter!"})}}const d=e=>{const t=/^event:\s+(?<event>[\w]+)((\r?)\n(\r?)data: (?<data>(.|\n)*))?/gm.exec(e);if(!t)return;const{event:r,data:s}=t.groups||{};if(r&&("data"===r||"end"===r))try{return{event:r,data:s?JSON.parse(s):void 0}}catch(e){return o(`LangServe stream adapter failed to parse data for chunk event "${r}" | Data: ${s}`),{event:r,data:void 0}}},m=e=>{if(!e)return[];const t=/(((?<=^)|(?<=\n))event:\s+(\w+))/g,r=[];let s=t.exec(e);for(;s;)r.push(s.index),s=t.exec(e);const o=(t,s)=>{const o=r[s+1]||e.length;return e.substring(t,o)};try{return r.map(o).map(d).filter((e=>void 0!==e)).map((e=>e))}catch(e){return e instanceof Error?e:[]}},f=e=>{if("object"==typeof e&&null!==e){const t=e;if(t.message&&"string"==typeof t.message&&t.message.toLowerCase().includes("connection error"))return"connection-error"}return null};class l extends u{constructor(e){super(e)}async fetchText(e,t){throw new s({source:this.constructor.name,message:"Cannot fetch text using the stream adapter!"})}streamText(e,t,n){const a=this.getRequestBody(e,n.conversationHistory);fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:a}).then((async e=>{if(!e.ok)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});if(!e.body)throw new r({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});const s=e.body.getReader(),n=new TextDecoder;let a=!1;for(;!a;){const{value:e,done:r}=await s.read();if(r){a=!0;continue}const i=n.decode(e),h=m(i);if(Array.isArray(h))for(const e of h)if("data"===e.event&&void 0!==e.data&&t.next(e.data),"end"===e.event){t.complete(),a=!0;break}h instanceof Error&&(o(h),t.error(h),a=!0)}})).catch((e=>{o(e),t.error(new s({source:this.constructor.name,message:e.message,exceptionId:f(e)??void 0}))}))}}class g{constructor(e){e&&(this.theDataTransferMode=e.theDataTransferMode,this.theHeaders=e.theHeaders,this.theInputPreProcessor=e.theInputPreProcessor,this.theOutputPreProcessor=e.theOutputPreProcessor,this.theUrl=e.theUrl)}create(){if(!this.theUrl)throw new s({source:this.constructor.name,message:"Unable to create LangServe adapter. URL is missing. Make sure you are calling withUrl() before calling create()."});const e={url:this.theUrl,dataTransferMode:this.theDataTransferMode,headers:this.theHeaders,inputPreProcessor:this.theInputPreProcessor,outputPreProcessor:this.theOutputPreProcessor,useInputSchema:this.theUseInputSchema};return"stream"===i(e)?new l(e):new p(e)}withDataTransferMode(e){if(void 0!==this.theDataTransferMode)throw new s({source:this.constructor.name,message:"Cannot set the data loading mode more than once"});return this.theDataTransferMode=e,this}withHeaders(e){if(void 0!==this.theHeaders)throw new s({source:this.constructor.name,message:"Cannot set the headers option more than once"});return this.theHeaders=e,this}withInputPreProcessor(e){if(void 0!==this.theInputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the input pre-processor option more than once"});return this.theInputPreProcessor=e,this}withInputSchema(e){if(void 0!==this.theUseInputSchema)throw new s({source:this.constructor.name,message:"Cannot set the input schema option more than once"});return this.theUseInputSchema=e,this}withOutputPreProcessor(e){if(void 0!==this.theOutputPreProcessor)throw new s({source:this.constructor.name,message:"Cannot set the output pre-processor option more than once"});return this.theOutputPreProcessor=e,this}withUrl(e){if(void 0!==this.theUrl)throw new s({source:this.constructor.name,message:"Cannot set the runnable URL option more than once"});return this.theUrl=e,this}}const v=()=>new g;export{v as createChatAdapter};

@@ -27,3 +27,3 @@ import { ChatItem, ChatAdapterBuilder as ChatAdapterBuilder$1, StandardChatAdapter, DataTransferMode } from '@nlux/core';

*/
type LangServeInputPreProcessor<AiMsg> = (input: string, conversationHistory?: ChatItem<AiMsg>[]) => any;
type LangServeInputPreProcessor<AiMsg> = (input: string, conversationHistory?: ChatItem<AiMsg>[]) => unknown;

@@ -45,3 +45,3 @@ type LangServeEndpointType = 'invoke' | 'stream';

*/
type LangServeOutputPreProcessor<AiMsg> = (output: any) => AiMsg;
type LangServeOutputPreProcessor<AiMsg> = (output: unknown) => AiMsg;

@@ -115,4 +115,4 @@ interface ChatAdapterBuilder<AiMsg> extends ChatAdapterBuilder$1<AiMsg> {

declare const createChatAdapter: <AiMsg>() => ChatAdapterBuilder<AiMsg>;
declare const createChatAdapter: <AiMsg = string>() => ChatAdapterBuilder<AiMsg>;
export { type ChatAdapterBuilder, type ChatAdapterOptions, type LangServeEndpointType, createChatAdapter };
{
"name": "@nlux/langchain",
"version": "2.0.12-alpha",
"version": "2.1.0-beta",
"description": "The LangChain adapters for nlux, the javascript library for building conversational AI interfaces.",

@@ -62,3 +62,3 @@ "keywords": [

"dependencies": {
"@nlux/core": "2.0.12-alpha"
"@nlux/core": "2.1.0-beta"
},

@@ -65,0 +65,0 @@ "peerDependencies": {},

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@nlux/langchain"]={})}(this,(function(e){"use strict";var t=Object.defineProperty,r=(e,r,s)=>((e,r,s)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s)(e,"symbol"!=typeof r?r+"":r,s);class s extends Error{constructor(e={}){super(e.message),r(this,"exceptionId"),r(this,"message"),r(this,"source"),r(this,"type"),this.message=e.message??"",this.source=e.source,this.type=this.constructor.name,this.exceptionId=e.exceptionId}}class o extends s{}const n=e=>{"string"!=typeof e?e&&"function"==typeof e.toString?console.warn(`[nlux] ${e.toString()}`):console.warn("[nlux]"):console.warn(`[nlux] ${e}`)},a=[],i=e=>{const t=/\/.*\/(invoke|stream)$/g.exec(e);if(!t||t.length<2)return;const r=t[1];return"invoke"===r||"stream"===r?r:void 0},h=e=>{const t=i(e.url),r=e.dataTransferMode,s=t?"stream"===t?"stream":"fetch":void 0;const o=s??e.dataTransferMode??p.defaultDataTransferMode;var h;return r&&s&&r!==s&&(h=`The data transfer mode provided to LangServe adapter does not match the LangServe runnable URL action. When you provide a runnable URL that ends with '/${t}', the data transfer mode is automatically set to '${s}' and the 'dataTransferMode' option should not be provided or should be set to '${s}'`,a.includes(h)||(a.push(h),n(h))),o},c=e=>{const t=e.url;return/\/.*\/(invoke|stream)$/g.test(t)?t.replace(/\/(invoke|stream)$/g,""):t},u=e=>{const t=c(e).replace(/\/$/,""),r=(e=>{const t=e.url,r=i(t);return r||("fetch"===h(e)?"invoke":"stream")})(e);return`${t}/${r}`};class p{constructor(e){this.__instanceId=`${this.info.id}-${"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}`,this.__options={...e},this.theDataTransferModeToUse=h(e),this.theHeadersToUse=e.headers||{},this.theUseInputSchemaOptionToUse="boolean"!=typeof e.useInputSchema||e.useInputSchema,this.theEndpointUrlToUse=u(e),this.theRunnableNameToUse=(e=>c(e).replace(/\/$/,"").split("/").pop()||"langserve-runnable")(e),this.theInputSchemaUrlToUse=((e,t)=>`${c(e).replace(/\/$/,"")}/input_schema`)(e),this.init()}get dataTransferMode(){return this.theDataTransferModeToUse}get endpointUrl(){return this.theEndpointUrlToUse}get headers(){return this.theHeadersToUse}get id(){return this.__instanceId}get info(){return{id:"langserve-adapter",capabilities:{chat:!0,fileUpload:!1,textToSpeech:!1,speechToText:!1}}}get inputPreProcessor(){return this.__options.inputPreProcessor}get inputSchema(){return this.theInputSchemaToUse}get outputPreProcessor(){return this.__options.outputPreProcessor}get runnableName(){return this.theRunnableNameToUse}get useInputSchema(){return this.theUseInputSchemaOptionToUse}get inputSchemaUrl(){return this.theInputSchemaUrlToUse}async fetchSchema(e){try{const t=await fetch(e),r=await t.json();return"object"==typeof r&&r?r:void n(`LangServe adapter is unable process schema loaded from: ${e}`)}catch(t){return void n(`LangServe adapter is unable to fetch schema from: ${e}`)}}init(){!this.inputPreProcessor&&this.useInputSchema&&this.fetchSchema(this.inputSchemaUrl).then((e=>{this.theInputSchemaToUse=e}))}getDisplayableMessageFromAiOutput(e){return this.outputPreProcessor?this.outputPreProcessor(e):e}getRequestBody(e,t){if(this.inputPreProcessor){const r=this.inputPreProcessor(e,t);return JSON.stringify({input:r})}if(this.inputSchema){const t=((e,t,r,s)=>{if(!r||"object"!=typeof r.properties)return e;if("object"!=typeof r||!r)return n(`LangServer adapter cannot process the input schema fetched for runnable "${s}". The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string as input.`),e;if("string"===r.type)return e;if("object"===r.type){const t="object"==typeof r.properties&&r.properties?r.properties:{},s=Object.keys(t).filter((e=>e&&"string"==typeof r.properties[e].type)).map((e=>e));if(1===s.length){const t=s[0];return{[t]:e}}n('LangServer adapter cannot find a valid property to match to user input inside the "${runnableName}" input schema. The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string accepted as part of input schema.')}})(e,0,this.inputSchema,this.runnableName);if(void 0!==t)return JSON.stringify({input:t})}return JSON.stringify({input:e})}}p.defaultDataTransferMode="stream";class d extends p{constructor(e){super(e)}async fetchText(e,t){const r=this.getRequestBody(e,t.conversationHistory),s=await fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:r});if(!s.ok)throw new Error(`LangServe runnable returned status code: ${s.status}`);const o=await s.json();if("object"!=typeof o||!o||void 0===o.output)throw new Error('Invalid response from LangServe runnable: Response is not an object or does not contain an "output" property');const n="object"==typeof o&&o?o.output:void 0;return this.getDisplayableMessageFromAiOutput(n)}streamText(e,t,r){throw new o({source:this.constructor.name,message:"Cannot stream text from the fetch adapter!"})}}const m=e=>{const t=/^event:\s+(?<event>[\w]+)((\r?)\n(\r?)data: (?<data>(.|\n)*))?/gm.exec(e);if(!t)return;const{event:r,data:s}=t.groups||{};if(r&&("data"===r||"end"===r))try{return{event:r,data:s?JSON.parse(s):void 0}}catch(e){return n(`LangServe stream adapter failed to parse data for chunk event "${r}" | Data: ${s}`),{event:r,data:void 0}}},l=e=>{if(!e)return[];const t=/(((?<=^)|(?<=\n))event:\s+(\w+))/g,r=[];let s=t.exec(e);for(;s;)r.push(s.index),s=t.exec(e);const o=(t,s)=>{const o=r[s+1]||e.length;return e.substring(t,o)};try{return r.map(o).map(m).filter((e=>void 0!==e)).map((e=>e))}catch(e){return e instanceof Error?e:[]}},f=e=>{if("object"==typeof e&&null!==e){const t=e;if(t.message&&"string"==typeof t.message&&t.message.toLowerCase().includes("connection error"))return"connection-error"}return null};class g extends p{constructor(e){super(e)}async fetchText(e,t){throw new o({source:this.constructor.name,message:"Cannot fetch text using the stream adapter!"})}streamText(e,t,r){const a=this.getRequestBody(e,r.conversationHistory);fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:a}).then((async e=>{if(!e.ok)throw new s({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});if(!e.body)throw new s({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});const r=e.body.getReader(),o=new TextDecoder;let a=!1;for(;!a;){const{value:e,done:s}=await r.read();if(s){a=!0;continue}const i=o.decode(e),h=l(i);if(Array.isArray(h))for(const e of h){if("data"===e.event&&void 0!==e.data){const r=this.getDisplayableMessageFromAiOutput(e.data);"string"==typeof r&&r&&t.next(r)}if("end"===e.event){t.complete(),a=!0;break}}h instanceof Error&&(n(h),t.error(h),a=!0)}})).catch((e=>{n(e),t.error(new o({source:this.constructor.name,message:e.message,exceptionId:f(e)??void 0}))}))}}class v{constructor(e){e&&(this.theDataTransferMode=e.theDataTransferMode,this.theHeaders=e.theHeaders,this.theInputPreProcessor=e.theInputPreProcessor,this.theOutputPreProcessor=e.theOutputPreProcessor,this.theUrl=e.theUrl)}create(){if(!this.theUrl)throw new o({source:this.constructor.name,message:"Unable to create LangServe adapter. URL is missing. Make sure you are calling withUrl() before calling create()."});const e={url:this.theUrl,dataTransferMode:this.theDataTransferMode,headers:this.theHeaders,inputPreProcessor:this.theInputPreProcessor,outputPreProcessor:this.theOutputPreProcessor,useInputSchema:this.theUseInputSchema};return"stream"===h(e)?new g(e):new d(e)}withDataTransferMode(e){if(void 0!==this.theDataTransferMode)throw new o({source:this.constructor.name,message:"Cannot set the data loading mode more than once"});return this.theDataTransferMode=e,this}withHeaders(e){if(void 0!==this.theHeaders)throw new o({source:this.constructor.name,message:"Cannot set the headers option more than once"});return this.theHeaders=e,this}withInputPreProcessor(e){if(void 0!==this.theInputPreProcessor)throw new o({source:this.constructor.name,message:"Cannot set the input pre-processor option more than once"});return this.theInputPreProcessor=e,this}withInputSchema(e){if(void 0!==this.theUseInputSchema)throw new o({source:this.constructor.name,message:"Cannot set the input schema option more than once"});return this.theUseInputSchema=e,this}withOutputPreProcessor(e){if(void 0!==this.theOutputPreProcessor)throw new o({source:this.constructor.name,message:"Cannot set the output pre-processor option more than once"});return this.theOutputPreProcessor=e,this}withUrl(e){if(void 0!==this.theUrl)throw new o({source:this.constructor.name,message:"Cannot set the runnable URL option more than once"});return this.theUrl=e,this}}e.createChatAdapter=function(){return new v}}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@nlux/langchain"]={})}(this,(function(e){"use strict";var t=Object.defineProperty,r=(e,r,s)=>((e,r,s)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s)(e,"symbol"!=typeof r?r+"":r,s);class s extends Error{constructor(e={}){super(e.message),r(this,"exceptionId"),r(this,"message"),r(this,"source"),r(this,"type"),this.message=e.message??"",this.source=e.source,this.type=this.constructor.name,this.exceptionId=e.exceptionId}}class n extends s{}const o=e=>{"string"!=typeof e?e&&"function"==typeof e.toString?console.warn(`[nlux] ${e.toString()}`):console.warn("[nlux]"):console.warn(`[nlux] ${e}`)},a=[],i=e=>{const t=/\/.*\/(invoke|stream)$/g.exec(e);if(!t||t.length<2)return;const r=t[1];return"invoke"===r||"stream"===r?r:void 0},h=e=>{const t=i(e.url),r=e.dataTransferMode,s=t?"stream"===t?"stream":"fetch":void 0;const n=s??e.dataTransferMode??p.defaultDataTransferMode;var h;return r&&s&&r!==s&&(h=`The data transfer mode provided to LangServe adapter does not match the LangServe runnable URL action. When you provide a runnable URL that ends with '/${t}', the data transfer mode is automatically set to '${s}' and the 'dataTransferMode' option should not be provided or should be set to '${s}'`,a.includes(h)||(a.push(h),o(h))),n},c=e=>{const t=e.url;return/\/.*\/(invoke|stream)$/g.test(t)?t.replace(/\/(invoke|stream)$/g,""):t},u=e=>{const t=c(e).replace(/\/$/,""),r=(e=>{const t=e.url,r=i(t);return r||("fetch"===h(e)?"invoke":"stream")})(e);return`${t}/${r}`};class p{constructor(e){this.__instanceId=`${this.info.id}-${"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}`,this.__options={...e},this.theDataTransferModeToUse=h(e),this.theHeadersToUse=e.headers||{},this.theUseInputSchemaOptionToUse="boolean"!=typeof e.useInputSchema||e.useInputSchema,this.theEndpointUrlToUse=u(e),this.theRunnableNameToUse=(e=>c(e).replace(/\/$/,"").split("/").pop()||"langserve-runnable")(e),this.theInputSchemaUrlToUse=((e,t)=>`${c(e).replace(/\/$/,"")}/input_schema`)(e),this.init()}get dataTransferMode(){return this.theDataTransferModeToUse}get endpointUrl(){return this.theEndpointUrlToUse}get headers(){return this.theHeadersToUse}get id(){return this.__instanceId}get info(){return{id:"langserve-adapter",capabilities:{chat:!0,fileUpload:!1,textToSpeech:!1,speechToText:!1}}}get inputPreProcessor(){return this.__options.inputPreProcessor}get inputSchema(){return this.theInputSchemaToUse}get outputPreProcessor(){return this.__options.outputPreProcessor}get runnableName(){return this.theRunnableNameToUse}get useInputSchema(){return this.theUseInputSchemaOptionToUse}get inputSchemaUrl(){return this.theInputSchemaUrlToUse}async fetchSchema(e){try{const t=await fetch(e),r=await t.json();return"object"==typeof r&&r?r:void o(`LangServe adapter is unable process schema loaded from: ${e}`)}catch(t){return void o(`LangServe adapter is unable to fetch schema from: ${e}`)}}init(){this.useInputSchema&&this.fetchSchema(this.inputSchemaUrl).then((e=>{this.theInputSchemaToUse=e}))}preProcessAiStreamedChunk(e,t){if(this.outputPreProcessor)return this.outputPreProcessor(e);if("string"==typeof e)return e;const r=e?.content;if("string"==typeof r)return r;o("LangServe adapter is unable to process the chunk from the runnable. Returning empty string. You may want to implement an output pre-processor to handle chunks of custom responses.")}preProcessAiUnifiedMessage(e,t){if(this.outputPreProcessor)return this.outputPreProcessor(e);if("string"==typeof e)return e;const r=e?.content;if("string"==typeof r)return r;o("LangServe adapter is unable to process the response from the runnable. Returning empty string. You may want to implement an output pre-processor to handle custom responses.")}getRequestBody(e,t){if(this.inputPreProcessor){const r=this.inputPreProcessor(e,t);return JSON.stringify({input:r})}if(this.inputSchema){const t=((e,t,r,s)=>{const n=r;if(!n||"object"!=typeof n.properties)return e;if("object"!=typeof n||!n)return o(`LangServer adapter cannot process the input schema fetched for runnable "${s}". The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string as input.`),e;if("string"===n.type)return e;if("object"===n.type){const t="object"==typeof n.properties&&n.properties?n.properties:{},r=Object.keys(t).filter((e=>e&&"string"==typeof t[e].type)).map((e=>e));if(1===r.length){const t=r[0];return{[t]:e}}o('LangServer adapter cannot find a valid property to match to user input inside the "${runnableName}" input schema. The user message will be sent to LangServe endpoint as is without transformations. To override this behavior, you can either set the "useInputSchema" option to false, or provide a custom input pre-processor via the "inputPreProcessor" option, or update your endpoint and input schema to have an object with a single string property or a string accepted as part of input schema.')}})(e,0,this.inputSchema,this.runnableName);if(void 0!==t)return JSON.stringify({input:t})}return JSON.stringify({input:e})}}p.defaultDataTransferMode="stream";class d extends p{constructor(e){super(e)}async fetchText(e,t){const r=this.getRequestBody(e,t.conversationHistory),s=await fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:r});if(!s.ok)throw new Error(`LangServe runnable returned status code: ${s.status}`);const n=await s.json();if("object"!=typeof n||!n||void 0===n.output)throw new Error('Invalid response from LangServe runnable: Response is not an object or does not contain an "output" property');return"object"==typeof n&&n?n.output:void 0}streamText(e,t,r){throw new n({source:this.constructor.name,message:"Cannot stream text from the fetch adapter!"})}}const m=e=>{const t=/^event:\s+(?<event>[\w]+)((\r?)\n(\r?)data: (?<data>(.|\n)*))?/gm.exec(e);if(!t)return;const{event:r,data:s}=t.groups||{};if(r&&("data"===r||"end"===r))try{return{event:r,data:s?JSON.parse(s):void 0}}catch(e){return o(`LangServe stream adapter failed to parse data for chunk event "${r}" | Data: ${s}`),{event:r,data:void 0}}},f=e=>{if(!e)return[];const t=/(((?<=^)|(?<=\n))event:\s+(\w+))/g,r=[];let s=t.exec(e);for(;s;)r.push(s.index),s=t.exec(e);const n=(t,s)=>{const n=r[s+1]||e.length;return e.substring(t,n)};try{return r.map(n).map(m).filter((e=>void 0!==e)).map((e=>e))}catch(e){return e instanceof Error?e:[]}},l=e=>{if("object"==typeof e&&null!==e){const t=e;if(t.message&&"string"==typeof t.message&&t.message.toLowerCase().includes("connection error"))return"connection-error"}return null};class g extends p{constructor(e){super(e)}async fetchText(e,t){throw new n({source:this.constructor.name,message:"Cannot fetch text using the stream adapter!"})}streamText(e,t,r){const a=this.getRequestBody(e,r.conversationHistory);fetch(this.endpointUrl,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:a}).then((async e=>{if(!e.ok)throw new s({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});if(!e.body)throw new s({source:this.constructor.name,message:`LangServe runnable returned status code: ${e.status}`});const r=e.body.getReader(),n=new TextDecoder;let a=!1;for(;!a;){const{value:e,done:s}=await r.read();if(s){a=!0;continue}const i=n.decode(e),h=f(i);if(Array.isArray(h))for(const e of h)if("data"===e.event&&void 0!==e.data&&t.next(e.data),"end"===e.event){t.complete(),a=!0;break}h instanceof Error&&(o(h),t.error(h),a=!0)}})).catch((e=>{o(e),t.error(new n({source:this.constructor.name,message:e.message,exceptionId:l(e)??void 0}))}))}}class v{constructor(e){e&&(this.theDataTransferMode=e.theDataTransferMode,this.theHeaders=e.theHeaders,this.theInputPreProcessor=e.theInputPreProcessor,this.theOutputPreProcessor=e.theOutputPreProcessor,this.theUrl=e.theUrl)}create(){if(!this.theUrl)throw new n({source:this.constructor.name,message:"Unable to create LangServe adapter. URL is missing. Make sure you are calling withUrl() before calling create()."});const e={url:this.theUrl,dataTransferMode:this.theDataTransferMode,headers:this.theHeaders,inputPreProcessor:this.theInputPreProcessor,outputPreProcessor:this.theOutputPreProcessor,useInputSchema:this.theUseInputSchema};return"stream"===h(e)?new g(e):new d(e)}withDataTransferMode(e){if(void 0!==this.theDataTransferMode)throw new n({source:this.constructor.name,message:"Cannot set the data loading mode more than once"});return this.theDataTransferMode=e,this}withHeaders(e){if(void 0!==this.theHeaders)throw new n({source:this.constructor.name,message:"Cannot set the headers option more than once"});return this.theHeaders=e,this}withInputPreProcessor(e){if(void 0!==this.theInputPreProcessor)throw new n({source:this.constructor.name,message:"Cannot set the input pre-processor option more than once"});return this.theInputPreProcessor=e,this}withInputSchema(e){if(void 0!==this.theUseInputSchema)throw new n({source:this.constructor.name,message:"Cannot set the input schema option more than once"});return this.theUseInputSchema=e,this}withOutputPreProcessor(e){if(void 0!==this.theOutputPreProcessor)throw new n({source:this.constructor.name,message:"Cannot set the output pre-processor option more than once"});return this.theOutputPreProcessor=e,this}withUrl(e){if(void 0!==this.theUrl)throw new n({source:this.constructor.name,message:"Cannot set the runnable URL option more than once"});return this.theUrl=e,this}}e.createChatAdapter=()=>new v}));
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc