R - MISTRAL-API
Simon-Pierre Boucher
2024-09-14
In [1]:
library(httr)
library(jsonlite)
# Define the function
call_mistral_api <- function(
model,
messages,
temperature = 0.7,
top_p = 1,
max_tokens = NULL,
min_tokens = NULL,
stream = FALSE,
stop = NULL,
random_seed = NULL,
response_format = NULL,
tools = NULL,
tool_choice = "auto",
safe_prompt = FALSE
) {
# Get the API key from environment variables
api_key <- Sys.getenv("MISTRAL_API_KEY")
if (api_key == "") {
stop("API key not found in environment variables. Please set MISTRAL_API_KEY.")
}
url <- "https://api.mistral.ai/v1/chat/completions"
headers <- add_headers(
`Authorization` = paste("Bearer", api_key),
`Content-Type` = "application/json"
)
body <- list(
model = model,
messages = messages,
temperature = temperature,
top_p = top_p,
stream = stream,
tool_choice = tool_choice,
safe_prompt = safe_prompt
)
# Add optional parameters if they are not NULL
if (!is.null(max_tokens)) {
body$max_tokens <- max_tokens
}
if (!is.null(min_tokens)) {
body$min_tokens <- min_tokens
}
if (!is.null(stop)) {
body$stop <- stop
}
if (!is.null(random_seed)) {
body$random_seed <- random_seed
}
if (!is.null(response_format)) {
body$response_format <- response_format
}
if (!is.null(tools)) {
body$tools <- tools
}
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_mistral_api(
model = "mistral-large-latest", # Replace with the model ID you wish to use
messages = messages,
temperature = 0.7,
top_p = 1,
max_tokens = 2024
)
# Display the assistant's response
cat(response$choices[[1]]$message$content)