Spaces:
Sleeping
Sleeping
Download app.py from rvdbra/EinbuergDemoforTesting2: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/spaces/rvdbra/EinbuergDemoforTesting2/resolve/main/app.py
- Command line
-
hf download hf://spaces/rvdbra/EinbuergDemoforTesting2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/rvdbra/EinbuergDemoforTesting2/resolve/main/app.py
16.5 kB
| import os | |
| import uuid | |
| from datetime import datetime | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| from supabase import create_client | |
| from langchain_core.runnables import RunnableConfig | |
| from typing import TypedDict, List, Optional, Annotated | |
| from langchain_core.messages import BaseMessage, AIMessage, HumanMessage, SystemMessage | |
| from langgraph.graph.message import add_messages | |
| from langgraph.graph import StateGraph, END | |
| from langchain_openai import OpenAIEmbeddings | |
| from langchain.chat_models import init_chat_model | |
| from langchain_pinecone import Pinecone as LangchainPinecone | |
| from langchain_core.chat_history import BaseChatMessageHistory | |
| from langchain_core.messages import messages_from_dict, messages_to_dict | |
| # --- Supabase Setup --- | |
| SUPABASE_URL = os.getenv("SUPABASE_URL") | |
| SUPABASE_KEY = os.getenv("SUPABASE_KEY") | |
| supabase = create_client(SUPABASE_URL, SUPABASE_KEY) | |
| # --- Custom State --- | |
| class CustomState(TypedDict): | |
| messages: Annotated[List[BaseMessage], add_messages] | |
| user_id: str | |
| chat_history: Optional[List[List[str]]] | |
| # --- AI Model --- | |
| if not os.environ.get("OPENAI_API_KEY"): | |
| os.environ["OPENAI_API_KEY"] = input("Enter API key for OpenAI: ") | |
| llm = init_chat_model("gpt-4.1", model_provider="openai", temperature=0.0) | |
| # --- Vector Store --- | |
| pinecone_api_key = os.getenv("PINECONE_API_KEY", "").strip() | |
| pinecone_index_name = os.getenv("PINECONE_INDEX_NAME", "").strip() | |
| embeddings = OpenAIEmbeddings(model="text-embedding-3-large") | |
| vector_store = LangchainPinecone( | |
| index_name=pinecone_index_name, | |
| embedding=embeddings, | |
| pinecone_api_key=pinecone_api_key | |
| ) | |
| # --- Supabase Chat Memory --- | |
| class SupabaseChatMessageHistory(BaseChatMessageHistory): | |
| def __init__(self, user_id: str, supabase_client): | |
| self.user_id = user_id | |
| self.supabase = supabase_client | |
| def messages(self): | |
| response = self.supabase.table("chat_memory").select("*").eq("user_id", self.user_id).execute() | |
| data = response.data[0] if response.data else {} | |
| return messages_from_dict(data.get("messages", [])) | |
| def add_message(self, message): | |
| all_messages = messages_to_dict(self.messages + [message]) | |
| self.supabase.table("chat_memory").upsert({ | |
| "user_id": self.user_id, | |
| "messages": all_messages | |
| }).execute() | |
| def add_user_message(self, content: str): | |
| self.add_message(HumanMessage(content=content)) | |
| def add_ai_message(self, content: str): | |
| self.add_message(AIMessage(content=content)) | |
| def clear(self): | |
| self.supabase.table("chat_memory").delete().eq("user_id", self.user_id).execute() | |
| class MemoryStore: | |
| def get_memory(self, user_id: str): | |
| return SupabaseChatMessageHistory(user_id, supabase) | |
| store = MemoryStore() | |
| # --- Logging --- | |
| def log_interaction_cloud(user_id: str, question: str, answer: str): | |
| payload = { | |
| "user_id": user_id, | |
| "question": question, | |
| "answer": answer, | |
| "timestamp": datetime.utcnow().isoformat(), | |
| } | |
| try: | |
| res = supabase.table("logs").insert(payload).execute() | |
| print("[Supabase Log Success]:", res.data) | |
| except Exception as e: | |
| print("[Supabase Log Error]:", e) | |
| # --- Retrieval --- | |
| def retrieve(query: str): | |
| retrieved_docs = vector_store.similarity_search(query, k=6) | |
| serialized = "\n\n".join( | |
| (f"Source: {doc.metadata}\n" f"Content: {doc.page_content}") | |
| for doc in retrieved_docs | |
| ) | |
| return serialized, retrieved_docs | |
| # --- System Message --- | |
| SYSTEM_MESSAGE_TEXT = ( | |
| "You are Einbürgerungs-Helfer, a highly skilled, friendly, and helpful administrative assistant for naturalization matters in Germany." | |
| " You only support the following languages: German, English, Turkish, and Arabic." | |
| " You MUST always respond in the language of the user's last message." | |
| " If a user sends a message in an unsupported language, politely inform them with the following message:" | |
| " 'Bitte stellen Sie Ihre Frage auf Deutsch, Englisch, Türkisch oder Arabisch.'" | |
| " Your sole purpose is to assist individuals who are eligible for German naturalization but have not yet applied." | |
| " You only answer questions directly related to the current naturalization process in Germany." | |
| " You do not assist with completing applications or submitting them." | |
| " Your answers must be based solely on the provided context. Do NOT generate answers from your own knowledge." | |
| " Your responses must always be accurate, concise, and easy to understand." | |
| " Never hallucinate, never go beyond the topic of naturalization, and never share information that is false or misleading." | |
| " If you do not have enough knowledge to answer a question based on the provided context, respond with:" | |
| " 'I do not have enough knowledge to answer your question accurately. Please email your question to SBD-Umfrage@polsoz.fu-berlin.de, and we will respond as soon as possible.'" | |
| " If a user uses toxic, offensive, or inappropriate language, kindly ask them to rephrase their question" | |
| " and explain that such behavior is not acceptable." | |
| ) | |
| def generate_user_id(): | |
| return "user_" + uuid.uuid4().hex[:6] | |
| def query_or_respond(state: CustomState) -> CustomState: | |
| user_id = state.get("user_id") or generate_user_id() | |
| human_messages = [m for m in state["messages"] if m.type == "human"] | |
| latest_user_msg = human_messages[-1] | |
| memory = store.get_memory(user_id) | |
| history = memory.messages[-5:] | |
| retrieved_text, _ = retrieve(latest_user_msg.content) | |
| context = SystemMessage(SYSTEM_MESSAGE_TEXT + "\n\nRetrieved Context:\n" + retrieved_text) | |
| prompt = [context] + history + [latest_user_msg] | |
| response = llm.invoke(prompt) | |
| memory.add_user_message(latest_user_msg.content) | |
| memory.add_ai_message(response.content) | |
| log_interaction_cloud(user_id, latest_user_msg.content, response.content) | |
| return {**state, "messages": [response], "user_id": user_id} | |
| # --- Graph --- | |
| graph_builder = StateGraph(CustomState) | |
| graph_builder.add_node("query_or_respond", query_or_respond) | |
| graph_builder.set_entry_point("query_or_respond") | |
| graph_builder.add_edge("query_or_respond", END) | |
| graph = graph_builder.compile() | |
| import gradio as gr | |
| import time | |
| import re | |
| # Translation dictionary for UI elements | |
| translations = { | |
| "Deutsch": { | |
| "user_id_label": "Benutzer-ID (User ID)", | |
| "user_id_placeholder": "z.B. user_123", | |
| "clear_btn": "🗑️ Verlauf löschen", | |
| "chatbot_label": "Chat", | |
| "msg_input_label": "Deine Nachricht", | |
| "msg_input_placeholder": "Frage eingeben...", | |
| "submit_btn": "Senden", | |
| "description": """ | |
| ### Was ist **Einbürgerungs-Helfer**? | |
| **Deutsch:** Einbürgerungs-Helfer hilft dir, den Weg zur deutschen Staatsangehörigkeit zu verstehen – einfach, mehrsprachig, datenschutzfreundlich. | |
| """ | |
| }, | |
| "English": { | |
| "user_id_label": "User ID", | |
| "user_id_placeholder": "e.g. user_123", | |
| "clear_btn": "🗑️ Clear History", | |
| "chatbot_label": "Chat", | |
| "msg_input_label": "Your Message", | |
| "msg_input_placeholder": "Enter your question...", | |
| "submit_btn": "Send", | |
| "description": """ | |
| ### What is **Einbürgerungs-Helfer**? | |
| **English:** Einbürgerungs-Helfer helps you understand the path to German citizenship – simple, multilingual, privacy-friendly. | |
| """ | |
| }, | |
| "Türkçe": { | |
| "user_id_label": "Kullanıcı Kimliği (User ID)", | |
| "user_id_placeholder": "ör. user_123", | |
| "clear_btn": "🗑️ Geçmişi Temizle", | |
| "chatbot_label": "Sohbet", | |
| "msg_input_label": "Mesajınız", | |
| "msg_input_placeholder": "Sorunuzu yazın...", | |
| "submit_btn": "Gönder", | |
| "description": """ | |
| ### **Einbürgerungs-Helfer** nedir? | |
| **Türkçe:** Einbürgerungs-Helfer, Almanya vatandaşlığına giden yolu anlamanıza yardımcı olur – basit, çok dilli ve gizlilik dostu. | |
| """ | |
| }, | |
| "العربية": { | |
| "user_id_label": "معرف المستخدم (User ID)", | |
| "user_id_placeholder": "مثال: user_123", | |
| "clear_btn": "🗑️ مسح السجل", | |
| "chatbot_label": "الدردشة", | |
| "msg_input_label": "رسالتك", | |
| "msg_input_placeholder": "اكتب سؤالك...", | |
| "submit_btn": "إرسال", | |
| "description": """ | |
| ### ما هو **مساعد التجنيس**؟ | |
| **العربية:** مساعد التجنيس يساعدك على فهم طريق الحصول على الجنسية الألمانية – بسيط، متعدد اللغات، ويحترم الخصوصية. | |
| """ | |
| } | |
| } | |
| # Language update function | |
| def update_language(lang): | |
| t = translations[lang] | |
| rtl_style = "" | |
| if lang == "العربية": | |
| rtl_style = """ | |
| <style> | |
| body, .gradio-container, .gr-block, .gr-textbox, .gr-button, textarea, label, h1, h2, h3, h4, p, div { | |
| direction: rtl !important; | |
| text-align: right !important; | |
| } | |
| </style> | |
| """ | |
| else: | |
| rtl_style = """ | |
| <style> | |
| body, .gradio-container, .gr-block, .gr-textbox, .gr-button, textarea, label, h1, h2, h3, h4, p, div { | |
| direction: ltr !important; | |
| text-align: left !important; | |
| } | |
| </style> | |
| """ | |
| return ( | |
| gr.update(value=t["description"]), | |
| gr.update(label=t["user_id_label"], placeholder=t["user_id_placeholder"]), | |
| gr.update(value=t["clear_btn"]), | |
| gr.update(label=t["chatbot_label"]), | |
| gr.update(label=t["msg_input_label"], placeholder=t["msg_input_placeholder"]), | |
| gr.update(value=t["submit_btn"]), | |
| gr.update(value=t["submit_btn"]), | |
| gr.update(value=rtl_style) | |
| ) | |
| def clear_history(user_id_state): | |
| """Clear chat history using your existing store implementation""" | |
| if user_id_state: | |
| store.get_memory(user_id_state).clear() | |
| # Return initial welcome message in the new format | |
| initial_message = [ | |
| { | |
| "role": "assistant", | |
| "content": "Ich bin hier, um Ihnen bei allen Fragen zur Einbürgerung in Deutschland zu helfen.\nLassen Sie uns loslegen – wie kann ich Ihnen heute helfen?" | |
| } | |
| ] | |
| return initial_message, user_id_state, "", user_id_state | |
| def user_message_handler(user_message, chat_history, user_id_input, user_id_state): | |
| """Handle user message and add it to chat history""" | |
| if not user_message: | |
| return "", chat_history, user_id_input, user_id_state | |
| # Add user message to history | |
| chat_history.append({"role": "user", "content": user_message}) | |
| return "", chat_history, user_id_input, user_id_state | |
| def bot_response_handler(chat_history, user_id_input, user_id_state): | |
| """Generate streaming bot response with smart formatting delays - Primary Method""" | |
| if not chat_history or chat_history[-1]["role"] != "user": | |
| return chat_history, user_id_state | |
| user_id = user_id_state or user_id_input or generate_user_id() | |
| user_message = chat_history[-1]["content"] | |
| # Use your existing LangGraph implementation | |
| state: CustomState = { | |
| "messages": [HumanMessage(content=user_message)], | |
| "user_id": user_id, | |
| "chat_history": None | |
| } | |
| config = RunnableConfig(configurable={"session_id": user_id}) | |
| try: | |
| # Show thinking indicator first | |
| chat_history.append({"role": "assistant", "content": "💭 Einen Moment..."}) | |
| yield chat_history, user_id | |
| # Invoke your existing graph | |
| final_state = graph.invoke(state, config=config) | |
| bot_response = final_state["messages"][-1].content | |
| # Smart chunk streaming - preserves formatting blocks | |
| # This regex splits on double newlines or before list markers | |
| chunks = re.split(r'(\n\n|\n(?=[*\-•]\s|\d+\.\s))', bot_response) | |
| chunks = [chunk for chunk in chunks if chunk.strip()] | |
| # Reset content | |
| chat_history[-1]["content"] = "" | |
| current_content = "" | |
| for chunk in chunks: | |
| current_content += chunk | |
| chat_history[-1]["content"] = current_content | |
| # Longer delay for formatting blocks | |
| if chunk.startswith('\n\n') or re.match(r'\n?[*\-•]\s|\d+\.\s', chunk): | |
| time.sleep(0.2) # Pause before new sections/lists | |
| else: | |
| time.sleep(0.1) # Regular content | |
| yield chat_history, user_id | |
| # Final update to ensure complete message is shown | |
| chat_history[-1]["content"] = bot_response | |
| yield chat_history, user_id | |
| except Exception as e: | |
| # Handle errors gracefully | |
| error_message = f"Entschuldigung, es gab einen Fehler bei der Verarbeitung Ihrer Anfrage: {str(e)}" | |
| chat_history[-1]["content"] = error_message | |
| yield chat_history, user_id | |
| # Custom CSS for better markdown formatting | |
| custom_css = """ | |
| .message.bot .message-body { | |
| white-space: pre-wrap !important; | |
| line-height: 1.5 !important; | |
| } | |
| .message.bot .message-body ul, .message.bot .message-body ol { | |
| margin: 0.5em 0 !important; | |
| padding-left: 1.5em !important; | |
| } | |
| .message.bot .message-body li { | |
| margin: 0.25em 0 !important; | |
| } | |
| """ | |
| # Gradio UI | |
| with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), css=custom_css) as iface: | |
| description_md = gr.Markdown(translations["Deutsch"]["description"]) | |
| rtl_style_html = gr.HTML(visible=False) # Used to inject direction style | |
| # Language selector BELOW the description | |
| language_selector = gr.Dropdown( | |
| choices=["Deutsch", "English", "Türkçe", "العربية"], | |
| value="Deutsch", | |
| label="Sprache / Language / Dil / اللغة" | |
| ) | |
| with gr.Row(): | |
| user_id_input = gr.Textbox( | |
| label=translations["Deutsch"]["user_id_label"], | |
| placeholder=translations["Deutsch"]["user_id_placeholder"], | |
| lines=1 | |
| ) | |
| clear_btn = gr.Button(translations["Deutsch"]["clear_btn"]) | |
| user_id_state = gr.State(value="") | |
| # Updated chatbot with type="messages" for streaming support | |
| chatbot = gr.Chatbot( | |
| label=translations["Deutsch"]["chatbot_label"], | |
| show_copy_button=True, | |
| type="messages", # This enables the new message format | |
| value=[ | |
| { | |
| "role": "assistant", | |
| "content": "Ich bin hier, um Ihnen bei allen Fragen zur Einbürgerung in Deutschland zu helfen.\nLassen Sie uns loslegen – wie kann ich Ihnen heute helfen?" | |
| } | |
| ] | |
| ) | |
| msg_input = gr.Textbox( | |
| placeholder=translations["Deutsch"]["msg_input_placeholder"], | |
| label=translations["Deutsch"]["msg_input_label"], | |
| lines=1, | |
| value="" | |
| ) | |
| with gr.Row(): | |
| submit_btn = gr.Button(translations["Deutsch"]["submit_btn"], variant="primary") | |
| # Chain the user message handler with the bot response handler | |
| submit_btn.click( | |
| fn=user_message_handler, | |
| inputs=[msg_input, chatbot, user_id_input, user_id_state], | |
| outputs=[msg_input, chatbot, user_id_input, user_id_state], | |
| queue=False | |
| ).then( | |
| fn=bot_response_handler, | |
| inputs=[chatbot, user_id_input, user_id_state], | |
| outputs=[chatbot, user_id_state] | |
| ) | |
| msg_input.submit( | |
| fn=user_message_handler, | |
| inputs=[msg_input, chatbot, user_id_input, user_id_state], | |
| outputs=[msg_input, chatbot, user_id_input, user_id_state], | |
| queue=False | |
| ).then( | |
| fn=bot_response_handler, | |
| inputs=[chatbot, user_id_input, user_id_state], | |
| outputs=[chatbot, user_id_state] | |
| ) | |
| clear_btn.click( | |
| fn=clear_history, | |
| inputs=[user_id_state], | |
| outputs=[chatbot, user_id_input, msg_input, user_id_state], | |
| queue=False | |
| ) | |
| language_selector.change( | |
| fn=update_language, | |
| inputs=language_selector, | |
| outputs=[ | |
| description_md, | |
| user_id_input, | |
| clear_btn, | |
| chatbot, | |
| msg_input, | |
| submit_btn, | |
| submit_btn, | |
| rtl_style_html | |
| ] | |
| ) | |
| iface.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", 7860)), share=True) |