# Load necessary R libraries
library(httr) # For making HTTP requests to the OpenAI API
library(jsonlite) # For encoding and decoding JSON data
setwd("~/data/llmclass/")

# OpenAI API key setup
api_key <- Sys.getenv("OPENAI_API_KEY")
Sys.setenv(OPENAI_API_KEY = api_key)
chat_url <- "https://api.openai.com/v1/chat/completions" # API endpoint for completions

# Simulating a series of "user" inputs as social media posts on work from home policies.
# Each post is considered a message in the conversation with the role 'system', indicating provided data.
messages <- list(
  list(role = "system", content = "Social Media Excerpt 1: 'I've been working from home since the pandemic started, and I've never been happier. The flexibility has improved my work-life balance significantly.'"),
  list(role = "system", content = "Social Media Excerpt 2: 'Work from home is not for everyone. I miss the office energy and find it hard to separate work from personal life.'"),
  list(role = "system", content = "Social Media Excerpt 3: 'I appreciate the option to work remotely, but I wish companies would provide more support for home offices.'"),
  list(role = "system", content = "Social Media Excerpt 4: 'Working from home has been great for productivity, but I miss the social interaction of the workplace.'"),
  list(role = "user", content = "Can you summarize the general sentiment and identify common themes from these excerpts?")
)

# Preparing the body of the request. Specifying the model and incorporating the messages.
body <- list(
  model = "gpt-4-turbo", # Assuming gpt-4-turbo is available; replace with the current suitable model.
  messages = messages
)

body_json <- toJSON(body, auto_unbox = TRUE)

# Making the POST request to the OpenAI API for chat completions
response <- POST(
  url = chat_url,
  add_headers(
    `Authorization` = paste("Bearer", api_key),
    `Content-Type` = "application/json"
  ),
  body = body_json,
  encode = "json"
)

# Parsing and printing the response
if (http_status(response)$category == "success") {
  content <- fromJSON(rawToChar(response$content))
  cat("API's Summary and Themes:\n")
  for (message in content$choices[[1]]$message) {
    print(message$content)
  }
} else {
  cat(paste("Failed to complete request. Status code:", http_status(response)$reason, "\nContent:", rawToChar(response$content)))
}