Skip to content

Commit 1ca982f

Browse files
authoredNov 4, 2023
docs: document customizing fetch (#420)
1 parent 37b0a58 commit 1ca982f

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed
 

‎README.md

+40-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ You can import in Deno via:
2121
<!-- x-release-please-start-version -->
2222

2323
```ts
24-
import OpenAI from 'https://raw.githubusercontent.com/openai/openai-node/v4.14.2-deno/mod.ts';
24+
import OpenAI from 'https://raw.githubusercontent.com/openai/openai-node/v4.15.0-deno/mod.ts';
2525
```
2626

2727
<!-- x-release-please-end -->
@@ -395,6 +395,45 @@ console.log(raw.headers.get('X-My-Header'));
395395
console.log(chatCompletion.choices);
396396
```
397397

398+
## Customizing the fetch client
399+
400+
By default, this library uses `node-fetch` in Node, and expects a global `fetch` function in other environments.
401+
402+
If you would prefer to use a global, web-standards-compliant `fetch` function even in a Node environment,
403+
(for example, if you are running Node with `--experimental-fetch` or using NextJS which polyfills with `undici`),
404+
add the following import before your first import `from "OpenAI"`:
405+
406+
<!-- prettier-ignore -->
407+
```ts
408+
// Tell TypeScript and the package to use the global web fetch instead of node-fetch.
409+
// Note, despite the name, this does not add any polyfills, but expects them to be provided if needed.
410+
import "openai/shims/web";
411+
import OpenAI from "openai";
412+
```
413+
414+
To do the inverse, add `import "openai/shims/node"` (which does import polyfills).
415+
This can also be useful if you are getting the wrong TypeScript types for `Response` - more details [here](https://github.com/openai/openai-node/src/_shims#readme).
416+
417+
You may also provide a custom `fetch` function when instantiating the client,
418+
which can be used to inspect or alter the `Request` or `Response` before/after each request:
419+
420+
```ts
421+
import { fetch } from 'undici'; // as one example
422+
import OpenAI from 'openai';
423+
424+
const client = new OpenAI({
425+
fetch: (url: RequestInfo, init?: RequestInfo): Response => {
426+
console.log('About to make request', url, init);
427+
const response = await fetch(url, init);
428+
console.log('Got response', response);
429+
return response;
430+
},
431+
});
432+
```
433+
434+
Note that if given a `DEBUG=true` environment variable, this library will log all requests and responses automatically.
435+
This is intended for debugging purposes only and may change in the future without notice.
436+
398437
## Configuring an HTTP(S) Agent (e.g., for proxies)
399438

400439
By default, this library uses a stable agent for all http/https requests to reuse TCP connections, eliminating many TCP & TLS handshakes and shaving around 100ms off most requests.

0 commit comments

Comments
 (0)
Please sign in to comment.