Định dạng API

Google GenAI SDK

Hướng dẫn dùng Google GenAI SDK với cheapkeyai.shop: generate content, streaming, chat, vision, function calling, embeddings và image/TTS.

Google GenAI-compatible phù hợp cho Gemini SDK, Gemini CLI và các workflow multimodal cần text, ảnh, audio hoặc video trong cùng một request.

Cài đặt

npm
npm install @google/genai

Khởi tạo Client

Client
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
  apiKey: process.env.CHEAPKEYAI_API_KEY,
  httpOptions: {
    baseUrl: "https://cheapkeyai.shop"
  }
});

const response = await ai.models.generateContent({
  model: "gemini-2.5-flash",
  contents: "Viết checklist kiểm thử trước khi deploy."
});

console.log(response.text);

Generate Content

System instruction
const response = await ai.models.generateContent({
  model: "gemini-2.5-flash",
  config: {
    systemInstruction: "Bạn là trợ lý kỹ thuật, trả lời bằng tiếng Việt."
  },
  contents: "Giải thích cache invalidation."
});
Streaming
const stream = await ai.models.generateContentStream({
  model: "gemini-2.5-flash",
  contents: "Viết tài liệu onboarding cho developer mới."
});

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

Chat đa lượt

Chat session
const chat = ai.chats.create({ model: "gemini-2.5-flash" });

await chat.sendMessage({ message: "Tôi đang build docs." });
const answer = await chat.sendMessage({ message: "Gợi ý cấu trúc SEO?" });
console.log(answer.text);

Vision

Image URL
const response = await ai.models.generateContent({
  model: "gemini-2.5-flash",
  contents: [{
    role: "user",
    parts: [
      { text: "Đọc nội dung trong ảnh." },
      { fileData: { fileUri: "https://example.com/image.png", mimeType: "image/png" } }
    ]
  }]
});

Function Calling

Khai báo function trong `config.tools`, để model chọn function, sau đó ứng dụng thực thi và đưa kết quả trở lại conversation. Với tool quan trọng, luôn validate tham số trước khi chạy.

Các endpoint thường dùng

Tính năngDùng choGhi chú
models.generateContentText, chat một lượt, multimodalDễ tích hợp nhất.
models.generateContentStreamTrả kết quả từng phầnPhù hợp UI realtime.
chats.createHội thoại nhiều lượtSDK giữ lịch sử trong session.
embeddingsSearch/RAGChuẩn hóa input trước khi index.
image/TTSẢnh và giọng nóiKiểm tra model và format được hỗ trợ.