Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

java-genai

> 编程语言
Open source

Google Gen AI Java SDK provides an interface for developers to integrate Google's generative models into their Java applications.

385 stars0 likes0 views
WebsiteGitHub

About

Google Gen AI Java SDK provides an interface for developers to integrate Google's generative models into their Java applications.

Google Gen AI Java SDK

Java idiomatic SDK for the [Gemini Developer APIs][gemini-api-doc] and [Gemini Enterprise Agent Platform][gemini-enterprise-agent-platform-doc] APIs.

[![Maven][maven-version-image]][maven-version-link] [![Javadoc][javadoc-image]][javadoc-link]

[!WARNING] Updates to Automatic Function Calling (AFC) in upcoming SDK version: We are changing AFC behavior in the next major version. Specifically, users will not be able to invoke AFC from direct calls to Models.generate_content or its stream and async variants. Instead, users should invoke AFC from Chats modules.

Methods/fields to be removed migration guide
prompt/text/image arguments in Models.generate_videos (and async variants) Use source argument instead

Upcoming Change to Java 17 Support: Starting from SDK version 2.0.0, Java version 17 or later is required.

To avoid unexpected updates, pin the SDK version to `

com.google.genai
google-genai
1.72.0
[//]: # ({x-version-update-end})

## Getting Started

Follow the instructions in this section to get started using the Google Gen AI
SDK for Java.

### Create a client
The Google Gen AI Java SDK provides a Client class, simplifying interaction
with both the Gemini API and Gemini Enterprise Agent Platform API. With minimal
configuration, you can seamlessly switch between the 2 backends without rewriting
your code.

#### Instantiate a client that uses Gemini API
```java
import com.google.genai.Client;

// Use Builder class for instantiation. Explicitly set the API key to use Gemini
// Developer backend.
Client client = Client.builder().apiKey("your-api-key").build();

Instantiate a client that uses Gemini Enterprise Agent Platform API

Using project and location
java
import com.google.genai.Client;

// Use Builder class for instantiation. Explicitly set the project and location,
// and set `enterprise(true)` to use Gemini Enterprise Agent Platform backend.
Client client = Client.builder()
  .project("your-project")
  .location("your-location")
  .enterprise(true)
  .build();
Using API key on Gemini Enterprise Agent Platform (GCP Express Mode)
java
import com.google.genai.Client;

// Explicitly set the `apiKey` and `enterprise(true)` to use Gemini Enterprise Agent Platform backend
// in express mode.
Client client = Client.builder()
  .apiKey("your-api-key")
  .enterprise(true)
  .build();

(Optional) Using environment variables:

You can create a client by configuring the necessary environment variables. Configuration setup instructions depends on whether you're using the Gemini Developer API or the Gemini API in Gemini Enterprise Agent Platform.

Gemini Developer API: Set the GOOGLE_API_KEY. It will automatically be picked up by the client. Note that GEMINI_API_KEY is a legacy environment variable, it's recommended to use GOOGLE_API_KEY only. But if both are set, GOOGLE_API_KEY takes precedence.

bash
export GOOGLE_API_KEY='your-api-key'

Gemini API on Gemini Enterprise Agent Platform: Set GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION, or GOOGLE_API_KEY for Gemini Enterprise Agent Platform express mode. It's recommended that you set only project & location, or API key. But if both are set, project & location takes precedence.

bash
export GOOGLE_GENAI_USE_ENTERPRISE=true

// Set project and location for Gemini Enterprise Agent Platform authentication
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'
// or API key for express mode
export GOOGLE_API_KEY='your-api-key'

After configuring the environment variables, you can instantiate a client without passing any variables.

java
import com.google.genai.Client;

Client client = new Client();

API Selection

By default, the SDK uses the beta API endpoints provided by Google to support preview features in the APIs. The stable API endpoints can be selected by setting the API version to v1.

To set the API version use HttpOptions. For example, to set the API version to v1 for Gemini Enterprise Agent Platform:

java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;

Client client = Client.builder()
  .project("your-project")
  .location("your-location")
  .enterprise(true)
  .httpOptions(HttpOptions.builder().apiVersion("v1"))
  .build();

To set the API version to v1alpha for the Gemini Developer API:

java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;

Client client = Client.builder()
  .apiKey("your-api-key")
  .httpOptions(HttpOptions.builder().apiVersion("v1alpha"))
  .build();

HttpOptions

Besides apiVersion, HttpOptions also allows for flexible customization of HTTP request parameters such as baseUrl, headers, and timeout:

java
HttpOptions httpOptions = HttpOptions.builder()
  .baseUrl("your-own-endpoint.com")
  .headers(ImmutableMap.of("key", "value"))
  .timeout(600)
  .build();

…

java
HttpOptions httpOptions = HttpOptions.builder()
  .retryOptions(
      HttpRetryOptions.builder()
          .attempts(3)
          .httpStatusCodes(408, 429))
  .build();

…

java
import com.google.genai.Client;
import com.google.genai.types.ClientOptions;

Client client =
    Client.builder()
        .apiKey("your-api-key")
        .clientOptions(
            ClientOptions.builder().maxConnections(64).maxConnectionsPerHost(16).build())
        .build();

Proxy

If your environment requires connecting through a proxy, you can configure it using ProxyOptions. The SDK supports HTTP, SOCKS, and DIRECT (no proxy) connection types, along with basic proxy authentication.

java
import com.google.genai.Client;
import com.google.genai.types.ClientOptions;
import com.google.genai.types.ProxyOptions;
import com.google.genai.types.ProxyType;

ClientOptions clientOptions =
    ClientOptions.builder()
        .proxyOptions(
            ProxyOptions.builder()
                .type(ProxyType.Known.HTTP)
                .host("your-proxy-host")
                .port(8080)
                .username("your-proxy-username")
                .password("your-proxy-password"))
        .build();
Client client = Client.builder().apiKey("your-api-key").clientOptions(clientOptions).build();

…

java
import com.google.genai.Client;
import com.google.genai.types.ClientOptions;
import okhttp3.OkHttpClient;
import java.time.Duration;

// Create your custom OkHttpClient
OkHttpClient customHttpClient = new OkHttpClient.Builder()
    .connectTimeout(Duration.ofSeconds(30))
    .readTimeout(Duration.ofSeconds(30))
    // Add your custom interceptors, SSL socket factory, etc.
    .build();

Client client = Client.builder()
    .apiKey("your-api-key")
    .clientOptions(
        ClientOptions.builder()
            .customHttpClient(customHttpClient)
            .build()
    )
    .build();

Interact with models

The Google Gen AI Java SDK allows you to access the service programmatically. The following code snippets are some basic usages of model inferencing.

Generate Content

Use generateContent method for the most basic content generation.

with text input
java
package ;

import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;

public class GenerateContentWithTextInput {
  public static void main(String[] args) {
    // Instantiate the client. The client by default uses the Gemini API. It
    //  gets the API key from the environment variable `GOOGLE_API_KEY`.
    Client client = new Client();

    GenerateContentResponse response =
        client.models.generateContent("gemini-flash-latest", "What is your name?", null);

    // Gets the text string from the response by the quick accessor method `text()`.
    System.out.println("Unary response: " + response.text());

    // Gets the http headers from the response.
    response
        .sdkHttpResponse()
        .ifPresent(
            httpResponse ->
                System.out.println("Response headers: " + httpResponse.headers().orElse(null)));
  }
}
with text and image input
java
package ;

import com.google.common.collect.ImmutableList;
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;

public class GenerateContentWithImageInput {
  public static void main(String[] args) {
    // Instantiate the client using Gemini Enterprise Agent Platform API. The client gets the project and
    // location from the environment variables `GOOGLE_CLOUD_PROJECT` and
    // `GOOGLE_CLOUD_LOCATION`.
    Client client = Client.builder().enterprise(true).build();

    // Construct a multimodal content with quick constructors
    Content content =
        Content.fromParts(
            Part.fromText("describe the image"),
            Part.fromUri("gs://path/to/image.jpg", "image/jpeg"));

    GenerateContentResponse response =
        client.models.generateContent("gemini-flash-latest", content, null);

    System.out.println("Response: " + response.text());
  }
}
Generate Content with extra configs

To set configurations like System Instructions and Safety Settings, you can pass a GenerateContentConfig to the GenerateContent method.

java
package ;

import com.google.common.collect.ImmutableList;
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.GoogleSearch;
import com.google.genai.types.HarmBlockThreshold;
import com.google.genai.types.HarmCategory;
import com.google.genai.types.Part;
import com.google.genai.types.SafetySetting;
import com.google.genai.types.ThinkingConfig;
import com.google.genai.types.Tool;

public class GenerateContentWithConfigs {
  public static void main(String[] args) {
    Client client = new Client();

    // Sets the safety settings in the config.
    ImmutableList safetySettings =
        ImmutableList.of(
            SafetySetting.builder()
                .category(HarmCategory.Known.HARM_CATEGORY_HATE_SPEECH)
                .threshold(HarmBlockThreshold.Known.BLOCK_ONLY_HIGH)
                .build(),
            SafetySetting.builder()
                .category(HarmCategory.Known.HARM_CATEGORY_DANGEROUS_CONTENT)
                .threshold(HarmBlockThreshold.Known.BLOCK_LOW_AND_ABOVE)
                .build());

    // Sets the system instruction in the config.
    Content systemInstruction = Content.fromParts(Part.fromText("You are a history teacher."));

    // Sets the Google Search tool in the config.
    Tool googleSearchTool = Tool.builder().googleSearch(GoogleSearch.builder()).build();

    GenerateContentConfig config =
        GenerateContentConfig.builder()
            // Sets the thinking budget to 0 to disable thinking mode
            .thinkingConfig(ThinkingConfig.builder().thinkingBudget(0))
            .candidateCount(1)
            .maxOutputTokens(1024)
            .safetySettings(safetySettings)
            .systemInstruction(systemInstruction)
            .tools(googleSearchTool)
            .build();

    GenerateContentResponse response =
        client.models.generateContent("gemini-flash-latest", "Tell me the history of LLM", config);

    System.out.println("Response: " + response.text());
  }
}
Automatic function calling with generate content

The Models.generateContent methods supports automatic function calling (AFC). If the user passes in a list of public static method in the tool list of the GenerateContentConfig, by default AFC will be enabled with maximum remote calls to be 10 times. Follow the followin

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Java

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言