SPB Git

Repository Public

text-generation.md 19.5 KB 657 lines markdown

1# Text generation23> [!NOTE]4> **Note** : This version of the page covers the new [Interactions API](https://ai.google.dev/gemini-api/docs/interactions/interactions-overview), which is currently in Beta.  5> For stable production deployments, we recommend you continue to use the `generateContent` API. You can use the toggle on this page to switch between the versions.67The Gemini API can generate text output from text, images, video, and audio8inputs.910Here's a basic example:1112### Python1314    from google import genai1516    client = genai.Client()1718    interaction = client.interactions.create(19        model="gemini-3.5-flash",20        input="How does AI work?"21    )22    print(interaction.output_text)2324### JavaScript2526    import { GoogleGenAI } from "@google/genai";2728    const ai = new GoogleGenAI({});2930    async function main() {31      const interaction = await ai.interactions.create({32        model: "gemini-3.5-flash",33        input: "How does AI work?",34      });35      console.log(interaction.output_text);36    }3738    await main();3940### REST4142    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \43      -H "x-goog-api-key: $GEMINI_API_KEY" \44      -H 'Content-Type: application/json' \45      -H "Api-Revision: 2026-05-20" \46      -d '{47        "model": "gemini-3.5-flash",48        "input": "How does AI work?"49      }'5051The Google GenAI SDKs provide convenience properties directly52on the returned `Interaction` object to access the model's response.5354The most common helper is **`interaction.output_text`** (String), which returns55the last text blocks in the model's response. If the response is split56across multiple consecutive `TextContent` blocks, it automatically joins them.57Note that `.output_text` does not include earlier text blocks separated by58non-text content (such as thoughts, images, audio, or tool calls). For complex59or interleaved multimodal responses, you must manually iterate over `steps`60instead. To learn more about other media convenience properties, see the61[Interactions overview](https://ai.google.dev/gemini-api/docs/interactions#convenience-properties).6263## Thinking with Gemini6465Gemini models often have ["thinking"](https://ai.google.dev/gemini-api/docs/interactions/thinking)66enabled by default which allows the model to reason before responding to a67request.6869Each model supports different thinking configurations which gives you control70over cost, latency, and intelligence. For more details, see the71[thinking guide](https://ai.google.dev/gemini-api/docs/interactions/thinking#set-budget).7273### Python7475    from google import genai7677    client = genai.Client()7879    interaction = client.interactions.create(80        model="gemini-3.5-flash",81        input="How does AI work?",82        generation_config={83            "thinking_level": "low"84        }85    )86    print(interaction.output_text)8788### JavaScript8990    import { GoogleGenAI } from "@google/genai";9192    const ai = new GoogleGenAI({});9394    async function main() {95      const interaction = await ai.interactions.create({96        model: "gemini-3.5-flash",97        input: "How does AI work?",98        generation_config: {99          thinking_level: "low",100        },101      });102      console.log(interaction.output_text);103    }104105    await main();106107### REST108109    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \110      -H "x-goog-api-key: $GEMINI_API_KEY" \111      -H 'Content-Type: application/json' \112      -H "Api-Revision: 2026-05-20" \113      -d '{114        "model": "gemini-3.5-flash",115        "input": "How does AI work?",116        "generation_config": {117          "thinking_level": "low"118        }119      }'120121## System instructions and other configurations122123You can guide the behavior of Gemini models with system instructions. Pass124a `system_instruction` parameter to configure the model's behavior.125126### Python127128    from google import genai129130    client = genai.Client()131132    interaction = client.interactions.create(133        model="gemini-3.5-flash",134        system_instruction="You are a cat. Your name is Neko.",135        input="Hello there"136    )137138    print(interaction.output_text)139140### JavaScript141142    import { GoogleGenAI } from "@google/genai";143144    const ai = new GoogleGenAI({});145146    async function main() {147      const interaction = await ai.interactions.create({148        model: "gemini-3.5-flash",149        input: "Hello there",150        system_instruction: "You are a cat. Your name is Neko.",151      });152      console.log(interaction.output_text);153    }154155    await main();156157### REST158159    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \160      -H "x-goog-api-key: $GEMINI_API_KEY" \161      -H 'Content-Type: application/json' \162      -H "Api-Revision: 2026-05-20" \163      -d '{164        "model": "gemini-3.5-flash",165        "system_instruction": "You are a cat. Your name is Neko.",166        "input": "Hello there"167      }'168169You can also override default generation parameters, such as170temperature, using the `generation_config` parameter.171172### Python173174    from google import genai175176    client = genai.Client()177178    interaction = client.interactions.create(179        model="gemini-3.5-flash",180        input="Explain how AI works",181        generation_config={182            "temperature": 1.0183        }184    )185    print(interaction.output_text)186187### JavaScript188189    import { GoogleGenAI } from "@google/genai";190191    const ai = new GoogleGenAI({});192193    async function main() {194      const interaction = await ai.interactions.create({195        model: "gemini-3.5-flash",196        input: "Explain how AI works",197        generation_config: {198          temperature: 1.0,199        },200      });201      console.log(interaction.output_text);202    }203204    await main();205206### REST207208    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \209      -H "x-goog-api-key: $GEMINI_API_KEY" \210      -H 'Content-Type: application/json' \211      -H "Api-Revision: 2026-05-20" \212      -d '{213        "model": "gemini-3.5-flash",214        "input": "Explain how AI works",215        "generation_config": {216          "temperature": 1.0217        }218      }'219220Refer to the [Interactions API reference](https://ai.google.dev/api/interactions-api)221for a complete list of configurable parameters and their222descriptions.223224## Multimodal inputs225226The Gemini API supports multimodal inputs, allowing you to combine text with227media files. The following example demonstrates providing an image:228229### Python230231    from google import genai232233    client = genai.Client()234235    uploaded_file = client.files.upload(file="path/to/organ.jpg")236237    interaction = client.interactions.create(238        model="gemini-3.5-flash",239        input=[240            {"type": "text", "text": "Tell me about this instrument"},241            {242                "type": "image",243                "uri": uploaded_file.uri,244                "mime_type": uploaded_file.mime_type245            }246        ]247    )248    print(interaction.output_text)249250### JavaScript251252    import { GoogleGenAI } from "@google/genai";253254    const ai = new GoogleGenAI({});255256    async function main() {257      const uploadedFile = await ai.files.upload({258        file: "path/to/organ.jpg",259        config: { mimeType: "image/jpeg" }260      });261262      const interaction = await ai.interactions.create({263        model: "gemini-3.5-flash",264        input: [265          {type: "text", text: "Tell me about this instrument"},266          {267            type: "image",268            uri: uploadedFile.uri,269            mime_type: uploadedFile.mimeType270          }271        ],272      });273      console.log(interaction.output_text);274    }275276    await main();277278### REST279280    # First upload the file using the Files API, then use the URI:281    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \282      -H "x-goog-api-key: $GEMINI_API_KEY" \283      -H 'Content-Type: application/json' \284      -H "Api-Revision: 2026-05-20" \285      -d '{286        "model": "gemini-3.5-flash",287        "input": [288          {"type": "text", "text": "Tell me about this instrument"},289          {290            "type": "image",291            "uri": "YOUR_FILE_URI",292            "mime_type": "image/jpeg"293          }294        ]295      }'296297For alternative methods of providing images and more advanced image processing,298see our [image understanding guide](https://ai.google.dev/gemini-api/docs/interactions/image-understanding).299The API also supports [document](https://ai.google.dev/gemini-api/docs/interactions/document-processing), [video](https://ai.google.dev/gemini-api/docs/interactions/video-understanding), and300[audio](https://ai.google.dev/gemini-api/docs/interactions/audio) inputs and understanding.301302## Streaming responses303304By default, the model returns a response only after the entire generation305process is complete.306307For more fluid interactions, use streaming to handle response chunks308as they're generated. For a comprehensive guide covering event types,309streaming with tools, thinking, agents, and image generation, see the310dedicated [Streaming interactions](https://ai.google.dev/gemini-api/docs/interactions/streaming)311guide.312313### Python314315    from google import genai316317    client = genai.Client()318319    stream = client.interactions.create(320        model="gemini-3.5-flash",321        input="Explain how AI works",322        stream=True323    )324    for event in stream:325        if event.event_type == "step.delta":326            if event.delta.type == "text":327                print(event.delta.text, end="")328329### JavaScript330331    import { GoogleGenAI } from "@google/genai";332333    const ai = new GoogleGenAI({});334335    async function main() {336      const stream = await ai.interactions.create({337        model: "gemini-3.5-flash",338        input: "Explain how AI works",339        stream: true,340      });341342      for await (const event of stream) {343        if (event.event_type === "step.delta") {344          if (event.delta.type === "text") {345            process.stdout.write(event.delta.text);346          }347        }348      }349    }350351    await main();352353### REST354355    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \356      -H "x-goog-api-key: $GEMINI_API_KEY" \357      -H 'Content-Type: application/json' \358      -H "Api-Revision: 2026-05-20" \359      --no-buffer \360      -d '{361        "model": "gemini-3.5-flash",362        "input": "Explain how AI works",363        "stream": true364      }'365366## Multi-turn conversations367368The Interactions API supports multi-turn conversations by chaining interactions369together using `previous_interaction_id`. Each turn is a separate interaction,370and the API automatically manages conversation history.371372> [!NOTE]373> **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.374375### Python376377    from google import genai378379    client = genai.Client()380381    interaction1 = client.interactions.create(382        model="gemini-3.5-flash",383        input="I have 2 dogs in my house.",384    )385    print(interaction1.output_text)386387    interaction2 = client.interactions.create(388        model="gemini-3.5-flash",389        input="How many paws are in my house?",390        previous_interaction_id=interaction1.id,391    )392    print(interaction2.output_text)393394### JavaScript395396    import { GoogleGenAI } from "@google/genai";397398    const ai = new GoogleGenAI({});399400    async function main() {401      const interaction1 = await ai.interactions.create({402        model: "gemini-3.5-flash",403        input: "I have 2 dogs in my house.",404      });405      console.log("Response 1:", interaction1.output_text);406407      const interaction2 = await ai.interactions.create({408        model: "gemini-3.5-flash",409        input: "How many paws are in my house?",410        previous_interaction_id: interaction1.id,411      });412      console.log("Response 2:", interaction2.output_text);413    }414415    await main();416417### REST418419    RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \420      -H "x-goog-api-key: $GEMINI_API_KEY" \421      -H 'Content-Type: application/json' \422      -H "Api-Revision: 2026-05-20" \423      -d '{424        "model": "gemini-3.5-flash",425        "input": "I have 2 dogs in my house."426      }')427428    INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')429430    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \431      -H "x-goog-api-key: $GEMINI_API_KEY" \432      -H 'Content-Type: application/json' \433      -H "Api-Revision: 2026-05-20" \434      -d '{435        "model": "gemini-3.5-flash",436        "input": "I have two dogs in my house. How many paws are in my house?",437        "previous_interaction_id": "'$INTERACTION_ID'"438      }'439440Streaming can also be used for multi-turn conversations by combining441`previous_interaction_id` with the streaming methods.442443### Python444445    from google import genai446447    client = genai.Client()448449    interaction1 = client.interactions.create(450        model="gemini-3.5-flash",451        input="I have 2 dogs in my house.",452    )453    print(interaction1.output_text)454455    stream = client.interactions.create(456        model="gemini-3.5-flash",457        input="How many paws are in my house?",458        previous_interaction_id=interaction1.id,459        stream=True460    )461    for event in stream:462        if event.event_type == "step.delta":463            if event.delta.type == "text":464                print(event.delta.text, end="")465466### JavaScript467468    import { GoogleGenAI } from "@google/genai";469470    const ai = new GoogleGenAI({});471472    async function main() {473      const interaction1 = await ai.interactions.create({474        model: "gemini-3.5-flash",475        input: "I have 2 dogs in my house.",476      });477      console.log("Response 1:", interaction1.output_text);478479      const stream = await ai.interactions.create({480        model: "gemini-3.5-flash",481        input: "How many paws are in my house?",482        previous_interaction_id: interaction1.id,483        stream: true,484      });485      for await (const event of stream) {486        if (event.event_type === "step.delta") {487          if (event.delta.type === "text") {488            process.stdout.write(event.delta.text);489          }490        }491      }492    }493494    await main();495496### REST497498    RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \499      -H "x-goog-api-key: $GEMINI_API_KEY" \500      -H 'Content-Type: application/json' \501      -H "Api-Revision: 2026-05-20" \502      -d '{503        "model": "gemini-3.5-flash",504        "input": "I have 2 dogs in my house."505      }')506    INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')507508    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \509      -H "x-goog-api-key: $GEMINI_API_KEY" \510      -H 'Content-Type: application/json' \511      -H "Api-Revision: 2026-05-20" \512      --no-buffer \513      -d '{514        "model": "gemini-3.5-flash",515        "input": "How many paws are in my house?",516        "previous_interaction_id": "'$INTERACTION_ID'",517        "stream": true518      }'519520## Stateless conversations521522By 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.523524To use stateless mode:5251. Set `store=false` in your request to opt out of server-side storage.5262. Maintain the conversation history as an array of **steps** on the client side.5273. In subsequent requests, pass the accumulated steps in the `input` field, and append your new turn as a `user_input` step.528529> [!NOTE]530> **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.531532### Python533534    from google import genai535536    client = genai.Client()537538    history = [539        {540            "type": "user_input",541            "content": [{"type": "text", "text": "I have 2 dogs in my house."}]542        }543    ]544545    interaction1 = client.interactions.create(546        model="gemini-3.5-flash",547        store=False,548        input=history549    )550    print("Response 1:", interaction1.steps[-1].content[0].text)551552    for step in interaction1.steps:553        history.append(step.model_dump())554555    history.append({556        "type": "user_input",557        "content": [{"type": "text", "text": "How many paws are in my house?"}]558    })559560    interaction2 = client.interactions.create(561        model="gemini-3.5-flash",562        store=False,563        input=history564    )565    print("Response 2:", interaction2.steps[-1].content[0].text)566567### JavaScript568569    import { GoogleGenAI } from "@google/genai";570571    const ai = new GoogleGenAI({});572573    async function main() {574      const history = [575        {576          type: "user_input",577          content: [{ type: "text", text: "I have 2 dogs in my house." }]578        }579      ];580581      const interaction1 = await ai.interactions.create({582        model: "gemini-3.5-flash",583        store: false,584        input: history585      });586      console.log("Response 1:", interaction1.steps.at(-1).content[0].text);587588      history.push(...interaction1.steps);589590      history.push({591        type: "user_input",592        content: [{ type: "text", text: "How many paws are in my house?" }]593      });594595      const interaction2 = await ai.interactions.create({596        model: "gemini-3.5-flash",597        store: false,598        input: history599      });600      console.log("Response 2:", interaction2.steps.at(-1).content[0].text);601    }602603    await main();604605### REST606607    # Turn 1: Send request with store: false608    RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \609      -H "x-goog-api-key: $GEMINI_API_KEY" \610      -H 'Content-Type: application/json' \611      -H "Api-Revision: 2026-05-20" \612      -d '{613        "model": "gemini-3.5-flash",614        "store": false,615        "input": [616          {617            "type": "user_input",618            "content": "I have 2 dogs in my house."619          }620        ]621      }')622623    # Extract the steps from response624    MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')625626    # Reconstruct the full history for Turn 2 by combining:627    # 1. First user input628    # 2. Model response steps629    # 3. Second user input630    HISTORY=$(jq -n \631      --argjson first_input '[{"type": "user_input", "content": "I have 2 dogs in my house."}]' \632      --argjson model_steps "$MODEL_STEPS" \633      --argjson second_input '[{"type": "user_input", "content": "How many paws are in my house?"}]' \634      "'"'"'$first_input + $model_steps + $second_input'"'"'")635636    # Turn 2: Send the full history637    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \638      -H "x-goog-api-key: $GEMINI_API_KEY" \639      -H 'Content-Type: application/json' \640      -H "Api-Revision: 2026-05-20" \641      -d "{642        \"model\": \"gemini-3.5-flash\",643        \"store\": false,644        \"input\": $HISTORY645      }"646647## Prompting tips648649Consult our [prompt engineering guide](https://ai.google.dev/gemini/docs/prompting-strategies) for650suggestions on getting the most out of Gemini.651652## What's next653654- Try [Gemini in Google AI Studio](https://aistudio.google.com).655- Experiment with [structured outputs](https://ai.google.dev/gemini-api/docs/interactions/structured-output) for JSON-like responses.656- Explore Gemini's [image](https://ai.google.dev/gemini-api/docs/interactions/image-understanding), [video](https://ai.google.dev/gemini-api/docs/interactions/video-understanding), [audio](https://ai.google.dev/gemini-api/docs/interactions/audio) and [document](https://ai.google.dev/gemini-api/docs/interactions/document-processing) understanding capabilities.657- Learn about multimodal [file prompting strategies](https://ai.google.dev/gemini-api/docs/interactions/files#prompt-guide).
Files main
Menu

Theme