README23 / app.py
rvdbra's picture
Update app.py
8c86fcb verified
Raw History Blame Contribute Delete
28.3 kB
import os
import uuid
import json
import uvicorn
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, Literal
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
from pydantic import BaseModel, Field
from relevant_links import RELEVANT_NATURALIZATION_LINKS
from prompts import SYSTEM_MESSAGE_TEXT, ROUTER_SYS
# --- 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]]]
# --- Router Structured Output Schema (SINGLE MODEL) ---
class RouterDecision(BaseModel):
action: Literal["reply", "retrieve"]
language: Literal["de", "en", "tr", "ar"]
text: Optional[str] = None
normalized_query: Optional[str] = None
# --- AI Models ---
_llm = None
def get_llm():
global _llm
if _llm is None:
key = os.getenv("OPENAI_API_KEY")
if not key:
raise RuntimeError("OPENAI_API_KEY not set")
_llm = init_chat_model("gpt-4.1", model_provider="openai", temperature=0.5)
return _llm
llm = get_llm()
# router with structured output using the single model
_router_llm_base = init_chat_model("gpt-4.1", model_provider="openai", temperature=0.7)
router_llm = _router_llm_base.with_structured_output(
schema=RouterDecision,
method="json_schema"
)
# --- 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
@property
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=4)
serialized = "\n\n".join(
(f"[Source]({doc.metadata.get('source', '')}):\n{doc.page_content}")
for doc in retrieved_docs
)
return serialized, retrieved_docs
def generate_user_id():
return "user_" + uuid.uuid4().hex[:6]
# --- STRICT Router (Structured Output + Retry + Runtime guards) ---
def route_or_reply(user_text: str, prior_msgs: List[BaseMessage]) -> dict:
history_slice = prior_msgs[-4:] if prior_msgs else []
msgs = [SystemMessage(ROUTER_SYS)] + history_slice + [HumanMessage(user_text)]
last_err = None
for attempt in range(2):
try:
obj = router_llm.invoke(msgs)
data = obj.model_dump()
action = data.get("action")
if action == "reply":
if not data.get("text"):
raise ValueError("RouterDecision 'reply' requires 'text'.")
data.pop("normalized_query", None)
elif action == "retrieve":
if not data.get("normalized_query"):
raise ValueError("RouterDecision 'retrieve' requires 'normalized_query'.")
data.pop("text", None)
else:
raise ValueError(f"Unknown action: {action}")
return data
except Exception as e:
last_err = e
print(f"[Router Parse/Validation Error Attempt {attempt+1}]:", repr(e))
return {"action": "reply", "language": "en", "text": "Sorry, something went wrong. Please try again."}
# --- Main Node ---
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
decision = route_or_reply(latest_user_msg.content, history)
print("[Router]", decision)
if decision.get("action") == "reply":
response = AIMessage(content=decision.get("text", ""))
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}
normalized_query = decision.get("normalized_query") or latest_user_msg.content
retrieved_text, _ = retrieve(normalized_query)
history_tail = history[-5:]
system_msg = SystemMessage(
SYSTEM_MESSAGE_TEXT
+ "\n\nStrictly use the following documents to answer the question. "
"If helpful, include direct source links in your answer: "
+ retrieved_text
)
prompt = [system_msg] + history_tail + [latest_user_msg]
response = llm.invoke(prompt)
print("The retrieved text is ", retrieved_text)
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()
# --- Gradio UI ---
import gradio as gr
import time
import re
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from gradio.routes import mount_gradio_app
# 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",
"welcome_msg": "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_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",
"welcome_msg": "I’m here to help you with any questions about naturalization in Germany.\nLet’s get started – how can I assist you today?",
"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",
"welcome_msg": "Almanya vatandaşlığına dair sorularınızda size yardımcı olmak için buradayım.\nHadi başlayalım – bugün size nasıl yardımcı olabilirim?",
"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": "الدردشة",
"welcome_msg": "أنا هنا لمساعدتك في جميع الأسئلة المتعلقة بالتجنيس في ألمانيا.\nلنبدأ – كيف يمكنني مساعدتك اليوم؟",
"msg_input_label": "رسالتك",
"msg_input_placeholder": "اكتب سؤالك...",
"submit_btn": "إرسال",
"description": """
### ما هو **مساعد التجنيس**؟
**العربية:** مساعد التجنيس يساعدك على فهم طريق الحصول على الجنسية الألمانية – بسيط، متعدد اللغات، ويحترم الخصوصية.
"""
}
}
# Add waiting messages to translations
waiting_messages = {
"Deutsch": "💭 Einen Moment...",
"English": "💭 One moment...",
"Türkçe": "💭 Bir dakika...",
"العربية": "💭 لحظة واحدة..."
}
# Global variable to track current language
current_language = "Deutsch"
# Language update function
def update_language(lang):
global current_language
current_language = lang
t = translations[lang]
rtl_style = ""
if lang == "العربية":
rtl_style = """
<style>
/* Force RTL for ALL elements when Arabic is selected */
* {
direction: rtl !important;
text-align: right !important;
}
/* Specific targeting for Gradio components */
.gradio-container, .gradio-container * {
direction: rtl !important;
text-align: right !important;
}
/* Markdown content - this targets your description */
.gr-prose, .gr-prose *, .markdown, .markdown * {
direction: rtl !important;
text-align: right !important;
}
/* Input fields and textboxes with placeholder fix */
input, textarea, .gr-textbox input, .gr-textbox textarea {
direction: rtl !important;
text-align: right !important;
unicode-bidi: plaintext !important;
}
/* CRITICAL: Fix for placeholders */
input::placeholder, textarea::placeholder,
.gr-textbox input::placeholder, .gr-textbox textarea::placeholder {
direction: rtl !important;
text-align: right !important;
unicode-bidi: plaintext !important;
}
/* Buttons */
button, .gr-button, .gr-button * {
direction: rtl !important;
text-align: right !important;
}
/* Dropdown menus */
select, .gr-dropdown, .gr-dropdown * {
direction: rtl !important;
text-align: right !important;
}
/* Labels - move to right side */
label, .gr-form label, .gr-block label, .gr-textbox label {
direction: rtl !important;
text-align: right !important;
float: right !important;
margin-left: 0 !important;
margin-right: auto !important;
}
/* Form layout adjustments for RTL */
.gr-form, .gr-block {
direction: rtl !important;
text-align: right !important;
}
/* Textbox container layout */
.gr-textbox {
direction: rtl !important;
text-align: right !important;
}
.gr-textbox > label {
float: right !important;
clear: right !important;
text-align: right !important;
}
/* Chat interface */
.gr-chatbot, .gr-chatbot * {
direction: rtl !important;
text-align: right !important;
}
/* Headings */
h1, h2, h3, h4, h5, h6 {
direction: rtl !important;
text-align: right !important;
}
/* Paragraphs and text */
p, div, span {
direction: rtl !important;
text-align: right !important;
}
/* Row layout adjustments for RTL */
.gr-row {
direction: rtl !important;
flex-direction: row-reverse !important;
}
/* Override any LTR forcing */
[dir="ltr"] {
direction: rtl !important;
text-align: right !important;
}
/* Additional input field targeting */
input[type="text"], input[type="search"] {
direction: rtl !important;
text-align: right !important;
}
input[type="text"]::placeholder, input[type="search"]::placeholder {
direction: rtl !important;
text-align: right !important;
}
</style>
"""
else:
rtl_style = """
<style>
/* Reset to LTR for other languages */
* {
direction: ltr !important;
text-align: left !important;
}
.gradio-container, .gradio-container * {
direction: ltr !important;
text-align: left !important;
}
.gr-prose, .gr-prose *, .markdown, .markdown * {
direction: ltr !important;
text-align: left !important;
}
input, textarea, .gr-textbox input, .gr-textbox textarea {
direction: ltr !important;
text-align: left !important;
}
input::placeholder, textarea::placeholder,
.gr-textbox input::placeholder, .gr-textbox textarea::placeholder {
direction: ltr !important;
text-align: left !important;
}
button, .gr-button, .gr-button * {
direction: ltr !important;
text-align: left !important;
}
select, .gr-dropdown, .gr-dropdown * {
direction: ltr !important;
text-align: left !important;
}
label, .gr-form label, .gr-block label, .gr-textbox label {
direction: ltr !important;
text-align: left !important;
float: left !important;
margin-right: 0 !important;
margin-left: auto !important;
}
.gr-form, .gr-block, .gr-textbox {
direction: ltr !important;
text-align: left !important;
}
.gr-textbox > label {
float: left !important;
clear: left !important;
text-align: left !important;
}
.gr-chatbot, .gr-chatbot * {
direction: ltr !important;
text-align: left !important;
}
h1, h2, h3, h4, h5, h6 {
direction: ltr !important;
text-align: left !important;
}
p, div, span {
direction: ltr !important;
text-align: left !important;
}
.gr-row {
direction: ltr !important;
flex-direction: row !important;
}
input[type="text"], input[type="search"] {
direction: ltr !important;
text-align: left !important;
}
input[type="text"]::placeholder, input[type="search"]::placeholder {
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"], value=[{"role": "assistant", "content": t["welcome_msg"]}]),
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):
if user_id_state:
store.get_memory(user_id_state).clear()
t = translations[current_language]
initial_message = [{"role": "assistant", "content": t["welcome_msg"]}]
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 detect_rtl_content(text):
"""Detect if text contains RTL characters (Arabic, Hebrew, etc.)"""
rtl_chars = '\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF'
return bool(re.search(f'[{rtl_chars}]', text))
def format_message_for_rtl(content):
"""Add RTL formatting wrapper if content contains RTL text"""
if detect_rtl_content(content):
return f'<div class="rtl-message">{content}</div>'
return content
def get_waiting_animation():
"""Return animated waiting indicator"""
animation_frames = ["⏳", "⌛", "⏳", "⌛"]
return animation_frames
def bot_response_handler(chat_history, user_id_input, user_id_state):
"""Generate streaming bot response with smart formatting delays, RTL support, and localized waiting"""
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 animated waiting indicator with proper language
global current_language
waiting_msg = waiting_messages.get(current_language, waiting_messages["Deutsch"])
# Animated waiting
animation_frames = get_waiting_animation()
chat_history.append({"role": "assistant", "content": waiting_msg})
yield chat_history, user_id
# Brief animation cycle
for i in range(10): # Show animation for few seconds
frame = animation_frames[i % len(animation_frames)]
base_msg = waiting_messages.get(current_language, waiting_messages["Deutsch"]).replace("💭", frame)
chat_history[-1]["content"] = base_msg
yield chat_history, user_id
time.sleep(0.4)
# Invoke your existing graph
final_state = graph.invoke(state, config=config)
bot_response = final_state["messages"][-1].content
# Check if response contains RTL content and format accordingly
is_rtl = detect_rtl_content(bot_response)
# 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
# Apply RTL formatting if needed
if is_rtl:
formatted_content = format_message_for_rtl(current_content)
else:
formatted_content = current_content
chat_history[-1]["content"] = formatted_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 with proper formatting
final_formatted = format_message_for_rtl(bot_response) if is_rtl else bot_response
chat_history[-1]["content"] = final_formatted
yield chat_history, user_id
except Exception as e:
# Handle errors gracefully with proper language
error_messages = {
"Deutsch": f"Entschuldigung, es gab einen Fehler bei der Verarbeitung Ihrer Anfrage: {str(e)}",
"English": f"Sorry, there was an error processing your request: {str(e)}",
"Türkçe": f"Üzgünüm, isteğinizi işlerken bir hata oluştu: {str(e)}",
"العربية": f"آسف، حدث خطأ أثناء معالجة طلبك: {str(e)}"
}
error_message = error_messages.get(current_language, error_messages["Deutsch"])
if detect_rtl_content(error_message):
error_message = format_message_for_rtl(error_message)
chat_history[-1]["content"] = error_message
yield chat_history, user_id
# Custom CSS for better markdown formatting and RTL support
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;
}
/* RTL support for Arabic text */
.rtl-message {
direction: rtl !important;
text-align: right !important;
unicode-bidi: embed;
}
.rtl-message ul, .rtl-message ol {
padding-right: 1.5em !important;
padding-left: 0 !important;
text-align: right !important;
}
.rtl-message li {
text-align: right !important;
}
/* Auto-detect Arabic content and apply RTL */
.message-body:has-arabic {
direction: rtl !important;
text-align: right !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("", elem_classes=["rtl-style-injector"]) # 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",
value=[
{"role": "assistant", "content": translations["Deutsch"]["welcome_msg"]}
]
)
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
]
)
# Define allowed origins
origins = [
"https://zum-deutschen-pass.de", # production
"http://127.0.0.1:5500", # optional: local dev
]
# Create FastAPI app
app = FastAPI()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Mount Gradio interface on FastAPI (without overwriting app)
mount_gradio_app(app, iface, path="/")
print("app imported successfully")
# 🔑 THIS keeps the server running
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)