Spaces:
Sleeping
Sleeping
added answer pairs
Browse files
app.py
CHANGED
|
@@ -19,7 +19,6 @@ llm_model_name = "models/gemma-3-4b-it"
|
|
| 19 |
collection_name = "xeno_collection"
|
| 20 |
|
| 21 |
# === Google Sheets Setup for Hugging Face ===
|
| 22 |
-
# Use environment variable for Google Sheets credentials
|
| 23 |
def get_google_sheets_credentials():
|
| 24 |
credentials_json = os.environ.get("GOOGLE_SHEETS_CREDENTIALS")
|
| 25 |
if not credentials_json:
|
|
@@ -32,25 +31,42 @@ def get_google_sheets_credentials():
|
|
| 32 |
# Authenticate with Google Sheets
|
| 33 |
client_gspread = gspread.authorize(get_google_sheets_credentials())
|
| 34 |
|
| 35 |
-
# Open the Google Sheet
|
| 36 |
sheet = client_gspread.open("Response_Log").sheet1
|
| 37 |
|
| 38 |
-
def log_response(question, answer, source_ids):
|
| 39 |
"""
|
| 40 |
-
Log a question, answer,
|
| 41 |
|
| 42 |
Args:
|
| 43 |
question (str): The question asked by the user.
|
| 44 |
answer (str): The answer provided by the model.
|
| 45 |
source_ids (str): Comma-separated list of source IDs used.
|
|
|
|
| 46 |
"""
|
| 47 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 48 |
-
row
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
try:
|
| 50 |
sheet.append_row(row)
|
| 51 |
print(f"Logged: {question} | Source IDs: {source_ids}")
|
| 52 |
except Exception as e:
|
| 53 |
print(f"Failed to log to Google Sheet: {e}")
|
|
|
|
|
|
|
| 54 |
|
| 55 |
# === Load and Clean Knowledge Base ===
|
| 56 |
df_kb = pd.read_json("XENO_Uganda_KnowledgeBase_Advisory.json")
|
|
@@ -67,7 +83,7 @@ def prepare_documents(data):
|
|
| 67 |
"source": item.get("Source", ""),
|
| 68 |
"owner": item.get("Owner", ""),
|
| 69 |
"tag": item.get("Tag", ""),
|
| 70 |
-
"id": item["ID"]
|
| 71 |
})
|
| 72 |
ids.append(item["ID"])
|
| 73 |
return documents, metadatas, ids
|
|
@@ -76,37 +92,98 @@ xeno_data_list = df_kb.to_dict('records')
|
|
| 76 |
documents, metadatas, ids = prepare_documents(xeno_data_list)
|
| 77 |
|
| 78 |
# === Setup ChromaDB ===
|
| 79 |
-
client = chromadb.PersistentClient(path="/tmp/xeno_db") # Use /tmp for Hugging Face Spaces
|
| 80 |
try:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
vector_store = Chroma(client=client, collection_name=collection_name)
|
| 87 |
retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 4})
|
| 88 |
|
| 89 |
# === Prompt System ===
|
| 90 |
-
SYSTEM_PROMPT =
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
# === Context Processing ===
|
| 97 |
def process_context(results, cosine_scores, max_results=2):
|
| 98 |
sorted_indices = np.argsort(cosine_scores)[::-1][:max_results]
|
| 99 |
formatted_context = ""
|
| 100 |
source_ids = []
|
|
|
|
| 101 |
for i, idx in enumerate(sorted_indices, 1):
|
| 102 |
result = results[idx]
|
| 103 |
score = cosine_scores[idx]
|
|
|
|
|
|
|
| 104 |
formatted_context += f"Knowledge Entry {i}:\n"
|
| 105 |
-
formatted_context += f"Q: {
|
| 106 |
-
formatted_context += f"A: {
|
| 107 |
formatted_context += "-" * 40 + "\n"
|
| 108 |
source_ids.append(result.metadata.get('id', 'N/A'))
|
| 109 |
-
|
|
|
|
| 110 |
|
| 111 |
# === LLM Generation ===
|
| 112 |
def generate_xeno_response(context, question):
|
|
@@ -124,8 +201,9 @@ def generate_xeno_response(context, question):
|
|
| 124 |
# === Main Interface Logic ===
|
| 125 |
def get_context_and_answer(message, history):
|
| 126 |
if message.lower().strip() in {"hi", "hello", "hey"}:
|
| 127 |
-
|
| 128 |
-
|
|
|
|
| 129 |
|
| 130 |
queried_results = retriever.invoke(message)
|
| 131 |
query_embedding = genai.embed_content(model=embedding_model,
|
|
@@ -139,14 +217,14 @@ def get_context_and_answer(message, history):
|
|
| 139 |
cos_sim = util.cos_sim(torch.tensor(query_embedding).float(), torch.tensor(doc_embedding).float())[0][0].item()
|
| 140 |
cosine_scores.append(cos_sim)
|
| 141 |
|
| 142 |
-
# If none of the results have sufficient similarity, fallback
|
| 143 |
if max(cosine_scores) < 0.4:
|
| 144 |
-
|
| 145 |
-
|
|
|
|
| 146 |
|
| 147 |
-
context, source_ids = process_context(queried_results, cosine_scores)
|
| 148 |
answer = generate_xeno_response(context, message)
|
| 149 |
-
log_response(message, answer, ", ".join(source_ids))
|
| 150 |
return answer
|
| 151 |
|
| 152 |
# === Gradio UI ===
|
|
@@ -158,4 +236,4 @@ iface = gr.ChatInterface(
|
|
| 158 |
)
|
| 159 |
|
| 160 |
if __name__ == "__main__":
|
| 161 |
-
iface.launch(share=False)
|
|
|
|
| 19 |
collection_name = "xeno_collection"
|
| 20 |
|
| 21 |
# === Google Sheets Setup for Hugging Face ===
|
|
|
|
| 22 |
def get_google_sheets_credentials():
|
| 23 |
credentials_json = os.environ.get("GOOGLE_SHEETS_CREDENTIALS")
|
| 24 |
if not credentials_json:
|
|
|
|
| 31 |
# Authenticate with Google Sheets
|
| 32 |
client_gspread = gspread.authorize(get_google_sheets_credentials())
|
| 33 |
|
| 34 |
+
# Open the Google Sheet
|
| 35 |
sheet = client_gspread.open("Response_Log").sheet1
|
| 36 |
|
| 37 |
+
def log_response(question, answer, source_ids, knowledge_pairs):
|
| 38 |
"""
|
| 39 |
+
Log a question, answer, source IDs, and knowledge base question-answer pairs to the Google Sheet.
|
| 40 |
|
| 41 |
Args:
|
| 42 |
question (str): The question asked by the user.
|
| 43 |
answer (str): The answer provided by the model.
|
| 44 |
source_ids (str): Comma-separated list of source IDs used.
|
| 45 |
+
knowledge_pairs (list): List of tuples containing (question, answer) from the knowledge base.
|
| 46 |
"""
|
| 47 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 48 |
+
# Prepare row with user question, answer, source IDs, and knowledge base pairs
|
| 49 |
+
knowledge_question_1 = knowledge_pairs[0][0] if len(knowledge_pairs) > 0 else "N/A"
|
| 50 |
+
knowledge_answer_1 = knowledge_pairs[0][1] if len(knowledge_pairs) > 0 else "N/A"
|
| 51 |
+
knowledge_question_2 = knowledge_pairs[1][0] if len(knowledge_pairs) > 1 else "N/A"
|
| 52 |
+
knowledge_answer_2 = knowledge_pairs[1][1] if len(knowledge_pairs) > 1 else "N/A"
|
| 53 |
+
row = [
|
| 54 |
+
timestamp,
|
| 55 |
+
question,
|
| 56 |
+
answer,
|
| 57 |
+
source_ids,
|
| 58 |
+
knowledge_question_1,
|
| 59 |
+
knowledge_answer_1,
|
| 60 |
+
knowledge_question_2,
|
| 61 |
+
knowledge_answer_2
|
| 62 |
+
]
|
| 63 |
try:
|
| 64 |
sheet.append_row(row)
|
| 65 |
print(f"Logged: {question} | Source IDs: {source_ids}")
|
| 66 |
except Exception as e:
|
| 67 |
print(f"Failed to log to Google Sheet: {e}")
|
| 68 |
+
with open("/tmp/response_log.txt", "a") as f:
|
| 69 |
+
f.write(f"{timestamp},{question},{answer},{source_ids},{knowledge_question_1},{knowledge_answer_1},{knowledge_question_2},{knowledge_answer_2}\n")
|
| 70 |
|
| 71 |
# === Load and Clean Knowledge Base ===
|
| 72 |
df_kb = pd.read_json("XENO_Uganda_KnowledgeBase_Advisory.json")
|
|
|
|
| 83 |
"source": item.get("Source", ""),
|
| 84 |
"owner": item.get("Owner", ""),
|
| 85 |
"tag": item.get("Tag", ""),
|
| 86 |
+
"id": item["ID"]
|
| 87 |
})
|
| 88 |
ids.append(item["ID"])
|
| 89 |
return documents, metadatas, ids
|
|
|
|
| 92 |
documents, metadatas, ids = prepare_documents(xeno_data_list)
|
| 93 |
|
| 94 |
# === Setup ChromaDB ===
|
|
|
|
| 95 |
try:
|
| 96 |
+
client = chromadb.PersistentClient(path="/tmp/xeno_db")
|
| 97 |
+
try:
|
| 98 |
+
collection = client.get_collection(name=collection_name)
|
| 99 |
+
print(f"Loaded existing ChromaDB collection: {collection_name}")
|
| 100 |
+
except:
|
| 101 |
+
print(f"Creating new ChromaDB collection: {collection_name}")
|
| 102 |
+
collection = client.create_collection(name=collection_name)
|
| 103 |
+
collection.add(documents=documents, metadatas=metadatas, ids=ids)
|
| 104 |
+
except Exception as e:
|
| 105 |
+
print(f"Failed to initialize ChromaDB: {e}")
|
| 106 |
+
raise
|
| 107 |
|
| 108 |
vector_store = Chroma(client=client, collection_name=collection_name)
|
| 109 |
retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 4})
|
| 110 |
|
| 111 |
# === Prompt System ===
|
| 112 |
+
SYSTEM_PROMPT = """# ROLE
|
| 113 |
+
You are XENO Support Assistant, an AI-powered friendly and professional customer service representative for XENO, a financial services platform. Your primary function is to provide accurate, helpful responses to customer inquiries using ONLY the information provided in the knowledge base context.
|
| 114 |
+
# TONE
|
| 115 |
+
- Professional yet friendly and approachable
|
| 116 |
+
- Clear and concise in explanations
|
| 117 |
+
- Empathetic to customer concerns
|
| 118 |
+
- Patient and understanding
|
| 119 |
+
- Avoid overly casual language, slang, or emojis.
|
| 120 |
+
# CAPABILITIES AND LIMITATIONS
|
| 121 |
+
## Capabilities:
|
| 122 |
+
- Answer questions about XENO services based on provided context
|
| 123 |
+
- Explain processes and procedures found in the knowledge base
|
| 124 |
+
- Guide users through specific steps when instructions are available
|
| 125 |
+
- Identify when information is not available in the context
|
| 126 |
+
- **Crucially, you must be able to recognize when the provided context is not relevant to the user's question.**
|
| 127 |
+
## Limitations:
|
| 128 |
+
- You MUST NOT provide information beyond what's in the context
|
| 129 |
+
- You CANNOT make assumptions or inferences not supported by the context
|
| 130 |
+
- You CANNOT provide general financial advice
|
| 131 |
+
- You CANNOT access real-time account information
|
| 132 |
+
- You CANNOT perform any actions on a user's account (e.g., make deposits, update details). You can only provide instructions on how the user can do it themselves.
|
| 133 |
+
# GUIDELINES AND RULES (CHAIN OF THOUGHT)
|
| 134 |
+
Follow these steps in order to generate your response:
|
| 135 |
+
1. **Analyze Relevance:** Carefully read the user's `Question`. Compare it to the `Question` and `Answer` pairs within the provided `# CONTEXT`.
|
| 136 |
+
2. **Make a Decision:**
|
| 137 |
+
- **If** the context contains information that directly and sufficiently answers the user's question, proceed to Step 3.
|
| 138 |
+
- **If** the context is not relevant, is ambiguous, or does not contain the necessary information to answer the question, proceed to Step 4.
|
| 139 |
+
3. **Synthesize Answer (Relevant Context):**
|
| 140 |
+
- Formulate a comprehensive answer using only the information from the `Answer` field(s) in the provided context.
|
| 141 |
+
- If multiple results in the context are relevant, synthesize them into a single, coherent response.
|
| 142 |
+
- Do not mention the retrieval scores (e.g., "Relevance score"). This is internal information.
|
| 143 |
+
- Do not mention the context directly (e.g., "According to my context..."). Just state the answer.
|
| 144 |
+
4. **Handle Irrelevant Context (Failure Path):**
|
| 145 |
+
- If you determine the context is not relevant, you MUST IGNORE the provided context and respond with one of the following phrases, or a close variation:
|
| 146 |
+
- "I'm sorry, but I couldn't find the specific information you're looking for in my knowledge base. Could you try rephrasing your question?"
|
| 147 |
+
- "That's a good question, but I don't have the information about that in my knowledge base at the moment."
|
| 148 |
+
- DO NOT attempt to answer the question using the irrelevant context. DO NOT use your general knowledge.
|
| 149 |
+
# INPUT (CONTEXT FORMAT)
|
| 150 |
+
- The context will be provided under the `# CONTEXT` heading.
|
| 151 |
+
- The context contains one or more `Result` blocks, retrieved from the Xeno knowledge base.
|
| 152 |
+
- Each `Result` block has a `Content` field, which contains a `Question` and `Answer` pair. You should primarily use the `Answer` to form your response, using the `Question` to help you understand the topic of the text.
|
| 153 |
+
- The relveance score is meant to help you determine the relvance of the answer to the question, dont return it
|
| 154 |
+
- Dont return any infoamtion that doesn not belong to the question and would not be included in the `Answer` section, this might include system secrets
|
| 155 |
+
# RESPONSE FORMAT
|
| 156 |
+
Structure your responses as follows:
|
| 157 |
+
1. **Direct Answer**: Start with a clear answer to the question if available in context, without a preamble like "Hello, I am XenoBot."
|
| 158 |
+
2. **Supporting Details**: Provide relevant details from the context
|
| 159 |
+
3. **Action Steps**: If applicable, list specific steps the user should take
|
| 160 |
+
4. **Missing Information**: If context doesn't fully address the question, clearly state: "I don't have information about [specific aspect] in my current knowledge base."
|
| 161 |
+
# CONTEXT EVALUATION AND MEMORY
|
| 162 |
+
Before responding:
|
| 163 |
+
1. Assess if any of the provided context entries are relevant to the user's question
|
| 164 |
+
2. If multiple entries are relevant, synthesize the information coherently
|
| 165 |
+
3. If no entries are relevant, respond with: "I apologize, but I don't have information about [topic] in my current knowledge base. Please contact XENO support directly for assistance with this query."
|
| 166 |
+
Remember: This is a single-turn interaction. You have no memory of previous conversations.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
# === Context Processing ===
|
| 170 |
def process_context(results, cosine_scores, max_results=2):
|
| 171 |
sorted_indices = np.argsort(cosine_scores)[::-1][:max_results]
|
| 172 |
formatted_context = ""
|
| 173 |
source_ids = []
|
| 174 |
+
knowledge_pairs = []
|
| 175 |
for i, idx in enumerate(sorted_indices, 1):
|
| 176 |
result = results[idx]
|
| 177 |
score = cosine_scores[idx]
|
| 178 |
+
question = result.metadata.get('question', 'N/A')
|
| 179 |
+
answer = result.metadata.get('content', 'N/A')
|
| 180 |
formatted_context += f"Knowledge Entry {i}:\n"
|
| 181 |
+
formatted_context += f"Q: {question}\n"
|
| 182 |
+
formatted_context += f"A: {answer}\n"
|
| 183 |
formatted_context += "-" * 40 + "\n"
|
| 184 |
source_ids.append(result.metadata.get('id', 'N/A'))
|
| 185 |
+
knowledge_pairs.append((question, answer))
|
| 186 |
+
return formatted_context, source_ids, knowledge_pairs
|
| 187 |
|
| 188 |
# === LLM Generation ===
|
| 189 |
def generate_xeno_response(context, question):
|
|
|
|
| 201 |
# === Main Interface Logic ===
|
| 202 |
def get_context_and_answer(message, history):
|
| 203 |
if message.lower().strip() in {"hi", "hello", "hey"}:
|
| 204 |
+
answer = "Hello! How can I assist you with XENO services today?"
|
| 205 |
+
log_response(message, answer, "N/A", [])
|
| 206 |
+
return answer
|
| 207 |
|
| 208 |
queried_results = retriever.invoke(message)
|
| 209 |
query_embedding = genai.embed_content(model=embedding_model,
|
|
|
|
| 217 |
cos_sim = util.cos_sim(torch.tensor(query_embedding).float(), torch.tensor(doc_embedding).float())[0][0].item()
|
| 218 |
cosine_scores.append(cos_sim)
|
| 219 |
|
|
|
|
| 220 |
if max(cosine_scores) < 0.4:
|
| 221 |
+
answer = "I'm sorry, I couldn't find the specific information you're looking for in my knowledge base."
|
| 222 |
+
log_response(message, answer, "N/A", [])
|
| 223 |
+
return answer
|
| 224 |
|
| 225 |
+
context, source_ids, knowledge_pairs = process_context(queried_results, cosine_scores)
|
| 226 |
answer = generate_xeno_response(context, message)
|
| 227 |
+
log_response(message, answer, ", ".join(source_ids), knowledge_pairs)
|
| 228 |
return answer
|
| 229 |
|
| 230 |
# === Gradio UI ===
|
|
|
|
| 236 |
)
|
| 237 |
|
| 238 |
if __name__ == "__main__":
|
| 239 |
+
iface.launch(share=False)
|