From cc9237756e2d90dc7b6ffcaef7d3e4ed1907cac2 Mon Sep 17 00:00:00 2001 From: Katlyn Edwards Date: Wed, 7 Oct 2026 13:20:18 -0700 Subject: [PATCH] No public description PiperOrigin-RevId: 995312571 --- interactions/JavaSamplesTest.java | 1035 +++++++++++++++++ interactions/bash_samples_test.sh | 621 ++++++++++ interactions/go_samples_test.go | 1413 +++++++++++++++++++++++ interactions/package.json | 17 + interactions/pom.xml | 57 + interactions/python_samples_test.py | 827 +++++++++++++ interactions/typescript_samples_test.ts | 794 +++++++++++++ javascript/code_execution.js | 2 +- javascript/count_tokens.js | 4 +- javascript/function_calling.js | 2 +- javascript/safety_settings.js | 2 +- rest/cache.sh | 5 +- rest/chat.sh | 6 +- rest/code_execution.sh | 4 +- rest/configure_model_parameters.sh | 2 +- rest/controlled_generation.sh | 4 +- rest/count_tokens.sh | 24 +- rest/files.sh | 12 +- rest/function_calling.sh | 2 +- rest/models.sh | 2 +- rest/safety_settings.sh | 4 +- rest/system_instruction.sh | 2 +- rest/text_generation.sh | 24 +- 23 files changed, 4813 insertions(+), 52 deletions(-) create mode 100644 interactions/JavaSamplesTest.java create mode 100644 interactions/bash_samples_test.sh create mode 100644 interactions/go_samples_test.go create mode 100644 interactions/package.json create mode 100644 interactions/pom.xml create mode 100644 interactions/python_samples_test.py create mode 100644 interactions/typescript_samples_test.ts diff --git a/interactions/JavaSamplesTest.java b/interactions/JavaSamplesTest.java new file mode 100644 index 0000000..eecfd1e --- /dev/null +++ b/interactions/JavaSamplesTest.java @@ -0,0 +1,1035 @@ +/** + * Copyright 2026 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 com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.gaos.models.agents.Agent; +import com.google.genai.gaos.models.agents.AgentListResponse; +import com.google.genai.gaos.models.agents.BaseEnvironment; +import com.google.genai.gaos.models.environments.CreateEnvironmentRequest; +import com.google.genai.gaos.models.environments.EnvironmentFile; +import com.google.genai.gaos.models.environments.GetEnvironmentFilesResponse; +import com.google.genai.gaos.models.interactions.AgentOption; +import com.google.genai.gaos.models.interactions.CodeExecution; +import com.google.genai.gaos.models.interactions.ComputerUse; +import com.google.genai.gaos.models.interactions.Content; +import com.google.genai.gaos.models.interactions.CreateAgentInteraction; +import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment; +import com.google.genai.gaos.models.interactions.CreateModelInteraction; +import com.google.genai.gaos.models.interactions.FileSearch; +import com.google.genai.gaos.models.interactions.Function; +import com.google.genai.gaos.models.interactions.GoogleMaps; +import com.google.genai.gaos.models.interactions.GoogleSearch; +import com.google.genai.gaos.models.interactions.ImageContent; +import com.google.genai.gaos.models.interactions.ImageContentMimeType; +import com.google.genai.gaos.models.interactions.Interaction; +import com.google.genai.gaos.models.interactions.InteractionStatus; +import com.google.genai.gaos.models.interactions.InteractionsInput; +import com.google.genai.gaos.models.interactions.MCPServer; +import com.google.genai.gaos.models.interactions.ModelOutputStep; +import com.google.genai.gaos.models.interactions.Source; +import com.google.genai.gaos.models.interactions.SourceType; +import com.google.genai.gaos.models.interactions.Step; +import com.google.genai.gaos.models.interactions.TextContent; +import com.google.genai.gaos.models.interactions.URLContext; +import com.google.genai.gaos.models.interactions.UserInputStep; +import com.google.genai.gaos.models.operations.CancelInteractionByIdResponse; +import com.google.genai.gaos.models.operations.CreateAgentResponse; +import com.google.genai.gaos.models.operations.CreateInteractionRequestBody; +import com.google.genai.gaos.models.operations.CreateInteractionResponse; +import com.google.genai.gaos.models.operations.CreateTriggerResponse; +import com.google.genai.gaos.models.operations.GetAgentResponse; +import com.google.genai.gaos.models.operations.GetEnvironmentFilesRequest; +import com.google.genai.gaos.models.operations.GetInteractionByIdRequest; +import com.google.genai.gaos.models.operations.GetInteractionByIdResponse; +import com.google.genai.gaos.models.operations.ListAgentsResponse; +import com.google.genai.gaos.models.operations.ListEnvironmentsResponse; +import com.google.genai.gaos.models.triggers.Trigger; +import com.google.genai.gaos.models.triggers.TriggerCreateParams; +import com.google.genai.types.CreateFileSearchStoreConfig; +import com.google.genai.types.FileSearchStore; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class JavaSamplesTest { + + @Test + public void testApiVersionAgentsGetList() throws Exception { + // [START paths['/{api_version}/agents'].get:list] + + Client client = new Client(); + ListAgentsResponse response = client.agents.list().call(); + List agents = + response.agentListResponse().flatMap(AgentListResponse::agents).orElse(List.of()); + for (Agent agent : agents) { + agent.id().ifPresent(System.out::println); + } + // [END paths['/{api_version}/agents'].get:list] + } + + @Test + public void testApiVersionAgentsPostCreate() throws Exception { + // [START paths['/{api_version}/agents'].post:create] + + Client client = new Client(); + String agentId = "research-assistant-" + UUID.randomUUID().toString().substring(0, 8); + Agent agent = + Agent.builder() + .id(agentId) + .baseAgent("antigravity-preview-05-2026") + .description("A helpful research assistant.") + .systemInstruction("You are a helpful research assistant.") + .baseEnvironment(BaseEnvironment.of("remote")) + .tools(List.of(new GoogleSearch())) + .build(); + CreateAgentResponse response = client.agents.create(agent); + System.out.println(response.agent().flatMap(Agent::id).orElse("")); + + // [cleanup] + client.agents.delete(agentId); + // [/cleanup] + // [END paths['/{api_version}/agents'].post:create] + } + + @Test + public void testApiVersionAgentsPostWithSources() throws Exception { + // [START paths['/{api_version}/agents'].post:with_sources] + + Client client = new Client(); + String agentId = "data-analyst-" + UUID.randomUUID().toString().substring(0, 8); + com.google.genai.gaos.models.interactions.Environment env = + com.google.genai.gaos.models.interactions.Environment.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.INLINE) + .target(".agents/AGENTS.md") + .content( + "Always use matplotlib for charts. Include a summary table in every" + + " report.") + .build(), + Source.builder() + .type(SourceType.REPOSITORY) + .source("https://github.com/my-org/analysis-templates") + .target("/workspace/templates") + .build())) + .build(); + Agent agent = + Agent.builder() + .id(agentId) + .baseAgent("antigravity-preview-05-2026") + .systemInstruction( + "You are a data analyst. Always include visualizations and export results as PDF.") + .baseEnvironment(BaseEnvironment.of(env)) + .build(); + CreateAgentResponse response = client.agents.create(agent); + System.out.println("Created agent: " + response.agent().flatMap(Agent::id).orElse("")); + + // [cleanup] + client.agents.delete(agentId); + // [/cleanup] + // [END paths['/{api_version}/agents'].post:with_sources] + } + + @Test + public void testApiVersionAgentsPostForkFromEnv() throws Exception { + // [START paths['/{api_version}/agents'].post:fork_from_env] + + Client client = new Client(); + + // Step 1: Set up the environment interactively. + CreateAgentInteraction params = + CreateAgentInteraction.builder() + .agent(AgentOption.of("antigravity-preview-05-2026")) + .input( + InteractionsInput.of( + "Write a basic Hello World template to /workspace/template.py.")) + .environment(CreateAgentInteractionEnvironment.of("remote")) + .build(); + CreateInteractionResponse interactionResponse = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + interactionResponse + .interaction() + .orElseThrow(() -> new RuntimeException("No interaction returned")); + + // Step 2: Fork that environment into a named agent. + String agentId = "my-data-analyst-" + UUID.randomUUID().toString().substring(0, 8); + Agent agent = + Agent.builder() + .id(agentId) + .baseAgent("antigravity-preview-05-2026") + .systemInstruction( + "You are a data analyst. Use the template at /workspace/template.py for all" + + " reports.") + .baseEnvironment(BaseEnvironment.of(interaction.environmentId().orElse(""))) + .build(); + CreateAgentResponse agentResponse = client.agents.create(agent); + System.out.println("Forked agent: " + agentResponse.agent().flatMap(Agent::id).orElse("")); + + // [cleanup] + client.agents.delete(agentId); + // [/cleanup] + // [END paths['/{api_version}/agents'].post:fork_from_env] + } + + @Test + public void testApiVersionAgentsIdDeleteDelete() throws Exception { + // [START paths['/{api_version}/agents/{id}'].delete:delete] + + Client client = new Client(); + + // [setup] + String agentId = "delete-test-" + UUID.randomUUID().toString().substring(0, 8); + client.agents.create( + Agent.builder() + .id(agentId) + .baseAgent("antigravity-preview-05-2026") + .description("Temporary agent for deletion.") + .baseEnvironment(BaseEnvironment.of("remote")) + .build()); + // [/setup] + + client.agents.delete(agentId); + System.out.println("Agent deleted successfully."); + // [END paths['/{api_version}/agents/{id}'].delete:delete] + } + + @Test + public void testApiVersionAgentsIdGetGet() throws Exception { + // [START paths['/{api_version}/agents/{id}'].get:get] + + Client client = new Client(); + + // [setup] + String agentId = "test-agent-" + UUID.randomUUID().toString().substring(0, 8); + client.agents.create( + Agent.builder() + .id(agentId) + .baseAgent("antigravity-preview-05-2026") + .description("A test agent.") + .baseEnvironment(BaseEnvironment.of("remote")) + .build()); + // [/setup] + + GetAgentResponse response = client.agents.get(agentId); + Agent agent = response.agent().orElseThrow(() -> new RuntimeException("No agent returned")); + System.out.println(agent.id().orElse("")); + + // [cleanup] + client.agents.delete(agentId); + // [/cleanup] + // [END paths['/{api_version}/agents/{id}'].get:get] + } + + @Test + public void testApiVersionEnvironmentsGetList() throws Exception { + // [START paths['/{api_version}/environments'].get:list] + + Client client = new Client(); + ListEnvironmentsResponse response = client.environments.listEnvironmentsDirect(); + for (com.google.genai.gaos.models.environments.Environment env : + response.listEnvironmentsResponse().flatMap(res -> res.environments()).orElse(List.of())) { + System.out.println(env.id().orElse("")); + } + // [END paths['/{api_version}/environments'].get:list] + } + + @Test + public void testApiVersionEnvironmentsPostCreate() throws Exception { + // [START paths['/{api_version}/environments'].post:create] + + Client client = new Client(); + CreateEnvironmentRequest request = + CreateEnvironmentRequest.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.INLINE) + .target("main.py") + .content("print('Hello, World!')") + .build())) + .build(); + com.google.genai.gaos.models.environments.Environment environment = + client.environments.createEnvironment(request).environment().orElseThrow(); + System.out.println(environment.id().orElse("")); + + // [cleanup] + environment.id().ifPresent(id -> client.environments.deleteEnvironment(id)); + // [/cleanup] + // [END paths['/{api_version}/environments'].post:create] + } + + @Test + public void testApiVersionEnvironmentsPostCopy() throws Exception { + // [START paths['/{api_version}/environments'].post:copy] + + Client client = new Client(); + + // [setup] + CreateEnvironmentRequest setupReq = + CreateEnvironmentRequest.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.INLINE) + .target("main.py") + .content("print('Hello')") + .build())) + .build(); + com.google.genai.gaos.models.environments.Environment sourceEnv = + client.environments.createEnvironment(setupReq).environment().orElseThrow(); + String sourceEnvId = sourceEnv.id().orElseThrow(); + // [/setup] + + CreateEnvironmentRequest request = + CreateEnvironmentRequest.builder().fromEnvironment(sourceEnvId).build(); + com.google.genai.gaos.models.environments.Environment environment = + client.environments.createEnvironment(request).environment().orElseThrow(); + System.out.println(environment.id().orElse("")); + + // [cleanup] + environment.id().ifPresent(id -> client.environments.deleteEnvironment(id)); + client.environments.deleteEnvironment(sourceEnvId); + // [/cleanup] + // [END paths['/{api_version}/environments'].post:copy] + } + + @Test + public void testApiVersionEnvironmentsEnvironmentFilesPathGetListFiles() throws Exception { + // [START paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] + + Client client = new Client(); + + // [setup] + CreateEnvironmentRequest createReq = + CreateEnvironmentRequest.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.INLINE) + .target("src/main.py") + .content("print('Hello')") + .build())) + .build(); + com.google.genai.gaos.models.environments.Environment created = + client.environments.createEnvironment(createReq).environment().orElseThrow(); + String envId = created.id().orElseThrow(); + // [/setup] + + com.google.genai.gaos.models.operations.GetEnvironmentFilesResponse response = + client + .environments + .files() + .list(GetEnvironmentFilesRequest.builder().environment(envId).path("src").build()); + GetEnvironmentFilesResponse filesResponse = + response.getEnvironmentFilesResponse().orElseThrow(); + for (EnvironmentFile file : filesResponse.files().orElse(List.of())) { + System.out.println( + file.name().orElse("") + + " " + + file.type().map(Object::toString).orElse("") + + " " + + file.sizeBytes().orElse("")); + } + + // [cleanup] + client.environments.deleteEnvironment(envId); + // [/cleanup] + // [END paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] + } + + @Test + public void testApiVersionEnvironmentsEnvironmentFilesPathGetGetFile() throws Exception { + // [START paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] + + Client client = new Client(); + + // [setup] + CreateEnvironmentRequest createReq = + CreateEnvironmentRequest.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.INLINE) + .target("main.py") + .content("print('Hello')") + .build())) + .build(); + com.google.genai.gaos.models.environments.Environment created = + client.environments.createEnvironment(createReq).environment().orElseThrow(); + String envId = created.id().orElseThrow(); + // [/setup] + + com.google.genai.gaos.models.operations.GetEnvironmentFilesResponse response = + client + .environments + .files() + .list(GetEnvironmentFilesRequest.builder().environment(envId).path("main.py").build()); + GetEnvironmentFilesResponse filesResponse = + response.getEnvironmentFilesResponse().orElseThrow(); + for (EnvironmentFile file : filesResponse.files().orElse(List.of())) { + System.out.println(file.name().orElse("") + " " + file.sizeBytes().orElse("")); + } + + // [cleanup] + client.environments.deleteEnvironment(envId); + // [/cleanup] + // [END paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] + } + + @Test + public void testApiVersionEnvironmentsIdDeleteDelete() throws Exception { + // [START paths['/{api_version}/environments/{id}'].delete:delete] + + Client client = new Client(); + + // [setup] + CreateEnvironmentRequest request = + CreateEnvironmentRequest.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.INLINE) + .target("main.py") + .content("print('Hello')") + .build())) + .build(); + com.google.genai.gaos.models.environments.Environment created = + client.environments.createEnvironment(request).environment().orElseThrow(); + String envId = created.id().orElseThrow(); + // [/setup] + + client.environments.deleteEnvironment(envId); + System.out.println( + "com.google.genai.gaos.models.environments.Environment deleted successfully."); + // [END paths['/{api_version}/environments/{id}'].delete:delete] + } + + @Test + public void testApiVersionEnvironmentsIdGetGet() throws Exception { + // [START paths['/{api_version}/environments/{id}'].get:get] + + Client client = new Client(); + + // [setup] + CreateEnvironmentRequest request = + CreateEnvironmentRequest.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.INLINE) + .target("main.py") + .content("print('Hello')") + .build())) + .build(); + com.google.genai.gaos.models.environments.Environment created = + client.environments.createEnvironment(request).environment().orElseThrow(); + String envId = created.id().orElseThrow(); + // [/setup] + + com.google.genai.gaos.models.environments.Environment environment = + client.environments.getEnvironment(envId).environment().orElseThrow(); + System.out.println(environment.id().orElse("")); + + // [cleanup] + client.environments.deleteEnvironment(envId); + // [/cleanup] + // [END paths['/{api_version}/environments/{id}'].get:get] + } + + @Test + public void testApiVersionInteractionsPostSimple() throws Exception { + // [START paths['/{api_version}/interactions'].post:simple] + + Client client = new Client(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .input(InteractionsInput.of("Hello, how are you?")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END paths['/{api_version}/interactions'].post:simple] + } + + @Test + public void testApiVersionInteractionsPostMultiTurn() throws Exception { + // [START paths['/{api_version}/interactions'].post:multi_turn] + + Client client = new Client(); + List conversation = + List.of( + UserInputStep.builder() + .content(List.of(TextContent.builder().text("Hello!").build())) + .build(), + ModelOutputStep.builder() + .content( + List.of( + TextContent.builder().text("Hi there! How can I help you today?").build())) + .build(), + UserInputStep.builder() + .content( + List.of(TextContent.builder().text("What is the capital of France?").build())) + .build()); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .input(InteractionsInput.ofStep(conversation)) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END paths['/{api_version}/interactions'].post:multi_turn] + } + + @Test + public void testApiVersionInteractionsPostMultimodalImage() throws Exception { + // [START paths['/{api_version}/interactions'].post:multimodal_image] + + Client client = new Client(); + List content = + List.of( + TextContent.builder().text("What is in this picture?").build(), + ImageContent.builder() + .data("BASE64_ENCODED_IMAGE") + .mimeType(ImageContentMimeType.IMAGE_PNG) + .build()); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .input(InteractionsInput.ofContent(content)) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END paths['/{api_version}/interactions'].post:multimodal_image] + } + + @Test + public void testApiVersionInteractionsPostFunctionCalling() throws Exception { + // [START paths['/{api_version}/interactions'].post:function_calling] + + Client client = new Client(); + Map parameters = + Map.of( + "type", "object", + "properties", + Map.of( + "location", + Map.of( + "type", "string", + "description", "The city and state, e.g. San Francisco, CA")), + "required", List.of("location")); + Function functionTool = + Function.builder() + .name("get_weather") + .description("Get the current weather in a given location") + .parameters(parameters) + .build(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(functionTool)) + .input(InteractionsInput.of("What is the weather like in Boston, MA?")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + List steps = interaction.steps().orElse(List.of()); + if (!steps.isEmpty()) { + System.out.println(steps.get(steps.size() - 1)); + } + // [END paths['/{api_version}/interactions'].post:function_calling] + } + + @Test + public void testApiVersionInteractionsPostDeepResearch() throws Exception { + // [START paths['/{api_version}/interactions'].post:deep_research] + + Client client = new Client(); + CreateAgentInteraction params = + CreateAgentInteraction.builder() + .agent(AgentOption.of("deep-research-pro-preview-12-2025")) + .input(InteractionsInput.of("find a cure to cancer")) + .background(true) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.status().map(InteractionStatus::value).orElse("")); + // [END paths['/{api_version}/interactions'].post:deep_research] + } + + @Test + public void testApiVersionInteractionsPostAntigravity() throws Exception { + // [START paths['/{api_version}/interactions'].post:antigravity] + + Client client = new Client(); + CreateAgentInteraction params = + CreateAgentInteraction.builder() + .agent(AgentOption.of("antigravity-preview-05-2026")) + .input( + InteractionsInput.of( + "Read Hacker News, summarize the top 5 stories, and save results as a markdown" + + " file.")) + .environment(CreateAgentInteractionEnvironment.of("remote")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END paths['/{api_version}/interactions'].post:antigravity] + } + + @Test + public void testApiVersionInteractionsPostReuseEnv() throws Exception { + // [START paths['/{api_version}/interactions'].post:reuse_env] + + Client client = new Client(); + + // Step 1: Create an interaction with a fresh remote environment. + CreateAgentInteraction params1 = + CreateAgentInteraction.builder() + .agent(AgentOption.of("antigravity-preview-05-2026")) + .input(InteractionsInput.of("Write a hello world script at /workspace/hello.py.")) + .environment(CreateAgentInteractionEnvironment.of("remote")) + .build(); + CreateInteractionResponse response1 = + client.interactions.create(CreateInteractionRequestBody.of(params1)); + Interaction interaction1 = + response1.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println("Environment ID: " + interaction1.environmentId().orElse("")); + + // Step 2: Reuse the same environment in a follow-up interaction. + CreateAgentInteraction params2 = + CreateAgentInteraction.builder() + .agent(AgentOption.of("antigravity-preview-05-2026")) + .input( + InteractionsInput.of( + "Modify the script to accept a name argument and greet the user.")) + .environment( + CreateAgentInteractionEnvironment.of(interaction1.environmentId().orElse(""))) + .previousInteractionId(interaction1.id().orElse(null)) + .build(); + CreateInteractionResponse response2 = + client.interactions.create(CreateInteractionRequestBody.of(params2)); + Interaction interaction2 = + response2.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction2.outputText().orElse("")); + // [END paths['/{api_version}/interactions'].post:reuse_env] + } + + @Test + public void testApiVersionInteractionsPostWithSources() throws Exception { + // [START paths['/{api_version}/interactions'].post:with_sources] + + Client client = new Client(); + com.google.genai.gaos.models.interactions.Environment env = + com.google.genai.gaos.models.interactions.Environment.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.REPOSITORY) + .source("https://github.com/octocat/Spoon-Knife") + .target("/workspace/repo") + .build(), + Source.builder() + .type(SourceType.INLINE) + .content("Focus on Python files only.") + .target("/workspace/notes.txt") + .build())) + .build(); + CreateAgentInteraction params = + CreateAgentInteraction.builder() + .agent(AgentOption.of("antigravity-preview-05-2026")) + .input( + InteractionsInput.of( + "List all files under /workspace and summarize what you find.")) + .environment(CreateAgentInteractionEnvironment.of(env)) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END paths['/{api_version}/interactions'].post:with_sources] + } + + @Test + public void testApiVersionInteractionsPostCustomAgent() throws Exception { + // [START paths['/{api_version}/interactions'].post:custom_agent] + + Client client = new Client(); + + // Step 1: Create a custom agent. + String agentId = "code-reviewer-" + UUID.randomUUID().toString().substring(0, 8); + com.google.genai.gaos.models.interactions.Environment baseEnv = + com.google.genai.gaos.models.interactions.Environment.builder() + .sources( + List.of( + Source.builder() + .type(SourceType.REPOSITORY) + .source("https://github.com/octocat/Spoon-Knife") + .target("/workspace/repo") + .build())) + .build(); + Agent customAgent = + Agent.builder() + .id(agentId) + .baseAgent("antigravity-preview-05-2026") + .systemInstruction( + "You are a senior code reviewer. Check every file for bugs, style issues, and" + + " security vulnerabilities.") + .baseEnvironment(BaseEnvironment.of(baseEnv)) + .build(); + client.agents.create(customAgent); + + // Step 2: Use the custom agent. + CreateAgentInteraction params = + CreateAgentInteraction.builder() + .agent(AgentOption.of(agentId)) + .input( + InteractionsInput.of( + "Review the latest changes in /workspace/repo/src and file a summary.")) + .environment(CreateAgentInteractionEnvironment.of("remote")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + + // [cleanup] + client.agents.delete(agentId); + // [/cleanup] + // [END paths['/{api_version}/interactions'].post:custom_agent] + } + + @Test + public void testApiVersionInteractionsIdDeleteDelete() throws Exception { + // [START paths['/{api_version}/interactions/{id}'].delete:delete] + + Client client = new Client(); + + // [setup] + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .input(InteractionsInput.of("Hello")) + .build(); + CreateInteractionResponse created = + client.interactions.create(CreateInteractionRequestBody.of(params)); + String interactionId = created.interaction().flatMap(Interaction::id).orElseThrow(); + // [/setup] + + client.interactions.delete(interactionId); + System.out.println("Interaction deleted successfully."); + // [END paths['/{api_version}/interactions/{id}'].delete:delete] + } + + @Test + public void testApiVersionInteractionsIdGetGet() throws Exception { + // [START paths['/{api_version}/interactions/{id}'].get:get] + + Client client = new Client(); + + // [setup] + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .input(InteractionsInput.of("Say hello.")) + .build(); + CreateInteractionResponse created = + client.interactions.create(CreateInteractionRequestBody.of(params)); + String interactionId = created.interaction().flatMap(Interaction::id).orElseThrow(); + // [/setup] + + GetInteractionByIdResponse getResponse = + client.interactions.get(new GetInteractionByIdRequest(interactionId)); + Interaction interaction = + getResponse + .interaction() + .orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.status().map(InteractionStatus::value).orElse("")); + // [END paths['/{api_version}/interactions/{id}'].get:get] + } + + @Test + public void testApiVersionInteractionsIdCancelPostCancel() throws Exception { + // [START paths['/{api_version}/interactions/{id}/cancel'].post:cancel] + + Client client = new Client(); + + // Start a background interaction so it stays in-progress. + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .input(InteractionsInput.of("Write a long essay about the history of computing.")) + .tools(List.of(new ComputerUse())) + .background(true) + .build(); + CreateInteractionResponse created = + client.interactions.create(CreateInteractionRequestBody.of(params)); + String interactionId = created.interaction().flatMap(Interaction::id).orElseThrow(); + + // Cancel the in-progress interaction. + CancelInteractionByIdResponse cancelResponse = client.interactions.cancel(interactionId); + Interaction interaction = + cancelResponse + .interaction() + .orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.status().map(InteractionStatus::value).orElse("")); + // [END paths['/{api_version}/interactions/{id}/cancel'].post:cancel] + } + + @Test + public void testSchemaCodeexecutionCodeExecution() throws Exception { + // [START components.schemas.CodeExecution:code_execution] + + Client client = new Client(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(new CodeExecution())) + .input(InteractionsInput.of("Calculate the first 10 Fibonacci numbers")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END components.schemas.CodeExecution:code_execution] + } + + @Test + public void testSchemaComputeruseComputerUse() throws Exception { + // [START components.schemas.ComputerUse:computer_use] + + Client client = new Client(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-2.5-computer-use-preview-10-2025") + .tools(List.of(new ComputerUse())) + .input(InteractionsInput.of("Find a flight to Tokyo")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END components.schemas.ComputerUse:computer_use] + } + + @Test + public void testSchemaFilesearchFileSearch() throws Exception { + // [START components.schemas.FileSearch:file_search] + + Client client = new Client(); + + // Create a file search store so we have a valid one to use. + FileSearchStore store = + client.fileSearchStores.create(CreateFileSearchStoreConfig.builder().build()); + String storeName = store.name().orElseThrow(); + + FileSearch tool = FileSearch.builder().fileSearchStoreNames(List.of(storeName)).build(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(tool)) + .input(InteractionsInput.of("What documents are available?")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + + // [cleanup] + client.fileSearchStores.delete(storeName, null); + // [/cleanup] + // [END components.schemas.FileSearch:file_search] + } + + @Test + public void testSchemaFunctionFunctionCalling() throws Exception { + // [START components.schemas.Function:function_calling] + + Client client = new Client(); + Map parameters = + Map.of( + "type", "object", + "properties", + Map.of( + "location", + Map.of( + "type", "string", + "description", "The city and state, e.g. San Francisco, CA")), + "required", List.of("location")); + Function functionTool = + Function.builder() + .name("get_weather") + .description("Get the current weather in a given location") + .parameters(parameters) + .build(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(functionTool)) + .input(InteractionsInput.of("What is the weather like in Boston?")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + List steps = interaction.steps().orElse(List.of()); + if (!steps.isEmpty()) { + System.out.println(steps.get(steps.size() - 1)); + } + // [END components.schemas.Function:function_calling] + } + + @Test + public void testSchemaGooglemapsGoogleMaps() throws Exception { + // [START components.schemas.GoogleMaps:google_maps] + + Client client = new Client(); + GoogleMaps tool = GoogleMaps.builder().latitude(37.7749).longitude(-122.4194).build(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(tool)) + .input(InteractionsInput.of("What is the best food near me?")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END components.schemas.GoogleMaps:google_maps] + } + + @Test + public void testSchemaGooglesearchGoogleSearch() throws Exception { + // [START components.schemas.GoogleSearch:google_search] + + Client client = new Client(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(new GoogleSearch())) + .input(InteractionsInput.of("Who is the current president of France?")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END components.schemas.GoogleSearch:google_search] + } + + @Test + public void testSchemaMcpserverMcpServer() throws Exception { + // [START components.schemas.McpServer:mcp_server] + + Client client = new Client(); + MCPServer mcpTool = + MCPServer.builder() + .name("weather_service") + .url("https://gemini-api-demos.uc.r.appspot.com/mcp") + .build(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(mcpTool)) + .input( + InteractionsInput.of( + "Today is 12-05-2025, what is the temperature today in London?")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END components.schemas.McpServer:mcp_server] + } + + @Test + public void testSchemaUrlcontextUrlContext() throws Exception { + // [START components.schemas.UrlContext:url_context] + + Client client = new Client(); + CreateModelInteraction params = + CreateModelInteraction.builder() + .model("gemini-3.6-flash") + .tools(List.of(new URLContext())) + .input(InteractionsInput.of("Summarize https://www.example.com")) + .build(); + CreateInteractionResponse response = + client.interactions.create(CreateInteractionRequestBody.of(params)); + Interaction interaction = + response.interaction().orElseThrow(() -> new RuntimeException("No interaction returned")); + System.out.println(interaction.outputText().orElse("")); + // [END components.schemas.UrlContext:url_context] + } + + @Test + public void testApiVersionTriggersPostCreate() throws Exception { + // [START paths['/{api_version}/triggers'].post:create] + + Client client = new Client(); + CreateAgentInteraction interaction = + CreateAgentInteraction.builder() + .agent(AgentOption.of("antigravity-preview-05-2026")) + .input(InteractionsInput.of("Summarize top news stories.")) + .environment(CreateAgentInteractionEnvironment.of("remote")) + .build(); + TriggerCreateParams params = + TriggerCreateParams.builder() + .schedule("0 9 * * *") + .timeZone("America/New_York") + .interaction(interaction) + .build(); + CreateTriggerResponse response = client.triggers.create(params); + Trigger trigger = + response.trigger().orElseThrow(() -> new RuntimeException("No trigger returned")); + System.out.println( + trigger.id().orElse("") + + " " + + trigger.interaction().flatMap(CreateAgentInteraction::agent).orElse(null)); + + // [cleanup] + trigger.id().ifPresent(client.triggers::delete); + // [/cleanup] + // [END paths['/{api_version}/triggers'].post:create] + } +} diff --git a/interactions/bash_samples_test.sh b/interactions/bash_samples_test.sh new file mode 100644 index 0000000..47d06e3 --- /dev/null +++ b/interactions/bash_samples_test.sh @@ -0,0 +1,621 @@ +#!/bin/bash +# Copyright 2026 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. + +set -e + +sample_upload_api_version_environments_environment_files_path_put_start_upload() { +# [START paths['/upload/{api_version}/environments/{environment}/files/{path}'].put:start_upload] +curl -i -X PUT \ + 'https://generativelanguage.googleapis.com/upload/v1beta/environments/env_abc123/files/main.py?overwrite=true' \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H 'X-Goog-Upload-Protocol: resumable' \ + -H 'X-Goog-Upload-Command: start' \ + -H "X-Goog-Upload-Header-Content-Length: $(wc -c < main.py)" \ + -H 'X-Goog-Upload-Header-Content-Type: text/x-python' +# [END paths['/upload/{api_version}/environments/{environment}/files/{path}'].put:start_upload] +} + +sample_api_version_agents_get_list() { +# [START paths['/{api_version}/agents'].get:list] +curl -X GET https://generativelanguage.googleapis.com/v1beta/agents \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/agents'].get:list] +} + +sample_api_version_agents_post_create() { +# [START paths['/{api_version}/agents'].post:create] +curl -X POST https://generativelanguage.googleapis.com/v1beta/agents \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "id": "research-assistant-abc123", + "base_agent": "antigravity-preview-05-2026", + "description": "A helpful research assistant.", + "system_instruction": "You are a helpful research assistant.", + "base_environment": "remote", + "tools": [{"type": "google_search"}] + }' +# [END paths['/{api_version}/agents'].post:create] +} + +sample_api_version_agents_post_with_sources() { +# [START paths['/{api_version}/agents'].post:with_sources] +curl -X POST https://generativelanguage.googleapis.com/v1beta/agents \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "id": "data-analyst-abc123", + "base_agent": "antigravity-preview-05-2026", + "system_instruction": "You are a data analyst. Always include visualizations and export results as PDF.", + "base_environment": { + "type": "remote", + "sources": [ + { + "type": "inline", + "target": ".agents/AGENTS.md", + "content": "Always use matplotlib for charts. Include a summary table in every report." + }, + { + "type": "repository", + "source": "https://github.com/my-org/analysis-templates", + "target": "/workspace/templates" + } + ] + } + }' +# [END paths['/{api_version}/agents'].post:with_sources] +} + +sample_api_version_agents_post_fork_from_env() { +# [START paths['/{api_version}/agents'].post:fork_from_env] +# Step 1: Set up the environment interactively +RESPONSE=$(curl -s -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "agent": "antigravity-preview-05-2026", + "input": "Write a basic Hello World template to /workspace/template.py.", + "environment": "remote" + }') +ENV_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['environment_id'])") + +# Step 2: Fork that environment into a named agent +curl -X POST https://generativelanguage.googleapis.com/v1beta/agents \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d "{ + \"id\": \"my-data-analyst\", + \"base_agent\": \"antigravity-preview-05-2026\", + \"system_instruction\": \"You are a data analyst. Use the template at /workspace/template.py for all reports.\", + \"base_environment\": \"$ENV_ID\" + }" +# [END paths['/{api_version}/agents'].post:fork_from_env] +} + +sample_api_version_agents_id_delete_delete() { +# [START paths['/{api_version}/agents/{id}'].delete:delete] +curl -X DELETE https://generativelanguage.googleapis.com/v1beta/agents/ag_abc123 \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/agents/{id}'].delete:delete] +} + +sample_api_version_agents_id_get_get() { +# [START paths['/{api_version}/agents/{id}'].get:get] +curl -X GET https://generativelanguage.googleapis.com/v1beta/agents/ag_abc123 \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/agents/{id}'].get:get] +} + +sample_api_version_environments_get_list() { +# [START paths['/{api_version}/environments'].get:list] +curl -X GET https://generativelanguage.googleapis.com/v1beta/environments \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/environments'].get:list] +} + +sample_api_version_environments_post_create() { +# [START paths['/{api_version}/environments'].post:create] +curl -X POST https://generativelanguage.googleapis.com/v1beta/environments \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "sources": [{ + "type": "inline", + "target": "main.py", + "content": "print(\"Hello, World!\")" + }] + }' +# [END paths['/{api_version}/environments'].post:create] +} + +sample_api_version_environments_post_copy() { +# [START paths['/{api_version}/environments'].post:copy] +curl -X POST https://generativelanguage.googleapis.com/v1beta/environments \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "from_environment": "environments/env_abc123" + }' +# [END paths['/{api_version}/environments'].post:copy] +} + +sample_api_version_environments_environment_files_path_get_list_files() { +# [START paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] +curl -X GET 'https://generativelanguage.googleapis.com/v1beta/environments/env_abc123/files/src' \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] +} + +sample_api_version_environments_environment_files_path_get_get_file() { +# [START paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] +curl -X GET 'https://generativelanguage.googleapis.com/v1beta/environments/env_abc123/files/main.py' \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] +} + +sample_api_version_environments_environment_files_path_get_download_file() { +# [START paths['/{api_version}/environments/{environment}/files/{path}'].get:download_file] +curl -X GET 'https://generativelanguage.googleapis.com/v1beta/environments/env_abc123/files/src/main.py?alt=media' \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + --output main.py +# [END paths['/{api_version}/environments/{environment}/files/{path}'].get:download_file] +} + +sample_api_version_environments_id_delete_delete() { +# [START paths['/{api_version}/environments/{id}'].delete:delete] +curl -X DELETE https://generativelanguage.googleapis.com/v1beta/environments/env_abc123 \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/environments/{id}'].delete:delete] +} + +sample_api_version_environments_id_get_get() { +# [START paths['/{api_version}/environments/{id}'].get:get] +curl -X GET https://generativelanguage.googleapis.com/v1beta/environments/env_abc123 \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/environments/{id}'].get:get] +} + +sample_api_version_interactions_post_simple() { +# [START paths['/{api_version}/interactions'].post:simple] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "input": "Hello, how are you?" + }' +# [END paths['/{api_version}/interactions'].post:simple] +} + +sample_api_version_interactions_post_multi_turn() { +# [START paths['/{api_version}/interactions'].post:multi_turn] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "input": [ + { "type": "user_input", "content": [{ "type": "text", "text": "Hello!" }] }, + { "type": "model_output", "content": [{ "type": "text", "text": "Hi there! How can I help you today?" }] }, + { "type": "user_input", "content": [{ "type": "text", "text": "What is the capital of France?" }] } + ] + }' +# [END paths['/{api_version}/interactions'].post:multi_turn] +} + +sample_api_version_interactions_post_multimodal_image() { +# [START paths['/{api_version}/interactions'].post:multimodal_image] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "input": [ + { + "type": "text", + "text": "What is in this picture?" + }, + { + "type": "image", + "data": "BASE64_ENCODED_IMAGE", + "mime_type": "image/png" + } + ] + }' +# [END paths['/{api_version}/interactions'].post:multimodal_image] +} + +sample_api_version_interactions_post_function_calling() { +# [START paths['/{api_version}/interactions'].post:function_calling] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [ + { + "type": "function", + "name": "get_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + } + }, + "required": [ + "location" + ] + } + } + ], + "input": "What is the weather like in Boston, MA?" + }' +# [END paths['/{api_version}/interactions'].post:function_calling] +} + +sample_api_version_interactions_post_deep_research() { +# [START paths['/{api_version}/interactions'].post:deep_research] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "agent": "deep-research-pro-preview-12-2025", + "input": "Find a cure to cancer", + "background": true + }' +# [END paths['/{api_version}/interactions'].post:deep_research] +} + +sample_api_version_interactions_post_antigravity() { +# [START paths['/{api_version}/interactions'].post:antigravity] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "agent": "antigravity-preview-05-2026", + "input": "Read Hacker News, summarize the top 5 stories, and save results as a markdown file.", + "environment": "remote" + }' +# [END paths['/{api_version}/interactions'].post:antigravity] +} + +sample_api_version_interactions_post_reuse_env() { +# [START paths['/{api_version}/interactions'].post:reuse_env] +# Step 1: Create an interaction with a fresh remote environment. +RESPONSE=$(curl -s -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "Api-Revision: 2026-05-20" \ + -d '{ + "agent": "antigravity-preview-05-2026", + "input": "Write a hello world script at /workspace/hello.py.", + "environment": "remote" + }') +INTERACTION_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") +ENV_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['environment_id'])") + +# Step 2: Reuse the same environment in a follow-up interaction. +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d "{ + \"agent\": \"antigravity-preview-05-2026\", + \"input\": \"Modify the script to accept a name argument and greet the user.\", + \"environment\": \"$ENV_ID\", + \"previous_interaction_id\": \"$INTERACTION_ID\" + }" +# [END paths['/{api_version}/interactions'].post:reuse_env] +} + +sample_api_version_interactions_post_with_sources() { +# [START paths['/{api_version}/interactions'].post:with_sources] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "agent": "antigravity-preview-05-2026", + "input": "List all files under /workspace and summarize what you find.", + "environment": { + "type": "remote", + "sources": [ + { + "type": "repository", + "source": "https://github.com/octocat/Spoon-Knife", + "target": "/workspace/repo" + }, + { + "type": "inline", + "content": "Focus on Python files only.", + "target": "/workspace/notes.txt" + } + ] + } + }' +# [END paths['/{api_version}/interactions'].post:with_sources] +} + +sample_api_version_interactions_post_custom_agent() { +# [START paths['/{api_version}/interactions'].post:custom_agent] +# Step 1: Create a custom agent. +curl -X POST https://generativelanguage.googleapis.com/v1beta/agents \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "id": "code-reviewer", + "base_agent": "antigravity-preview-05-2026", + "system_instruction": "You are a senior code reviewer. Check every file for bugs, style issues, and security vulnerabilities.", + "base_environment": { + "type": "remote", + "sources": [{ + "type": "repository", + "source": "https://github.com/octocat/Spoon-Knife", + "target": "/workspace/repo" + }] + } + }' + +# Step 2: Use the custom agent. +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "agent": "code-reviewer", + "input": "Review the latest changes in /workspace/repo/src and file a summary.", + "environment": "remote" + }' +# [END paths['/{api_version}/interactions'].post:custom_agent] +} + +sample_api_version_interactions_id_delete_delete() { +# [START paths['/{api_version}/interactions/{id}'].delete:delete] +# [setup] +INTERACTION_ID=$(curl -s -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ -d '{"model": "gemini-3.6-flash", "input": "Hello"}' \ + | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") +# [/setup] + +curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID" \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/interactions/{id}'].delete:delete] +} + +sample_api_version_interactions_id_get_get() { +# [START paths['/{api_version}/interactions/{id}'].get:get] +# [setup] +INTERACTION_ID=$(curl -s -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "Api-Revision: 2026-05-20" \ + -d '{"model": "gemini-3.6-flash", "input": "Say hello."}' \ + | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") +# [/setup] + +curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID" \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Api-Revision: 2026-05-20" +# [END paths['/{api_version}/interactions/{id}'].get:get] +} + +sample_api_version_interactions_id_cancel_post_cancel() { +# [START paths['/{api_version}/interactions/{id}/cancel'].post:cancel] +# [setup] +INTERACTION_ID=$(curl -s -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ -d '{"model": "gemini-3.6-flash", "input": "Write a long essay about the history of computing.", "background": true}' \ + | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") +# [/setup] + +curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID/cancel" \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/interactions/{id}/cancel'].post:cancel] +} + +sample_schema_CodeExecution_code_execution() { +# [START components.schemas.CodeExecution:code_execution] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [{ + "type": "code_execution" + }], + "input": "Calculate the first 10 Fibonacci numbers" + }' +# [END components.schemas.CodeExecution:code_execution] +} + +sample_schema_ComputerUse_computer_use() { +# [START components.schemas.ComputerUse:computer_use] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-2.5-computer-use-preview-10-2025", + "tools": [{ + "type": "computer_use" + }], + "input": "Find a flight to Tokyo" + }' +# [END components.schemas.ComputerUse:computer_use] +} + +sample_schema_FileSearch_file_search() { +# [START components.schemas.FileSearch:file_search] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [{ + "type": "file_search", + "file_search_store_names": ["fileSearchStores/m64d1sevsr4y-xfyawui3fxqg"] + }], + "input": "Who is the author of the book?" + }' +# [END components.schemas.FileSearch:file_search] +} + +sample_schema_Function_function_calling() { +# [START components.schemas.Function:function_calling] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [{ + "type": "function", + "name": "get_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + } + }, + "required": ["location"] + } + }], + "input": "What is the weather like in Boston, MA?" + }' +# [END components.schemas.Function:function_calling] +} + +sample_schema_GoogleMaps_google_maps() { +# [START components.schemas.GoogleMaps:google_maps] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [{ + "type": "google_maps", + "latitude": 37.7749, + "longitude": -122.4194 + }], + "input": "What is the best food near me?" + }' +# [END components.schemas.GoogleMaps:google_maps] +} + +sample_schema_GoogleSearch_google_search() { +# [START components.schemas.GoogleSearch:google_search] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [{ + "type": "google_search" + }], + "input": "Who is the current president of France?" + }' +# [END components.schemas.GoogleSearch:google_search] +} + +sample_schema_McpServer_mcp_server() { +# [START components.schemas.McpServer:mcp_server] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [{ + "type": "mcp_server", + "name": "weather_service", + "url": "https://gemini-api-demos.uc.r.appspot.com/mcp" + }], + "input": "Today is 12-05-2025, what is the temperature today in London?" + }' +# [END components.schemas.McpServer:mcp_server] +} + +sample_schema_UrlContext_url_context() { +# [START components.schemas.UrlContext:url_context] +curl -X POST https://generativelanguage.googleapis.com/v1beta/interactions \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gemini-3.6-flash", + "tools": [{ + "type": "url_context" + }], + "input": "Summarize https://www.example.com" + }' +# [END components.schemas.UrlContext:url_context] +} + +sample_api_version_voices_get_list() { +# [START paths['/{api_version}/voices'].get:list] +curl -X GET https://generativelanguage.googleapis.com/v1beta/voices \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/voices'].get:list] +} + +sample_api_version_voices_post_create() { +# [START paths['/{api_version}/voices'].post:create] +curl -X POST https://generativelanguage.googleapis.com/v1beta/voices \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "store": true, + "voice": { + "type": "prompted", + "display_name": "Warm Narrator", + "language_code": "en-US", + "prompted": { + "input": "A warm, friendly narrator voice with a calm pace." + } + } + }' +# [END paths['/{api_version}/voices'].post:create] +} + +sample_api_version_voices_voicesid_get_get() { +# [START paths['/{api_version}/voices/{voicesId}'].get:get] +curl -X GET https://generativelanguage.googleapis.com/v1beta/voices/voice_abc123 \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/voices/{voicesId}'].get:get] +} + +sample_api_version_voices_voicesid_delete_delete() { +# [START paths['/{api_version}/voices/{voicesId}'].delete:delete] +curl -X DELETE https://generativelanguage.googleapis.com/v1beta/voices/voice_abc123 \ + -H "x-goog-api-key: $GEMINI_API_KEY" +# [END paths['/{api_version}/voices/{voicesId}'].delete:delete] +} + +sample_api_version_triggers_post_create() { +# [START paths['/{api_version}/triggers'].post:create] +curl -X POST https://generativelanguage.googleapis.com/v1beta/triggers \ + -H "x-goog-api-key: $GEMINI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "schedule": "0 9 * * *", + "time_zone": "America/New_York", + "interaction": { + "agent": "antigravity-preview-05-2026", + "input": "Summarize top news stories.", + "environment": "remote" + } + }' +# [END paths['/{api_version}/triggers'].post:create] +} diff --git a/interactions/go_samples_test.go b/interactions/go_samples_test.go new file mode 100644 index 0000000..6530720 --- /dev/null +++ b/interactions/go_samples_test.go @@ -0,0 +1,1413 @@ +// Copyright 2026 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 samples_test + +import ( + "context" + "fmt" + "google.golang.org/genai" + interactions "google.golang.org/genai/interactions" + gaos_agents "google.golang.org/genai/interactions/models/agents" + gaos_environments "google.golang.org/genai/interactions/models/environments" + gaos_interactions "google.golang.org/genai/interactions/models/interactions" + "google.golang.org/genai/interactions/models/operations" + gaos_voices "google.golang.org/genai/interactions/models/voices" + "log" + "testing" + "time" +) + +func TestSample_api_version_agents_get_list(t *testing.T) { + // [START paths['/{api_version}/agents'].get:list] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + res, err := client.Agents.List(ctx, operations.ListAgentsRequest{}) + if err != nil { + log.Fatal(err) + } + + if res.AgentListResponse != nil { + for _, agent := range res.AgentListResponse.Agents { + if agent.ID != nil { + fmt.Println(*agent.ID) + } + } + } + // [END paths['/{api_version}/agents'].get:list] +} + +func TestSample_api_version_agents_post_create(t *testing.T) { + // [START paths['/{api_version}/agents'].post:create] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + agentID := fmt.Sprintf("research-assistant-%d", time.Now().UnixNano()) + req := operations.CreateAgentRequest{ + Body: gaos_agents.Agent{ + ID: genai.Ptr(agentID), + BaseAgent: genai.Ptr("antigravity-preview-05-2026"), + Description: genai.Ptr("A helpful research assistant."), + SystemInstruction: genai.Ptr("You are a helpful research assistant."), + BaseEnvironment: genai.Ptr(gaos_agents.NewBaseEnvironment("remote")), + Tools: []gaos_agents.AgentTool{ + gaos_agents.NewAgentTool(gaos_interactions.GoogleSearch{}), + }, + }, + } + + res, err := client.Agents.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Agent != nil && res.Agent.ID != nil { + fmt.Println(*res.Agent.ID) + } + + // [cleanup] + _, _ = client.Agents.Delete(ctx, operations.DeleteAgentRequest{ID: agentID}) + // [/cleanup] + // [END paths['/{api_version}/agents'].post:create] +} + +func TestSample_api_version_agents_post_with_sources(t *testing.T) { + // [START paths['/{api_version}/agents'].post:with_sources] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + agentID := fmt.Sprintf("data-analyst-%d", time.Now().UnixNano()) + env := gaos_interactions.Environment{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Target: genai.Ptr(".agents/AGENTS.md"), + Content: genai.Ptr("Always use matplotlib for charts. Include a summary table in every report."), + }, + { + Type: genai.Ptr(gaos_interactions.SourceTypeRepository), + Source: genai.Ptr("https://github.com/my-org/analysis-templates"), + Target: genai.Ptr("/workspace/templates"), + }, + }, + } + + req := operations.CreateAgentRequest{ + Body: gaos_agents.Agent{ + ID: genai.Ptr(agentID), + BaseAgent: genai.Ptr("antigravity-preview-05-2026"), + SystemInstruction: genai.Ptr("You are a data analyst. Always include visualizations and export results as PDF."), + BaseEnvironment: genai.Ptr(gaos_agents.NewBaseEnvironment(env)), + }, + } + + res, err := client.Agents.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Agent != nil && res.Agent.ID != nil { + fmt.Printf("Created agent: %s\n", *res.Agent.ID) + } + + // [cleanup] + _, _ = client.Agents.Delete(ctx, operations.DeleteAgentRequest{ID: agentID}) + // [/cleanup] + // [END paths['/{api_version}/agents'].post:with_sources] +} + +func TestSample_api_version_agents_post_fork_from_env(t *testing.T) { + // [START paths['/{api_version}/agents'].post:fork_from_env] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // Step 1: Set up the environment interactively. + interactionReq := operations.CreateInteractionRequest{ + Body: operations.NewCreateInteractionRequestBody(gaos_interactions.CreateAgentInteraction{ + Agent: gaos_interactions.AgentOption("antigravity-preview-05-2026"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Write a basic Hello World template to /workspace/template.py.")), + Environment: genai.Ptr(gaos_interactions.NewCreateAgentInteractionEnvironment("remote")), + }), + } + interactionRes, err := client.Interactions.Create(ctx, interactionReq) + if err != nil { + log.Fatal(err) + } + envID := "" + if interactionRes.Interaction != nil && interactionRes.Interaction.EnvironmentID != nil { + envID = *interactionRes.Interaction.EnvironmentID + } + + // Step 2: Fork that environment into a named agent. + agentID := fmt.Sprintf("my-data-analyst-%d", time.Now().UnixNano()) + req := operations.CreateAgentRequest{ + Body: gaos_agents.Agent{ + ID: genai.Ptr(agentID), + BaseAgent: genai.Ptr("antigravity-preview-05-2026"), + SystemInstruction: genai.Ptr("You are a data analyst. Use the template at /workspace/template.py for all reports."), + BaseEnvironment: genai.Ptr(gaos_agents.NewBaseEnvironment(envID)), + }, + } + res, err := client.Agents.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + if res.Agent != nil && res.Agent.ID != nil { + fmt.Printf("Forked agent: %s\n", *res.Agent.ID) + } + + // [cleanup] + _, _ = client.Agents.Delete(ctx, operations.DeleteAgentRequest{ID: agentID}) + // [/cleanup] + // [END paths['/{api_version}/agents'].post:fork_from_env] +} + +func TestSample_api_version_agents_id_delete_delete(t *testing.T) { + // [START paths['/{api_version}/agents/{id}'].delete:delete] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // [setup] + agentID := fmt.Sprintf("delete-test-%d", time.Now().UnixNano()) + _, err = client.Agents.Create(ctx, operations.CreateAgentRequest{ + Body: gaos_agents.Agent{ + ID: genai.Ptr(agentID), + BaseAgent: genai.Ptr("antigravity-preview-05-2026"), + Description: genai.Ptr("Temporary agent for deletion."), + BaseEnvironment: genai.Ptr(gaos_agents.NewBaseEnvironment("remote")), + }, + }) + if err != nil { + log.Fatal(err) + } + // [/setup] + + _, err = client.Agents.Delete(ctx, operations.DeleteAgentRequest{ID: agentID}) + if err != nil { + log.Fatal(err) + } + fmt.Println("Agent deleted successfully.") + // [END paths['/{api_version}/agents/{id}'].delete:delete] +} + +func TestSample_api_version_agents_id_get_get(t *testing.T) { + // [START paths['/{api_version}/agents/{id}'].get:get] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // [setup] + agentID := fmt.Sprintf("test-agent-%d", time.Now().UnixNano()) + _, err = client.Agents.Create(ctx, operations.CreateAgentRequest{ + Body: gaos_agents.Agent{ + ID: genai.Ptr(agentID), + BaseAgent: genai.Ptr("antigravity-preview-05-2026"), + Description: genai.Ptr("A test agent."), + BaseEnvironment: genai.Ptr(gaos_agents.NewBaseEnvironment("remote")), + }, + }) + if err != nil { + log.Fatal(err) + } + // [/setup] + + res, err := client.Agents.Get(ctx, operations.GetAgentRequest{ID: agentID}) + if err != nil { + log.Fatal(err) + } + + if res.Agent != nil && res.Agent.ID != nil { + fmt.Println(*res.Agent.ID) + } + + // [cleanup] + _, _ = client.Agents.Delete(ctx, operations.DeleteAgentRequest{ID: agentID}) + // [/cleanup] + // [END paths['/{api_version}/agents/{id}'].get:get] +} + +func TestSample_api_version_environments_get_list(t *testing.T) { + // [START paths['/{api_version}/environments'].get:list] + ctx := context.Background() + client := interactions.New() + + res, err := client.Environments.ListEnvironments(ctx, operations.ListEnvironmentsRequest{}) + if err != nil { + log.Fatal(err) + } + + if res.ListEnvironmentsResponse != nil { + for _, env := range res.ListEnvironmentsResponse.Environments { + if env.ID != "" { + fmt.Println(env.ID) + } + } + } + // [END paths['/{api_version}/environments'].get:list] +} + +func TestSample_api_version_environments_post_create(t *testing.T) { + // [START paths['/{api_version}/environments'].post:create] + ctx := context.Background() + client := interactions.New() + + req := operations.CreateEnvironmentRequest{ + Body: gaos_environments.CreateEnvironmentRequest{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Target: genai.Ptr("main.py"), + Content: genai.Ptr("print('Hello, World!')"), + }, + }, + }, + } + + res, err := client.Environments.CreateEnvironment(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Environment != nil && res.Environment.ID != "" { + fmt.Println(res.Environment.ID) + + // [cleanup] + _, _ = client.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{ID: res.Environment.ID}) + // [/cleanup] + } + // [END paths['/{api_version}/environments'].post:create] +} + +func TestSample_api_version_environments_post_copy(t *testing.T) { + // [START paths['/{api_version}/environments'].post:copy] + ctx := context.Background() + client := interactions.New() + + // [setup] + sourceReq := operations.CreateEnvironmentRequest{ + Body: gaos_environments.CreateEnvironmentRequest{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Target: genai.Ptr("main.py"), + Content: genai.Ptr("print('Hello')"), + }, + }, + }, + } + sourceRes, err := client.Environments.CreateEnvironment(ctx, sourceReq) + if err != nil { + log.Fatal(err) + } + if sourceRes.Environment == nil || sourceRes.Environment.ID == "" { + log.Fatal("missing source environment ID") + } + sourceEnvID := sourceRes.Environment.ID + // [/setup] + + res, err := client.Environments.CreateEnvironment(ctx, operations.CreateEnvironmentRequest{ + Body: gaos_environments.CreateEnvironmentRequest{ + FromEnvironment: genai.Ptr(sourceEnvID), + }, + }) + if err != nil { + log.Fatal(err) + } + + if res.Environment != nil && res.Environment.ID != "" { + fmt.Println(res.Environment.ID) + + // [cleanup] + _, _ = client.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{ID: res.Environment.ID}) + _, _ = client.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{ID: sourceEnvID}) + // [/cleanup] + } + // [END paths['/{api_version}/environments'].post:copy] +} + +func TestSample_api_version_environments_environment_files_path_get_list_files(t *testing.T) { + // [START paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] + ctx := context.Background() + client := interactions.New() + + // [setup] + createReq := operations.CreateEnvironmentRequest{ + Body: gaos_environments.CreateEnvironmentRequest{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Target: genai.Ptr("src/main.py"), + Content: genai.Ptr("print('Hello')"), + }, + }, + }, + } + createRes, err := client.Environments.CreateEnvironment(ctx, createReq) + if err != nil { + log.Fatal(err) + } + if createRes.Environment == nil || createRes.Environment.ID == "" { + log.Fatal("missing environment ID") + } + envID := createRes.Environment.ID + // [/setup] + + res, err := client.Environments.Files.List(ctx, operations.GetEnvironmentFilesRequest{ + Environment: envID, + Path: "src", + }) + if err != nil { + log.Fatal(err) + } + + if res.GetEnvironmentFilesResponse != nil { + for _, file := range res.GetEnvironmentFilesResponse.Files { + name := "" + if file.Name != nil { + name = *file.Name + } + fileType := "" + if file.Type != nil { + fileType = string(*file.Type) + } + var size int64 + if file.SizeBytes != nil { + size = *file.SizeBytes + } + fmt.Println(name, fileType, size) + } + } + + // [cleanup] + _, _ = client.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{ + ID: envID, + }) + // [/cleanup] + // [END paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] +} + +func TestSample_api_version_environments_environment_files_path_get_get_file(t *testing.T) { + // [START paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] + ctx := context.Background() + client := interactions.New() + + // [setup] + createReq := operations.CreateEnvironmentRequest{ + Body: gaos_environments.CreateEnvironmentRequest{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Target: genai.Ptr("main.py"), + Content: genai.Ptr("print('Hello')"), + }, + }, + }, + } + createRes, err := client.Environments.CreateEnvironment(ctx, createReq) + if err != nil { + log.Fatal(err) + } + if createRes.Environment == nil || createRes.Environment.ID == "" { + log.Fatal("missing environment ID") + } + envID := createRes.Environment.ID + // [/setup] + + res, err := client.Environments.Files.List(ctx, operations.GetEnvironmentFilesRequest{ + Environment: envID, + Path: "main.py", + }) + if err != nil { + log.Fatal(err) + } + + if res.GetEnvironmentFilesResponse != nil { + for _, file := range res.GetEnvironmentFilesResponse.Files { + name := "" + if file.Name != nil { + name = *file.Name + } + var size int64 + if file.SizeBytes != nil { + size = *file.SizeBytes + } + fmt.Println(name, size) + } + } + + // [cleanup] + _, _ = client.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{ + ID: envID, + }) + // [/cleanup] + // [END paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] +} + +func TestSample_api_version_environments_id_delete_delete(t *testing.T) { + // [START paths['/{api_version}/environments/{id}'].delete:delete] + ctx := context.Background() + client := interactions.New() + + // [setup] + createReq := operations.CreateEnvironmentRequest{ + Body: gaos_environments.CreateEnvironmentRequest{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Target: genai.Ptr("main.py"), + Content: genai.Ptr("print('Hello')"), + }, + }, + }, + } + createRes, err := client.Environments.CreateEnvironment(ctx, createReq) + if err != nil { + log.Fatal(err) + } + if createRes.Environment == nil || createRes.Environment.ID == "" { + log.Fatal("missing environment ID") + } + envID := createRes.Environment.ID + // [/setup] + + _, err = client.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{ + ID: envID, + }) + if err != nil { + log.Fatal(err) + } + fmt.Println("Environment deleted successfully.") + // [END paths['/{api_version}/environments/{id}'].delete:delete] +} + +func TestSample_api_version_environments_id_get_get(t *testing.T) { + // [START paths['/{api_version}/environments/{id}'].get:get] + ctx := context.Background() + client := interactions.New() + + // [setup] + createReq := operations.CreateEnvironmentRequest{ + Body: gaos_environments.CreateEnvironmentRequest{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Target: genai.Ptr("main.py"), + Content: genai.Ptr("print('Hello')"), + }, + }, + }, + } + createRes, err := client.Environments.CreateEnvironment(ctx, createReq) + if err != nil { + log.Fatal(err) + } + if createRes.Environment == nil || createRes.Environment.ID == "" { + log.Fatal("missing environment ID") + } + envID := createRes.Environment.ID + // [/setup] + + res, err := client.Environments.GetEnvironment(ctx, operations.GetEnvironmentRequest{ + ID: envID, + }) + if err != nil { + log.Fatal(err) + } + + if res.Environment != nil && res.Environment.ID != "" { + fmt.Println(res.Environment.ID) + } + + // [cleanup] + _, _ = client.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{ + ID: envID, + }) + // [/cleanup] + // [END paths['/{api_version}/environments/{id}'].get:get] +} + +func TestSample_api_version_interactions_post_simple(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:simple] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Hello, how are you?")), + }) + + res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END paths['/{api_version}/interactions'].post:simple] +} + +func TestSample_api_version_interactions_post_multi_turn(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:multi_turn] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + history := []gaos_interactions.Step{ + gaos_interactions.NewStep(gaos_interactions.UserInputStep{ + Content: []gaos_interactions.Content{ + gaos_interactions.NewContent(gaos_interactions.TextContent{ + Text: "Hello!", + }), + }, + }), + gaos_interactions.NewStep(gaos_interactions.ModelOutputStep{ + Content: []gaos_interactions.Content{ + gaos_interactions.NewContent(gaos_interactions.TextContent{ + Text: "Hi there! How can I help you today?", + }), + }, + }), + gaos_interactions.NewStep(gaos_interactions.UserInputStep{ + Content: []gaos_interactions.Content{ + gaos_interactions.NewContent(gaos_interactions.TextContent{ + Text: "What is the capital of France?", + }), + }, + }), + } + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput(history)), + }) + + res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END paths['/{api_version}/interactions'].post:multi_turn] +} + +func TestSample_api_version_interactions_post_multimodal_image(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:multimodal_image] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + contents := []gaos_interactions.Content{ + gaos_interactions.NewContent(gaos_interactions.TextContent{ + Text: "What is in this picture?", + }), + gaos_interactions.NewContent(gaos_interactions.ImageContent{ + Data: genai.Ptr("BASE64_ENCODED_IMAGE"), + MimeType: gaos_interactions.ImageContentMimeTypeImagePng.ToPointer(), + }), + } + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput(contents)), + }) + + res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END paths['/{api_version}/interactions'].post:multimodal_image] +} + +func TestSample_api_version_interactions_post_function_calling(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:function_calling] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + function := gaos_interactions.Function{ + Name: genai.Ptr("get_weather"), + Description: genai.Ptr("Get the current weather in a given location"), + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "location": map[string]any{ + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + }, + "required": []string{"location"}, + }, + } + + tool := gaos_interactions.NewTool(function) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("What is the weather like in Boston, MA?")), + Tools: []gaos_interactions.Tool{tool}, + }) + + res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil { + for _, step := range res.Interaction.Steps { + if step.FunctionCallStep != nil { + fmt.Println("Function Call:", step.FunctionCallStep.Name) + fmt.Println("Arguments:", step.FunctionCallStep.Arguments) + } + } + } + // [END paths['/{api_version}/interactions'].post:function_calling] +} + +func TestSample_api_version_interactions_post_deep_research(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:deep_research] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateAgentInteraction{ + Agent: gaos_interactions.AgentOption("deep-research-pro-preview-12-2025"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("find a cure to cancer")), + Background: genai.Ptr(true), + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil { + fmt.Println(res.Interaction.Status) + } + // [END paths['/{api_version}/interactions'].post:deep_research] +} + +func TestSample_api_version_interactions_post_antigravity(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:antigravity] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateAgentInteraction{ + Agent: gaos_interactions.AgentOption("antigravity-preview-05-2026"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Read Hacker News, summarize the top 5 stories, and save results as a markdown file.")), + Environment: genai.Ptr(gaos_interactions.NewCreateAgentInteractionEnvironment("remote")), + }) + + res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END paths['/{api_version}/interactions'].post:antigravity] +} + +func TestSample_api_version_interactions_post_reuse_env(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:reuse_env] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // Step 1: Create an interaction with a fresh remote environment. + body1 := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateAgentInteraction{ + Agent: gaos_interactions.AgentOption("antigravity-preview-05-2026"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Write a hello world script at /workspace/hello.py.")), + Environment: genai.Ptr(gaos_interactions.NewCreateAgentInteractionEnvironment("remote")), + }) + + res1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body1}) + if err != nil { + log.Fatal(err) + } + + if res1.Interaction == nil || res1.Interaction.EnvironmentID == nil { + log.Fatal("No environment ID returned") + } + fmt.Printf("Environment ID: %s\n", *res1.Interaction.EnvironmentID) + + // Step 2: Reuse the same environment in a follow-up interaction. + body2 := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateAgentInteraction{ + Agent: gaos_interactions.AgentOption("antigravity-preview-05-2026"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Modify the script to accept a name argument and greet the user.")), + Environment: genai.Ptr(gaos_interactions.NewCreateAgentInteractionEnvironment(*res1.Interaction.EnvironmentID)), + PreviousInteractionID: res1.Interaction.ID, + }) + + res2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body2}) + if err != nil { + log.Fatal(err) + } + + if res2.Interaction != nil && res2.Interaction.OutputText != nil { + fmt.Println(*res2.Interaction.OutputText) + } + // [END paths['/{api_version}/interactions'].post:reuse_env] +} + +func TestSample_api_version_interactions_post_with_sources(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:with_sources] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + env := gaos_interactions.Environment{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeRepository), + Source: genai.Ptr("https://github.com/octocat/Spoon-Knife"), + Target: genai.Ptr("/workspace/repo"), + }, + { + Type: genai.Ptr(gaos_interactions.SourceTypeInline), + Content: genai.Ptr("Focus on Python files only."), + Target: genai.Ptr("/workspace/notes.txt"), + }, + }, + } + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateAgentInteraction{ + Agent: gaos_interactions.AgentOption("antigravity-preview-05-2026"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("List all files under /workspace and summarize what you find.")), + Environment: genai.Ptr(gaos_interactions.NewCreateAgentInteractionEnvironment(env)), + }) + + res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END paths['/{api_version}/interactions'].post:with_sources] +} + +func TestSample_api_version_interactions_post_custom_agent(t *testing.T) { + // [START paths['/{api_version}/interactions'].post:custom_agent] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // Step 1: Create a custom agent. + agentID := fmt.Sprintf("code-reviewer-%d", time.Now().UnixNano()) + baseEnv := gaos_interactions.Environment{ + Sources: []gaos_interactions.Source{ + { + Type: genai.Ptr(gaos_interactions.SourceTypeRepository), + Source: genai.Ptr("https://github.com/octocat/Spoon-Knife"), + Target: genai.Ptr("/workspace/repo"), + }, + }, + } + + _, err = client.Agents.Create(ctx, operations.CreateAgentRequest{ + Body: gaos_agents.Agent{ + ID: genai.Ptr(agentID), + BaseAgent: genai.Ptr("antigravity-preview-05-2026"), + SystemInstruction: genai.Ptr("You are a senior code reviewer. Check every file for bugs, style issues, and security vulnerabilities."), + BaseEnvironment: genai.Ptr(gaos_agents.NewBaseEnvironment(baseEnv)), + }, + }) + if err != nil { + log.Fatal(err) + } + + // Step 2: Use the custom agent. + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateAgentInteraction{ + Agent: gaos_interactions.AgentOption(agentID), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Review the latest changes in /workspace/repo/src and file a summary.")), + Environment: genai.Ptr(gaos_interactions.NewCreateAgentInteractionEnvironment("remote")), + }) + + res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + + // [cleanup] + _, _ = client.Agents.Delete(ctx, operations.DeleteAgentRequest{ID: agentID}) + // [/cleanup] + // [END paths['/{api_version}/interactions'].post:custom_agent] +} + +func TestSample_api_version_interactions_id_delete_delete(t *testing.T) { + // [START paths['/{api_version}/interactions/{id}'].delete:delete] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // [setup] + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Hello")), + }) + createReq := operations.CreateInteractionRequest{ + Body: body, + } + + created, err := client.Interactions.Create(ctx, createReq) + if err != nil { + log.Fatal(err) + } + if created.Interaction == nil || created.Interaction.ID == nil { + log.Fatal("failed to create interaction in setup") + } + interactionID := *created.Interaction.ID + // [/setup] + + req := operations.DeleteInteractionRequest{ + ID: interactionID, + } + + _, err = client.Interactions.Delete( + ctx, + req, + ) + if err != nil { + log.Fatal(err) + } + + fmt.Println("Interaction deleted successfully.") + // [END paths['/{api_version}/interactions/{id}'].delete:delete] +} + +func TestSample_api_version_interactions_id_get_get(t *testing.T) { + // [START paths['/{api_version}/interactions/{id}'].get:get] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // [setup] + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Say hello.")), + }) + created, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{Body: body}) + if err != nil { + log.Fatal(err) + } + if created.Interaction == nil || created.Interaction.ID == nil { + log.Fatal("No interaction ID returned") + } + // [/setup] + + interaction, err := client.Interactions.Get(ctx, operations.GetInteractionByIDRequest{ + ID: *created.Interaction.ID, + }) + if err != nil { + log.Fatal(err) + } + + if interaction.Interaction != nil { + fmt.Println(interaction.Interaction.Status) + } + // [END paths['/{api_version}/interactions/{id}'].get:get] +} + +func TestSample_api_version_interactions_id_cancel_post_cancel(t *testing.T) { + // [START paths['/{api_version}/interactions/{id}/cancel'].post:cancel] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // [setup] + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Write a long essay about the history of computing.")), + Background: genai.Ptr(true), + }) + createReq := operations.CreateInteractionRequest{ + Body: body, + } + + created, err := client.Interactions.Create(ctx, createReq) + if err != nil { + log.Fatal(err) + } + if created.Interaction == nil || created.Interaction.ID == nil { + log.Fatal("failed to create interaction in setup") + } + interactionID := *created.Interaction.ID + // [/setup] + + req := operations.CancelInteractionByIDRequest{ + ID: interactionID, + } + + res, err := client.Interactions.Cancel( + ctx, + req, + ) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil { + fmt.Println(res.Interaction.Status) + } + // [END paths['/{api_version}/interactions/{id}/cancel'].post:cancel] +} + +func TestSample_schema_CodeExecution_code_execution(t *testing.T) { + // [START components.schemas.CodeExecution:code_execution] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + tool := gaos_interactions.NewTool(gaos_interactions.CodeExecution{}) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Calculate the first 10 Fibonacci numbers")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END components.schemas.CodeExecution:code_execution] +} + +func TestSample_schema_ComputerUse_computer_use(t *testing.T) { + // [START components.schemas.ComputerUse:computer_use] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + tool := gaos_interactions.NewTool(gaos_interactions.ComputerUse{}) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-2.5-computer-use-preview-10-2025"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Find a flight to Tokyo")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END components.schemas.ComputerUse:computer_use] +} + +func TestSample_schema_FileSearch_file_search(t *testing.T) { + // [START components.schemas.FileSearch:file_search] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + // [setup] + store, err := client.FileSearchStores.Create(ctx, nil) + if err != nil { + log.Fatal(err) + } + // [/setup] + + tool := gaos_interactions.NewTool(gaos_interactions.FileSearch{ + FileSearchStoreNames: []string{store.Name}, + }) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("What documents are available?")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + + // [cleanup] + _ = client.FileSearchStores.Delete(ctx, store.Name, nil) + // [/cleanup] + // [END components.schemas.FileSearch:file_search] +} + +func TestSample_schema_Function_function_calling(t *testing.T) { + // [START components.schemas.Function:function_calling] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + function := gaos_interactions.Function{ + Name: genai.Ptr("get_weather"), + Description: genai.Ptr("Get the current weather in a given location"), + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "location": map[string]any{ + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + }, + "required": []string{"location"}, + }, + } + + tool := gaos_interactions.NewTool(function) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("What is the weather like in Boston, MA?")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil { + for _, step := range res.Interaction.Steps { + if step.FunctionCallStep != nil { + fmt.Println("Function Call:", step.FunctionCallStep.Name) + fmt.Println("Arguments:", step.FunctionCallStep.Arguments) + } + } + } + // [END components.schemas.Function:function_calling] +} + +func TestSample_schema_GoogleMaps_google_maps(t *testing.T) { + // [START components.schemas.GoogleMaps:google_maps] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + tool := gaos_interactions.NewTool(gaos_interactions.GoogleMaps{ + Latitude: genai.Ptr(37.7749), + Longitude: genai.Ptr(-122.4194), + }) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("What is the best food near me?")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END components.schemas.GoogleMaps:google_maps] +} + +func TestSample_schema_GoogleSearch_google_search(t *testing.T) { + // [START components.schemas.GoogleSearch:google_search] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + tool := gaos_interactions.NewTool(gaos_interactions.GoogleSearch{}) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Who is the current president of France?")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END components.schemas.GoogleSearch:google_search] +} + +func TestSample_schema_McpServer_mcp_server(t *testing.T) { + // [START components.schemas.McpServer:mcp_server] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + mcpServer := gaos_interactions.MCPServer{ + Name: genai.Ptr("weather_service"), + URL: genai.Ptr("https://gemini-api-demos.uc.r.appspot.com/mcp"), + } + tool := gaos_interactions.NewTool(mcpServer) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Today is 12-05-2025, what is the temperature today in London?")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END components.schemas.McpServer:mcp_server] +} + +func TestSample_schema_UrlContext_url_context(t *testing.T) { + // [START components.schemas.UrlContext:url_context] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + tool := gaos_interactions.NewTool(gaos_interactions.URLContext{}) + + body := operations.NewCreateInteractionRequestBody(gaos_interactions.CreateModelInteraction{ + Model: gaos_interactions.Model("gemini-3.6-flash"), + Input: genai.Ptr(gaos_interactions.NewInteractionsInput("Summarize https://www.example.com")), + Tools: []gaos_interactions.Tool{tool}, + }) + + req := operations.CreateInteractionRequest{ + Body: body, + } + + res, err := client.Interactions.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Interaction != nil && res.Interaction.OutputText != nil { + fmt.Println(*res.Interaction.OutputText) + } + // [END components.schemas.UrlContext:url_context] +} + +func TestSample_api_version_voices_get_list(t *testing.T) { + // [START paths['/{api_version}/voices'].get:list] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + res, err := client.Voices.List(ctx, operations.ListVoicesRequest{}) + if err != nil { + log.Fatal(err) + } + + if res.ListVoicesResponse != nil { + for _, voice := range res.ListVoicesResponse.Voices { + if voice.ID != nil && voice.DisplayName != nil { + fmt.Println(*voice.ID, *voice.DisplayName) + } + } + } + // [END paths['/{api_version}/voices'].get:list] +} + +func TestSample_api_version_voices_post_create(t *testing.T) { + // [START paths['/{api_version}/voices'].post:create] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + req := operations.CreateVoiceRequest{ + Body: gaos_voices.CreateVoiceRequest{ + Store: genai.Ptr(true), + Voice: gaos_voices.VoiceInput{ + Type: gaos_voices.VoiceTypePrompted, + DisplayName: genai.Ptr("Warm Narrator"), + LanguageCode: genai.Ptr("en-US"), + Prompted: &gaos_voices.PromptedVoice{ + Input: "A warm, friendly narrator voice with a calm pace.", + }, + }, + }, + } + + res, err := client.Voices.Create(ctx, req) + if err != nil { + log.Fatal(err) + } + + if res.Voice != nil && res.Voice.ID != nil { + fmt.Println(*res.Voice.ID) + } + + // [cleanup] + if res.Voice != nil && res.Voice.ID != nil { + _, _ = client.Voices.Delete(ctx, operations.DeleteVoiceRequest{ID: *res.Voice.ID}) + } + // [/cleanup] + // [END paths['/{api_version}/voices'].post:create] +} + +func TestSample_api_version_voices_voicesid_get_get(t *testing.T) { + // [START paths['/{api_version}/voices/{voicesId}'].get:get] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + res, err := client.Voices.Get(ctx, operations.GetVoiceRequest{ + ID: "voice_abc123", + }) + if err != nil { + log.Fatal(err) + } + + if res.Voice != nil && res.Voice.ID != nil && res.Voice.DisplayName != nil { + fmt.Println(*res.Voice.ID, *res.Voice.DisplayName) + } + // [END paths['/{api_version}/voices/{voicesId}'].get:get] +} + +func TestSample_api_version_voices_voicesid_delete_delete(t *testing.T) { + // [START paths['/{api_version}/voices/{voicesId}'].delete:delete] + ctx := context.Background() + client, err := genai.NewClient(ctx, nil) + if err != nil { + log.Fatal(err) + } + + _, err = client.Voices.Delete(ctx, operations.DeleteVoiceRequest{ + ID: "voice_abc123", + }) + if err != nil { + log.Fatal(err) + } + // [END paths['/{api_version}/voices/{voicesId}'].delete:delete] +} diff --git a/interactions/package.json b/interactions/package.json new file mode 100644 index 0000000..2ad857b --- /dev/null +++ b/interactions/package.json @@ -0,0 +1,17 @@ +{ + "name": "gemini-api-interactions-examples", + "version": "1.0.0", + "private": true, + "description": "Interactions API reference samples, run as Jasmine specs.", + "license": "Apache-2.0", + "type": "module", + "scripts": { + "test": "jasmine typescript_samples_test.ts" + }, + "dependencies": { + "@google/genai": "^2.27.0" + }, + "devDependencies": { + "jasmine": "^7.0.0" + } +} diff --git a/interactions/pom.xml b/interactions/pom.xml new file mode 100644 index 0000000..0fa104e --- /dev/null +++ b/interactions/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + + com.example.gemini + interactions + 1.0-SNAPSHOT + + + 17 + UTF-8 + + + + + com.google.genai + google-genai + 1.57.0 + + + junit + junit + 4.13.2 + test + + + + + ${project.basedir} + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + JavaSamplesTest.java + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + **/JavaSamplesTest.java + + + + + + diff --git a/interactions/python_samples_test.py b/interactions/python_samples_test.py new file mode 100644 index 0000000..c3383b7 --- /dev/null +++ b/interactions/python_samples_test.py @@ -0,0 +1,827 @@ +# Copyright 2026 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. + +"""Tests and code samples for Gemini Interactions API in Python.""" + +# pylint: disable=g-import-not-at-top,line-too-long,invalid-name + +from absl.testing import absltest +from absl.testing import parameterized + + +class PythonSamplesTest(parameterized.TestCase): + + def test_api_version_agents_get_list(self): + # [START paths['/{api_version}/agents'].get:list] + from google import genai + + client = genai.Client() + response = client.agents.list() + for agent in response.agents or []: + print(agent.id) + # [END paths['/{api_version}/agents'].get:list] + + def test_api_version_agents_post_create(self): + # [START paths['/{api_version}/agents'].post:create] + import uuid + from google import genai + + client = genai.Client() + agent = client.agents.create( + id=f"research-assistant-{uuid.uuid4().hex[:8]}", + base_agent="antigravity-preview-05-2026", + description="A helpful research assistant.", + system_instruction="You are a helpful research assistant.", + base_environment="remote", + tools=[{"type": "google_search"}], + ) + print(agent.id) + + # [cleanup] + client.agents.delete(agent.id) + # [/cleanup] + # [END paths['/{api_version}/agents'].post:create] + + def test_api_version_agents_post_with_sources(self): + # [START paths['/{api_version}/agents'].post:with_sources] + import uuid + from google import genai + + client = genai.Client() + agent = client.agents.create( + id=f"data-analyst-{uuid.uuid4().hex[:8]}", + base_agent="antigravity-preview-05-2026", + system_instruction=( + "You are a data analyst. Always include visualizations and export" + " results as PDF." + ), + base_environment={ + "type": "remote", + "sources": [ + { + "type": "inline", + "target": ".agents/AGENTS.md", + "content": ( + "Always use matplotlib for charts. Include a summary" + " table in every report." + ), + }, + { + "type": "repository", + "source": "https://github.com/my-org/analysis-templates", + "target": "/workspace/templates", + }, + ], + }, + ) + print(f"Created agent: {agent.id}") + + # [cleanup] + client.agents.delete(agent.id) + # [/cleanup] + # [END paths['/{api_version}/agents'].post:with_sources] + + def test_api_version_agents_post_fork_from_env(self): + # [START paths['/{api_version}/agents'].post:fork_from_env] + import uuid + from google import genai + + client = genai.Client() + + # Step 1: Set up the environment interactively. + interaction = client.interactions.create( + agent="antigravity-preview-05-2026", + input="Write a basic Hello World template to /workspace/template.py.", + environment="remote", + ) + + # Step 2: Fork that environment into a named agent. + agent_id = f"my-data-analyst-{uuid.uuid4().hex[:8]}" + agent = client.agents.create( + id=agent_id, + base_agent="antigravity-preview-05-2026", + system_instruction=( + "You are a data analyst. Use the template at /workspace/template.py" + " for all reports." + ), + base_environment=interaction.environment_id, + ) + print(f"Forked agent: {agent.id}") + + # [cleanup] + client.agents.delete(agent.id) + # [/cleanup] + # [END paths['/{api_version}/agents'].post:fork_from_env] + + def test_api_version_agents_id_delete_delete(self): + # [START paths['/{api_version}/agents/{id}'].delete:delete] + import uuid + from google import genai + + client = genai.Client() + + # [setup] + agent_id = f"delete-test-{uuid.uuid4().hex[:8]}" + client.agents.create( + id=agent_id, + base_agent="antigravity-preview-05-2026", + description="Temporary agent for deletion.", + base_environment="remote", + ) + # [/setup] + + client.agents.delete(agent_id) + print("Agent deleted successfully.") + # [END paths['/{api_version}/agents/{id}'].delete:delete] + + def test_api_version_agents_id_get_get(self): + # [START paths['/{api_version}/agents/{id}'].get:get] + import uuid + from google import genai + + client = genai.Client() + + # [setup] + agent_id = f"test-agent-{uuid.uuid4().hex[:8]}" + client.agents.create( + id=agent_id, + base_agent="antigravity-preview-05-2026", + description="A test agent.", + base_environment="remote", + ) + # [/setup] + + agent = client.agents.get(agent_id) + print(agent.id) + + # [cleanup] + client.agents.delete(agent.id) + # [/cleanup] + # [END paths['/{api_version}/agents/{id}'].get:get] + + def test_api_version_environments_get_list(self): + # [START paths['/{api_version}/environments'].get:list] + from google import genai + + client = genai.Client() + response = client.environments.list() + for environment in response.environments or []: + print(environment.id) + # [END paths['/{api_version}/environments'].get:list] + + def test_api_version_environments_post_create(self): + # [START paths['/{api_version}/environments'].post:create] + from google import genai + + client = genai.Client() + environment = client.environments.create( + sources=[{ + "type": "inline", + "target": "main.py", + "content": "print('Hello, World!')", + }] + ) + print(environment.id) + + # [cleanup] + client.environments.delete(id=environment.id) + # [/cleanup] + # [END paths['/{api_version}/environments'].post:create] + + def test_api_version_environments_post_copy(self): + # [START paths['/{api_version}/environments'].post:copy] + from google import genai + + client = genai.Client() + + # [setup] + source_env = client.environments.create( + sources=[{ + "type": "inline", + "target": "main.py", + "content": "print('Hello')", + }] + ) + # [/setup] + + environment = client.environments.create( + from_environment=source_env.id, + ) + print(environment.id) + + # [cleanup] + client.environments.delete(id=environment.id) + client.environments.delete(id=source_env.id) + # [/cleanup] + # [END paths['/{api_version}/environments'].post:copy] + + def test_api_version_environments_environment_files_path_get_list_files(self): + # [START paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] + from google import genai + + client = genai.Client() + + # [setup] + created = client.environments.create( + sources=[{ + "type": "inline", + "target": "src/main.py", + "content": "print('Hello')", + }] + ) + # [/setup] + + response = client.environments.files.list( + environment=created.id, + path="src", + ) + for file in response.files or []: + print(file.name, file.type, file.size_bytes) + + # [cleanup] + client.environments.delete(id=created.id) + # [/cleanup] + # [END paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] + + def test_api_version_environments_environment_files_path_get_get_file(self): + # [START paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] + from google import genai + + client = genai.Client() + + # [setup] + created = client.environments.create( + sources=[ + {"type": "inline", "target": "main.py", "content": "print('Hello')"} + ] + ) + # [/setup] + + response = client.environments.files.get( + environment=created.id, + path="main.py", + ) + for file in response.files or []: + print(file.name, file.size_bytes) + + # [cleanup] + client.environments.delete(id=created.id) + # [/cleanup] + # [END paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] + + def test_api_version_environments_environment_files_path_get_download_file( + self, + ): + # [START paths['/{api_version}/environments/{environment}/files/{path}'].get:download_file] + from google import genai + + client = genai.Client() + + # [setup] + created = client.environments.create( + sources=[{ + "type": "inline", + "target": "src/main.py", + "content": "print('Hello')", + }] + ) + # [/setup] + + content = client.environments.files.download( + environment=created.id, + path="src/main.py", + ) + print(content.decode("utf-8")) + + # [cleanup] + client.environments.delete(id=created.id) + # [/cleanup] + # [END paths['/{api_version}/environments/{environment}/files/{path}'].get:download_file] + + def test_api_version_environments_id_delete_delete(self): + # [START paths['/{api_version}/environments/{id}'].delete:delete] + from google import genai + + client = genai.Client() + + # [setup] + created = client.environments.create( + sources=[ + {"type": "inline", "target": "main.py", "content": "print('Hello')"} + ] + ) + # [/setup] + + client.environments.delete(id=created.id) + print("Environment deleted successfully.") + # [END paths['/{api_version}/environments/{id}'].delete:delete] + + def test_api_version_environments_id_get_get(self): + # [START paths['/{api_version}/environments/{id}'].get:get] + from google import genai + + client = genai.Client() + + # [setup] + created = client.environments.create( + sources=[ + {"type": "inline", "target": "main.py", "content": "print('Hello')"} + ] + ) + # [/setup] + + environment = client.environments.get(id=created.id) + print(environment.id) + + # [cleanup] + client.environments.delete(id=created.id) + # [/cleanup] + # [END paths['/{api_version}/environments/{id}'].get:get] + + def test_api_version_interactions_post_simple(self): + # [START paths['/{api_version}/interactions'].post:simple] + from google import genai + + client = genai.Client() + interaction = client.interactions.create( + model="gemini-3.6-flash", + input="Hello, how are you?", + ) + print(interaction.output_text) + # [END paths['/{api_version}/interactions'].post:simple] + + def test_api_version_interactions_post_multi_turn(self): + # [START paths['/{api_version}/interactions'].post:multi_turn] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + input=[ + { + "type": "user_input", + "content": [{"type": "text", "text": "Hello!"}], + }, + { + "type": "model_output", + "content": [{ + "type": "text", + "text": "Hi there! How can I help you today?", + }], + }, + { + "type": "user_input", + "content": [ + {"type": "text", "text": "What is the capital of France?"} + ], + }, + ], + ) + print(response.output_text) + # [END paths['/{api_version}/interactions'].post:multi_turn] + + def test_api_version_interactions_post_multimodal_image(self): + # [START paths['/{api_version}/interactions'].post:multimodal_image] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + input=[ + {"type": "text", "text": "What is in this picture?"}, + { + "type": "image", + "data": "BASE64_ENCODED_IMAGE", + "mime_type": "image/png", + }, + ], + ) + print(response.output_text) + # [END paths['/{api_version}/interactions'].post:multimodal_image] + + def test_api_version_interactions_post_function_calling(self): + # [START paths['/{api_version}/interactions'].post:function_calling] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[{ + "type": "function", + "name": "get_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": ( + "The city and state, e.g. San Francisco, CA" + ), + } + }, + "required": ["location"], + }, + }], + input="What is the weather like in Boston, MA?", + ) + print(response.steps[-1]) + # [END paths['/{api_version}/interactions'].post:function_calling] + + def test_api_version_interactions_post_deep_research(self): + # [START paths['/{api_version}/interactions'].post:deep_research] + from google import genai + + client = genai.Client() + interaction = client.interactions.create( + agent="deep-research-pro-preview-12-2025", + input="find a cure to cancer", + background=True, + ) + print(interaction.status) + # [END paths['/{api_version}/interactions'].post:deep_research] + + def test_api_version_interactions_post_antigravity(self): + # [START paths['/{api_version}/interactions'].post:antigravity] + from google import genai + + client = genai.Client() + interaction = client.interactions.create( + agent="antigravity-preview-05-2026", + input=( + "Read Hacker News, summarize the top 5 stories, and save results as" + " a markdown file." + ), + environment="remote", + ) + print(interaction.output_text) + # [END paths['/{api_version}/interactions'].post:antigravity] + + def test_api_version_interactions_post_reuse_env(self): + # [START paths['/{api_version}/interactions'].post:reuse_env] + from google import genai + + client = genai.Client() + + # Step 1: Create an interaction with a fresh remote environment. + interaction = client.interactions.create( + agent="antigravity-preview-05-2026", + input="Write a hello world script at /workspace/hello.py.", + environment="remote", + ) + print(f"Environment ID: {interaction.environment_id}") + + # Step 2: Reuse the same environment in a follow-up interaction. + interaction_2 = client.interactions.create( + agent="antigravity-preview-05-2026", + input="Modify the script to accept a name argument and greet the user.", + environment=interaction.environment_id, + previous_interaction_id=interaction.id, + ) + print(interaction_2.output_text) + # [END paths['/{api_version}/interactions'].post:reuse_env] + + def test_api_version_interactions_post_with_sources(self): + # [START paths['/{api_version}/interactions'].post:with_sources] + from google import genai + + client = genai.Client() + interaction = client.interactions.create( + agent="antigravity-preview-05-2026", + input="List all files under /workspace and summarize what you find.", + environment={ + "type": "remote", + "sources": [ + { + "type": "repository", + "source": "https://github.com/octocat/Spoon-Knife", + "target": "/workspace/repo", + }, + { + "type": "inline", + "content": "Focus on Python files only.", + "target": "/workspace/notes.txt", + }, + ], + }, + ) + print(interaction.output_text) + # [END paths['/{api_version}/interactions'].post:with_sources] + + def test_api_version_interactions_post_custom_agent(self): + # [START paths['/{api_version}/interactions'].post:custom_agent] + import uuid + from google import genai + + client = genai.Client() + + # Step 1: Create a custom agent. + agent_id = f"code-reviewer-{uuid.uuid4().hex[:8]}" + client.agents.create( + id=agent_id, + base_agent="antigravity-preview-05-2026", + system_instruction=( + "You are a senior code reviewer. Check every file for bugs, style" + " issues, and security vulnerabilities." + ), + base_environment={ + "type": "remote", + "sources": [{ + "type": "repository", + "source": "https://github.com/octocat/Spoon-Knife", + "target": "/workspace/repo", + }], + }, + ) + + # Step 2: Use the custom agent. + result = client.interactions.create( + agent=agent_id, + input=( + "Review the latest changes in /workspace/repo/src and file a" + " summary." + ), + environment="remote", + ) + print(result.output_text) + + # [cleanup] + client.agents.delete(agent_id) + # [/cleanup] + # [END paths['/{api_version}/interactions'].post:custom_agent] + + def test_api_version_interactions_id_delete_delete(self): + # [START paths['/{api_version}/interactions/{id}'].delete:delete] + from google import genai + + client = genai.Client() + + # [setup] + created = client.interactions.create( + model="gemini-3.6-flash", + input="Hello", + ) + # [/setup] + + client.interactions.delete(id=created.id) + print("Interaction deleted successfully.") + # [END paths['/{api_version}/interactions/{id}'].delete:delete] + + def test_api_version_interactions_id_get_get(self): + # [START paths['/{api_version}/interactions/{id}'].get:get] + from google import genai + + client = genai.Client() + + # [setup] + created = client.interactions.create( + model="gemini-3.6-flash", input="Say hello." + ) + # [/setup] + + interaction = client.interactions.get(id=created.id) + print(interaction.status) + # [END paths['/{api_version}/interactions/{id}'].get:get] + + def test_api_version_interactions_id_cancel_post_cancel(self): + # [START paths['/{api_version}/interactions/{id}/cancel'].post:cancel] + from google import genai + + client = genai.Client() + + # Start a background interaction so it stays in-progress. + created = client.interactions.create( + model="gemini-3.6-flash", + input="Write a long essay about the history of computing.", + tools=[{"type": "computer_use"}], + background=True, + ) + + # Cancel the in-progress interaction. + interaction = client.interactions.cancel(id=created.id) + print(interaction.status) + # [END paths['/{api_version}/interactions/{id}/cancel'].post:cancel] + + def test_schema_CodeExecution_code_execution(self): + # [START components.schemas.CodeExecution:code_execution] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[{"type": "code_execution"}], + input="Calculate the first 10 Fibonacci numbers", + ) + print(response.output_text) + # [END components.schemas.CodeExecution:code_execution] + + def test_schema_ComputerUse_computer_use(self): + # [START components.schemas.ComputerUse:computer_use] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-2.5-computer-use-preview-10-2025", + tools=[{"type": "computer_use"}], + input="Find a flight to Tokyo", + ) + print(response.output_text) + # [END components.schemas.ComputerUse:computer_use] + + def test_schema_FileSearch_file_search(self): + # [START components.schemas.FileSearch:file_search] + from google import genai + + client = genai.Client() + + # Create a file search store so we have a valid one to use. + store = client.file_search_stores.create() + + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[ + {"type": "file_search", "file_search_store_names": [store.name]} + ], + input="What documents are available?", + ) + print(response.output_text) + + # [cleanup] + client.file_search_stores.delete(name=store.name) + # [/cleanup] + # [END components.schemas.FileSearch:file_search] + + def test_schema_Function_function_calling(self): + # [START components.schemas.Function:function_calling] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[{ + "type": "function", + "name": "get_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": ( + "The city and state, e.g. San Francisco, CA" + ), + } + }, + "required": ["location"], + }, + }], + input="What is the weather like in Boston?", + ) + print(response.steps[-1]) + # [END components.schemas.Function:function_calling] + + def test_schema_GoogleMaps_google_maps(self): + # [START components.schemas.GoogleMaps:google_maps] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[ + {"type": "google_maps", "latitude": 37.7749, "longitude": -122.4194} + ], + input="What is the best food near me?", + ) + print(response.output_text) + # [END components.schemas.GoogleMaps:google_maps] + + def test_schema_GoogleSearch_google_search(self): + # [START components.schemas.GoogleSearch:google_search] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[{"type": "google_search"}], + input="Who is the current president of France?", + ) + print(response.output_text) + # [END components.schemas.GoogleSearch:google_search] + + def test_schema_McpServer_mcp_server(self): + # [START components.schemas.McpServer:mcp_server] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[{ + "type": "mcp_server", + "name": "weather_service", + "url": "https://gemini-api-demos.uc.r.appspot.com/mcp", + }], + input="Today is 12-05-2025, what is the temperature today in London?", + ) + print(response.output_text) + # [END components.schemas.McpServer:mcp_server] + + def test_schema_UrlContext_url_context(self): + # [START components.schemas.UrlContext:url_context] + from google import genai + + client = genai.Client() + response = client.interactions.create( + model="gemini-3.6-flash", + tools=[{"type": "url_context"}], + input="Summarize https://www.example.com", + ) + print(response.output_text) + # [END components.schemas.UrlContext:url_context] + + def test_api_version_voices_get_list(self): + # [START paths['/{api_version}/voices'].get:list] + from google import genai + + client = genai.Client() + response = client.voices.list() + for voice in response.voices or []: + print(voice.id, voice.display_name) + # [END paths['/{api_version}/voices'].get:list] + + def test_api_version_voices_post_create(self): + # [START paths['/{api_version}/voices'].post:create] + from google import genai + + client = genai.Client() + voice = client.voices.create( + store=True, + voice={ + "type": "prompted", + "display_name": "Warm Narrator", + "language_code": "en-US", + "prompted": { + "input": "A warm, friendly narrator voice with a calm pace.", + }, + }, + ) + print(voice.id) + + # [cleanup] + if voice.id: + client.voices.delete(id=voice.id) + # [/cleanup] + # [END paths['/{api_version}/voices'].post:create] + + def test_api_version_voices_voicesid_get_get(self): + # [START paths['/{api_version}/voices/{voicesId}'].get:get] + from google import genai + + client = genai.Client() + voice = client.voices.get(id="voice_abc123") + print(voice.id, voice.display_name) + # [END paths['/{api_version}/voices/{voicesId}'].get:get] + + def test_api_version_voices_voicesid_delete_delete(self): + # [START paths['/{api_version}/voices/{voicesId}'].delete:delete] + from google import genai + + client = genai.Client() + client.voices.delete(id="voice_abc123") + # [END paths['/{api_version}/voices/{voicesId}'].delete:delete] + + def test_api_version_triggers_post_create(self): + # [START paths['/{api_version}/triggers'].post:create] + from google import genai + + client = genai.Client() + trigger = client.triggers.create( + schedule="0 9 * * *", + time_zone="America/New_York", + interaction={ + "agent": "antigravity-preview-05-2026", + "input": "Summarize top news stories.", + "environment": "remote", + }, + ) + print(trigger.id, trigger.interaction.agent) + + # [cleanup] + if trigger.id: + client.triggers.delete(id=trigger.id) + # [/cleanup] + # [END paths['/{api_version}/triggers'].post:create] + + +if __name__ == "__main__": + absltest.main() diff --git a/interactions/typescript_samples_test.ts b/interactions/typescript_samples_test.ts new file mode 100644 index 0000000..b0e764d --- /dev/null +++ b/interactions/typescript_samples_test.ts @@ -0,0 +1,794 @@ +/** + * @license + * Copyright 2026 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. + */ + +import {GoogleGenAI} from '@google/genai'; + +describe('Interactions API TypeScript Samples', () => { + it('api version agents get list', async () => { + // [START paths['/{api_version}/agents'].get:list] + + const ai = new GoogleGenAI({}); + const agents = await ai.agents.list(); + for (const agent of agents.agents ?? []) { + console.log(agent.id); + } + // [END paths['/{api_version}/agents'].get:list] + }); + + it('api version agents post create', async () => { + // [START paths['/{api_version}/agents'].post:create] + + const ai = new GoogleGenAI({}); + const agentId = `research-assistant-${crypto.randomUUID().slice(0, 8)}`; + const agent = await ai.agents.create({ + id: agentId, + base_agent: 'antigravity-preview-05-2026', + description: 'A helpful research assistant.', + system_instruction: 'You are a helpful research assistant.', + base_environment: 'remote', + tools: [{type: 'google_search'}], + }); + if (!agent.id) { + throw new Error('Agent creation failed: ID is undefined'); + } + console.log(agent.id); + + // [cleanup] + await ai.agents.delete(agent.id); + // [/cleanup] + // [END paths['/{api_version}/agents'].post:create] + }); + + it('api version agents post with sources', async () => { + // [START paths['/{api_version}/agents'].post:with_sources] + + const ai = new GoogleGenAI({}); + const agentId = `data-analyst-${crypto.randomUUID().slice(0, 8)}`; + const agent = await ai.agents.create({ + id: agentId, + base_agent: 'antigravity-preview-05-2026', + system_instruction: + 'You are a data analyst. Always include visualizations and export results as PDF.', + base_environment: { + type: 'remote', + sources: [ + { + type: 'inline', + target: '.agents/AGENTS.md', + content: + 'Always use matplotlib for charts. Include a summary table in every report.', + }, + { + type: 'repository', + source: 'https://github.com/my-org/analysis-templates', + target: '/workspace/templates', + }, + ], + }, + }); + console.log(`Created agent: ${agent.id}`); + + // [cleanup] + if (agent.id) await ai.agents.delete(agent.id); + // [/cleanup] + // [END paths['/{api_version}/agents'].post:with_sources] + }); + + it('api version agents post fork from env', async () => { + // [START paths['/{api_version}/agents'].post:fork_from_env] + + const ai = new GoogleGenAI({}); + + // Step 1: Set up the environment interactively. + const interaction = await ai.interactions.create({ + agent: 'antigravity-preview-05-2026', + input: 'Write a basic Hello World template to /workspace/template.py.', + environment: 'remote', + }); + + // Step 2: Fork that environment into a named agent. + const agentId = `my-data-analyst-${crypto.randomUUID().slice(0, 8)}`; + const agent = await ai.agents.create({ + id: agentId, + base_agent: 'antigravity-preview-05-2026', + system_instruction: + 'You are a data analyst. Use the template at /workspace/template.py for all reports.', + base_environment: interaction.environment_id, + }); + console.log(`Forked agent: ${agent.id}`); + + // [cleanup] + if (agent.id) await ai.agents.delete(agent.id); + // [/cleanup] + // [END paths['/{api_version}/agents'].post:fork_from_env] + }); + + it('api version agents id delete delete', async () => { + // [START paths['/{api_version}/agents/{id}'].delete:delete] + + const ai = new GoogleGenAI({}); + + // [setup] + const agentId = `delete-test-${crypto.randomUUID().slice(0, 8)}`; + await ai.agents.create({ + id: agentId, + base_agent: 'antigravity-preview-05-2026', + description: 'Temporary agent for deletion.', + base_environment: 'remote', + }); + // [/setup] + + await ai.agents.delete(agentId); + console.log('Agent deleted successfully.'); + // [END paths['/{api_version}/agents/{id}'].delete:delete] + }); + + it('api version agents id get get', async () => { + // [START paths['/{api_version}/agents/{id}'].get:get] + + const ai = new GoogleGenAI({}); + + // [setup] + const agentId = `test-agent-${crypto.randomUUID().slice(0, 8)}`; + await ai.agents.create({ + id: agentId, + base_agent: 'antigravity-preview-05-2026', + description: 'A test agent.', + base_environment: 'remote', + }); + // [/setup] + + const agent = await ai.agents.get(agentId); + if (!agent.id) { + throw new Error('Agent retrieval failed: ID is undefined'); + } + console.log(agent.id); + + // [cleanup] + await ai.agents.delete(agent.id); + // [/cleanup] + // [END paths['/{api_version}/agents/{id}'].get:get] + }); + + it('api version environments get list', async () => { + // [START paths['/{api_version}/environments'].get:list] + + const ai = new GoogleGenAI({}); + const response = await ai.environments.list(); + for (const env of response.environments ?? []) { + console.log(env.id); + } + // [END paths['/{api_version}/environments'].get:list] + }); + + it('api version environments post create', async () => { + // [START paths['/{api_version}/environments'].post:create] + + const ai = new GoogleGenAI({}); + const environment = await ai.environments.create({ + sources: [ + { + type: 'inline', + target: 'main.py', + content: "print('Hello, World!')", + }, + ], + }); + if (!environment.id) { + throw new Error('Environment creation failed: ID is undefined'); + } + console.log(environment.id); + + // [cleanup] + await ai.environments.delete(environment.id); + // [/cleanup] + // [END paths['/{api_version}/environments'].post:create] + }); + + it('api version environments post copy', async () => { + // [START paths['/{api_version}/environments'].post:copy] + + const ai = new GoogleGenAI({}); + + // [setup] + const sourceEnv = await ai.environments.create({ + sources: [{type: 'inline', target: 'main.py', content: "print('Hello')"}], + }); + if (!sourceEnv.id) throw new Error('Failed to create source environment'); + // [/setup] + + const environment = await ai.environments.create({ + from_environment: sourceEnv.id, + }); + if (!environment.id) { + throw new Error('Environment creation failed: ID is undefined'); + } + console.log(environment.id); + + // [cleanup] + await ai.environments.delete(environment.id); + await ai.environments.delete(sourceEnv.id); + // [/cleanup] + // [END paths['/{api_version}/environments'].post:copy] + }); + + it('api version environments environment files path get list files', async () => { + // [START paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] + + const ai = new GoogleGenAI({}); + + // [setup] + const created = await ai.environments.create({ + sources: [ + {type: 'inline', target: 'src/main.py', content: "print('Hello')"}, + ], + }); + if (!created.id) throw new Error('Failed to create environment'); + // [/setup] + + const response = await ai.environments.files.list({ + environment: created.id, + path: 'src', + }); + for (const file of response.files ?? []) { + console.log(file.name, file.type, file.size_bytes); + } + + // [cleanup] + await ai.environments.delete(created.id); + // [/cleanup] + // [END paths['/{api_version}/environments/{environment}/files/{path}'].get:list_files] + }); + + it('api version environments environment files path get get file', async () => { + // [START paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] + + const ai = new GoogleGenAI({}); + + // [setup] + const created = await ai.environments.create({ + sources: [{type: 'inline', target: 'main.py', content: "print('Hello')"}], + }); + if (!created.id) throw new Error('Failed to create environment'); + // [/setup] + + const response = await ai.environments.files.list({ + environment: created.id, + path: 'main.py', + }); + for (const file of response.files ?? []) { + console.log(file.name, file.size_bytes); + } + + // [cleanup] + await ai.environments.delete(created.id); + // [/cleanup] + // [END paths['/{api_version}/environments/{environment}/files/{path}'].get:get_file] + }); + + it('api version environments id delete delete', async () => { + // [START paths['/{api_version}/environments/{id}'].delete:delete] + + const ai = new GoogleGenAI({}); + + // [setup] + const created = await ai.environments.create({ + sources: [{type: 'inline', target: 'main.py', content: "print('Hello')"}], + }); + if (!created.id) throw new Error('Failed to create environment'); + // [/setup] + + await ai.environments.delete(created.id); + console.log('Environment deleted successfully.'); + // [END paths['/{api_version}/environments/{id}'].delete:delete] + }); + + it('api version environments id get get', async () => { + // [START paths['/{api_version}/environments/{id}'].get:get] + + const ai = new GoogleGenAI({}); + + // [setup] + const created = await ai.environments.create({ + sources: [{type: 'inline', target: 'main.py', content: "print('Hello')"}], + }); + if (!created.id) throw new Error('Failed to create environment'); + // [/setup] + + const environment = await ai.environments.get(created.id); + console.log(environment.id); + + // [cleanup] + await ai.environments.delete(created.id); + // [/cleanup] + // [END paths['/{api_version}/environments/{id}'].get:get] + }); + + it('api version interactions post simple', async () => { + // [START paths['/{api_version}/interactions'].post:simple] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + input: 'Hello, how are you?', + }); + console.log(interaction.output_text); + // [END paths['/{api_version}/interactions'].post:simple] + }); + + it('api version interactions post multi turn', async () => { + // [START paths['/{api_version}/interactions'].post:multi_turn] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + input: [ + {type: 'user_input', content: [{type: 'text', text: 'Hello'}]}, + { + type: 'model_output', + content: [ + {type: 'text', text: 'Hi there! How can I help you today?'}, + ], + }, + { + type: 'user_input', + content: [{type: 'text', text: 'What is the capital of France?'}], + }, + ], + }); + console.log(interaction.output_text); + // [END paths['/{api_version}/interactions'].post:multi_turn] + }); + + it('api version interactions post multimodal image', async () => { + // [START paths['/{api_version}/interactions'].post:multimodal_image] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + input: [ + {type: 'text', text: 'What is in this picture?'}, + {type: 'image', data: 'BASE64_ENCODED_IMAGE', mime_type: 'image/png'}, + ], + }); + console.log(interaction.output_text); + // [END paths['/{api_version}/interactions'].post:multimodal_image] + }); + + it('api version interactions post function calling', async () => { + // [START paths['/{api_version}/interactions'].post:function_calling] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [ + { + type: 'function', + name: 'get_weather', + description: 'Get the current weather in a given location', + parameters: { + type: 'object', + properties: { + location: { + type: 'string', + description: 'The city and state, e.g. San Francisco, CA', + }, + }, + required: ['location'], + }, + }, + ], + input: 'What is the weather like in Boston, MA?', + }); + console.log(interaction.steps.at(-1)); + // [END paths['/{api_version}/interactions'].post:function_calling] + }); + + it('api version interactions post deep research', async () => { + // [START paths['/{api_version}/interactions'].post:deep_research] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + agent: 'deep-research-pro-preview-12-2025', + input: 'find a cure to cancer', + background: true, + }); + console.log(interaction.status); + // [END paths['/{api_version}/interactions'].post:deep_research] + }); + + it('api version interactions post antigravity', async () => { + // [START paths['/{api_version}/interactions'].post:antigravity] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + agent: 'antigravity-preview-05-2026', + input: + 'Read Hacker News, summarize the top 5 stories, and save results as a markdown file.', + environment: 'remote', + }); + console.log(interaction.output_text); + // [END paths['/{api_version}/interactions'].post:antigravity] + }); + + it('api version interactions post reuse env', async () => { + // [START paths['/{api_version}/interactions'].post:reuse_env] + + const ai = new GoogleGenAI({}); + + // Step 1: Create an interaction with a fresh remote environment. + const interaction = await ai.interactions.create({ + agent: 'antigravity-preview-05-2026', + input: 'Write a hello world script at /workspace/hello.py.', + environment: 'remote', + }); + console.log(`Environment ID: ${interaction.environment_id}`); + + // Step 2: Reuse the same environment in a follow-up interaction. + const interaction2 = await ai.interactions.create({ + agent: 'antigravity-preview-05-2026', + input: 'Modify the script to accept a name argument and greet the user.', + environment: interaction.environment_id, + previous_interaction_id: interaction.id, + }); + console.log(interaction2.output_text); + // [END paths['/{api_version}/interactions'].post:reuse_env] + }); + + it('api version interactions post with sources', async () => { + // [START paths['/{api_version}/interactions'].post:with_sources] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + agent: 'antigravity-preview-05-2026', + input: 'List all files under /workspace and summarize what you find.', + environment: { + type: 'remote', + sources: [ + { + type: 'repository', + source: 'https://github.com/octocat/Spoon-Knife', + target: '/workspace/repo', + }, + { + type: 'inline', + content: 'Focus on Python files only.', + target: '/workspace/notes.txt', + }, + ], + }, + }); + console.log(interaction.output_text); + // [END paths['/{api_version}/interactions'].post:with_sources] + }); + + it('api version interactions post custom agent', async () => { + // [START paths['/{api_version}/interactions'].post:custom_agent] + + const ai = new GoogleGenAI({}); + + // Step 1: Create a custom agent. + const agentId = `code-reviewer-${crypto.randomUUID().slice(0, 8)}`; + await ai.agents.create({ + id: agentId, + base_agent: 'antigravity-preview-05-2026', + system_instruction: + 'You are a senior code reviewer. Check every file for bugs, style issues, and security vulnerabilities.', + base_environment: { + type: 'remote', + sources: [ + { + type: 'repository', + source: 'https://github.com/octocat/Spoon-Knife', + target: '/workspace/repo', + }, + ], + }, + }); + + // Step 2: Use the custom agent. + const result = await ai.interactions.create({ + agent: agentId, + input: + 'Review the latest changes in /workspace/repo/src and file a summary.', + environment: 'remote', + }); + console.log(result.output_text); + + // [cleanup] + await ai.agents.delete(agentId); + // [/cleanup] + // [END paths['/{api_version}/interactions'].post:custom_agent] + }); + + it('api version interactions id delete delete', async () => { + // [START paths['/{api_version}/interactions/{id}'].delete:delete] + + const ai = new GoogleGenAI({}); + + // [setup] + const created = await ai.interactions.create({ + model: 'gemini-3.6-flash', + input: 'Hello', + }); + // [/setup] + + await ai.interactions.delete(created.id); + console.log('Interaction deleted successfully.'); + // [END paths['/{api_version}/interactions/{id}'].delete:delete] + }); + + it('api version interactions id get get', async () => { + // [START paths['/{api_version}/interactions/{id}'].get:get] + + const ai = new GoogleGenAI({}); + + // [setup] + const created = await ai.interactions.create({ + model: 'gemini-3.6-flash', + input: 'Say hello.', + }); + // [/setup] + + const interaction = await ai.interactions.get(created.id); + console.log(interaction.status); + // [END paths['/{api_version}/interactions/{id}'].get:get] + }); + + it('api version interactions id cancel post cancel', async () => { + // [START paths['/{api_version}/interactions/{id}/cancel'].post:cancel] + + const ai = new GoogleGenAI({}); + + // Start a background interaction so it stays in-progress. + const created = await ai.interactions.create({ + model: 'gemini-3.6-flash', + input: 'Write a long essay about the history of computing.', + tools: [{type: 'computer_use'}], + background: true, + }); + + // Cancel the in-progress interaction. + const interaction = await ai.interactions.cancel(created.id); + console.log(interaction.status); + // [END paths['/{api_version}/interactions/{id}/cancel'].post:cancel] + }); + + it('schema CodeExecution code execution', async () => { + // [START components.schemas.CodeExecution:code_execution] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [{type: 'code_execution'}], + input: 'Calculate the first 10 Fibonacci numbers', + }); + console.log(interaction.output_text); + // [END components.schemas.CodeExecution:code_execution] + }); + + it('schema ComputerUse computer use', async () => { + // [START components.schemas.ComputerUse:computer_use] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-2.5-computer-use-preview-10-2025', + tools: [{type: 'computer_use'}], + input: 'Find a flight to Tokyo', + }); + console.log(interaction.output_text); + // [END components.schemas.ComputerUse:computer_use] + }); + + it('schema FileSearch file search', async () => { + // [START components.schemas.FileSearch:file_search] + + const ai = new GoogleGenAI({}); + + // Create a file search store so we have a valid one to use. + const store = await ai.fileSearchStores.create({}); + if (!store.name) { + throw new Error('Store creation failed: Name is undefined'); + } + + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [ + { + type: 'file_search', + file_search_store_names: [store.name], + }, + ], + input: 'What documents are available?', + }); + console.log(interaction.output_text); + + // [cleanup] + await ai.fileSearchStores.delete({name: store.name}); + // [/cleanup] + // [END components.schemas.FileSearch:file_search] + }); + + it('schema Function function calling', async () => { + // [START components.schemas.Function:function_calling] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [ + { + type: 'function', + name: 'get_weather', + description: 'Get the current weather in a given location', + parameters: { + type: 'object', + properties: { + location: { + type: 'string', + description: 'The city and state, e.g. San Francisco, CA', + }, + }, + required: ['location'], + }, + }, + ], + input: 'What is the weather like in Boston?', + }); + console.log(interaction.steps.at(-1)); + // [END components.schemas.Function:function_calling] + }); + + it('schema GoogleMaps google maps', async () => { + // [START components.schemas.GoogleMaps:google_maps] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [ + { + type: 'google_maps', + latitude: 37.7749, + longitude: -122.4194, + }, + ], + input: 'What is the best food near me?', + }); + console.log(interaction.output_text); + // [END components.schemas.GoogleMaps:google_maps] + }); + + it('schema GoogleSearch google search', async () => { + // [START components.schemas.GoogleSearch:google_search] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [{type: 'google_search'}], + input: 'Who is the current president of France?', + }); + console.log(interaction.output_text); + // [END components.schemas.GoogleSearch:google_search] + }); + + it('schema McpServer mcp server', async () => { + // [START components.schemas.McpServer:mcp_server] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [ + { + type: 'mcp_server', + name: 'weather_service', + url: 'https://gemini-api-demos.uc.r.appspot.com/mcp', + }, + ], + input: 'Today is 12-05-2025, what is the temperature today in London?', + }); + console.log(interaction.output_text); + // [END components.schemas.McpServer:mcp_server] + }); + + it('schema UrlContext url context', async () => { + // [START components.schemas.UrlContext:url_context] + + const ai = new GoogleGenAI({}); + const interaction = await ai.interactions.create({ + model: 'gemini-3.6-flash', + tools: [{type: 'url_context'}], + input: 'Summarize https://www.example.com', + }); + console.log(interaction.output_text); + // [END components.schemas.UrlContext:url_context] + }); + + it('api version voices get list', async () => { + // [START paths['/{api_version}/voices'].get:list] + + const ai = new GoogleGenAI({}); + const response = await ai.voices.list(); + for (const voice of response.voices ?? []) { + console.log(voice.id, voice.display_name); + } + // [END paths['/{api_version}/voices'].get:list] + }); + + it('api version voices post create', async () => { + // [START paths['/{api_version}/voices'].post:create] + + const ai = new GoogleGenAI({}); + const voice = await ai.voices.create({ + store: true, + voice: { + type: 'prompted', + display_name: 'Warm Narrator', + language_code: 'en-US', + prompted: { + input: 'A warm, friendly narrator voice with a calm pace.', + }, + }, + }); + console.log(voice.id); + + // [cleanup] + if (voice.id) { + await ai.voices.delete(voice.id); + } + // [/cleanup] + // [END paths['/{api_version}/voices'].post:create] + }); + + it('api version voices voicesId get get', async () => { + // [START paths['/{api_version}/voices/{voicesId}'].get:get] + + const ai = new GoogleGenAI({}); + const voice = await ai.voices.get('voice_abc123'); + console.log(voice.id, voice.display_name); + // [END paths['/{api_version}/voices/{voicesId}'].get:get] + }); + + it('api version voices voicesId delete delete', async () => { + // [START paths['/{api_version}/voices/{voicesId}'].delete:delete] + + const ai = new GoogleGenAI({}); + await ai.voices.delete('voice_abc123'); + // [END paths['/{api_version}/voices/{voicesId}'].delete:delete] + }); + + it('api version triggers post create', async () => { + // [START paths['/{api_version}/triggers'].post:create] + + const ai = new GoogleGenAI({}); + const trigger = await ai.triggers.create({ + schedule: '0 9 * * *', + time_zone: 'America/New_York', + interaction: { + agent: 'antigravity-preview-05-2026', + input: 'Summarize top news stories.', + environment: 'remote', + }, + }); + console.log(trigger.id, trigger.interaction.agent); + + // [cleanup] + if (trigger.id) { + await ai.triggers.delete(trigger.id); + } + // [/cleanup] + // [END paths['/{api_version}/triggers'].post:create] + }); +}); diff --git a/javascript/code_execution.js b/javascript/code_execution.js index 30b5dcb..d7d46f8 100644 --- a/javascript/code_execution.js +++ b/javascript/code_execution.js @@ -214,7 +214,7 @@ export async function codeExecutionChat() { // 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, // 229] // sum(primes)=5117 - // [END code_execution_request_chat_return] + // [END code_execution_chat_return] return { executableCode: response.executableCode, diff --git a/javascript/count_tokens.js b/javascript/count_tokens.js index e788dc0..d6020e0 100644 --- a/javascript/count_tokens.js +++ b/javascript/count_tokens.js @@ -244,7 +244,7 @@ export async function tokensMultimodalPdfFileApi() { ]), }); console.log(generateResponse.usageMetadata); - // [START tokens_multimodal_pdf_file_api] + // [END tokens_multimodal_pdf_file_api] return { totalTokens: countTokensResponse.totalTokens, usage: generateResponse.usageMetadata, @@ -288,7 +288,7 @@ export async function tokensCachedContent() { console.log(generateResponse.usageMetadata); await ai.caches.delete({name: cache.name}); - // [START tokens_cached_content] + // [END tokens_cached_content] return { totalTokens: countTokensResponse.totalTokens, usage: generateResponse.usageMetadata, diff --git a/javascript/function_calling.js b/javascript/function_calling.js index 23de484..4db4a40 100644 --- a/javascript/function_calling.js +++ b/javascript/function_calling.js @@ -198,6 +198,6 @@ export async function functionCalling() { message: 'The final result is ' + resultValue, }); console.log(chatResponse.text); - // [START function_calling] + // [END function_calling] return chatResponse; } diff --git a/javascript/safety_settings.js b/javascript/safety_settings.js index 3933a67..be95a18 100644 --- a/javascript/safety_settings.js +++ b/javascript/safety_settings.js @@ -75,6 +75,6 @@ export async function safetySettingsMulti() { console.log('No information generated by the model.'); } console.log('Safety ratings:', response.candidates[0].safetyRatings); - // [START safety_settings_multi] + // [END safety_settings_multi] return response; } diff --git a/rest/cache.sh b/rest/cache.sh index 8df6878..e55530d 100644 --- a/rest/cache.sh +++ b/rest/cache.sh @@ -10,7 +10,7 @@ echo "[START cache_create]" # [START cache_create] wget https://storage.googleapis.com/generativeai-downloads/data/a11.txt echo '{ - "model": "models/gemini-1.5-flash-001", + "model": "models/gemini-3.8-flash", "contents":[ { "parts":[ @@ -41,9 +41,8 @@ curl -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents?ke CACHE_NAME=$(cat cache.json | grep '"name":' | cut -d '"' -f 4 | head -n 1) -echo "[START cache_generate_content]" # [START cache_generate_content] -curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-001:generateContent?key=$GEMINI_API_KEY" \ +curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "contents": [ diff --git a/rest/chat.sh b/rest/chat.sh index 67abfbf..1a6b4b4 100644 --- a/rest/chat.sh +++ b/rest/chat.sh @@ -5,7 +5,7 @@ MEDIA_DIR=$(realpath ${SCRIPT_DIR}/../third_party) echo "[START chat]" # [START chat] -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \ +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -25,7 +25,7 @@ curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:ge echo "[START chat_streaming]" # [START chat_streaming] -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \ +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -53,7 +53,7 @@ else B64FLAGS="-w0" fi -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \ +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \ -H 'Content-Type: application/json' \ -X POST \ -d '{ diff --git a/rest/code_execution.sh b/rest/code_execution.sh index f134e72..98007cc 100644 --- a/rest/code_execution.sh +++ b/rest/code_execution.sh @@ -2,7 +2,7 @@ set -eu echo "[START code_execution_basic]" # [START code_execution_basic] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d ' {"tools": [{"code_execution": {}}], "contents": { @@ -16,7 +16,7 @@ curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:g echo "[START code_execution_chat]" # [START code_execution_chat] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"tools": [{"code_execution": {}}], "contents": [ diff --git a/rest/configure_model_parameters.sh b/rest/configure_model_parameters.sh index 2e6e31b..5d70c2f 100644 --- a/rest/configure_model_parameters.sh +++ b/rest/configure_model_parameters.sh @@ -2,7 +2,7 @@ set -eu echo "[START configure_model_parameters]" # [START configure_model_parameters] -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \ +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY \ -H 'Content-Type: application/json' \ -X POST \ -d '{ diff --git a/rest/controlled_generation.sh b/rest/controlled_generation.sh index 352b435..538b7af 100644 --- a/rest/controlled_generation.sh +++ b/rest/controlled_generation.sh @@ -2,7 +2,7 @@ set -eu echo "json_controlled_generation" # [START json_controlled_generation] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "contents": [{ @@ -27,7 +27,7 @@ curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:g echo "json_no_schema" # [START json_no_schema] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "contents": [{ diff --git a/rest/count_tokens.sh b/rest/count_tokens.sh index 78d5afb..da72934 100644 --- a/rest/count_tokens.sh +++ b/rest/count_tokens.sh @@ -19,14 +19,14 @@ fi echo "[START tokens_context_window]" # [START tokens_context_window] -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro?key=$GEMINI_API_KEY > model.json +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash?key=$GEMINI_API_KEY > model.json jq .inputTokenLimit model.json jq .outputTokenLimit model.json # [END tokens_context_window] echo "[START tokens_text_only]" # [START tokens_text_only] -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:countTokens?key=$GEMINI_API_KEY \ +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:countTokens?key=$GEMINI_API_KEY \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -40,7 +40,7 @@ curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:co echo "[START tokens_chat]" # [START tokens_chat] -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:countTokens?key=$GEMINI_API_KEY \ +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:countTokens?key=$GEMINI_API_KEY \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -57,7 +57,7 @@ curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:co echo "[START tokens_multimodal_image_inline]" # [START tokens_multimodal_image_inline] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:countTokens?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:countTokens?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -85,7 +85,7 @@ tmp_header_file=upload-header.tmp # Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file. -curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}" \ +curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}" \ -D upload-header.tmp \ -H "X-Goog-Upload-Protocol: resumable" \ -H "X-Goog-Upload-Command: start" \ @@ -106,7 +106,7 @@ curl "${upload_url}" \ file_uri=$(jq ".file.uri" file_info.json) -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:countTokens?key=$GOOGLE_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:countTokens?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -130,7 +130,7 @@ DISPLAY_NAME=VIDEO_PATH # Initial resumable request defining metadata. # The upload url is in the response headers dump them to a file. -curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}" \ +curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}" \ -D upload-header.tmp \ -H "X-Goog-Upload-Protocol: resumable" \ -H "X-Goog-Upload-Command: start" \ @@ -164,7 +164,7 @@ do state=$(jq ".file.state" file_info.json) done -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:countTokens?key=$GOOGLE_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:countTokens?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -179,7 +179,7 @@ curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:c echo "[START tokens_cached_content]" # [START tokens_cached_content] echo '{ - "model": "models/gemini-1.5-flash-001", + "model": "models/gemini-3.8-flash", "contents":[ { "parts":[ @@ -203,7 +203,7 @@ echo '{ "ttl": "300s" }' > request.json -curl -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GOOGLE_API_KEY" \ +curl -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d @request.json \ > cache.json @@ -213,7 +213,7 @@ jq .usageMetadata.totalTokenCount cache.json echo "[START tokens_system_instruction]" # [START tokens_system_instruction] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=$GOOGLE_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "system_instruction": { "parts": @@ -260,7 +260,7 @@ cat > tools.json << EOF } EOF -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=$GOOGLE_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d ' { diff --git a/rest/files.sh b/rest/files.sh index 7006c69..e770033 100644 --- a/rest/files.sh +++ b/rest/files.sh @@ -45,7 +45,7 @@ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri # Now generate content using that file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -61,7 +61,6 @@ echo jq ".candidates[].content.parts[].text" response.json -echo "[START files_get]" # [START files_get] name=$(jq ".file.name" file_info.json) # Get the file of interest to check state @@ -73,7 +72,6 @@ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri # [END files_get] -echo "[START files_delete]" # [START files_delete] curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name?key=$GEMINI_API_KEY # [END files_delete] @@ -113,7 +111,7 @@ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri # Now generate content using that file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -166,7 +164,7 @@ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri # Now generate content using that file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -227,7 +225,7 @@ do done # Now generate content using that file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -275,7 +273,7 @@ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri # Now generate content using that file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ diff --git a/rest/function_calling.sh b/rest/function_calling.sh index a0e0fa2..f7ebf26 100644 --- a/rest/function_calling.sh +++ b/rest/function_calling.sh @@ -34,7 +34,7 @@ cat > tools.json << EOF } EOF -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d @<(echo ' { diff --git a/rest/models.sh b/rest/models.sh index 465d627..0c796dd 100644 --- a/rest/models.sh +++ b/rest/models.sh @@ -7,5 +7,5 @@ curl https://generativelanguage.googleapis.com/v1beta/models?key=$GEMINI_API_KEY echo "[START models_get]" # [START models_get] -curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash?key=$GEMINI_API_KEY +curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash?key=$GEMINI_API_KEY # [END models_get] diff --git a/rest/safety_settings.sh b/rest/safety_settings.sh index a087307..f22bd83 100644 --- a/rest/safety_settings.sh +++ b/rest/safety_settings.sh @@ -10,7 +10,7 @@ echo "[START safety_settings]" "parts":[{ "text": "'I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them.'"}]}]}' > request.json - curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ + curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d @request.json 2> /dev/null @@ -27,7 +27,7 @@ echo "[START safety_settings_multi]" "parts":[{ "text": "'I support Martians Soccer Club and I think Jupiterians Football Club sucks! Write a ironic phrase about them.'"}]}]}' > request.json - curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ + curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d @request.json 2> /dev/null diff --git a/rest/system_instruction.sh b/rest/system_instruction.sh index 44f77ea..a7757fe 100644 --- a/rest/system_instruction.sh +++ b/rest/system_instruction.sh @@ -2,7 +2,7 @@ set -eu echo "[START system_instruction]" # [START system_instruction] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "system_instruction": { "parts": diff --git a/rest/text_generation.sh b/rest/text_generation.sh index dc078af..cd4c490 100644 --- a/rest/text_generation.sh +++ b/rest/text_generation.sh @@ -19,7 +19,7 @@ BASE_URL="https://generativelanguage.googleapis.com" echo "[START text_gen_text_only_prompt]" # [START text_gen_text_only_prompt] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -31,7 +31,7 @@ curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:g echo "[START text_gen_text_only_prompt_streaming]" # [START text_gen_text_only_prompt_streaming] -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \ -H 'Content-Type: application/json' \ --no-buffer \ -d '{ "contents":[{"parts":[{"text": "Write a story about a magic backpack."}]}]}' @@ -64,7 +64,7 @@ cat > "$TEMP_JSON" << EOF } EOF -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d "@$TEMP_JSON" 2> /dev/null @@ -88,7 +88,7 @@ cat > "$TEMP_JSON" << EOF } EOF -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d "@$TEMP_JSON" 2> /dev/null @@ -129,7 +129,7 @@ cat > "$TEMP_JSON" << EOF EOF # Make the API request using the JSON file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d "@$TEMP_JSON" 2> /dev/null > response.json @@ -162,7 +162,7 @@ cat > "$TEMP_JSON" << EOF EOF # Make the API request using the JSON file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d "@$TEMP_JSON" 2> /dev/null > response.json @@ -203,7 +203,7 @@ curl "${upload_url}" \ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -253,7 +253,7 @@ curl "${upload_url}" \ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -314,7 +314,7 @@ do state=$(jq ".file.state" file_info.json) done -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -374,7 +374,7 @@ do state=$(jq ".file.state" file_info.json) done -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -424,7 +424,7 @@ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri # Now generate content using that file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ @@ -476,7 +476,7 @@ file_uri=$(jq ".file.uri" file_info.json) echo file_uri=$file_uri # Now generate content using that file -curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ +curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{