SPB Git

Repository Public

text-generation.md 31.2 KB 948 lines markdown

1The Gemini API can generate text output from text, images, video, and audio2inputs.34Here's a basic example:56### Python78    from google import genai910    client = genai.Client()1112    interaction = client.interactions.create(13        model="gemini-3.8-flash",14        input="How does AI work?"15    )16    print(interaction.output_text)1718### JavaScript1920    import { GoogleGenAI } from "@google/genai";2122    const ai = new GoogleGenAI({});2324    async function main() {25      const interaction = await ai.interactions.create({26        model: "gemini-3.8-flash",27        input: "How does AI work?",28      });29      console.log(interaction.output_text);30    }3132    await main();3334### Java3536    import com.google.genai.Client;37    import com.google.genai.gaos.models.interactions.CreateModelInteraction;38    import com.google.genai.gaos.models.interactions.Interaction;39    import com.google.genai.gaos.models.interactions.InteractionsInput;40    import com.google.genai.gaos.models.interactions.Model;41    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;4243    Client client = new Client();4445    CreateModelInteraction params =46        CreateModelInteraction.builder()47            .model(Model.of("gemini-3.8-flash"))48            .input(InteractionsInput.of("How does AI work?"))49            .build();5051    Interaction interaction =52        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();5354    System.out.println(interaction.outputText().orElse(""));5556### REST5758    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \59      -H "x-goog-api-key: $GEMINI_API_KEY" \60      -H 'Content-Type: application/json' \61      -d '{62        "model": "gemini-3.8-flash",63        "input": "How does AI work?"64      }'6566The Google GenAI SDKs provide convenience properties directly67on the returned `Interaction` object to access the model's response.6869The most common helper is **`interaction.output_text`** (String), which returns70the last text blocks in the model's response. If the response is split71across multiple consecutive `TextContent` blocks, it automatically joins them.72Note that `.output_text` does not include earlier text blocks separated by73non-text content (such as thoughts, images, audio, or tool calls). For complex74or interleaved multimodal responses, you must manually iterate over `steps`75instead. To learn more about other media convenience properties, see the76[Interactions overview](https://ai.google.dev/gemini-api/docs/interactions#convenience-properties).7778## Thinking with Gemini7980Gemini models often have ["thinking"](https://ai.google.dev/gemini-api/docs/thinking)81enabled by default which allows the model to reason before responding to a82request.8384Each model supports different thinking configurations which gives you control85over cost, latency, and intelligence. For more details, see the86[thinking guide](https://ai.google.dev/gemini-api/docs/thinking#set-budget).8788### Python8990    from google import genai9192    client = genai.Client()9394    interaction = client.interactions.create(95        model="gemini-3.8-flash",96        input="How does AI work?",97        generation_config={98            "thinking_level": "low"99        }100    )101    print(interaction.output_text)102103### JavaScript104105    import { GoogleGenAI } from "@google/genai";106107    const ai = new GoogleGenAI({});108109    async function main() {110      const interaction = await ai.interactions.create({111        model: "gemini-3.8-flash",112        input: "How does AI work?",113        generation_config: {114          thinking_level: "low",115        },116      });117      console.log(interaction.output_text);118    }119120    await main();121122### Java123124    import com.google.genai.Client;125    import com.google.genai.gaos.models.interactions.CreateModelInteraction;126    import com.google.genai.gaos.models.interactions.GenerationConfig;127    import com.google.genai.gaos.models.interactions.Interaction;128    import com.google.genai.gaos.models.interactions.InteractionsInput;129    import com.google.genai.gaos.models.interactions.Model;130    import com.google.genai.gaos.models.interactions.ThinkingLevel;131    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;132133    Client client = new Client();134135    CreateModelInteraction params =136        CreateModelInteraction.builder()137            .model(Model.of("gemini-3.8-flash"))138            .input(InteractionsInput.of("How does AI work?"))139            .generationConfig(GenerationConfig.builder().thinkingLevel(ThinkingLevel.LOW).build())140            .build();141142    Interaction interaction =143        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();144145    System.out.println(interaction.outputText().orElse(""));146147### REST148149    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \150      -H "x-goog-api-key: $GEMINI_API_KEY" \151      -H 'Content-Type: application/json' \152      -d '{153        "model": "gemini-3.8-flash",154        "input": "How does AI work?",155        "generation_config": {156          "thinking_level": "low"157        }158      }'159160## System instructions and other configurations161162You can guide the behavior of Gemini models with system instructions. Pass163a `system_instruction` parameter to configure the model's behavior.164165### Python166167    from google import genai168169    client = genai.Client()170171    interaction = client.interactions.create(172        model="gemini-3.8-flash",173        system_instruction="You are a cat. Your name is Neko.",174        input="Hello there"175    )176177    print(interaction.output_text)178179### JavaScript180181    import { GoogleGenAI } from "@google/genai";182183    const ai = new GoogleGenAI({});184185    async function main() {186      const interaction = await ai.interactions.create({187        model: "gemini-3.8-flash",188        input: "Hello there",189        system_instruction: "You are a cat. Your name is Neko.",190      });191      console.log(interaction.output_text);192    }193194    await main();195196### Java197198    import com.google.genai.Client;199    import com.google.genai.gaos.models.interactions.CreateModelInteraction;200    import com.google.genai.gaos.models.interactions.Interaction;201    import com.google.genai.gaos.models.interactions.InteractionsInput;202    import com.google.genai.gaos.models.interactions.Model;203    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;204205    Client client = new Client();206207    CreateModelInteraction params =208        CreateModelInteraction.builder()209            .model(Model.of("gemini-3.8-flash"))210            .systemInstruction("You are a cat. Your name is Neko.")211            .input(InteractionsInput.of("Hello there"))212            .build();213214    Interaction interaction =215        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();216217    System.out.println(interaction.outputText().orElse(""));218219### REST220221    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \222      -H "x-goog-api-key: $GEMINI_API_KEY" \223      -H 'Content-Type: application/json' \224      -d '{225        "model": "gemini-3.8-flash",226        "system_instruction": "You are a cat. Your name is Neko.",227        "input": "Hello there"228      }'229230You can also override default generation parameters, such as231temperature, using the `generation_config` parameter.232233### Python234235    from google import genai236237    client = genai.Client()238239    interaction = client.interactions.create(240        model="gemini-3.8-flash",241        input="Explain how AI works",242        generation_config={243            "temperature": 1.0244        }245    )246    print(interaction.output_text)247248### JavaScript249250    import { GoogleGenAI } from "@google/genai";251252    const ai = new GoogleGenAI({});253254    async function main() {255      const interaction = await ai.interactions.create({256        model: "gemini-3.8-flash",257        input: "Explain how AI works",258        generation_config: {259          temperature: 1.0,260        },261      });262      console.log(interaction.output_text);263    }264265    await main();266267### Java268269    import com.google.genai.Client;270    import com.google.genai.gaos.models.interactions.CreateModelInteraction;271    import com.google.genai.gaos.models.interactions.GenerationConfig;272    import com.google.genai.gaos.models.interactions.Interaction;273    import com.google.genai.gaos.models.interactions.InteractionsInput;274    import com.google.genai.gaos.models.interactions.Model;275    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;276277    Client client = new Client();278279    CreateModelInteraction params =280        CreateModelInteraction.builder()281            .model(Model.of("gemini-3.8-flash"))282            .input(InteractionsInput.of("Explain how AI works"))283            .generationConfig(GenerationConfig.builder().maxOutputTokens(500).build())284            .build();285286    Interaction interaction =287        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();288289    System.out.println(interaction.outputText().orElse(""));290291### REST292293    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \294      -H "x-goog-api-key: $GEMINI_API_KEY" \295      -H 'Content-Type: application/json' \296      -d '{297        "model": "gemini-3.8-flash",298        "input": "Explain how AI works",299        "generation_config": {300          "temperature": 1.0301        }302      }'303304Refer to the [Interactions API reference](https://ai.google.dev/api/interactions-api)305for a complete list of configurable parameters and their306descriptions.307308## Multimodal inputs309310The Gemini API supports multimodal inputs, allowing you to combine text with311media files. The following example demonstrates providing an image:312313### Python314315    from google import genai316317    client = genai.Client()318319    uploaded_file = client.files.upload(file="path/to/organ.jpg")320321    interaction = client.interactions.create(322        model="gemini-3.8-flash",323        input=[324            {"type": "text", "text": "Tell me about this instrument"},325            {326                "type": "image",327                "uri": uploaded_file.uri,328                "mime_type": uploaded_file.mime_type329            }330        ]331    )332    print(interaction.output_text)333334### JavaScript335336    import { GoogleGenAI } from "@google/genai";337338    const ai = new GoogleGenAI({});339340    async function main() {341      const uploadedFile = await ai.files.upload({342        file: "path/to/organ.jpg",343        config: { mimeType: "image/jpeg" }344      });345346      const interaction = await ai.interactions.create({347        model: "gemini-3.8-flash",348        input: [349          {type: "text", text: "Tell me about this instrument"},350          {351            type: "image",352            uri: uploadedFile.uri,353            mime_type: uploadedFile.mimeType354          }355        ],356      });357      console.log(interaction.output_text);358    }359360    await main();361362### Java363364    import com.google.genai.Client;365    import com.google.genai.gaos.models.interactions.CreateModelInteraction;366    import com.google.genai.gaos.models.interactions.ImageContent;367    import com.google.genai.gaos.models.interactions.ImageContentMimeType;368    import com.google.genai.gaos.models.interactions.Interaction;369    import com.google.genai.gaos.models.interactions.InteractionsInput;370    import com.google.genai.gaos.models.interactions.Model;371    import com.google.genai.gaos.models.interactions.TextContent;372    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;373    import com.google.genai.types.File;374    import com.google.genai.types.UploadFileConfig;375    import java.util.Arrays;376377    Client client = new Client();378379    File uploadedFile =380        client.files.upload(381            new java.io.File("path/to/organ.jpg"),382            UploadFileConfig.builder().mimeType("image/jpeg").build());383384    CreateModelInteraction params =385        CreateModelInteraction.builder()386            .model(Model.of("gemini-3.8-flash"))387            .input(388                InteractionsInput.ofContent(389                    Arrays.asList(390                        TextContent.builder().text("Tell me about this instrument").build(),391                        ImageContent.builder()392                            .uri(uploadedFile.uri().orElse(""))393                            .mimeType(394                                ImageContentMimeType.of(uploadedFile.mimeType().orElse("image/jpeg")))395                            .build())))396            .build();397398    Interaction interaction =399        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();400401    System.out.println(interaction.outputText().orElse(""));402403### REST404405    # First upload the file using the Files API, then use the URI:406    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \407      -H "x-goog-api-key: $GEMINI_API_KEY" \408      -H 'Content-Type: application/json' \409      -d '{410        "model": "gemini-3.8-flash",411        "input": [412          {"type": "text", "text": "Tell me about this instrument"},413          {414            "type": "image",415            "uri": "YOUR_FILE_URI",416            "mime_type": "image/jpeg"417          }418        ]419      }'420421For alternative methods of providing images and more advanced image processing,422see our [image understanding guide](https://ai.google.dev/gemini-api/docs/image-understanding).423The API also supports [document](https://ai.google.dev/gemini-api/docs/document-processing), [video](https://ai.google.dev/gemini-api/docs/video-understanding), and424[audio](https://ai.google.dev/gemini-api/docs/audio) inputs and understanding.425426## Streaming responses427428By default, the model returns a response only after the entire generation429process is complete.430431For more fluid interactions, use streaming to handle response chunks432as they're generated. For a comprehensive guide covering event types,433streaming with tools, thinking, agents, and image generation, see the434dedicated [Streaming interactions](https://ai.google.dev/gemini-api/docs/streaming)435guide.436437### Python438439    from google import genai440441    client = genai.Client()442443    stream = client.interactions.create(444        model="gemini-3.8-flash",445        input="Explain how AI works",446        stream=True447    )448    for event in stream:449        if event.event_type == "step.delta":450            if event.delta.type == "text":451                print(event.delta.text, end="")452453### JavaScript454455    import { GoogleGenAI } from "@google/genai";456457    const ai = new GoogleGenAI({});458459    async function main() {460      const stream = await ai.interactions.create({461        model: "gemini-3.8-flash",462        input: "Explain how AI works",463        stream: true,464      });465466      for await (const event of stream) {467        if (event.event_type === "step.delta") {468          if (event.delta.type === "text") {469            process.stdout.write(event.delta.text);470          }471        }472      }473    }474475    await main();476477### Java478479    import com.google.genai.Client;480    import com.google.genai.gaos.models.interactions.CreateModelInteraction;481    import com.google.genai.gaos.models.interactions.InteractionSSEEvent;482    import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent;483    import com.google.genai.gaos.models.interactions.InteractionsInput;484    import com.google.genai.gaos.models.interactions.Model;485    import com.google.genai.gaos.models.interactions.StepDelta;486    import com.google.genai.gaos.models.interactions.StepDeltaData;487    import com.google.genai.gaos.models.interactions.TextDelta;488    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;489    import com.google.genai.gaos.models.operations.CreateInteractionResponse;490    import com.google.genai.gaos.utils.EventStream;491492    Client client = new Client();493494    CreateModelInteraction params =495        CreateModelInteraction.builder()496            .model(Model.of("gemini-3.8-flash"))497            .input(InteractionsInput.of("Explain how AI works"))498            .stream(true)499            .build();500501    CreateInteractionResponse response =502        client.interactions.create(CreateInteractionRequestBody.of(params));503504    try (EventStream<InteractionSSEStreamEvent> stream = response.events()) {505      for (InteractionSSEStreamEvent streamEvent : stream) {506        InteractionSSEEvent event = streamEvent.data().orElse(null);507        if (event instanceof StepDelta stepDelta) {508          StepDeltaData delta = stepDelta.delta().orElse(null);509          if (delta instanceof TextDelta textDelta) {510            System.out.print(textDelta.text().orElse(""));511          }512        }513      }514    }515516### REST517518    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \519      -H "x-goog-api-key: $GEMINI_API_KEY" \520      -H 'Content-Type: application/json' \521      --no-buffer \522      -d '{523        "model": "gemini-3.8-flash",524        "input": "Explain how AI works",525        "stream": true526      }'527528## Multi-turn conversations529530The Interactions API supports multi-turn conversations by chaining interactions531together using `previous_interaction_id`. Each turn is a separate interaction,532and the API automatically manages conversation history.533534> [!NOTE]535> **Note:** Unlike other APIs where you might manage conversation history manually, the Interactions API handles conversation state server-side. You pass the `id` from the previous interaction to continue the conversation.536537### Python538539    from google import genai540541    client = genai.Client()542543    interaction1 = client.interactions.create(544        model="gemini-3.8-flash",545        input="I have 2 dogs in my house.",546    )547    print(interaction1.output_text)548549    interaction2 = client.interactions.create(550        model="gemini-3.8-flash",551        input="How many paws are in my house?",552        previous_interaction_id=interaction1.id,553    )554    print(interaction2.output_text)555556### JavaScript557558    import { GoogleGenAI } from "@google/genai";559560    const ai = new GoogleGenAI({});561562    async function main() {563      const interaction1 = await ai.interactions.create({564        model: "gemini-3.8-flash",565        input: "I have 2 dogs in my house.",566      });567      console.log("Response 1:", interaction1.output_text);568569      const interaction2 = await ai.interactions.create({570        model: "gemini-3.8-flash",571        input: "How many paws are in my house?",572        previous_interaction_id: interaction1.id,573      });574      console.log("Response 2:", interaction2.output_text);575    }576577    await main();578579### Java580581    import com.google.genai.Client;582    import com.google.genai.gaos.models.interactions.CreateModelInteraction;583    import com.google.genai.gaos.models.interactions.Interaction;584    import com.google.genai.gaos.models.interactions.InteractionsInput;585    import com.google.genai.gaos.models.interactions.Model;586    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;587588    Client client = new Client();589590    CreateModelInteraction params1 =591        CreateModelInteraction.builder()592            .model(Model.of("gemini-3.8-flash"))593            .input(InteractionsInput.of("I have 2 dogs in my house."))594            .build();595596    Interaction interaction1 =597        client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();598    System.out.println("Response 1: " + interaction1.outputText().orElse(""));599600    CreateModelInteraction params2 =601        CreateModelInteraction.builder()602            .model(Model.of("gemini-3.8-flash"))603            .input(InteractionsInput.of("How many paws are in my house?"))604            .previousInteractionId(interaction1.id().orElse(""))605            .build();606607    Interaction interaction2 =608        client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();609    System.out.println("Response 2: " + interaction2.outputText().orElse(""));610611### REST612613    RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \614      -H "x-goog-api-key: $GEMINI_API_KEY" \615      -H 'Content-Type: application/json' \616      -d '{617        "model": "gemini-3.8-flash",618        "input": "I have 2 dogs in my house."619      }')620621    INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')622623    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \624      -H "x-goog-api-key: $GEMINI_API_KEY" \625      -H 'Content-Type: application/json' \626      -d '{627        "model": "gemini-3.8-flash",628        "input": "I have two dogs in my house. How many paws are in my house?",629        "previous_interaction_id": "'$INTERACTION_ID'"630      }'631632Streaming can also be used for multi-turn conversations by combining633`previous_interaction_id` with the streaming methods.634635### Python636637    from google import genai638639    client = genai.Client()640641    interaction1 = client.interactions.create(642        model="gemini-3.8-flash",643        input="I have 2 dogs in my house.",644    )645    print(interaction1.output_text)646647    stream = client.interactions.create(648        model="gemini-3.8-flash",649        input="How many paws are in my house?",650        previous_interaction_id=interaction1.id,651        stream=True652    )653    for event in stream:654        if event.event_type == "step.delta":655            if event.delta.type == "text":656                print(event.delta.text, end="")657658### JavaScript659660    import { GoogleGenAI } from "@google/genai";661662    const ai = new GoogleGenAI({});663664    async function main() {665      const interaction1 = await ai.interactions.create({666        model: "gemini-3.8-flash",667        input: "I have 2 dogs in my house.",668      });669      console.log("Response 1:", interaction1.output_text);670671      const stream = await ai.interactions.create({672        model: "gemini-3.8-flash",673        input: "How many paws are in my house?",674        previous_interaction_id: interaction1.id,675        stream: true,676      });677      for await (const event of stream) {678        if (event.event_type === "step.delta") {679          if (event.delta.type === "text") {680            process.stdout.write(event.delta.text);681          }682        }683      }684    }685686    await main();687688### Java689690    import com.google.genai.Client;691    import com.google.genai.gaos.models.interactions.CreateModelInteraction;692    import com.google.genai.gaos.models.interactions.Interaction;693    import com.google.genai.gaos.models.interactions.InteractionSSEEvent;694    import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent;695    import com.google.genai.gaos.models.interactions.InteractionsInput;696    import com.google.genai.gaos.models.interactions.Model;697    import com.google.genai.gaos.models.interactions.StepDelta;698    import com.google.genai.gaos.models.interactions.StepDeltaData;699    import com.google.genai.gaos.models.interactions.TextDelta;700    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;701    import com.google.genai.gaos.models.operations.CreateInteractionResponse;702    import com.google.genai.gaos.utils.EventStream;703704    Client client = new Client();705706    CreateModelInteraction params1 =707        CreateModelInteraction.builder()708            .model(Model.of("gemini-3.8-flash"))709            .input(InteractionsInput.of("I have 2 dogs in my house."))710            .build();711712    Interaction interaction1 =713        client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();714    System.out.println("Response 1: " + interaction1.outputText().orElse(""));715716    CreateModelInteraction params2 =717        CreateModelInteraction.builder()718            .model(Model.of("gemini-3.8-flash"))719            .input(InteractionsInput.of("How many paws are in my house?"))720            .previousInteractionId(interaction1.id().orElse(""))721            .stream(true)722            .build();723724    CreateInteractionResponse response2 =725        client.interactions.create(CreateInteractionRequestBody.of(params2));726727    try (EventStream<InteractionSSEStreamEvent> stream = response2.events()) {728      for (InteractionSSEStreamEvent streamEvent : stream) {729        InteractionSSEEvent event = streamEvent.data().orElse(null);730        if (event instanceof StepDelta stepDelta) {731          StepDeltaData delta = stepDelta.delta().orElse(null);732          if (delta instanceof TextDelta textDelta) {733            System.out.print(textDelta.text().orElse(""));734          }735        }736      }737    }738739### REST740741    RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \742      -H "x-goog-api-key: $GEMINI_API_KEY" \743      -H 'Content-Type: application/json' \744      -d '{745        "model": "gemini-3.8-flash",746        "input": "I have 2 dogs in my house."747      }')748    INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')749750    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \751      -H "x-goog-api-key: $GEMINI_API_KEY" \752      -H 'Content-Type: application/json' \753      --no-buffer \754      -d '{755        "model": "gemini-3.8-flash",756        "input": "How many paws are in my house?",757        "previous_interaction_id": "'$INTERACTION_ID'",758        "stream": true759      }'760761## Stateless conversations762763By default, the Interactions API manages conversation state server-side when you use `previous_interaction_id`. However, you can also operate in stateless mode by managing the conversation history yourself on the client side.764765To use stateless mode:7661. Set `store=false` in your request to opt out of server-side storage.7672. Maintain the conversation history as an array of **steps** on the client side.7683. In subsequent requests, pass the accumulated steps in the `input` field, and append your new turn as a `user_input` step.769770> [!NOTE]771> **Note:** If the model uses "thinking" or tools, you **must** preserve and resend all model-generated steps (such as `thought` and `function_call` steps) exactly as received, as they contain signatures required to continue the conversation.772773### Python774775    from google import genai776777    client = genai.Client()778779    history = [780        {781            "type": "user_input",782            "content": [{"type": "text", "text": "I have 2 dogs in my house."}]783        }784    ]785786    interaction1 = client.interactions.create(787        model="gemini-3.8-flash",788        store=False,789        input=history790    )791    print("Response 1:", interaction1.steps[-1].content[0].text)792793    for step in interaction1.steps:794        history.append(step.model_dump())795796    history.append({797        "type": "user_input",798        "content": [{"type": "text", "text": "How many paws are in my house?"}]799    })800801    interaction2 = client.interactions.create(802        model="gemini-3.8-flash",803        store=False,804        input=history805    )806    print("Response 2:", interaction2.steps[-1].content[0].text)807808### JavaScript809810    import { GoogleGenAI } from "@google/genai";811812    const ai = new GoogleGenAI({});813814    async function main() {815      const history = [816        {817          type: "user_input",818          content: [{ type: "text", text: "I have 2 dogs in my house." }]819        }820      ];821822      const interaction1 = await ai.interactions.create({823        model: "gemini-3.8-flash",824        store: false,825        input: history826      });827      console.log("Response 1:", interaction1.steps.at(-1).content[0].text);828829      history.push(...interaction1.steps);830831      history.push({832        type: "user_input",833        content: [{ type: "text", text: "How many paws are in my house?" }]834      });835836      const interaction2 = await ai.interactions.create({837        model: "gemini-3.8-flash",838        store: false,839        input: history840      });841      console.log("Response 2:", interaction2.steps.at(-1).content[0].text);842    }843844    await main();845846### Java847848    import com.google.genai.Client;849    import com.google.genai.gaos.models.interactions.CreateModelInteraction;850    import com.google.genai.gaos.models.interactions.Interaction;851    import com.google.genai.gaos.models.interactions.InteractionsInput;852    import com.google.genai.gaos.models.interactions.Model;853    import com.google.genai.gaos.models.interactions.Step;854    import com.google.genai.gaos.models.interactions.TextContent;855    import com.google.genai.gaos.models.interactions.UserInputStep;856    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;857    import java.util.ArrayList;858    import java.util.Arrays;859    import java.util.List;860861    Client client = new Client();862863    List<Step> history = new ArrayList<>();864    history.add(865        UserInputStep.builder()866            .content(Arrays.asList(TextContent.builder().text("I have 2 dogs in my house.").build()))867            .build());868869    CreateModelInteraction params1 =870        CreateModelInteraction.builder()871            .model(Model.of("gemini-3.8-flash"))872            .store(false)873            .input(InteractionsInput.ofStep(history))874            .build();875876    Interaction interaction1 =877        client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();878    System.out.println("Response 1: " + interaction1.outputText().orElse(""));879880    interaction1.steps().ifPresent(history::addAll);881882    history.add(883        UserInputStep.builder()884            .content(Arrays.asList(TextContent.builder().text("How many paws are in my house?").build()))885            .build());886887    CreateModelInteraction params2 =888        CreateModelInteraction.builder()889            .model(Model.of("gemini-3.8-flash"))890            .store(false)891            .input(InteractionsInput.ofStep(history))892            .build();893894    Interaction interaction2 =895        client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();896    System.out.println("Response 2: " + interaction2.outputText().orElse(""));897898### REST899900    # Turn 1: Send request with store: false901    RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \902      -H "x-goog-api-key: $GEMINI_API_KEY" \903      -H 'Content-Type: application/json' \904      -d '{905        "model": "gemini-3.8-flash",906        "store": false,907        "input": [908          {909            "type": "user_input",910            "content": "I have 2 dogs in my house."911          }912        ]913      }')914915    # Extract the steps from response916    MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')917918    # Reconstruct the full history for Turn 2 by combining:919    # 1. First user input920    # 2. Model response steps921    # 3. Second user input922    HISTORY=$(jq -n \923      --argjson first_input '[{"type": "user_input", "content": "I have 2 dogs in my house."}]' \924      --argjson model_steps "$MODEL_STEPS" \925      --argjson second_input '[{"type": "user_input", "content": "How many paws are in my house?"}]' \926      "'"'"'$first_input + $model_steps + $second_input'"'"'")927928    # Turn 2: Send the full history929    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \930      -H "x-goog-api-key: $GEMINI_API_KEY" \931      -H 'Content-Type: application/json' \932      -d "{933        \"model\": \"gemini-3.8-flash\",934        \"store\": false,935        \"input\": $HISTORY936      }"937938## Prompting tips939940Consult our [prompt engineering guide](https://ai.google.dev/gemini/docs/prompting-strategies) for941suggestions on getting the most out of Gemini.942943## What's next944945- Try [Gemini in Google AI Studio](https://aistudio.google.com).946- Experiment with [structured outputs](https://ai.google.dev/gemini-api/docs/structured-output) for JSON-like responses.947- Explore Gemini's [image](https://ai.google.dev/gemini-api/docs/image-understanding), [video](https://ai.google.dev/gemini-api/docs/video-understanding), [audio](https://ai.google.dev/gemini-api/docs/audio) and [document](https://ai.google.dev/gemini-api/docs/document-processing) understanding capabilities.948- Learn about multimodal [file prompting strategies](https://ai.google.dev/gemini-api/docs/files#prompt-guide).
Files main
Menu

Theme