Định dạng API

Google GenAI SDK

Cài đặt

code
npm install @google/genai

hoặc

code
yarn add @google/genai

Khởi tạo Client

code
import { GoogleGenAI } from '@google/genai';

const ai = new GoogleGenAI({
  apiKey: 'your-shopaikey-api-key',
  httpOptions: {
    baseUrl: 'https://api.shopaikey.com',
  },
});

Tạo nội dung cơ bản

code
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Xin chào! Bạn là ai?',
});

console.log(response.text);

Sử dụng System Instruction

code
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  config: {
    systemInstruction: 'Bạn là một trợ lý AI chuyên về lập trình.',
  },
  contents: 'Giải thích về async/await trong JavaScript',
});

console.log(response.text);

Streaming Response

code
const response = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: 'Kể cho tôi một câu chuyện dài',
});

for await (const chunk of response) {
  if (chunk.text) {
    process.stdout.write(chunk.text);
  }
}

Hội thoại đa lượt (Chat)

code
const chat = ai.chats.create({
  model: 'gemini-2.5-flash',
  config: {
    systemInstruction: 'Bạn là một trợ lý thân thiện.',
  },
});

const response1 = await chat.sendMessage({ message: 'Tôi tên là Huy' });
console.log(response1.text);

const response2 = await chat.sendMessage({ message: 'Bạn nhớ tên tôi không?' });
console.log(response2.text);

Chat Streaming

code
const chat = ai.chats.create({
  model: 'gemini-2.5-flash',
});

const response = await chat.sendMessageStream({ message: 'Viết một bài thơ' });

for await (const chunk of response) {
  if (chunk.text) {
    process.stdout.write(chunk.text);
  }
}

Vision API (Nhận diện hình ảnh)

Từ URL

code
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    {
      role: 'user',
      parts: [
        { text: 'Bức ảnh này có nội dung gì? Hãy mô tả chi tiết.' },
        {
          fileData: {
            fileUri: 'https://example.com/image.png',
            mimeType: 'image/png',
          },
        },
      ],
    },
  ],
});

console.log(response.text);

Từ Base64

code
const fs = require('fs');

const imageBuffer = fs.readFileSync('./image.jpg');
const base64Image = imageBuffer.toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    {
      role: 'user',
      parts: [
        { text: 'Mô tả hình ảnh này' },
        {
          inlineData: {
            data: base64Image,
            mimeType: 'image/jpeg',
          },
        },
      ],
    },
  ],
});

console.log(response.text);

Video API (Đọc video)

Gemini nhận video làm input: model xem theo trục thời gian nên trả lời được những câu hỏi phụ thuộc diễn biến, không chỉ nội dung một khung hình.

Từ URL

Cách gửi qua URL cần model Gemini 3 (gemini-3-flash-preview, gemini-3-pro-preview). Với gemini-2.5-flash, hãy dùng base64 ở dưới.

code
const response = await ai.models.generateContent({
  model: 'gemini-3-flash-preview',
  contents: [
    {
      role: 'user',
      parts: [
        { text: 'Video này hướng dẫn điều gì? Tóm tắt theo từng bước.' },
        {
          fileData: {
            fileUri: 'https://example.com/guide.mp4',
            mimeType: 'video/mp4',
          },
        },
      ],
    },
  ],
});

console.log(response.text);

Từ Base64

code
const fs = require('fs');

const base64Video = fs.readFileSync('./clip.mp4').toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-3-flash-preview',
  contents: [
    {
      role: 'user',
      parts: [
        { text: 'Mô tả những gì xảy ra trong video, kèm mốc thời gian.' },
        {
          inlineData: {
            data: base64Video,
            mimeType: 'video/mp4',
          },
        },
      ],
    },
  ],
});

console.log(response.text);

Chi phí token

Video tốn 70 token cho mỗi giây, tách riêng trong usageMetadata.promptTokensDetails với modality: "VIDEO". Một video 85 giây tiêu tốn khoảng 6.000 token input, vì vậy hãy cắt bớt phần không cần thiết trước khi gửi.

Lưu ý khi dùng chuẩn OpenAI

Trên /v1/chat/completions, video phải gửi bằng part image_url (URL trực tiếp hoặc data URI data:video/mp4;base64,...). Các part video_url và input_video sẽ bị bỏ qua: request vẫn trả về 200 và vẫn bị tính phí, nhưng model không thấy video và có thể trả lời như chưa nhận được gì. Nếu cần đọc video, ưu tiên dùng định dạng Gemini native ở trên.

Audio API (Đọc âm thanh)

Gemini nhận file âm thanh làm input: dùng để ghi lại lời nói, tóm tắt cuộc họp, trả lời câu hỏi về nội dung đã nghe, hoặc nhận biết ngôn ngữ và giọng điệu.

Từ URL

Cách gửi qua URL cần model Gemini 3 (gemini-3-flash-preview, gemini-3-pro-preview). Với gemini-2.5-flash, hãy dùng base64 ở dưới.

code
const response = await ai.models.generateContent({
  model: 'gemini-3-flash-preview',
  contents: [
    {
      role: 'user',
      parts: [
        { text: 'Ghi lại nội dung đoạn ghi âm này bằng tiếng Việt có dấu.' },
        {
          fileData: {
            fileUri: 'https://example.com/meeting.mp3',
            mimeType: 'audio/mp3',
          },
        },
      ],
    },
  ],
});

console.log(response.text);

Từ Base64

code
const fs = require('fs');

const base64Audio = fs.readFileSync('./record.mp3').toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-3-flash-preview',
  contents: [
    {
      role: 'user',
      parts: [
        { text: 'Tóm tắt các quyết định được đưa ra trong đoạn ghi âm.' },
        {
          inlineData: {
            data: base64Audio,
            mimeType: 'audio/mp3',
          },
        },
      ],
    },
  ],
});

console.log(response.text);

Định dạng hỗ trợ

audio/mp3, audio/mpeg, audio/wav, audio/aac, audio/ogg, audio/flac.

Chọn định dạng nén (mp3) hay không nén (wav) không làm thay đổi chi phí: cùng một nội dung sẽ cho ra promptTokenCount bằng nhau.

Chi phí token

Âm thanh tốn 32 token cho mỗi giây, tách riêng trong usageMetadata.promptTokensDetails với modality: "AUDIO". Một đoạn ghi âm 5 phút tiêu tốn khoảng 9.600 token input.

Lưu ý khi đọc promptTokensDetails: với file nén, phần token của âm thanh có thể bị gộp sai sang modality: "TEXT". Tổng promptTokenCount vẫn đúng, nên hãy dựa vào tổng này khi cần đối chiếu chi phí.

Lưu ý về độ trễ

Model gemini-3-pro-preview cho kết quả chính xác nhất nhưng xử lý âm thanh rất chậm. Với các tác vụ ghi lại lời nói thông thường, gemini-3-flash-preview nhanh hơn nhiều lần và độ chính xác đã đủ dùng.

Function Calling

code
import { Type } from '@google/genai';

const getWeather = {
  name: 'get_weather',
  description: 'Lấy thông tin thời tiết tại một địa điểm',
  parameters: {
    type: Type.OBJECT,
    properties: {
      location: {
        type: Type.STRING,
        description: 'Tên thành phố hoặc địa điểm',
      },
      unit: {
        type: Type.STRING,
        enum: ['celsius', 'fahrenheit'],
      },
    },
    required: ['location'],
  },
};

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Thời tiết ở Hà Nội hôm nay như thế nào?',
  config: {
    tools: [{ functionDeclarations: [getWeather] }],
  },
});

const functionCall = response.functionCalls?.[0];
if (functionCall) {
  console.log('Function:', functionCall.name);
  console.log('Args:', functionCall.args);
}

Cấu hình nâng cao

code
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Viết một đoạn code Python',
  config: {
    maxOutputTokens: 2048,
    temperature: 0.7,
    topP: 0.9,
    topK: 40,
  },
});

Xử lý lỗi

code
try {
  const response = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: 'Hello',
  });
  console.log(response.text);
} catch (error) {
  console.error('Error:', error.message);
  if (error.status) {
    console.error('Status:', error.status);
  }
}

TypeScript Support

code
import { GoogleGenAI, GenerateContentResponse } from '@google/genai';

const ai = new GoogleGenAI({
  apiKey: process.env.SHOPAIKEY_API_KEY!,
  httpOptions: {
    baseUrl: 'https://api.shopaikey.com',
  },
});

async function chat(message: string): Promise<string> {
  const response: GenerateContentResponse = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: message,
  });

  return response.text || '';
}

Chi tiết API: Google Gemini (Native Format)

(generateContent / streamGenerateContent)

API này cho phép gửi yêu cầu đến các mô hình Gemini bằng định dạng gốc của Google.

  • Phương thức: POST
  • URL generateContent: https://api.shopaikey.com/v1beta/models/{model}:generateContent
  • URL streamGenerateContent: https://api.shopaikey.com/v1beta/models/{model}:streamGenerateContent

Yêu cầu (Request)

Headers

TênGiá trịBắt buộcMô tả
AuthorizationBearer <Token>CóToken xác thực API của bạn.
Content-Typeapplication/jsonCóĐịnh dạng dữ liệu gửi đi.

Query Parameters

TênGiá trịBắt buộcMô tả
key<API Key>CóAPI key của bạn (SDK tự thêm).

Body (application/json)

code
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Xin chào, hãy giới thiệu về bạn."
        }
      ]
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 1024,
    "temperature": 1.0
  }
}

Các tham số chính:

  • contents (array): Danh sách nội dung hội thoại.
    • role: user hoặc model.
    • parts: Mảng các phần nội dung (text, inlineData, fileData).
  • generationConfig (object): Cấu hình sinh nội dung.
    • maxOutputTokens: Số token tối đa.
    • temperature: Độ ngẫu nhiên (0 - 2).
    • topP, topK: Tham số sampling.
  • systemInstruction (object): System prompt.
  • tools (array): Danh sách tools cho function calling.

Ví dụ gọi API (cURL)

code
curl -X POST 'https://api.shopaikey.com/v1beta/models/gemini-2.5-flash:generateContent?key=YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Xin chào, hãy giới thiệu về bạn."
        }
      ]
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 1024
  }
}'

Streaming (cURL)

code
curl -X POST 'https://api.shopaikey.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=YOUR_API_KEY&alt=sse' \
-H 'Content-Type: application/json' \
-d '{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Kể cho tôi một câu chuyện dài."
        }
      ]
    }
  ]
}'

Phản hồi (Response)

Trạng thái: 200 OK

code
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Xin chào! Tôi là Gemini, một mô hình ngôn ngữ AI được phát triển bởi Google."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 10,
    "candidatesTokenCount": 25,
    "totalTokenCount": 35
  }
}

Lưu ý quan trọng

  • Base URL: Khi dùng SDK, cần set httpOptions.baseUrl thành https://api.shopaikey.com
  • API Key: Sử dụng API key từ ShopAIKey, không cần Google Cloud API key
  • Models: Hỗ trợ tất cả Gemini models có sẵn (gemini-2.5-flash, gemini-2.5-pro, gemini-2.0-flash, v.v.)
  • Tương thích: Hoàn toàn tương thích với Google GenAI SDK chính thức

Các Endpoint hỗ trợ

Liệt kê Models

  • Phương thức: GET
  • URL: https://api.shopaikey.com/v1beta/models
code
const models = await ai.models.list();
for await (const model of models) {
  console.log(model.name);
}

Generate Content

  • Phương thức: POST
  • URL: https://api.shopaikey.com/v1beta/models/{model}:generateContent

Stream Generate Content

  • Phương thức: POST
  • URL: https://api.shopaikey.com/v1beta/models/{model}:streamGenerateContent
code
const stream = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: 'Kể cho tôi một câu chuyện dài',
});

for await (const chunk of stream) {
  process.stdout.write(chunk.text);
}

Embeddings

  • Phương thức: POST
  • URL: https://api.shopaikey.com/v1/engines/{model}/embeddings
Tên tham sốKiểuMô tả
modelstringBắt buộc. ID model embedding
inputstring/arrayBắt buộc. Văn bản cần nhúng
encoding_formatstringĐịnh dạng (float/base64)
dimensionsintegerSố chiều vector đầu ra

Sinh ảnh (Image Generation)

Sử dụng responseModalities trong generationConfig:

code
const response = await ai.models.generateContent({
  model: 'gemini-2.0-flash-exp',
  contents: 'Vẽ một con mèo phong cách pixel art',
  config: {
    responseModalities: ['TEXT', 'IMAGE'],
    imageConfig: {
      aspectRatio: '16:9',
      imageSize: '1024x1024',
    },
  },
});

Sinh âm thanh TTS (Audio Generation)

Sử dụng responseModalities: ['AUDIO'] trong generationConfig:

code
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Đọc đoạn văn này bằng giọng tự nhiên.',
  config: {
    responseModalities: ['AUDIO'],
    speechConfig: {
      voiceConfig: {
        prebuiltVoiceConfig: {
          voiceName: 'Kore',
        },
      },
    },
  },
});

Bài cùng nhóm · Định dạng API