本快速入門導覽課程說明如何透過您選擇的 SDK 開始使用 Gemini API。
必要條件
Python
在 Google AI 中查看 | 在 Google Colab 中執行 | 前往 GitHub 查看筆記本 |
如要在本機完成本快速入門導覽課程,請確保您的開發環境符合下列需求:
- Python 3.9 以上版本
- 安裝
jupyter
以執行筆記本。
查看
本快速入門導覽課程假設您已熟悉如何使用 Go 建構應用程式。
如要完成本快速入門導覽課程,請確保您的開發環境符合下列需求:
- Go 1.20 以上版本
Node.js
本快速入門導覽課程假設您熟悉如何使用 Node.js 建構應用程式。
如要完成本快速入門導覽課程,請確保您的開發環境符合下列需求:
- Node.js v18 以上版本
- npm
Web
本快速入門導覽課程假設您熟悉如何使用 JavaScript 來開發網頁應用程式。本指南與架構無關。
如要完成本快速入門導覽課程,請確保您的開發環境符合下列需求:
- (選用) Node.js
- 新式網路瀏覽器
飛鏢 (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 金鑰
如要使用 Gemini API,您必須具備 API 金鑰。如果您還沒有金鑰 請在 Google AI Studio 中建立金鑰
然後設定金鑰。
Python
強烈建議您「不要」將 API 金鑰登錄到版本管控系統。本快速入門導覽課程假設您存取 API 金鑰做為環境變數。
將 API 金鑰指派給環境變數:
export API_KEY=<YOUR_API_KEY>
查看
強烈建議您「不要」將 API 金鑰登錄到版本管控系統。本快速入門導覽課程假設您存取 API 金鑰做為環境變數。
將 API 金鑰指派給環境變數:
export API_KEY=<YOUR_API_KEY>
Node.js
強烈建議您「不要」將 API 金鑰登錄到版本管控系統。本快速入門導覽課程假設您存取 API 金鑰做為環境變數。
將 API 金鑰指派給環境變數:
export API_KEY=<YOUR_API_KEY>
Web
強烈建議您「不要」將 API 金鑰登錄到版本管控系統。而應將 API 金鑰立即傳送至應用程式,再初始化模型。
本快速入門導覽課程假設您存取 API 金鑰做為全域常數。
飛鏢 (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
檔案 (位於專案的根目錄中,但不在版本管控中),然後使用 Secrets Gradle Plugin for Android 將 API 金鑰做為建構設定變數讀取。
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
查看
如要在自己的應用程式中使用 Gemini API,您必須在模組目錄中 get
Go SDK 套件:
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>
飛鏢 (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」。
在「Add Packages」對話方塊中,將套件網址貼到搜尋列中:
none https://github.com/google/generative-ai-swift
按一下「Add Package」。Xcode 現在會在專案中新增
GoogleGenerativeAI
套件。
Android
在模組 (應用程式層級) Gradle 設定檔 (例如
<project>/<app-module>/build.gradle.kts
) 中,新增 Android 版 Google AI SDK 的依附元件: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')
查看
您必須先匯入並初始化生成式模型,才能進行任何 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"});
// ...
Web
您必須先匯入並初始化生成式模型,才能進行任何 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>
飛鏢 (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)
查看
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();
Web
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();
飛鏢 (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,請參閱 Android 說明文件的使用 ListenableFuture
相關說明。
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 總覽,然後再嘗試進行快速入門導覽課程。