Skip to content

快速开始

本指南将帮助你快速上手 Google Gemini API。

环境准备

确保已安装 Node.js (18+) 或 Python (3.9+)。

安装 SDK

bash
npm install @google/generative-ai
bash
pip install google-generativeai

获取 API Key

  1. 访问 Google AI Studio
  2. 创建新的 API Key
  3. 妥善保存,切勿泄露

基础调用示例

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

下一步

最后更新于:

Gemini 中文版博客