-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(genai): add live samples (1) #10194
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jdomingr
wants to merge
2
commits into
GoogleCloudPlatform:main
Choose a base branch
from
jdomingr:genai-sdk-live-samples-p1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+562
−5
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
117 changes: 117 additions & 0 deletions
117
genai/snippets/src/main/java/genai/live/LiveCodeExecWithTxt.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| /* | ||
| * Copyright 2025 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package genai.live; | ||
|
|
||
| // [START googlegenaisdk_live_code_exec_with_txt] | ||
|
|
||
| import static com.google.genai.types.Modality.Known.TEXT; | ||
|
|
||
| import com.google.genai.AsyncSession; | ||
| import com.google.genai.Client; | ||
| import com.google.genai.types.Content; | ||
| import com.google.genai.types.LiveConnectConfig; | ||
| import com.google.genai.types.LiveSendClientContentParameters; | ||
| import com.google.genai.types.LiveServerContent; | ||
| import com.google.genai.types.LiveServerMessage; | ||
| import com.google.genai.types.Part; | ||
| import com.google.genai.types.Tool; | ||
| import com.google.genai.types.ToolCodeExecution; | ||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| public class LiveCodeExecWithTxt { | ||
|
|
||
| public static void main(String[] args) { | ||
| // TODO(developer): Replace these variables before running the sample. | ||
| String modelId = "gemini-2.0-flash-live-preview-04-09"; | ||
| generateContent(modelId); | ||
| } | ||
|
|
||
| // Shows how to generate content with the Code Execution tool and a text input. | ||
| public static void generateContent(String modelId) { | ||
| // Client Initialization. Once created, it can be reused for multiple requests. | ||
| try (Client client = Client.builder().location("us-central1").vertexAI(true).build()) { | ||
|
|
||
| // Connects to the live server. | ||
| CompletableFuture<AsyncSession> sessionFuture = | ||
| client.async.live.connect( | ||
| modelId, | ||
| LiveConnectConfig.builder() | ||
| .responseModalities(TEXT) | ||
| .tools(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build()) | ||
| .build()); | ||
|
|
||
| // Sends and receives messages from the server. | ||
| sessionFuture | ||
| .thenCompose( | ||
| session -> { | ||
| // A future that completes when the server signals the end of its turn. | ||
| CompletableFuture<Void> turnComplete = new CompletableFuture<>(); | ||
| // Starts receiving messages from the live server. | ||
| session.receive(message -> handleLiveServerMessage(message, turnComplete)); | ||
| // Sends content to the server and waits for the turn to complete. | ||
| return sendContent(session) | ||
| .thenCompose(unused -> turnComplete) | ||
| .thenCompose(unused -> session.close()); | ||
| }) | ||
| .join(); | ||
|
|
||
| // Example output: | ||
| // > Compute the largest prime palindrome under 100000 | ||
| // text: Okay, I need | ||
| // text: to find the largest prime palindrome less than 100000... | ||
| // code: ExecutableCode{code=Optional[def is_prime(n):... | ||
| // result: CodeExecutionResult{outcome=Optional[OUTCOME_OK], | ||
| // output=Optional[largest_prime_palindrome=98689... | ||
| // The model is done generating. | ||
| } | ||
| } | ||
|
|
||
| // Sends content to the server. | ||
| private static CompletableFuture<Void> sendContent(AsyncSession session) { | ||
| String textInput = "Compute the largest prime palindrome under 100000"; | ||
| System.out.printf("> %s\n", textInput); | ||
| return session.sendClientContent( | ||
| LiveSendClientContentParameters.builder() | ||
| .turns(Content.builder().role("user").parts(Part.fromText(textInput)).build()) | ||
| .turnComplete(true) | ||
| .build()); | ||
| } | ||
|
|
||
| // Prints response messages from the server and signals `turnComplete` when the server is done. | ||
| private static void handleLiveServerMessage( | ||
| LiveServerMessage message, CompletableFuture<Void> turnComplete) { | ||
| message | ||
| .serverContent() | ||
| .flatMap(LiveServerContent::modelTurn) | ||
| .flatMap(Content::parts) | ||
| .ifPresent( | ||
| parts -> | ||
| parts.forEach( | ||
| part -> { | ||
| part.text().ifPresent(text -> System.out.println("text: " + text)); | ||
| part.executableCode().ifPresent(code -> System.out.println("code: " + code)); | ||
| part.codeExecutionResult() | ||
| .ifPresent(result -> System.out.println("result: " + result)); | ||
| })); | ||
|
|
||
| if (message.serverContent().flatMap(LiveServerContent::turnComplete).orElse(false)) { | ||
| System.out.println("The model is done generating."); | ||
| turnComplete.complete(null); | ||
| } | ||
| } | ||
| } | ||
| // [END googlegenaisdk_live_code_exec_with_txt] | ||
110 changes: 110 additions & 0 deletions
110
genai/snippets/src/main/java/genai/live/LiveGroundGoogSearchWithTxt.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| /* | ||
| * Copyright 2025 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package genai.live; | ||
|
|
||
| // [START googlegenaisdk_live_ground_googsearch_with_txt] | ||
|
|
||
| import static com.google.genai.types.Modality.Known.TEXT; | ||
|
|
||
| import com.google.genai.AsyncSession; | ||
| import com.google.genai.Client; | ||
| import com.google.genai.types.Content; | ||
| import com.google.genai.types.GoogleSearch; | ||
| import com.google.genai.types.LiveConnectConfig; | ||
| import com.google.genai.types.LiveSendClientContentParameters; | ||
| import com.google.genai.types.LiveServerContent; | ||
| import com.google.genai.types.LiveServerMessage; | ||
| import com.google.genai.types.Part; | ||
| import com.google.genai.types.Tool; | ||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| public class LiveGroundGoogSearchWithTxt { | ||
|
|
||
| public static void main(String[] args) { | ||
| // TODO(developer): Replace these variables before running the sample. | ||
| String modelId = "gemini-2.0-flash-live-preview-04-09"; | ||
| generateContent(modelId); | ||
| } | ||
|
|
||
| // Shows how to generate content with the Google Search tool and a text input. | ||
| public static void generateContent(String modelId) { | ||
| // Client Initialization. Once created, it can be reused for multiple requests. | ||
| try (Client client = Client.builder().location("us-central1").vertexAI(true).build()) { | ||
|
|
||
| // Connects to the live server. | ||
| CompletableFuture<AsyncSession> sessionFuture = | ||
| client.async.live.connect( | ||
| modelId, | ||
| LiveConnectConfig.builder() | ||
| .responseModalities(TEXT) | ||
| .tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build()) | ||
| .build()); | ||
|
|
||
| // Sends and receives messages from the server. | ||
| sessionFuture | ||
| .thenCompose( | ||
| session -> { | ||
| // A future that completes when the server signals the end of its turn. | ||
| CompletableFuture<Void> turnComplete = new CompletableFuture<>(); | ||
| // Starts receiving messages from the live server. | ||
| session.receive(message -> handleLiveServerMessage(message, turnComplete)); | ||
| // Sends content to the server and waits for the turn to complete. | ||
| return sendContent(session) | ||
| .thenCompose(unused -> turnComplete) | ||
| .thenCompose(unused -> session.close()); | ||
| }) | ||
| .join(); | ||
| // Example response: | ||
| // > When did the last Brazil vs. Argentina soccer match happen? | ||
| // Output: The last Brazil vs | ||
| // Output: . Argentina soccer match was on March 25, 2025 | ||
| // Output: , a World Cup Qualifying match that Argentina won 4-1. Quite a game. | ||
| // The model is done generating. | ||
| } | ||
| } | ||
|
|
||
| // Sends content to the live server. | ||
| private static CompletableFuture<Void> sendContent(AsyncSession session) { | ||
| String textInput = "When did the last Brazil vs. Argentina soccer match happen?"; | ||
| System.out.printf("> %s\n", textInput); | ||
| return session.sendClientContent( | ||
| LiveSendClientContentParameters.builder() | ||
| .turns(Content.builder().role("user").parts(Part.fromText(textInput)).build()) | ||
| .turnComplete(true) | ||
| .build()); | ||
| } | ||
|
|
||
| // Prints response messages from the server and signals `turnComplete` when the server is done. | ||
| private static void handleLiveServerMessage( | ||
| LiveServerMessage message, CompletableFuture<Void> turnComplete) { | ||
| message | ||
| .serverContent() | ||
| .flatMap(LiveServerContent::modelTurn) | ||
| .flatMap(Content::parts) | ||
| .ifPresent( | ||
| parts -> | ||
| parts.forEach( | ||
| part -> | ||
| part.text().ifPresent(text -> System.out.println("Output: " + text)))); | ||
|
|
||
| if (message.serverContent().flatMap(LiveServerContent::turnComplete).orElse(false)) { | ||
| System.out.println("The model is done generating."); | ||
| turnComplete.complete(null); | ||
| } | ||
jdomingr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| // [END googlegenaisdk_live_ground_googsearch_with_txt] | ||
119 changes: 119 additions & 0 deletions
119
genai/snippets/src/main/java/genai/live/LiveTranscribeWithAudio.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| /* | ||
| * Copyright 2025 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package genai.live; | ||
|
|
||
| // [START googlegenaisdk_live_transcribe_with_audio] | ||
|
|
||
| import static com.google.genai.types.Modality.Known.AUDIO; | ||
|
|
||
| import com.google.genai.AsyncSession; | ||
| import com.google.genai.Client; | ||
| import com.google.genai.types.AudioTranscriptionConfig; | ||
| import com.google.genai.types.Content; | ||
| import com.google.genai.types.LiveConnectConfig; | ||
| import com.google.genai.types.LiveSendClientContentParameters; | ||
| import com.google.genai.types.LiveServerContent; | ||
| import com.google.genai.types.LiveServerMessage; | ||
| import com.google.genai.types.Part; | ||
| import com.google.genai.types.Transcription; | ||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| public class LiveTranscribeWithAudio { | ||
|
|
||
| public static void main(String[] args) { | ||
| // TODO(developer): Replace these variables before running the sample. | ||
| String modelId = "gemini-live-2.5-flash-preview-native-audio"; | ||
| generateContent(modelId); | ||
| } | ||
|
|
||
| // Shows how to transcribe audio | ||
| public static void generateContent(String modelId) { | ||
| // Client Initialization. Once created, it can be reused for multiple requests. | ||
| try (Client client = Client.builder().location("us-central1").vertexAI(true).build()) { | ||
|
|
||
| // Connects to the live server. | ||
| CompletableFuture<AsyncSession> sessionFuture = | ||
| client.async.live.connect( | ||
| modelId, | ||
| LiveConnectConfig.builder() | ||
| .responseModalities(AUDIO) | ||
| .inputAudioTranscription(AudioTranscriptionConfig.builder().build()) | ||
| .outputAudioTranscription(AudioTranscriptionConfig.builder().build()) | ||
| .build()); | ||
|
|
||
| // Sends and receives messages from the live server. | ||
| sessionFuture | ||
| .thenCompose( | ||
| session -> { | ||
| // A future that completes when the server signals the end of its turn. | ||
| CompletableFuture<Void> turnComplete = new CompletableFuture<>(); | ||
| // Starts receiving messages from the live server. | ||
| session.receive(message -> handleLiveServerMessage(message, turnComplete)); | ||
| // Sends content to the server and waits for the turn to complete. | ||
| return sendContent(session) | ||
| .thenCompose(unused -> turnComplete) | ||
| .thenCompose(unused -> session.close()); | ||
| }) | ||
| .join(); | ||
| // Example output: | ||
| // > Hello? Gemini, are you there? | ||
| // Output transcript: Yes, I'm here | ||
| // Output transcript: How can I help you today? | ||
| // ... | ||
| // The model is done generating. | ||
| } | ||
| } | ||
|
|
||
| // Sends content to the live server. | ||
| private static CompletableFuture<Void> sendContent(AsyncSession session) { | ||
| String textInput = "Hello? Gemini, are you there?"; | ||
| System.out.printf("> %s\n", textInput); | ||
| return session.sendClientContent( | ||
| LiveSendClientContentParameters.builder() | ||
| .turns(Content.builder().role("user").parts(Part.fromText(textInput)).build()) | ||
| .turnComplete(true) | ||
| .build()); | ||
| } | ||
|
|
||
| // Prints response messages from the server and signals `turnComplete` when the server is done. | ||
| private static void handleLiveServerMessage( | ||
| LiveServerMessage message, CompletableFuture<Void> turnComplete) { | ||
|
|
||
| if (message.serverContent().isPresent()) { | ||
| LiveServerContent serverContent = message.serverContent().get(); | ||
| serverContent | ||
| .modelTurn() | ||
| .ifPresent(modelTurn -> System.out.println("Model turn: " + modelTurn.parts())); | ||
|
|
||
| serverContent | ||
| .inputTranscription() | ||
| .flatMap(Transcription::text) | ||
| .ifPresent(text -> System.out.println("Input transcript: " + text)); | ||
|
|
||
| serverContent | ||
| .outputTranscription() | ||
| .flatMap(Transcription::text) | ||
| .ifPresent(text -> System.out.println("Output transcript: " + text)); | ||
|
|
||
| if (serverContent.turnComplete().orElse(false)) { | ||
| System.out.println("The model is done generating."); | ||
| turnComplete.complete(null); | ||
| } | ||
| } | ||
jdomingr marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| // [END googlegenaisdk_live_transcribe_with_audio] | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.