traceable.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { isRunTree } from "../run_trees.js";
  2. class MockAsyncLocalStorage {
  3. getStore() {
  4. return undefined;
  5. }
  6. run(_, callback) {
  7. return callback();
  8. }
  9. }
  10. const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage");
  11. const mockAsyncLocalStorage = new MockAsyncLocalStorage();
  12. class AsyncLocalStorageProvider {
  13. getInstance() {
  14. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15. return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage;
  16. }
  17. initializeGlobalInstance(instance) {
  18. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19. if (globalThis[TRACING_ALS_KEY] === undefined) {
  20. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  21. globalThis[TRACING_ALS_KEY] = instance;
  22. }
  23. }
  24. }
  25. export const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();
  26. export function getCurrentRunTree(permitAbsentRunTree = false) {
  27. const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore();
  28. if (!permitAbsentRunTree && !isRunTree(runTree)) {
  29. throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");
  30. }
  31. return runTree;
  32. }
  33. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  34. export function withRunTree(runTree, fn) {
  35. const storage = AsyncLocalStorageProviderSingleton.getInstance();
  36. return new Promise((resolve, reject) => {
  37. storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject));
  38. });
  39. }
  40. export const ROOT = Symbol.for("langsmith:traceable:root");
  41. export function isTraceableFunction(x
  42. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  43. ) {
  44. return typeof x === "function" && "langsmith:traceable" in x;
  45. }