mgbam commited on
Commit
f8873d7
·
verified ·
1 Parent(s): cc37352

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -24
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # ------------------------------
2
- # Enhanced NeuroResearch AI System
3
  # ------------------------------
4
  import logging
5
  import os
@@ -7,10 +7,12 @@ import re
7
  import hashlib
8
  import json
9
  import time
 
10
  from datetime import datetime
 
11
  from concurrent.futures import ThreadPoolExecutor, as_completed
12
  from typing import List, Dict, Any, Optional, Sequence
13
- import chromadb
14
  import requests
15
  import streamlit as st
16
 
@@ -25,11 +27,14 @@ from langgraph.graph.message import add_messages
25
  from typing_extensions import TypedDict, Annotated
26
  from langchain.tools.retriever import create_retriever_tool
27
 
 
 
 
28
  # ------------------------------
29
  # Logging Configuration
30
  # ------------------------------
31
  logging.basicConfig(
32
- level=logging.INFO,
33
  format="%(asctime)s [%(levelname)s] %(message)s"
34
  )
35
  logger = logging.getLogger(__name__)
@@ -53,11 +58,11 @@ class ResearchConfig:
53
  MAX_CONCURRENT_REQUESTS = 5
54
  EMBEDDING_DIMENSIONS = 1536
55
  DOCUMENT_MAP = {
56
- "Research Report: Results of a New AI Model Improving Image Recognition Accuracy to 98%":
57
  "CV-Transformer Hybrid Architecture",
58
- "Academic Paper Summary: Why Transformers Became the Mainstream Architecture in Natural Language Processing":
59
  "Transformer Architecture Analysis",
60
- "Latest Trends in Machine Learning Methods Using Quantum Computing":
61
  "Quantum ML Frontiers"
62
  }
63
  ANALYSIS_TEMPLATE = (
@@ -85,7 +90,7 @@ if not ResearchConfig.DEEPSEEK_API_KEY:
85
  # ------------------------------
86
  class QuantumDocumentManager:
87
  """
88
- Manages the creation of Chroma collections from raw document texts.
89
  """
90
  def __init__(self) -> None:
91
  try:
@@ -197,7 +202,7 @@ class CognitiveProcessor:
197
 
198
  def process_query(self, prompt: str) -> Dict:
199
  """
200
- Process a query by sending multiple API requests in parallel.
201
  """
202
  futures = []
203
  for _ in range(3): # Triple redundancy for reliability
@@ -254,7 +259,6 @@ class CognitiveProcessor:
254
  if not valid_results:
255
  logger.error("All API requests failed.")
256
  return {"error": "All API requests failed"}
257
- # Choose the response with the longest content
258
  return max(valid_results, key=lambda x: len(x.get('choices', [{}])[0].get('message', {}).get('content', '')))
259
 
260
  # ------------------------------
@@ -291,14 +295,16 @@ class ResearchWorkflow:
291
 
292
  def ingest_query(self, state: AgentState) -> Dict:
293
  """
294
- Ingests the research query.
295
  """
296
  try:
297
  query = state["messages"][-1].content
 
 
298
  logger.info("Query ingested.")
299
  return {
300
  "messages": [AIMessage(content="Query ingested successfully")],
301
- "context": {"raw_query": query},
302
  "metadata": {"timestamp": datetime.now().isoformat()}
303
  }
304
  except Exception as e:
@@ -314,7 +320,7 @@ class ResearchWorkflow:
314
  logger.info(f"Retrieved {len(docs)} documents for query.")
315
  return {
316
  "messages": [AIMessage(content=f"Retrieved {len(docs)} documents")],
317
- "context": {"documents": docs, "retrieval_time": time.time()}
318
  }
319
  except Exception as e:
320
  return self._error_state(f"Retrieval Error: {str(e)}")
@@ -333,7 +339,7 @@ class ResearchWorkflow:
333
  logger.info("Content analysis completed.")
334
  return {
335
  "messages": [AIMessage(content=response.get('choices', [{}])[0].get('message', {}).get('content', ''))],
336
- "context": {"analysis": response}
337
  }
338
  except Exception as e:
339
  return self._error_state(f"Analysis Error: {str(e)}")
@@ -351,18 +357,18 @@ class ResearchWorkflow:
351
  response = self.processor.process_query(validation_prompt)
352
  logger.info("Output validation completed.")
353
  return {
354
- "messages": [
355
- AIMessage(
356
- content=analysis +
357
- f"\n\nValidation: {response.get('choices', [{}])[0].get('message', {}).get('content', '')}"
358
- )
359
- ]
360
  }
361
 
362
  def refine_results(self, state: AgentState) -> Dict:
363
  """
364
  Refines the analysis report if validation fails.
 
365
  """
 
 
 
 
366
  refinement_prompt = (
367
  f"Refine this analysis:\n{state['messages'][-1].content}\n\n"
368
  "Improve:\n1. Technical precision\n2. Empirical grounding\n3. Theoretical coherence"
@@ -370,18 +376,19 @@ class ResearchWorkflow:
370
  response = self.processor.process_query(refinement_prompt)
371
  logger.info("Refinement completed.")
372
  return {
373
- "messages": [
374
- AIMessage(
375
- content=response.get('choices', [{}])[0].get('message', {}).get('content', '')
376
- )
377
- ],
378
  "context": state["context"]
379
  }
380
 
381
  def _quality_check(self, state: AgentState) -> str:
382
  """
383
  Checks whether the analysis report is valid.
 
384
  """
 
 
 
 
385
  content = state["messages"][-1].content
386
  quality = "valid" if "VALID" in content else "invalid"
387
  logger.info(f"Quality check returned: {quality}")
 
1
  # ------------------------------
2
+ # Enhanced NeuroResearch AI System with Refinement Counter
3
  # ------------------------------
4
  import logging
5
  import os
 
7
  import hashlib
8
  import json
9
  import time
10
+ import sys
11
  from datetime import datetime
12
+ import chromdb
13
  from concurrent.futures import ThreadPoolExecutor, as_completed
14
  from typing import List, Dict, Any, Optional, Sequence
15
+
16
  import requests
17
  import streamlit as st
18
 
 
27
  from typing_extensions import TypedDict, Annotated
28
  from langchain.tools.retriever import create_retriever_tool
29
 
30
+ # Optionally increase the recursion limit if needed
31
+ sys.setrecursionlimit(100)
32
+
33
  # ------------------------------
34
  # Logging Configuration
35
  # ------------------------------
36
  logging.basicConfig(
37
+ level=logging.INFO,
38
  format="%(asctime)s [%(levelname)s] %(message)s"
39
  )
40
  logger = logging.getLogger(__name__)
 
58
  MAX_CONCURRENT_REQUESTS = 5
59
  EMBEDDING_DIMENSIONS = 1536
60
  DOCUMENT_MAP = {
61
+ "Research Report: Results of a New AI Model Improving Image Recognition Accuracy to 98%":
62
  "CV-Transformer Hybrid Architecture",
63
+ "Academic Paper Summary: Why Transformers Became the Mainstream Architecture in Natural Language Processing":
64
  "Transformer Architecture Analysis",
65
+ "Latest Trends in Machine Learning Methods Using Quantum Computing":
66
  "Quantum ML Frontiers"
67
  }
68
  ANALYSIS_TEMPLATE = (
 
90
  # ------------------------------
91
  class QuantumDocumentManager:
92
  """
93
+ Manages creation of Chroma collections from raw document texts.
94
  """
95
  def __init__(self) -> None:
96
  try:
 
202
 
203
  def process_query(self, prompt: str) -> Dict:
204
  """
205
+ Processes a query by sending multiple API requests in parallel.
206
  """
207
  futures = []
208
  for _ in range(3): # Triple redundancy for reliability
 
259
  if not valid_results:
260
  logger.error("All API requests failed.")
261
  return {"error": "All API requests failed"}
 
262
  return max(valid_results, key=lambda x: len(x.get('choices', [{}])[0].get('message', {}).get('content', '')))
263
 
264
  # ------------------------------
 
295
 
296
  def ingest_query(self, state: AgentState) -> Dict:
297
  """
298
+ Ingests the research query and initializes the refinement counter.
299
  """
300
  try:
301
  query = state["messages"][-1].content
302
+ # Initialize context with raw query and refinement counter
303
+ new_context = {"raw_query": query, "refine_count": 0}
304
  logger.info("Query ingested.")
305
  return {
306
  "messages": [AIMessage(content="Query ingested successfully")],
307
+ "context": new_context,
308
  "metadata": {"timestamp": datetime.now().isoformat()}
309
  }
310
  except Exception as e:
 
320
  logger.info(f"Retrieved {len(docs)} documents for query.")
321
  return {
322
  "messages": [AIMessage(content=f"Retrieved {len(docs)} documents")],
323
+ "context": {"documents": docs, "retrieval_time": time.time(), "refine_count": state["context"].get("refine_count", 0)}
324
  }
325
  except Exception as e:
326
  return self._error_state(f"Retrieval Error: {str(e)}")
 
339
  logger.info("Content analysis completed.")
340
  return {
341
  "messages": [AIMessage(content=response.get('choices', [{}])[0].get('message', {}).get('content', ''))],
342
+ "context": {"analysis": response, "refine_count": state["context"].get("refine_count", 0)}
343
  }
344
  except Exception as e:
345
  return self._error_state(f"Analysis Error: {str(e)}")
 
357
  response = self.processor.process_query(validation_prompt)
358
  logger.info("Output validation completed.")
359
  return {
360
+ "messages": [AIMessage(content=analysis + f"\n\nValidation: {response.get('choices', [{}])[0].get('message', {}).get('content', '')}")]
 
 
 
 
 
361
  }
362
 
363
  def refine_results(self, state: AgentState) -> Dict:
364
  """
365
  Refines the analysis report if validation fails.
366
+ Increments the refinement counter to limit infinite loops.
367
  """
368
+ current_count = state["context"].get("refine_count", 0)
369
+ state["context"]["refine_count"] = current_count + 1
370
+ logger.info(f"Refinement iteration: {state['context']['refine_count']}")
371
+
372
  refinement_prompt = (
373
  f"Refine this analysis:\n{state['messages'][-1].content}\n\n"
374
  "Improve:\n1. Technical precision\n2. Empirical grounding\n3. Theoretical coherence"
 
376
  response = self.processor.process_query(refinement_prompt)
377
  logger.info("Refinement completed.")
378
  return {
379
+ "messages": [AIMessage(content=response.get('choices', [{}])[0].get('message', {}).get('content', ''))],
 
 
 
 
380
  "context": state["context"]
381
  }
382
 
383
  def _quality_check(self, state: AgentState) -> str:
384
  """
385
  Checks whether the analysis report is valid.
386
+ Forces a valid state if the refinement count exceeds a threshold.
387
  """
388
+ refine_count = state["context"].get("refine_count", 0)
389
+ if refine_count >= 3:
390
+ logger.warning("Refinement limit reached. Forcing valid outcome to prevent infinite recursion.")
391
+ return "valid"
392
  content = state["messages"][-1].content
393
  quality = "valid" if "VALID" in content else "invalid"
394
  logger.info(f"Quality check returned: {quality}")