JULIA-MISTRAL-API
Simon-Pierre Boucher
2024-09-14
In [1]:
using HTTP
using JSON
function call_mistral_api(
model::String,
messages::Vector{Dict{String, Any}}; # Les arguments supplémentaires sont des keywords
temperature::Float64 = 0.7,
top_p::Float64 = 1.0,
max_tokens::Union{Int, Nothing} = nothing,
min_tokens::Union{Int, Nothing} = nothing,
stream::Bool = false,
stop::Union{String, Nothing} = nothing,
random_seed::Union{Int, Nothing} = nothing,
response_format::Union{String, Nothing} = nothing,
tools::Union{Vector{String}, Nothing} = nothing,
tool_choice::String = "auto",
safe_prompt::Bool = false
)
# Récupérer la clé API depuis les variables d'environnement
api_key = get(ENV, "MISTRAL_API_KEY", "")
if isempty(api_key)
error("API key not found in environment variables. Please set MISTRAL_API_KEY.")
end
url = "https://api.mistral.ai/v1/chat/completions"
headers = [
"Authorization" => "Bearer $api_key",
"Content-Type" => "application/json"
]
# Crée le dictionnaire de données pour la requête
data = Dict(
"model" => model,
"messages" => messages,
"temperature" => temperature,
"top_p" => top_p,
"stream" => stream,
"tool_choice" => tool_choice,
"safe_prompt" => safe_prompt
)
# Ajoute les paramètres optionnels s'ils ne sont pas `nothing`
if max_tokens !== nothing
data["max_tokens"] = max_tokens
end
if min_tokens !== nothing
data["min_tokens"] = min_tokens
end
if stop !== nothing
data["stop"] = stop
end
if random_seed !== nothing
data["random_seed"] = random_seed
end
if response_format !== nothing
data["response_format"] = response_format
end
if tools !== nothing
data["tools"] = tools
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
messages = [
Dict{String, Any}("role" => "user", "content" => "give me a julia code for snake game")
]
Out[2]:
In [3]:
# Appeler la fonction pour obtenir une réponse
response = call_mistral_api(
"mistral-large-latest", # Remplacez par le modèle que vous souhaitez utiliser
messages;
temperature = 0.7,
top_p = 1.0,
max_tokens = 2024
)
# Afficher la réponse de l'assistant
println(response["choices"][1]["message"]["content"])