Spaces:
Sleeping
Sleeping
File size: 1,510 Bytes
0f00de7 952ff27 0f00de7 952ff27 0f00de7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | # llm_api.R
library(httr)
library(jsonlite)
# Function to send a chat completion request to the Groq API
send_chat_completion <- function(api_key, model, system_message, messages, max_tokens = NULL, temperature = 1, top_p = 1) {
url <- "https://api.groq.com/openai/v1/chat/completions"
# Set up the headers
headers <- add_headers(
`Content-Type` = "application/json",
`Authorization` = paste("Bearer", api_key)
)
# Create the request body
body <- list(
model = model,
messages = append(list(list(role = "system", content = system_message)), messages),
temperature = temperature,
top_p = top_p
)
if (!is.null(max_tokens)) {
body$max_tokens <- max_tokens
}
# Convert body to JSON
body_json <- toJSON(body, auto_unbox = TRUE, pretty = TRUE)
# Send the POST request
response <- POST(url, headers, body = body_json)
# Get response content as text
response_content <- content(response, as = "text", encoding = "UTF-8")
# Check for HTTP errors
if (http_error(response)) {
error_message <- paste("API request failed [", status_code(response), "]: ", response_content)
stop(error_message)
}
# Parse the response JSON without flattening
response_json <- fromJSON(response_content, simplifyDataFrame = FALSE)
# Return a list containing the response JSON, request body, and response content
return(list(
response_json = response_json,
request_body = body_json,
response_text = response_content
))
}
|