File tree Expand file tree Collapse file tree 2 files changed +27
-3
lines changed Expand file tree Collapse file tree 2 files changed +27
-3
lines changed Original file line number Diff line number Diff line change @@ -138,8 +138,11 @@ export class APIPromise<T> extends Promise<WithRequestID<T>> {
138138 asResponse ( ) : Promise < Response > {
139139 return this . responsePromise . then ( ( p ) => p . response ) ;
140140 }
141+
141142 /**
142- * Gets the parsed response data and the raw `Response` instance.
143+ * Gets the parsed response data, the raw `Response` instance and the ID of the request,
144+ * returned via the X-Request-ID header which is useful for debugging requests and reporting
145+ * issues to OpenAI.
143146 *
144147 * If you just want to get the raw `Response` instance without parsing it,
145148 * you can use {@link asResponse()}.
@@ -151,9 +154,9 @@ export class APIPromise<T> extends Promise<WithRequestID<T>> {
151154 * - `import 'openai/shims/node'` (if you're running on Node)
152155 * - `import 'openai/shims/web'` (otherwise)
153156 */
154- async withResponse ( ) : Promise < { data : T ; response : Response } > {
157+ async withResponse ( ) : Promise < { data : T ; response : Response ; request_id : string | null | undefined } > {
155158 const [ data , response ] = await Promise . all ( [ this . parse ( ) , this . asResponse ( ) ] ) ;
156- return { data, response } ;
159+ return { data, response, request_id : response . headers . get ( 'x-request-id' ) } ;
157160 }
158161
159162 private parse ( ) : Promise < WithRequestID < T > > {
Original file line number Diff line number Diff line change @@ -41,6 +41,27 @@ describe('request id', () => {
4141 compareType < Awaited < APIPromise < Array < { foo : string } > > > , Array < { foo : string } > > ( true ) ;
4242 } ) ;
4343
44+ test ( 'withResponse' , async ( ) => {
45+ const client = new OpenAI ( {
46+ apiKey : 'dummy' ,
47+ fetch : async ( ) =>
48+ new Response ( JSON . stringify ( { id : 'bar' } ) , {
49+ headers : { 'x-request-id' : 'req_id_xxx' , 'content-type' : 'application/json' } ,
50+ } ) ,
51+ } ) ;
52+
53+ const {
54+ data : completion ,
55+ response,
56+ request_id,
57+ } = await client . chat . completions . create ( { messages : [ ] , model : 'gpt-4' } ) . withResponse ( ) ;
58+
59+ expect ( request_id ) . toBe ( 'req_id_xxx' ) ;
60+ expect ( response . headers . get ( 'x-request-id' ) ) . toBe ( 'req_id_xxx' ) ;
61+ expect ( completion . id ) . toBe ( 'bar' ) ;
62+ expect ( JSON . stringify ( completion ) ) . toBe ( '{"id":"bar"}' ) ;
63+ } ) ;
64+
4465 test ( 'object response' , async ( ) => {
4566 const client = new OpenAI ( {
4667 apiKey : 'dummy' ,
You can’t perform that action at this time.
0 commit comments