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
impl Conversation
Sourcepub fn new(conn: AnyConnection, max_history_size: Option<usize>) -> Self
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.
Sourcepub fn connection(&self) -> AnyConnection
pub fn connection(&self) -> AnyConnection
Returns the underlying Connection.
Sourcepub fn conversation_id(&self) -> &str
pub fn conversation_id(&self) -> &str
Returns the conversation ID assigned to the session.
Sourcepub async fn history(&self) -> Vec<Step>
pub async fn history(&self) -> Vec<Step>
Retrieves a copy of the current conversation history steps.
Sourcepub async fn turn_count(&self) -> usize
pub async fn turn_count(&self) -> usize
Returns the total number of user-initiated turns executed in this session.
Sourcepub async fn compaction_indices(&self) -> Vec<usize>
pub async fn compaction_indices(&self) -> Vec<usize>
Returns the step indices where compaction (history compression) occurred.
Sourcepub async fn last_response(&self) -> String
pub async fn last_response(&self) -> String
Scans the history backward and returns the text content of the last completed model response.
Sourcepub async fn total_usage(&self) -> UsageMetadata
pub async fn total_usage(&self) -> UsageMetadata
Returns the total token usage accumulated over all turns in the session.
Sourcepub async fn last_turn_usage(&self) -> Option<UsageMetadata>
pub async fn last_turn_usage(&self) -> Option<UsageMetadata>
Returns the token usage metrics from the last completed turn.
Sourcepub async fn clear_history(&self)
pub async fn clear_history(&self)
Resets the conversation state, clearing all steps, compaction boundaries, and usage statistics.
Sourcepub async fn send(&self, prompt: &str) -> Result<(), Error>
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.
Sourcepub fn receive_steps(&self) -> BoxStream<'static, Result<Step, Error>>
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.
Sourcepub fn receive_chunks(&self) -> BoxStream<'static, Result<StreamChunk, Error>>
pub fn receive_chunks(&self) -> BoxStream<'static, Result<StreamChunk, Error>>
Filters and maps the step event stream to yielding high-level StreamChunk deltas.
Sourcepub async fn chat(
&self,
prompt: &str,
) -> Result<BoxStream<'static, Result<StreamChunk, Error>>, Error>
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?
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}Sourcepub async fn chat_to_completion(
&self,
prompt: &str,
) -> Result<ChatResponse, Error>
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.