Spaces:
Running
Running
Rivalcoder
commited on
Commit
·
641e531
1
Parent(s):
63bcf13
[edit] Fallback For Erro Response
Browse files
llm.py
CHANGED
@@ -13,7 +13,7 @@ if not api_keys:
|
|
13 |
api_keys = [k.strip() for k in api_keys.split(",") if k.strip()]
|
14 |
print(f"Loaded {len(api_keys)} Gemini API key(s)")
|
15 |
|
16 |
-
def query_gemini(questions, contexts):
|
17 |
context = "\n\n".join(contexts)
|
18 |
questions_text = "\n".join([f"{i+1}. {q}" for i, q in enumerate(questions)])
|
19 |
|
@@ -30,10 +30,11 @@ You are an expert insurance assistant generating formal yet user-facing answers
|
|
30 |
- If the question is NOT covered by the context Provide Then Give The General Answer It Not Be In Context if Nothing Found Give Normal Ai Answer for The Question Correctly
|
31 |
- Limit each answer to 2–3 sentences, and do not repeat unnecessary information.
|
32 |
- If a question can be answered with a simple "Yes", "No", "Can apply", or "Cannot apply", then begin the answer with that phrase, followed by a short supporting Statement In Natural Human Like response.So Give A Good Answer For The Question With Correct Information.
|
33 |
-
- Avoid giving
|
34 |
- Dont Give Long theory Like Response Very Large Response Just Give Short And Good Response For The Question.
|
35 |
- If the question is general (math, code, tech, etc.) and No Matches With Context, answer normally without referencing the document.
|
36 |
- Avoid Saying “Not found” or “Out of scope” For The Answer of The Question Try to Give Basic General Response For The Question.
|
|
|
37 |
|
38 |
🛑 DO NOT:
|
39 |
- Mention "context", "document", or "text" in any form.
|
@@ -45,19 +46,16 @@ You are an expert insurance assistant generating formal yet user-facing answers
|
|
45 |
- Say "This info is not covered", "Out of scope", or similar.
|
46 |
- Say "Please refer to other sources".
|
47 |
- Say "Not mentioned in the document" — if nothing is found, give a general insurance-based response.
|
48 |
-
- If no general answer is possible, only then say: "No relevant information is available to answer this question."
|
49 |
|
50 |
✅ DO:
|
51 |
- Write in clean, informative language.
|
52 |
- Give complete answers in 2–3 sentences maximum.
|
53 |
|
54 |
-
|
55 |
📝 EXAMPLE ANSWERS:
|
56 |
- "Yes, the policy covers damage to personal property caused by fire, up to a limit of $50,000."
|
57 |
- "No, the policy does not cover pre-existing conditions."
|
58 |
- "The waiting period for coverage to begin is 30 days from the start date of the policy."
|
59 |
|
60 |
-
|
61 |
📤 OUTPUT FORMAT (strict):
|
62 |
Respond with only the following JSON — no explanations, no comments, no markdown:
|
63 |
|
@@ -81,33 +79,41 @@ Your task: For each question, provide a complete, professional, and clearly writ
|
|
81 |
last_exception = None
|
82 |
|
83 |
for key_idx, key in enumerate(api_keys):
|
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 |
print(f"All Gemini API keys failed. Last error: {last_exception}")
|
113 |
return {"answers": [f"Error generating response: {str(last_exception)}"] * len(questions)}
|
|
|
13 |
api_keys = [k.strip() for k in api_keys.split(",") if k.strip()]
|
14 |
print(f"Loaded {len(api_keys)} Gemini API key(s)")
|
15 |
|
16 |
+
def query_gemini(questions, contexts, max_retries=3):
|
17 |
context = "\n\n".join(contexts)
|
18 |
questions_text = "\n".join([f"{i+1}. {q}" for i, q in enumerate(questions)])
|
19 |
|
|
|
30 |
- If the question is NOT covered by the context Provide Then Give The General Answer It Not Be In Context if Nothing Found Give Normal Ai Answer for The Question Correctly
|
31 |
- Limit each answer to 2–3 sentences, and do not repeat unnecessary information.
|
32 |
- If a question can be answered with a simple "Yes", "No", "Can apply", or "Cannot apply", then begin the answer with that phrase, followed by a short supporting Statement In Natural Human Like response.So Give A Good Answer For The Question With Correct Information.
|
33 |
+
- Avoid giving theory Based Long Long answers Try to Give Short Good Reasonable Answers.
|
34 |
- Dont Give Long theory Like Response Very Large Response Just Give Short And Good Response For The Question.
|
35 |
- If the question is general (math, code, tech, etc.) and No Matches With Context, answer normally without referencing the document.
|
36 |
- Avoid Saying “Not found” or “Out of scope” For The Answer of The Question Try to Give Basic General Response For The Question.
|
37 |
+
- If no general answer is possible, only then say: "No relevant information is available to answer this question."
|
38 |
|
39 |
🛑 DO NOT:
|
40 |
- Mention "context", "document", or "text" in any form.
|
|
|
46 |
- Say "This info is not covered", "Out of scope", or similar.
|
47 |
- Say "Please refer to other sources".
|
48 |
- Say "Not mentioned in the document" — if nothing is found, give a general insurance-based response.
|
|
|
49 |
|
50 |
✅ DO:
|
51 |
- Write in clean, informative language.
|
52 |
- Give complete answers in 2–3 sentences maximum.
|
53 |
|
|
|
54 |
📝 EXAMPLE ANSWERS:
|
55 |
- "Yes, the policy covers damage to personal property caused by fire, up to a limit of $50,000."
|
56 |
- "No, the policy does not cover pre-existing conditions."
|
57 |
- "The waiting period for coverage to begin is 30 days from the start date of the policy."
|
58 |
|
|
|
59 |
📤 OUTPUT FORMAT (strict):
|
60 |
Respond with only the following JSON — no explanations, no comments, no markdown:
|
61 |
|
|
|
79 |
last_exception = None
|
80 |
|
81 |
for key_idx, key in enumerate(api_keys):
|
82 |
+
for attempt in range(max_retries):
|
83 |
+
try:
|
84 |
+
genai.configure(api_key=key)
|
85 |
+
model = genai.GenerativeModel("gemini-2.5-flash-lite")
|
86 |
+
response = model.generate_content(prompt)
|
87 |
+
response_text = getattr(response, "text", "").strip()
|
88 |
+
|
89 |
+
if not response_text:
|
90 |
+
raise ValueError("Empty response received from Gemini API.")
|
91 |
+
|
92 |
+
# Clean JSON from wrapped code blocks
|
93 |
+
if response_text.startswith("```json"):
|
94 |
+
response_text = response_text.replace("```json", "").replace("```", "").strip()
|
95 |
+
elif response_text.startswith("```"):
|
96 |
+
response_text = response_text.replace("```", "").strip()
|
97 |
+
|
98 |
+
# Optional debug log:
|
99 |
+
# print(f"[Gemini Response]: {response_text[:300]}")
|
100 |
+
|
101 |
+
parsed = json.loads(response_text)
|
102 |
+
if "answers" in parsed and isinstance(parsed["answers"], list):
|
103 |
+
return parsed
|
104 |
+
else:
|
105 |
+
raise ValueError("Invalid response format received from Gemini.")
|
106 |
+
|
107 |
+
except Exception as e:
|
108 |
+
msg = str(e).lower()
|
109 |
+
if "429" in msg or "quota" in msg or "rate limit" in msg or "exceeded" in msg:
|
110 |
+
print(f"Gemini key {key[:8]}... quota/rate limited. Trying next key ({key_idx+1}/{len(api_keys)}).")
|
111 |
+
last_exception = e
|
112 |
+
break # Try next key
|
113 |
+
else:
|
114 |
+
print(f"Retry {attempt+1}/{max_retries} failed using Gemini key {key[:8]}...: {e}")
|
115 |
+
last_exception = e
|
116 |
+
continue # Retry same key
|
117 |
|
118 |
print(f"All Gemini API keys failed. Last error: {last_exception}")
|
119 |
return {"answers": [f"Error generating response: {str(last_exception)}"] * len(questions)}
|