Spaces:
Sleeping
Sleeping
Create processor.py
Browse files- processor.py +129 -0
processor.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# processor.py
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import hashlib
|
| 5 |
+
import time
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 8 |
+
from typing import Dict, List
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from langchain_core.messages import AIMessage
|
| 12 |
+
|
| 13 |
+
from config import ResearchConfig
|
| 14 |
+
from knowledge_graph import QuantumKnowledgeGraph
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
class CognitiveProcessor:
|
| 19 |
+
"""
|
| 20 |
+
Executes API requests to the backend using triple redundancy and consolidates results via a consensus mechanism.
|
| 21 |
+
"""
|
| 22 |
+
def __init__(self) -> None:
|
| 23 |
+
self.executor = ThreadPoolExecutor(max_workers=ResearchConfig.MAX_CONCURRENT_REQUESTS)
|
| 24 |
+
self.session_id = hashlib.sha256(datetime.now().isoformat().encode()).hexdigest()[:12]
|
| 25 |
+
|
| 26 |
+
def process_query(self, prompt: str) -> Dict:
|
| 27 |
+
futures = [self.executor.submit(self._execute_api_request, prompt) for _ in range(3)]
|
| 28 |
+
results = []
|
| 29 |
+
for future in as_completed(futures):
|
| 30 |
+
try:
|
| 31 |
+
results.append(future.result())
|
| 32 |
+
except Exception as e:
|
| 33 |
+
logger.exception("Error during API request execution.")
|
| 34 |
+
return self._consensus_check(results)
|
| 35 |
+
|
| 36 |
+
def _execute_api_request(self, prompt: str) -> Dict:
|
| 37 |
+
headers = {
|
| 38 |
+
"Authorization": f"Bearer {ResearchConfig.DEEPSEEK_API_KEY}",
|
| 39 |
+
"Content-Type": "application/json",
|
| 40 |
+
"X-Research-Session": self.session_id
|
| 41 |
+
}
|
| 42 |
+
payload = {
|
| 43 |
+
"model": "deepseek-chat",
|
| 44 |
+
"messages": [{
|
| 45 |
+
"role": "user",
|
| 46 |
+
"content": f"Respond as a Senior AI Researcher and Technical Writer:\n{prompt}"
|
| 47 |
+
}],
|
| 48 |
+
"temperature": 0.7,
|
| 49 |
+
"max_tokens": 1500,
|
| 50 |
+
"top_p": 0.9
|
| 51 |
+
}
|
| 52 |
+
try:
|
| 53 |
+
response = requests.post(
|
| 54 |
+
"https://api.deepseek.com/v1/chat/completions",
|
| 55 |
+
headers=headers,
|
| 56 |
+
json=payload,
|
| 57 |
+
timeout=45
|
| 58 |
+
)
|
| 59 |
+
response.raise_for_status()
|
| 60 |
+
logger.info("Backend API request successful.")
|
| 61 |
+
return response.json()
|
| 62 |
+
except requests.exceptions.RequestException as e:
|
| 63 |
+
logger.exception("Backend API request failed.")
|
| 64 |
+
return {"error": str(e)}
|
| 65 |
+
|
| 66 |
+
def _consensus_check(self, results: List[Dict]) -> Dict:
|
| 67 |
+
valid_results = [r for r in results if "error" not in r]
|
| 68 |
+
if not valid_results:
|
| 69 |
+
logger.error("All API requests failed.")
|
| 70 |
+
return {"error": "All API requests failed"}
|
| 71 |
+
# Choose the result with the longest response content as a simple consensus metric
|
| 72 |
+
return max(valid_results, key=lambda x: len(x.get('choices', [{}])[0].get('message', {}).get('content', '')))
|
| 73 |
+
|
| 74 |
+
class EnhancedCognitiveProcessor(CognitiveProcessor):
|
| 75 |
+
"""
|
| 76 |
+
Extends CognitiveProcessor with ensemble processing and knowledge graph integration.
|
| 77 |
+
"""
|
| 78 |
+
def __init__(self) -> None:
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.knowledge_graph = QuantumKnowledgeGraph()
|
| 81 |
+
self.ensemble_models = ["deepseek-chat", "deepseek-coder"]
|
| 82 |
+
|
| 83 |
+
def process_query(self, prompt: str) -> Dict:
|
| 84 |
+
futures = [self.executor.submit(self._execute_api_request, prompt, model) for model in self.ensemble_models]
|
| 85 |
+
results = []
|
| 86 |
+
for future in as_completed(futures):
|
| 87 |
+
try:
|
| 88 |
+
results.append(future.result())
|
| 89 |
+
except Exception as e:
|
| 90 |
+
logger.error(f"Model processing error: {str(e)}")
|
| 91 |
+
best_response = self._consensus_check(results)
|
| 92 |
+
self._update_knowledge_graph(best_response)
|
| 93 |
+
return best_response
|
| 94 |
+
|
| 95 |
+
def _execute_api_request(self, prompt: str, model: str) -> Dict:
|
| 96 |
+
headers = {
|
| 97 |
+
"Authorization": f"Bearer {ResearchConfig.DEEPSEEK_API_KEY}",
|
| 98 |
+
"Content-Type": "application/json",
|
| 99 |
+
"X-Research-Session": self.session_id
|
| 100 |
+
}
|
| 101 |
+
payload = {
|
| 102 |
+
"model": model,
|
| 103 |
+
"messages": [{
|
| 104 |
+
"role": "user",
|
| 105 |
+
"content": f"Respond as a Senior AI Researcher and Technical Writer:\n{prompt}"
|
| 106 |
+
}],
|
| 107 |
+
"temperature": ResearchConfig.ENSEMBLE_MODELS[model]["temp"],
|
| 108 |
+
"max_tokens": ResearchConfig.ENSEMBLE_MODELS[model]["max_tokens"],
|
| 109 |
+
"top_p": 0.9
|
| 110 |
+
}
|
| 111 |
+
try:
|
| 112 |
+
response = requests.post(
|
| 113 |
+
"https://api.deepseek.com/v1/chat/completions",
|
| 114 |
+
headers=headers,
|
| 115 |
+
json=payload,
|
| 116 |
+
timeout=45
|
| 117 |
+
)
|
| 118 |
+
response.raise_for_status()
|
| 119 |
+
logger.info(f"API request successful for model {model}.")
|
| 120 |
+
return response.json()
|
| 121 |
+
except requests.exceptions.RequestException as e:
|
| 122 |
+
logger.exception(f"API request failed for model {model}.")
|
| 123 |
+
return {"error": str(e)}
|
| 124 |
+
|
| 125 |
+
def _update_knowledge_graph(self, response: Dict) -> None:
|
| 126 |
+
content = response.get('choices', [{}])[0].get('message', {}).get('content', '')
|
| 127 |
+
node_id = self.knowledge_graph.create_node({"content": content}, "analysis")
|
| 128 |
+
if self.knowledge_graph.node_counter > 1:
|
| 129 |
+
self.knowledge_graph.create_relation(node_id - 1, node_id, "evolution", strength=0.8)
|