library(httr)
library(jsonlite)
# Function to make API request
<- function(prompt = NULL,
prompt_claude api_key = NULL,
model = "opus",
max_tokens = 1000) {
if (is.null(api_key)) {
stop("api_key must provided")
}<- grep(model, c("claude-3-haiku-20240307",
model "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")
}
<- httr::POST(
response url = "https://api.anthropic.com/v1/messages",
::add_headers(`x-api-key` = api_key,
httr`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)
),
)<- httr::content(response, as="text")
content <- jsonlite::fromJSON(content, flatten = TRUE)
json_data <- json_data$content$text
response
return(response)
}
<- Sys.getenv("CLAUDE_API_KEY") # api key was stored in the .Renviron file
api_key <- prompt_claude(prompt="The cat sat on the", api_key, model="haiku")
res cat(res)
Claude 3
LLM
Claude
Testing Claude 3 with R