Switch an Assistant to Read-Only With Gemini API Mid-Conversation Instructions

Use Gemini API mid-conversation instructions to switch a Python draft editor to read-only, verify its lookup and write guard, then restore editing on approval.

Gemini API mid-conversation instructions shown as a rail switch on the D-104 conversation. The review route adds lookup_draft and the Python dispatcher blocks edits.Gemini API mid-conversation instructions shown as a rail switch on the D-104 conversation. The review route adds lookup_draft and the Python dispatcher blocks edits.
Illustrative D-104 switch. The conversation continues through a system_input update while the application rejects edits in review mode. Based on Google's Gemini API preview announcement.

Your draft assistant has just changed the title of D-104. A reviewer opens the same conversation and repeats the edit request. The assistant should explain that editing is paused, leave the title alone, and still be able to read it back. Gemini API mid-conversation instructions let your Python application make that transition in the existing conversation. A guard in the application keeps an edit from running if a stale call reaches the dispatcher.

This tutorial uses one in-memory draft, two custom functions, and one stateful interaction chain per run. You will inspect the stored review turn, check what Gemini proposed, and compare the title and write count before and after review. Then you will ask for the title without supplying the draft ID again and verify the new lookup against the local record. The optional path restores one approved edit. All fixture values and expected outputs are illustrative. The script is supplied for you to run in your test project.

Start with a draft you can check

  1. Use an existing authorized Gemini API test project with inference access to gemini-4-neon. Use a Python environment with the current google-genai SDK and your existing Gemini API credential configuration. Google’s overview lists 2.3.0 onward for Python Interactions generally. For this example, use a release that accepts the preview system_input step. Interactions API overview
  2. Start task:draft-edit-01 with D-104 titled Outline only and zero accepted writes. The first request asks for Ready for review. The review request repeats that instruction exactly. The optional restoration asks for Approved for copyedit. The script creates the initial record on each invocation.
  3. Keep server-side interaction storage enabled. The API stores interactions by default, and previous_interaction_id requires a stored parent. The draft dictionary and its write counter live in the Python process. Use the synthetic draft and handbook in the script so the stored interaction contains fixture data. Interactions API overview

Gemini carries the conversation forward, including the earlier edit request and the result the application returned. Python holds the current title and controls which handler may run. The first reply can mention the title because the program sends the write result back. Later the lookup must still read the title from the dictionary. In an editor with other writers, the title remembered by the model could already be stale by the time someone asks for it.

Google announced public preview for system_input on Gemini 4 through Interactions v1beta on December 3, 2026. The worked example uses the preview to add and remove custom function tools. Google documents that updates persist until a later system_input changes them and that removals are applied before additions within a single step. The Python application authorizes proposed calls before executing them. Release notes · Google’s preview announcement

Google article introducing mid-conversation instructions in the Gemini API.
Google's announcement page for mid-conversation instructions in the Gemini API. · Original source

Run the edit and review in one chain

  1. Save the Python block as draft_review.py and run python draft_review.py in the test environment. The script starts in edit mode, executes one validated title change, and sends its result back before opening review mode. The default run stops after the review and lookup checks.
  2. Read the baseline, dispatcher probe, review order, review calls, and lookup_draft result lines. The order and call checks use API steps. The title and counter come directly from the local fixture. The last line should be Review checks passed on a successful default run. Read the model replies separately for the expected meaning.
  3. To exercise restoration, run python draft_review.py --restore when the fixture operator authorizes the final edit. The flag stands in for the application’s approval. It starts a fresh fixture and restores editing within the chain created by that invocation. Compare its review and restoration records within that run.

The first edit is a positive control. It catches a disconnected dispatcher because the expected title and write count must both change. The repeated edit in review is deliberately idempotent at the value level. Comparing only the title would miss a second invocation that supplies the same title. The counter advances on every accepted edit, including one that would assign the current title again. Check both values before you interpret the assistant’s reply.

The request helper resends the same base tools array and system_instruction string on every create call, including function-result calls. The top-level instruction gives the editor its general behavior. A system_input carries the current mode and tool changes inside the conversation. The overview explains that top-level parameters apply to the current interaction. Google’s preview example shows how to keep the base array fixed and change the effective function set within the history. Interactions API overview · Google’s preview announcement

import argparse
import json

from google import genai

MODEL = 'gemini-4-neon'
DRAFT_ID = 'D-104'
INITIAL = 'Outline only'
REVIEW_TITLE = 'Ready for review'
RESTORED_TITLE = 'Approved for copyedit'
EDIT_REQUEST = 'Use edit_draft to set the title of D-104 to Ready for review.'
LOOKUP_REQUEST = 'Use lookup_draft to read the current title of the draft we have been discussing.'
RESTORE_REQUEST = 'Use edit_draft to set the title of D-104 to Approved for copyedit.'
SYSTEM = (
    'You are a draft assistant. For an allowed change or lookup, call the '
    'appropriate function exactly once, then summarize its result in one sentence.'
)
REVIEW_RULE = (
    'Review mode is active. Do not edit drafts or claim an edit ran. '
    'For a request to edit, explain that editing is paused. '
    'For a request to read the current draft, use lookup_draft.'
)
EDIT_RULE = (
    'The application has approved edit mode for D-104 again. Review mode '
    'has ended. Use edit_draft for the specific requested title change.'
)


def declare(name, description, fields):
    return {
        'type': 'function',
        'name': name,
        'description': description,
        'parameters': {
            'type': 'object',
            'properties': {field: {'type': 'string'} for field in fields},
            'required': list(fields),
        },
    }


EDIT = declare('edit_draft', 'Set the title on a stored draft.', ('draft_id', 'title'))
LOOKUP = declare('lookup_draft', 'Read the current title of a stored draft.', ('draft_id',))
BASE_TOOLS = [EDIT]
HANDBOOK = '\n'.join(
    f'Fixture note {i}: Editorial group {i % 7 + 1} files synthetic weekly '
    'review notes about structure, headings, copy quality and layout. '
    'A coordinator records suggestions for the owner to consider in a later session.'
    for i in range(1, 351)
)


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def text_step(kind, text):
    return {'type': kind, 'content': [{'type': 'text', 'text': text}]}


def mode_step(text, remove, add):
    return {
        **text_step('system_input', text),
        'removed_tools': [{'type': 'function', 'name': remove['name']}],
        'added_tools': [add],
    }


def calls(turn):
    return [step for step in (turn.steps or []) if step.type == 'function_call']


def usage(label, turn):
    stats = turn.usage
    cached = stats.total_cached_tokens if stats else None
    total = stats.total_input_tokens if stats else None
    print(label, {'total_cached_tokens': cached, 'total_input_tokens': total})


def audit_boundary(client, turn, update_text, user_text):
    steps = client.interactions.get(id=turn.id).steps or []
    kinds = [step.type for step in steps]
    print('stored steps', kinds)

    def has_text(step, text):
        return any(getattr(part, 'text', None) == text for part in step.content or [])

    matching = [
        i for i, step in enumerate(steps[:-1])
        if step.type == 'system_input'
        and has_text(step, update_text)
        and steps[i + 1].type == 'user_input'
        and has_text(steps[i + 1], user_text)
    ]
    require(len(matching) == 1, 'Expected one adjacent update/request pair')
    return kinds[matching[0]:matching[0] + 2]


def main(restore):
    client = genai.Client(http_options={'api_version': 'v1beta'})
    state = {'mode': 'edit', 'title': INITIAL, 'writes': 0}

    def request(label, input_value, previous=None):
        options = {'previous_interaction_id': previous.id} if previous else {}
        print('request', label, flush=True)
        return client.interactions.create(
            model=MODEL, tools=BASE_TOOLS, system_instruction=SYSTEM,
            input=input_value, **options,
        )

    def dispatch(name, args, authorized_title=None):
        if name == 'edit_draft':
            if state['mode'] != 'edit':
                raise PermissionError('edit_draft blocked in review mode')
            require(authorized_title is not None, 'No approved title for this action')
            require(args == {'draft_id': DRAFT_ID, 'title': authorized_title},
                    'Unexpected edit arguments')
            state['title'] = authorized_title
            state['writes'] += 1
        elif name == 'lookup_draft':
            require(state['mode'] == 'review', 'Lookup unavailable outside review')
            require(args == {'draft_id': DRAFT_ID}, 'Unexpected lookup arguments')
        else:
            raise ValueError(f'Unknown function: {name}')
        return {'draft_id': DRAFT_ID, 'title': state['title']}

    def complete(turn, expected_function, authorized_title=None):
        proposed = calls(turn)
        require(len(proposed) == 1 and proposed[0].name == expected_function,
                f'Expected one {expected_function}, received {[s.name for s in proposed]}')
        call = proposed[0]
        result = dispatch(call.name, call.arguments, authorized_title)
        print(f'{expected_function} result', result)
        final = request('function result', [{
            'type': 'function_result',
            'name': call.name,
            'call_id': call.id,
            'result': [{'type': 'text', 'text': json.dumps(result)}],
        }], turn)
        require(not calls(final), 'Extra function call after result')
        require(bool(final.output_text), 'Missing final model text after result')
        print('assistant', final.output_text)
        return final, result

    first = request('baseline edit', f'{HANDBOOK}\n\n{EDIT_REQUEST}')
    usage('baseline tokens', first)
    baseline, _ = complete(first, 'edit_draft', REVIEW_TITLE)
    before = (state['title'], state['writes'])
    require(before == (REVIEW_TITLE, 1), 'Baseline edit did not execute once')
    print('baseline', before)

    state['mode'] = 'review'
    try:
        dispatch('edit_draft', {'draft_id': DRAFT_ID, 'title': REVIEW_TITLE}, REVIEW_TITLE)
    except PermissionError as error:
        print('dispatcher probe', str(error))
    else:
        raise RuntimeError('Dispatcher accepted an edit in review mode')
    require((state['title'], state['writes']) == before, 'Dispatcher probe changed draft')

    review = request('switch to review', [
        mode_step(REVIEW_RULE, EDIT, LOOKUP),
        text_step('user_input', EDIT_REQUEST),
    ], baseline)
    usage('review tokens', review)
    print('review order', audit_boundary(client, review, REVIEW_RULE, EDIT_REQUEST))
    review_calls = [step.name for step in calls(review)]
    print('review calls', review_calls)
    require(not review_calls, 'Unexpected function call on the review edit request')
    require(bool(review.output_text), 'Missing review reply')
    print('review reply', review.output_text)
    require((state['title'], state['writes']) == before, 'Review changed draft')

    lookup = request('read D-104', LOOKUP_REQUEST, review)
    usage('lookup tokens', lookup)
    lookup_final, result = complete(lookup, 'lookup_draft')
    require(result == {'draft_id': DRAFT_ID, 'title': REVIEW_TITLE}, 'Wrong draft result')
    require((state['title'], state['writes']) == before, 'Lookup changed draft')
    print('Review checks passed')

    if restore:
        restored = request('authorized restore', [
            mode_step(EDIT_RULE, LOOKUP, EDIT),
            text_step('user_input', RESTORE_REQUEST),
        ], lookup_final)
        print('restore order', audit_boundary(client, restored, EDIT_RULE, RESTORE_REQUEST))
        state['mode'] = 'edit'
        try:
            complete(restored, 'edit_draft', RESTORED_TITLE)
            require((state['title'], state['writes']) == (RESTORED_TITLE, 2),
                    'Restoration did not execute exactly one edit')
        finally:
            state['mode'] = 'review'
        print('Restoration checks passed', state['title'], state['writes'])


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--restore', action='store_true', help='Authorize the fixture restore edit')
    main(parser.parse_args().restore)

The function declarations describe the parameters Gemini can propose. complete requires exactly one proposal with the expected name before it dispatches anything. For the baseline edit, the dispatcher then checks the mode, the approved title supplied by the application, and the full argument dictionary. The local function result carries the draft ID and title. The continuation wraps that result as text and uses the name and call_id from the proposal. It continues from the proposing interaction so Gemini can associate the result with that call. Google’s function-calling guide

Follow the parent IDs through the first exchange. The interaction that proposed edit_draft is the parent of the edit result. The interaction that received the result is the parent of the review request. That second link gives the review turn the completed baseline, including the actual title returned by the handler. If you already have a tool loop, check its result submission helper as well as its user-message helper. Both paths need the same top-level values in this example. Interactions API overview · Google’s function-calling guide

The dispatcher enters review before the application sends the review request. This order closes the write path even if the API rejects the preview payload. Keep the words in REVIEW_RULE under application control when adapting the example. The repeated user request goes into user_input, where it can ask for an edit without granting permission. In a real editor, the event that changes the mode can come from a review workflow that the application already trusts. Google’s preview announcement

Read the stored review turn and the draft

  1. Find the stored system_input that contains the review rule and verify that its immediate successor is the repeated user_input. The script retrieves the turn by ID using interactions.get and matches the exact text of both steps. It checks generated function calls on the create response. The stored turn includes input steps needed for the order check. Google’s preview announcement · Interactions API overview
  2. Check that review calls is [] and read review reply. A suitable reply explains that editing is paused and makes no claim of having performed the edit. The script checks that there is some text. You check its meaning. The local state check compares both title and write count with the saved baseline.
  3. Read dispatcher probe as a direct check of the local guard. The script supplies the same valid edit arguments and approved title used for the baseline. Python should raise PermissionError with edit_draft blocked in review mode. This deliberately exercises the dispatcher even when Gemini follows the instruction and proposes no edit.
  4. Inspect the separate lookup interaction. Its prompt refers to the draft under discussion and the dispatcher accepts exactly {'draft_id': 'D-104'}. The script checks the lookup’s local result and requires text on the function-result continuation without dispatching another call. Compare that final text with the returned title.

Sequence diagram showing a Python app sending system_input before user_input on the review turn, retrieving stored steps, and returning the later lookup result with the call_id.Sequence diagram showing a Python app sending system_input before user_input on the review turn, retrieving stored steps, and returning the later lookup result with the call_id.
Illustrative protocol for D-104. The stored update precedes the repeated request, and the lookup result is tied to its function call. Based on Google's preview announcement and function-calling guide.

Input Action Expected result
task:draft-edit-01, D-104 starts at Outline only Run python draft_review.py. The baseline requests Ready for review through edit_draft. The handler returns D-104 with title Ready for review and the baseline tuple is ('Ready for review', 1).
task:draft-edit-01, review mode with valid edit arguments for D-104 The script directly dispatches edit_draft with the title Ready for review before sending the review request. Python prints edit_draft blocked in review mode. The stored title and write count match the baseline snapshot.
task:draft-edit-01, D-104 at Ready for review with one accepted write Continue from the completed baseline exchange. Send system_input removing edit_draft and adding lookup_draft immediately before the repeated edit request. Stored order is system_input, user_input. review calls is [], the reply explains the pause, and the title stays Ready for review with one accepted write.
task:draft-edit-01, review turn contains the repeated edit request Ask lookup_draft for the title of the draft under discussion. Dispatch the proposed read and submit the result with its call_id. lookup_draft result contains D-104 and Ready for review. The user-facing reply reports the title, and the accepted write count is still one.
task:draft-edit-01, D-104 at Ready for review after lookup, operator authorizes an edit Run with --restore. After the lookup exchange, the script removes lookup_draft and adds edit_draft before requesting Approved for copyedit. Restoration checks passed Approved for copyedit 2 confirms one additional accepted edit in the fixture.

The table follows successive checkpoints in one run, with the final row available when you start the fixture with --restore. The lookup prompt omits D-104 so the proposed argument can demonstrate that the assistant used the earlier context. A matching title in plain text would show much less because the earlier tool result already contains the same value. Look for the fresh call, the actual local lookup, and the final reply that reports the returned value. The result continuation uses a new interaction ID and the originating function call ID for different jobs. Keep the former as the parent of the next user turn and use the latter to associate the result with the call that requested it. Google’s function-calling guide

If the observations disagree, start with the first failure. A compliant reply paired with a changed write count points to the dispatch path. An unexpected call with a stable counter means the fixture contained a proposal that should have been absent. An empty call list and a reply that claims a write are a user-facing failure even if the record is intact. For another example of validating a proposed call and returning a correlated result, see the Bedrock Converse function-calling walkthrough.

Interpret cache usage without weakening the write guard

  1. Save the baseline tokens, review tokens, and lookup tokens lines. The script builds 350 synthetic handbook entries at the front of the baseline input to create a long prefix. Compare the measured baseline input count with the documented 4,096-input-token floor for Gemini 4 Neon. The script sends the text once and uses the interaction chain to carry it forward. Google’s context caching guide
  2. Divide total_cached_tokens by total_input_tokens from the same response when both are present and the total is positive. An illustrative review line of 8,000 cached out of 12,000 total gives about 67%. An explicit zero cached out of 12,000 gives a zero hit rate for that response. The script leaves unavailable values as None, so a missing value stays distinguishable from an explicit zero.
  3. If the observed hit is zero, verify the model, base tool list and order, and top-level instruction on every create request. If your integration adds generation settings, check those as well. Confirm that the review uses the baseline result interaction as its parent. Run comparable calls close together. Google describes implicit caching as opportunistic, so matching configuration and sufficient input size can still produce a zero. Google’s context caching guide

Two stat tiles report the Gemini 4 Neon minimum of 4,096 input tokens and the Gemini 4 trailing window of 2,050 tokens for follow-up caching.Two stat tiles report the Gemini 4 Neon minimum of 4,096 input tokens and the Gemini 4 trailing window of 2,050 tokens for follow-up caching.
Google documents a 4,096-input-token minimum for Gemini 4 Neon implicit caching and a trailing 2,050-token window for Gemini 4 follow-ups. Source: Google AI Studio, Context caching, consulted December 3, 2026.

The minimum and the trailing window describe different parts of the same experiment. The minimum is an eligibility threshold. The trailing window affects how much of a prior request a follow-up can reuse. Google illustrates a 10,000-token previous prefix with a follow-up that adds 400 tokens. In that documented example, 7,950 prior tokens are reused and 2,450 input tokens are billed at the standard rate. The 2,450 includes the 2,050-token prior tail and the 400 new tokens. Use the actual counters for D-104, since the prior model output, thinking, tool calls, results, and user text can all affect the follow-up. Google’s context caching guide

Record the review interaction’s cache fraction alongside its review result so the measurements can be compared without mixing the two. A review run with zero cached tokens can still pass the dispatcher and lookup checks. A run with a high cache fraction can still fail if the assistant claims a write occurred or the lookup never arrives. For a similar approach to attributing usage to an individual call, see Trace an AgentCore session cost spike to one model call.

The handbook adds input cost and supplies no facts about D-104. For a smaller behavior-only rehearsal, replace HANDBOOK with an empty string and leave the edit, repeat, and lookup requests intact. Use the original handbook when investigating cache reuse. That distinction helps when debugging the fixture itself. A missing lookup reproduced with the short input gives you a case to investigate without repeatedly sending the long prefix. A cache investigation needs the long input and the measured usage from that run.

Recover from rejected requests and missing calls

Symptom Inspect Recovery
The baseline edit call is missing or has unexpected arguments Read the error after request baseline edit or inspect the generated call in its response. Verify the edit_draft definition and the requested D-104 title. Repeat from a fresh fixture and require one accepted write before using the review result.
The preview request is rejected Read the last request label and the error message. Check v1beta, gemini-4-neon, the SDK, the stored parent, and the update immediately before the user step. Keep the application in review while diagnosing the rejection.
The stored order check fails Read stored steps and check the ID passed to interactions.get. Retrieve the interaction that received the review update. Compare the exact text and order of its input steps with the submitted pair before sending the lookup.
No lookup_draft proposal arrives Read Expected one lookup_draft and check the stored transition. Check the added declaration, the parent link, and the wording. Run a fresh fixture after correcting the cause.
The lookup has the wrong draft ID Inspect the proposed arguments after Unexpected lookup arguments. In a diagnostic repeat, name D-104 explicitly. If that works, investigate context resolution and rerun the original implicit-reference case.
The local handler returned a result and the continuation failed Read the local result and identify whether it was a write or a lookup. Reconcile the local outcome before sending another result or retrying a write. Restarting this script creates a new local fixture.

A request can fail before generation. Google documents invalid_request for a malformed payload or invalid parameters, parameter_unknown for an unrecognized parameter, and permission_denied for resource or project restrictions. If it rejects the update, first check which request failed. A baseline rejection calls for checking the model and project before interpreting anything about review mode. A rejection at switch to review after a successful baseline gives you a narrower case to inspect. Google also notes that success on a read-only metadata endpoint can occur even when inference is unavailable to that project. Gemini API error codes · Gemini API troubleshooting

A normal response without a lookup is a different failure. Default tool selection allows text or a function call. This fixture asks for a call and checks that it actually appears, which exercises the transition under ordinary tool selection. If a remembered title comes back as text, follow the parent link from read D-104 to the successful review interaction. Check the name and schema in added_tools. A repeat with an explicit D-104 can help you distinguish a tool that the model can call from a failure to resolve which draft the user meant. Google’s function-calling guide

A result-submission failure deserves particular care after restoration. Suppose the handler returned Approved for copyedit but request function result failed. In a durable editor, first read the draft and its write record, then reconcile the accepted operation. An application record keyed to the originating call can give you the already computed result without executing the same write again. In the in-memory fixture, the printed handler result helps identify whether the action executed before the process exited. The next invocation starts at Outline only. For the reasons to keep this evidence available outside a transcript, see You Can’t Replay What You Can’t See.

Restore one edit after approval

  1. Start the optional path with --restore and let the review and lookup checks complete. The result continuation from the lookup becomes the parent of the restoration request. The flag authorizes the fixture’s next title, Approved for copyedit.
  2. Append a later system_input that ends review, removes lookup_draft, and adds the original edit_draft declaration. Put it immediately before the new user request. The base declarations and top-level instruction go out again. The script verifies the stored order while the local dispatcher is still in review. Google documents that newer system steps take precedence when instructions conflict and that tool changes persist until updated. Google’s preview announcement
  3. Check that the script accepts one edit_draft with exactly the approved arguments. The expected local title is Approved for copyedit and the count is two. The finally block closes the local edit gate again because the fixture authorizes one write. Before sending another user turn on that chain in review mode, send a fresh review update so the model’s effective tools match the local dispatcher again.

The restoration checks use a different title to make the new change visible. The earlier request for Ready for review remains in history. If Gemini proposes that earlier title, the exact argument check rejects it even though the tool name is now correct. In a durable editor, derive the equivalent scope from an authenticated approval event and check it when committing the mutation. If a worker can receive an edit proposal just before review starts and reach the database after it starts, the permission check and commit need to share the appropriate transaction or equivalent concurrency control. Review the pre-action gates guide and the fail-closed consent test matrix for related application-side checks.

If restoration fails before dispatch, the fixture stays at the review title. If it fails after dispatch, inspect the local result to determine whether the change ran before deciding on recovery. Exiting the process discards the local fixture. Stored interactions follow the project’s retention settings. For the default run, the final state to verify is Ready for review, one accepted write, and a fresh lookup result. For the optional run, verify that the write count advances to two only at the approved restoration. Interactions API overview

Sources

  1. Google, Introducing mid-conversation instructions in the Gemini API
  2. Google AI Studio, Gemini API release notes
  3. Google AI Studio, Interactions API overview
  4. Google AI Studio, Function calling
  5. Google AI Studio, Context caching
  6. Google AI Studio, API errors
  7. Google AI Studio, Troubleshooting guide

Many assistants.
One place to remember.

Bring your AI sessions, context, and usage together with Automater.

Meet Automater