JULIA-COHERE-API
Simon-Pierre Boucher
2024-09-14
In [1]:
using HTTP
using JSON
function call_cohere_api(
message::String;
chat_history::Union{Vector{Dict{String, Any}}, Nothing} = nothing,
model::String = "command-light-nightly",
temperature::Float64 = 0.3,
max_tokens::Int = 1000,
max_input_tokens::Int = 1000,
frequency_penalty::Float64 = 0.0,
presence_penalty::Float64 = 0.0,
k::Int = 0,
p::Float64 = 0.0,
preamble::Union{String, Nothing} = nothing
)
# Récupérer la clé API depuis les variables d'environnement
api_key = get(ENV, "COHERE_API_KEY", "")
if isempty(api_key)
error("API key not found in environment variables. Please set COHERE_API_KEY.")
end
url = "https://api.cohere.com/v1/chat"
headers = [
"Authorization" => "Bearer $api_key",
"Content-Type" => "application/json",
"Accept" => "application/json"
]
# Crée le dictionnaire pour le corps de la requête
data = Dict(
"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
)
# Ajoute les paramètres optionnels s'ils ne sont pas `nothing`
if chat_history !== nothing
data["chat_history"] = chat_history
end
if preamble !== nothing
data["preamble"] = preamble
end
json_data = JSON.json(data)
response = HTTP.post(url, headers; body = json_data)
if response.status != 200
error("API request failed: $(response.status) - $(String(response.body))")
end
result = JSON.parse(String(response.body))
return result
end
Out[1]:
In [2]:
# Exemple d'utilisation de la fonction
chat_history = [
Dict{String, Any}("message" => "Hello, who are you", "role" => "USER"),
Dict{String, Any}(
"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"
)
]
Out[2]:
In [3]:
response = call_cohere_api(
"give me a julia code for snake game";
chat_history = chat_history,
model = "command-light-nightly",
temperature = 0.3,
max_tokens = 2000,
max_input_tokens = 1000,
frequency_penalty = 0.0,
presence_penalty = 0.0,
k = 0,
p = 0.0,
preamble = "You are an AI-assistant chatbot. You are trained to assist users by providing thorough and helpful responses to their queries."
)
# Affiche la réponse du chatbot
println(response["text"])
In [ ]: