fetch.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { getLangSmithEnvironmentVariable } from "../utils/env.js";
  2. // Wrap the default fetch call due to issues with illegal invocations
  3. // in some environments:
  4. // https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err
  5. // @ts-expect-error Broad typing to support a range of fetch implementations
  6. const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args);
  7. const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation");
  8. /**
  9. * Overrides the fetch implementation used for LangSmith calls.
  10. * You should use this if you need to use an implementation of fetch
  11. * other than the default global (e.g. for dealing with proxies).
  12. * @param fetch The new fetch functino to use.
  13. */
  14. export const overrideFetchImplementation = (fetch) => {
  15. globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch;
  16. };
  17. export const _globalFetchImplementationIsNodeFetch = () => {
  18. const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY];
  19. if (!fetchImpl)
  20. return false;
  21. // Check if the implementation has node-fetch specific properties
  22. return (typeof fetchImpl === "function" &&
  23. "Headers" in fetchImpl &&
  24. "Request" in fetchImpl &&
  25. "Response" in fetchImpl);
  26. };
  27. /**
  28. * @internal
  29. */
  30. export const _getFetchImplementation = (debug) => {
  31. return async (...args) => {
  32. if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") {
  33. const [url, options] = args;
  34. console.log(`→ ${options?.method || "GET"} ${url}`);
  35. }
  36. const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ??
  37. DEFAULT_FETCH_IMPLEMENTATION)(...args);
  38. if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") {
  39. console.log(`← ${res.status} ${res.statusText} ${res.url}`);
  40. }
  41. return res;
  42. };
  43. };