Installation
npm install openai
or
yarn add openai
Initializing the Client
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: 'your-shopaikey-api-key',
baseURL: 'https://api.shopaikey.com/v1',
});
Chat Completions
Basic API Call
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Hello!' }
],
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: 'Tell me a long story' }
],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
if (content) {
process.stdout.write(content);
}
}
Vision API (Image Recognition)
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: 'What is in this image? Please describe in detail.'
},
{
type: 'image_url',
image_url: {
url: 'https://example.com/image.png'
}
}
]
}
],
max_tokens: 1000,
});
console.log(completion.choices[0].message.content);
Vision with 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: 'Describe this image'
},
{
type: 'image_url',
image_url: {
url: dataUrl
}
}
]
}
],
});
Function Calling
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: "What's the weather like in Hanoi today?" }
],
tools: [
{
type: 'function',
function: {
name: 'get_weather',
description: 'Get weather information for a location',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City or location name',
},
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);
}
Error Handling
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 || '';
}
API Detail: Create Chat Completion (Stream)
(Create Chat Completion - Stream)
This endpoint is used to generate model responses for a given conversation. Data can be returned in chunks (streaming) for real-time display.
- Method:
POST - URL:
https://api.shopaikey.com/v1/chat/completions
Description
Given a prompt, the model returns one or more predicted completions. This API can also return probabilities of alternative tokens at each position.
- Original docs: OpenAI API Reference - Chat Create
Request Parameters
Header Parameters
Body Parameters (application/json)
Request Example
JSON Body:
{
"model": "gpt-5-mini",
"max_tokens": 1000,
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello"
}
],
"temperature": 1.0,
"stream": true,
"stream_options": {
"include_usage": true
}
}
API Call Example (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."
},
{
"role": "user",
"content": "Hello"
}
]
}'
Response
Status: 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
}
}
API Detail: Chat Vision (Stream)
(Create Chat Vision - Stream)
This endpoint allows sending images along with text prompts to multimodal models (such as GPT-4o, Claude 3.5 Sonnet) for real-time image recognition and description.
- Method:
POST - URL:
https://api.shopaikey.com/v1/chat/completions
Description
Send a prompt that includes both text and image URLs. The model returns a description or answer based on the image content.
- Original docs: OpenAI API Reference - Vision
Request
Headers
Body (application/json)
The most important structure is the messages array. Instead of sending a plain text string (content: "string"), you send an array of content objects (content: array) including text and image_url.
{
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "What is in this image? Please describe in detail."
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.png"
}
}
]
}
],
"stream": true,
"max_tokens": 1000
}
Parameter explanation:
model: Models supporting Vision (e.g.,gpt-4o,gpt-4-turbo,claude-3-5-sonnet-20240620,gemini-1.5-pro).content(in messages):type: "text": The text prompt or question.type: "image_url": Object containing the image URL.url: Direct link to the image (must be publicly accessible) or a Base64 string (data:image/jpeg;base64,...format).
API Call Example (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": "What is in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.png"
}
}
]
}
],
"stream": true
}'
Response
Status: 200 OK
The response is similar to the standard Chat API. If stream: true, data arrives in chunks. Below is a JSON example of a complete response (or final chunk):
{
"id": "chatcmpl-890",
"object": "chat.completion",
"created": 1677652288,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The image shows a beautiful natural landscape with a blue sky..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 120,
"completion_tokens": 50,
"total_tokens": 170
}
}
Responses API
The OpenAI Responses API is used to generate model responses. Supports multi-turn conversations, tool calling, and reasoning.
- Method:
POST - URL:
https://api.shopaikey.com/v1/responses
Request Body
Example
const response = await openai.responses.create({
model: 'gpt-4o',
input: 'Hello!',
instructions: 'You are a helpful assistant.',
});
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": "Hello! How can I help you?"
}
]
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 15,
"total_tokens": 25
}
}
Responses Compaction
Compact long conversations for the Responses API.
- Method:
POST - URL:
https://api.shopaikey.com/v1/responses/compact
Images API
Generate Image
- Method:
POST - URL:
https://api.shopaikey.com/v1/images/generations
const image = await openai.images.generate({
model: 'gpt-image-1',
prompt: 'A small cat wearing a beret standing in an old town',
n: 1,
size: '1024x1024',
quality: 'high',
response_format: 'url',
});
console.log(image.data[0].url);
Edit Image
- Method:
POST - URL:
https://api.shopaikey.com/v1/images/edits - Content-Type:
multipart/form-data
Videos API
Generate Video (OpenAI format)
- Method:
POST - URL:
https://api.shopaikey.com/v1/videos - Content-Type:
multipart/form-data
Get Video Status
- Method:
GET - URL:
https://api.shopaikey.com/v1/videos/{task_id}
Get Video Content
- Method:
GET - URL:
https://api.shopaikey.com/v1/videos/{task_id}/content
Returns video file stream (video/mp4).
Generate Video (Generic format)
- Method:
POST - URL:
https://api.shopaikey.com/v1/video/generations
Get Video Status (Generic format)
- Method:
GET - URL:
https://api.shopaikey.com/v1/video/generations/{task_id}
Embeddings API
- Method:
POST - URL:
https://api.shopaikey.com/v1/embeddings
const embedding = await openai.embeddings.create({
model: 'text-embedding-ada-002',
input: 'Hello world',
});
console.log(embedding.data[0].embedding);
Audio API
Text-to-Speech
- Method:
POST - URL:
https://api.shopaikey.com/v1/audio/speech
const mp3 = await openai.audio.speech.create({
model: 'tts-1',
voice: 'alloy',
input: 'Hello, I am an AI assistant.',
});
Transcription
- Method:
POST - URL:
https://api.shopaikey.com/v1/audio/transcriptions - Content-Type:
multipart/form-data
Translation
- Method:
POST - URL:
https://api.shopaikey.com/v1/audio/translations - Content-Type:
multipart/form-data
Completions API (Legacy)
- Method:
POST - URL:
https://api.shopaikey.com/v1/completions
Rerank API
- Method:
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
- Method:
POST - URL:
https://api.shopaikey.com/v1/moderations
Realtime API (WebSocket)
- Method:
GET(WebSocket upgrade) - URL:
wss://api.shopaikey.com/v1/realtime?model=gpt-4o-realtime-preview
Establish a WebSocket connection for real-time conversations.
List Models
- Method:
GET - URL:
https://api.shopaikey.com/v1/models
const models = await openai.models.list();
console.log(models.data);