Back to all snippets
Library/Node.js/OpenAI API Chat Completion
typescriptintermediateopenaiapiaichat

How to implement OpenAI API Chat Completion in Typescript

Make chat completion requests to OpenAI API with streaming support

Quick Answer

Import `OpenAI` from `openai` package, instantiate with your API key, and call `client.chat.completions.create()` with messages — streaming via `stream: true`.

Code Snippet

1import OpenAI from 'openai';
2
3const client = new OpenAI({
4  apiKey: process.env.OPENAI_API_KEY,
5});
6
7// Simple chat completion
8export async function getChatCompletion(message: string) {
9  const completion = await client.chat.completions.create({
10    model: 'gpt-4o-mini',
11    messages: [
12      {
13        role: 'system',
14        content: 'You are a helpful assistant.',
15      },
16      {
17        role: 'user',
18        content: message,
19      },
20    ],
21  });
22
23  return completion.choices[0].message.content;
24}
25
26// Streaming chat completion
27export async function* streamChatCompletion(message: string) {
28  const stream = await client.chat.completions.create({
29    model: 'gpt-4o-mini',
30    messages: [
31      {
32        role: 'system',
33        content: 'You are a helpful assistant.',
34      },
35      {
36        role: 'user',
37        content: message,
38      },
39    ],
40    stream: true,
41  });
42
43  for await (const chunk of stream) {
44    if (chunk.choices[0].delta.content) {
45      yield chunk.choices[0].delta.content;
46    }
47  }
48}

What is OpenAI API Chat Completion?

The OpenAI API is the standard way to add GPT power to your applications. The official Node.js SDK handles authentication, retries, and error handling. This snippet covers both simple completions and streaming responses for real-time UI updates.

How It Works

  1. 1`new OpenAI({ apiKey: process.env.OPENAI_API_KEY })` creates an authenticated client
  2. 2`client.chat.completions.create()` sends a request with message history and model name
  3. 3Set `stream: true` to get a response stream for real-time token-by-token output
  4. 4Iterate over the stream with `for await ... of response` to process tokens as they arrive

Common Use Cases

  • Chatbots - Build conversational AI with full message history
  • Content generation - Generate articles, emails, or code snippets
  • Code assistance - Use GPT-4 for code review and generation
  • Real-time AI - Stream tokens to users for responsive UX

Key Benefits

  • Official SDK with full type support and automatic retries
  • Streaming support for real-time token-by-token responses
  • Message history maintains conversation context
  • Works with all OpenAI models (GPT-4, GPT-3.5, etc.)

Common Mistakes to Avoid

  • Hardcoding the API key in code — always use `process.env.OPENAI_API_KEY` and store it securely.
  • Not handling rate limits — wrap calls in try/catch to handle `RateLimitError` and implement exponential backoff.
  • Streaming without proper cleanup — if streaming, ensure you close the stream if the user disconnects.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

How do I reduce costs when calling OpenAI APIs?

Use GPT-3.5-turbo instead of GPT-4 (much cheaper), implement caching for common prompts, batch requests when possible, and monitor usage with the OpenAI dashboard.

Can I use OpenAI API for free?

OpenAI offers a free $5 credit for new accounts (expires after 3 months). After that, you pay per token. GPT-3.5-turbo is the cheapest production model.

About This Typescript Code Snippet

This free typescript code snippet for openai api chat completion is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement openai api chat completion quickly and correctly.

All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.

Tags: openai, api, ai, chat  | Language: typescript  | Difficulty: intermediate  | Category: Node.js

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.