remote.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import { Runnable, _coerceToDict } from "./base.js";
  2. import { getCallbackManagerForConfig } from "./config.js";
  3. import { Document } from "../documents/index.js";
  4. import { ChatPromptValue, StringPromptValue } from "../prompt_values.js";
  5. import { RunLogPatch, RunLog, } from "../tracers/log_stream.js";
  6. import { AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessage, FunctionMessageChunk, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, isBaseMessage, } from "../messages/index.js";
  7. import { GenerationChunk, ChatGenerationChunk, RUN_KEY } from "../outputs.js";
  8. import { convertEventStreamToIterableReadableDataStream } from "../utils/event_source_parse.js";
  9. import { IterableReadableStream, concat } from "../utils/stream.js";
  10. function isSuperset(set, subset) {
  11. for (const elem of subset) {
  12. if (!set.has(elem)) {
  13. return false;
  14. }
  15. }
  16. return true;
  17. }
  18. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19. function revive(obj) {
  20. if (Array.isArray(obj))
  21. return obj.map(revive);
  22. if (typeof obj === "object") {
  23. // eslint-disable-next-line no-instanceof/no-instanceof
  24. if (!obj || obj instanceof Date) {
  25. return obj;
  26. }
  27. const keysArr = Object.keys(obj);
  28. const keys = new Set(keysArr);
  29. if (isSuperset(keys, new Set(["page_content", "metadata"]))) {
  30. return new Document({
  31. pageContent: obj.page_content,
  32. metadata: obj.metadata,
  33. });
  34. }
  35. if (isSuperset(keys, new Set(["content", "type", "additional_kwargs"]))) {
  36. if (obj.type === "HumanMessage" || obj.type === "human") {
  37. return new HumanMessage({
  38. content: obj.content,
  39. });
  40. }
  41. if (obj.type === "SystemMessage" || obj.type === "system") {
  42. return new SystemMessage({
  43. content: obj.content,
  44. });
  45. }
  46. if (obj.type === "ChatMessage" || obj.type === "generic") {
  47. return new ChatMessage({
  48. content: obj.content,
  49. role: obj.role,
  50. });
  51. }
  52. if (obj.type === "FunctionMessage" || obj.type === "function") {
  53. return new FunctionMessage({
  54. content: obj.content,
  55. name: obj.name,
  56. });
  57. }
  58. if (obj.type === "ToolMessage" || obj.type === "tool") {
  59. return new ToolMessage({
  60. content: obj.content,
  61. tool_call_id: obj.tool_call_id,
  62. status: obj.status,
  63. artifact: obj.artifact,
  64. });
  65. }
  66. if (obj.type === "AIMessage" || obj.type === "ai") {
  67. return new AIMessage({
  68. content: obj.content,
  69. });
  70. }
  71. if (obj.type === "HumanMessageChunk") {
  72. return new HumanMessageChunk({
  73. content: obj.content,
  74. });
  75. }
  76. if (obj.type === "SystemMessageChunk") {
  77. return new SystemMessageChunk({
  78. content: obj.content,
  79. });
  80. }
  81. if (obj.type === "ChatMessageChunk") {
  82. return new ChatMessageChunk({
  83. content: obj.content,
  84. role: obj.role,
  85. });
  86. }
  87. if (obj.type === "FunctionMessageChunk") {
  88. return new FunctionMessageChunk({
  89. content: obj.content,
  90. name: obj.name,
  91. });
  92. }
  93. if (obj.type === "ToolMessageChunk") {
  94. return new ToolMessageChunk({
  95. content: obj.content,
  96. tool_call_id: obj.tool_call_id,
  97. status: obj.status,
  98. artifact: obj.artifact,
  99. });
  100. }
  101. if (obj.type === "AIMessageChunk") {
  102. return new AIMessageChunk({
  103. content: obj.content,
  104. });
  105. }
  106. }
  107. if (isSuperset(keys, new Set(["text", "generation_info", "type"]))) {
  108. if (obj.type === "ChatGenerationChunk") {
  109. return new ChatGenerationChunk({
  110. message: revive(obj.message),
  111. text: obj.text,
  112. generationInfo: obj.generation_info,
  113. });
  114. }
  115. else if (obj.type === "ChatGeneration") {
  116. return {
  117. message: revive(obj.message),
  118. text: obj.text,
  119. generationInfo: obj.generation_info,
  120. };
  121. }
  122. else if (obj.type === "GenerationChunk") {
  123. return new GenerationChunk({
  124. text: obj.text,
  125. generationInfo: obj.generation_info,
  126. });
  127. }
  128. else if (obj.type === "Generation") {
  129. return {
  130. text: obj.text,
  131. generationInfo: obj.generation_info,
  132. };
  133. }
  134. }
  135. if (isSuperset(keys, new Set(["tool", "tool_input", "log", "type"]))) {
  136. if (obj.type === "AgentAction") {
  137. return {
  138. tool: obj.tool,
  139. toolInput: obj.tool_input,
  140. log: obj.log,
  141. };
  142. }
  143. }
  144. if (isSuperset(keys, new Set(["return_values", "log", "type"]))) {
  145. if (obj.type === "AgentFinish") {
  146. return {
  147. returnValues: obj.return_values,
  148. log: obj.log,
  149. };
  150. }
  151. }
  152. if (isSuperset(keys, new Set(["generations", "run", "type"]))) {
  153. if (obj.type === "LLMResult") {
  154. return {
  155. generations: revive(obj.generations),
  156. llmOutput: obj.llm_output,
  157. [RUN_KEY]: obj.run,
  158. };
  159. }
  160. }
  161. if (isSuperset(keys, new Set(["messages"]))) {
  162. // TODO: Start checking for type: ChatPromptValue and ChatPromptValueConcrete
  163. // when LangServe bug is fixed
  164. return new ChatPromptValue({
  165. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  166. messages: obj.messages.map((msg) => revive(msg)),
  167. });
  168. }
  169. if (isSuperset(keys, new Set(["text"]))) {
  170. // TODO: Start checking for type: StringPromptValue
  171. // when LangServe bug is fixed
  172. return new StringPromptValue(obj.text);
  173. }
  174. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  175. const innerRevive = (key) => [
  176. key,
  177. revive(obj[key]),
  178. ];
  179. const rtn = Object.fromEntries(keysArr.map(innerRevive));
  180. return rtn;
  181. }
  182. return obj;
  183. }
  184. function deserialize(str) {
  185. const obj = JSON.parse(str);
  186. return revive(obj);
  187. }
  188. function removeCallbacksAndSignal(options) {
  189. const rest = { ...options };
  190. delete rest.callbacks;
  191. delete rest.signal;
  192. return rest;
  193. }
  194. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  195. function serialize(input) {
  196. if (Array.isArray(input))
  197. return input.map(serialize);
  198. if (isBaseMessage(input)) {
  199. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  200. const serializedMessage = {
  201. content: input.content,
  202. type: input._getType(),
  203. additional_kwargs: input.additional_kwargs,
  204. name: input.name,
  205. example: false,
  206. };
  207. if (ToolMessage.isInstance(input)) {
  208. serializedMessage.tool_call_id = input.tool_call_id;
  209. }
  210. else if (ChatMessage.isInstance(input)) {
  211. serializedMessage.role = input.role;
  212. }
  213. return serializedMessage;
  214. }
  215. if (typeof input === "object") {
  216. // eslint-disable-next-line no-instanceof/no-instanceof
  217. if (!input || input instanceof Date) {
  218. return input;
  219. }
  220. const keysArr = Object.keys(input);
  221. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  222. const innerSerialize = (key) => [
  223. key,
  224. serialize(input[key]),
  225. ];
  226. const rtn = Object.fromEntries(keysArr.map(innerSerialize));
  227. return rtn;
  228. }
  229. return input;
  230. }
  231. /**
  232. * Client for interacting with LangChain runnables
  233. * that are hosted as LangServe endpoints.
  234. *
  235. * Allows you to interact with hosted runnables using the standard
  236. * `.invoke()`, `.stream()`, `.streamEvents()`, etc. methods that
  237. * other runnables support.
  238. *
  239. * @deprecated LangServe is no longer actively developed - please consider using LangGraph Platform.
  240. *
  241. * @param url - The base URL of the LangServe endpoint.
  242. * @param options - Optional configuration for the remote runnable, including timeout and headers.
  243. * @param fetch - Optional custom fetch implementation.
  244. * @param fetchRequestOptions - Optional additional options for fetch requests.
  245. */
  246. export class RemoteRunnable extends Runnable {
  247. constructor(fields) {
  248. super(fields);
  249. Object.defineProperty(this, "url", {
  250. enumerable: true,
  251. configurable: true,
  252. writable: true,
  253. value: void 0
  254. });
  255. Object.defineProperty(this, "options", {
  256. enumerable: true,
  257. configurable: true,
  258. writable: true,
  259. value: void 0
  260. });
  261. // Wrap the default fetch call due to issues with illegal invocations
  262. // from the browser:
  263. // https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err
  264. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  265. Object.defineProperty(this, "fetchImplementation", {
  266. enumerable: true,
  267. configurable: true,
  268. writable: true,
  269. value: (...args) =>
  270. // @ts-expect-error Broad typing to support a range of fetch implementations
  271. fetch(...args)
  272. });
  273. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  274. Object.defineProperty(this, "fetchRequestOptions", {
  275. enumerable: true,
  276. configurable: true,
  277. writable: true,
  278. value: void 0
  279. });
  280. Object.defineProperty(this, "lc_namespace", {
  281. enumerable: true,
  282. configurable: true,
  283. writable: true,
  284. value: ["langchain", "schema", "runnable", "remote"]
  285. });
  286. const { url, options, fetch: fetchImplementation, fetchRequestOptions, } = fields;
  287. this.url = url.replace(/\/$/, ""); // remove trailing slash
  288. this.options = options;
  289. this.fetchImplementation = fetchImplementation ?? this.fetchImplementation;
  290. this.fetchRequestOptions = fetchRequestOptions;
  291. }
  292. async post(path, body, signal) {
  293. return this.fetchImplementation(`${this.url}${path}`, {
  294. method: "POST",
  295. body: JSON.stringify(serialize(body)),
  296. signal: signal ?? AbortSignal.timeout(this.options?.timeout ?? 60000),
  297. ...this.fetchRequestOptions,
  298. headers: {
  299. "Content-Type": "application/json",
  300. ...this.fetchRequestOptions?.headers,
  301. ...this.options?.headers,
  302. },
  303. });
  304. }
  305. async _invoke(input, options, _) {
  306. const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
  307. const response = await this.post("/invoke", {
  308. input,
  309. config: removeCallbacksAndSignal(config),
  310. kwargs: kwargs ?? {},
  311. }, config.signal);
  312. if (!response.ok) {
  313. throw new Error(`${response.status} Error: ${await response.text()}`);
  314. }
  315. return revive((await response.json()).output);
  316. }
  317. async invoke(input, options) {
  318. return this._callWithConfig(this._invoke, input, options);
  319. }
  320. async _batch(inputs, options, _, batchOptions) {
  321. if (batchOptions?.returnExceptions) {
  322. throw new Error("returnExceptions is not supported for remote clients");
  323. }
  324. const configsAndKwargsArray = options?.map((opts) => this._separateRunnableConfigFromCallOptions(opts));
  325. const [configs, kwargs] = configsAndKwargsArray?.reduce(([pc, pk], [c, k]) => [
  326. [...pc, c],
  327. [...pk, k],
  328. ], [[], []]) ?? [undefined, undefined];
  329. const response = await this.post("/batch", {
  330. inputs,
  331. config: (configs ?? [])
  332. .map(removeCallbacksAndSignal)
  333. .map((config) => ({ ...config, ...batchOptions })),
  334. kwargs,
  335. }, options?.[0]?.signal);
  336. if (!response.ok) {
  337. throw new Error(`${response.status} Error: ${await response.text()}`);
  338. }
  339. const body = await response.json();
  340. if (!body.output)
  341. throw new Error("Invalid response from remote runnable");
  342. return revive(body.output);
  343. }
  344. async batch(inputs, options, batchOptions) {
  345. if (batchOptions?.returnExceptions) {
  346. throw Error("returnExceptions is not supported for remote clients");
  347. }
  348. return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
  349. }
  350. async *_streamIterator(input, options) {
  351. const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
  352. const callbackManager_ = await getCallbackManagerForConfig(options);
  353. const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config.runName);
  354. delete config.runId;
  355. let finalOutput;
  356. let finalOutputSupported = true;
  357. try {
  358. const response = await this.post("/stream", {
  359. input,
  360. config: removeCallbacksAndSignal(config),
  361. kwargs,
  362. }, config.signal);
  363. if (!response.ok) {
  364. const json = await response.json();
  365. const error = new Error(`RemoteRunnable call failed with status code ${response.status}: ${json.message}`);
  366. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  367. error.response = response;
  368. throw error;
  369. }
  370. const { body } = response;
  371. if (!body) {
  372. throw new Error("Could not begin remote stream. Please check the given URL and try again.");
  373. }
  374. const runnableStream = convertEventStreamToIterableReadableDataStream(body);
  375. for await (const chunk of runnableStream) {
  376. const deserializedChunk = deserialize(chunk);
  377. yield deserializedChunk;
  378. if (finalOutputSupported) {
  379. if (finalOutput === undefined) {
  380. finalOutput = deserializedChunk;
  381. }
  382. else {
  383. try {
  384. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  385. finalOutput = concat(finalOutput, deserializedChunk);
  386. }
  387. catch {
  388. finalOutput = undefined;
  389. finalOutputSupported = false;
  390. }
  391. }
  392. }
  393. }
  394. }
  395. catch (err) {
  396. await runManager?.handleChainError(err);
  397. throw err;
  398. }
  399. await runManager?.handleChainEnd(finalOutput ?? {});
  400. }
  401. async *streamLog(input, options, streamOptions) {
  402. const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
  403. const callbackManager_ = await getCallbackManagerForConfig(options);
  404. const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config.runName);
  405. delete config.runId;
  406. // The type is in camelCase but the API only accepts snake_case.
  407. const camelCaseStreamOptions = {
  408. include_names: streamOptions?.includeNames,
  409. include_types: streamOptions?.includeTypes,
  410. include_tags: streamOptions?.includeTags,
  411. exclude_names: streamOptions?.excludeNames,
  412. exclude_types: streamOptions?.excludeTypes,
  413. exclude_tags: streamOptions?.excludeTags,
  414. };
  415. let runLog;
  416. try {
  417. const response = await this.post("/stream_log", {
  418. input,
  419. config: removeCallbacksAndSignal(config),
  420. kwargs,
  421. ...camelCaseStreamOptions,
  422. diff: false,
  423. }, config.signal);
  424. const { body, ok } = response;
  425. if (!ok) {
  426. throw new Error(`${response.status} Error: ${await response.text()}`);
  427. }
  428. if (!body) {
  429. throw new Error("Could not begin remote stream log. Please check the given URL and try again.");
  430. }
  431. const runnableStream = convertEventStreamToIterableReadableDataStream(body);
  432. for await (const log of runnableStream) {
  433. const chunk = revive(JSON.parse(log));
  434. const logPatch = new RunLogPatch({ ops: chunk.ops });
  435. yield logPatch;
  436. if (runLog === undefined) {
  437. runLog = RunLog.fromRunLogPatch(logPatch);
  438. }
  439. else {
  440. runLog = runLog.concat(logPatch);
  441. }
  442. }
  443. }
  444. catch (err) {
  445. await runManager?.handleChainError(err);
  446. throw err;
  447. }
  448. await runManager?.handleChainEnd(runLog?.state.final_output);
  449. }
  450. _streamEvents(input, options, streamOptions) {
  451. // eslint-disable-next-line @typescript-eslint/no-this-alias
  452. const outerThis = this;
  453. const generator = async function* () {
  454. const [config, kwargs] = outerThis._separateRunnableConfigFromCallOptions(options);
  455. const callbackManager_ = await getCallbackManagerForConfig(options);
  456. const runManager = await callbackManager_?.handleChainStart(outerThis.toJSON(), _coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config.runName);
  457. delete config.runId;
  458. // The type is in camelCase but the API only accepts snake_case.
  459. const camelCaseStreamOptions = {
  460. include_names: streamOptions?.includeNames,
  461. include_types: streamOptions?.includeTypes,
  462. include_tags: streamOptions?.includeTags,
  463. exclude_names: streamOptions?.excludeNames,
  464. exclude_types: streamOptions?.excludeTypes,
  465. exclude_tags: streamOptions?.excludeTags,
  466. };
  467. const events = [];
  468. try {
  469. const response = await outerThis.post("/stream_events", {
  470. input,
  471. config: removeCallbacksAndSignal(config),
  472. kwargs,
  473. ...camelCaseStreamOptions,
  474. diff: false,
  475. }, config.signal);
  476. const { body, ok } = response;
  477. if (!ok) {
  478. throw new Error(`${response.status} Error: ${await response.text()}`);
  479. }
  480. if (!body) {
  481. throw new Error("Could not begin remote stream events. Please check the given URL and try again.");
  482. }
  483. const runnableStream = convertEventStreamToIterableReadableDataStream(body);
  484. for await (const log of runnableStream) {
  485. const chunk = revive(JSON.parse(log));
  486. const event = {
  487. event: chunk.event,
  488. name: chunk.name,
  489. run_id: chunk.run_id,
  490. tags: chunk.tags,
  491. metadata: chunk.metadata,
  492. data: chunk.data,
  493. };
  494. yield event;
  495. events.push(event);
  496. }
  497. }
  498. catch (err) {
  499. await runManager?.handleChainError(err);
  500. throw err;
  501. }
  502. await runManager?.handleChainEnd(events);
  503. };
  504. return generator();
  505. }
  506. streamEvents(input, options, streamOptions) {
  507. if (options.version !== "v1" && options.version !== "v2") {
  508. throw new Error(`Only versions "v1" and "v2" of the events schema is currently supported.`);
  509. }
  510. if (options.encoding !== undefined) {
  511. throw new Error("Special encodings are not supported for this runnable.");
  512. }
  513. const eventStream = this._streamEvents(input, options, streamOptions);
  514. return IterableReadableStream.fromAsyncGenerator(eventStream);
  515. }
  516. }