import gradio as gr
from huggingface_hub import InferenceClient
import os

"""
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
"""
import requests

from openai import OpenAI, AsyncOpenAI

clients = {}
token = os.getenv('API_KEY')

clients['32B-QWQ'] = [
    OpenAI(api_key=token, base_url=os.getenv('RUADAPT_UNIVERSAL_URL')), 
    'RefalMachine/RuadaptQwen2.5-32B-QWQ-Beta'
]

def respond(
    message,
    history: list[tuple[str, str]],
    model_name,
    system_message,
    max_tokens,
    temperature,
    top_p,
    repetition_penalty
):
    messages = []
    if len(system_message.strip()) > 0:
        messages = [{"role": "system", "content": system_message}]

    for val in history:
        if val[0]:
            messages.append({"role": "user", "content": val[0]})
        if val[1]:
            messages.append({"role": "assistant", "content": val[1]})

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

    response = ""

    res = clients[model_name][0].chat.completions.create(
        model=clients[model_name][1],
        messages=messages,
        temperature=temperature,
        top_p=top_p,
        max_tokens=max_tokens,
        stream=True,
        extra_body={
            "repetition_penalty": repetition_penalty,
            "add_generation_prompt": True,
        }
    )
    #print(res)
    for message in res:
        #print(message)
        token = message.choices[0].delta.content
        #if token in ['<think>', '</think>']:
        #    token = token.replace('<', '\\<').replace('>', '\\>')
        #print(type(token))
        response += token
        if '<think>' in response:
            response = response.replace('<think>', '\\<think\\>')

        if '</think>' in response:
            response = response.replace('</think>', '\\</think\\>')
        #print(response)
        yield response


"""
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
"""
options = ['32B-QWQ']
options = options[:1]
system_old = "You are a helpful and harmless assistant. You should think step-by-step. First, reason (the user does not see your reasoning), then give your final answer."
system_new = "Ты Руадапт - полезный и дружелюбный интеллектуальный ассистент для помощи пользователям в их вопросах."
system_new2 = "Ты — Руадапт, русскоязычный автоматический ассистент. Ты разговариваешь с людьми и помогаешь им."
latex_delimiters = [{
    "left": "\\(",
    "right": "\\)",
    "display": True
}, {
    "left": "\\begin\{equation\}",
    "right": "\\end\{equation\}",
    "display": True
}, {
    "left": "\\begin\{align\}",
    "right": "\\end\{align\}",
    "display": True
}, {
    "left": "\\begin\{alignat\}",
    "right": "\\end\{alignat\}",
    "display": True
}, {
    "left": "\\begin\{gather\}",
    "right": "\\end\{gather\}",
    "display": True
}, {
    "left": "\\begin\{CD\}",
    "right": "\\end\{CD\}",
    "display": True
}, {
    "left": "\\[",
    "right": "\\]",
    "display": True
}, {"left": "$$", "right": "$$", "display": True}]
chatbot = gr.Chatbot(label="Chatbot",
                scale=1,
                height=400,
                latex_delimiters=latex_delimiters)
demo = gr.ChatInterface(
    respond,
    additional_inputs=[
        gr.Radio(choices=options, label="Model:", value=options[0]),
        gr.Textbox(value="", label="System message"),
        gr.Slider(minimum=1, maximum=4096*6, value=4096, step=2, label="Max new tokens"),
        gr.Slider(minimum=0.0, maximum=2.0, value=0.0, step=0.1, label="Temperature"),
        gr.Slider(
            minimum=0.1,
            maximum=1.0,
            value=0.95,
            step=0.05,
            label="Top-p (nucleus sampling)",
        ),
        gr.Slider(minimum=0.9, maximum=1.5, value=1.05, step=0.05, label="repetition_penalty"),
    ],
    chatbot=chatbot,
    concurrency_limit=10
)


if __name__ == "__main__":
    demo.launch(share=True)