File size: 7,091 Bytes
ee98f9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import os
import uuid
from dotenv import load_dotenv
load_dotenv()

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_core.tools import tool
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 InMemoryChatMessageHistory

class CustomState(TypedDict):
    messages: Annotated[List[BaseMessage], add_messages]
    user_id: str
    chat_history: Optional[List[List[str]]]

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = input("Enter API key for OpenAI: ")
llm = init_chat_model("gpt-4o", model_provider="openai", temperature=0.0)

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
)

class MemoryStore:
    def get_memory(self, user_id: str):
        return InMemoryChatMessageHistory()

store = MemoryStore()

def retrieve(query: str):
    """Retrieve information related to the last query."""
    retrieved_docs = vector_store.similarity_search(query, k=6)
    print("\n🔎 Retrieved Documents:")
    for i, doc in enumerate(retrieved_docs, 1):
        print(f"\n--- Document {i} ---")
        print(f"Source: {doc.metadata}")
        print(f"Content (excerpt):\n{doc.page_content}...")

    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_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:] if hasattr(memory, 'messages') else []

    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)

    return {**state, "messages": [response], "user_id": user_id}

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

def clear_history(user_id_state):
    return [["", "Ich bin hier, um Ihnen bei allen Fragen zur Einbürgerung in Deutschland zu helfen..."]], user_id_state, "", user_id_state

def respond(user_message, chatbot, user_id_input, chat_state, user_id_state):
    if not user_message:
        return chatbot, chat_state, user_id_input, "", user_id_state

    user_id = user_id_state or user_id_input or generate_user_id()

    state: CustomState = {
        "messages": [HumanMessage(content=user_message)],
        "user_id": user_id,
        "chat_history": None
    }

    config = RunnableConfig(configurable={"session_id": user_id})
    final_state = graph.invoke(state, config=config)

    bot_response = final_state["messages"][-1].content
    chatbot.append([user_message, bot_response])

    return chatbot, chatbot, user_id, "", user_id

description = """
### Was ist **Einbürgerungs-Helfer**?
 **Deutsch:** Einbürgerungs-Helfer hilft dir, den Weg zur deutschen Staatsangehörigkeit zu verstehen – einfach, mehrsprachig, datenschutzfreundlich.
"""

with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as iface:
    gr.Markdown(f"#  Einbürgerungs-Helfer\n{description}")
    with gr.Row():
        user_id_input = gr.Textbox(label="Benutzer-ID (User ID)", placeholder="z.B. user_123", lines=1)
        clear_btn = gr.Button("🗑️ Verlauf löschen")

    user_id_state = gr.State(value="")
    chat_state = gr.State([])

    chatbot = gr.Chatbot(
        label="Chat",
        show_copy_button=True,
        value=[[None, "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="Frage eingeben...", label="Deine Nachricht", lines=1, value="")

    with gr.Row():
        submit_btn = gr.Button("Senden", variant="primary")
        submit_btn.click(fn=respond, inputs=[msg_input, chatbot, user_id_input, chat_state, user_id_state], outputs=[chatbot, chat_state, user_id_input, msg_input, user_id_state])
        msg_input.submit(fn=respond, inputs=[msg_input, chatbot, user_id_input, chat_state, user_id_state], outputs=[chatbot, chat_state, user_id_input, msg_input, user_id_state])

    clear_btn.click(fn=clear_history, inputs=[user_id_state], outputs=[chatbot, user_id_input, msg_input, user_id_state])

iface.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", 7860)), share=True)