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 install @google/genaiKhởi tạo 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
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."
});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
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
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ăng | Dùng cho | Ghi chú |
|---|---|---|
| models.generateContent | Text, chat một lượt, multimodal | Dễ tích hợp nhất. |
| models.generateContentStream | Trả kết quả từng phần | Phù hợp UI realtime. |
| chats.create | Hội thoại nhiều lượt | SDK giữ lịch sử trong session. |
| embeddings | Search/RAG | Chuẩn hóa input trước khi index. |
| image/TTS | Ảnh và giọng nói | Kiểm tra model và format được hỗ trợ. |