# Goal: Build an AI powered chat bot

import gradio as gr
from dotenv import load_dotenv
from openai import OpenAI
import json

load_dotenv()

client = OpenAI()

def save_history(history):
    with open("data.json", "w") as data:
        json.dump(history, data)

def load_history():
    with open("data.json", "r") as data:
        return json.load(data)

# Backend: Python
def echo(message, history):
    # LLM: OpenAI
    converstation_history = load_history()

    converstation_history.append({"role": "user", "content": message})

    completion = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=converstation_history
    )

    converstation_history.append({"role": "assistant", "content": completion.choices[0].message.content})

    save_history(converstation_history)

    return completion.choices[0].message.content

# Frontend: Gradio
demo = gr.ChatInterface(fn=echo, type="messages", examples=["I want to lear about LLMs", "What is NLP", "what is RAG"], title="LLM Mentor")
demo.launch()