import gradio as gr from huggingface_hub import InferenceClient import random class GemmaChatApp: def __init__(self): self.models = [ "google/gemma-7b", "google/gemma-7b-it", "google/gemma-2b", "google/gemma-2b-it" ] self.clients = [ InferenceClient(self.models[0]), InferenceClient(self.models[1]), InferenceClient(self.models[2]), InferenceClient(self.models[3]), ] self.rand_val = random.randint(1, 1111111111111111) self.create_app() def format_prompt(self, message, history): prompt = "" if history: for user_prompt, bot_response in history: prompt += f"usuário{user_prompt}" prompt += f"modelo{bot_response}" prompt += f"usuário{message}modelo" return prompt def chat_inf(self, system_prompt, prompt, history, client_choice, seed, temp, tokens, top_p, rep_p, stream_output): client = self.clients[int(client_choice) - 1] if not history: history = [] generate_kwargs = dict( temperature=temp, max_new_tokens=tokens, top_p=top_p, repetition_penalty=rep_p, do_sample=True, seed=seed, ) formatted_prompt = self.format_prompt(f"{system_prompt}, {prompt}", history) stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=stream_output, details=True, return_full_text=False) output = "" for response in stream: output += response.token.text yield [(prompt, output)] history.append((prompt, output)) yield history def clear_fn(self): return None, None, None def create_app(self): # Function to create a guide HTML for the user def create_guide(): return """

Gemma Google LLM

Um conjunto de modelos leves e avançados, construídos a partir da mesma pesquisa e tecnologia utilizadas para criar os modelos Gemini.

Instruções:

  1. Insira seu prompt na caixa "Prompt".
  2. Opcionalmente, adicione um prompt de sistema na caixa "Prompt do Sistema".
  3. Escolha um modelo na lista suspensa "Modelos".
  4. Ajuste os parâmetros conforme necessário:
    • Temperatura: Controla a aleatoriedade da geração (valores mais baixos são mais determinísticos).
    • Top-P: Controla a diversidade da geração (valores mais baixos são mais restritos).
    • Penalidade de Repetição: Controla a penalidade para repetições na resposta gerada.
    • Máximo de Novos Tokens: Limita o número máximo de tokens gerados.
  5. Se desejar, marque "Semente Aleatória" para gerar uma semente aleatória.
  6. Clique em "Enviar" para gerar uma resposta do modelo.
  7. Clique em "Parar" a qualquer momento para interromper a conversa.
  8. Clique em "Limpar" para reiniciar a conversa.
  9. Marque "Saída em Tempo Real" para exibir a resposta do modelo em tempo real.
""" # With Gradio Blocks, create the app interface with gr.Blocks() as app: gr.HTML(create_guide()) # Display the guide chat_b = gr.Chatbot(height=500) with gr.Group(): with gr.Row(): with gr.Column(scale=3): inp = gr.Textbox(label="Prompt", placeholder="Digite seu prompt aqui") sys_inp = gr.TextArea(label="Prompt do Sistema (opcional)", placeholder="Opcional: Adicione um prompt de sistema aqui") with gr.Row(): with gr.Column(scale=2): btn = gr.Button("Enviar") with gr.Column(scale=1): with gr.Group(): stop_btn = gr.Button("Parar") clear_btn = gr.Button("Limpar") client_choice = gr.Dropdown(label="Modelos", type='index', choices={c: f"Model {i+1}" for i, c in enumerate(self.models)}, value=self.models[0], interactive=True) with gr.Column(scale=1): with gr.Group(): rand = gr.Checkbox(label="Semente Aleatória", value=True) seed = self.check_rand(rand, self.rand_val) tokens = gr.Slider(label="Número Máximo de Tokens", value=6400, minimum=0, maximum=8000, step=64, interactive=True, visible=True, info="O número máximo de tokens") temp = gr.Slider(label="Temperatura (Determinismo)", step=0.01, minimum=0.01, maximum=1.0, value=0.9) top_p = gr.Slider(label="Top-P (Diversidade)", step=0.01, minimum=0.01, maximum=1.0, value=0.9) rep_p = gr.Slider(label="Penalidade por Repetição", step=0.1, minimum=0.1, maximum=2.0, value=1.0) stream_output = gr.Checkbox(label="Saída em Tempo Real", value=True) go = btn.click(self.check_rand, [rand, seed], seed).then(self.chat_inf, [sys_inp, inp, chat_b, client_choice, seed, temp, tokens, top_p, rep_p, stream_output], chat_b) stop_btn.click(None, None, None, cancels=go) clear_btn.click(self.clear_fn, None, [inp, sys_inp, chat_b]) app.queue(default_concurrency_limit=10).launch() def check_rand(self, inp, val): if inp: return gr.Slider(label="Semente", minimum=1, maximum=1111111111111111, value=random.randint(1, 1111111111111111)) else: return gr.Slider(label="Semente", minimum=1, maximum=1111111111111111, value=int(val)) # Create an instance of the GemmaChatApp and launch the app gemma_chat_app = GemmaChatApp()