Claudio.Messages.Request (Claudio v0.6.0)

View Source

Builder for constructing Messages API requests.

Example

alias Claudio.Messages.Request

Request.new("claude-sonnet-4-5-20250929")
|> Request.add_message(:user, "Hello!")
|> Request.set_system("You are a helpful assistant")
|> Request.set_max_tokens(1024)
|> Request.set_temperature(0.7)
|> Request.to_map()

Summary

Functions

Adds the client-side, schema-less bash tool (bash_20250124). You execute the returned tool_use locally and send back a tool_result. Do not add an input_schema — the schema is built into the model.

Adds a beta feature flag the request requires.

Adds the server-side code_execution tool (code_execution_20260120). GA — no beta header. Pairs with set_container/2 for container reuse and the Files API (container_upload blocks). Results are typed as bash_code_execution_tool_result / text_editor_code_execution_tool_result.

Adds the computer tool (computer_20250124) for desktop control, and declares the required computer-use-2025-01-24 beta header (via add_beta/2, so the send path attaches it automatically).

Adds MCP (Model Context Protocol) server definitions.

Adds the client-side memory tool (memory_20250818). GA — no beta header.

Adds a message to the conversation.

Adds a text message whose content block carries a cache_control breakpoint.

Adds a text message with a document from the Files API.

Adds a text message with an image from a base64-encoded string.

Adds a text message with an image from a URL.

Adds a tool with strict schema validation enabled (strict: true).

Adds the client-side, schema-less text editor tool (text_editor_20250728, name str_replace_based_edit_tool). Client-executed like bash.

Adds a tool definition.

Adds a tool definition with prompt caching enabled.

Adds a tool with fine-grained ("eager") input streaming enabled.

Adds the server-side web_fetch tool. GA — no beta header.

Adds the server-side web_search tool. GA — no beta header.

Enables streaming responses.

Enables extended thinking with optional budget.

Creates a new request builder with the specified model.

Returns the list of beta feature flags this request requires.

Builds a search_result content block for RAG / grounded citations.

Sets a top-level cache_control breakpoint, auto-placed on the last cacheable block of the request (server-side). The simplest way to cache the request prefix when you don't need per-block placement. GA — no beta header.

Sets container identifier for tool reuse.

Sets context management configuration.

Sets the maximum number of tokens to generate.

Sets request metadata.

Sets the raw output_config map.

Requests structured JSON output matching schema (a JSON Schema map).

Sets service tier for capacity selection.

Sets custom stop sequences.

Sets the system prompt.

Sets the system prompt with prompt caching enabled.

Sets the temperature (0.0-1.0).

Sets tool choice strategy.

Sets top_k for sampling from top K options.

Sets top_p for nucleus sampling (0.0-1.0).

Converts the request to a map suitable for the API.

Types

content()

@type content() :: String.t() | [map()]

role()

@type role() :: :user | :assistant

t()

@type t() :: %Claudio.Messages.Request{
  betas: [String.t()],
  cache_control: map() | nil,
  container: String.t() | map() | nil,
  context_management: map() | nil,
  max_tokens: integer() | nil,
  mcp_servers: [map()] | nil,
  messages: [map()],
  metadata: map() | nil,
  model: String.t(),
  output_config: map() | nil,
  service_tier: String.t() | nil,
  stop_sequences: [String.t()] | nil,
  stream: boolean() | nil,
  system: String.t() | list() | nil,
  temperature: float() | nil,
  thinking: map() | nil,
  tool_choice: map() | nil,
  tools: [map()] | nil,
  top_k: integer() | nil,
  top_p: float() | nil
}

tool_choice()

@type tool_choice() :: :auto | :any | {:tool, String.t()} | :none

Functions

add_bash_tool(request)

@spec add_bash_tool(t()) :: t()

Adds the client-side, schema-less bash tool (bash_20250124). You execute the returned tool_use locally and send back a tool_result. Do not add an input_schema — the schema is built into the model.

add_beta(request, beta)

@spec add_beta(t(), String.t()) :: t()

Adds a beta feature flag the request requires.

Beta flags are merged into the anthropic-beta request header at send time (see Claudio.Client.with_betas/2). Use this to opt into beta-gated features the library does not model with a dedicated setter.

Duplicates are ignored; insertion order is preserved.

Example

Request.new("claude-opus-4-8")
|> Request.add_beta("context-management-2025-06-27")

add_code_execution_tool(request)

@spec add_code_execution_tool(t()) :: t()

Adds the server-side code_execution tool (code_execution_20260120). GA — no beta header. Pairs with set_container/2 for container reuse and the Files API (container_upload blocks). Results are typed as bash_code_execution_tool_result / text_editor_code_execution_tool_result.

add_computer_tool(request, display_width_px, display_height_px, opts \\ [])

@spec add_computer_tool(t(), pos_integer(), pos_integer(), keyword()) :: t()

Adds the computer tool (computer_20250124) for desktop control, and declares the required computer-use-2025-01-24 beta header (via add_beta/2, so the send path attaches it automatically).

Client-side: Claude requests screenshots / mouse / keyboard actions that your application executes. Typically paired with add_bash_tool/1 and add_text_editor_tool/2.

Options

  • :display_number — X11 display number for the environment.

add_mcp_server(request, server)

@spec add_mcp_server(t(), Claudio.MCP.ServerConfig.t() | map()) :: t()

Adds MCP (Model Context Protocol) server definitions.

Example

Request.new("claude-sonnet-4-5-20250929")
|> Request.add_mcp_server(%{
  "name" => "my_server",
  "url" => "http://localhost:8080"
})

add_memory_tool(request)

@spec add_memory_tool(t()) :: t()

Adds the client-side memory tool (memory_20250818). GA — no beta header.

Claude issues view / create / str_replace / insert / delete / rename commands scoped to a /memories directory; you execute them locally. Confine every operation to /memories and reject path traversal. Pairs with set_context_management/2 for long-running agents.

add_message(request, role, content)

@spec add_message(t(), role(), content()) :: t()

Adds a message to the conversation.

Content can be:

  • A string for simple text messages
  • A list of content blocks for multimodal messages (text, images, documents)

Examples

# Simple text message
Request.new("claude-3-5-sonnet-20241022")
|> Request.add_message(:user, "What is the weather?")

# Multimodal message with image
Request.new("claude-3-5-sonnet-20241022")
|> Request.add_message(:user, [
  %{"type" => "image", "source" => %{
    "type" => "base64",
    "media_type" => "image/jpeg",
    "data" => base64_image
  }},
  %{"type" => "text", "text" => "What's in this image?"}
])

add_message_with_cache(request, role, text, opts \\ [])

@spec add_message_with_cache(t(), role(), String.t(), keyword()) :: t()

Adds a text message whose content block carries a cache_control breakpoint.

Use for the "growing conversation prefix" caching pattern — mark the last stable turn so the prefix up to it is cached. GA — no beta header. Up to 4 cache_control breakpoints are allowed per request (not enforced here).

Options

  • :ttl — cache duration, "5m" (default) or "1h"

Example

Request.new("claude-opus-4-8")
|> Request.add_message_with_cache(:user, "Large shared context...", ttl: "1h")
|> Request.add_message(:user, "The actual question")

add_message_with_document(request, role, text, file_id, opts \\ [])

@spec add_message_with_document(t(), role(), String.t(), String.t(), keyword()) :: t()

Adds a text message with a document from the Files API.

Options

  • :citations - When true, enables citations on the document ("citations" => %{"enabled" => true}). The API requires citations to be enabled on all-or-none of the documents in a request. Incompatible with structured outputs (set_output_config/2) — the API returns 400.
  • :title - Optional document title (length-limited; not cited from).
  • :context - Optional document metadata passed to the model but not cited from.

Examples

Request.new("claude-3-5-sonnet-20241022")
|> Request.add_message_with_document(:user, "Summarize this document", "file_abc123")

Request.new("claude-opus-4-8")
|> Request.add_message_with_document(:user, "Summarize", "file_abc123",
  citations: true,
  title: "Q4 Report"
)

add_message_with_image(request, role, text, base64_data, media_type \\ "image/jpeg")

@spec add_message_with_image(t(), role(), String.t(), String.t(), String.t()) :: t()

Adds a text message with an image from a base64-encoded string.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.add_message_with_image(:user, "What's in this image?", base64_data, "image/jpeg")

add_message_with_image_url(request, role, text, image_url)

@spec add_message_with_image_url(t(), role(), String.t(), String.t()) :: t()

Adds a text message with an image from a URL.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.add_message_with_image_url(:user, "What's in this image?", "https://example.com/image.jpg")

add_strict_tool(request, tool)

@spec add_strict_tool(t(), map()) :: t()

Adds a tool with strict schema validation enabled (strict: true).

Guarantees the model's tool_use.input validates exactly against the schema. The schema must use "additionalProperties" => false and list "required". GA — no beta header. (strict is a plain tool field; add_tool/2 also passes it through if you set it yourself.)

add_text_editor_tool(request, opts \\ [])

@spec add_text_editor_tool(
  t(),
  keyword()
) :: t()

Adds the client-side, schema-less text editor tool (text_editor_20250728, name str_replace_based_edit_tool). Client-executed like bash.

Options

  • :max_characters — cap view-command output length.

add_tool(request, tool)

@spec add_tool(t(), map()) :: t()

Adds a tool definition.

Example

tool = %{
  "name" => "get_weather",
  "description" => "Get weather for a location",
  "input_schema" => %{
    "type" => "object",
    "properties" => %{
      "location" => %{"type" => "string"}
    },
    "required" => ["location"]
  }
}

Request.new("claude-3-5-sonnet-20241022")
|> Request.add_tool(tool)

add_tool_with_cache(request, tool, opts \\ [])

@spec add_tool_with_cache(t(), map(), keyword()) :: t()

Adds a tool definition with prompt caching enabled.

Useful when you have many tool definitions and want to cache them.

Example

tool = %{
  "name" => "get_weather",
  "description" => "Get weather for a location",
  "input_schema" => %{"type" => "object", "properties" => %{}}
}

Request.new("claude-3-5-sonnet-20241022")
|> Request.add_tool_with_cache(tool)

add_tool_with_eager_streaming(request, tool)

@spec add_tool_with_eager_streaming(t(), map()) :: t()

Adds a tool with fine-grained ("eager") input streaming enabled.

Sets eager_input_streaming: true so the tool's input_json_delta chunks stream as they are generated. GA — not a beta feature; use the regular streaming path (enable_streaming/1).

add_web_fetch_tool(request, opts \\ [])

@spec add_web_fetch_tool(
  t(),
  keyword()
) :: t()

Adds the server-side web_fetch tool. GA — no beta header.

Options

  • :version:basic for web_fetch_20250910, otherwise the default web_fetch_20260209 (dynamic filtering). A full type string is also accepted.
  • :max_uses — cap the number of fetches per request.
  • :allowed_domains / :blocked_domains — domain filtering (lists).
  • :citationstrue enables citations on fetched content.
  • :max_content_tokens — approximate cap on fetched content size.

Unlike web search (URLs Claude finds), web fetch can only retrieve URLs that already appeared in the conversation.

add_web_search_tool(request, opts \\ [])

@spec add_web_search_tool(
  t(),
  keyword()
) :: t()

Adds the server-side web_search tool. GA — no beta header.

Options

  • :version:basic for web_search_20250305, otherwise the default web_search_20260209 (dynamic filtering on 4.6+). A full type string is also accepted.
  • :max_uses — cap the number of searches per request.
  • :allowed_domains / :blocked_domains — domain filtering (lists).
  • :user_location — approximate-location map for localized results.

Server-tool output is typed as server_tool_use / web_search_tool_result blocks (see Claudio.Messages.Response.get_server_tool_uses/1).

enable_streaming(request)

@spec enable_streaming(t()) :: t()

Enables streaming responses.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.enable_streaming()

enable_thinking(request, config)

@spec enable_thinking(t(), map()) :: t()

Enables extended thinking with optional budget.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.enable_thinking(%{"type" => "enabled", "budget_tokens" => 1000})

new(model)

@spec new(String.t()) :: t()

Creates a new request builder with the specified model.

Example

Request.new("claude-sonnet-4-5-20250929")

required_betas(request)

@spec required_betas(t()) :: [String.t()]

Returns the list of beta feature flags this request requires.

search_result_block(source, title, contents, opts \\ [])

@spec search_result_block(String.t(), String.t(), [String.t() | map()], keyword()) ::
  map()

Builds a search_result content block for RAG / grounded citations.

contents may be a list of strings (each wrapped as a text block) or a list of pre-built text-block maps. Compose into a turn with add_message/3:

result =
  Request.search_result_block("https://docs/api", "API Reference", ["…"],
    citations: true
  )

request
|> Request.add_message(:user, [
  result,
  %{"type" => "text", "text" => "How do I authenticate?"}
])

Options

  • :citations - When true, enables citations on this result (surfaces as search_result_location citations on response text blocks).
  • :cache_control - true for default ephemeral caching, or a ttl string ("5m" / "1h").

set_cache_control(request, opts \\ [])

@spec set_cache_control(
  t(),
  keyword()
) :: t()

Sets a top-level cache_control breakpoint, auto-placed on the last cacheable block of the request (server-side). The simplest way to cache the request prefix when you don't need per-block placement. GA — no beta header.

Options

  • :ttl — cache duration, "5m" (default) or "1h"

Example

Request.new("claude-opus-4-8")
|> Request.set_system("Large shared context...")
|> Request.set_cache_control(ttl: "1h")

set_container(request, container)

@spec set_container(t(), String.t() | map()) :: t()

Sets container identifier for tool reuse.

Allows tools to maintain state across requests.

Example

# String container ID
Request.new("claude-3-5-sonnet-20241022")
|> Request.set_container("my-container-123")

# Container config object
Request.new("claude-3-5-sonnet-20241022")
|> Request.set_container(%{
  "id" => "my-container",
  "ttl" => 3600
})

set_context_management(request, config)

@spec set_context_management(t(), map()) :: t()

Sets context management configuration.

Controls how context is managed across requests.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_context_management(%{
  "strategy" => "auto",
  "max_context_tokens" => 100000
})

set_max_tokens(request, max_tokens)

@spec set_max_tokens(t(), integer()) :: t()

Sets the maximum number of tokens to generate.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_max_tokens(1024)

set_metadata(request, metadata)

@spec set_metadata(t(), map()) :: t()

Sets request metadata.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_metadata(%{"user_id" => "123"})

set_output_config(request, config)

@spec set_output_config(t(), map()) :: t()

Sets the raw output_config map.

output_config is the API container for output controls (format, and on supported models effort / task_budget). This replaces the whole map; for structured JSON output prefer set_output_format/2, which merges.

Example

Request.new("claude-opus-4-8")
|> Request.set_output_config(%{"effort" => "high"})

set_output_format(request, schema)

@spec set_output_format(t(), map()) :: t()

Requests structured JSON output matching schema (a JSON Schema map).

Sets output_config.format to {type: "json_schema", schema: schema}, merging into any existing output_config (so a prior set_output_config/2 survives). GA — no beta header. The schema must use "additionalProperties" => false and list its "required" keys. Not compatible with document citations.

Example

Request.new("claude-opus-4-8")
|> Request.set_output_format(%{
  "type" => "object",
  "properties" => %{"name" => %{"type" => "string"}},
  "required" => ["name"],
  "additionalProperties" => false
})

set_service_tier(request, tier)

@spec set_service_tier(t(), String.t()) :: t()

Sets service tier for capacity selection.

Options:

  • "auto" - Automatically select based on availability
  • "standard_only" - Only use standard tier capacity

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_service_tier("auto")

set_stop_sequences(request, sequences)

@spec set_stop_sequences(t(), [String.t()]) :: t()

Sets custom stop sequences.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_stop_sequences(["END", "STOP"])

set_system(request, system)

@spec set_system(t(), String.t() | list()) :: t()

Sets the system prompt.

Can be a string or a list of content blocks with optional cache_control.

Examples

# Simple string
Request.new("claude-3-5-sonnet-20241022")
|> Request.set_system("You are a helpful assistant")

# With prompt caching
Request.new("claude-3-5-sonnet-20241022")
|> Request.set_system([
  %{
    "type" => "text",
    "text" => "Long system prompt here...",
    "cache_control" => %{"type" => "ephemeral"}
  }
])

set_system_with_cache(request, text, opts \\ [])

@spec set_system_with_cache(t(), String.t(), keyword()) :: t()

Sets the system prompt with prompt caching enabled.

Options

  • :ttl - Cache duration, either "5m" (default) or "1h"

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_system_with_cache("Long system prompt...", ttl: "1h")

set_temperature(request, temperature)

@spec set_temperature(t(), float()) :: t()

Sets the temperature (0.0-1.0).

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_temperature(0.7)

set_tool_choice(request, arg2)

@spec set_tool_choice(t(), tool_choice()) :: t()

Sets tool choice strategy.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_tool_choice(:auto)
|> Request.set_tool_choice(:any)
|> Request.set_tool_choice({:tool, "get_weather"})
|> Request.set_tool_choice(:none)

set_top_k(request, top_k)

@spec set_top_k(t(), integer()) :: t()

Sets top_k for sampling from top K options.

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_top_k(40)

set_top_p(request, top_p)

@spec set_top_p(t(), float()) :: t()

Sets top_p for nucleus sampling (0.0-1.0).

Example

Request.new("claude-3-5-sonnet-20241022")
|> Request.set_top_p(0.9)

to_map(request)

@spec to_map(t()) :: map()

Converts the request to a map suitable for the API.