Struct Message

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

Represents a single message in a conversation with an AI model.

Messages are the fundamental building blocks of conversations in chat-based AI interactions. Each message has a role (indicating who sent it) and content (the actual message text). Messages can also contain refusal information when the AI model declines to respond to certain requests.

§Roles

Common roles include:

  • “system”: System messages that set the behavior or context for the AI
  • “user”: Messages from the human user
  • “assistant”: Messages from the AI assistant
  • “function”: Messages related to function/tool calls (for advanced use cases)

§Fields

  • role - The role of the message sender
  • content - The text content of the message
  • refusal - Optional refusal message if the AI declined to respond

§Example

use openai_tools::common::Message;

// Create a system message to set context
let system_msg = Message::from_string(
    "system".to_string(),
    "You are a helpful assistant that explains complex topics simply.".to_string()
);

// Create a user message
let user_msg = Message::from_string(
    "user".to_string(),
    "What is quantum computing?".to_string()
);

// Create an assistant response
let assistant_msg = Message::from_string(
    "assistant".to_string(),
    "Quantum computing is a type of computation that uses quantum mechanics...".to_string()
);

// Messages are typically used in vectors for conversation history
let conversation = vec![system_msg, user_msg, assistant_msg];

Implementations§

Source§

impl Message

Source

pub fn from_string(role: String, message: String) -> Self

Creates a new Message with the specified role and content.

This is the primary constructor for creating message instances. The refusal field is automatically set to None and can be modified separately if needed.

§Arguments
  • role - The role of the message sender (e.g., “user”, “assistant”, “system”)
  • message - The text content of the message
§Returns

A new Message instance with the specified role and content.

§Example
// Create various types of messages
let system_message = Message::from_string(
    "system".to_string(),
    "You are a helpful AI assistant.".to_string()
);

let user_message = Message::from_string(
    "user".to_string(),
    "Hello! How are you today?".to_string()
);

let assistant_message = Message::from_string(
    "assistant".to_string(),
    "Hello! I'm doing well, thank you for asking.".to_string()
);

Creates a new Message from a role and text string.

This constructor creates a message with a single text content. It’s the most common way to create simple text-based messages for conversations with AI models.

§Arguments
  • role - The role of the message sender (e.g., “user”, “assistant”, “system”)
  • message - The text content of the message
§Returns

A new Message instance with the specified role and text content.

§Example
use openai_tools::common::Message;

let user_message = Message::from_string(
    "user".to_string(),
    "What is the weather like today?".to_string()
);

let system_message = Message::from_string(
    "system".to_string(),
    "You are a helpful weather assistant.".to_string()
);
Source

pub fn from_message_array(role: String, contents: Vec<MessageContent>) -> Self

Creates a new Message from a role and an array of message contents.

This constructor allows creating messages with multiple content types, such as messages that contain both text and images. This is useful for multimodal conversations where a single message may include various types of content.

§Arguments
  • role - The role of the message sender (e.g., “user”, “assistant”, “system”)
  • contents - A vector of MessageContent instances representing different content types
§Returns

A new Message instance with the specified role and multiple content elements.

§Example
use openai_tools::common::{Message, MessageContent};

let contents = vec![
    MessageContent::from_text("Please analyze this image:".to_string()),
    MessageContent::from_image_url("https://example.com/image.jpg".to_string()),
];

let multimodal_message = Message::from_message_array(
    "user".to_string(),
    contents
);
Source

pub fn get_input_token_count(&self) -> usize

Calculates the number of input tokens for this message.

This method uses the OpenAI tiktoken tokenizer (o200k_base) to count the number of tokens in the text content of the message. This is useful for estimating API costs and ensuring messages don’t exceed token limits.

§Returns

The number of tokens in the message’s text content. Returns 0 if:

  • The message has no content
  • The message content has no text (e.g., image-only messages)
§Note

This method only counts tokens for text content. Image content tokens are not included in the count as they are calculated differently by the OpenAI API.

§Example
use openai_tools::common::Message;

let message = Message::from_string(
    "user".to_string(),
    "Hello, how are you today?".to_string()
);

let token_count = message.get_input_token_count();
println!("Message contains {} tokens", token_count);

Trait Implementations§

Source§

impl Clone for Message

Source§

fn clone(&self) -> Message

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Message

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Message

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Message

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Custom serialization implementation for Message.

This method ensures that messages are serialized correctly by enforcing that either content or contents is present, but not both. This prevents invalid message structures from being serialized.

§Arguments
  • serializer - The serializer to use for output
§Returns

Result of the serialization operation

§Errors

Returns a serialization error if:

  • Both content and contents are present
  • Neither content nor contents are present

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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<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<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,