{"id":33179689,"url":"https://github.com/googleapis/java-genai","last_synced_at":"2026-04-15T02:05:54.517Z","repository":{"id":276208867,"uuid":"899744537","full_name":"googleapis/java-genai","owner":"googleapis","description":"Google Gen AI Java SDK provides an interface for developers to integrate Google's generative models into their Java applications.","archived":false,"fork":false,"pushed_at":"2026-01-16T00:23:35.000Z","size":347309,"stargazers_count":319,"open_issues_count":41,"forks_count":99,"subscribers_count":25,"default_branch":"main","last_synced_at":"2026-01-16T05:58:42.641Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://googleapis.github.io/java-genai/javadoc/","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/googleapis.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-12-06T23:16:56.000Z","updated_at":"2026-01-15T08:38:59.000Z","dependencies_parsed_at":"2025-02-06T22:30:32.459Z","dependency_job_id":"f436aa5c-d246-4337-830c-1df7f332587a","html_url":"https://github.com/googleapis/java-genai","commit_stats":null,"previous_names":["googleapis/java-genai"],"tags_count":46,"template":false,"template_full_name":null,"purl":"pkg:github/googleapis/java-genai","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjava-genai","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjava-genai/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjava-genai/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjava-genai/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/googleapis","download_url":"https://codeload.github.com/googleapis/java-genai/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/googleapis%2Fjava-genai/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28531368,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-18T00:39:45.795Z","status":"online","status_checked_at":"2026-01-18T02:00:07.578Z","response_time":98,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-11-16T03:00:36.840Z","updated_at":"2026-04-15T02:05:54.487Z","avatar_url":"https://github.com/googleapis.png","language":"Java","funding_links":[],"categories":["人工智能"],"sub_categories":[],"readme":"# Google Gen AI Java SDK\n\nJava idiomatic SDK for the\n[Gemini Developer APIs][gemini-api-doc] and [Vertex AI][vertex-api-doc] APIs.\n\n**Note:** The SDK now has experimental support for the [Interactions API](#interactions-experimental).\n\n[![Maven][maven-version-image]][maven-version-link]\n[![Javadoc][javadoc-image]][javadoc-link]\n\n## Add dependency\n\nIf you're using Maven, add the following to your dependencies:\n\n[//]: # ({x-version-update-start:google-genai:released})\n```xml\n\u003cdependencies\u003e\n  \u003cdependency\u003e\n    \u003cgroupId\u003ecom.google.genai\u003c/groupId\u003e\n    \u003cartifactId\u003egoogle-genai\u003c/artifactId\u003e\n    \u003cversion\u003e1.50.0\u003c/version\u003e\n  \u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n[//]: # ({x-version-update-end})\n\n## Getting Started\n\nFollow the instructions in this section to get started using the Google Gen AI\nSDK for Java.\n\n### Create a client\nThe Google Gen AI Java SDK provides a Client class, simplifying interaction\nwith both the Gemini API and Vertex AI API. With minimal configuration,\nyou can seamlessly switch between the 2 backends without rewriting\nyour code.\n\n#### Instantiate a client that uses Gemini API\n```java\nimport com.google.genai.Client;\n\n// Use Builder class for instantiation. Explicitly set the API key to use Gemini\n// Developer backend.\nClient client = Client.builder().apiKey(\"your-api-key\").build();\n```\n\n#### Instantiate a client that uses Vertex AI API\n\n##### Using project and location\n\n```java\nimport com.google.genai.Client;\n\n// Use Builder class for instantiation. Explicitly set the project and location,\n// and set `vertexAI(true)` to use Vertex AI backend.\nClient client = Client.builder()\n  .project(\"your-project\")\n  .location(\"your-location\")\n  .vertexAI(true)\n  .build();\n```\n\n##### Using API key on Vertex AI (GCP Express Mode)\n\n```java\nimport com.google.genai.Client;\n\n// Explicitly set the `apiKey` and `vertexAI(true)` to use Vertex AI backend\n// in express mode.\nClient client = Client.builder()\n  .apiKey(\"your-api-key\")\n  .vertexAI(true)\n  .build();\n```\n\n#### (Optional) Using environment variables:\n\nYou can create a client by configuring the necessary environment variables.\nConfiguration setup instructions depends on whether you're using the Gemini\nDeveloper API or the Gemini API in Vertex AI.\n\n**Gemini Developer API:** Set the `GOOGLE_API_KEY`. It will automatically be\npicked up by the client. Note that `GEMINI_API_KEY` is a legacy environment\nvariable, it's recommended to use `GOOGLE_API_KEY` only. But if both are set,\n`GOOGLE_API_KEY` takes precedence.\n\n```bash\nexport GOOGLE_API_KEY='your-api-key'\n```\n\n**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`,\n`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, or `GOOGLE_API_KEY` for\nVertex AI express mode. It's recommended that you set only project \u0026 location,\nor API key. But if both are set, project \u0026 location takes precedence.\n\n```bash\nexport GOOGLE_GENAI_USE_VERTEXAI=true\n\n// Set project and location for Vertex AI authentication\nexport GOOGLE_CLOUD_PROJECT='your-project-id'\nexport GOOGLE_CLOUD_LOCATION='us-central1'\n// or API key for express mode\nexport GOOGLE_API_KEY='your-api-key'\n```\n\nAfter configuring the environment variables, you can instantiate a client\nwithout passing any variables.\n\n```java\nimport com.google.genai.Client;\n\nClient client = new Client();\n```\n\n### API Selection\n\nBy default, the SDK uses the beta API endpoints provided by Google to support\npreview features in the APIs. The stable API endpoints can be selected by\nsetting the API version to `v1`.\n\nTo set the API version use `HttpOptions`. For example, to set the API version to\n`v1` for Vertex AI:\n\n```java\nimport com.google.genai.Client;\nimport com.google.genai.types.HttpOptions;\n\nClient client = Client.builder()\n  .project(\"your-project\")\n  .location(\"your-location\")\n  .vertexAI(true)\n  .httpOptions(HttpOptions.builder().apiVersion(\"v1\"))\n  .build();\n```\n\nTo set the API version to `v1alpha` for the Gemini Developer API:\n\n```java\nimport com.google.genai.Client;\nimport com.google.genai.types.HttpOptions;\n\nClient client = Client.builder()\n  .apiKey(\"your-api-key\")\n  .httpOptions(HttpOptions.builder().apiVersion(\"v1alpha\"))\n  .build();\n```\n\n### HttpOptions\n\nBesides `apiVersion`, [HttpOptions](https://github.com/googleapis/java-genai/blob/main/src/main/java/com/google/genai/types/HttpOptions.java)\nalso allows for flexible customization of HTTP request parameters such as\n`baseUrl`, `headers`, and `timeout`:\n\n```java\nHttpOptions httpOptions = HttpOptions.builder()\n  .baseUrl(\"your-own-endpoint.com\")\n  .headers(ImmutableMap.of(\"key\", \"value\"))\n  .timeout(600)\n  .build();\n```\n\nBeyond client-level configuration, `HttpOptions` can also be set on a\nper-request basis, providing maximum flexibility for diverse API call settings.\nSee [this example](https://github.com/googleapis/java-genai/blob/main/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java)\nfor more details.\n\n### HttpRetryOptions\n\n[HttpRetryOptions](https://github.com/googleapis/java-genai/blob/main/src/main/java/com/google/genai/types/HttpRetryOptions.java)\nallows you to configure the automatic retry behavior for failed API calls. You\ncan customize key settings like:\n\n  * Total number of attempts.\n  * Which HTTP status codes should trigger a retry (e.g., 429 for rate limits).\n  * Backoff strategy, including the initial delay and maximum delay between retries.\n\n```java\nHttpOptions httpOptions = HttpOptions.builder()\n  .retryOptions(\n      HttpRetryOptions.builder()\n          .attempts(3)\n          .httpStatusCodes(408, 429))\n  .build();\n```\n\nSince HttpRetryOptions is part of HttpOptions, it supports being set at the\nclient level (as shown) or on a per-request basis. Note that Providing\n`HttpRetryOptions` for a specific request will completely override any default\nretry settings configured on the client.\n\n### ClientOptions\n[ClientOptions](https://github.com/googleapis/java-genai/blob/main/src/main/java/com/google/genai/types/ClientOptions.java)\nenables you to customize the behavior of the HTTP client, including connection\npool settings and proxy configurations.\n\n#### Connection Pool\nYou can configure the connection pool via `maxConnections` (total maximum\nconnections) and `maxConnectionsPerHost` (maximum connections to a single host).\n\n```java\nimport com.google.genai.Client;\nimport com.google.genai.types.ClientOptions;\n\nClient client =\n    Client.builder()\n        .apiKey(\"your-api-key\")\n        .clientOptions(\n            ClientOptions.builder().maxConnections(64).maxConnectionsPerHost(16).build())\n        .build();\n```\n\n#### Proxy\nIf your environment requires connecting through a proxy, you can configure it\nusing `ProxyOptions`. The SDK supports `HTTP`, `SOCKS`, and `DIRECT` (no proxy)\nconnection types, along with basic proxy authentication.\n\n```java\nimport com.google.genai.Client;\nimport com.google.genai.types.ClientOptions;\nimport com.google.genai.types.ProxyOptions;\nimport com.google.genai.types.ProxyType;\n\nClientOptions clientOptions =\n    ClientOptions.builder()\n        .proxyOptions(\n            ProxyOptions.builder()\n                .type(ProxyType.Known.HTTP)\n                .host(\"your-proxy-host\")\n                .port(8080)\n                .username(\"your-proxy-username\")\n                .password(\"your-proxy-password\"))\n        .build();\nClient client = Client.builder().apiKey(\"your-api-key\").clientOptions(clientOptions).build();\n```\n\nIf `ProxyOptions` is provided with `type` set to `DIRECT`, it will enforce a\ndirect connection, bypassing any system-level proxy settings.\n\n### Interact with models\nThe Google Gen AI Java SDK allows you to access the service programmatically.\nThe following code snippets are some basic usages of model inferencing.\n\n#### Generate Content\nUse `generateContent` method for the most basic content generation.\n\n##### with text input\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.GenerateContentResponse;\n\npublic class GenerateContentWithTextInput {\n  public static void main(String[] args) {\n    // Instantiate the client. The client by default uses the Gemini API. It\n    //  gets the API key from the environment variable `GOOGLE_API_KEY`.\n    Client client = new Client();\n\n    GenerateContentResponse response =\n        client.models.generateContent(\"gemini-2.5-flash\", \"What is your name?\", null);\n\n    // Gets the text string from the response by the quick accessor method `text()`.\n    System.out.println(\"Unary response: \" + response.text());\n\n    // Gets the http headers from the response.\n    response\n        .sdkHttpResponse()\n        .ifPresent(\n            httpResponse -\u003e\n                System.out.println(\"Response headers: \" + httpResponse.headers().orElse(null)));\n  }\n}\n```\n\n##### with text and image input\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.Client;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.Part;\n\npublic class GenerateContentWithImageInput {\n  public static void main(String[] args) {\n    // Instantiate the client using Vertex API. The client gets the project and\n    // location from the environment variables `GOOGLE_CLOUD_PROJECT` and\n    // `GOOGLE_CLOUD_LOCATION`.\n    Client client = Client.builder().vertexAI(true).build();\n\n    // Construct a multimodal content with quick constructors\n    Content content =\n        Content.fromParts(\n            Part.fromText(\"describe the image\"),\n            Part.fromUri(\"gs://path/to/image.jpg\", \"image/jpeg\"));\n\n    GenerateContentResponse response =\n        client.models.generateContent(\"gemini-2.5-flash\", content, null);\n\n    System.out.println(\"Response: \" + response.text());\n  }\n}\n```\n\n##### Generate Content with extra configs\nTo set configurations like System Instructions and Safety Settings, you can pass\na `GenerateContentConfig` to the `GenerateContent` method.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.Client;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.GoogleSearch;\nimport com.google.genai.types.HarmBlockThreshold;\nimport com.google.genai.types.HarmCategory;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.SafetySetting;\nimport com.google.genai.types.ThinkingConfig;\nimport com.google.genai.types.Tool;\n\npublic class GenerateContentWithConfigs {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    // Sets the safety settings in the config.\n    ImmutableList\u003cSafetySetting\u003e safetySettings =\n        ImmutableList.of(\n            SafetySetting.builder()\n                .category(HarmCategory.Known.HARM_CATEGORY_HATE_SPEECH)\n                .threshold(HarmBlockThreshold.Known.BLOCK_ONLY_HIGH)\n                .build(),\n            SafetySetting.builder()\n                .category(HarmCategory.Known.HARM_CATEGORY_DANGEROUS_CONTENT)\n                .threshold(HarmBlockThreshold.Known.BLOCK_LOW_AND_ABOVE)\n                .build());\n\n    // Sets the system instruction in the config.\n    Content systemInstruction = Content.fromParts(Part.fromText(\"You are a history teacher.\"));\n\n    // Sets the Google Search tool in the config.\n    Tool googleSearchTool = Tool.builder().googleSearch(GoogleSearch.builder()).build();\n\n    GenerateContentConfig config =\n        GenerateContentConfig.builder()\n            // Sets the thinking budget to 0 to disable thinking mode\n            .thinkingConfig(ThinkingConfig.builder().thinkingBudget(0))\n            .candidateCount(1)\n            .maxOutputTokens(1024)\n            .safetySettings(safetySettings)\n            .systemInstruction(systemInstruction)\n            .tools(googleSearchTool)\n            .build();\n\n    GenerateContentResponse response =\n        client.models.generateContent(\"gemini-2.5-flash\", \"Tell me the history of LLM\", config);\n\n    System.out.println(\"Response: \" + response.text());\n  }\n}\n```\n\n##### Automatic function calling with generate content\n\nThe Models.generateContent methods supports automatic function calling (AFC). If\nthe user passes in a list of public static method in the tool list of the\nGenerateContentConfig, by default AFC will be enabled with maximum remote calls\nto be 10 times. Follow the following steps to experience this feature.\n\n**Step 1**: enable the compiler to parse parameter name of your methods. In your\n`pom.xml`, include the following compiler configuration.\n\n```\n\u003cplugin\u003e\n  \u003cgroupId\u003eorg.apache.maven.plugins\u003c/groupId\u003e\n  \u003cartifactId\u003emaven-compiler-plugin\u003c/artifactId\u003e\n  \u003cversion\u003e3.14.0\u003c/version\u003e\n  \u003cconfiguration\u003e\n    \u003ccompilerArgs\u003e\n      \u003carg\u003e-parameters\u003c/arg\u003e\n    \u003c/compilerArgs\u003e\n  \u003c/configuration\u003e\n\u003c/plugin\u003e\n```\n\n**Step 2**: see the following code example to use AFC, pay special attention to\nthe code line where the `java.lang.reflect.Method` instance was extracted.\n\n```java\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.Client;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.Tool;\nimport java.lang.reflect.Method;\n\npublic class GenerateContentWithFunctionCall {\n  public static String getCurrentWeather(String location, String unit) {\n    return \"The weather in \" + location + \" is \" + \"very nice.\";\n  }\n\n  public static void main(String[] args) throws NoSuchMethodException {\n    Client client = new Client();\n\n    // Load the method as a reflected Method object so that it can be\n    // automatically executed on the client side.\n    Method method =\n        GenerateContentWithFunctionCall.class.getMethod(\n            \"getCurrentWeather\", String.class, String.class);\n\n    GenerateContentConfig config =\n        GenerateContentConfig.builder()\n            .tools(Tool.builder().functions(method))\n            .build();\n\n    GenerateContentResponse response =\n        client.models.generateContent(\n            \"gemini-2.5-flash\",\n            \"What is the weather in Vancouver?\",\n            config);\n\n    System.out.println(\"The response is: \" + response.text());\n    System.out.println(\n        \"The automatic function calling history is: \"\n            + response.automaticFunctionCallingHistory().get());\n  }\n}\n```\n\n##### Stream Generated Content\nTo get a streamed response, you can use the `generateContentStream` method:\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.ResponseStream;\nimport com.google.genai.types.GenerateContentResponse;\n\npublic class StreamGeneration {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    ResponseStream\u003cGenerateContentResponse\u003e responseStream =\n        client.models.generateContentStream(\n            \"gemini-2.5-flash\", \"Tell me a story in 300 words.\", null);\n\n    System.out.println(\"Streaming response: \");\n    for (GenerateContentResponse res : responseStream) {\n      System.out.print(res.text());\n    }\n\n    // To save resources and avoid connection leaks, it is recommended to close the response\n    // stream after consumption (or using try block to get the response stream).\n    responseStream.close();\n  }\n}\n```\n\n##### Async Generate Content\nTo get a response asynchronously, you can use the `generateContent` method from\nthe `client.async.models` namespace.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.GenerateContentResponse;\nimport java.util.concurrent.CompletableFuture;\n\npublic class GenerateContentAsync {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    CompletableFuture\u003cGenerateContentResponse\u003e responseFuture =\n        client.async.models.generateContent(\n            \"gemini-2.5-flash\", \"Introduce Google AI Studio.\", null);\n\n    responseFuture\n        .thenAccept(\n            response -\u003e {\n              System.out.println(\"Async response: \" + response.text());\n            })\n        .join();\n  }\n}\n```\n\n##### Generate Content with JSON response schema\nTo get a response in JSON by passing in a response schema to the\n`GenerateContent` API.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.Client;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.Schema;\nimport com.google.genai.types.Type;\n\npublic class GenerateContentWithSchema {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    // Define the schema for the response, in Json format.\n    ImmutableMap\u003cString, Object\u003e schema = ImmutableMap.of(\n        \"type\", \"object\",\n        \"properties\", ImmutableMap.of(\n            \"recipe_name\", ImmutableMap.of(\"type\", \"string\"),\n            \"ingredients\", ImmutableMap.of(\n                \"type\", \"array\",\n                \"items\", ImmutableMap.of(\"type\", \"string\")\n            )\n        ),\n        \"required\", ImmutableList.of(\"recipe_name\", \"ingredients\")\n    );\n\n    // Set the response schema in GenerateContentConfig\n    GenerateContentConfig config =\n        GenerateContentConfig.builder()\n            .responseMimeType(\"application/json\")\n            .candidateCount(1)\n            .responseSchema(schema)\n            .build();\n\n    GenerateContentResponse response =\n        client.models.generateContent(\"gemini-2.5-flash\", \"Tell me your name\", config);\n\n    System.out.println(\"Response: \" + response.text());\n  }\n}\n```\n\n#### Count Tokens and Compute Tokens\n\nThe `countTokens` method allows you to calculate the number of tokens your\nprompt will use before sending it to the model, helping you manage costs and\nstay within the context window.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.CountTokensResponse;\n\npublic class CountTokens {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    CountTokensResponse response =\n        client.models.countTokens(\"gemini-2.5-flash\", \"What is your name?\", null);\n\n    System.out.println(\"Count tokens response: \" + response);\n  }\n}\n```\n\nThe `computeTokens` method returns the Tokens Info that contains tokens and\ntoken IDs given your prompt. This method is only supported in Vertex AI.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.ComputeTokensResponse;\n\npublic class ComputeTokens {\n  public static void main(String[] args) {\n    Client client = Client.builder().vertexAI(true).build();\n\n    ComputeTokensResponse response =\n        client.models.computeTokens(\"gemini-2.5-flash\", \"What is your name?\", null);\n\n    System.out.println(\"Compute tokens response: \" + response);\n  }\n}\n```\n\n#### Embed Content\n\nThe `embedContent` method allows you to generate embeddings for words, phrases,\nsentences, and code, as well as multimodal content like images or videos via Vertex AI.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.EmbedContentConfig;\nimport com.google.genai.types.EmbedContentResponse;\n\npublic class EmbedContent {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    EmbedContentResponse response =\n        client.models.embedContent(\"gemini-embedding-001\", \"why is the sky blue?\", null);\n\n    System.out.println(\"Embedding response: \" + response);\n\n    // Multimodal embedding with Vertex AI\n    Client vertexClient = Client.builder().vertexAI(true).build();\n    EmbedContentConfig config =\n        EmbedContentConfig.builder()\n            .outputDimensionality(10)\n            .title(\"test_title\")\n            .taskType(\"RETRIEVAL_DOCUMENT\")\n            .build();\n\n    EmbedContentResponse mmResponse =\n        vertexClient.models.embedContent(\n            \"gemini-embedding-2-exp-11-2025\",\n            Content.fromParts(\n                Part.fromText(\"Hello\"),\n                Part.fromUri(\"gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png\", \"image/png\")),\n            config);\n    System.out.println(\"Multimodal embedding response: \" + mmResponse);\n  }\n}\n```\n\n### Imagen\n\nImagen is a text-to-image GenAI service.\n\n#### Generate Images\n\nThe `generateImages` method helps you create high-quality, unique images given a\ntext prompt.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.GenerateImagesConfig;\nimport com.google.genai.types.GenerateImagesResponse;\nimport com.google.genai.types.Image;\n\npublic class GenerateImages {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    GenerateImagesConfig config =\n        GenerateImagesConfig.builder()\n            .numberOfImages(1)\n            .outputMimeType(\"image/jpeg\")\n            .includeSafetyAttributes(true)\n            .build();\n\n    GenerateImagesResponse response =\n        client.models.generateImages(\n            \"imagen-3.0-generate-002\", \"Robot holding a red skateboard\", config);\n\n    if (generatedImagesResponse.images().isEmpty()) {\n      System.out.println(\"Unable to generate images.\");\n    }\n    System.out.println(\"Generated \" + generatedImagesResponse.images().size() + \" images.\");\n    Image generatedImage = generatedImagesResponse.images().get(0);\n  }\n}\n```\n\n#### Upscale Image\n\nThe `upscaleImage` method allows you to upscale an image. This feature is only\nsupported in Vertex AI.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.Image;\nimport com.google.genai.types.UpscaleImageConfig;\nimport com.google.genai.types.UpscaleImageResponse;\n\npublic class UpscaleImage {\n  public static void main(String[] args) {\n    Client client = Client.builder().vertexAI(true).build();\n\n    Image image = Image.fromFile(\"path/to/your/image\");\n\n    UpscaleImageConfig config =\n        UpscaleImageConfig.builder()\n            .outputMimeType(\"image/jpeg\")\n            .enhanceInputImage(true)\n            .imagePreservationFactor(0.6f)\n            .build();\n\n    UpscaleImageResponse response =\n        client.models.upscaleImage(\"imagen-3.0-generate-002\", image, \"x2\", config);\n\n    response.generatedImages().ifPresent(\n        images -\u003e {\n            Image upscaledImage = images.get(0).image().orElse(null);\n            // Do something with the upscaled image.\n        }\n    );\n  }\n}\n```\n\n#### Edit Image\n\nThe `editImage` method lets you edit an image. You can input reference images\n(ex. mask reference for inpainting, or style reference for style transfer) in\naddition to a text prompt to guide the editing.\n\nThis feature uses a different model than `generateImages` and `upscaleImage`. It\nis only supported in Vertex AI.\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.EditImageConfig;\nimport com.google.genai.types.EditImageResponse;\nimport com.google.genai.types.EditMode;\nimport com.google.genai.types.Image;\nimport com.google.genai.types.MaskReferenceConfig;\nimport com.google.genai.types.MaskReferenceImage;\nimport com.google.genai.types.MaskReferenceMode;\nimport com.google.genai.types.RawReferenceImage;\nimport com.google.genai.types.ReferenceImage;\nimport java.util.ArrayList;\n\npublic class EditImage {\n  public static void main(String[] args) {\n    Client client = Client.builder().vertexAI(true).build();\n\n    Image image = Image.fromFile(\"path/to/your/image\");\n\n    // Edit image with a mask.\n    EditImageConfig config =\n        EditImageConfig.builder()\n            .editMode(EditMode.Known.EDIT_MODE_INPAINT_INSERTION)\n            .numberOfImages(1)\n            .outputMimeType(\"image/jpeg\")\n            .build();\n\n    ArrayList\u003cReferenceImage\u003e referenceImages = new ArrayList\u003c\u003e();\n    RawReferenceImage rawReferenceImage =\n        RawReferenceImage.builder().referenceImage(image).referenceId(1).build();\n    referenceImages.add(rawReferenceImage);\n\n    MaskReferenceImage maskReferenceImage =\n        MaskReferenceImage.builder()\n            .referenceId(2)\n            .config(\n                MaskReferenceConfig.builder()\n                    .maskMode(MaskReferenceMode.Known.MASK_MODE_BACKGROUND)\n                    .maskDilation(0.0f))\n            .build();\n    referenceImages.add(maskReferenceImage);\n\n    EditImageResponse response =\n        client.models.editImage(\n            \"imagen-3.0-capability-001\", \"Sunlight and clear sky\", referenceImages, config);\n\n    response.generatedImages().ifPresent(\n        images -\u003e {\n            Image editedImage = images.get(0).image().orElse(null);\n            // Do something with the edited image.\n        }\n    );\n  }\n}\n```\n\n### Veo\n\nVeo is a video generation GenAI service.\n\n#### Generate Videos (Text to Video)\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.GenerateVideosConfig;\nimport com.google.genai.types.GenerateVideosOperation;\nimport com.google.genai.types.Video;\n\npublic class GenerateVideosWithText {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    GenerateVideosConfig config =\n        GenerateVideosConfig.builder()\n            .numberOfVideos(1)\n            .enhancePrompt(true)\n            .durationSeconds(5)\n            .build();\n\n    // generateVideos returns an operation\n    GenerateVideosOperation operation =\n        client.models.generateVideos(\n            \"veo-2.0-generate-001\", \"A neon hologram of a cat driving at top speed\", null, config);\n\n    // When the operation hasn't been finished, operation.done() is empty\n    while (!operation.done().isPresent()) {\n        try {\n            System.out.println(\"Waiting for operation to complete...\");\n            Thread.sleep(10000);\n            // Sleep for 10 seconds and check the operation again\n            operation = client.operations.getVideosOperation(operation, null);\n        } catch (InterruptedException e) {\n            System.out.println(\"Thread was interrupted while sleeping.\");\n            Thread.currentThread().interrupt();\n        }\n    }\n\n    operation.response().ifPresent(\n        response -\u003e {\n            response.generatedVideos().ifPresent(\n                videos -\u003e {\n                    System.out.println(\"Generated \" + videos.size() + \" videos.\");\n                    Video video = videos.get(0).video().orElse(null);\n                    // Do something with the generated video\n                }\n            );\n        }\n    );\n  }\n}\n```\n\n#### Generate Videos (Image to Video)\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.types.GenerateVideosConfig;\nimport com.google.genai.types.GenerateVideosOperation;\nimport com.google.genai.types.Image;\nimport com.google.genai.types.Video;\n\npublic class GenerateVideosWithImage {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    Image image = Image.fromFile(\"path/to/your/image\");\n\n    GenerateVideosConfig config =\n        GenerateVideosConfig.builder()\n            .numberOfVideos(1)\n            .enhancePrompt(true)\n            .durationSeconds(5)\n            .build();\n\n    // generateVideos returns an operation\n    GenerateVideosOperation operation =\n        client.models.generateVideos(\n            \"veo-2.0-generate-001\",\n            \"Night sky\",\n            image,\n            config);\n\n    // When the operation hasn't been finished, operation.done() is empty\n    while (!operation.done().isPresent()) {\n        try {\n            System.out.println(\"Waiting for operation to complete...\");\n            Thread.sleep(10000);\n            // Sleep for 10 seconds and check the operation again\n            operation = client.operations.getVideosOperation(operation, null);\n        } catch (InterruptedException e) {\n            System.out.println(\"Thread was interrupted while sleeping.\");\n            Thread.currentThread().interrupt();\n        }\n    }\n\n    operation.response().ifPresent(\n        response -\u003e {\n            response.generatedVideos().ifPresent(\n                videos -\u003e {\n                    System.out.println(\"Generated \" + videos.size() + \" videos.\");\n                    Video video = videos.get(0).video().orElse(null);\n                    // Do something with the generated video\n                }\n            );\n        }\n    );\n  }\n}\n```\n\n### Files API\n\nGemini models support various input data types, including text, images, and\naudio. The Files API allows you to upload and manage these media files for use\nwith Gemini models. **This feature is exclusively supported by the Gemini API**.\n\n#### Usage info\nYou can use the Files API to upload and interact with media files. The Files API\nlets you store up to 20 GB of files per project, with a per-file maximum size of\n2 GB. Files are stored for 48 hours. During that time, you can use the API to\nget metadata about the files, but you can't download the files. The Files API is\navailable at no cost in all regions where the Gemini API is available.\n\nThe basic operations are:\n\n1. **Upload**: You can use the Files API to upload a media file. Always use\nthe Files API when the total request size (including the files, text prompt,\nsystem instructions, etc.) is larger than 20 MB.\n\n2. **Get**: You can verify that the API successfully stored the uploaded file\nand get its metadata.\n\n3. **List**: You can upload multiple files using the Files API. The following\ncode gets a list of all the files uploaded.\n\n4. **Delete**: Files are automatically deleted after 48 hours. You can also\nmanually delete an uploaded file:\n\n#### Sample usage\n\n```java\npackage \u003cyour package name\u003e;\n\nimport com.google.genai.Client;\nimport com.google.genai.errors.GenAiIOException;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.DeleteFileResponse;\nimport com.google.genai.types.File;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.ListFilesConfig;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.UploadFileConfig;\n\n/** An example of how to use the Files module to upload, retrieve, list, and delete files. */\npublic final class FileOperations {\n  public static void main(String[] args) {\n    Client client = new Client();\n\n    // Upload a file to the API.\n    try {\n      File file =\n          client.files.upload(\n              \"path/to/your/file.pdf\",\n              UploadFileConfig.builder().mimeType(\"application/pdf\").build());\n\n      // Use the uploaded file in the generateContent\n      Content content =\n          Content.fromParts(\n              Part.fromText(\"Summary this pdf.\"),\n              Part.fromUri(file.name().get(), file.mimeType().get()));\n      GenerateContentResponse response =\n          client.models.generateContent(\"gemini-2.5-flash\", content, null);\n\n      // Get the uploaded file.\n      File retrievedFile = client.files.get(file.name().get(), null);\n\n      // List all files.\n      System.out.println(\"List files: \");\n      for (File f : client.files.list(ListFilesConfig.builder().pageSize(10).build())) {\n        System.out.println(\"File name: \" + f.name().get());\n      }\n\n      // Delete the uploaded file.\n      client.files.delete(file.name().get(), null);\n\n    } catch (GenAiIOException e) {\n      System.out.println(\"An error occurred while uploading the file: \" + e.getMessage());\n    }\n  }\n}\n```\n\n### Interactions (Experimental)\n\nThe `interactions` service provides access to experimental features.\n\n\u003e [!WARNING]\n\u003e This service is experimental and subject to change or removal in future releases.\n\nYou can access it via the client:\n```java\nclient.interactions\n```\nor asynchronously:\n```java\nclient.async.interactions\n```\n\n### Example: Create Interaction\n\nThis example demonstrates creating a simple model interaction.\n\n```java\nimport com.google.genai.Client;\nimport com.google.genai.interactions.models.interactions.Content;\nimport com.google.genai.interactions.models.interactions.CreateModelInteractionParams;\nimport com.google.genai.interactions.models.interactions.Interaction;\nimport com.google.genai.interactions.models.interactions.Model;\n\nClient client = new Client();\n\nCreateModelInteractionParams params =\n    CreateModelInteractionParams.builder()\n        .input(\"Why is the sky blue?\")\n        .model(Model.GEMINI_2_5_FLASH)\n        .build();\n\nInteraction interaction = client.interactions.create(params);\n\nSystem.out.println(\"Interaction ID: \" + interaction.id());\nSystem.out.println(\"Status: \" + interaction.status());\n\n// Print the text outputs from the interaction.\ninteraction.outputs().ifPresent(outputs -\u003e {\n  for (Content output : outputs) {\n    output.text().ifPresent(text -\u003e System.out.println(\"Output: \" + text.text()));\n  }\n});\n```\n\nFor more examples, see `interactions*` in the [examples directory](https://github.com/googleapis/java-genai/tree/main/examples/).\n\n\n\n## Versioning\n\nThis library follows [Semantic Versioning](http://semver.org/).\n\n## Contribute to this library\n\nThe Google Gen AI Java SDK will accept contributions in the future.\n\n## License\n\nApache 2.0 - See [LICENSE][license] for more information.\n\n[gemini-api-doc]: https://ai.google.dev/gemini-api/docs\n[vertex-api-doc]: https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview\n[maven-version-image]: https://img.shields.io/maven-central/v/com.google.genai/google-genai.svg\n[maven-version-link]: https://central.sonatype.com/artifact/com.google.genai/google-genai\n[javadoc-image]: https://img.shields.io/badge/JavaDoc-Online-green\n[javadoc-link]: https://googleapis.github.io/java-genai/javadoc/\n[license]: https://github.com/googleapis/java-genai/blob/main/LICENSE\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogleapis%2Fjava-genai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogleapis%2Fjava-genai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogleapis%2Fjava-genai/lists"}