A minimal and opinionated OpenAI client powered by fetch.
Unfortunately, the official openai-node uses Axios, which only supports Node and is bloated.
- Supports all envs with native fetch: Node 18+, browsers, Deno, Cloudflare Workers, etc
- Package size:
openai-fetch
is ~5kb andopenai-node
is ~180kb openai-fetch
includes the first choice in the response (no repetitive:response.choices[0.text]
)- You only need the completions, edits, and embeddings endpoints
- Endpoints other than completions, edits, and embeddings
- Streaming response support (this may be added later)
- Responses to contain more than one choice (no
n
support) - To use tokens instead of strings for input
Install openai-fetch
with your favorite package manager and create an instance of the OpenAIClient
class.
import { OpenAIClient } from 'openai-fetch';
const client = new OpenAIClient({ apiKey: '<your api key>' });
The apiKey
is optional and will be read from process.env.OPENAI_API_KEY
if present.
The API follows OpenAI very closely, so their reference documentation can generally be used. Everything is strongly typed, so you will know if anything is different as soon as TypeScript parses your code.
See: OpenAI docs | Type definitions
client.createCompletion(params: CompletionParams): Promise<{
/** The completion string. */
completion: string;
/** The raw response from the API. */
response: CompletionResponse;
}>
See: OpenAI docs | Type definitions
client.createChatCompletion(params: ChatCompletionParams): Promise<{
/** The completion message. */
message: ChatResponseMessage;
/** The raw response from the API. */
response: ChatCompletionResponse;
}>
See: OpenAI docs | Type definitions
client.createEmbedding(params: EmbeddingParams): Promise<{
/** The embedding for the input string. */
embedding: number[];
/** The raw response from the API. */
response: EmbeddingResponse;
}>
See: OpenAI docs | Type definitions
client.createEdit(params: EditParams): Promise<{
/** The edited input string. */
completion: string;
/** The raw response from the API. */
response: EditResponse;
}>