Skip to main content

Conversation

Struct Conversation 

Source
pub struct Conversation { /* private fields */ }
Expand description

A stateful wrapper managing an active agentic session and its history.

Conversation consumes step events from an underlying Connection, updates the cumulative history, tracks token usage, and provides high-level APIs to chat, stream structured events, and wait for run completions.

Implementations§

Source§

impl Conversation

Source

pub fn new(conn: AnyConnection, max_history_size: Option<usize>) -> Self

Creates a new Conversation instance wrapping a Connection.

Optionally restricts the memory storage to max_history_size steps (default is 10,000 steps). If max_history_size is set to 0, state trimming is disabled.

Source

pub fn connection(&self) -> AnyConnection

Returns the underlying Connection.

Source

pub fn conversation_id(&self) -> &str

Returns the conversation ID assigned to the session.

Source

pub fn is_idle(&self) -> bool

Returns whether the connection is currently idle.

Source

pub async fn history(&self) -> Vec<Step>

Retrieves a copy of the current conversation history steps.

Source

pub async fn turn_count(&self) -> usize

Returns the total number of user-initiated turns executed in this session.

Source

pub async fn compaction_indices(&self) -> Vec<usize>

Returns the step indices where compaction (history compression) occurred.

Source

pub async fn last_response(&self) -> String

Scans the history backward and returns the text content of the last completed model response.

Source

pub async fn total_usage(&self) -> UsageMetadata

Returns the total token usage accumulated over all turns in the session.

Source

pub async fn last_turn_usage(&self) -> Option<UsageMetadata>

Returns the token usage metrics from the last completed turn.

Source

pub async fn clear_history(&self)

Resets the conversation state, clearing all steps, compaction boundaries, and usage statistics.

Source

pub async fn send(&self, prompt: &str) -> Result<(), Error>

Sends a text prompt to the connection and registers the turn start boundary.

§Errors

Returns an error if the underlying connection fails to transmit the prompt.

Source

pub fn receive_steps(&self) -> BoxStream<'static, Result<Step, Error>>

Subscribes to step updates from the connection, inserting them into history and enforcing history limits.

Source

pub fn receive_chunks(&self) -> BoxStream<'static, Result<StreamChunk, Error>>

Filters and maps the step event stream to yielding high-level StreamChunk deltas.

Source

pub async fn chat( &self, prompt: &str, ) -> Result<BoxStream<'static, Result<StreamChunk, Error>>, Error>

Starts a prompt turn and returns a stream of StreamChunk events.

§Errors

Returns an error if sending the prompt fails.

Examples found in repository?
examples/streaming.rs (line 39)
7async fn main() -> Result<(), anyhow::Error> {
8    // Initialize tracing subscriber
9    tracing_subscriber::fmt()
10        .with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
11        .init();
12
13    // Load environment variables from .env file if present
14    dotenvy::dotenv().ok();
15
16    let harness_path = std::env::var("ANTIGRAVITY_HARNESS_PATH").ok();
17    let api_key = std::env::var("GEMINI_API_KEY").ok();
18
19    let mut builder = Agent::builder();
20    if let Some(path) = harness_path {
21        builder = builder.binary_path(path);
22    }
23    if let Some(key) = api_key {
24        builder = builder.api_key(key);
25    }
26
27    let agent = builder
28        .default_model("gemini-3.5-flash")
29        .allow_all()
30        .build();
31
32    println!("Starting agent...");
33    let agent = agent.start().await?;
34
35    let prompt = "Solve this riddle: I speak without a mouth and hear without ears. I have no body, but I come alive with wind. What am I? Explain your reasoning.";
36    println!("\n  User: {}\n", prompt);
37
38    let conversation = agent.conversation();
39    let mut stream = conversation.chat(prompt).await?;
40
41    println!("  Agent (Streaming response):");
42    println!("  -------------------------------------------------------");
43
44    while let Some(chunk_res) = stream.next().await {
45        match chunk_res? {
46            StreamChunk::Thought { text, .. } => {
47                // Print thought chunks (e.g. in grey or wrapped in brackets if desired, or directly)
48                print!("{}", text);
49                std::io::Write::flush(&mut std::io::stdout())?;
50            }
51            StreamChunk::Text { text, .. } => {
52                // Print response text chunks
53                print!("{}", text);
54                std::io::Write::flush(&mut std::io::stdout())?;
55            }
56            StreamChunk::ToolCall(call) => {
57                println!(
58                    "\n[Tool Call Requested: {} with args: {}]",
59                    call.name, call.args
60                );
61            }
62        }
63    }
64    println!("\n  -------------------------------------------------------\n");
65
66    agent.stop().await?;
67    Ok(())
68}
Source

pub async fn chat_to_completion( &self, prompt: &str, ) -> Result<ChatResponse, Error>

Starts a prompt turn and resolves once the model completes its response.

§Errors

Returns an error if sending the prompt or receiving chunk responses fails.

Source

pub async fn disconnect(&self) -> Result<(), Error>

Gracefully closes the underlying connection.

§Errors

Returns an error if disconnecting the transport layer fails.

Trait Implementations§

Source§

impl Debug for Conversation

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,