Spaces:
Runtime error

diptaraj commited on
Commit
97f043c
·
1 Parent(s): 06430dd

V2.2-Pro: Smart Prompting and Auto-Retry for 429s

Browse files
Files changed (2) hide show
  1. app/main.py +5 -5
  2. app/services/llm_providers.py +46 -21
app/main.py CHANGED
@@ -13,7 +13,7 @@ logger = logging.getLogger("rag-pipeline")
13
  app = FastAPI(
14
  title="RAG Pipeline API",
15
  description="Production-grade Document RAG with Supabase and Gemini",
16
- version="1.0.0-prod-v2.1-final",
17
  docs_url="/docs",
18
  redoc_url="/redoc"
19
  )
@@ -25,15 +25,15 @@ app.include_router(metadata.router)
25
 
26
  @app.on_event("startup")
27
  async def startup_event():
28
- logger.info("Initializing RAG Pipeline v2.1-final...")
29
  logger.info(f"Debug mode: {settings.DEBUG}")
30
 
31
  @app.get("/")
32
  async def root():
33
  return {
34
- "message": "RAG Pipeline API - Stable Production v2.1",
35
  "debug": settings.DEBUG,
36
- "version": "1.0.0-prod-v2.1-final",
37
  "status": "online",
38
  "endpoints": [
39
  "/docs - API Documentation",
@@ -56,7 +56,7 @@ async def health():
56
 
57
  return {
58
  "status": "healthy",
59
- "version": "v2.1-final",
60
  "services": {
61
  "api": "running",
62
  "database": "connected",
 
13
  app = FastAPI(
14
  title="RAG Pipeline API",
15
  description="Production-grade Document RAG with Supabase and Gemini",
16
+ version="1.0.0-prod-v2.2-pro",
17
  docs_url="/docs",
18
  redoc_url="/redoc"
19
  )
 
25
 
26
  @app.on_event("startup")
27
  async def startup_event():
28
+ logger.info("Initializing RAG Pipeline v2.2-pro...")
29
  logger.info(f"Debug mode: {settings.DEBUG}")
30
 
31
  @app.get("/")
32
  async def root():
33
  return {
34
+ "message": "RAG Pipeline API - Stable Production v2.2-pro",
35
  "debug": settings.DEBUG,
36
+ "version": "1.0.0-prod-v2.2-pro",
37
  "status": "online",
38
  "endpoints": [
39
  "/docs - API Documentation",
 
56
 
57
  return {
58
  "status": "healthy",
59
+ "version": "v2.2-pro",
60
  "services": {
61
  "api": "running",
62
  "database": "connected",
app/services/llm_providers.py CHANGED
@@ -1,7 +1,8 @@
1
  from typing import List, Optional
2
  import logging
 
3
  from google import genai
4
- from google.genai import errors
5
  import openai
6
  import cohere
7
  from pydantic import BaseModel
@@ -29,25 +30,47 @@ class LLMProvider:
29
  class GeminiProvider(LLMProvider):
30
  def __init__(self):
31
  super().__init__("gemini", 1)
32
- # Using Gemini 2.0 Flash as the most stable current flagship
33
  self.model_id = "gemini-2.0-flash"
34
 
35
  def generate(self, request: LLMRequest) -> str:
36
  if not gemini_client:
37
  raise ValueError("Gemini API key not configured")
38
 
39
- prompt = f"Context: {request.context}\n\nQuestion: {request.query}\n\nAnswer:"
 
 
 
 
 
 
40
 
41
- try:
42
- response = gemini_client.models.generate_content(
43
- model=self.model_id,
44
- contents=prompt
45
- )
46
- return response.text
47
- except Exception as e:
48
- if "429" in str(e) or "RESOURCE_EXHAUSTED" in str(e):
49
- logger.error(f"Gemini 429: Rate limit reached. {str(e)}")
50
- raise e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  class OpenAIProvider(LLMProvider):
53
  def __init__(self):
@@ -64,12 +87,15 @@ class OpenAIProvider(LLMProvider):
64
  if not self.client:
65
  raise ValueError("OpenAI API key not configured")
66
 
67
- messages = [
68
- {"role": "user", "content": f"Context: {request.context}\n\nQuestion: {request.query}"}
69
- ]
70
  response = self.client.chat.completions.create(
71
  model="gpt-3.5-turbo",
72
- messages=messages,
 
 
 
73
  temperature=0.2,
74
  max_tokens=500
75
  )
@@ -90,7 +116,7 @@ class CohereProvider(LLMProvider):
90
  if not self.client:
91
  raise ValueError("Cohere API key not configured")
92
 
93
- prompt = f"Context: {request.context}\n\nQuestion: {request.query}\n\nAnswer:"
94
  response = self.client.generate(
95
  model="command-r",
96
  prompt=prompt,
@@ -125,15 +151,14 @@ def generate_with_fallback(request: LLMRequest) -> dict:
125
  error_str = str(e)
126
  logger.error(f"Provider {provider.name} failed: {error_str}")
127
 
128
- # Special message for 429s (Rate Limit)
129
  if "429" in error_str or "quota" in error_str.lower():
130
- last_error = f"Rate limit reached for {provider.name}. Please wait 60 seconds."
131
  else:
132
  last_error = error_str
133
  continue
134
 
135
  return {
136
- "answer": f"API Error: {last_error}",
137
  "provider_used": "none",
138
  "success": False,
139
  "error": last_error
 
1
  from typing import List, Optional
2
  import logging
3
+ import time
4
  from google import genai
5
+ from google.genai import types
6
  import openai
7
  import cohere
8
  from pydantic import BaseModel
 
30
  class GeminiProvider(LLMProvider):
31
  def __init__(self):
32
  super().__init__("gemini", 1)
 
33
  self.model_id = "gemini-2.0-flash"
34
 
35
  def generate(self, request: LLMRequest) -> str:
36
  if not gemini_client:
37
  raise ValueError("Gemini API key not configured")
38
 
39
+ # PROMPT IMPROVEMENTS: STRICT INSTRUCTIONS
40
+ system_prompt = (
41
+ "You are a professional RAG assistant. "
42
+ "Use ONLY the following context to answer the user's question. "
43
+ "If the answer is not in the context, say 'I cannot find the answer in the documents provided.' "
44
+ "Keep your answer concise and accurate. DO NOT repeat the context itself; just provide the answer."
45
+ )
46
 
47
+ user_prompt = f"CONTEXT:\n{request.context}\n\nQUESTION: {request.query}\n\nANSWER:"
48
+
49
+ # Retry loop for 429s
50
+ max_retries = 3
51
+ for attempt in range(max_retries):
52
+ try:
53
+ response = gemini_client.models.generate_content(
54
+ model=self.model_id,
55
+ contents=user_prompt,
56
+ config=types.GenerateContentConfig(
57
+ system_instruction=system_prompt,
58
+ temperature=0.1, # Focused, deterministic answers
59
+ max_output_tokens=1000,
60
+ top_p=0.9
61
+ )
62
+ )
63
+ if not response.text:
64
+ raise ValueError("Empty response from AI")
65
+ return response.text
66
+ except Exception as e:
67
+ error_str = str(e)
68
+ if ("429" in error_str or "quota" in error_str.lower() or "RESOURCE_EXHAUSTED" in error_str) and attempt < max_retries - 1:
69
+ wait_time = 10 * (attempt + 1)
70
+ logger.warning(f"Gemini Rate Limit hit. Retrying in {wait_time}s... (Attempt {attempt+1}/{max_retries})")
71
+ time.sleep(wait_time)
72
+ continue
73
+ raise e
74
 
75
  class OpenAIProvider(LLMProvider):
76
  def __init__(self):
 
87
  if not self.client:
88
  raise ValueError("OpenAI API key not configured")
89
 
90
+ system_msg = "You are a helpful assistant. Use the provided context to answer the question concisely."
91
+ user_msg = f"Context: {request.context}\n\nQuestion: {request.query}"
92
+
93
  response = self.client.chat.completions.create(
94
  model="gpt-3.5-turbo",
95
+ messages=[
96
+ {"role": "system", "content": system_msg},
97
+ {"role": "user", "content": user_msg}
98
+ ],
99
  temperature=0.2,
100
  max_tokens=500
101
  )
 
116
  if not self.client:
117
  raise ValueError("Cohere API key not configured")
118
 
119
+ prompt = f"Use the context below to answer the question.\nContext: {request.context}\nQuestion: {request.query}\nAnswer:"
120
  response = self.client.generate(
121
  model="command-r",
122
  prompt=prompt,
 
151
  error_str = str(e)
152
  logger.error(f"Provider {provider.name} failed: {error_str}")
153
 
 
154
  if "429" in error_str or "quota" in error_str.lower():
155
+ last_error = f"Rate limit reached for {provider.name}. The system tried retrying but the quota is exhausted. Please wait 60 seconds."
156
  else:
157
  last_error = error_str
158
  continue
159
 
160
  return {
161
+ "answer": f"AI Error: {last_error}",
162
  "provider_used": "none",
163
  "success": False,
164
  "error": last_error