R - COHERE - API
Simon-Pierre Boucher
2024-09-14
In [1]:
library(httr)
library(jsonlite)
# Define the function
call_cohere_api <- function(
message,
chat_history = NULL,
model = "command-light-nightly",
temperature = 0.3,
max_tokens = 1000,
max_input_tokens = 1000,
frequency_penalty = 0,
presence_penalty = 0,
k = 0,
p = 0,
preamble = NULL
) {
# Get the API key from environment variables
api_key <- Sys.getenv("COHERE_API_KEY")
if (api_key == "") {
stop("API key not found in environment variables. Please set COHERE_API_KEY.")
}
url <- "https://api.cohere.com/v1/chat"
headers <- add_headers(
`Authorization` = paste("Bearer", api_key),
`Content-Type` = "application/json",
`Accept` = "application/json"
)
body <- list(
message = message,
model = model,
temperature = temperature,
max_tokens = max_tokens,
max_input_tokens = max_input_tokens,
frequency_penalty = frequency_penalty,
presence_penalty = presence_penalty,
k = k,
p = p
)
# Add optional parameters if they are not NULL
if (!is.null(chat_history)) {
body$chat_history <- chat_history
}
if (!is.null(preamble)) {
body$preamble <- preamble
}
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]:
chat_history <- list(
list(message = "allo", role = "USER"),
list(
message = "I'm your friendly AI chatbot assistant! I'm here to help you with questions, provide me with your queries, and I'll do my best to assist and provide helpful answers and information for you.",
role = "CHATBOT"
)
)
In [3]:
response <- call_cohere_api(
message = "give me a list of gift idea for my girl friend",
chat_history = chat_history,
model = "command-light-nightly",
temperature = 0.3,
max_tokens = 1000,
max_input_tokens = 1000,
frequency_penalty = 0,
presence_penalty = 0,
k = 0,
p = 0,
preamble = "You are an AI-assistant chatbot. You are trained to assist users by providing thorough and helpful responses to their queries."
)
# Display the chatbot's response
cat(response$text)