Skip to main content

ChatMessage

Struct ChatMessage 

Source
pub struct ChatMessage {
    pub role: String,
    pub content: Option<String>,
    pub content_blocks: Option<Vec<ContentBlock>>,
    pub tool_call_id: Option<String>,
    pub is_error: Option<bool>,
}
Expand description

A single message in a conversation.

Fields§

§role: String

One of “system”, “user”, “assistant”, or “tool”.

§content: Option<String>

Text content of the message.

§content_blocks: Option<Vec<ContentBlock>>

Structured content for assistant messages with tool calls. When present, takes precedence over content.

§tool_call_id: Option<String>

Required when role is “tool” — references the tool_use ID.

§is_error: Option<bool>

Whether a tool result is an error.

Implementations§

Source§

impl ChatMessage

Source

pub fn user(content: impl Into<String>) -> Self

Creates a user message.

Examples found in repository?
examples/chat.rs (lines 23-25)
12async fn main() {
13    let api_key = std::env::var("QAI_API_KEY").expect("QAI_API_KEY environment variable is required");
14
15    let client = Client::new(api_key);
16
17    // --- Non-streaming example ---
18    println!("=== Non-streaming Chat ===");
19
20    let resp = client
21        .chat(&ChatRequest {
22            model: "claude-sonnet-4-6".into(),
23            messages: vec![ChatMessage::user(
24                "What is quantum computing in one sentence?",
25            )],
26            ..Default::default()
27        })
28        .await
29        .expect("Chat failed");
30
31    println!("Model: {}", resp.model);
32    println!("Response: {}", resp.text());
33    if let Some(usage) = &resp.usage {
34        println!(
35            "Tokens: {} in / {} out (cost: {} ticks)",
36            usage.input_tokens, usage.output_tokens, usage.cost_ticks
37        );
38    }
39    println!("Request ID: {}\n", resp.request_id);
40
41    // --- Streaming example ---
42    println!("=== Streaming Chat ===");
43
44    let mut stream = client
45        .chat_stream(&ChatRequest {
46            model: "claude-sonnet-4-6".into(),
47            messages: vec![ChatMessage::user(
48                "Count from 1 to 5, one number per line.",
49            )],
50            ..Default::default()
51        })
52        .await
53        .expect("ChatStream failed");
54
55    while let Some(ev) = stream.next().await {
56        match ev.event_type.as_str() {
57            "content_delta" => {
58                if let Some(delta) = &ev.delta {
59                    print!("{}", delta.text);
60                }
61            }
62            "usage" => {
63                if let Some(usage) = &ev.usage {
64                    println!("\n[Cost: {} ticks]", usage.cost_ticks);
65                }
66            }
67            "error" => {
68                eprintln!("Stream error: {}", ev.error.as_deref().unwrap_or("unknown"));
69                std::process::exit(1);
70            }
71            "done" => {
72                println!("\n[Stream complete]");
73            }
74            _ => {}
75        }
76    }
77}
Source

pub fn assistant(content: impl Into<String>) -> Self

Creates an assistant message.

Source

pub fn system(content: impl Into<String>) -> Self

Creates a system message.

Source

pub fn tool_result( tool_call_id: impl Into<String>, content: impl Into<String>, ) -> Self

Creates a tool result message.

Source

pub fn tool_error( tool_call_id: impl Into<String>, content: impl Into<String>, ) -> Self

Creates a tool error result message.

Trait Implementations§

Source§

impl Clone for ChatMessage

Source§

fn clone(&self) -> ChatMessage

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 ChatMessage

Source§

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

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

impl Default for ChatMessage

Source§

fn default() -> ChatMessage

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ChatMessage

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 ChatMessage

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> 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> 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<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
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,