Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -49,34 +49,35 @@ async def health_check():
|
|
| 49 |
|
| 50 |
@app.post("/chat")
|
| 51 |
async def chat_with_gemini(input_data: ChatInput):
|
| 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 |
headers = {"Content-Type": "application/json"}
|
| 81 |
payload = {
|
| 82 |
"contents": [
|
|
@@ -85,19 +86,16 @@ Answer:"""
|
|
| 85 |
}
|
| 86 |
]
|
| 87 |
}
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
debug_info
|
| 97 |
-
|
| 98 |
-
debug_info += f" (Top {len(relevant_docs)} documents used)"
|
| 99 |
-
|
| 100 |
-
return {"bot_response": bot_response, "debug": debug_info}
|
| 101 |
|
| 102 |
except Exception as e:
|
| 103 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 49 |
|
| 50 |
@app.post("/chat")
|
| 51 |
async def chat_with_gemini(input_data: ChatInput):
|
| 52 |
+
|
| 53 |
+
# 1. Search Knowledge Base
|
| 54 |
+
kb_results = search_knowledge_base(input_data.user_message, top_k=10)
|
| 55 |
+
logging.info(kb_results)
|
| 56 |
+
|
| 57 |
+
context = ""
|
| 58 |
+
relevant_docs = []
|
| 59 |
+
|
| 60 |
+
# 2. Extract relevant KB docs
|
| 61 |
+
if kb_results and kb_results.get("documents"):
|
| 62 |
+
relevant_docs = kb_results["documents"][0][:2]
|
| 63 |
+
context = "\n\n".join(relevant_docs)
|
| 64 |
+
|
| 65 |
+
# 3. If KB contains direct answer → RETURN it (No LLM call)
|
| 66 |
+
if context:
|
| 67 |
+
kb_answer = f"From knowledge base:\n\n{context}"
|
| 68 |
+
return {
|
| 69 |
+
"bot_response": kb_answer,
|
| 70 |
+
"debug_info": f"Context found: YES, docs used: {len(relevant_docs)}"
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
# 4. If KB empty → fallback to Gemini
|
| 74 |
+
enhanced_prompt = (
|
| 75 |
+
f"User question: {input_data.user_message}\n\n"
|
| 76 |
+
"No relevant KB found. You must raise a ticket.\n"
|
| 77 |
+
"Say: 'I'm raising a ticket. Ticket# 12345'."
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# 5. Call Gemini
|
| 81 |
headers = {"Content-Type": "application/json"}
|
| 82 |
payload = {
|
| 83 |
"contents": [
|
|
|
|
| 86 |
}
|
| 87 |
]
|
| 88 |
}
|
| 89 |
+
|
| 90 |
+
response = requests.post(GEMINI_URL, headers=headers, json=payload)
|
| 91 |
+
result = response.json()
|
| 92 |
+
|
| 93 |
+
bot_response = result["candidates"][0]["content"]["parts"][0]["text"]
|
| 94 |
+
|
| 95 |
+
return {
|
| 96 |
+
"bot_response": bot_response,
|
| 97 |
+
"debug_info": "Context found: NO"
|
| 98 |
+
}
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
except Exception as e:
|
| 101 |
raise HTTPException(status_code=500, detail=str(e))
|