Overview
The Client struct manages interactions with the t3.chat API, including session management, message handling, and image processing.
Struct Definition
pub struct Client {
cookies: String,
convex_session_id: String,
thread_id: Option<String>,
client: reqwest::Client,
messages: Vec<Message>,
}
Constructor
new
Initializes a new Client instance.
pub fn new(cookies: String, convex_session_id: String) -> Self
The authentication cookies for t3.chat requests
The session ID for Convex authentication
A new Client instance configured with the provided credentials
Example:
use t3router::t3::client::Client;
let client = Client::new(
"wos-session=abc123...".to_string(),
"session_xyz789".to_string()
);
Session Management
init
Initializes the client by sending a GET request to the main page.
pub async fn init(&self) -> Result<bool, reqwest::Error>
return
Result<bool, reqwest::Error>
Returns Ok(true) if the initialization was successful, otherwise an error
Example:
let success = client.init().await?;
if success {
println!("Client initialized successfully");
}
refresh_session
Refreshes the session by calling the active sessions endpoint to update cookies.
pub async fn refresh_session(&mut self) -> Result<bool, reqwest::Error>
return
Result<bool, reqwest::Error>
Returns Ok(true) if the session refresh succeeded
Example:
let refreshed = client.refresh_session().await?;
if refreshed {
println!("Session refreshed successfully");
}
Message Sending
send
Sends the conversation messages to the chat API and returns the assistant’s response. If a new message is provided, it will be appended to the conversation before sending.
pub async fn send(
&mut self,
model: &str,
new_message: Option<Message>,
config: Option<Config>,
) -> Result<Message, reqwest::Error>
The model to use for the request (e.g., “gpt-4”, “claude-3”)
Optional new message to append before sending. If provided, it will be added to the conversation history
Optional configuration for the request. If not provided, default config will be used
return
Result<Message, reqwest::Error>
The assistant’s response message or an error
Example:
use t3router::t3::{message::{Message, Type}, config::Config};
let user_msg = Message::new(Type::User, "Hello!".to_string());
let response = client.send("gpt-4", Some(user_msg), None).await?;
println!("Assistant: {}", response.content);
send_with_image_download
Sends a message and downloads any generated images.
pub async fn send_with_image_download(
&mut self,
model: &str,
new_message: Option<Message>,
config: Option<Config>,
save_path: Option<&Path>,
) -> Result<Message, Box<dyn std::error::Error>>
The model to use for the request
Optional new message to append before sending
Optional configuration for the request
Optional file path to save generated images
return
Result<Message, Box<dyn std::error::Error>>
The assistant’s response with downloaded image data
Example:
use std::path::Path;
use t3router::t3::message::{Message, Type};
let user_msg = Message::new(Type::User, "Generate an image of a cat".to_string());
let save_path = Path::new("./cat_image.png");
let response = client.send_with_image_download(
"dall-e-3",
Some(user_msg),
None,
Some(save_path)
).await?;
if let Some(base64) = &response.base64_data {
println!("Image downloaded and saved");
}
Conversation Management
new_conversation
Starts a new conversation by resetting the thread ID and clearing messages.
pub fn new_conversation(&mut self)
Example:
client.new_conversation();
println!("Started a new conversation");
append_message
Appends a message to the conversation without sending it.
pub fn append_message(&mut self, message: Message)
The message to append to the conversation
Example:
use t3router::t3::message::{Message, Type};
let msg = Message::new(Type::User, "First message".to_string());
client.append_message(msg);
let msg2 = Message::new(Type::User, "Second message".to_string());
client.append_message(msg2);
get_messages
Gets all messages in the current conversation.
pub fn get_messages(&self) -> &Vec<Message>
Reference to the messages vector
Example:
let messages = client.get_messages();
for msg in messages {
println!("{:?}: {}", msg.role, msg.content);
}
clear_messages
Clears all messages in the current conversation.
pub fn clear_messages(&mut self)
Example:
client.clear_messages();
println!("All messages cleared");
get_thread_id
Gets the current thread ID.
pub fn get_thread_id(&self) -> Option<&String>
The thread ID if present, None otherwise
Example:
if let Some(thread_id) = client.get_thread_id() {
println!("Current thread: {}", thread_id);
} else {
println!("No active thread");
}
Image Processing
download_image
Downloads an image from a URL and optionally saves it to a file.
pub async fn download_image(
&self,
url: &str,
save_path: Option<&Path>,
) -> Result<String, Box<dyn std::error::Error>>
The URL of the image to download
Optional path to save the image file. If provided, the image will be saved to disk
return
Result<String, Box<dyn std::error::Error>>
Base64 encoded image data or an error
Example:
use std::path::Path;
let image_url = "https://example.com/image.png";
let save_path = Path::new("./downloaded_image.png");
let base64_data = client.download_image(image_url, Some(save_path)).await?;
println!("Image downloaded: {} bytes", base64_data.len());
parse_response
Parses the EventStream response and extracts content (text or image).
pub async fn parse_response(
&self,
response: &str,
) -> Result<(String, Option<String>, Option<String>), String>
The raw response text to parse from the EventStream
return
Result<(String, Option<String>, Option<String>), String>
A tuple containing:
- Parsed text content
- Optional image URL
- Optional inline base64 image data
Returns an error if no valid content is found
Example:
let raw_response = "data: {\"type\":\"text\",\"delta\":\"Hello\"}\n";
let (text, image_url, base64) = client.parse_response(raw_response).await?;
println!("Parsed text: {}", text);