API Format

OpenAI Format

How to look up and call a modelFind models by price group, read the input/output pricing table, then configure Claude Code or the OpenAI SDK to call them.

Installation

code
npm install openai

or

code
yarn add openai

Initializing the Client

code
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: 'your-shopaikey-api-key',
  baseURL: 'https://api.shopaikey.com/v1',
});

Chat Completions

Basic API Call

code
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

code
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)

code
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

code
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

code
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

code
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

code
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.

Request Parameters

Header Parameters

NameValueDescription
AuthorizationBearer <Token>Required. Your API authentication token.
Content-Typeapplication/jsonRequired. Format of the request data.
Acceptapplication/json

Body Parameters (application/json)

NameTypeDescription
modelstringID of the model to use (e.g., gpt-5-mini, gpt-4o).
messagesarrayList of messages in the conversation.
max_tokensintegerMaximum number of tokens to generate in the completion.
temperaturenumberSampling temperature (0 to 2). Higher values (e.g., 0.8) make output more random; lower values (e.g., 0.2) make it more deterministic.
streambooleanIf true, data is sent as server-sent events.
stream_optionsobjectAdditional streaming options, e.g., { "include_usage": true } to receive token usage info.

Request Example

JSON Body:

code
{
  "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)

code
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

code
{
  "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.

Request

Headers

NameValueRequiredDescription
AuthorizationBearer <Token>YesYour API authentication token.
Content-Typeapplication/jsonYesFormat of the request data.
Acceptapplication/jsonNo

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.

code
{
  "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)

code
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):

code
{
  "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

ParameterTypeDescription
modelstringRequired. Model ID
inputstring/arrayInput content
instructionsstringInstructions for the model
max_output_tokensintegerMaximum output tokens
temperaturenumberSampling temperature
top_pnumberNucleus sampling parameter
streambooleanStream response
toolsarrayList of tools
tool_choicestring/objectTool choice
reasoningobjectReasoning configuration (effort: low/medium/high)
previous_response_idstringPrevious response ID (multi-turn)
truncationstringTruncation mode (auto/disabled)

Example

code
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

code
{
  "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
ParameterTypeDescription
modelstringRequired. Model ID
inputstring/arrayContent to compact
instructionsstringCompaction instructions
previous_response_idstringPrevious response ID

Images API

Generate Image

  • Method: POST
  • URL: https://api.shopaikey.com/v1/images/generations
code
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);
ParameterTypeDescription
modelstringImage generation model (dall-e-2, dall-e-3, gpt-image-1)
promptstringRequired. Description of the image to create
nintegerNumber of images (1-10)
sizestringOutput image size
qualitystringImage quality
backgroundstringImage background (transparent/opaque/auto)
stylestringImage style
response_formatstringResponse format (url/b64_json)

Edit Image

  • Method: POST
  • URL: https://api.shopaikey.com/v1/images/edits
  • Content-Type: multipart/form-data
ParameterTypeDescription
imagefileRequired. Original image to edit
promptstringRequired. Edit description
maskfilePNG mask image for edit area
modelstringImage editing model
nstringNumber of output images
sizestringSize (256x256, 512x512, 1024x1024)

Videos API

Generate Video (OpenAI format)

  • Method: POST
  • URL: https://api.shopaikey.com/v1/videos
  • Content-Type: multipart/form-data
ParameterTypeDescription
modelstringModel name (e.g., sora-2)
promptstringVideo description prompt
secondsstringGeneration duration in seconds
input_referencefileReference image file

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
ParameterTypeDescription
modelstringModel ID (e.g., kling-v1)
promptstringDescription prompt
imagestringInput image (URL or Base64)
durationnumberVideo duration (seconds)
widthintegerVideo width
heightintegerVideo height
fpsintegerFrame rate
seedintegerRandom seed
nintegerNumber of videos

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
code
const embedding = await openai.embeddings.create({
  model: 'text-embedding-ada-002',
  input: 'Hello world',
});

console.log(embedding.data[0].embedding);
ParameterTypeDescription
modelstringRequired. Model ID (e.g., text-embedding-ada-002)
inputstring/arrayRequired. Text to embed
encoding_formatstringFormat (float/base64)
dimensionsintegerOutput vector dimensions

Audio API

Text-to-Speech

  • Method: POST
  • URL: https://api.shopaikey.com/v1/audio/speech
code
const mp3 = await openai.audio.speech.create({
  model: 'tts-1',
  voice: 'alloy',
  input: 'Hello, I am an AI assistant.',
});
ParameterTypeDescription
modelstringRequired. TTS model (e.g., tts-1)
inputstringRequired. Text to convert (max 4096 characters)
voicestringRequired. Voice (alloy/echo/fable/onyx/nova/shimmer)
response_formatstringFormat (mp3/opus/aac/flac/wav/pcm)
speednumberSpeed (0.25 - 4.0)

Transcription

  • Method: POST
  • URL: https://api.shopaikey.com/v1/audio/transcriptions
  • Content-Type: multipart/form-data
ParameterTypeDescription
filefileRequired. Audio file
modelstringRequired. Model (e.g., whisper-1)
languagestringISO-639-1 language code
response_formatstringFormat (json/text/srt/verbose_json/vtt)

Translation

  • Method: POST
  • URL: https://api.shopaikey.com/v1/audio/translations
  • Content-Type: multipart/form-data
ParameterTypeDescription
filefileRequired. Audio file
modelstringRequired. Model (e.g., whisper-1)

Completions API (Legacy)

  • Method: POST
  • URL: https://api.shopaikey.com/v1/completions
ParameterTypeDescription
modelstringRequired. Model ID
promptstring/arrayRequired. Input prompt
max_tokensintegerMaximum tokens
temperaturenumberSampling temperature
streambooleanStream response

Rerank API

  • Method: POST
  • URL: https://api.shopaikey.com/v1/rerank
code
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,
  }),
});
ParameterTypeDescription
modelstringRequired. Rerank model
querystringRequired. Query text
documentsarrayRequired. List of documents
top_nintegerReturn top N results
return_documentsbooleanReturn document content

Moderations API

  • Method: POST
  • URL: https://api.shopaikey.com/v1/moderations
ParameterTypeDescription
inputstring/arrayRequired. Content to moderate
modelstringModeration model (e.g., text-moderation-latest)

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.

ParameterTypeDescription
modelquery stringModel to use (e.g., gpt-4o-realtime-preview)

List Models

  • Method: GET
  • URL: https://api.shopaikey.com/v1/models
code
const models = await openai.models.list();
console.log(models.data);

In this section · API Format