本快速入门介绍了如何通过您选择的 SDK 开始使用 Gemini API。
前提条件
Python
在 Google AI 上查看 | 在 Google Colab 中运行 | 在 GitHub 上查看笔记本 |
如需在本地完成本快速入门,请确保您的开发环境满足以下要求:
- Python 3.9 及更高版本
- 安装了
jupyter
,用于运行笔记本。
Go
本快速入门假定您熟悉使用 Go 构建应用。
为完成本快速入门,请确保您的开发环境满足以下要求:
- Go 1.20 及更高版本
Node.js
本快速入门假定您熟悉使用 Node.js 构建应用。
为完成本快速入门,请确保您的开发环境满足以下要求:
- Node.js 18 版及更高版本
- npm
网站
本快速入门假定您熟悉使用 JavaScript 开发 Web 应用的方法。本指南独立于框架。
为完成本快速入门,请确保您的开发环境满足以下要求:
- (可选)Node.js
- 现代网络浏览器
Dart (Flutter)
本快速入门假定您熟悉使用 Dart 构建应用。
为完成本快速入门,请确保您的开发环境满足以下要求:
- Dart 3.2.0 及更高版本
Swift
本快速入门假定您熟悉使用 Xcode 开发 Swift 应用的方法。
如需完成本快速入门,请确保您的开发环境和 Swift 应用满足以下要求:
- Xcode 15.0 或更高版本
- 您的 Swift 应用必须以 iOS 15 或更高版本或者 macOS 12 或更高版本为目标平台。
Android
本快速入门假定您已熟悉如何使用 Android Studio 开发 Android 应用。
为完成本快速入门,请确保您的开发环境和 Android 应用满足以下要求:
- Android Studio(最新版本)
- 您的 Android 应用必须以 API 级别 21 或更高级别为目标平台。
设置您的 API 密钥
您需要 API 密钥才能使用 Gemini API。如果您还没有密钥,请在 Google AI Studio 中创建密钥。
然后配置密钥。
Python
强烈建议您不要将 API 密钥签入版本控制系统。本快速入门假定您以环境变量的形式访问 API 密钥。
将您的 API 密钥分配给环境变量:
export API_KEY=<YOUR_API_KEY>
Go
强烈建议您不要将 API 密钥签入版本控制系统。本快速入门假定您以环境变量的形式访问 API 密钥。
将您的 API 密钥分配给环境变量:
export API_KEY=<YOUR_API_KEY>
Node.js
强烈建议您不要将 API 密钥签入版本控制系统。本快速入门假定您以环境变量的形式访问 API 密钥。
将您的 API 密钥分配给环境变量:
export API_KEY=<YOUR_API_KEY>
网站
强烈建议您不要将 API 密钥签入版本控制系统。相反,您应该在初始化模型之前将 API 密钥传递给应用。
本快速入门假定您以全局常量的形式访问 API 密钥。
Dart (Flutter)
强烈建议您不要将 API 密钥签入版本控制系统。本快速入门假定您将 API 密钥作为进程环境变量进行访问。如果您要开发 Flutter 应用,可以使用 String.fromEnvironment
并将 --dart-define=API_KEY=$API_KEY
传递给 flutter build
或 flutter run
,以使用 API 密钥进行编译,因为运行应用时的进程环境会有所不同。
Swift
强烈建议您不要将 API 密钥签入版本控制系统。一种替代方法是将其存储在 GenerativeAI-Info.plist
文件中,然后从 .plist
文件中读取 API 密钥。请务必将此 .plist
文件放在应用的根文件夹中,并将其从版本控制中排除。
enum APIKey {
// Fetch the API key from `GenerativeAI-Info.plist`
static var `default`: String {
guard let filePath = Bundle.main.path(forResource: "GenerativeAI-Info", ofType: "plist")
else {
fatalError("Couldn't find file 'GenerativeAI-Info.plist'.")
}
let plist = NSDictionary(contentsOfFile: filePath)
guard let value = plist?.object(forKey: "API_KEY") as? String else {
fatalError("Couldn't find key 'API_KEY' in 'GenerativeAI-Info.plist'.")
}
if value.starts(with: "_") {
fatalError(
"Follow the instructions at https://ai.google.dev/tutorials/setup to get an API key."
)
}
return value
}
}
Android
强烈建议您不要将 API 密钥签入版本控制系统。请改为将 API 密钥存储在 local.properties
文件中(该文件位于项目的根目录中,但不在版本控制系统中),然后使用 Android 版 Secrets Gradle 插件将 API 密钥作为 build 配置变量读取。
Kotlin:
// Access your API key as a Build Configuration variable
val apiKey = BuildConfig.apiKey
Java:
// Access your API key as a Build Configuration variable
String apiKey = BuildConfig.apiKey;
如果您想查看 Secrets Gradle 插件的实现,可以查看此 SDK 的示例应用,或者使用 Android Studio Iguana 的最新预览,其中包含 Gemini API Starter 模板(包含 local.properties
文件,以帮助您上手)。
安装 SDK
Python
适用于 Gemini API 的 Python SDK 包含在 google-generativeai
软件包中。使用 pip 安装依赖项:
pip install -q -U google-generativeai
Go
如需在您自己的应用中使用 Gemini API,您需要在模块目录中对 Go SDK 软件包执行 get
操作:
go get github.com/google/generative-ai-go
Node.js
如需在您自己的应用中使用 Gemini API,您需要安装 Node.js 版 GoogleGenerativeAI
软件包:
npm install @google/generative-ai
网站
如需在您自己的 Web 应用中使用 Gemini API,请导入 @google/generative-ai
:
<script type="importmap">
{
"imports": {
"@google/generative-ai": "https://esm.run/@google/generative-ai"
}
}
</script>
Dart (Flutter)
如需在您自己的应用中使用 Gemini API,您需要将 google_generative_ai
软件包 add
到您的 Dart 或 Flutter 应用:
Dart:
dart pub add google_generative_ai
Flutter:
flutter pub add google_generative_ai
Swift
如需在您自己的 Swift 应用中使用 Gemini API,请将 GoogleGenerativeAI
软件包添加到您的应用中:
在 Xcode 的项目导航器中,右键点击您的项目。
从上下文菜单中选择添加软件包。
在 Add Packages 对话框中,将软件包网址粘贴到搜索栏:
none https://github.com/google/generative-ai-swift
点击 Add Package(添加软件包)。Xcode 现在会将
GoogleGenerativeAI
软件包添加到您的项目中。
Android
在您的模块(应用级)Gradle 配置文件(例如
<project>/<app-module>/build.gradle.kts
)中,添加 Google AI SDK for Android 的依赖项:Kotlin:
dependencies { // add the dependency for the Google AI client SDK for Android implementation("com.google.ai.client.generativeai:generativeai:0.3.0") }
Java:
对于 Java,您需要添加两个额外的库。
dependencies { // add the dependency for the Google AI client SDK for Android implementation("com.google.ai.client.generativeai:generativeai:0.3.0") // Required for one-shot operations (to use `ListenableFuture` from Guava Android) implementation("com.google.guava:guava:31.0.1-android") // Required for streaming operations (to use `Publisher` from Reactive Streams) implementation("org.reactivestreams:reactive-streams:1.0.4") }
将您的 Android 项目与 Gradle 文件同步。
初始化生成模型
Python
您需要先导入并初始化生成模型,然后才能进行任何 API 调用。
import google.generativeai as genai
genai.configure(api_key=os.environ["API_KEY"])
model = genai.GenerativeModel('gemini-pro')
Go
您需要先导入并初始化生成模型,然后才能进行任何 API 调用。
import "github.com/google/generative-ai-go/genai"
import "google.golang.org/api/option"
ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
// For text-only input, use the gemini-pro model
model := client.GenerativeModel("gemini-pro")
Node.js
您需要先导入并初始化生成模型,然后才能进行任何 API 调用。
const { GoogleGenerativeAI } = require("@google/generative-ai");
// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
// ...
// For text-only input, use the gemini-pro model
const model = genAI.getGenerativeModel({ model: "gemini-pro"});
// ...
网站
您需要先导入并初始化生成模型,然后才能进行任何 API 调用。
<html>
<body>
<!-- ... Your HTML and CSS -->
<!-- Import @google/generative-ai, as shown above. -->
<script type="module">
import { GoogleGenerativeAI } from "@google/generative-ai";
// Fetch your API_KEY
const API_KEY = "...";
// Access your API key (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(API_KEY);
// ...
// For text-only input, use the gemini-pro model
const model = genAI.getGenerativeModel({ model: "gemini-pro"});
// ...
</script>
</body>
</html>
Dart (Flutter)
您需要先导入并初始化生成模型,然后才能进行任何 API 调用。
import 'package:google_generative_ai/google_generative_ai.dart';
// Access your API key as an environment variable (see "Set up your API key" above)
final apiKey = Platform.environment['API_KEY'];
if (apiKey == null) {
print('No \$API_KEY environment variable');
exit(1);
}
// For text-only input, use the gemini-pro model
final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
Swift
您需要先初始化生成模型,然后才能进行任何 API 调用。
导入
GoogleAI
模块:import GoogleGenerativeAI
初始化生成模型:
// For text-only input, use the gemini-pro model // Access your API key from your on-demand resource .plist file (see "Set up your API key" above) let model = GenerativeModel(name: "gemini-pro", apiKey: APIKey.default)
Android
您需要先初始化 GenerativeModel
对象,然后才能进行任何 API 调用:
Kotlin:
val generativeModel = GenerativeModel(
// For text-only input, use the gemini-pro model
modelName = "gemini-pro",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey
)
Java:
对于 Java,您还需要初始化 GenerativeModelFutures
对象。
// For text-only input, use the gemini-pro model
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-pro",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
/* apiKey */ BuildConfig.apiKey);
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
生成文本
Python
response = model.generate_content("Write a story about a magic backpack.")
print(response.text)
Go
resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
log.Fatal(err)
}
Node.js
async function run() {
const prompt = "Write a story about a magic backpack."
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();
console.log(text);
}
run();
网站
async function run() {
const prompt = "Write a story about a magic backpack."
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();
console.log(text);
}
run();
Dart (Flutter)
void main() async {
// Access your API key as an environment variable (see "Set up your API key" above)
final apiKey = Platform.environment['API_KEY'];
if (apiKey == null) {
print('No \$API_KEY environment variable');
exit(1);
}
// For text-only input, use the gemini-pro model
final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
final content = [Content.text('Write a story about a magic backpack.')];
final response = await model.generateContent(content);
print(response.text);
}
Swift
let prompt = "Write a story about a magic backpack."
let response = try await model.generateContent(prompt)
if let text = response.text {
print(text)
}
Android
Kotlin:
请注意,generateContent()
是一个挂起函数,需要从协程作用域中调用。如果您不熟悉协程,请参阅 Android 上的 Kotlin 协程。
val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)
Java:
请注意,generateContent()
会返回一个 ListenableFuture
。如果您不熟悉此 API,请参阅有关使用 ListenableFuture
的 Android 文档。
Content content = new Content.Builder()
.addText("Write a story about a magic backpack.")
.build();
Executor executor = // ...
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
后续步骤
如需详细了解如何使用 Gemini API,请参阅与您所选语言对应的教程。
您还可以使用 curl
命令来试用 Gemini API:
如果您刚开始接触生成式 AI 模型,不妨先查看概念指南和 Gemini API 概览,然后再尝试快速入门。