pub struct MessagesResponse {
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: StringUnique identifier for this message
model: StringThe model that generated the response
role: MessageRoleThe 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: StringThe type of the response (always “message”)
usage: UsageToken usage statistics for the request and response
Implementations§
Source§impl MessagesResponse
impl MessagesResponse
Sourcepub async fn create(request: MessagesRequest) -> ApiResponseOrError<Self>
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,
thinking: None,
tool_choice: None,
tools: None,
top_k: None,
top_p: None,
};
let response = MessagesResponse::create(request).await?;Source§impl MessagesResponse
impl MessagesResponse
Sourcepub fn builder(
model: &str,
messages: impl Into<Vec<Message>>,
max_tokens: u64,
) -> MessagesBuilder
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 =MessagesBuilder::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?
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 = MessagesResponse::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
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 = MessagesBuilder::builder("claude-3-7-sonnet-20250219", messages.clone(), 2000)
39 .credentials(credentials.clone())
40 .thinking(Thinking {
41 thinking_type: ThinkingType::Enabled,
42 budget_tokens: 1000,
43 })
44 .create()
45 .await
46 .unwrap();
47
48 // Print assistant's response
49 if let Some(content) = response.content.first() {
50 match content {
51 ResponseContentBlock::Text { text } => {
52 println!("Assistant: {}", text.trim());
53 messages.push(Message {
54 role: MessageRole::Assistant,
55 content: MessageContent::Text(text.clone()),
56 });
57 }
58 _ => {}
59 }
60 }
61
62 // Start conversation loop
63 loop {
64 print!("User: ");
65 stdout().flush().unwrap();
66
67 let mut user_input = String::new();
68 stdin().read_line(&mut user_input).unwrap();
69
70 // Add user message
71 messages.push(Message {
72 role: MessageRole::User,
73 content: MessageContent::Text(user_input),
74 });
75
76 // Send message request
77 let response =
78 MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
79 .credentials(credentials.clone())
80 .create()
81 .await
82 .unwrap();
83
84 // Print assistant's response
85 if let Some(content) = response.content.first() {
86 match content {
87 ResponseContentBlock::Text { text } => {
88 println!("Assistant: {}", text.trim());
89 messages.push(Message {
90 role: MessageRole::Assistant,
91 content: MessageContent::Text(text.clone()),
92 });
93 }
94 _ => {}
95 }
96 }
97 }
98}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 =
40 MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
41 .credentials(credentials.clone())
42 .create_stream()
43 .await
44 .unwrap();
45
46 // Print assistant's streaming response
47 print!("Assistant: ");
48 stdout().flush().unwrap();
49 while let Some(event) = stream.recv().await {
50 match event {
51 StreamEvent::ContentBlockDelta { delta, .. } => {
52 if let ContentBlockDelta::Text { text } = delta {
53 print!("{}", text);
54 stdout().flush().unwrap();
55 }
56 }
57 StreamEvent::MessageStop => {
58 println!();
59 }
60 _ => {}
61 }
62 }
63
64 // Start conversation loop
65 loop {
66 print!("\nUser: ");
67 stdout().flush().unwrap();
68
69 let mut user_input = String::new();
70 stdin().read_line(&mut user_input).unwrap();
71
72 // Add user message
73 messages.push(Message {
74 role: MessageRole::User,
75 content: MessageContent::Text(user_input),
76 });
77
78 // Send message request with streaming
79 let mut stream =
80 MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
81 .credentials(credentials.clone())
82 .create_stream()
83 .await
84 .unwrap();
85
86 // Print assistant's streaming response and store the text
87 print!("\nAssistant: ");
88 stdout().flush().unwrap();
89 let mut full_response = String::new();
90 while let Some(event) = stream.recv().await {
91 match event {
92 StreamEvent::ContentBlockDelta { delta, .. } => {
93 if let ContentBlockDelta::Text { text } = delta {
94 print!("{}", text);
95 stdout().flush().unwrap();
96 full_response.push_str(&text);
97 }
98 }
99 StreamEvent::MessageStop => {
100 println!();
101 }
102 _ => {}
103 }
104 }
105
106 // Add assistant's complete response to messages
107 messages.push(Message {
108 role: MessageRole::Assistant,
109 content: MessageContent::Text(full_response),
110 });
111 }
112}Trait Implementations§
Source§impl Clone for MessagesResponse
impl Clone for MessagesResponse
Source§fn clone(&self) -> MessagesResponse
fn clone(&self) -> MessagesResponse
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more