Claude 3

LLM
Claude
Author

Jong-Hoon Kim

Published

May 30, 2024

Testing Claude 3 with R

library(httr)
library(jsonlite)

# Function to make API request
prompt_claude <- function(prompt = NULL, 
                          api_key = NULL, 
                          model = "opus",
                          max_tokens = 1000) {
  if (is.null(api_key)) {
   stop("api_key must provided")
  }
  model <- grep(model, c("claude-3-haiku-20240307",
                         "claude-3-sonnet-20240229",
                         "claude-3-opus-20240229"), value=TRUE)
  if(length(model) == 0){
    stop("The model name is wrong. It must be one of the haiku, sonnet, and opus")
  }
  
  response <- httr::POST(
    url = "https://api.anthropic.com/v1/messages",
    httr::add_headers(`x-api-key` = api_key, 
                `anthropic-version` = "2023-06-01",
                `content-type` = "application/json"),
    encode = "json",
    body = jsonlite::toJSON(list(
     model = model,
     max_tokens = max_tokens,
     messages = list(list(role = "user", content = prompt))
    ), auto_unbox = TRUE)
 )
 content <- httr::content(response, as="text")
 json_data <- jsonlite::fromJSON(content, flatten = TRUE)
 response <- json_data$content$text
 
 return(response)
}

api_key <- Sys.getenv("CLAUDE_API_KEY") # api key was stored in the .Renviron file
res <- prompt_claude(prompt="The cat sat on the", api_key, model="haiku")
cat(res)