import gradio as gr from huggingface_hub import InferenceClient import plotly.express as px # Inisialisasi client client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct") # Fungsi untuk menghasilkan plot acak def random_plot(): df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", size='petal_length', hover_data=['petal_width']) return fig # Fungsi untuk mencetak data suka/tidak suka def print_like_dislike(x: gr.LikeData): print(x.index, x.value, x.liked) # Fungsi untuk menambahkan pesan ke riwayat def add_message(history, message): if message["files"]: for x in message["files"]: history.append(((x,), None)) if message["text"] is not None: history.append((message["text"], None)) return history, gr.Textbox(value="", interactive=True) # Fungsi untuk menghubungkan dengan model Llama def chat_mem(message, chat_history): chat_history_role = [{"role": "system", "content": "Anda adalah Chat Bot milik Riswan Nopiyar, yang dirancang untuk membantu menjawab pertanyaan dan memberikan informasi dengan sopan dan akurat dalam bahasa Indonesia. Seluruh percakapan akan dilakukan dalam bahasa Indonesia."}] if chat_history: for user_msg, assistant_msg in chat_history: chat_history_role.append({"role": "user", "content": user_msg}) chat_history_role.append({"role": "assistant", "content": assistant_msg}) chat_history_role.append({"role": "user", "content": message}) if "siapa pembuat" in message.lower() or "siapa pencipta" in message.lower(): assistant_response = "Chatbot ini dibuat oleh Riswan Nopiyar. Jika Anda memiliki pertanyaan lain atau membutuhkan bantuan lebih lanjut, jangan ragu untuk bertanya." else: chat_completion = client.chat_completion( messages=chat_history_role, max_tokens=500, ) assistant_response = chat_completion.choices[0].message.content chat_history_role.append({"role": "assistant", "content": assistant_response}) modified = [msg["content"] for msg in chat_history_role] chat_history = [(modified[i * 2 + 1], modified[i * 2 + 2]) for i in range(len(modified) // 2)] return "", chat_history fig = random_plot() # Membuat antarmuka Gradio with gr.Blocks(fill_height=True) as demo: chatbot = gr.Chatbot( elem_id="chatbot", bubble_full_width=False, scale=1, ) chat_input = gr.Textbox(interactive=True, placeholder="Enter message...", show_label=False) chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input]) bot_msg = chat_msg.then(chat_mem, inputs=[chat_input, chatbot], outputs=[chat_input, chatbot], api_name="bot_response") bot_msg.then(lambda: gr.Textbox(interactive=True), None, [chat_input]) chatbot.like(print_like_dislike, None, None) demo.launch()