OpenAI API Guide: คู่มือใช้งาน GPT API
OpenAI API เป็นช่องทางหลักในการเข้าถึง GPT models เรียนรู้วิธีใช้งานตั้งแต่พื้นฐานไปจนถึงฟีเจอร์ขั้นสูง
Getting Started
API Key Setup
# 1. ไปที่ platform.openai.com
# 2. สร้าง API key
# 3. เก็บไว้ใน environment variable
import os
from openai import OpenAI
# Set API key
os.environ["OPENAI_API_KEY"] = "sk-..."
# Initialize client
client = OpenAI()
Available Models
GPT-4o (gpt-4o)
- Multimodal (text + vision)
- Best performance
- $2.50/1M input, $10/1M output
GPT-4o-mini (gpt-4o-mini)
- Fast และ affordable
- Good for most tasks
- $0.15/1M input, $0.60/1M output
GPT-4 Turbo (gpt-4-turbo)
- 128K context
- Good performance
- $10/1M input, $30/1M output
o1 (o1-preview, o1-mini)
- Reasoning models
- Complex problem solving
- Higher cost
Chat Completions
Basic Usage
from openai import OpenAI
client = OpenAI()
# Basic chat completion
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is Python?"}
]
)
print(response.choices[0].message.content)
Conversation History
# Maintain conversation context
messages = [
{"role": "system", "content": "You are a coding tutor."}
]
def chat(user_message):
messages.append({"role": "user", "content": user_message})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
assistant_message = response.choices[0].message.content
messages.append({"role": "assistant", "content": assistant_message})
return assistant_message
# Usage
print(chat("Teach me about lists in Python"))
print(chat("How do I add items to it?")) # Remembers context
Parameters
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[...],
# Control randomness (0-2)
temperature=0.7,
# Alternative to temperature
top_p=1.0,
# Max tokens in response
max_tokens=1000,
# Number of responses
n=1,
# Stop sequences
stop=["\n\n"],
# Presence penalty (-2 to 2)
presence_penalty=0,
# Frequency penalty (-2 to 2)
frequency_penalty=0,
# Add metadata
user="user-123"
)
Streaming
Stream Responses
# Stream for real-time output
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Write a poem about coding"}
],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
Async Streaming
import asyncio
from openai import AsyncOpenAI
async_client = AsyncOpenAI()
async def stream_chat():
stream = await async_client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello!"}],
stream=True
)
async for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
asyncio.run(stream_chat())
Function Calling (Tools)
Define Functions
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g., Bangkok"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}
}
]
Use Function Calling
import json
# Actual function implementation
def get_weather(location, unit="celsius"):
# In real app, call weather API
return {"temp": 30, "condition": "sunny", "unit": unit}
# Request with tools
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "What's the weather in Bangkok?"}
],
tools=tools,
tool_choice="auto"
)
# Check if model wants to call a function
message = response.choices[0].message
if message.tool_calls:
for tool_call in message.tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
# Execute function
if function_name == "get_weather":
result = get_weather(**arguments)
# Send result back
messages = [
{"role": "user", "content": "What's the weather in Bangkok?"},
message,
{
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
}
]
# Get final response
final_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
print(final_response.choices[0].message.content)
Structured Outputs
JSON Mode
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "Output JSON only."
},
{
"role": "user",
"content": "List 3 programming languages with their uses"
}
],
response_format={"type": "json_object"}
)
import json
data = json.loads(response.choices[0].message.content)
Structured Output with Schema
from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float
category: str
in_stock: bool
response = client.beta.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Generate a product for a tech store"}
],
response_format=Product
)
product = response.choices[0].message.parsed
print(f"Name: {product.name}, Price: ${product.price}")
Vision (Image Input)
Analyze Images
import base64
# From URL
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg"
}
}
]
}
]
)
# From base64
def encode_image(image_path):
with open(image_path, "rb") as f:
return base64.standard_b64encode(f.read()).decode("utf-8")
base64_image = encode_image("photo.jpg")
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image"},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
]
)
Embeddings
Generate Embeddings
# Create embedding
response = client.embeddings.create(
model="text-embedding-3-small",
input="Hello world"
)
embedding = response.data[0].embedding
print(f"Dimension: {len(embedding)}") # 1536
# Multiple inputs
response = client.embeddings.create(
model="text-embedding-3-small",
input=["Text 1", "Text 2", "Text 3"]
)
embeddings = [d.embedding for d in response.data]
Similarity Search
import numpy as np
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
# Compare texts
texts = ["Python programming", "Machine learning", "Cooking recipes"]
embeddings = client.embeddings.create(
model="text-embedding-3-small",
input=texts
).data
query_embedding = client.embeddings.create(
model="text-embedding-3-small",
input="AI development"
).data[0].embedding
# Find most similar
similarities = [
cosine_similarity(query_embedding, e.embedding)
for e in embeddings
]
most_similar_idx = np.argmax(similarities)
print(f"Most similar to 'AI development': {texts[most_similar_idx]}")
Error Handling
Robust API Calls
from openai import OpenAI, APIError, RateLimitError, APIConnectionError
import time
client = OpenAI()
def call_with_retry(messages, max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return response.choices[0].message.content
except RateLimitError:
wait_time = 2 ** attempt
print(f"Rate limited. Waiting {wait_time}s...")
time.sleep(wait_time)
except APIConnectionError:
print("Connection error. Retrying...")
time.sleep(1)
except APIError as e:
print(f"API error: {e}")
raise
raise Exception("Max retries exceeded")
Best Practices
1. Token Management
import tiktoken
def count_tokens(text, model="gpt-4o-mini"):
encoding = tiktoken.encoding_for_model(model)
return len(encoding.encode(text))
# Count before sending
message_tokens = count_tokens(user_message)
if message_tokens > 4000:
# Truncate or split
pass
2. Cost Optimization
# Use appropriate model
# - gpt-4o-mini for simple tasks
# - gpt-4o for complex reasoning
# Limit max_tokens
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[...],
max_tokens=500 # Limit response length
)
# Use caching for repeated queries
3. Prompt Engineering
# Be specific and clear
messages = [
{
"role": "system",
"content": """You are a Python expert.
- Answer concisely
- Include code examples
- Use markdown formatting"""
},
{
"role": "user",
"content": "How do I read a CSV file?"
}
]
สรุป
OpenAI API Features:
- Chat Completions: หลักในการใช้งาน
- Streaming: Real-time responses
- Function Calling: ให้ AI เรียก functions
- Vision: วิเคราะห์รูปภาพ
- Embeddings: สร้าง vectors
Best Practices:
- Manage tokens และ costs
- Handle errors gracefully
- Use streaming for UX
- Choose right model for task
Remember:
- Start with gpt-4o-mini
- Use structured outputs
- Implement retry logic
- Monitor usage and costs
อ่านเพิ่มเติม:
เขียนโดย
AI Unlocked Team
บทความอื่นๆ ที่น่าสนใจ
วิธีติดตั้ง FFmpeg บน Windows และ Mac: คู่มือฉบับสมบูรณ์
เรียนรู้วิธีติดตั้ง FFmpeg บน Windows และ macOS พร้อมการตั้งค่า PATH อย่างละเอียด เพื่อใช้งานโปรแกรมตัดต่อวิดีโอและเสียงระดับมืออาชีพ
04/12/2568
สร้าง AI-Powered SaaS: จากไอเดียสู่ผลิตภัณฑ์
คู่มือครบวงจรในการสร้าง AI-Powered SaaS ตั้งแต่การวางแผน พัฒนา ไปจนถึง launch และ scale รวมถึง tech stack, pricing และ business model
03/02/2568
AI Security: วิธีใช้ AI อย่างปลอดภัย
เรียนรู้แนวทางการใช้ AI อย่างปลอดภัย ครอบคลุม prompt injection, data privacy, API security และ best practices สำหรับองค์กร
02/02/2568