Openai
OpenAI API
OpenAI API Chat Completions import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // Basic completion const response =…
OpenAI API
Chat Completions
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Basic completion
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Explain React hooks in 2 sentences.' },
],
max_tokens: 500,
temperature: 0.7, // 0 = deterministic, 2 = very random
top_p: 1,
});
const answer = response.choices[0].message.content;
const usage = response.usage; // { prompt_tokens, completion_tokens, total_tokens }
// Streaming (Next.js Route Handler)
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = await openai.chat.completions.create({
model: 'gpt-4o',
messages,
stream: true,
});
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content ?? '';
if (text) controller.enqueue(encoder.encode(text));
}
controller.close();
},
});
return new Response(readable, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}
// Client — read stream
const response = await fetch('/api/chat', { method: 'POST', body: JSON.stringify({ messages }) });
const reader = response.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
setOutput(prev => prev + decoder.decode(value));
}Structured Output & Function Calling
import { z } from 'zod';
import { zodResponseFormat } from 'openai/helpers/zod';
// Structured output with Zod (gpt-4o, gpt-4o-mini)
const RecipeSchema = z.object({
name: z.string(),
ingredients: z.array(z.object({ item: z.string(), amount: z.string() })),
steps: z.array(z.string()),
prepTimeMinutes: z.number(),
});
const completion = await openai.beta.chat.completions.parse({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Give me a pasta recipe' }],
response_format: zodResponseFormat(RecipeSchema, 'recipe'),
});
const recipe = completion.choices[0].message.parsed; // fully typed!
// Function calling (tools)
const tools = [
{
type: 'function' as const,
function: {
name: 'get_weather',
description: 'Get current weather for a location',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'City and state, e.g. Austin, TX' },
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
},
required: ['location'],
},
},
},
];
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'What's the weather in Tokyo?' }],
tools,
tool_choice: 'auto',
});
// Check if model wants to call a function
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall?.function.name === 'get_weather') {
const args = JSON.parse(toolCall.function.arguments);
const weather = await getWeather(args.location, args.unit);
// Continue conversation with function result...
}Embeddings & Other APIs
// Embeddings — convert text to vector for semantic search
const embeddingResponse = await openai.embeddings.create({
model: 'text-embedding-3-small', // cheap, good quality
input: 'The quick brown fox', // or array of strings
dimensions: 1536, // optional: reduce dimensions
});
const vector = embeddingResponse.data[0].embedding; // number[]
// Cosine similarity (for manual comparison)
function cosineSimilarity(a: number[], b: number[]): number {
const dot = a.reduce((sum, ai, i) => sum + ai * b[i], 0);
const magA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0));
const magB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0));
return dot / (magA * magB);
}
// Image generation (DALL-E 3)
const image = await openai.images.generate({
model: 'dall-e-3',
prompt: 'A futuristic city at sunset, digital art',
n: 1,
size: '1024x1024',
quality: 'standard', // or 'hd'
style: 'vivid', // or 'natural'
});
const imageUrl = image.data[0].url;
// Vision — analyze images
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'Describe this image' },
{ type: 'image_url', image_url: { url: 'https://example.com/image.png' } },
],
}],
});
// Audio transcription (Whisper)
const transcription = await openai.audio.transcriptions.create({
file: fs.createReadStream('audio.mp3'),
model: 'whisper-1',
language: 'en',
});