Skip to main content

MessagesRequest

Struct MessagesRequest 

Source
pub struct MessagesRequest {
Show 17 fields pub model: String, pub max_tokens: u32, pub messages: Vec<Message>, pub system: Option<SystemPrompt>, pub tools: Option<Vec<ToolDefinition>>, pub tool_choice: Option<ToolChoice>, pub temperature: Option<f32>, pub top_p: Option<f32>, pub top_k: Option<u32>, pub stop_sequences: Option<Vec<String>>, pub stream: Option<bool>, pub output_config: Option<OutputConfig>, pub thinking: Option<ThinkingConfig>, pub metadata: Option<Metadata>, pub service_tier: Option<ServiceTier>, pub inference_geo: Option<String>, pub container: Option<String>,
}
Expand description

Request to create a message

Fields§

§model: String

Model identifier (e.g., “claude-3-5-sonnet-20241022”)

§max_tokens: u32

Maximum tokens to generate

§messages: Vec<Message>

Conversation messages

§system: Option<SystemPrompt>

System prompt

§tools: Option<Vec<ToolDefinition>>

Available tools (custom client tools and/or server tools)

§tool_choice: Option<ToolChoice>

Tool choice configuration

Controls how Claude uses tools:

  • Auto (default): Claude decides whether to use tools
  • Any: Claude must use one of the provided tools
  • Tool { name }: Force Claude to use a specific tool
  • None: Prevent Claude from using any tools
§temperature: Option<f32>

Sampling temperature (0.0 to 1.0)

§top_p: Option<f32>

Top-p sampling

§top_k: Option<u32>

Top-k sampling

§stop_sequences: Option<Vec<String>>

Stop sequences

§stream: Option<bool>

Whether to stream the response

§output_config: Option<OutputConfig>

Output configuration (beta)

Controls output behavior like effort level. Requires beta header for effort: anthropic-beta: effort-2025-11-24

§thinking: Option<ThinkingConfig>

Extended thinking configuration

Enables Claude’s step-by-step reasoning process. Supported models: Sonnet 4.5, Haiku 4.5, Opus 4.5, and more.

§metadata: Option<Metadata>

Request metadata for abuse detection

§service_tier: Option<ServiceTier>

Service tier for request routing

§inference_geo: Option<String>

Geographic inference routing

§container: Option<String>

Container ID for persistent code execution

Implementations§

Source§

impl MessagesRequest

Source

pub fn new( model: impl Into<String>, max_tokens: u32, messages: Vec<Message>, ) -> Self

Create a new message request with required fields

§Example
use claude_sdk::{MessagesRequest, Message};

let request = MessagesRequest::new(
    "claude-3-5-sonnet-20241022",
    1024,
    vec![Message::user("Hello!")]
);
Source

pub fn with_system(self, system: impl Into<String>) -> Self

Set the system prompt.

The system prompt provides instructions and context that guide Claude’s behavior.

§Example
use claude_sdk::{MessagesRequest, Message};

let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("What's 2+2?")],
)
.with_system("You are a math tutor. Always explain your reasoning step by step.");
Source

pub fn with_tools(self, tools: Vec<ToolDefinition>) -> Self

Set the available tools for this request.

Accepts any mix of custom and server tools via ToolDefinition.

§Example
use claude_sdk::{MessagesRequest, Message, CustomTool, ToolDefinition};
use serde_json::json;

let calculator = ToolDefinition::Custom(
    CustomTool::new(
        "calculator",
        "Perform basic arithmetic operations",
        json!({
            "type": "object",
            "properties": {
                "operation": { "type": "string", "enum": ["add", "subtract", "multiply", "divide"] },
                "a": { "type": "number" },
                "b": { "type": "number" }
            },
            "required": ["operation", "a", "b"]
        }),
    )
    .programmatic()
);

let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("What's 15 * 7?")],
)
.with_tools(vec![calculator]);
Source

pub fn with_custom_tools(self, tools: Vec<CustomTool>) -> Self

Set tools using only custom (client-side) tools.

Convenience method that wraps each CustomTool in ToolDefinition::Custom.

§Example
use claude_sdk::{MessagesRequest, Message, CustomTool};
use serde_json::json;

let tool = CustomTool::new("my_tool", "A tool", json!({"type": "object"}));

let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("Hello")],
)
.with_custom_tools(vec![tool]);
Source

pub fn with_tool_choice(self, choice: ToolChoice) -> Self

Set tool choice configuration.

Controls how Claude decides whether and which tools to use.

§Example
use claude_sdk::{MessagesRequest, Message, ToolChoice};

// Force Claude to use a specific tool
let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("Search for weather")],
)
.with_tool_choice(ToolChoice::tool("get_weather"));

// Or let Claude decide (default)
let request2 = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("Hello")],
)
.with_tool_choice(ToolChoice::auto());
Source

pub fn with_temperature(self, temperature: f32) -> Self

Set the sampling temperature.

Temperature controls randomness in the output:

  • 0.0 - Deterministic, most likely tokens
  • 0.5 - Balanced creativity
  • 1.0 - Maximum randomness
§Example
use claude_sdk::{MessagesRequest, Message};

// Low temperature for factual responses
let factual = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("What is the capital of France?")],
)
.with_temperature(0.0);

// Higher temperature for creative writing
let creative = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    1024,
    vec![Message::user("Write a short poem about the ocean.")],
)
.with_temperature(0.8);
Source

pub fn with_effort(self, effort: EffortLevel) -> Self

Set effort level (beta - requires anthropic-beta: effort-2025-11-24 header).

Controls the trade-off between response quality and token usage. Only supported by Claude Opus 4.5.

§Effort Levels
§Example
use claude_sdk::{MessagesRequest, Message, EffortLevel};

let request = MessagesRequest::new(
    "claude-opus-4-5-20251101",  // Opus 4.5 only
    1024,
    vec![Message::user("Summarize this document briefly.")],
)
.with_effort(EffortLevel::Low);  // Optimize for efficiency
Source

pub fn with_json_schema(self, schema: Value) -> Self

Set JSON schema for structured output

Source

pub fn with_thinking(self, budget_tokens: u32) -> Self

Enable extended thinking with a token budget.

Extended thinking allows Claude to reason through complex problems step-by-step before providing a final answer.

§Requirements
  • Supported by: Claude Sonnet 4.5, Haiku 4.5, Opus 4.5, and other Claude 4+ models
  • Minimum budget: 1024 tokens
  • The thinking process appears in ContentBlock::Thinking blocks
§Example
use claude_sdk::{MessagesRequest, Message};

let request = MessagesRequest::new(
    "claude-sonnet-4-5-20250929",
    8192,
    vec![Message::user("Solve this step by step: If a train travels...")],
)
.with_thinking(4096);  // Allow up to 4096 tokens for reasoning
Source

pub fn with_adaptive_thinking(self) -> Self

Enable adaptive thinking – let the model decide how much to think

Source

pub fn with_metadata(self, metadata: Metadata) -> Self

Set request metadata for abuse detection.

Source

pub fn with_service_tier(self, tier: ServiceTier) -> Self

Set the service tier for request routing.

Source

pub fn with_inference_geo(self, geo: impl Into<String>) -> Self

Set the geographic inference routing.

Source

pub fn with_container(self, container_id: impl Into<String>) -> Self

Set container ID for persistent code execution state

Trait Implementations§

Source§

impl Clone for MessagesRequest

Source§

fn clone(&self) -> MessagesRequest

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MessagesRequest

Source§

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

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

impl<'de> Deserialize<'de> for MessagesRequest

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 MessagesRequest

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
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<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