From e2b14a9499c6d694dbbbf491d9c3c46dc2351de7 Mon Sep 17 00:00:00 2001 From: William FH <13333726+hinthornw@users.noreply.github.com> Date: Mon, 2 Jun 2025 13:43:16 -0700 Subject: [PATCH] feat: Add onRequest callback to JS SDK (#4919) Add onRequest callback --- libs/sdk-js/package.json | 2 +- libs/sdk-js/src/client.ts | 20 +++++++++++++++++--- libs/sdk-js/src/index.ts | 3 ++- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/libs/sdk-js/package.json b/libs/sdk-js/package.json index 90324e17d..8d97eb1da 100644 --- a/libs/sdk-js/package.json +++ b/libs/sdk-js/package.json @@ -1,6 +1,6 @@ { "name": "@langchain/langgraph-sdk", - "version": "0.0.79", + "version": "0.0.80", "description": "Client library for interacting with the LangGraph API", "type": "module", "packageManager": "yarn@1.22.19", diff --git a/libs/sdk-js/src/client.ts b/libs/sdk-js/src/client.ts index 25745b3c6..14ae37583 100644 --- a/libs/sdk-js/src/client.ts +++ b/libs/sdk-js/src/client.ts @@ -86,12 +86,18 @@ function getRunMetadataFromResponse( }; } +export type RequestHook = ( + url: URL, + init: RequestInit, +) => Promise | RequestInit; + export interface ClientConfig { apiUrl?: string; apiKey?: string; callerOptions?: AsyncCallerParams; timeoutMs?: number; defaultHeaders?: Record; + onRequest?: RequestHook; } class BaseClient { @@ -103,6 +109,8 @@ class BaseClient { protected defaultHeaders: Record; + protected onRequest?: RequestHook; + constructor(config?: ClientConfig) { const callerOptions = { maxRetries: 4, @@ -136,6 +144,7 @@ class BaseClient { // Regex to remove trailing slash, if present this.apiUrl = config?.apiUrl?.replace(/\/$/, "") || defaultApiUrl; this.defaultHeaders = config?.defaultHeaders || {}; + this.onRequest = config?.onRequest; const apiKey = getApiKey(config?.apiKey); if (apiKey) { this.defaultHeaders["X-Api-Key"] = apiKey; @@ -230,9 +239,14 @@ class BaseClient { withResponse?: boolean; }, ): Promise { - const response = await this.asyncCaller.fetch( - ...this.prepareFetchOptions(path, options), - ); + const [url, init] = this.prepareFetchOptions(path, options); + + let finalInit = init; + if (this.onRequest) { + finalInit = await this.onRequest(url, init); + } + + const response = await this.asyncCaller.fetch(url, finalInit); const body = (() => { if (response.status === 202 || response.status === 204) { diff --git a/libs/sdk-js/src/index.ts b/libs/sdk-js/src/index.ts index 71253b679..00978a121 100644 --- a/libs/sdk-js/src/index.ts +++ b/libs/sdk-js/src/index.ts @@ -1,4 +1,5 @@ -export { Client } from "./client.js"; +export { Client, getApiKey } from "./client.js"; +export type { ClientConfig, RequestHook } from "./client.js"; export type { AssistantBase,