anthropic/request

API request and response types for the Anthropic Messages API

This module defines the types for creating message requests and parsing message responses from Claude’s API.

Types

Request to create a message via the Messages API

pub type CreateMessageRequest {
  CreateMessageRequest(
    model: String,
    messages: List(message.Message),
    max_tokens: Int,
    system: option.Option(String),
    temperature: option.Option(Float),
    top_p: option.Option(Float),
    top_k: option.Option(Int),
    stop_sequences: option.Option(List(String)),
    stream: option.Option(Bool),
    metadata: option.Option(Metadata),
    tools: option.Option(List(tool.Tool)),
    tool_choice: option.Option(tool.ToolChoice),
  )
}

Constructors

  • CreateMessageRequest(
      model: String,
      messages: List(message.Message),
      max_tokens: Int,
      system: option.Option(String),
      temperature: option.Option(Float),
      top_p: option.Option(Float),
      top_k: option.Option(Int),
      stop_sequences: option.Option(List(String)),
      stream: option.Option(Bool),
      metadata: option.Option(Metadata),
      tools: option.Option(List(tool.Tool)),
      tool_choice: option.Option(tool.ToolChoice),
    )

    Arguments

    model

    The model to use (e.g., “claude-opus-4-20250514”, “claude-sonnet-4-20250514”)

    messages

    List of messages in the conversation

    max_tokens

    Maximum number of tokens to generate

    system

    System prompt to set context for the conversation

    temperature

    Temperature for sampling (0.0 to 1.0)

    top_p

    Top-p sampling parameter

    top_k

    Top-k sampling parameter

    stop_sequences

    Sequences that will stop generation

    stream

    Whether to stream the response

    metadata

    Optional metadata including user_id

    tools

    List of tools available to the model

    tool_choice

    How the model should choose which tool to use

Response from the Messages API

pub type CreateMessageResponse {
  CreateMessageResponse(
    id: String,
    response_type: String,
    role: message.Role,
    content: List(message.ContentBlock),
    model: String,
    stop_reason: option.Option(StopReason),
    stop_sequence: option.Option(String),
    usage: Usage,
  )
}

Constructors

  • CreateMessageResponse(
      id: String,
      response_type: String,
      role: message.Role,
      content: List(message.ContentBlock),
      model: String,
      stop_reason: option.Option(StopReason),
      stop_sequence: option.Option(String),
      usage: Usage,
    )

    Arguments

    id

    Unique identifier for this message

    response_type

    Object type, always “message”

    role

    Role of the response, always “assistant”

    content

    Content blocks in the response

    model

    Model that generated the response

    stop_reason

    Reason generation stopped

    stop_sequence

    The stop sequence that triggered stop_reason, if applicable

    usage

    Token usage information

Optional metadata for requests

pub type Metadata {
  Metadata(user_id: option.Option(String))
}

Constructors

  • Metadata(user_id: option.Option(String))

    Arguments

    user_id

    External identifier for the user making the request

Options for configuring a message request

Use this when you want to specify multiple options at once, or when copying options between requests. For simple cases, the builder pattern with with_* functions is recommended.

Example

// Create reusable options
let opts = request.options()
  |> request.opt_system("You are a helpful assistant")
  |> request.opt_temperature(0.7)
  |> request.opt_max_tokens(2048)

// Use options with new_with
let req = request.new_with("claude-sonnet-4-20250514", messages, opts)
pub type RequestOptions {
  RequestOptions(
    max_tokens: Int,
    system: option.Option(String),
    temperature: option.Option(Float),
    top_p: option.Option(Float),
    top_k: option.Option(Int),
    stop_sequences: option.Option(List(String)),
    stream: option.Option(Bool),
    metadata: option.Option(Metadata),
    tools: option.Option(List(tool.Tool)),
    tool_choice: option.Option(tool.ToolChoice),
  )
}

Constructors

  • RequestOptions(
      max_tokens: Int,
      system: option.Option(String),
      temperature: option.Option(Float),
      top_p: option.Option(Float),
      top_k: option.Option(Int),
      stop_sequences: option.Option(List(String)),
      stream: option.Option(Bool),
      metadata: option.Option(Metadata),
      tools: option.Option(List(tool.Tool)),
      tool_choice: option.Option(tool.ToolChoice),
    )

    Arguments

    max_tokens

    Maximum number of tokens to generate (required, defaults to 1024)

    system

    System prompt to set context for the conversation

    temperature

    Temperature for sampling (0.0 to 1.0)

    top_p

    Top-p sampling parameter

    top_k

    Top-k sampling parameter

    stop_sequences

    Sequences that will stop generation

    stream

    Whether to stream the response

    metadata

    Optional metadata including user_id

    tools

    List of tools available to the model

    tool_choice

    How the model should choose which tool to use

Reason why the model stopped generating

pub type StopReason {
  EndTurn
  MaxTokens
  StopSequence
  ToolUse
}

Constructors

  • EndTurn

    Model reached a natural stopping point

  • MaxTokens

    Model reached the max_tokens limit

  • StopSequence

    Model encountered a stop sequence

  • ToolUse

    Model is requesting to use a tool

Token usage information from an API response

pub type Usage {
  Usage(input_tokens: Int, output_tokens: Int)
}

Constructors

  • Usage(input_tokens: Int, output_tokens: Int)

    Arguments

    input_tokens

    Number of tokens in the input/prompt

    output_tokens

    Number of tokens in the output/completion

Values

pub fn apply_options(
  req: CreateMessageRequest,
  opts: RequestOptions,
) -> CreateMessageRequest

Apply options to an existing request

This merges options into an existing request, overwriting any options that are set (not None) in the provided RequestOptions.

Example

let req = request.new("claude-sonnet-4-20250514", messages, 1024)
let opts = request.options()
  |> request.opt_temperature(0.7)
  |> request.opt_system("Be helpful")

let updated_req = request.apply_options(req, opts)
pub fn create_request(
  model: String,
  messages: List(message.Message),
  max_tokens: Int,
) -> CreateMessageRequest

Deprecated: Use request.new instead

Create a basic request with required fields only

@deprecated Use request.new instead for idiomatic Gleam style

pub fn create_response(
  id: String,
  content: List(message.ContentBlock),
  model: String,
  stop_reason: option.Option(StopReason),
  u: Usage,
) -> CreateMessageResponse

Create a response (primarily for testing)

pub fn create_response_with_stop_sequence(
  id: String,
  content: List(message.ContentBlock),
  model: String,
  stop_reason: StopReason,
  stop_sequence: String,
  u: Usage,
) -> CreateMessageResponse

Create a response with a stop sequence

pub fn get_options(req: CreateMessageRequest) -> RequestOptions

Extract options from an existing request

This allows copying options from one request to use in another.

Example

// Extract options from an existing request
let opts = request.get_options(existing_request)

// Modify and use for a new request
let new_opts = opts |> request.opt_temperature(0.5)
let new_req = request.new_with("claude-sonnet-4-20250514", messages, new_opts)
pub fn get_pending_tool_calls(
  response: CreateMessageResponse,
) -> List(tool.ToolCall)

Extract tool calls that need execution from a response

Returns a list of structured ToolCall records ready for execution. Each ToolCall contains the id, name, and input (as JSON string).

Example

let calls = request.get_pending_tool_calls(response)
let results = list.map(calls, fn(call) {
  case call.name {
    "get_weather" -> execute_weather(call)
    "search" -> execute_search(call)
    _ -> ToolFailure(call.id, "Unknown tool")
  }
})
pub fn metadata_to_json(metadata: Metadata) -> json.Json

Encode Metadata to JSON

pub fn needs_tool_execution(
  response: CreateMessageResponse,
) -> Bool

Check if response requires tool execution to continue

Returns True if the model stopped because it wants to use a tool. This is the signal to extract tool calls, execute them, and continue the conversation with tool results.

Example

case request.needs_tool_execution(response) {
  True -> {
    let calls = request.get_pending_tool_calls(response)
    // Execute tools and continue conversation
  }
  False -> {
    // Response is complete, get the text
    request.response_text(response)
  }
}
pub fn new(
  model: String,
  messages: List(message.Message),
  max_tokens: Int,
) -> CreateMessageRequest

Create a new message request with required fields only

This is the idiomatic Gleam constructor for CreateMessageRequest.

Example

import anthropic/types/request
import anthropic/types/message.{user_message}

let req = request.new(
  "claude-sonnet-4-20250514",
  [user_message("Hello, Claude!")],
  1024,
)
pub fn new_with(
  model: String,
  messages: List(message.Message),
  opts: RequestOptions,
) -> CreateMessageRequest

Create a new message request with options

This allows specifying multiple options at once using a RequestOptions record. Useful for config-driven scenarios, copying options between requests, or when you have many options to set.

Example

import anthropic/types/request
import anthropic/types/message.{user_message}

// Create reusable options
let creative_opts = request.options()
  |> request.opt_system("You are a creative writer")
  |> request.opt_temperature(0.9)
  |> request.opt_max_tokens(2048)

// Use options with new_with
let req = request.new_with(
  "claude-sonnet-4-20250514",
  [user_message("Write a poem about stars")],
  creative_opts,
)

// Reuse the same options for another request
let req2 = request.new_with(
  "claude-sonnet-4-20250514",
  [user_message("Write a poem about the ocean")],
  creative_opts,
)
pub fn opt_max_tokens(
  opts: RequestOptions,
  max_tokens: Int,
) -> RequestOptions

Set max_tokens in options

pub fn opt_metadata(
  opts: RequestOptions,
  metadata: Metadata,
) -> RequestOptions

Set metadata in options

pub fn opt_stop_sequences(
  opts: RequestOptions,
  sequences: List(String),
) -> RequestOptions

Set stop sequences in options

pub fn opt_stream(
  opts: RequestOptions,
  stream: Bool,
) -> RequestOptions

Set stream in options

pub fn opt_system(
  opts: RequestOptions,
  system: String,
) -> RequestOptions

Set system prompt in options

pub fn opt_temperature(
  opts: RequestOptions,
  temperature: Float,
) -> RequestOptions

Set temperature in options

pub fn opt_tool_choice(
  opts: RequestOptions,
  choice: tool.ToolChoice,
) -> RequestOptions

Set tool choice in options

pub fn opt_tools(
  opts: RequestOptions,
  tools: List(tool.Tool),
) -> RequestOptions

Set tools in options

pub fn opt_tools_and_choice(
  opts: RequestOptions,
  tools: List(tool.Tool),
  choice: tool.ToolChoice,
) -> RequestOptions

Set tools and tool choice in options (convenience function)

pub fn opt_top_k(
  opts: RequestOptions,
  top_k: Int,
) -> RequestOptions

Set top_k in options

pub fn opt_top_p(
  opts: RequestOptions,
  top_p: Float,
) -> RequestOptions

Set top_p in options

pub fn opt_user_id(
  opts: RequestOptions,
  user_id: String,
) -> RequestOptions

Set user_id in options (creates Metadata automatically)

pub fn options() -> RequestOptions

Create default request options

Returns options with max_tokens set to 1024 and all other options as None.

Example

let opts = request.options()
  |> request.opt_temperature(0.8)
  |> request.opt_system("Be concise")
pub fn request_to_json(
  request: CreateMessageRequest,
) -> json.Json

Encode a CreateMessageRequest to JSON

pub fn request_to_json_string(
  request: CreateMessageRequest,
) -> String

Convert a request to a JSON string

pub fn response_get_tool_uses(
  response: CreateMessageResponse,
) -> List(message.ContentBlock)

Get all tool use blocks from a response

pub fn response_has_tool_use(
  response: CreateMessageResponse,
) -> Bool

Check if a response contains tool use blocks

pub fn response_text(response: CreateMessageResponse) -> String

Get the text content from a response (concatenated)

pub fn response_to_json(
  response: CreateMessageResponse,
) -> json.Json

Encode a response to JSON (for testing/serialization)

pub fn response_to_json_string(
  response: CreateMessageResponse,
) -> String

Convert a response to a JSON string

pub fn stop_reason_from_string(
  str: String,
) -> Result(StopReason, String)

Parse a string into a StopReason

pub fn stop_reason_to_json(reason: StopReason) -> json.Json

Encode a StopReason to JSON

pub fn stop_reason_to_string(reason: StopReason) -> String

Convert a StopReason to its JSON string representation

pub fn usage_to_json(u: Usage) -> json.Json

Encode Usage to JSON

pub fn with_metadata(
  request: CreateMessageRequest,
  metadata: Metadata,
) -> CreateMessageRequest

Set metadata on a request

pub fn with_stop_sequences(
  request: CreateMessageRequest,
  sequences: List(String),
) -> CreateMessageRequest

Set stop sequences on a request

pub fn with_stream(
  request: CreateMessageRequest,
  stream: Bool,
) -> CreateMessageRequest

Enable streaming on a request

pub fn with_system(
  request: CreateMessageRequest,
  system: String,
) -> CreateMessageRequest

Set the system prompt on a request

pub fn with_temperature(
  request: CreateMessageRequest,
  temperature: Float,
) -> CreateMessageRequest

Set the temperature on a request

pub fn with_tool_choice(
  request: CreateMessageRequest,
  choice: tool.ToolChoice,
) -> CreateMessageRequest

Set tool choice on a request

pub fn with_tools(
  request: CreateMessageRequest,
  tools: List(tool.Tool),
) -> CreateMessageRequest

Set tools on a request

pub fn with_tools_and_choice(
  request: CreateMessageRequest,
  tools: List(tool.Tool),
  choice: tool.ToolChoice,
) -> CreateMessageRequest

Set tools and tool choice on a request (convenience function)

pub fn with_top_k(
  request: CreateMessageRequest,
  top_k: Int,
) -> CreateMessageRequest

Set top_k on a request

pub fn with_top_p(
  request: CreateMessageRequest,
  top_p: Float,
) -> CreateMessageRequest

Set top_p on a request

pub fn with_user_id(
  request: CreateMessageRequest,
  user_id: String,
) -> CreateMessageRequest

Set user_id in metadata on a request

Search Document