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 sendercontent
- The text content of the messagerefusal
- 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
impl Message
Sourcepub fn from_string(role: String, message: String) -> Self
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()
);
Sourcepub fn from_message_array(role: String, contents: Vec<MessageContent>) -> Self
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 ofMessageContent
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
);
Sourcepub fn get_input_token_count(&self) -> usize
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<'de> Deserialize<'de> for Message
impl<'de> Deserialize<'de> for Message
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl Serialize for Message
impl Serialize for Message
Source§fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where
S: Serializer,
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
andcontents
are present - Neither
content
norcontents
are present
Auto Trait Implementations§
impl Freeze for Message
impl RefUnwindSafe for Message
impl Send for Message
impl Sync for Message
impl Unpin for Message
impl UnwindSafe for Message
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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