Struct Message

Source
pub struct Message {
    pub role: Role,
    pub content: Option<Content>,
    pub content_list: Option<Vec<Content>>,
    pub tool_calls: Option<Vec<ToolCall>>,
    pub refusal: Option<String>,
    pub annotations: Option<Vec<String>>,
}
Expand description

Represents a message in an OpenAI conversation.

Messages are the core communication unit between users and OpenAI models. They can contain various types of content including text, images, tool calls, and metadata like refusals and annotations.

§Content Types

A message can contain either:

  • Single content (content field) - for simple text messages
  • Multiple content items (content_list field) - for multi-modal messages

§Fields

  • role - The role of the message sender (User, Assistant, System, etc.)
  • content - Optional single content item
  • content_list - Optional list of content items for multi-modal messages
  • tool_calls - Optional list of tool calls made by the assistant
  • refusal - Optional refusal message if the model declined to respond
  • annotations - Optional list of annotations or metadata

§Examples

use openai_tools::common::message::{Message, Content};
use openai_tools::common::role::Role;

// Simple text message
let message = Message::from_string(Role::User, "Hello!");

// Multi-modal message with text and image
let contents = vec![
    Content::from_text("What's in this image?"),
    Content::from_image_url("https://example.com/image.png"),
];
let message = Message::from_message_array(Role::User, contents);

Fields§

§role: Role

The role of the message sender

§content: Option<Content>

Optional single content item

§content_list: Option<Vec<Content>>

Optional list of content items for multi-modal messages

§tool_calls: Option<Vec<ToolCall>>

Optional list of tool calls made by the assistant

§refusal: Option<String>

Optional refusal message if the model declined to respond

§annotations: Option<Vec<String>>

Optional list of annotations or metadata

Implementations§

Source§

impl Message

Source

pub fn from_string<T: AsRef<str>>(role: Role, message: T) -> Self

Creates a new Message with a single text content.

This is a convenience method for creating simple text messages.

§Arguments
  • role - The role of the message sender
  • message - The text content of the message
§Returns

A new Message instance with the specified role and text content

§Examples
use openai_tools::common::message::Message;
use openai_tools::common::role::Role;

let message = Message::from_string(Role::User, "Hello, how are you?");
Source

pub fn from_message_array(role: Role, contents: Vec<Content>) -> Self

Creates a new Message with multiple content items.

This method is used for multi-modal messages that contain multiple types of content such as text and images.

§Arguments
  • role - The role of the message sender
  • contents - Vector of content items to include in the message
§Returns

A new Message instance with the specified role and content list

§Examples
use openai_tools::common::message::{Message, Content};
use openai_tools::common::role::Role;

let contents = vec![
    Content::from_text("What's in this image?"),
    Content::from_image_url("https://example.com/image.png"),
];
let message = Message::from_message_array(Role::User, contents);
Source

pub fn get_input_token_count(&self) -> usize

Calculates the approximate token count for the message content.

This method uses the tiktoken library to estimate the number of tokens that would be consumed by this message when sent to OpenAI’s API. Only text content is counted; images are not included in the calculation.

§Returns

The estimated number of tokens for the text content in this message

§Examples
use openai_tools::common::message::Message;
use openai_tools::common::role::Role;

let message = Message::from_string(Role::User, "Hello, world!");
let token_count = message.get_input_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§

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

Custom deserialization implementation for Message.

This implementation handles the deserialization of messages from OpenAI API responses, converting string content to Content objects and handling optional fields.

Source§

fn deserialize<D>(deserializer: D) -> Result<Message, D::Error>
where D: Deserializer<'de>,

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

impl Serialize for Message

Custom serialization implementation for Message.

This implementation ensures that messages are serialized correctly for the OpenAI API, handling the mutually exclusive nature of content and content_list fields. Either content or content_list must be present, but not both.

Source§

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

Serialize this value into the given Serde serializer. Read more

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,