Skip to content

Instantly share code, notes, and snippets.

@htlin222
Created January 30, 2024 11:56
Show Gist options
  • Save htlin222/4ae28eb11c8f772abe000d49bdabdb59 to your computer and use it in GitHub Desktop.
Save htlin222/4ae28eb11c8f772abe000d49bdabdb59 to your computer and use it in GitHub Desktop.
send chatGPT request in R
# desc: send chatGPT request in R
# date: "2024-01-30"
# install.packages("dotenv")
# install.packages("httr")
# install.packages("jsonlite")
send_chatgpt_request <- function(system_message, user_message) {
library(httr)
library(jsonlite)
library(dotenv)
load_dot_env()
api_key <- Sys.getenv("OPENAI_API_KEY")
url <- "https://api.openai.com/v1/chat/completions"
body <- list(
model = "gpt-3.5-turbo",
messages = list(
list(role = "system", content = system_message),
list(role = "user", content = user_message)
)
)
response <- POST(url,
body = toJSON(body, auto_unbox = TRUE),
add_headers(
`Authorization` = paste("Bearer", api_key),
`Content-Type` = "application/json"
)
)
parsed_response <- fromJSON(content(response, "text", encoding = "UTF-8"))
# 提取 content
if (is.data.frame(parsed_response$choices)) {
message_df <- parsed_response$choices$message
if (is.data.frame(message_df)) {
return(message_df$content[1])
}
}
return(NULL)
}
@htlin222
Copy link
Author

  1. create a file named.env in same directory, and add OPENAI_API_KEY=sk-xxxx
  2. in other Rscript, you can load this function by source("chatgpt.R")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment