快速开始
本指南将帮助你快速上手 Google Gemini API。
环境准备
确保已安装 Node.js (18+) 或 Python (3.9+)。
安装 SDK
bash
npm install @google/generative-aibash
pip install google-generativeai获取 API Key
- 访问 Google AI Studio
- 创建新的 API Key
- 妥善保存,切勿泄露
基础调用示例
typescript
import { GoogleGenerativeAI } from '@google/generative-ai'
const genAI = new GoogleGenerativeAI('YOUR_API_KEY')
async function main() {
const model = genAI.getGenerativeModel({ model: 'gemini-pro' })
const prompt = '解释什么是量子计算'
const result = await model.generateContent(prompt)
const response = await result.response
const text = response.text()
console.log(text)
}
main()流式输出
typescript
const result = await model.generateContentStream(prompt)
for await (const chunk of result.stream) {
const chunkText = chunk.text()
process.stdout.write(chunkText)
}下一步
- 学习 提示工程最佳实践
