pub struct MessagesBuilder { /* private fields */ }Expand description
Builder for MessagesRequest.
Implementations§
Source§impl MessagesBuilder
impl MessagesBuilder
Sourcepub fn model<VALUE: Into<String>>(self, value: VALUE) -> Self
pub fn model<VALUE: Into<String>>(self, value: VALUE) -> Self
The model to use (e.g., “claude-3-7-sonnet-20250219”).
Sourcepub fn messages<VALUE: Into<Vec<Message>>>(self, value: VALUE) -> Self
pub fn messages<VALUE: Into<Vec<Message>>>(self, value: VALUE) -> Self
The conversation messages.
Sourcepub fn max_tokens<VALUE: Into<u64>>(self, value: VALUE) -> Self
pub fn max_tokens<VALUE: Into<u64>>(self, value: VALUE) -> Self
Maximum number of tokens to generate.
Sourcepub fn stop_sequences<VALUE: Into<Vec<String>>>(self, value: VALUE) -> Self
pub fn stop_sequences<VALUE: Into<Vec<String>>>(self, value: VALUE) -> Self
Sequences where generation should stop.
Sourcepub fn system<VALUE: Into<String>>(self, value: VALUE) -> Self
pub fn system<VALUE: Into<String>>(self, value: VALUE) -> Self
System prompt to guide the assistant’s behavior.
Sourcepub fn temperature<VALUE: Into<f64>>(self, value: VALUE) -> Self
pub fn temperature<VALUE: Into<f64>>(self, value: VALUE) -> Self
Sampling temperature (0.0 to 1.0).
pub fn thinking<VALUE: Into<Thinking>>(self, value: VALUE) -> Self
Sourcepub fn tool_choice<VALUE: Into<ToolChoice>>(self, value: VALUE) -> Self
pub fn tool_choice<VALUE: Into<ToolChoice>>(self, value: VALUE) -> Self
Tool choice specification.
Examples found in repository?
examples/tool_use.rs (line 65)
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 ResponseContentBlock::Thinking {
84 signature,
85 thinking,
86 } => {
87 println!("Claude {} is thinking: {}", signature, thinking);
88 }
89 ResponseContentBlock::RedactedThinking { data } => {
90 println!("Claude is thinking: {}", data);
91 }
92 }
93 }
94}Sourcepub fn tools<VALUE: Into<Vec<Tool>>>(self, value: VALUE) -> Self
pub fn tools<VALUE: Into<Vec<Tool>>>(self, value: VALUE) -> Self
Tools the assistant can use.
Examples found in repository?
examples/tool_use.rs (line 64)
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 ResponseContentBlock::Thinking {
84 signature,
85 thinking,
86 } => {
87 println!("Claude {} is thinking: {}", signature, thinking);
88 }
89 ResponseContentBlock::RedactedThinking { data } => {
90 println!("Claude is thinking: {}", data);
91 }
92 }
93 }
94}Sourcepub fn credentials<VALUE: Into<Credentials>>(self, value: VALUE) -> Self
pub fn credentials<VALUE: Into<Credentials>>(self, value: VALUE) -> Self
Credentials for authentication (not serialized).
Examples found in repository?
examples/tool_use.rs (line 63)
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 ResponseContentBlock::Thinking {
84 signature,
85 thinking,
86 } => {
87 println!("Claude {} is thinking: {}", signature, thinking);
88 }
89 ResponseContentBlock::RedactedThinking { data } => {
90 println!("Claude is thinking: {}", data);
91 }
92 }
93 }
94}More examples
examples/message_cli.rs (line 39)
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(), 2048)
39 .credentials(credentials.clone())
40 // Uncomment this to enable thinking
41 // .thinking(Thinking {
42 // thinking_type: ThinkingType::Enabled,
43 // budget_tokens: 1024,
44 // })
45 .create()
46 .await
47 .unwrap();
48
49 // Print assistant's response
50 if let Some(content) = response.content.first() {
51 match content {
52 ResponseContentBlock::Text { text } => {
53 println!("Assistant: {}", text.trim());
54 messages.push(Message {
55 role: MessageRole::Assistant,
56 content: MessageContent::Text(text.clone()),
57 });
58 }
59 _ => {}
60 }
61 }
62
63 // Start conversation loop
64 loop {
65 print!("User: ");
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
78 let response =
79 MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
80 .credentials(credentials.clone())
81 .create()
82 .await
83 .unwrap();
84
85 // Print assistant's response
86 if let Some(content) = response.content.first() {
87 match content {
88 ResponseContentBlock::Text { text } => {
89 println!("Assistant: {}", text.trim());
90 messages.push(Message {
91 role: MessageRole::Assistant,
92 content: MessageContent::Text(text.clone()),
93 });
94 }
95 _ => {}
96 }
97 }
98 }
99}examples/streaming.rs (line 41)
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}Sourcepub fn build(self) -> Result<MessagesRequest, MessagesBuilderError>
pub fn build(self) -> Result<MessagesRequest, MessagesBuilderError>
Source§impl MessagesBuilder
impl MessagesBuilder
Sourcepub fn builder(
model: &str,
messages: impl Into<Vec<Message>>,
max_tokens: u64,
) -> Self
pub fn builder( model: &str, messages: impl Into<Vec<Message>>, max_tokens: u64, ) -> Self
Examples found in repository?
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 = MessagesBuilder::builder("claude-3-7-sonnet-20250219", messages.clone(), 2048)
39 .credentials(credentials.clone())
40 // Uncomment this to enable thinking
41 // .thinking(Thinking {
42 // thinking_type: ThinkingType::Enabled,
43 // budget_tokens: 1024,
44 // })
45 .create()
46 .await
47 .unwrap();
48
49 // Print assistant's response
50 if let Some(content) = response.content.first() {
51 match content {
52 ResponseContentBlock::Text { text } => {
53 println!("Assistant: {}", text.trim());
54 messages.push(Message {
55 role: MessageRole::Assistant,
56 content: MessageContent::Text(text.clone()),
57 });
58 }
59 _ => {}
60 }
61 }
62
63 // Start conversation loop
64 loop {
65 print!("User: ");
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
78 let response =
79 MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
80 .credentials(credentials.clone())
81 .create()
82 .await
83 .unwrap();
84
85 // Print assistant's response
86 if let Some(content) = response.content.first() {
87 match content {
88 ResponseContentBlock::Text { text } => {
89 println!("Assistant: {}", text.trim());
90 messages.push(Message {
91 role: MessageRole::Assistant,
92 content: MessageContent::Text(text.clone()),
93 });
94 }
95 _ => {}
96 }
97 }
98 }
99}Sourcepub async fn create(self) -> ApiResponseOrError<MessagesResponse>
pub async fn create(self) -> ApiResponseOrError<MessagesResponse>
Creates a new message request and returns the response.
This is a convenience method that builds the request from the builder and sends it to the Messages API.
§Example
let credentials = Credentials::from_env();
let response =MessagesBuilder::builder("claude-3-7-sonnet-20250219",[], 1024)
.credentials(credentials.clone())
.create()
.await
.unwrap();Examples found in repository?
examples/tool_use.rs (line 66)
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 ResponseContentBlock::Thinking {
84 signature,
85 thinking,
86 } => {
87 println!("Claude {} is thinking: {}", signature, thinking);
88 }
89 ResponseContentBlock::RedactedThinking { data } => {
90 println!("Claude is thinking: {}", data);
91 }
92 }
93 }
94}More examples
examples/message_cli.rs (line 45)
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(), 2048)
39 .credentials(credentials.clone())
40 // Uncomment this to enable thinking
41 // .thinking(Thinking {
42 // thinking_type: ThinkingType::Enabled,
43 // budget_tokens: 1024,
44 // })
45 .create()
46 .await
47 .unwrap();
48
49 // Print assistant's response
50 if let Some(content) = response.content.first() {
51 match content {
52 ResponseContentBlock::Text { text } => {
53 println!("Assistant: {}", text.trim());
54 messages.push(Message {
55 role: MessageRole::Assistant,
56 content: MessageContent::Text(text.clone()),
57 });
58 }
59 _ => {}
60 }
61 }
62
63 // Start conversation loop
64 loop {
65 print!("User: ");
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
78 let response =
79 MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
80 .credentials(credentials.clone())
81 .create()
82 .await
83 .unwrap();
84
85 // Print assistant's response
86 if let Some(content) = response.content.first() {
87 match content {
88 ResponseContentBlock::Text { text } => {
89 println!("Assistant: {}", text.trim());
90 messages.push(Message {
91 role: MessageRole::Assistant,
92 content: MessageContent::Text(text.clone()),
93 });
94 }
95 _ => {}
96 }
97 }
98 }
99}Sourcepub async fn create_stream(
self,
) -> Result<Receiver<StreamEvent>, CannotCloneRequestError>
pub async fn create_stream( self, ) -> Result<Receiver<StreamEvent>, CannotCloneRequestError>
Creates a new streaming message request and returns a channel of events.
This is a convenience method that builds the request from the builder and sends it to the Messages API in streaming mode.
§Example
let credentials = Credentials::from_env();
let mut stream =MessagesBuilder::builder("claude-3-7-sonnet-20250219", [], 1024)
.credentials(credentials)
.create_stream()
.await?;
while let Some(event) = stream.recv().await {
// Process streaming events
println!("{:?}", event);
}Examples found in repository?
examples/streaming.rs (line 42)
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 MessagesBuilder
impl Clone for MessagesBuilder
Source§fn clone(&self) -> MessagesBuilder
fn clone(&self) -> MessagesBuilder
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl Debug for MessagesBuilder
impl Debug for MessagesBuilder
Source§impl Default for MessagesBuilder
impl Default for MessagesBuilder
Source§impl PartialEq for MessagesBuilder
impl PartialEq for MessagesBuilder
impl StructuralPartialEq for MessagesBuilder
Auto Trait Implementations§
impl Freeze for MessagesBuilder
impl RefUnwindSafe for MessagesBuilder
impl Send for MessagesBuilder
impl Sync for MessagesBuilder
impl Unpin for MessagesBuilder
impl UnwindSafe for MessagesBuilder
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
Mutably borrows from an owned value. Read more