Skip to content
Streaming and multimodal - Antigravity SDKsdkAntigravity SDKAntigravity SDKStreaming and multimodal - Antigravity SDK Antigravity SDK Antigravity SDKAntigravity SDK

Every call to await agent.chat(prompt) sends your prompt and immediately returns a lazy, buffered types.ChatResponse stream. You can read the complete reply at once, stream text deltas, reasoning thoughts, and tool calls in real time, pass multimodal attachments (Image, Document, Audio, and Video), generate images, and cancel active turns cleanly.

ChatResponse maintains a shared internal chunk buffer. Every iterator on a ChatResponse creates an independent cursor over that buffer, so you can consume streams sequentially (for example, thoughts followed by text) or concurrently with asyncio.gather without losing events. An internal lock serializes upstream pulls, and any stream error is recorded and re-raised to each cursor that reaches the end of the buffer.

MemberReturn typeDescription
async for token in responseAsyncIterator[str]Streams incremental conversational text deltas (types.Text.text).
await response.text()strDrains the turn and returns the concatenated response text.
response.thoughtsAsyncIterator[str]Streams incremental model reasoning deltas (types.Thought.text).
response.tool_callsAsyncIterator[types.ToolCall]Streams deduplicated ToolCall objects (name, args, id, step_id, canonical_path, server_name) as tools are dispatched.
response.chunksAsyncIterator[StreamChunk | ToolCall | ToolResult]Streams all semantic events in arrival order, including types.Text, types.Thought, types.ToolCall, and types.ToolResult.
await response.resolve()list[StreamChunk | ToolCall | ToolResult]Drains the stream and returns every chunk yielded during the turn as a list.
await response.structured_output()Any | NoneDrains the stream and returns the parsed payload when response_schema is set (see Structured output).
await response.cancel()NoneAborts the active turn on the backend (safe no-op if already finished).
response.usage_metadataUsageMetadata | NoneAccumulated token usage across all model calls in the turn, snapshotted when the stream finishes.
response.stop_reasontypes.StopReasonTerminal stop reason for the turn (StopReason.UNSPECIFIED on normal completion; see Sessions and context).

Stream text, thoughts, and complete replies

Section titled “Stream text, thoughts, and complete replies”

Iterate directly over response for real-time text tokens, iterate response.thoughts for internal reasoning deltas, or await response.text() when you only need the final string:

from google.antigravity import Agent, LocalAgentConfig

async with Agent(LocalAgentConfig()) as agent:
    response = await agent.chat(
        "Solve this riddle and explain your reasoning: I speak without a mouth "
        "and hear without ears. What am I?"
    )

    print("Thoughts:")
    async for thought in response.thoughts:
        print(thought, end="", flush=True)
    print("\n")

    print("Answer:")
    async for token in response:
        print(token, end="", flush=True)
    print()

    # Or collect the full reply in one call (also works after streaming because
    # all chunks are retained in the response buffer):
    full_text = await response.text()

Iterating response.thoughts to completion first drains the full turn stream and then replays the buffered answer tokens immediately in async for token in response:. To display live thought and text deltas as they arrive, iterate response.chunks or consume both cursors together with asyncio.gather (shown below).

Inspect tool calls and the unified chunk stream

Section titled “Inspect tool calls and the unified chunk stream”

Use response.tool_calls to watch tool dispatches, or response.chunks when your UI needs a single ordered stream across all event types. types.Text and types.Thought inherit from types.StreamChunk (frozen Pydantic models with step_index: int and text: str; Thought also includes signature: bytes | None = None):

from google.antigravity import Agent, LocalAgentConfig, types

async with Agent(LocalAgentConfig()) as agent:
    response = await agent.chat("Summarize the top-level README.md file.")

    async for chunk in response.chunks:
        if isinstance(chunk, types.Thought):
            print(f"[thought step={chunk.step_index}] {chunk.text}", end="")
        elif isinstance(chunk, types.Text):
            print(chunk.text, end="", flush=True)
        elif isinstance(chunk, types.ToolCall):
            print(f"\n[tool call] {chunk.name}({chunk.args})")
        elif isinstance(chunk, types.ToolResult):
            print(f"\n[tool result] {chunk.name}: error={chunk.error}")
    print()

When you prefer to buffer every chunk for post-processing rather than handling deltas incrementally, call chunks = await response.resolve().

Because .thoughts, .tool_calls, and async for token in response maintain independent positions over the same buffer, you can process them in parallel with asyncio.gather so text tokens and tool calls render immediately without waiting for another consumer to finish first:

import asyncio
from google.antigravity import Agent, LocalAgentConfig, types


async def consume_thoughts(response: types.ChatResponse) -> str:
    parts = [delta async for delta in response.thoughts]
    return "".join(parts)


async def consume_tools(response: types.ChatResponse) -> list[str]:
    return [str(call.name) async for call in response.tool_calls]


async def consume_text(response: types.ChatResponse) -> str:
    tokens: list[str] = []
    async for token in response:
        print(token, end="", flush=True)
        tokens.append(token)
    return "".join(tokens)


async with Agent(LocalAgentConfig()) as agent:
    response = await agent.chat("Read pyproject.toml and list the dependencies.")
    thoughts, tools_used, answer = await asyncio.gather(
        consume_thoughts(response),
        consume_tools(response),
        consume_text(response),
    )
    print(f"\nCalled tools: {tools_used} ({len(thoughts)} thought chars)")

After draining a ChatResponse, inspect response.usage_metadata and response.stop_reason to record per-turn costs and verify whether the turn completed normally or hit an execution limit. Both properties are snapshotted to that ChatResponse, so subsequent turns on the same agent do not overwrite them:

from google.antigravity import Agent, LocalAgentConfig, types

async with Agent(LocalAgentConfig()) as agent:
    response = await agent.chat("Explain Python async generators in two sentences.")
    text = await response.text()

    if response.stop_reason != types.StopReason.UNSPECIFIED:
        print(f"Turn halted early: {response.stop_reason.value}")

    if usage := response.usage_metadata:
        print(
            f"Prompt: {usage.prompt_token_count} "
            f"(cached: {usage.cached_content_token_count}), "
            f"Candidates: {usage.candidates_token_count}, "
            f"Thoughts: {usage.thoughts_token_count}, "
            f"Total: {usage.total_token_count}"
        )

For cumulative session usage (agent.conversation.total_usage) and budget enforcement, see Sessions and context and Observability, evals, and errors.

agent.chat(prompt) accepts Content, which is either a single primitive or a sequence of primitives combining str, Image, Document, Audio, Video, and types.SlashCommand. All four media classes and both loader functions are exported directly from google.antigravity (and google.antigravity.types).

You can construct media primitives in four ways:

  • from_file(path, description=None): Expands ~, reads bytes from a str or pathlib.Path, infers the MIME type, and returns the matching Image, Document, Audio, or Video instance. Raises ValueError if the MIME type cannot be inferred or is unsupported.
  • from_bytes(data, mime_type, description=None): Resolves raw bytes and a MIME type string (normalized to lowercase) into the matching media class.
  • <Media>.from_file(path, description=None): Loads a local file (with ~ expansion) and enforces a specific media class such as Image.from_file(...) or Document.from_file(...), raising ValueError if the file’s MIME type belongs to a different category.
  • Direct constructor: Instantiate Image(data=..., mime_type=..., description=None) (or Document, Audio, Video) as a frozen Pydantic model with validated mime_type.
from google.antigravity import (
    Agent,
    Audio,
    Document,
    Image,
    LocalAgentConfig,
    Video,
    from_bytes,
    from_file,
)

async with Agent(LocalAgentConfig()) as agent:
    # Auto-detect media classes from file extensions (supports ~ expansion)
    spec = from_file("~/specs/architecture.pdf", description="System design PDF")
    diagram = Image.from_file("assets/topology.png", description="Network chart")

    # Build attachments from in-memory bytes
    metrics_csv = from_bytes(
        b"service,p99_ms\napi,42\nworker,118\n",
        mime_type="text/csv",
        description="Latency sample",
    )
    changelog = Document(
        data=b'{"version": "0.1.24", "breaking": false}',
        mime_type="application/json",
    )

    response = await agent.chat([
        "Compare the diagram and latency sample against the specification:",
        spec,
        diagram,
        metrics_csv,
        changelog,
    ])
    print(await response.text())

    # Send audio or video clips for transcription and analysis
    recording = Audio.from_file("recordings/standup.wav")
    walkthrough = Video.from_file("recordings/demo.mp4")
    summary = await agent.chat([
        "Summarize the action items from the standup and demo walkthrough:",
        recording,
        walkthrough,
    ])
    print(await summary.text())

The SDK validates every attachment’s MIME type against the supported set for its media class:

Media classSupported MIME types
Imageimage/bmp, image/jpeg, image/png, image/webp
Documentapplication/pdf, application/json, text/css, text/csv, text/html, text/javascript, text/plain, text/rtf, text/xml
Audioaudio/aac, audio/flac, audio/l16, audio/m4a, audio/mp3, audio/mp4, audio/mpeg, audio/ogg, audio/opus, audio/vnd.wave, audio/wav, audio/wave, audio/webm, audio/x-wav
Videovideo/3gpp, video/avi, video/mp4, video/mpeg, video/mpg, video/quicktime, video/webm, video/wmv, video/x-flv

Custom Python tools can return Image, Document, Audio, or Video instances either directly or inside a list, tuple, or dict (including nested combinations) alongside text; media nested inside Pydantic BaseModel or dataclass return values is not extracted automatically. The SDK delivers returned media to the model as supplemental content in the same turn, so the model can inspect tool-produced screenshots, charts, or audio without requiring a follow-up user prompt:

from google.antigravity import Agent, Image, LocalAgentConfig


def capture_chart(report_name: str) -> list[object]:
    """Loads a rendered PNG chart for visual inspection."""
    return [
        f"Loaded rendered chart for {report_name}.",
        Image.from_file(f"reports/{report_name}.png"),
    ]


config = LocalAgentConfig(tools=[capture_chart])

async with Agent(config) as agent:
    response = await agent.chat(
        "Call capture_chart for 'q4_latency' and describe any anomalies."
    )
    print(await response.text())

See Tools and skills for full custom tool typing, async execution, and ToolContext state patterns.

Generate images with BuiltinTools.GENERATE_IMAGE

Section titled “Generate images with BuiltinTools.GENERATE_IMAGE”

BuiltinTools.GENERATE_IMAGE ("generate_image") is included in BuiltinTools.default(), allowing the agent to synthesize images and save them to disk (under app_data_dir by default). When you restrict enabled_tools, include BuiltinTools.GENERATE_IMAGE explicitly.

By default, LocalAgentConfig routes image generation to gemini-3.1-flash-lite-image (DEFAULT_IMAGE_GENERATION_MODEL in google.antigravity.models). To customize the image model while keeping the default text model, pass a ModelTarget with types=[ModelType.IMAGE] and an explicit endpoint (required on every entry in models, because shorthand endpoints are not auto-populated onto models items):

from google.antigravity import (
    Agent,
    BuiltinTools,
    CapabilitiesConfig,
    GeminiAPIEndpoint,
    LocalAgentConfig,
    ModelTarget,
    ModelType,
)

config = LocalAgentConfig(
    models=[
        ModelTarget(
            name="gemini-3.1-flash-lite-image",
            types=[ModelType.IMAGE],
            # Or use VertexEndpoint(...) on Gemini Enterprise (see Authentication)
            endpoint=GeminiAPIEndpoint(),
        ),
    ],
    capabilities=CapabilitiesConfig(
        enabled_tools=[BuiltinTools.GENERATE_IMAGE],
    ),
)

async with Agent(config) as agent:
    response = await agent.chat(
        "Generate a 16:9 isometric diagram of an event-driven pipeline named "
        "'event_pipeline' and return the saved file path."
    )
    print(await response.text())

For multi-model routing, endpoints, and authentication options, see Models and configuration.

Call await response.cancel() (or await agent.conversation.cancel()) from another coroutine to abort an active turn on the backend. If the turn has already finished, response.cancel() is a safe no-op.

When a turn is aborted programmatically, active consumers of response raise types.AntigravityCancelledError, which subclasses Python’s built-in asyncio.CancelledError. Always catch types.AntigravityCancelledError before asyncio.CancelledError so you can distinguish an SDK turn abort (after which the agent session stays open for new turns) from native task.cancel() cancellation:

import asyncio
from google.antigravity import Agent, LocalAgentConfig, types


async def stream_turn(response: types.ChatResponse) -> None:
    async for thought in response.thoughts:
        print(thought, end="", flush=True)
    async for token in response:
        print(token, end="", flush=True)


async with Agent(LocalAgentConfig()) as agent:
    response = await agent.chat(
        "Write an exhaustive guide to distributed consensus protocols."
    )
    render_task = asyncio.create_task(stream_turn(response))

    # Let streaming start, then abort the turn programmatically
    await asyncio.sleep(2.0)
    if not render_task.done():
        await response.cancel()

    try:
        await render_task
    except types.AntigravityCancelledError as err:
        print(f"\nTurn cancelled by client: {err}")
    except asyncio.CancelledError:
        print("\nPython consumer task cancelled via task.cancel()")

    # The session remains usable for subsequent turns
    follow_up = await agent.chat("Give a one-sentence summary of Raft instead.")
    print(await follow_up.text())

Explore runnable scripts in the SDK repository on GitHub:

  • streaming.py: Real-time streaming of response.thoughts and response text tokens.
  • multimodal.py: Image, document, and audio inputs, image generation with BuiltinTools.GENERATE_IMAGE, and custom tools returning media.
  • multimodal_pipeline.py: Two-agent pipeline combining image generation with multimodal visual analysis.
  • cancellation.py: Programmatic response.cancel() with AntigravityCancelledError compared against native task.cancel().
  • Structured output: Constrain agent responses to a Pydantic model or JSON Schema.
  • Sessions and context: Work with Conversation step streams, session persistence, context compaction, and execution budgets.
  • Local models: Run multimodal vision and streaming locally with LiteRTAgentConfig.
  • Models and configuration: Configure ModelTarget, ModelType.IMAGE, and reasoning effort.