Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,11 @@ export class APIPromise<T> extends Promise<WithRequestID<T>> {
asResponse(): Promise<Response> {
return this.responsePromise.then((p) => p.response);
}

/**
* Gets the parsed response data and the raw `Response` instance.
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the X-Request-ID header which is useful for debugging requests and reporting
* issues to OpenAI.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
Expand All @@ -151,9 +154,9 @@ export class APIPromise<T> extends Promise<WithRequestID<T>> {
* - `import 'openai/shims/node'` (if you're running on Node)
* - `import 'openai/shims/web'` (otherwise)
*/
async withResponse(): Promise<{ data: T; response: Response }> {
async withResponse(): Promise<{ data: T; response: Response; request_id: string | null | undefined }> {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response };
return { data, response, request_id: response.headers.get('x-request-id') };
}

private parse(): Promise<WithRequestID<T>> {
Expand Down
21 changes: 21 additions & 0 deletions tests/responses.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,27 @@ describe('request id', () => {
compareType<Awaited<APIPromise<Array<{ foo: string }>>>, Array<{ foo: string }>>(true);
});

test('withResponse', async () => {
const client = new OpenAI({
apiKey: 'dummy',
fetch: async () =>
new Response(JSON.stringify({ id: 'bar' }), {
headers: { 'x-request-id': 'req_id_xxx', 'content-type': 'application/json' },
}),
});

const {
data: completion,
response,
request_id,
} = await client.chat.completions.create({ messages: [], model: 'gpt-4' }).withResponse();

expect(request_id).toBe('req_id_xxx');
expect(response.headers.get('x-request-id')).toBe('req_id_xxx');
expect(completion.id).toBe('bar');
expect(JSON.stringify(completion)).toBe('{"id":"bar"}');
});

test('object response', async () => {
const client = new OpenAI({
apiKey: 'dummy',
Expand Down