JULIA-MISTRAL-API
Simon-Pierre Boucher
2024-09-14

Julia Mistral

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]:
call_mistral_api (generic function with 1 method)
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]:
1-element Vector{Dict{String, Any}}:
 Dict("role" => "user", "content" => "give me a julia code for snake game")
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"])
Here's a simple implementation of the Snake game in Julia using the `Plots` package for graphics. This version will use the arrow keys to control the snake's direction.

```julia
using Plots

function snake_game()
    # Game settings
    width, height = 20, 20
    snake = [[10, 10], [10, 9], [10, 8]]
    direction = [0, 1]
    food = [rand(1:width), rand(1:height)]
    game_over = false

    # Game loop
    while !game_over
        # Clear the screen
        plot(size=(600, 600), grid=false, xlim=(0, width), ylim=(0, height), aspect_ratio=:equal)

        # Draw snake
        plot!(snake, color=:blue, lw=5)

        # Draw food
        scatter!([food], color=:red, ms=10)

        # Update snake position
        head = snake[1] + direction
        pushfirst!(snake, head)

        # Check for collision with food
        if head == food
            food = [rand(1:width), rand(1:height)]
        else
            pop!(snake)
        end

        # Check for collision with walls or snake body
        if !((1 <= head[1] <= width) && (1 <= head[2] <= height)) || head in snake[2:end]
            game_over = true
        end

        # Update direction based on user input
        if isdefined(:stdout, :in) && !isempty(stdout.in)
            key = read(stdout.in, Char)
            if key == '\e'
                read(stdout.in, Char) # Skip '['
                arrow = read(stdout.in, Char)
                direction = if arrow == 'A'
                    [0, -1]
                elseif arrow == 'B'
                    [0, 1]
                elseif arrow == 'C'
                    [1, 0]
                elseif arrow == 'D'
                    [-1, 0]
                else
                    direction
                end
            end
        end

        # Sleep for a short time to control game speed
        sleep(0.1)
    end

    println("Game Over!")
end

snake_game()
```

To run this code, make sure you have Julia and the `Plots` package installed. You can add the `Plots` package using the following command in the Julia REPL:

```julia
using Pkg
Pkg.add("Plots")
```

Then, save the code in a file with a `.jl` extension (e.g., `snake_game.jl`), and run it using the Julia command:

```sh
julia snake_game.jl
```

Use the arrow keys to control the snake's direction. The game will end when the snake collides with the walls or its own body.