R - ANTHROPIC - API
Simon-Pierre Boucher
2024-09-14

R Powered by R Made with R Anthropic

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)
Here's a list of gift ideas for your girlfriend:

1. Personalized jewelry (necklace, bracelet, or ring)
2. Spa day or massage gift certificate
3. Tickets to a concert, show, or event she'd enjoy
4. Customized photo album or scrapbook
5. High-quality leather handbag or wallet
6. Stylish smartwatch or fitness tracker
7. Comfortable and luxurious pajama set
8. Subscription box tailored to her interests (beauty, books, food, etc.)
9. Romantic weekend getaway
10. Handmade crafts or artwork
11. Gourmet chocolate or food basket
12. Trendy sunglasses or accessories
13. Luxury skincare or makeup set
14. Cozy throw blanket or weighted blanket
15. Kindle or e-reader with her favorite books preloaded
16. Polaroid camera or instant photo printer
17. Cooking class for two
18. Personalized star map of a significant date
19. High-quality noise-canceling headphones
20. Indoor plant or herb garden kit
21. Customized phone case or tech accessories
22. Luxury candle set or essential oil diffuser
23. Stylish backpack or tote bag
24. Unique piece of art or home decor
25. Experience gift (hot air balloon ride, wine tasting, etc.)

Remember to consider her personal interests and preferences when selecting a gift.