Update app.py
Browse files
app.py
CHANGED
|
@@ -1,278 +1,34 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import uuid
|
| 3 |
-
import traceback
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
from typing_extensions import TypedDict
|
| 6 |
-
|
| 7 |
import gradio as gr
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
llm = None
|
| 12 |
-
vector_store = None
|
| 13 |
-
supabase = None
|
| 14 |
-
graph = None
|
| 15 |
-
|
| 16 |
-
def initialize_services():
|
| 17 |
-
"""Initialize all external services with comprehensive error handling"""
|
| 18 |
-
global SERVICES_AVAILABLE, llm, vector_store, supabase, graph
|
| 19 |
-
|
| 20 |
-
try:
|
| 21 |
-
from dotenv import load_dotenv
|
| 22 |
-
load_dotenv()
|
| 23 |
-
|
| 24 |
-
# Check required environment variables
|
| 25 |
-
required_env_vars = {
|
| 26 |
-
"SUPABASE_URL": os.environ.get("SUPABASE_URL"),
|
| 27 |
-
"SUPABASE_KEY": os.environ.get("SUPABASE_KEY"),
|
| 28 |
-
"OPENAI_API_KEY": os.environ.get("OPENAI_API_KEY"),
|
| 29 |
-
"PINECONE_API_KEY": os.environ.get("PINECONE_API_KEY")
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
missing_vars = [var for var, value in required_env_vars.items() if not value]
|
| 33 |
-
if missing_vars:
|
| 34 |
-
print(f"Missing environment variables: {missing_vars}")
|
| 35 |
-
return False
|
| 36 |
-
|
| 37 |
-
# Initialize OpenAI
|
| 38 |
-
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
|
| 39 |
-
llm = ChatOpenAI(
|
| 40 |
-
model="gpt-4o-mini",
|
| 41 |
-
temperature=0.0,
|
| 42 |
-
api_key=required_env_vars["OPENAI_API_KEY"]
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
embeddings = OpenAIEmbeddings(
|
| 46 |
-
model="text-embedding-3-small",
|
| 47 |
-
api_key=required_env_vars["OPENAI_API_KEY"]
|
| 48 |
-
)
|
| 49 |
-
|
| 50 |
-
# Initialize Pinecone
|
| 51 |
-
from pinecone import Pinecone
|
| 52 |
-
from langchain_community.vectorstores import Pinecone as PineconeVectorStore
|
| 53 |
-
|
| 54 |
-
pc = Pinecone(api_key=required_env_vars["PINECONE_API_KEY"])
|
| 55 |
-
vector_store = PineconeVectorStore.from_existing_index(
|
| 56 |
-
index_name=os.environ.get("PINECONE_INDEX", "natstudy"),
|
| 57 |
-
embedding=embeddings
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
-
# Initialize Supabase
|
| 61 |
-
from supabase import create_client
|
| 62 |
-
supabase = create_client(
|
| 63 |
-
required_env_vars["SUPABASE_URL"],
|
| 64 |
-
required_env_vars["SUPABASE_KEY"]
|
| 65 |
-
)
|
| 66 |
-
|
| 67 |
-
# Initialize LangGraph components
|
| 68 |
-
from langchain_core.messages import SystemMessage
|
| 69 |
-
from langchain_core.tools import tool
|
| 70 |
-
from langgraph.graph import StateGraph, END
|
| 71 |
-
from langgraph.prebuilt import ToolNode, tools_condition
|
| 72 |
-
|
| 73 |
-
@tool
|
| 74 |
-
def retrieve(query: str):
|
| 75 |
-
"""Retrieve information related to the query."""
|
| 76 |
-
try:
|
| 77 |
-
retrieved_docs = vector_store.similarity_search(query, k=3)
|
| 78 |
-
return "\n\n".join(
|
| 79 |
-
f"Source: {doc.metadata}\nContent: {doc.page_content}"
|
| 80 |
-
for doc in retrieved_docs
|
| 81 |
-
)
|
| 82 |
-
except Exception as e:
|
| 83 |
-
return f"Retrieval error: {str(e)}"
|
| 84 |
-
|
| 85 |
-
class MyState(TypedDict):
|
| 86 |
-
messages: list
|
| 87 |
-
user_id: str
|
| 88 |
-
|
| 89 |
-
def query_or_respond(state: MyState):
|
| 90 |
-
try:
|
| 91 |
-
system_message = SystemMessage(
|
| 92 |
-
"You are 'Einbürgerungs-Helfer', a helpful assistant for German citizenship questions. "
|
| 93 |
-
"Respond in the user's language (German, English, Turkish, or Arabic)."
|
| 94 |
-
)
|
| 95 |
-
|
| 96 |
-
user_message = [m for m in state["messages"] if m.get("role") == "user"][-1]["content"]
|
| 97 |
-
llm_with_tools = llm.bind_tools([retrieve])
|
| 98 |
-
response = llm_with_tools.invoke([system_message, {"role": "user", "content": user_message}])
|
| 99 |
-
|
| 100 |
-
return {
|
| 101 |
-
"messages": state["messages"] + [{"role": "assistant", "content": response.content}],
|
| 102 |
-
"user_id": state.get("user_id", "unknown")
|
| 103 |
-
}
|
| 104 |
-
except Exception as e:
|
| 105 |
-
return {
|
| 106 |
-
"messages": state["messages"] + [{"role": "assistant", "content": f"I apologize, but I encountered an error: {str(e)}"}],
|
| 107 |
-
"user_id": state.get("user_id", "unknown")
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
def generate_final(state: MyState):
|
| 111 |
-
return state
|
| 112 |
-
|
| 113 |
-
# Build graph
|
| 114 |
-
workflow = StateGraph(MyState)
|
| 115 |
-
workflow.add_node("query_or_respond", query_or_respond)
|
| 116 |
-
workflow.add_node("tool", ToolNode([retrieve]))
|
| 117 |
-
workflow.add_node("generate", generate_final)
|
| 118 |
-
|
| 119 |
-
workflow.add_conditional_edges("query_or_respond", tools_condition, {
|
| 120 |
-
"tool": "tool",
|
| 121 |
-
"generate": "generate"
|
| 122 |
-
})
|
| 123 |
-
workflow.add_edge("tool", "generate")
|
| 124 |
-
workflow.add_edge("generate", END)
|
| 125 |
-
workflow.set_entry_point("query_or_respond")
|
| 126 |
-
|
| 127 |
-
graph = workflow.compile()
|
| 128 |
-
|
| 129 |
-
print("All services initialized successfully!")
|
| 130 |
-
return True
|
| 131 |
-
|
| 132 |
-
except Exception as e:
|
| 133 |
-
print(f"Service initialization failed: {e}")
|
| 134 |
-
print(f"Traceback: {traceback.format_exc()}")
|
| 135 |
-
return False
|
| 136 |
-
|
| 137 |
-
def log_interaction(user_id: str, question: str, answer: str):
|
| 138 |
-
"""Log interaction to Supabase"""
|
| 139 |
-
if not supabase:
|
| 140 |
-
return
|
| 141 |
-
|
| 142 |
-
try:
|
| 143 |
-
supabase.table("logs").insert({
|
| 144 |
-
"user_id": user_id,
|
| 145 |
-
"question": question,
|
| 146 |
-
"answer": answer,
|
| 147 |
-
"timestamp": datetime.utcnow().isoformat()
|
| 148 |
-
}).execute()
|
| 149 |
-
except Exception as e:
|
| 150 |
-
print(f"Logging error: {e}")
|
| 151 |
-
|
| 152 |
-
def generate_user_id():
|
| 153 |
-
return "user_" + uuid.uuid4().hex[:8]
|
| 154 |
-
|
| 155 |
-
def respond(user_message, chat_history, user_id):
|
| 156 |
-
"""Main response function"""
|
| 157 |
-
if not user_message.strip():
|
| 158 |
-
return chat_history
|
| 159 |
-
|
| 160 |
-
if not user_id:
|
| 161 |
-
user_id = generate_user_id()
|
| 162 |
-
|
| 163 |
try:
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
"user_id": user_id
|
| 177 |
-
}
|
| 178 |
-
|
| 179 |
-
result = graph.invoke(state)
|
| 180 |
-
bot_response = result["messages"][-1]["content"]
|
| 181 |
-
|
| 182 |
-
# Log interaction
|
| 183 |
-
log_interaction(user_id, user_message, bot_response)
|
| 184 |
-
|
| 185 |
-
new_history = chat_history + [[user_message, bot_response]]
|
| 186 |
-
return new_history
|
| 187 |
-
|
| 188 |
except Exception as e:
|
| 189 |
-
|
| 190 |
-
return chat_history + [[user_message, error_response]]
|
| 191 |
-
|
| 192 |
-
def clear_chat():
|
| 193 |
-
return [], ""
|
| 194 |
-
|
| 195 |
-
# Initialize services
|
| 196 |
-
print("Initializing services...")
|
| 197 |
-
SERVICES_AVAILABLE = initialize_services()
|
| 198 |
-
|
| 199 |
-
if SERVICES_AVAILABLE:
|
| 200 |
-
print("✅ All services ready!")
|
| 201 |
-
else:
|
| 202 |
-
print("⚠️ Running in limited mode - some features may not be available")
|
| 203 |
-
|
| 204 |
-
# Create Gradio interface
|
| 205 |
-
description = """
|
| 206 |
-
### Was ist **Einbürgerungs-Helfer**?
|
| 207 |
-
**Deutsch:** Einbürgerungs-Helfer hilft dir, den Weg zur deutschen Staatsangehörigkeit zu verstehen.
|
| 208 |
-
|
| 209 |
-
**English:** Einbürgerungs-Helfer helps you understand how to get German citizenship.
|
| 210 |
-
|
| 211 |
-
**Türkçe:** Einbürgerungs-Helfer, Almanya vatandaşlığına giden yolu anlamanıza yardımcı olur.
|
| 212 |
-
|
| 213 |
-
**العربية:** يساعدك "Einbürgerungs-Helfer" على فهم كيفية الحصول على الجنسية الألمانية.
|
| 214 |
-
"""
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
gr.
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
with gr.Row():
|
| 226 |
-
user_id_input = gr.Textbox(
|
| 227 |
-
label="User ID",
|
| 228 |
-
value=generate_user_id(),
|
| 229 |
-
placeholder="Enter your user ID"
|
| 230 |
-
)
|
| 231 |
-
clear_btn = gr.Button("🗑️ Clear Chat")
|
| 232 |
-
|
| 233 |
-
chatbot = gr.Chatbot(
|
| 234 |
-
label="Chat",
|
| 235 |
-
value=[[None,
|
| 236 |
-
"Hallo! Ich bin hier, um Ihnen bei Fragen zur deutschen Einbürgerung zu helfen.\n\n"
|
| 237 |
-
"Hello! I'm here to help you with German citizenship questions.\n\n"
|
| 238 |
-
"Wie kann ich Ihnen helfen? / How can I help you?"
|
| 239 |
-
]]
|
| 240 |
-
)
|
| 241 |
-
|
| 242 |
-
msg_input = gr.Textbox(
|
| 243 |
-
label="Your Message",
|
| 244 |
-
placeholder="Ask your question in German, English, Turkish, or Arabic..."
|
| 245 |
-
)
|
| 246 |
-
|
| 247 |
-
submit_btn = gr.Button("Send", variant="primary")
|
| 248 |
-
|
| 249 |
-
# Event handlers
|
| 250 |
-
submit_btn.click(
|
| 251 |
-
respond,
|
| 252 |
-
inputs=[msg_input, chatbot, user_id_input],
|
| 253 |
-
outputs=[chatbot]
|
| 254 |
-
).then(
|
| 255 |
-
lambda: "",
|
| 256 |
-
outputs=[msg_input]
|
| 257 |
-
)
|
| 258 |
-
|
| 259 |
-
msg_input.submit(
|
| 260 |
-
respond,
|
| 261 |
-
inputs=[msg_input, chatbot, user_id_input],
|
| 262 |
-
outputs=[chatbot]
|
| 263 |
-
).then(
|
| 264 |
-
lambda: "",
|
| 265 |
-
outputs=[msg_input]
|
| 266 |
-
)
|
| 267 |
-
|
| 268 |
-
clear_btn.click(
|
| 269 |
-
clear_chat,
|
| 270 |
-
outputs=[chatbot, msg_input]
|
| 271 |
-
)
|
| 272 |
|
| 273 |
if __name__ == "__main__":
|
| 274 |
-
demo.launch(
|
| 275 |
-
|
| 276 |
-
server_port=7860,
|
| 277 |
-
show_error=True
|
| 278 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
|
| 5 |
+
def hello(name):
|
| 6 |
+
"""Ultra simple function to test basic functionality"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
try:
|
| 8 |
+
env_info = []
|
| 9 |
+
env_info.append(f"Python version: {sys.version}")
|
| 10 |
+
env_info.append(f"Working directory: {os.getcwd()}")
|
| 11 |
+
env_info.append(f"Environment variables count: {len(os.environ)}")
|
| 12 |
+
|
| 13 |
+
# Check if key env vars exist (without exposing values)
|
| 14 |
+
key_vars = ["OPENAI_API_KEY", "PINECONE_API_KEY", "SUPABASE_URL", "SUPABASE_KEY"]
|
| 15 |
+
for var in key_vars:
|
| 16 |
+
exists = "✅" if os.environ.get(var) else "❌"
|
| 17 |
+
env_info.append(f"{var}: {exists}")
|
| 18 |
+
|
| 19 |
+
return f"Hello {name}!\n\n" + "\n".join(env_info)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
except Exception as e:
|
| 21 |
+
return f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# Create the simplest possible interface
|
| 24 |
+
demo = gr.Interface(
|
| 25 |
+
fn=hello,
|
| 26 |
+
inputs=gr.Textbox(label="Enter your name"),
|
| 27 |
+
outputs=gr.Textbox(label="Response"),
|
| 28 |
+
title="Ultra Minimal Test",
|
| 29 |
+
description="If you see this, Gradio is working!"
|
| 30 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
if __name__ == "__main__":
|
| 33 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 34 |
+
|
|
|
|
|
|
|
|
|