From b3f13ee904e1859319959bea85376af0eabd99ad Mon Sep 17 00:00:00 2001 From: Tat Dat Duong Date: Tue, 6 May 2025 03:15:44 +0200 Subject: [PATCH] Add onRunCreated callback --- libs/sdk-js/src/client.ts | 33 +++++++++++++++++++++++++++------ libs/sdk-js/src/types.ts | 5 +++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/libs/sdk-js/src/client.ts b/libs/sdk-js/src/client.ts index b66a6f168..b5147f75c 100644 --- a/libs/sdk-js/src/client.ts +++ b/libs/sdk-js/src/client.ts @@ -68,6 +68,24 @@ export function getApiKey(apiKey?: string): string | undefined { return undefined; } +const REGEX_RUN_METADATA = + /(\/threads\/(?.+))?\/runs\/(?.+)/; + +function getRunMetadataFromResponse( + response: Response, +): { run_id: string; thread_id?: string } | undefined { + const contentLocation = response.headers.get("Content-Location"); + if (!contentLocation) return undefined; + + const match = REGEX_RUN_METADATA.exec(contentLocation); + + if (!match?.groups?.run_id) return undefined; + return { + run_id: match.groups.run_id, + thread_id: match.groups.thread_id || undefined, + }; +} + export interface ClientConfig { apiUrl?: string; apiKey?: string; @@ -903,8 +921,9 @@ export class RunsClient< }), ); - const contentLocation = response.headers.get("Content-Location"); - if (contentLocation) payload?.onResponse?.(response); + payload?.onResponse?.(response); + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) payload?.onRunCreated?.(runMetadata); const stream: ReadableStream<{ event: any; data: any }> = ( response.body || new ReadableStream({ start: (ctrl) => ctrl.close() }) @@ -954,8 +973,9 @@ export class RunsClient< withResponse: true, }); - const contentLocation = response.headers.get("Content-Location"); - if (contentLocation) payload?.onResponse?.(response); + payload?.onResponse?.(response); + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) payload?.onRunCreated?.(runMetadata); return run; } @@ -1036,8 +1056,9 @@ export class RunsClient< withResponse: true, }); - const contentLocation = response.headers.get("Content-Location"); - if (contentLocation) payload?.onResponse?.(response); + payload?.onResponse?.(response); + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) payload?.onRunCreated?.(runMetadata); const raiseError = payload?.raiseError !== undefined ? payload.raiseError : true; diff --git a/libs/sdk-js/src/types.ts b/libs/sdk-js/src/types.ts index 4cc4733e5..69ad16c98 100644 --- a/libs/sdk-js/src/types.ts +++ b/libs/sdk-js/src/types.ts @@ -141,6 +141,11 @@ interface RunsInvokePayload { * Useful when obtaining headers from the response. */ onResponse?: (response: Response) => void; + + /** + * Callback when a run is created. + */ + onRunCreated?: (params: { run_id: string; thread_id?: string }) => void; } export interface RunsStreamPayload<