Google Gen AI Java SDK 为开发人员提供了一个接口,可将 Google 的生成模型集成到他们的 Java 应用中。
Google Gen AI Java SDK 为开发人员提供了一个接口,可将 Google 的生成模型集成到他们的 Java 应用中。
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_contentor its stream and async variants. Instead, users should invoke AFC fromChatsmodules.
Methods/fields to be removed migration guide prompt/text/imagearguments inModels.generate_videos(and async variants)Use sourceargument insteadUpcoming 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();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();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();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.
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.
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.
import com.google.genai.Client;
Client client = new Client();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:
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:
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();Besides apiVersion, HttpOptions
also allows for flexible customization of HTTP request parameters such as
baseUrl, headers, and timeout:
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();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.
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();The Google Gen AI Java SDK allows you to access the service programmatically. The following code snippets are some basic usages of model inferencing.
Use generateContent method for the most basic content generation.
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)));
}
}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());
}
}To set configurations like System Instructions and Safety Settings, you can pass
a GenerateContentConfig to the GenerateContent method.
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());
}
}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,或尚未同步最近议题。