Devisri515 commited on
Commit
38b974d
·
1 Parent(s): 79e127c

gradio fetches data from fast api

Browse files
Files changed (3) hide show
  1. app.py +24 -101
  2. src/agent.py +2 -4
  3. src/main.py +11 -4
app.py CHANGED
@@ -1,8 +1,7 @@
1
  import os
2
- import gradio as gr
3
- from src.agent import get_agent_executor
4
- from src.file_processor import FileProcessor
5
  import logging
 
 
6
 
7
  # Suppress HuggingFace tokenizer parallelism warning
8
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
@@ -11,42 +10,9 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
- # Initialize Agent
15
- try:
16
- agent_executor = get_agent_executor()
17
- logger.info("Agent initialized successfully")
18
- except Exception as e:
19
- logger.error(f"Failed to initialize agent: {e}")
20
- agent_executor = None
21
-
22
- # Initialize File Processor for user-uploaded documents
23
- file_processor = FileProcessor(embedding_model="all-MiniLM-L6-v2")
24
-
25
- def process_uploaded_files(files) -> str:
26
- """
27
- Wrapper function to process uploaded PDF files using FileProcessor.
28
-
29
- Args:
30
- files: List of file objects from Gradio
31
-
32
- Returns:
33
- Status message
34
- """
35
- return file_processor.process_files(files)
36
-
37
-
38
- def retrieve_from_uploaded_files(query: str, k: int = 4) -> str:
39
- """
40
- Wrapper function to retrieve content from uploaded files using FileProcessor.
41
-
42
- Args:
43
- query: Search query
44
- k: Number of results to return
45
-
46
- Returns:
47
- Retrieved content or empty string if no index
48
- """
49
- return file_processor.retrieve(query, k=k)
50
 
51
 
52
  def determine_source(response_text) -> str:
@@ -76,7 +42,7 @@ def determine_source(response_text) -> str:
76
 
77
  def process_query(message: str, chat_history: list) -> tuple[list, str]:
78
  """
79
- Process user query through uploaded files first, then agent + web search.
80
 
81
  Args:
82
  message: User query
@@ -85,55 +51,37 @@ def process_query(message: str, chat_history: list) -> tuple[list, str]:
85
  Returns:
86
  Tuple of (updated_chat_history, status_message)
87
  """
88
- if not agent_executor:
89
- error_msg = "Agent not initialized. Please check GOOGLE_API_KEY."
90
- chat_history.append([message, f"ERROR: {error_msg}"])
91
- return chat_history, error_msg
92
-
93
  try:
94
- logger.info(f"Processing query: {message}")
95
-
96
- # Step 1: Check uploaded files first
97
- uploaded_content = retrieve_from_uploaded_files(message)
98
-
99
- if uploaded_content:
100
- # If we found relevant content in uploaded files, use it directly
101
- logger.info("Found content in uploaded files")
102
- source = "Source: Uploaded Documents"
103
- full_response = f"{uploaded_content}\n\n--- {source} ---"
104
- chat_history.append([message, full_response])
105
- return chat_history, source
106
-
107
- # Step 2: Fall back to agent (which uses RAG + web search)
108
- inputs = {"messages": [("user", message)]}
109
- result = agent_executor.invoke(inputs)
110
-
111
- # Extract response from agent output
112
- last_message = result["messages"][-1]
113
- response_text = last_message.content
114
 
115
- # Convert to string if it's a list
116
  if isinstance(response_text, list):
117
  response_text = "\n".join(str(item) for item in response_text)
118
  else:
119
  response_text = str(response_text)
120
 
121
- # Determine source
122
  source = determine_source(response_text)
123
-
124
- # Format response with source indicator
125
  full_response = f"{response_text}\n\n--- {source} ---"
126
 
127
- # Append to chat history as list [user, assistant]
128
- chat_history.append([message, full_response])
129
 
130
- logger.info(f"Response generated successfully")
131
  return chat_history, f"Query processed. {source}"
132
-
 
 
 
 
 
133
  except Exception as e:
134
  error_msg = f"Error processing query: {str(e)}"
135
  logger.error(error_msg)
136
- chat_history.append([message, f"ERROR: {error_msg}"])
 
137
  return chat_history, error_msg
138
 
139
  def clear_chat() -> tuple[list, str]:
@@ -143,25 +91,7 @@ def clear_chat() -> tuple[list, str]:
143
  # Build Gradio Interface
144
  with gr.Blocks(title="Agentic RAG Knowledge Search") as demo:
145
  gr.Markdown("# 🔍 Agentic RAG Knowledge Search")
146
- gr.Markdown("Upload your documents or ask questions answered from internal docs (RAG) or the live web — the agent decides.")
147
-
148
- with gr.Group():
149
- gr.Markdown("### Upload Your Documents (Optional)")
150
- file_upload = gr.File(
151
- label="Upload PDF files",
152
- file_count="multiple",
153
- file_types=[".pdf"]
154
- )
155
- upload_btn = gr.Button("Process Uploaded Files", variant="secondary")
156
- upload_status = gr.Textbox(
157
- label="Upload Status",
158
- interactive=False,
159
- lines=2
160
- )
161
-
162
- # Set initial status
163
- upload_status.value = "No files uploaded. Using internal docs + web search."
164
-
165
  with gr.Group():
166
  chatbot = gr.Chatbot(
167
  label="Conversation History",
@@ -171,7 +101,7 @@ with gr.Blocks(title="Agentic RAG Knowledge Search") as demo:
171
 
172
  with gr.Row():
173
  user_input = gr.Textbox(
174
- placeholder="Ask a question about your uploaded documents or anything on the web...",
175
  label="Your Question",
176
  lines=2
177
  )
@@ -186,13 +116,6 @@ with gr.Blocks(title="Agentic RAG Knowledge Search") as demo:
186
  lines=1
187
  )
188
 
189
- # Wire up file upload
190
- upload_btn.click(
191
- fn=process_uploaded_files,
192
- inputs=[file_upload],
193
- outputs=[upload_status]
194
- )
195
-
196
  # Wire up chat interactions
197
  submit_btn.click(
198
  fn=process_query,
 
1
  import os
 
 
 
2
  import logging
3
+ import gradio as gr
4
+ import requests
5
 
6
  # Suppress HuggingFace tokenizer parallelism warning
7
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
 
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
+ # FastAPI endpoint configuration
14
+ FASTAPI_URL = os.getenv("FASTAPI_URL", "http://127.0.0.1:8000")
15
+ CHAT_ENDPOINT = f"{FASTAPI_URL}/chat"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
 
18
  def determine_source(response_text) -> str:
 
42
 
43
  def process_query(message: str, chat_history: list) -> tuple[list, str]:
44
  """
45
+ Process user query by calling the FastAPI /chat endpoint.
46
 
47
  Args:
48
  message: User query
 
51
  Returns:
52
  Tuple of (updated_chat_history, status_message)
53
  """
 
 
 
 
 
54
  try:
55
+ logger.info(f"Sending query to FastAPI: {message}")
56
+ response = requests.post(CHAT_ENDPOINT, json={"query": message}, timeout=60)
57
+ response.raise_for_status()
58
+ payload = response.json()
59
+ response_text = payload.get("response", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
 
61
  if isinstance(response_text, list):
62
  response_text = "\n".join(str(item) for item in response_text)
63
  else:
64
  response_text = str(response_text)
65
 
 
66
  source = determine_source(response_text)
 
 
67
  full_response = f"{response_text}\n\n--- {source} ---"
68
 
69
+ chat_history.append({"role": "user", "content": message})
70
+ chat_history.append({"role": "assistant", "content": full_response})
71
 
72
+ logger.info("Response received from FastAPI")
73
  return chat_history, f"Query processed. {source}"
74
+ except requests.exceptions.RequestException as e:
75
+ error_msg = f"FastAPI request failed: {str(e)}"
76
+ logger.error(error_msg)
77
+ chat_history.append({"role": "user", "content": message})
78
+ chat_history.append({"role": "assistant", "content": f"ERROR: {error_msg}"})
79
+ return chat_history, error_msg
80
  except Exception as e:
81
  error_msg = f"Error processing query: {str(e)}"
82
  logger.error(error_msg)
83
+ chat_history.append({"role": "user", "content": message})
84
+ chat_history.append({"role": "assistant", "content": f"ERROR: {error_msg}"})
85
  return chat_history, error_msg
86
 
87
  def clear_chat() -> tuple[list, str]:
 
91
  # Build Gradio Interface
92
  with gr.Blocks(title="Agentic RAG Knowledge Search") as demo:
93
  gr.Markdown("# 🔍 Agentic RAG Knowledge Search")
94
+ gr.Markdown("Ask questions answered from internal documents (RAG) or the live web — the agent decides.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  with gr.Group():
96
  chatbot = gr.Chatbot(
97
  label="Conversation History",
 
101
 
102
  with gr.Row():
103
  user_input = gr.Textbox(
104
+ placeholder="Ask a question about policy documents or anything on the web...",
105
  label="Your Question",
106
  lines=2
107
  )
 
116
  lines=1
117
  )
118
 
 
 
 
 
 
 
 
119
  # Wire up chat interactions
120
  submit_btn.click(
121
  fn=process_query,
src/agent.py CHANGED
@@ -42,11 +42,9 @@ def get_agent_executor():
42
  if not os.getenv("GOOGLE_API_KEY"):
43
  raise ValueError("GOOGLE_API_KEY not found in .env file")
44
 
45
- print("Initializing Gemini Agent (Model: gemini-2.5-flash)...")
46
-
47
- # Using the model explicitly found in your check_model script
48
  llm = ChatGoogleGenerativeAI(
49
- model="gemini-2.5-flash",
50
  temperature=0
51
  )
52
 
 
42
  if not os.getenv("GOOGLE_API_KEY"):
43
  raise ValueError("GOOGLE_API_KEY not found in .env file")
44
 
45
+ print("Initializing Gemini Agent (Model: gemini-2.5-flash-lite)...")
 
 
46
  llm = ChatGoogleGenerativeAI(
47
+ model="gemini-2.5-flash-lite",
48
  temperature=0
49
  )
50
 
src/main.py CHANGED
@@ -55,10 +55,17 @@ async def chat(request: QueryRequest):
55
  # The result contains the entire conversation state.
56
  # The last message is the AI's answer.
57
  last_message = result["messages"][-1]
58
-
59
- return QueryResponse(
60
- response=last_message.content
61
- )
 
 
 
 
 
 
 
62
 
63
  except Exception as e:
64
  logger.error(f"Error processing query: {e}")
 
55
  # The result contains the entire conversation state.
56
  # The last message is the AI's answer.
57
  last_message = result["messages"][-1]
58
+
59
+ # Gemini may return content as a list of typed blocks; extract plain text
60
+ content = last_message.content
61
+ if isinstance(content, list):
62
+ content = " ".join(
63
+ block["text"] if isinstance(block, dict) else str(block)
64
+ for block in content
65
+ if not isinstance(block, dict) or block.get("type") == "text"
66
+ )
67
+
68
+ return QueryResponse(response=str(content))
69
 
70
  except Exception as e:
71
  logger.error(f"Error processing query: {e}")