ข้ามไปเนื้อหาหลัก

Category: guide

OpenAI API — Text Generation, Vision และ Embeddings

คู่มือใช้ OpenAI API กับ Node.js/TypeScript — chat completions, streaming, vision และ embeddings

· อ่านประมาณ 1 นาที

สารบัญ

ติดตั้ง

npm install openai

Chat Completions (พื้นฐาน)

import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const completion = await openai.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [
    { role: 'system', content: 'คุณเป็น assistant ที่ตอบภาษาไทยเสมอ' },
    { role: 'user', content: 'อธิบาย CSS Grid ให้เข้าใจง่าย' },
  ],
  max_tokens: 500,
});

console.log(completion.choices[0].message.content);

Streaming

const stream = await openai.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'เขียน README สั้นๆ ให้หน่อย' }],
  stream: true,
});

for await (const chunk of stream) {
  const text = chunk.choices[0]?.delta?.content ?? '';
  process.stdout.write(text);  // แสดงทีละ token
}

Vision (Image Input)

const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{
    role: 'user',
    content: [
      { type: 'text', text: 'อธิบายรูปนี้' },
      {
        type: 'image_url',
        image_url: { url: 'https://example.com/image.jpg' },
      },
    ],
  }],
});

Embeddings

const embedding = await openai.embeddings.create({
  model: 'text-embedding-3-small',
  input: 'TypeScript conditional types',
});

const vector = embedding.data[0].embedding;  // float[]
// ใช้กับ vector database (Pinecone, pgvector) สำหรับ semantic search

Structured Output (JSON Mode)

const result = await openai.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'ส่งข้อมูล user เป็น JSON' }],
  response_format: { type: 'json_object' },
});

const data = JSON.parse(result.choices[0].message.content!);

Rate Limit Handling

import { RateLimitError } from 'openai';

try {
  const res = await openai.chat.completions.create({ ... });
} catch (err) {
  if (err instanceof RateLimitError) {
    await new Promise((r) => setTimeout(r, 60_000));
    // retry
  }
}

ข้อสำคัญ: เก็บ API key ใน .env เสมอ ห้าม hardcode หรือ commit ลง repo