Jaita commited on
Commit
fec7fe0
·
verified ·
1 Parent(s): bd5225f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +39 -41
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
- try:
53
- # Retrieve relevant documents from knowledge base
54
-
55
- kb_results = search_knowledge_base(input_data.user_message, top_k=10)
56
- logging.info(f"kb_results are: {kb_results}")
57
-
58
- # Extract relevant context from search results
59
- context = ""
60
- if kb_results and kb_results.get('documents'):
61
- # Limit context to avoid token limits - take top 2 most relevant
62
- relevant_docs = kb_results['documents'][0][:2]
63
- context = "\n\n".join(relevant_docs)
64
-
65
- # Construct enhanced prompt with context
66
- if context:
67
- enhanced_prompt = f"""Use the following knowledge base context to answer the user's question accurately.
68
- If the context contains relevant information, base your answer on it.
69
- If the context doesn't help, say you're raising a ticket and provide a ticket number.
70
-
71
- Knowledge Base Context:
72
- {context}
73
-
74
- User Question: {input_data.user_message}
75
-
76
- Answer:"""
77
- else:
78
- enhanced_prompt = f"User Question: {input_data.user_message}\n\nAnswer:"
79
-
 
80
  headers = {"Content-Type": "application/json"}
81
  payload = {
82
  "contents": [
@@ -85,19 +86,16 @@ Answer:"""
85
  }
86
  ]
87
  }
88
-
89
- response = requests.post(GEMINI_URL, headers=headers, json=payload, verify=False) # SSL disabled for testing
90
- result = response.json()
91
-
92
- # Extract Gemini's response
93
- bot_response = result["candidates"][0]["content"]["parts"][0]["text"]
94
-
95
- # Include debug info in response
96
- debug_info = f"Context found: {'Yes' if context else 'No'}"
97
- if context:
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))