R - ANTHROPIC - API
Simon-Pierre Boucher
2024-09-14
In [1]:
library(httr)
library(jsonlite)
# Define the function
call_claude_api <- function(
model = "claude-3-5-sonnet-20240620",
messages,
max_tokens = 1024,
anthropic_version = "2023-06-01"
) {
# Get the API key from environment variables
api_key <- Sys.getenv("ANTHROPIC_API_KEY")
if (api_key == "") {
stop("API key not found in environment variables. Please set ANTHROPIC_API_KEY.")
}
url <- "https://api.anthropic.com/v1/messages"
headers <- add_headers(
`x-api-key` = api_key,
`anthropic-version` = anthropic_version,
`content-type` = "application/json"
)
body <- list(
model = model,
max_tokens = max_tokens,
messages = messages
)
response <- POST(url, headers, body = toJSON(body, auto_unbox = TRUE))
if (status_code(response) != 200) {
stop("API request failed: ", content(response, "text", encoding = "UTF-8"))
}
result <- content(response, as = "parsed", encoding = "UTF-8")
return(result)
}
In [2]:
messages <- list(
list(role = "user", content = "give me a list of gift idea for my girl friend")
)
In [3]:
response <- call_claude_api(
model = "claude-3-5-sonnet-20240620",
messages = messages,
max_tokens = 1024
)
# Display the assistant's response
cat(response$content[[1]]$text)