Skip to main content

Conversations

Struct Conversations 

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

Client for interacting with the OpenAI Conversations API.

This struct provides methods to create, retrieve, update, delete conversations, and manage conversation items. Use Conversations::new() to create a new instance.

§Example

use openai_tools::conversations::request::Conversations;
use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;

    // Create a conversation with metadata
    let mut metadata = HashMap::new();
    metadata.insert("user_id".to_string(), "user123".to_string());

    let conv = conversations.create(Some(metadata), None).await?;
    println!("Created: {}", conv.id);

    // Retrieve the conversation
    let retrieved = conversations.retrieve(&conv.id).await?;
    println!("Retrieved: {:?}", retrieved.metadata);

    Ok(())
}

Implementations§

Source§

impl Conversations

Source

pub fn new() -> Result<Self>

Creates a new Conversations client for OpenAI API.

Initializes the client by loading the OpenAI API key from the environment variable OPENAI_API_KEY. Supports .env file loading via dotenvy.

§Returns
  • Ok(Conversations) - A new Conversations client ready for use
  • Err(OpenAIToolError) - If the API key is not found in the environment
§Example
use openai_tools::conversations::request::Conversations;

let conversations = Conversations::new().expect("API key should be set");
Source

pub fn with_auth(auth: AuthProvider) -> Self

Creates a new Conversations client with a custom authentication provider

Source

pub fn azure() -> Result<Self>

Creates a new Conversations client for Azure OpenAI API

Source

pub fn detect_provider() -> Result<Self>

Creates a new Conversations client by auto-detecting the provider

Source

pub fn with_url<S: Into<String>>(base_url: S, api_key: S) -> Self

Creates a new Conversations client with URL-based provider detection

Source

pub fn from_url<S: Into<String>>(url: S) -> Result<Self>

Creates a new Conversations client from URL using environment variables

Source

pub fn auth(&self) -> &AuthProvider

Returns the authentication provider

Source

pub fn timeout(&mut self, timeout: Duration) -> &mut Self

Sets the request timeout duration.

§Arguments
  • timeout - The maximum time to wait for a response
§Returns

A mutable reference to self for method chaining

Source

pub async fn create( &self, metadata: Option<HashMap<String, String>>, items: Option<Vec<InputItem>>, ) -> Result<Conversation>

Creates a new conversation.

You can optionally provide metadata and initial items to include in the conversation.

§Arguments
  • metadata - Optional key-value pairs for storing additional information
  • items - Optional initial items to add to the conversation (up to 20 items)
§Returns
  • Ok(Conversation) - The created conversation object
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::conversations::request::Conversations;
use openai_tools::conversations::response::InputItem;
use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;

    // Create with metadata and initial message
    let mut metadata = HashMap::new();
    metadata.insert("topic".to_string(), "greeting".to_string());

    let items = vec![InputItem::user_message("Hello!")];

    let conv = conversations.create(Some(metadata), Some(items)).await?;
    println!("Created conversation: {}", conv.id);
    Ok(())
}
Source

pub async fn retrieve(&self, conversation_id: &str) -> Result<Conversation>

Retrieves a specific conversation.

§Arguments
  • conversation_id - The ID of the conversation to retrieve
§Returns
  • Ok(Conversation) - The conversation object
  • Err(OpenAIToolError) - If the conversation is not found or the request fails
§Example
use openai_tools::conversations::request::Conversations;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;
    let conv = conversations.retrieve("conv_abc123").await?;

    println!("Conversation: {}", conv.id);
    println!("Created at: {}", conv.created_at);
    Ok(())
}
Source

pub async fn update( &self, conversation_id: &str, metadata: HashMap<String, String>, ) -> Result<Conversation>

Updates a conversation’s metadata.

§Arguments
  • conversation_id - The ID of the conversation to update
  • metadata - The new metadata to set
§Returns
  • Ok(Conversation) - The updated conversation object
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::conversations::request::Conversations;
use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;

    let mut metadata = HashMap::new();
    metadata.insert("topic".to_string(), "updated-topic".to_string());

    let conv = conversations.update("conv_abc123", metadata).await?;
    println!("Updated: {:?}", conv.metadata);
    Ok(())
}
Source

pub async fn delete( &self, conversation_id: &str, ) -> Result<DeleteConversationResponse>

Deletes a conversation.

§Arguments
  • conversation_id - The ID of the conversation to delete
§Returns
  • Ok(DeleteConversationResponse) - Confirmation of deletion
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::conversations::request::Conversations;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;
    let result = conversations.delete("conv_abc123").await?;

    if result.deleted {
        println!("Conversation {} was deleted", result.id);
    }
    Ok(())
}
Source

pub async fn create_items( &self, conversation_id: &str, items: Vec<InputItem>, ) -> Result<ConversationItemListResponse>

Creates items in a conversation.

You can add up to 20 items at a time.

§Arguments
  • conversation_id - The ID of the conversation
  • items - The items to add to the conversation
§Returns
  • Ok(ConversationItemListResponse) - The created items
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::conversations::request::Conversations;
use openai_tools::conversations::response::InputItem;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;

    let items = vec![
        InputItem::user_message("What is the weather like?"),
        InputItem::assistant_message("I'd be happy to help with weather information!"),
    ];

    let result = conversations.create_items("conv_abc123", items).await?;
    println!("Added {} items", result.data.len());
    Ok(())
}
Source

pub async fn list_items( &self, conversation_id: &str, limit: Option<u32>, after: Option<&str>, order: Option<&str>, include: Option<Vec<ConversationInclude>>, ) -> Result<ConversationItemListResponse>

Lists items in a conversation.

§Arguments
  • conversation_id - The ID of the conversation
  • limit - Maximum number of items to return (1-100, default 20)
  • after - Cursor for pagination (item ID to start after)
  • order - Sort order (“asc” or “desc”, default “desc”)
  • include - Additional data to include in the response
§Returns
  • Ok(ConversationItemListResponse) - The list of items
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::conversations::request::{Conversations, ConversationInclude};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;

    // List items with pagination
    let items = conversations.list_items(
        "conv_abc123",
        Some(20),
        None,
        Some("desc"),
        None,
    ).await?;

    for item in &items.data {
        println!("Item: {} ({})", item.id, item.item_type);
    }
    Ok(())
}
Source

pub async fn list( &self, limit: Option<u32>, after: Option<&str>, ) -> Result<ConversationListResponse>

Lists all conversations (if available).

Note: This endpoint may not be available in all API versions.

§Arguments
  • limit - Maximum number of conversations to return (1-100, default 20)
  • after - Cursor for pagination (conversation ID to start after)
§Returns
  • Ok(ConversationListResponse) - The list of conversations
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::conversations::request::Conversations;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let conversations = Conversations::new()?;

    let response = conversations.list(Some(10), None).await?;
    for conv in &response.data {
        println!("Conversation: {} (created: {})", conv.id, conv.created_at);
    }
    Ok(())
}

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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