Struct MessagesAPI

Source
pub struct MessagesAPI {
    pub id: String,
    pub model: String,
    pub role: MessageRole,
    pub content: Vec<ResponseContentBlock>,
    pub stop_reason: Option<String>,
    pub stop_sequence: Option<String>,
    pub typ: String,
    pub usage: Usage,
}
Expand description

Represents a full message response from the Anthropic API.

This struct contains the complete response from a message request, including the model’s generated content and usage statistics.

Fields§

§id: String

Unique identifier for this message

§model: String

The model that generated the response

§role: MessageRole

The role of the message sender (always Assistant for responses)

§content: Vec<ResponseContentBlock>

The content blocks in the response (text or tool use)

§stop_reason: Option<String>

Reason why the model stopped generating, if applicable

§stop_sequence: Option<String>

The specific sequence that caused generation to stop, if applicable

§typ: String

The type of the response (always “message”)

§usage: Usage

Token usage statistics for the request and response

Implementations§

Source§

impl MessagesAPI

Source

pub async fn create(request: MessagesRequest) -> ApiResponseOrError<Self>

Creates a new message request and returns the response.

This method sends a request to the Messages API and returns the complete response.

§Example
let credentials = Credentials::from_env();
let request = MessagesRequest {
    model: "claude-3-7-sonnet-20250219".to_string(),
    messages: vec![Message {
        role: MessageRole::User,
        content: MessageContent::Text("Hello!".to_string()),
    }],
    max_tokens: 100,
    credentials: Some(credentials),
    metadata: None,
    stop_sequences: None,
    stream: None,
    system: None,
    temperature: None,
    tool_choice: None,
    tools: None,
    top_k: None,
    top_p: None,
};

let response = MessagesAPI::create(request).await?;
Source§

impl MessagesAPI

Source

pub fn builder( model: &str, messages: impl Into<Vec<Message>>, max_tokens: u64, ) -> MessagesBuilder

Creates a new builder with the required fields.

This is a convenience method to create a builder with the minimum required fields for a message request.

§Example
let credentials = Credentials::from_env();

let response = MessagesAPI::builder(
    "claude-3-7-sonnet-20250219",
    vec![Message {
        role: MessageRole::User,
        content: MessageContent::Text("Hello!".to_string()),
    }],
    100,
)
.credentials(credentials)
.create()
.await?;
Examples found in repository?
examples/tool_use.rs (line 62)
27async fn main() {
28    let credentials = Credentials::from_env();
29
30    // Define a calculator tool
31    let calculator_tool = Tool {
32        name: "calculator".to_string(),
33        description: "A calculator that can perform basic arithmetic operations".to_string(),
34        input_schema: json!({
35            "type": "object",
36            "properties": {
37                "operation": {
38                    "type": "string",
39                    "enum": ["add", "subtract", "multiply", "divide"]
40                },
41                "operands": {
42                    "type": "array",
43                    "items": {"type": "number"},
44                    "minItems": 2,
45                    "maxItems": 2
46                }
47            },
48            "required": ["operation", "operands"]
49        }),
50    };
51
52    let content =
53        "You are a helpful AI assistant. Please calculate 15 + 27 using the calculator tool.";
54    let mut messages = vec![Message {
55        role: MessageRole::User,
56        content: MessageContent::Text(content.to_string()),
57    }];
58
59    println!("Claude: {}", content);
60
61    // Create message request with tool
62    let response = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
63        .credentials(credentials.clone())
64        .tools(vec![calculator_tool.clone()])
65        .tool_choice(ToolChoice::Any)
66        .create()
67        .await
68        .unwrap();
69
70    // Print assistant's response and tool usage
71    for content in response.content {
72        match content {
73            ResponseContentBlock::Text { text } => {
74                println!("Assistant: {}", text.trim());
75                messages.push(Message {
76                    role: MessageRole::Assistant,
77                    content: MessageContent::Text(text),
78                });
79            }
80            ResponseContentBlock::ToolUse { name, input, .. } => {
81                println!("Claude decided to use the tool: {}: {}", name, input);
82            }
83        }
84    }
85}
More examples
Hide additional examples
examples/message_cli.rs (line 38)
26async fn main() {
27    // Load .env file containing ANTHROPIC_API_KEY
28    let credentials = Credentials::from_env();
29
30    let mut messages = vec![Message {
31        role: MessageRole::User,
32        content: MessageContent::Text(
33            "You are a helpful AI assistant. Please introduce yourself briefly.".to_string(),
34        ),
35    }];
36
37    // Create initial message request
38    let response = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
39        .credentials(credentials.clone())
40        .create()
41        .await
42        .unwrap();
43
44    // Print assistant's response
45    if let Some(content) = response.content.first() {
46        match content {
47            ResponseContentBlock::Text { text } => {
48                println!("Assistant: {}", text.trim());
49                messages.push(Message {
50                    role: MessageRole::Assistant,
51                    content: MessageContent::Text(text.clone()),
52                });
53            }
54            _ => {}
55        }
56    }
57
58    // Start conversation loop
59    loop {
60        print!("User: ");
61        stdout().flush().unwrap();
62
63        let mut user_input = String::new();
64        stdin().read_line(&mut user_input).unwrap();
65
66        // Add user message
67        messages.push(Message {
68            role: MessageRole::User,
69            content: MessageContent::Text(user_input),
70        });
71
72        // Send message request
73        let response = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
74            .credentials(credentials.clone())
75            .create()
76            .await
77            .unwrap();
78
79        // Print assistant's response
80        if let Some(content) = response.content.first() {
81            match content {
82                ResponseContentBlock::Text { text } => {
83                    println!("Assistant: {}", text.trim());
84                    messages.push(Message {
85                        role: MessageRole::Assistant,
86                        content: MessageContent::Text(text.clone()),
87                    });
88                }
89                _ => {}
90            }
91        }
92    }
93}
examples/streaming.rs (line 39)
28async fn main() {
29    let credentials = Credentials::from_env();
30
31    let mut messages = vec![Message {
32        role: MessageRole::User,
33        content: MessageContent::Text(
34            "You are a helpful AI assistant. Please introduce yourself briefly.".to_string(),
35        ),
36    }];
37
38    // Create initial message request with streaming
39    let mut stream = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
40        .credentials(credentials.clone())
41        .create_stream()
42        .await
43        .unwrap();
44
45    // Print assistant's streaming response
46    print!("Assistant: ");
47    stdout().flush().unwrap();
48    while let Some(event) = stream.recv().await {
49        match event {
50            StreamEvent::ContentBlockDelta { delta, .. } => {
51                if let ContentBlockDelta::Text { text } = delta {
52                    print!("{}", text);
53                    stdout().flush().unwrap();
54                }
55            }
56            StreamEvent::MessageStop => {
57                println!();
58            }
59            _ => {}
60        }
61    }
62
63    // Start conversation loop
64    loop {
65        print!("\nUser: ");
66        stdout().flush().unwrap();
67
68        let mut user_input = String::new();
69        stdin().read_line(&mut user_input).unwrap();
70
71        // Add user message
72        messages.push(Message {
73            role: MessageRole::User,
74            content: MessageContent::Text(user_input),
75        });
76
77        // Send message request with streaming
78        let mut stream = MessagesAPI::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
79            .credentials(credentials.clone())
80            .create_stream()
81            .await
82            .unwrap();
83
84        // Print assistant's streaming response and store the text
85        print!("\nAssistant: ");
86        stdout().flush().unwrap();
87        let mut full_response = String::new();
88        while let Some(event) = stream.recv().await {
89            match event {
90                StreamEvent::ContentBlockDelta { delta, .. } => {
91                    if let ContentBlockDelta::Text { text } = delta {
92                        print!("{}", text);
93                        stdout().flush().unwrap();
94                        full_response.push_str(&text);
95                    }
96                }
97                StreamEvent::MessageStop => {
98                    println!();
99                }
100                _ => {}
101            }
102        }
103
104        // Add assistant's complete response to messages
105        messages.push(Message {
106            role: MessageRole::Assistant,
107            content: MessageContent::Text(full_response),
108        });
109    }
110}

Trait Implementations§

Source§

impl Clone for MessagesAPI

Source§

fn clone(&self) -> MessagesAPI

Returns a copy 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 MessagesAPI

Source§

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

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

impl<'de> Deserialize<'de> for MessagesAPI

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 PartialEq for MessagesAPI

Source§

fn eq(&self, other: &MessagesAPI) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for MessagesAPI

Source§

impl StructuralPartialEq for MessagesAPI

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, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> 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,

Source§

impl<T> MaybeSendSync for T