Page
Library
Module
Module type
Parameter
Class
Class type
Source
Anthropic
SourceOCaml bindings for the Anthropic API.
This library provides type-safe OCaml bindings to the Anthropic API, and supports both synchronous and streaming responses.
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)
client
represents a configured Anthropic API client.
The client handles authentication, network requests, and automatic retries. All API operations require a client instance.
type api_error_type =
| Invalid_request_error
The request is malformed or invalid.
*)| Authentication_error
The API key is invalid or missing.
*)| Permission_error
The API key lacks required permissions.
*)| Not_found_error
The requested resource does not exist.
*)| Rate_limit_error
The rate limit has been exceeded.
*)| Api_error_other of string
Any other error type returned by the API.
*)api_error_type
categorizes specific API error responses.
type error =
| Api_error of {
type_ : api_error_type;
The specific type of API error.
*)message : string;
Human-readable error description.
*)request_id : string option;
Request ID for debugging, if available.
*)}
Structured errors returned by the Anthropic API.
*)| Http_error of {
status : Cohttp.Code.status_code;
The HTTP status code.
*)message : string;
Response body or error description.
*)}
HTTP-level errors without API error structure.
*)| 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.
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"
type 'a page = {
data : 'a list;
The items in the current page.
*)has_more : bool;
Whether more pages are available.
*)first_id : string option;
ID of the first item in this page.
*)last_id : string option;
ID of the last item in this page.
*)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)
type model = [
| `Claude_3_7_Sonnet_Latest
Latest Claude 3.7 Sonnet model.
*)| `Claude_3_7_Sonnet_20250219
Claude 3.7 Sonnet, February 19, 2025 version.
*)| `Claude_3_5_Haiku_Latest
Latest Claude 3.5 Haiku model (fastest).
*)| `Claude_3_5_Haiku_20241022
Claude 3.5 Haiku, October 22, 2024 version.
*)| `Claude_Sonnet_4_20250514
Claude 4 Sonnet, May 14, 2025 version.
*)| `Claude_Sonnet_4_0
Claude 4.0 Sonnet base version.
*)| `Claude_4_Sonnet_20250514
Alternative naming for Claude 4 Sonnet.
*)| `Claude_3_5_Sonnet_Latest
Latest Claude 3.5 Sonnet model (balanced).
*)| `Claude_3_5_Sonnet_20241022
Claude 3.5 Sonnet, October 22, 2024 version.
*)| `Claude_3_5_Sonnet_20240620
Claude 3.5 Sonnet, June 20, 2024 version.
*)| `Claude_Opus_4_0
Claude 4.0 Opus base version (most capable).
*)| `Claude_Opus_4_20250514
Claude 4 Opus, May 14, 2025 version.
*)| `Claude_4_Opus_20250514
Alternative naming for Claude 4 Opus.
*)| `Claude_3_Opus_Latest
| `Claude_3_Opus_20240229
| `Claude_3_Sonnet_20240229
| `Claude_3_Haiku_20240307
| `Claude_2_1
| `Claude_2_0
| `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.
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.
type input_content_block =
| Text of string
Plain text content.
*)| Image of {
media_type : string;
MIME type (e.g., "image/jpeg", "image/png").
*)data : string;
Base64-encoded image data.
*)}
Image content for vision tasks.
*)| Document of {
name : string;
Display name for the document.
*)content : string;
Base64-encoded document data.
*)media_type : string;
MIME type (e.g., "application/pdf").
*)}
Document content for analysis.
*)| Tool_result of {
tool_use_id : string;
ID from the corresponding tool use request.
*)content : string;
Result of the tool execution.
*)is_error : bool option;
Whether the tool execution failed.
*)}
Results from tool execution.
*)| Tool_use of {
id : string;
Unique identifier for this tool use.
*)name : string;
Name of the tool to invoke.
*)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.
Helper functions for creating content blocks.
type message = {
role : role;
The author of the message.
*)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.
type tool = {
name : string;
Unique identifier for the tool.
*)description : string option;
Human-readable description of the tool's purpose.
*)input_schema : Yojson.Safe.t;
JSON Schema defining the tool's parameters.
*)type_ : string option;
The type of the tool.
*)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.
tool_choice
controls how Claude selects tools during generation.
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.
val 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.
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 *)
type api_error = {
type_ : string;
Error type identifier.
*)message : string;
Human-readable error message.
*)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.