package anthropic

  1. Overview
  2. Docs

Module AnthropicSource

OCaml bindings for the Anthropic API.

This library provides type-safe OCaml bindings to the Anthropic API, and supports both synchronous and streaming responses.

Getting Started

Create a client using your API key, then interact with the Anthropic API through sub-modules like Messages and Models. The library requires an Eio environment.

The client manages connection pooling and automatic retries. Stream operations provide backpressure control through Eio streams

Example: Sends a simple message to Claude.

  open Eio.Std
  open Anthropic

  let () =
    Eio_main.run @@ fun env ->
    Switch.run @@ fun sw ->
    let client = create ~sw ~env () in
    let messages =
      [ Message.user [ Content_block.text "Hello, Claude!" ] ]
    in
    match
      Messages.send client ~max_tokens:1024
        ~model:`Claude_3_5_Sonnet_20240620 ~messages ()
    with
    | Ok response -> (
        match response.content with
        | [ Text_block { text } ] -> traceln "Assistant: %s" text
        | _ -> traceln "Received unexpected content.")
    | Error err -> traceln "Error: %s" (string_of_error err)

Core Types

Sourcetype auth_method =
  1. | Api_key of string
  2. | Bearer_token of string
    (*

    Authentication method for the client

    *)
Sourcetype client

client represents a configured Anthropic API client.

The client handles authentication, network requests, and automatic retries. All API operations require a client instance.

Sourcetype api_error_type =
  1. | Invalid_request_error
    (*

    The request is malformed or invalid.

    *)
  2. | Authentication_error
    (*

    The API key is invalid or missing.

    *)
  3. | Permission_error
    (*

    The API key lacks required permissions.

    *)
  4. | Not_found_error
    (*

    The requested resource does not exist.

    *)
  5. | Rate_limit_error
    (*

    The rate limit has been exceeded.

    *)
  6. | Api_error_other of string
    (*

    Any other error type returned by the API.

    *)

api_error_type categorizes specific API error responses.

Sourcetype error =
  1. | Api_error of {
    1. type_ : api_error_type;
      (*

      The specific type of API error.

      *)
    2. message : string;
      (*

      Human-readable error description.

      *)
    3. request_id : string option;
      (*

      Request ID for debugging, if available.

      *)
    }
    (*

    Structured errors returned by the Anthropic API.

    *)
  2. | Http_error of {
    1. status : Cohttp.Code.status_code;
      (*

      The HTTP status code.

      *)
    2. message : string;
      (*

      Response body or error description.

      *)
    }
    (*

    HTTP-level errors without API error structure.

    *)
  3. | Connection_error of exn
    (*

    Network or connection-level exceptions.

    *)

error represents all possible errors from API operations.

Errors are categorized into three main types: API-level errors with structured information, HTTP-level errors with status codes, and connection-level errors for network issues.

Sourceval string_of_error : error -> string

string_of_error err converts an error to a human-readable string.

The output format varies by error type: API errors show the type and message, HTTP errors show the status code and message, and connection errors show the exception details.

Example: Converts an authentication error.

  let err =
    Api_error
      {
        type_ = Authentication_error;
        message = "Invalid API key";
        request_id = None;
      }
  in
  string_of_error err = "API Error (authentication_error): Invalid API key"
Sourcetype 'a page = {
  1. data : 'a list;
    (*

    The items in the current page.

    *)
  2. has_more : bool;
    (*

    Whether more pages are available.

    *)
  3. first_id : string option;
    (*

    ID of the first item in this page.

    *)
  4. last_id : string option;
    (*

    ID of the last item in this page.

    *)
  5. get_next_page : unit -> ('a page, error) result option;
    (*

    Fetches the next page if available.

    *)
}

'a page provides pagination for list endpoints.

Pages are immutable snapshots of results. The get_next_page function returns None when no more pages exist, or Some result containing either the next page or an error.

Example: Iterates through all models.

  let rec print_all_models page =
    List.iter (fun model -> print_endline model.Models.id) page.data;
    match page.get_next_page () with
    | None -> ()
    | Some (Ok next_page) -> print_all_models next_page
    | Some (Error err) -> Printf.eprintf "Error: %s\n" (string_of_error err)
Sourcetype model = [
  1. | `Claude_3_7_Sonnet_Latest
    (*

    Latest Claude 3.7 Sonnet model.

    *)
  2. | `Claude_3_7_Sonnet_20250219
    (*

    Claude 3.7 Sonnet, February 19, 2025 version.

    *)
  3. | `Claude_3_5_Haiku_Latest
    (*

    Latest Claude 3.5 Haiku model (fastest).

    *)
  4. | `Claude_3_5_Haiku_20241022
    (*

    Claude 3.5 Haiku, October 22, 2024 version.

    *)
  5. | `Claude_Sonnet_4_20250514
    (*

    Claude 4 Sonnet, May 14, 2025 version.

    *)
  6. | `Claude_Sonnet_4_0
    (*

    Claude 4.0 Sonnet base version.

    *)
  7. | `Claude_4_Sonnet_20250514
    (*

    Alternative naming for Claude 4 Sonnet.

    *)
  8. | `Claude_3_5_Sonnet_Latest
    (*

    Latest Claude 3.5 Sonnet model (balanced).

    *)
  9. | `Claude_3_5_Sonnet_20241022
    (*

    Claude 3.5 Sonnet, October 22, 2024 version.

    *)
  10. | `Claude_3_5_Sonnet_20240620
    (*

    Claude 3.5 Sonnet, June 20, 2024 version.

    *)
  11. | `Claude_Opus_4_0
    (*

    Claude 4.0 Opus base version (most capable).

    *)
  12. | `Claude_Opus_4_20250514
    (*

    Claude 4 Opus, May 14, 2025 version.

    *)
  13. | `Claude_4_Opus_20250514
    (*

    Alternative naming for Claude 4 Opus.

    *)
  14. | `Claude_3_Opus_Latest
    (*
    • deprecated

      Will reach end-of-life on January 5th, 2026. Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.

    *)
  15. | `Claude_3_Opus_20240229
    (*
    • deprecated

      Will reach end-of-life on January 5th, 2026. Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.

    *)
  16. | `Claude_3_Sonnet_20240229
    (*
    • deprecated

      Will reach end-of-life on July 21st, 2025. Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.

    *)
  17. | `Claude_3_Haiku_20240307
    (*
    • deprecated

      Will reach end-of-life on July 21st, 2025. Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.

    *)
  18. | `Claude_2_1
    (*
    • deprecated

      Will reach end-of-life on July 21st, 2025. Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.

    *)
  19. | `Claude_2_0
    (*
    • deprecated

      Will reach end-of-life on July 21st, 2025. Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.

    *)
  20. | `Other of string
    (*

    Custom model identifier for experimental or private models.

    *)
]

model specifies which Claude model to use for API requests.

Models are organized by family (Haiku, Sonnet, Opus) and version. Use the "Latest" variants for automatic updates to the newest stable version within a family. The `Other variant allows specifying custom model identifiers.

Sourcetype role = [
  1. | `User
  2. | `Assistant
]

role identifies the author of a message in a conversation.

Messages alternate between `User (human input) and `Assistant (Claude's responses). Conversations must start with a `User message.

Sourcetype input_content_block =
  1. | Text of string
    (*

    Plain text content.

    *)
  2. | Image of {
    1. media_type : string;
      (*

      MIME type (e.g., "image/jpeg", "image/png").

      *)
    2. data : string;
      (*

      Base64-encoded image data.

      *)
    }
    (*

    Image content for vision tasks.

    *)
  3. | Document of {
    1. name : string;
      (*

      Display name for the document.

      *)
    2. content : string;
      (*

      Base64-encoded document data.

      *)
    3. media_type : string;
      (*

      MIME type (e.g., "application/pdf").

      *)
    }
    (*

    Document content for analysis.

    *)
  4. | Tool_result of {
    1. tool_use_id : string;
      (*

      ID from the corresponding tool use request.

      *)
    2. content : string;
      (*

      Result of the tool execution.

      *)
    3. is_error : bool option;
      (*

      Whether the tool execution failed.

      *)
    }
    (*

    Results from tool execution.

    *)
  5. | Tool_use of {
    1. id : string;
      (*

      Unique identifier for this tool use.

      *)
    2. name : string;
      (*

      Name of the tool to invoke.

      *)
    3. input : Yojson.Safe.t;
      (*

      Arguments for the tool.

      *)
    }
    (*

    Tool use requests from assistant responses.

    *)

input_content_block represents content that can be sent to the API.

Content blocks are the building blocks of messages. A single message can contain multiple content blocks of different types, enabling rich conversations with text, images, documents, and tool results.

Sourcemodule Content_block : sig ... end

Helper functions for creating content blocks.

Sourcetype message = {
  1. role : role;
    (*

    The author of the message.

    *)
  2. content : input_content_block list;
    (*

    Content blocks comprising the message.

    *)
}

message represents a single turn in a conversation.

Messages contain one or more content blocks and are attributed to either the user or assistant. Conversations must start with a user message and alternate between roles.

Sourcemodule Message : sig ... end

Helper functions for creating messages.

Sourcetype tool = {
  1. name : string;
    (*

    Unique identifier for the tool.

    *)
  2. description : string option;
    (*

    Human-readable description of the tool's purpose.

    *)
  3. input_schema : Yojson.Safe.t;
    (*

    JSON Schema defining the tool's parameters.

    *)
  4. type_ : string option;
    (*

    The type of the tool.

    *)
  5. cache_control : Yojson.Safe.t option;
    (*

    Cache control configuration for the tool.

    *)
}

tool defines a function that Claude can call.

Tools enable Claude to interact with external systems or perform computations. The input_schema must be a valid JSON Schema object describing the expected parameters.

Sourcetype tool_choice =
  1. | Auto
    (*

    Claude decides whether and which tools to use based on the conversation.

    *)
  2. | Any
    (*

    Claude must use at least one tool, but chooses which one.

    *)
  3. | Tool of string
    (*

    Claude must use the specified tool by name.

    *)
  4. | Tool_none
    (*

    Claude cannot use any tools, even if provided.

    *)

tool_choice controls how Claude selects tools during generation.

Sourcetype metadata = {
  1. user_id : string option;
    (*

    Optional identifier for the end user.

    *)
}

metadata provides optional tracking information for requests.

Use metadata to associate API requests with specific users for analytics or debugging. The user_id should be an opaque identifier that doesn't contain PII.

Client Creation

Sourceval create_client : sw:Eio.Switch.t -> env:< net : 'a Eio.Net.t ; clock : float Eio.Time.clock_ty Eio.Std.r.. > -> ?api_key:string -> ?auth_token:string -> ?base_url:string -> ?max_retries:int -> unit -> client

create_client ~sw ~env ?api_key ?auth_token ?base_url ?max_retries () creates a new API client.

The client manages connection pooling, automatic retries, and request authentication. It requires an Eio switch for lifecycle management and an environment with network and clock capabilities.

  • parameter sw

    The Eio switch managing the client's resources.

  • parameter env

    The Eio environment providing network and clock access.

  • parameter api_key

    The Anthropic API key. Cannot be used with auth_token.

  • parameter auth_token

    OAuth bearer token for authentication. Cannot be used with api_key.

  • parameter base_url

    The API base URL. Defaults to "https://api.anthropic.com/v1".

  • parameter max_retries

    Maximum retry attempts for failed requests. Defaults to 2.

  • raises Invalid_argument

    if neither authentication method is provided or both are provided.

Example: Creates a client with default settings.

  Eio_main.run @@ fun env ->
  Switch.run @@ fun sw ->
  let client = Anthropic.create ~sw ~env
    ~api_key:"sk-ant-api03-..."
    ~max_retries:5 () in
  (* Use client for API operations *)
Sourcemodule Messages : sig ... end

Messages API for conversations with Claude.

Sourcemodule Tools : sig ... end

Tools module for handling tool execution patterns.

Sourcemodule Models : sig ... end

Models API for querying available Claude models.

Sourcetype api_error = {
  1. type_ : string;
    (*

    Error type identifier.

    *)
  2. message : string;
    (*

    Human-readable error message.

    *)
  3. request_id : string option;
    (*

    Request ID for debugging.

    *)
}

api_error represents structured error responses from the API.

This type is primarily used internally and in the Batches module for individual request failures.

Sourcemodule Batches : sig ... end

Batches API for asynchronous bulk message processing.

Sourcemodule Beta : sig ... end

Beta features for experimental functionality.

OCaml

Innovation. Community. Security.