This quickstart shows you how to get started with the Gemini API using the SDK of your choice.
Prerequisites
Python
View on Google AI | Run in Google Colab | View notebook on GitHub |
To complete this quickstart locally, ensure that your development environment meets the following requirements:
- Python 3.9+
- An installation of
jupyter
to run the notebook.
Go
This quickstart assumes that you're familiar with building applications with Go.
To complete this quickstart, make sure that your development environment meets the following requirements:
- Go 1.20+
Node.js
This quickstart assumes that you're familiar with building applications with Node.js.
To complete this quickstart, make sure that your development environment meets the following requirements:
- Node.js v18+
- npm
Web
This quickstart assumes that you're familiar with using JavaScript to develop web apps. This guide is framework-independent.
To complete this quickstart, make sure that your development environment meets the following requirements:
- (Optional) Node.js
- Modern web browser
Dart (Flutter)
This quickstart assumes you're familiar with building applications with Dart.
To complete this quickstart, make sure that your development environment meets the following requirements:
- Dart 3.2.0+
Swift
This quickstart assumes that you're familiar with using Xcode to develop Swift apps.
To complete this quickstart, make sure that your development environment and Swift app meet the following requirements:
- Xcode 15.0 or higher
- Your Swift app must target iOS 15 or higher, or macOS 12 or higher.
Android
This quickstart assumes that you're familiar with using Android Studio to develop Android apps.
To complete this quickstart, make sure that your development environment and Android app meet the following requirements:
- Android Studio (latest version)
- Your Android app must target API level 21 or higher.
Set up your API key
To use the Gemini API, you'll need an API key. If you don't already have one, create a key in Google AI Studio.
Then configure your key.
Python
It's strongly recommended that you do not check an API key into your version control system. This quickstart assumes that you're accessing your API key as an environment variable.
Assign your API key to an environment variable:
export API_KEY=<YOUR_API_KEY>
Go
It's strongly recommended that you do not check an API key into your version control system. This quickstart assumes that you're accessing your API key as an environment variable.
Assign your API key to an environment variable:
export API_KEY=<YOUR_API_KEY>
Node.js
It's strongly recommended that you do not check an API key into your version control system. This quickstart assumes that you're accessing your API key as an environment variable.
Assign your API key to an environment variable:
export API_KEY=<YOUR_API_KEY>
Web
It's strongly recommended that you do not check an API key into your version control system. Instead, you should pass your API key to your app right before initializing the model.
This quickstart assumes that you're accessing your API key as a global constant.
Dart (Flutter)
It's strongly recommended that you do not check an API key into your
version control system. This quickstart assumes that you're accessing your
API key as a process environment variable. If you're developing a Flutter
app, you can use String.fromEnvironment
and pass
--dart-define=API_KEY=$API_KEY
to flutter build
or flutter run
to
compile with the API key since the process environment will be different when
running the app.
Swift
It's strongly recommended that you do not check an API key into your
version control system. One alternative option is to store it in a
GenerativeAI-Info.plist
file, and then read the API key from the .plist
file. Make sure to put this .plist
file in the root folder of your app and
exclude it from version control.
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
It's strongly recommended that you do not check an API key into your
version control system. Instead, you should store it in a local.properties
file (which is located in your project's root directory, but excluded from
version control), and then use the
Secrets Gradle plugin for Android
to read your API key as a Build Configuration variable.
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;
If you want to see the implementation of the Secrets Gradle plugin, you can
review the
sample app
for this SDK or use the latest preview of Android Studio Iguana which has a
Gemini API Starter template
(which includes the local.properties
file to get you started).
Install the SDK
Python
The Python SDK for the Gemini API is contained in the
google-generativeai
package. Install the dependency using pip:
pip install -q -U google-generativeai
Go
To use the Gemini API in your own application, you need to get
the Go SDK
package in your module directory:
go get github.com/google/generative-ai-go
Node.js
To use the Gemini API in your own application, you need to install the
GoogleGenerativeAI
package for Node.js:
npm install @google/generative-ai
Web
To use the Gemini API in your own web app, import @google/generative-ai
:
<script type="importmap">
{
"imports": {
"@google/generative-ai": "https://esm.run/@google/generative-ai"
}
}
</script>
Dart (Flutter)
To use the Gemini API in your own application, you need to add
the
google_generative_ai
package to your Dart or Flutter app:
Dart:
dart pub add google_generative_ai
Flutter:
flutter pub add google_generative_ai
Swift
To use the Gemini API in your own Swift app, add the GoogleGenerativeAI
package to your app:
In Xcode, right-click on your project in the project navigator.
Select Add Packages from the context menu.
In the Add Packages dialog, paste the package URL in the search bar:
none https://github.com/google/generative-ai-swift
Click Add Package. Xcode will now add the
GoogleGenerativeAI
package to your project.
Android
In your module (app-level) Gradle configuration file (like
<project>/<app-module>/build.gradle.kts
), add the dependency for the 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:
For Java, you need to add two additional libraries.
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") }
Sync your Android project with Gradle files.
Initialize the generative model
Python
Before you can make any API calls, you need to import and initialize the generative model.
import google.generativeai as genai
genai.configure(api_key=os.environ["API_KEY"])
model = genai.GenerativeModel('gemini-pro')
Go
Before you can make any API calls, you need to import and initialize the generative model.
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
Before you can make any API calls, you need to import and initialize the generative model.
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
Before you can make any API calls, you need to import and initialize the generative model.
<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)
Before you can make any API calls, you need to import and initialize the generative model.
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
Before you can make any API calls, you need to initialize the generative model.
Import the
GoogleAI
module:import GoogleGenerativeAI
Initialize the generative model:
// 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
Before you can make any API calls, you need to initialize the
GenerativeModel
object:
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:
For Java, you also need to initialize the GenerativeModelFutures
object.
// 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);
Generate text
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();
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();
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:
Note that generateContent()
is a suspend function and needs to be
called from a Coroutine scope. If you're unfamiliar with Coroutines, read
Kotlin Coroutines on Android.
val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)
Java:
Note that generateContent()
returns a ListenableFuture
. If
you're unfamiliar with this API, see the Android documentation about
Using a 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);
What's next
To learn more about working with the Gemini API, see the tutorial for your language of choice.
You can also use curl
commands to try out the Gemini API:
If you're new to generative AI models, you might want to look at the concepts guide and the Gemini API overview before trying a quickstart.