Update app.py
Browse files
app.py
CHANGED
|
@@ -1,62 +1,78 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
|
| 3 |
-
import getpass
|
| 4 |
import os
|
|
|
|
| 5 |
import uuid
|
| 6 |
from datetime import datetime
|
| 7 |
|
| 8 |
import gradio as gr
|
| 9 |
-
from dotenv import load_dotenv
|
| 10 |
-
from supabase import create_client, Client
|
| 11 |
|
|
|
|
| 12 |
from langchain.chat_models import init_chat_model
|
| 13 |
from langchain_openai import OpenAIEmbeddings
|
| 14 |
-
from
|
| 15 |
from pinecone import Pinecone
|
|
|
|
| 16 |
from langchain.memory import ConversationBufferWindowMemory
|
| 17 |
-
from langchain_core.tools import tool
|
| 18 |
from langchain_core.messages import SystemMessage
|
| 19 |
-
from langgraph.graph import
|
| 20 |
from langgraph.prebuilt import ToolNode, tools_condition
|
| 21 |
|
| 22 |
-
# Load environment variables
|
| 23 |
load_dotenv()
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
PINECONE_API_KEY = os.
|
| 29 |
-
|
| 30 |
-
|
|
|
|
| 31 |
llm = init_chat_model("gpt-4.1-2025-04-14", model_provider="openai", temperature=0.0)
|
| 32 |
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
|
| 33 |
-
|
| 34 |
-
# Vector store
|
| 35 |
pc = Pinecone(api_key=PINECONE_API_KEY)
|
| 36 |
-
index = pc.Index(
|
| 37 |
-
vector_store =
|
| 38 |
|
| 39 |
# Supabase logging
|
| 40 |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 41 |
|
| 42 |
def log_interaction_cloud(user_id: str, question: str, answer: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
try:
|
| 44 |
-
payload = {
|
| 45 |
-
"user_id": user_id,
|
| 46 |
-
"question": question,
|
| 47 |
-
"answer": answer,
|
| 48 |
-
"timestamp": datetime.utcnow().isoformat(),
|
| 49 |
-
}
|
| 50 |
res = supabase.table("logs").insert(payload).execute()
|
| 51 |
-
if hasattr(res, "status_code") and res.status_code >= 400:
|
| 52 |
-
print(f"[Supabase Error #{res.status_code}]:", res.data)
|
| 53 |
-
else:
|
| 54 |
-
print("[Supabase Success]:", res.data)
|
| 55 |
except Exception as e:
|
| 56 |
print("[Supabase Exception]", e)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
SYSTEM_MESSAGE_TEXT = (
|
| 62 |
"You are “Einbürgerungs-Helfer”, a highly skilled, friendly, and helpful administrative"
|
|
@@ -82,124 +98,99 @@ SYSTEM_MESSAGE_TEXT = (
|
|
| 82 |
" to rephrase their question and explain that this behavior is not acceptable."
|
| 83 |
)
|
| 84 |
|
| 85 |
-
@tool(response_format="content_and_artifact")
|
| 86 |
-
def retrieve(query: str):
|
| 87 |
-
retrieved_docs = vector_store.similarity_search(query, k=5)
|
| 88 |
-
serialized = "\n\n".join(
|
| 89 |
-
(f"Source: {doc.metadata}\n" f"Content: {doc.page_content}") for doc in retrieved_docs
|
| 90 |
-
)
|
| 91 |
-
return serialized, retrieved_docs
|
| 92 |
-
|
| 93 |
-
def generate_user_id():
|
| 94 |
-
return "user_" + uuid.uuid4().hex[:6]
|
| 95 |
-
|
| 96 |
def query_or_respond(state: MessagesState):
|
|
|
|
| 97 |
system_message = SystemMessage(SYSTEM_MESSAGE_TEXT)
|
| 98 |
raw_history = memory.load_memory_variables({})["chat_history"]
|
| 99 |
OFF_TOPIC_RESPONSE_SNIPPET = "I can only answer questions related to the process of naturalization in Germany"
|
| 100 |
-
filtered_history = [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
history = filtered_history[-5:]
|
| 102 |
prompt = [system_message] + history
|
| 103 |
llm_with_tools = llm.bind_tools([retrieve])
|
| 104 |
response = llm_with_tools.invoke(prompt)
|
| 105 |
-
|
| 106 |
user_id = state.get("user_id", "unknown_user")
|
| 107 |
user_question = [m.content for m in state["messages"] if m.type == "human"][-1]
|
| 108 |
answer_text = response.content
|
| 109 |
-
memory.save_context(
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
if not getattr(response, "tool_calls", None):
|
| 112 |
log_interaction_cloud(user_id, user_question, answer_text)
|
| 113 |
return {"messages": state["messages"] + [response]}
|
| 114 |
|
| 115 |
def generate(state: MessagesState):
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
system_prompt = SYSTEM_MESSAGE_TEXT + ("\n\n" + docs_content if docs_content else "")
|
| 119 |
-
conversation_messages = [msg for msg in state["messages"] if msg.type == "human" or (msg.type == "ai" and not getattr(msg, "tool_calls", None))]
|
| 120 |
-
recent_context = conversation_messages[-6:]
|
| 121 |
-
prompt = [SystemMessage(system_prompt)] + recent_context
|
| 122 |
-
response = llm.invoke(prompt)
|
| 123 |
-
|
| 124 |
user_id = state.get("user_id", "unknown_user")
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
# LangGraph
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
graph_builder.add_node(ToolNode([retrieve]))
|
| 134 |
-
graph_builder.add_node(generate)
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
graph = graph_builder.compile()
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
|
|
|
| 144 |
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
if not user_id:
|
| 147 |
-
user_id =
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
for partial in response_generator:
|
| 165 |
-
full_response = partial
|
| 166 |
-
yield chat_history + [[user_message, full_response]]
|
| 167 |
-
chat_histories[user_id].append([user_message, full_response])
|
| 168 |
-
|
| 169 |
-
def clear_history():
|
| 170 |
-
return "", []
|
| 171 |
-
|
| 172 |
-
description = """
|
| 173 |
-
### Was ist **Einbürgerungs-Helfer**?
|
| 174 |
-
**Deutsch:** Einbürgerungs-Helfer hilft dir, den Weg zur deutschen Staatsangehörigkeit zu verstehen – einfach, mehrsprachig, datenschutzfreundlich.
|
| 175 |
-
**English:** Einbürgerungs-Helfer helps you understand how to get German citizenship – simple, multilingual, and privacy-friendly.
|
| 176 |
-
**Türkçe:** Einbürgerungs-Helfer, Almanya vatandaşlığına giden yolu anlamanıza yardımcı olur – basit, çok dilli ve gizliliğe saygılı.
|
| 177 |
-
**العربية:** يساعدك "Einbürgerungs-Helfer" على فهم كيفية الحصول على الجنسية الألمانية - بطريقة بسيطة، متعددة اللغات وتحترم الخصوصية.
|
| 178 |
-
"""
|
| 179 |
-
|
| 180 |
-
with gr.Blocks(
|
| 181 |
-
theme=gr.themes.Soft(primary_hue="blue"),
|
| 182 |
-
css="""* { font-family: 'Noto Sans', sans-serif !important; }"""
|
| 183 |
-
) as iface:
|
| 184 |
-
gr.Markdown(f"# Einbürgerungs-Helfer\n{description}")
|
| 185 |
with gr.Row():
|
| 186 |
-
|
| 187 |
-
clear_btn = gr.Button("🗑️ Verlauf löschen")
|
| 188 |
-
|
| 189 |
-
chatbot = gr.Chatbot(
|
| 190 |
-
label="Chat",
|
| 191 |
-
show_copy_button=True,
|
| 192 |
-
value=[[None,
|
| 193 |
-
"Ich bin hier, um Ihnen bei allen Fragen zur Einbürgerung in Deutschland zu helfen.\n"
|
| 194 |
-
"Sie können Ihre Frage auf Deutsch, Englisch, Türkisch oder Arabisch stellen.\n"
|
| 195 |
-
"Lassen Sie uns loslegen – wie kann ich Ihnen heute helfen?"]]
|
| 196 |
-
)
|
| 197 |
-
msg_input = gr.Textbox(placeholder="Frage eingeben...", label="Deine Nachricht")
|
| 198 |
with gr.Row():
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
|
|
|
|
| 204 |
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
import uuid
|
| 4 |
from datetime import datetime
|
| 5 |
|
| 6 |
import gradio as gr
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# LangChain and related imports
|
| 9 |
from langchain.chat_models import init_chat_model
|
| 10 |
from langchain_openai import OpenAIEmbeddings
|
| 11 |
+
from langchain_pinecone import PineconeVectorStore
|
| 12 |
from pinecone import Pinecone
|
| 13 |
+
from supabase import create_client, Client
|
| 14 |
from langchain.memory import ConversationBufferWindowMemory
|
|
|
|
| 15 |
from langchain_core.messages import SystemMessage
|
| 16 |
+
from langgraph.graph import MessagesState, StateGraph, END
|
| 17 |
from langgraph.prebuilt import ToolNode, tools_condition
|
| 18 |
|
| 19 |
+
# Load environment variables (set these in your Space settings)
|
| 20 |
load_dotenv()
|
| 21 |
+
SUPABASE_URL = os.environ.get("SUPABASE_URL")
|
| 22 |
+
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
|
| 23 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 24 |
+
LANGSMITH_API_KEY = os.environ.get("LANGSMITH_API_KEY")
|
| 25 |
+
PINECONE_API_KEY = os.environ.get("PINECONE_API_KEY") or "pcsk_6QDugC_7m1gcD6Pf4gENbcCQRir3UewfxdpGj4rCaZMq3Sw6djHYXUomt2HGxbWaCt5iBU"
|
| 26 |
+
PINECONE_INDEX = os.environ.get("PINECONE_INDEX") or "natstudy"
|
| 27 |
+
|
| 28 |
+
# Model and vector store setup
|
| 29 |
llm = init_chat_model("gpt-4.1-2025-04-14", model_provider="openai", temperature=0.0)
|
| 30 |
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
|
|
|
|
|
|
|
| 31 |
pc = Pinecone(api_key=PINECONE_API_KEY)
|
| 32 |
+
index = pc.Index(PINECONE_INDEX)
|
| 33 |
+
vector_store = PineconeVectorStore(embedding=embeddings, index=index)
|
| 34 |
|
| 35 |
# Supabase logging
|
| 36 |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 37 |
|
| 38 |
def log_interaction_cloud(user_id: str, question: str, answer: str):
|
| 39 |
+
payload = {
|
| 40 |
+
"user_id": user_id,
|
| 41 |
+
"question": question,
|
| 42 |
+
"answer": answer,
|
| 43 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 44 |
+
}
|
| 45 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
res = supabase.table("logs").insert(payload).execute()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
print("[Supabase Exception]", e)
|
| 49 |
+
return
|
| 50 |
+
if hasattr(res, "status_code") and res.status_code >= 400:
|
| 51 |
+
print(f"[Supabase Error #{res.status_code}]:", res.data)
|
| 52 |
+
else:
|
| 53 |
+
print("[Supabase Success]:", res.data)
|
| 54 |
+
|
| 55 |
+
def generate_user_id():
|
| 56 |
+
return "user_" + uuid.uuid4().hex[:6]
|
| 57 |
+
|
| 58 |
+
memory = ConversationBufferWindowMemory(
|
| 59 |
+
memory_key="chat_history",
|
| 60 |
+
return_messages=True,
|
| 61 |
+
k=5
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# LangGraph setup
|
| 65 |
+
from langchain_core.tools import tool
|
| 66 |
|
| 67 |
+
@tool(response_format="content_and_artifact")
|
| 68 |
+
def retrieve(query: str):
|
| 69 |
+
"""Retrieve information related to the last query."""
|
| 70 |
+
retrieved_docs = vector_store.similarity_search(query, k=5)
|
| 71 |
+
serialized = "\n\n".join(
|
| 72 |
+
(f"Source: {doc.metadata}\n" f"Content: {doc.page_content}")
|
| 73 |
+
for doc in retrieved_docs
|
| 74 |
+
)
|
| 75 |
+
return serialized, retrieved_docs
|
| 76 |
|
| 77 |
SYSTEM_MESSAGE_TEXT = (
|
| 78 |
"You are “Einbürgerungs-Helfer”, a highly skilled, friendly, and helpful administrative"
|
|
|
|
| 98 |
" to rephrase their question and explain that this behavior is not acceptable."
|
| 99 |
)
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def query_or_respond(state: MessagesState):
|
| 102 |
+
"""Generate tool call for retrieval or respond."""
|
| 103 |
system_message = SystemMessage(SYSTEM_MESSAGE_TEXT)
|
| 104 |
raw_history = memory.load_memory_variables({})["chat_history"]
|
| 105 |
OFF_TOPIC_RESPONSE_SNIPPET = "I can only answer questions related to the process of naturalization in Germany"
|
| 106 |
+
filtered_history = []
|
| 107 |
+
for msg in raw_history:
|
| 108 |
+
if msg.type == "ai" and OFF_TOPIC_RESPONSE_SNIPPET in msg.content:
|
| 109 |
+
continue
|
| 110 |
+
filtered_history.append(msg)
|
| 111 |
history = filtered_history[-5:]
|
| 112 |
prompt = [system_message] + history
|
| 113 |
llm_with_tools = llm.bind_tools([retrieve])
|
| 114 |
response = llm_with_tools.invoke(prompt)
|
|
|
|
| 115 |
user_id = state.get("user_id", "unknown_user")
|
| 116 |
user_question = [m.content for m in state["messages"] if m.type == "human"][-1]
|
| 117 |
answer_text = response.content
|
| 118 |
+
memory.save_context(
|
| 119 |
+
{"input": user_question},
|
| 120 |
+
{"output": answer_text}
|
| 121 |
+
)
|
| 122 |
if not getattr(response, "tool_calls", None):
|
| 123 |
log_interaction_cloud(user_id, user_question, answer_text)
|
| 124 |
return {"messages": state["messages"] + [response]}
|
| 125 |
|
| 126 |
def generate(state: MessagesState):
|
| 127 |
+
"""Generate a response based on the tool result."""
|
| 128 |
+
last_message = state["messages"][-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
user_id = state.get("user_id", "unknown_user")
|
| 130 |
+
if hasattr(last_message, "content"):
|
| 131 |
+
answer_text = last_message.content
|
| 132 |
+
else:
|
| 133 |
+
answer_text = str(last_message)
|
| 134 |
+
user_question = [m.content for m in state["messages"] if m.type == "human"][-1]
|
| 135 |
+
log_interaction_cloud(user_id, user_question, answer_text)
|
| 136 |
+
return {"messages": state["messages"]}
|
| 137 |
|
| 138 |
+
# LangGraph state and graph definition
|
| 139 |
+
class MyState(MessagesState):
|
| 140 |
+
user_id: str = "unknown_user"
|
|
|
|
|
|
|
| 141 |
|
| 142 |
+
workflow = StateGraph(MyState)
|
| 143 |
+
workflow.add_node("query_or_respond", query_or_respond)
|
| 144 |
+
workflow.add_node("tool", ToolNode([retrieve]))
|
| 145 |
+
workflow.add_node("generate", generate)
|
|
|
|
| 146 |
|
| 147 |
+
workflow.add_edge("query_or_respond", tools_condition)
|
| 148 |
+
workflow.add_edge("tool", "generate")
|
| 149 |
+
workflow.add_edge("generate", END)
|
| 150 |
|
| 151 |
+
workflow.set_entry_point("query_or_respond")
|
| 152 |
+
graph = workflow.compile()
|
| 153 |
+
|
| 154 |
+
# Gradio UI
|
| 155 |
+
def gradio_chatbot(user_message, chat_history, user_id):
|
| 156 |
if not user_id:
|
| 157 |
+
user_id = generate_user_id()
|
| 158 |
+
# Convert chat_history to MessagesState format
|
| 159 |
+
messages = []
|
| 160 |
+
for turn in chat_history:
|
| 161 |
+
messages.append({"type": "human", "content": turn[0]})
|
| 162 |
+
if turn[1]:
|
| 163 |
+
messages.append({"type": "ai", "content": turn[1]})
|
| 164 |
+
messages.append({"type": "human", "content": user_message})
|
| 165 |
+
state = {"messages": messages, "user_id": user_id}
|
| 166 |
+
result = graph.invoke(state)
|
| 167 |
+
# Extract the last AI message
|
| 168 |
+
ai_message = [m.content for m in result["messages"] if m.type == "ai"][-1]
|
| 169 |
+
chat_history.append((user_message, ai_message))
|
| 170 |
+
return chat_history, user_id
|
| 171 |
+
|
| 172 |
+
with gr.Blocks() as iface:
|
| 173 |
+
gr.Markdown("# 🇩🇪 Einbürgerungs-Helfer\nA chatbot to help with questions about naturalization in Germany.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
with gr.Row():
|
| 175 |
+
chatbot = gr.Chatbot()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
with gr.Row():
|
| 177 |
+
user_input = gr.Textbox(placeholder="Stellen Sie Ihre Frage hier / Ask your question here")
|
| 178 |
+
user_id_state = gr.State("")
|
| 179 |
+
send_btn = gr.Button("Send")
|
| 180 |
+
clear_btn = gr.Button("Clear")
|
| 181 |
+
send_btn.click(
|
| 182 |
+
gradio_chatbot,
|
| 183 |
+
inputs=[user_input, chatbot, user_id_state],
|
| 184 |
+
outputs=[chatbot, user_id_state]
|
| 185 |
+
)
|
| 186 |
+
clear_btn.click(lambda: ([], generate_user_id()), None, [chatbot, user_id_state])
|
| 187 |
+
user_input.submit(
|
| 188 |
+
gradio_chatbot,
|
| 189 |
+
inputs=[user_input, chatbot, user_id_state],
|
| 190 |
+
outputs=[chatbot, user_id_state]
|
| 191 |
+
)
|
| 192 |
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
iface.launch()
|
| 195 |
|
| 196 |
|