Haskell bindings to Anthropic's Claude API using servant.
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
import Claude.V1
import Claude.V1.Messages
import Data.Foldable (traverse_)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text.IO
import qualified System.Environment as Environment
main :: IO ()
main = do
key <- Environment.getEnv "ANTHROPIC_KEY"
clientEnv <- getClientEnv "https://api.anthropic.com"
let Methods{ createMessage } = makeMethods clientEnv (Text.pack key) (Just "2023-06-01")
MessageResponse{ content } <- createMessage _CreateMessage
{ model = "claude-sonnet-5"
, messages = [ Message{ role = User, content = [ textContent "Hello!" ] } ]
, max_tokens = 1024
}
let display (ContentBlock_Text{ text }) = Text.IO.putStrLn text
display _ = pure ()
traverse_ display contentThe bindings support prompt caching at multiple levels:
- top-level request (
CreateMessage.cache_control) - system blocks (
SystemBlock.cache_control) - message/content blocks (
Message.cache_control, text/image content block cache control) - tool definitions (
withToolCacheControl)
MessageResponse{ usage } <- createMessage _CreateMessage
{ model = "claude-sonnet-5"
, max_tokens = 1024
, cache_control = Just (ephemeralCacheWithTTLDuration "1h")
, system = Just $ systemBlocks
[ systemTextBlockCached ephemeralCache "You are a coding assistant."
]
, messages =
[ Message{ role = User, content = [ textContent "Summarize this file." ] } ]
}- Ensure you have Nix with flakes enabled
- Copy the sample environment file:
cp .envrc.sample .envrc- Edit
.envrcwith your Anthropic API key - Run
direnv allow
cabal buildSet your Anthropic API key as an environment variable:
# Option 1: Set directly in your shell
export ANTHROPIC_KEY="your-anthropic-api-key"
# Option 2: Using .envrc with direnv (recommended)
cp .envrc.sample .envrc
# Edit .envrc to add your API key
direnv allowThe API key is needed for running the test suite and example programs.
Run the test suite:
cabal testSee examples for descriptions.
cabal run claude-example
cabal run claude-stream-example
cabal run claude-tool-example
cabal run claude-vision-example
cabal run claude-tool-search-example
cabal run claude-programmatic-tool-calling-example
cabal run claude-structured-outputs-example-
Structured Outputs: Constrain Claude's responses to follow a specific JSON schema, or validate tool parameters with strict mode
-
Tool Search Tool: Server-side tool search for efficiently handling large numbers of tools
-
Programmatic Tool Calling (PTC): Claude writes and executes code to call multiple tools and aggregate results