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`.
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}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.
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.
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.
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.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.