Cài đặt
npm install openai
hoặc
yarn add openai
Khởi tạo Client
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: 'your-shopaikey-api-key',
baseURL: 'https://api.shopaikey.com/v1',
});
Chat Completions
Gọi API cơ bản
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Xin chào!' }
],
max_tokens: 1000,
temperature: 1.0,
});
console.log(completion.choices[0].message.content);
Streaming Response
const stream = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Kể cho tôi một câu chuyện dài' }
],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
if (content) {
process.stdout.write(content);
}
}
Vision API (Nhận diện hình ảnh)
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: 'Bức ảnh này có nội dung gì? Hãy mô tả chi tiết.'
},
{
type: 'image_url',
image_url: {
url: 'https://example.com/image.png'
}
}
]
}
],
max_tokens: 1000,
});
console.log(completion.choices[0].message.content);
Vision với Base64 Image
const fs = require('fs');
const imageBuffer = fs.readFileSync('./image.jpg');
const base64Image = imageBuffer.toString('base64');
const dataUrl = `data:image/jpeg;base64,${base64Image}`;
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: 'Mô tả hình ảnh này'
},
{
type: 'image_url',
image_url: {
url: dataUrl
}
}
]
}
],
});
Function Calling
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Thời tiết ở Hà Nội hôm nay như thế nào?' }
],
tools: [
{
type: 'function',
function: {
name: 'get_weather',
description: 'Lấy thông tin thời tiết tại một địa điểm',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'Tên thành phố hoặc địa điểm',
},
unit: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
},
},
required: ['location'],
},
},
},
],
tool_choice: 'auto',
});
const message = completion.choices[0].message;
if (message.tool_calls) {
console.log('Function calls:', message.tool_calls);
}
Xử lý lỗi
try {
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }],
});
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error('API Error:', error.status);
console.error('Message:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
TypeScript Support
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.SHOPAIKEY_API_KEY!,
baseURL: 'https://api.shopaikey.com/v1',
});
async function chat(message: string): Promise<string> {
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: message }],
});
return completion.choices[0].message.content || '';
}
Chi tiết API: Tạo trò chuyện (Stream)
(Create Chat Completion - Stream)
Endpoint này được sử dụng để tạo phản hồi từ mô hình cho một cuộc hội thoại đã cho. Dữ liệu có thể được trả về từng phần (streaming) để hiển thị thời gian thực.
- Phương thức (Method):
POST - URL:
https://api.shopaikey.com/v1/chat/completions
Mô tả
Đưa ra một lời nhắc (prompt), mô hình sẽ trả về một hoặc nhiều dự đoán hoàn thành. API này cũng có thể trả về xác suất của các token thay thế tại mỗi vị trí.
- Tài liệu gốc: OpenAI API Reference - Chat Create
Thông số Yêu cầu (Request Parameters)
Header Parameters
Body Parameters (application/json)
Ví dụ Yêu cầu (Request Example)
JSON Body:
{
"model": "gpt-5-mini",
"max_tokens": 1000,
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Xin chào"
}
],
"temperature": 1.0,
"stream": true,
"stream_options": {
"include_usage": true
}
}
Ví dụ gọi API (cURL)
curl --location --request POST 'https://api.shopaikey.com/v1/chat/completions' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <YOUR_TOKEN_HERE>' \
--header 'Content-Type: application/json' \
--data-raw '{
"model": "gpt-5-mini",
"max_tokens": 1000,
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
]
}
Phản hồi (Response)
Trạng thái: 200 OK
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "\n\nHello there, how may I assist you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}
Chi tiết API: Tạo trò chuyện nhận diện hình ảnh (Stream)
(Create Chat Vision - Stream)
Endpoint này cho phép bạn gửi hình ảnh kèm theo câu hỏi văn bản đến các mô hình đa phương thức (như GPT-4o, Claude 3.5 Sonnet) để nhận diện và mô tả nội dung hình ảnh theo thời gian thực.
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/chat/completions
Mô tả
Gửi một lời nhắc bao gồm cả văn bản và URL hình ảnh. Mô hình sẽ trả về mô tả hoặc câu trả lời dựa trên nội dung hình ảnh đó.
- Tài liệu gốc: OpenAI API Reference - Vision
Yêu cầu (Request)
Headers
Body (application/json)
Cấu trúc quan trọng nhất là mảng messages. Thay vì chỉ gửi chuỗi văn bản (content: "string"), bạn cần gửi một mảng các đối tượng nội dung (content: array) bao gồm text và image_url.
{
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Bức ảnh này có nội dung gì? Hãy mô tả chi tiết."
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.png"
}
}
]
}
],
"stream": true,
"max_tokens": 1000
}
Giải thích tham số:
model: Các mô hình hỗ trợ Vision (ví dụ:gpt-4o,gpt-4-turbo,claude-3-5-sonnet-20240620,gemini-1.5-pro).content(trong messages):type: "text": Phần câu hỏi hoặc lời nhắc văn bản.type: "image_url": Đối tượng chứa đường dẫn hình ảnh.url: Đường dẫn trực tiếp đến ảnh (phải công khai truy cập được) hoặc chuỗi Base64 (định dạngdata:image/jpeg;base64,...).
Ví dụ gọi API (cURL)
curl --location --request POST 'https://api.shopaikey.com/v1/chat/completions' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <YOUR_TOKEN_HERE>' \
--header 'Content-Type: application/json' \
--data-raw '{
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Trong ảnh này có những gì?"
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.png"
}
}
]
}
],
"stream": true
}'
Phản hồi (Response)
Trạng thái: 200 OK
Phản hồi trả về tương tự như API Chat thông thường. Nếu stream: true, dữ liệu sẽ về từng chunk. Dưới đây là ví dụ JSON của một phản hồi hoàn chỉnh (hoặc chunk cuối):
{
"id": "chatcmpl-890",
"object": "chat.completion",
"created": 1677652288,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Trong ảnh là một phong cảnh thiên nhiên tuyệt đẹp với bầu trời xanh..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 120,
"completion_tokens": 50,
"total_tokens": 170
}
}
Responses API
OpenAI Responses API dùng để tạo phản hồi mô hình. Hỗ trợ hội thoại nhiều lượt, gọi công cụ, suy luận.
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/responses
Request Body
Ví dụ
const response = await openai.responses.create({
model: 'gpt-4o',
input: 'Xin chào!',
instructions: 'Bạn là trợ lý hữu ích.',
});
console.log(response.output[0].content[0].text);
Response
{
"id": "resp_abc123",
"object": "response",
"created_at": 1700000000,
"status": "completed",
"model": "gpt-4o",
"output": [
{
"type": "message",
"id": "msg_abc123",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Xin chào! Tôi có thể giúp gì cho bạn?"
}
]
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 15,
"total_tokens": 25
}
}
Responses Compaction
Nén hội thoại dài (compaction) cho Responses API.
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/responses/compact
Images API
Tạo ảnh
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/images/generations
const image = await openai.images.generate({
model: 'gpt-image-1',
prompt: 'Một chú mèo nhỏ đội mũ nồi đứng giữa phố cổ',
n: 1,
size: '1024x1024',
quality: 'high',
response_format: 'url',
});
console.log(image.data[0].url);
Chỉnh sửa ảnh
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/images/edits - Content-Type:
multipart/form-data
Videos API
Tạo video (OpenAI format)
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/videos - Content-Type:
multipart/form-data
Lấy trạng thái video
- Phương thức:
GET - URL:
https://api.shopaikey.com/v1/videos/{task_id}
Lấy nội dung video
- Phương thức:
GET - URL:
https://api.shopaikey.com/v1/videos/{task_id}/content
Trả về luồng tệp video (video/mp4).
Tạo video (Generic format)
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/video/generations
Lấy trạng thái video (Generic format)
- Phương thức:
GET - URL:
https://api.shopaikey.com/v1/video/generations/{task_id}
Embeddings API
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/embeddings
const embedding = await openai.embeddings.create({
model: 'text-embedding-ada-002',
input: 'Xin chào thế giới',
});
console.log(embedding.data[0].embedding);
Audio API
Text-to-Speech
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/audio/speech
const mp3 = await openai.audio.speech.create({
model: 'tts-1',
voice: 'alloy',
input: 'Xin chào, tôi là trợ lý AI.',
});
Phiên âm (Transcription)
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/audio/transcriptions - Content-Type:
multipart/form-data
Dịch âm thanh (Translation)
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/audio/translations - Content-Type:
multipart/form-data
Completions API (Legacy)
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/completions
Rerank API
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/rerank
const result = await fetch('https://api.shopaikey.com/v1/rerank', {
method: 'POST',
headers: {
'Authorization': 'Bearer <your-api-key>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'rerank-english-v2.0',
query: 'What is machine learning?',
documents: ['ML is a subset of AI', 'Cooking recipes', 'Deep learning models'],
top_n: 2,
}),
});
Moderations API
- Phương thức:
POST - URL:
https://api.shopaikey.com/v1/moderations
Realtime API (WebSocket)
- Phương thức:
GET(WebSocket upgrade) - URL:
wss://api.shopaikey.com/v1/realtime?model=gpt-4o-realtime-preview
Thiết lập kết nối WebSocket cho hội thoại thời gian thực.
Liệt kê Models
- Phương thức:
GET - URL:
https://api.shopaikey.com/v1/models
const models = await openai.models.list();
console.log(models.data);