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

Julia Cohere

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]:
call_cohere_api (generic function with 1 method)
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]:
2-element Vector{Dict{String, Any}}:
 Dict("role" => "USER", "message" => "Hello, who are you")
 Dict("role" => "CHATBOT", "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.")
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"])
I can help you with creating a simple Snake Game using Python. Here's simple code to get you started with creating the basic structure: 

```python
import pygame
import random

# Initialize pygame
pygame.pygame_init()

# Set up display parameters
screen_width = 640
screen_height = 480
screen = pygame.surverse(screen_width, screen_height)

# Snake and food properties
snake_speed = 2
snake_direction = [1, 0]  # Vertical movement
snake_position = [50, screen_height - 30]
snake_color = (255, 0, 0)
food_position = [random.randint(screen_width -x), random.randint(screen_height)]
food_color = (0, 128, 255)

# Game loop
running = True
while running:
    # Handle input and movement
    for event in pygame.event.get():
        new():
        keys = event.keys()
    
    if event.keydown(py) and event.key == pygame.K_ES):
        new_key = pygame.K_UP:
        snake_position[1] -= snake_speed
    if snake_position[1] < 0 or snake_position[1] > screen_height:
        snake_direction[1] = -1  # Reverse direction if out of screen
    if event.key == pygame.K_DOWN:
        snake_position[1] += snake_speed
    if snake_position[0] < 0 or snake_position[0] > screen_width:
        snake_direction[0] = -1  # Reverse direction if out of screen
    if event.key == pygame.K_LEFT:
        snake_position[0] += snake_speed
    if snake_position[0] < 0 or snake_position[0] > screen_width or snake_position[1] < 0 or snake_position[1] > screen_height:
        continue  # Stop snake if outside boundaries

    # Check for food and collision
    if food_position[0] == snake_position[0] and food_position[1] == snake_position[1]:
        print("Food found!")
        score += 1  # Increase score

    # Check for collision
    for x in range(screen_width):
        for y in range(screen_height):
            if x == snake_position[0] and y == snake_position[1]:
                print("Snake collided with itself!")
                running = False  # Game over

    # Draw the game
    screen.fill(black)
    rect(snake_position[0], snake_position[1], 20, 20, snake_color), 1)
    pygame.draw.rect(screen,rect(food_position[0], food_position[1], 20, 20, food_color), 1)

# Update the display
pygame.display()

# Loop continues
running = False
```

This is a basic structure for a simple Snake game. You can expand and improve it with various features and improvements.
In [ ]: