Aller au contenu

Leçon 18 · The Gemini API

Conversations, Thinking and Streaming

Build multi-turn Gemini API chats with previous_interaction_id or your own history, control thinking levels, understand storage and stream replies.

One request is easy. A useful assistant needs follow-up questions, a sensible amount of reasoning and replies that appear while they are written. This lesson covers all three with the Interactions API. Code that calls Gemini is read-only. Facts are as of December 2026.

Two ways to keep a conversation

Server-side state. Pass the id of the previous interaction. The server reuses that conversation's inputs and outputs.

Python
# Read-only.
first = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Give me three names for a gardening club.",
)
second = client.interactions.create(
    model="gemini-4-hydrogen",
    previous_interaction_id=first.id,
    input="Make the second name shorter.",
)
print(second.output_text)

Only the history carries over. Google's documentation says that system_instruction, tools and generation_config apply to a single interaction, so send them again each turn.

Your own history (stateless). Set store=False and send the whole conversation each time, including the model's earlier steps unchanged. You control the data, and you manage more details yourself. Thought steps carry an encrypted signature, and in stateless mode you must send those blocks back unmodified.

Storage and retention

By default, interactions are stored. Google's documentation says the paid tier keeps them for 55 days by default (you can choose a shorter window in AI Studio) and the free tier keeps them for 1 day. You can delete a stored interaction by its ID. With store=False you cannot use previous_interaction_id for that interaction or run it in background mode. Choose based on your privacy needs, and tell your users what you keep.

Python Stand-in: server-side history by ID

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second reply shows "none" because the instruction was not sent again.

Long histories

Earlier turns are input to later ones, so long chats cost more and can reach limits. You can start fresh for a new topic, or begin a new conversation from a short summary of the old one. Remember that a summary can lose details.

Thinking levels

You control reasoning effort inside generation_config:

Python
# Read-only.
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Plan a three-week study schedule for four topics.",
    generation_config={
        "thinking_level": "medium",
        "thinking_summaries": "auto",
    },
)

Supported levels differ by model. Google's thinking page lists low, medium and high for Gemini 4 models, plus xhigh for Hydrogen and Neon. minimal is not supported on Gemini 4. Defaults differ too: that page shows medium for Carbon and high for Hydrogen and Neon. Thinking tokens are billed as output, so higher levels usually cost more.

Thought summaries are optional and can be empty, so your code must handle that. A summary is not a proof that the answer is right. Check the answer itself.

Streaming

Streaming shows text as it arrives, so a long reply feels faster.

Python
# Read-only.
stream = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Write a short story about a lighthouse.",
    stream=True,
)
for event in stream:
    if event.event_type == "step.delta" and event.delta.type == "text":
        print(event.delta.text, end="", flush=True)

Google's streaming guide lists events such as interaction.created, step.start, step.delta, step.stop, interaction.completed and error. Delta types include text, images, thought summaries and partial function arguments, which you must join before you use them. Skip event types you do not recognize, because new ones may be added.

Python Stand-in: assemble streamed events

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Google's streaming guide, function arguments arrive in arguments_delta events, with a string fragment in the arguments field. Join all the fragments before you parse them. The events above are simplified, so check the current reference for the other fields.

Errors in the middle of a stream

A stream can fail halfway. Decide whether to show the partial text, mark it as incomplete or retry. Never treat a partial reply as finished, and never run an action from half-received arguments.

Which state option should you choose?

Question Server-side history Your own history
Who keeps the transcript? The service, for its retention period Your application
How much do you send each turn? The new input and the previous ID The whole relevant history
Can you edit or trim old turns? Not through the ID alone Yes, with care for model steps
What must you protect? Interaction IDs and your account Your own database too

Whichever you choose, connect each conversation to the right user in your application. Never accept an interaction ID from a browser without checking that it belongs to the signed-in user, or one person might continue another person's conversation. Plan what happens when a stored interaction has expired or was deleted: your app should explain the problem and start a new conversation instead of crashing.

Test long conversations

A bot that works for two turns can drift after twenty. Write a test that corrects an earlier fact, changes topic and returns to the first topic. Check that the latest fact wins and that your rules are still sent each time. Record token usage per turn, so you can see how quickly a conversation becomes expensive.

Common mistake: assuming that the system instruction "sticks" after the first request. With previous_interaction_id, send it again every time.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. With previous_interaction_id, what must you send again if you need it?

    Only the conversation history carries over.
  2. 2. What is true when you set store to False?

    Stateless mode means that your application keeps and resends the history.
  3. 3. How should your code treat an unknown streaming event type?

    Google advises skipping unrecognized types because new ones may be added.

Summary

  • Continue chats with previous_interaction_id, or send your own history with store=False.
  • Settings apply per interaction, and stored data has retention periods.
  • Choose a thinking level for each task. Higher levels usually cost more.
  • Stream by handling events, joining deltas and tolerating unknown types.

Next: Structured Output and Multimodal Input

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.