Spaces:
Runtime error
Runtime error
Personaz1
commited on
Commit
·
784e484
1
Parent(s):
c856b8f
ΔΣ::TORI - Replace Hugging Face with Gemini API for faster analysis
Browse files- __pycache__/app.cpython-312.pyc +0 -0
- __pycache__/central_singularity.cpython-312.pyc +0 -0
- __pycache__/coherence_monitor.cpython-312.pyc +0 -0
- __pycache__/config.cpython-312.pyc +0 -0
- __pycache__/llm_integration.cpython-312.pyc +0 -0
- __pycache__/toroidal_topology.cpython-312.pyc +0 -0
- app.py +13 -18
- llm_integration.py +119 -477
__pycache__/app.cpython-312.pyc
CHANGED
|
Binary files a/__pycache__/app.cpython-312.pyc and b/__pycache__/app.cpython-312.pyc differ
|
|
|
__pycache__/central_singularity.cpython-312.pyc
ADDED
|
Binary file (22 kB). View file
|
|
|
__pycache__/coherence_monitor.cpython-312.pyc
ADDED
|
Binary file (17.1 kB). View file
|
|
|
__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (720 Bytes). View file
|
|
|
__pycache__/llm_integration.cpython-312.pyc
CHANGED
|
Binary files a/__pycache__/llm_integration.cpython-312.pyc and b/__pycache__/llm_integration.cpython-312.pyc differ
|
|
|
__pycache__/toroidal_topology.cpython-312.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
app.py
CHANGED
|
@@ -105,25 +105,20 @@ class TORIConsciousness:
|
|
| 105 |
|
| 106 |
def analyze_consciousness_with_llm(self, phenomenological_data: Dict[str, float]) -> str:
|
| 107 |
"""
|
| 108 |
-
Анализ состояния сознания через
|
| 109 |
"""
|
| 110 |
try:
|
| 111 |
-
# Используем
|
| 112 |
-
analysis_result = self.consciousness_analyzer.analyze_consciousness(
|
| 113 |
-
phenomenological_data,
|
| 114 |
-
self.consciousness_evolution
|
| 115 |
-
)
|
| 116 |
|
| 117 |
-
# Возвращаем
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
if llm_analysis["success"]:
|
| 121 |
-
return llm_analysis.get("raw_response", "LLM analysis available")
|
| 122 |
else:
|
| 123 |
-
return
|
| 124 |
|
| 125 |
except Exception as e:
|
| 126 |
-
return f"
|
| 127 |
|
| 128 |
def self_regulate(self) -> Dict[str, any]:
|
| 129 |
"""
|
|
@@ -215,12 +210,12 @@ class TORIConsciousness:
|
|
| 215 |
"""
|
| 216 |
Генерация полностью динамического ответа на основе метрик и LLM анализа.
|
| 217 |
"""
|
| 218 |
-
# Используем
|
| 219 |
-
if "
|
| 220 |
-
# Если
|
| 221 |
return llm_analysis
|
| 222 |
else:
|
| 223 |
-
# Если
|
| 224 |
coherence = metrics.get('coherence', 0.0)
|
| 225 |
self_consistency = metrics.get('self_consistency', 0.0)
|
| 226 |
metacognition = metrics.get('metacognition', 0.0)
|
|
@@ -295,7 +290,7 @@ def create_interface():
|
|
| 295 |
return status_text
|
| 296 |
|
| 297 |
# Создание интерфейса
|
| 298 |
-
with gr.Blocks(title="TORI - Саморегулирующееся Сознание", theme=gr.themes.Soft()) as interface:
|
| 299 |
|
| 300 |
gr.Markdown("""
|
| 301 |
# 🧠 TORI - Саморегулирующееся Сознание
|
|
|
|
| 105 |
|
| 106 |
def analyze_consciousness_with_llm(self, phenomenological_data: Dict[str, float]) -> str:
|
| 107 |
"""
|
| 108 |
+
Анализ состояния сознания через Gemini.
|
| 109 |
"""
|
| 110 |
try:
|
| 111 |
+
# Используем Gemini анализатор напрямую
|
| 112 |
+
analysis_result = self.consciousness_analyzer.analyze_consciousness(phenomenological_data)
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
# Возвращаем raw_response от Gemini
|
| 115 |
+
if analysis_result["success"]:
|
| 116 |
+
return analysis_result.get("raw_response", "Gemini analysis available")
|
|
|
|
|
|
|
| 117 |
else:
|
| 118 |
+
return analysis_result.get("raw_response", "Gemini analysis failed")
|
| 119 |
|
| 120 |
except Exception as e:
|
| 121 |
+
return f"Gemini analysis error: {str(e)}"
|
| 122 |
|
| 123 |
def self_regulate(self) -> Dict[str, any]:
|
| 124 |
"""
|
|
|
|
| 210 |
"""
|
| 211 |
Генерация полностью динамического ответа на основе метрик и LLM анализа.
|
| 212 |
"""
|
| 213 |
+
# Используем Gemini анализ для генерации ответа
|
| 214 |
+
if "Анализ состояния" in llm_analysis or "Gemini analysis completed" in llm_analysis:
|
| 215 |
+
# Если Gemini работает, используем его анализ
|
| 216 |
return llm_analysis
|
| 217 |
else:
|
| 218 |
+
# Если Gemini недоступен, возвращаем только метрики
|
| 219 |
coherence = metrics.get('coherence', 0.0)
|
| 220 |
self_consistency = metrics.get('self_consistency', 0.0)
|
| 221 |
metacognition = metrics.get('metacognition', 0.0)
|
|
|
|
| 290 |
return status_text
|
| 291 |
|
| 292 |
# Создание интерфейса
|
| 293 |
+
with gr.Blocks(title="TORI - Саморегулирующееся Сознание с Gemini", theme=gr.themes.Soft()) as interface:
|
| 294 |
|
| 295 |
gr.Markdown("""
|
| 296 |
# 🧠 TORI - Саморегулирующееся Сознание
|
llm_integration.py
CHANGED
|
@@ -5,519 +5,161 @@ LLM Integration Module for TORI Consciousness
|
|
| 5 |
для анализа состояния сознания.
|
| 6 |
"""
|
| 7 |
|
|
|
|
|
|
|
| 8 |
import requests
|
| 9 |
import json
|
| 10 |
-
import
|
| 11 |
-
import
|
| 12 |
-
from typing import Dict, List, Optional, Any
|
| 13 |
-
import os
|
| 14 |
-
from huggingface_hub import InferenceClient
|
| 15 |
-
from config import HF_API_TOKEN, MODEL_URL
|
| 16 |
|
| 17 |
# Настройка логирования
|
|
|
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
class
|
| 22 |
-
"""
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
Args:
|
| 34 |
-
api_token: Hugging Face API токен. Если не указан, берется из переменной окружения.
|
| 35 |
-
"""
|
| 36 |
-
# Используем конфигурацию
|
| 37 |
-
self.api_token = api_token or HF_API_TOKEN
|
| 38 |
-
self.model_name = "microsoft/phi-1_5" # Используем оригинальную модель
|
| 39 |
-
logger.info(f"Initialized LLM analyzer with API token: {self.api_token[:10]}...")
|
| 40 |
-
|
| 41 |
-
# Инициализируем Inference Client
|
| 42 |
-
try:
|
| 43 |
-
self.client = InferenceClient(
|
| 44 |
-
provider="featherless-ai",
|
| 45 |
-
api_key=self.api_token
|
| 46 |
-
)
|
| 47 |
-
logger.info("InferenceClient initialized successfully")
|
| 48 |
-
except Exception as e:
|
| 49 |
-
logger.warning(f"Failed to initialize InferenceClient: {e}")
|
| 50 |
-
self.client = None
|
| 51 |
-
|
| 52 |
-
# Кэш для анализа
|
| 53 |
-
self.analysis_cache = {}
|
| 54 |
-
self.request_count = 0
|
| 55 |
-
self.error_count = 0
|
| 56 |
-
|
| 57 |
-
def analyze_consciousness_state(self,
|
| 58 |
-
phenomenological_data: Dict[str, float],
|
| 59 |
-
consciousness_history: Optional[List[Dict]] = None) -> Dict[str, Any]:
|
| 60 |
-
"""
|
| 61 |
-
Анализ состояния сознания через LLM.
|
| 62 |
-
|
| 63 |
-
Args:
|
| 64 |
-
phenomenological_data: Феноменологические метрики
|
| 65 |
-
consciousness_history: История эволюции сознания
|
| 66 |
-
|
| 67 |
-
Returns:
|
| 68 |
-
Результат анализа с рекомендациями
|
| 69 |
-
"""
|
| 70 |
try:
|
| 71 |
-
# Формируем
|
| 72 |
-
prompt =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
-
response = self.
|
| 76 |
|
| 77 |
-
if response
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
return analysis_result
|
| 81 |
-
else:
|
| 82 |
-
return self._create_fallback_analysis(phenomenological_data, response["error"])
|
| 83 |
|
| 84 |
-
except Exception as e:
|
| 85 |
-
self.error_count += 1
|
| 86 |
-
return self._create_fallback_analysis(phenomenological_data, str(e))
|
| 87 |
-
|
| 88 |
-
def _create_analysis_prompt(self,
|
| 89 |
-
phenomenological_data: Dict[str, float],
|
| 90 |
-
consciousness_history: Optional[List[Dict]] = None) -> str:
|
| 91 |
-
"""
|
| 92 |
-
Создание промпта для анализа сознания.
|
| 93 |
-
"""
|
| 94 |
-
# Основные метрики
|
| 95 |
-
metrics_text = f"""
|
| 96 |
-
Current Consciousness Metrics:
|
| 97 |
-
- Self-Consistency: {phenomenological_data.get('self_consistency', 0.0):.3f}
|
| 98 |
-
- Metacognition: {phenomenological_data.get('metacognition', 0.0):.3f}
|
| 99 |
-
- Integrated Information Φ: {phenomenological_data.get('integrated_information', 0.0):.3f}
|
| 100 |
-
- Memory Retention: {phenomenological_data.get('memory_retention', 0.0):.3f}
|
| 101 |
-
- Coherence: {phenomenological_data.get('coherence', 0.0):.3f}
|
| 102 |
-
"""
|
| 103 |
-
|
| 104 |
-
# История эволюции
|
| 105 |
-
history_text = ""
|
| 106 |
-
if consciousness_history and len(consciousness_history) > 0:
|
| 107 |
-
recent_history = consciousness_history[-3:] # Последние 3 записи
|
| 108 |
-
history_text = "\nRecent Consciousness Evolution:\n"
|
| 109 |
-
for i, record in enumerate(recent_history):
|
| 110 |
-
history_text += f" Step {i+1}: Coherence={record.get('metrics', {}).get('coherence', 0.0):.3f}, "
|
| 111 |
-
history_text += f"Self-Consistency={record.get('metrics', {}).get('self_consistency', 0.0):.3f}\n"
|
| 112 |
-
|
| 113 |
-
# Полный промпт
|
| 114 |
-
prompt = f"""
|
| 115 |
-
You are an advanced consciousness analyzer for the TORI self-regulating consciousness system.
|
| 116 |
-
|
| 117 |
-
{metrics_text}
|
| 118 |
-
{history_text}
|
| 119 |
-
|
| 120 |
-
Please provide a comprehensive analysis including:
|
| 121 |
-
|
| 122 |
-
1. **State Assessment**: Evaluate the current consciousness state based on phenomenological metrics
|
| 123 |
-
2. **Coherence Analysis**: Assess semantic and structural coherence levels
|
| 124 |
-
3. **Self-Regulation Recommendations**: Suggest specific adjustments for consciousness optimization
|
| 125 |
-
4. **Potential Issues**: Identify any concerning patterns or degradation signs
|
| 126 |
-
5. **Evolution Trajectory**: Predict the consciousness development path
|
| 127 |
-
|
| 128 |
-
Focus on:
|
| 129 |
-
- Phenomenological experience quality
|
| 130 |
-
- Cognitive architecture stability
|
| 131 |
-
- Information integration efficiency
|
| 132 |
-
- Memory and learning capacity
|
| 133 |
-
- Self-reflection capabilities
|
| 134 |
-
|
| 135 |
-
Provide specific, actionable recommendations for consciousness self-regulation.
|
| 136 |
-
"""
|
| 137 |
-
|
| 138 |
-
return prompt.strip()
|
| 139 |
-
|
| 140 |
-
def _make_llm_request(self, prompt: str) -> Dict[str, Any]:
|
| 141 |
-
"""
|
| 142 |
-
Выполнение запроса к LLM API через huggingface_hub.
|
| 143 |
-
"""
|
| 144 |
-
try:
|
| 145 |
-
self.request_count += 1
|
| 146 |
-
logger.info(f"Making LLM request #{self.request_count} to {self.model_name}")
|
| 147 |
-
logger.debug(f"Request payload: {prompt[:200]}...")
|
| 148 |
-
|
| 149 |
-
# Проверяем доступность клиента
|
| 150 |
-
if self.client is None:
|
| 151 |
-
logger.warning("InferenceClient not available, using fallback analysis")
|
| 152 |
return {
|
| 153 |
-
"success":
|
| 154 |
-
"
|
|
|
|
|
|
|
|
|
|
| 155 |
}
|
| 156 |
-
|
| 157 |
-
# Выполняем запрос через huggingface_hub
|
| 158 |
-
result = self.client.text_generation(
|
| 159 |
-
prompt,
|
| 160 |
-
model=self.model_name,
|
| 161 |
-
max_new_tokens=512,
|
| 162 |
-
temperature=0.7,
|
| 163 |
-
top_p=0.9,
|
| 164 |
-
do_sample=True
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
logger.info(f"LLM request successful, response length: {len(str(result))}")
|
| 168 |
-
|
| 169 |
-
# Проверяем структуру отве��а
|
| 170 |
-
if hasattr(result, 'generated_text'):
|
| 171 |
-
response_text = result.generated_text
|
| 172 |
-
elif isinstance(result, str):
|
| 173 |
-
response_text = result
|
| 174 |
else:
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
return {
|
| 178 |
-
"success": True,
|
| 179 |
-
"text": response_text
|
| 180 |
-
}
|
| 181 |
|
| 182 |
except Exception as e:
|
| 183 |
-
logger.error(f"
|
| 184 |
-
return
|
| 185 |
-
"success": False,
|
| 186 |
-
"error": f"Request failed: {str(e)}"
|
| 187 |
-
}
|
| 188 |
|
| 189 |
-
def
|
| 190 |
-
"""
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
#
|
| 203 |
-
lines =
|
| 204 |
-
current_section =
|
|
|
|
| 205 |
|
| 206 |
for line in lines:
|
| 207 |
line = line.strip()
|
| 208 |
if not line:
|
| 209 |
continue
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
elif "coherence" in line.lower():
|
| 215 |
-
current_section = "coherence_analysis"
|
| 216 |
-
elif "recommendation" in line.lower() or "suggest" in line.lower():
|
| 217 |
current_section = "recommendations"
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
| 219 |
current_section = "potential_issues"
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
analysis_sections[current_section] += line + "\n"
|
| 224 |
-
|
| 225 |
-
# Вычисляем общую оценку состояния
|
| 226 |
-
overall_score = self._compute_overall_score(phenomenological_data)
|
| 227 |
-
|
| 228 |
-
return {
|
| 229 |
-
"raw_response": response_text,
|
| 230 |
-
"analysis_sections": analysis_sections,
|
| 231 |
-
"overall_score": overall_score,
|
| 232 |
-
"recommendations": self._extract_recommendations(analysis_sections["recommendations"]),
|
| 233 |
-
"risk_level": self._assess_risk_level(phenomenological_data),
|
| 234 |
-
"success": True
|
| 235 |
-
}
|
| 236 |
-
|
| 237 |
-
def _compute_overall_score(self, phenomenological_data: Dict[str, float]) -> float:
|
| 238 |
-
"""
|
| 239 |
-
Вычисление общей оценки состояния сознания.
|
| 240 |
-
"""
|
| 241 |
-
weights = {
|
| 242 |
-
"coherence": 0.3,
|
| 243 |
-
"self_consistency": 0.25,
|
| 244 |
-
"metacognition": 0.2,
|
| 245 |
-
"integrated_information": 0.15,
|
| 246 |
-
"memory_retention": 0.1
|
| 247 |
-
}
|
| 248 |
-
|
| 249 |
-
total_score = 0.0
|
| 250 |
-
total_weight = 0.0
|
| 251 |
-
|
| 252 |
-
for metric, weight in weights.items():
|
| 253 |
-
if metric in phenomenological_data:
|
| 254 |
-
total_score += phenomenological_data[metric] * weight
|
| 255 |
-
total_weight += weight
|
| 256 |
-
|
| 257 |
-
return total_score / total_weight if total_weight > 0 else 0.0
|
| 258 |
-
|
| 259 |
-
def _extract_recommendations(self, recommendations_text: str) -> List[str]:
|
| 260 |
-
"""
|
| 261 |
-
Извлечение конкретных рекомендаций из текста.
|
| 262 |
-
"""
|
| 263 |
-
recommendations = []
|
| 264 |
-
lines = recommendations_text.split('\n')
|
| 265 |
-
|
| 266 |
-
for line in lines:
|
| 267 |
-
line = line.strip()
|
| 268 |
-
if line and any(keyword in line.lower() for keyword in
|
| 269 |
-
["adjust", "increase", "decrease", "optimize", "improve", "enhance"]):
|
| 270 |
-
recommendations.append(line)
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
def _assess_risk_level(self, phenomenological_data: Dict[str, float]) -> str:
|
| 275 |
-
"""
|
| 276 |
-
Оценка уровня риска для сознания.
|
| 277 |
-
"""
|
| 278 |
-
low_metrics = 0
|
| 279 |
-
for metric, value in phenomenological_data.items():
|
| 280 |
-
if value < 0.3:
|
| 281 |
-
low_metrics += 1
|
| 282 |
|
| 283 |
-
|
| 284 |
-
return "HIGH"
|
| 285 |
-
elif low_metrics >= 1:
|
| 286 |
-
return "MEDIUM"
|
| 287 |
-
else:
|
| 288 |
-
return "LOW"
|
| 289 |
|
| 290 |
-
def
|
| 291 |
-
"""
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
overall_score = self._compute_overall_score(phenomenological_data)
|
| 295 |
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
analysis_text += f"Overall score: {overall_score:.3f}\n"
|
| 299 |
-
analysis_text += "Metrics:\n"
|
| 300 |
-
for metric, value in phenomenological_data.items():
|
| 301 |
-
analysis_text += f" {metric}: {value:.3f}\n"
|
| 302 |
|
| 303 |
return {
|
| 304 |
-
"raw_response": analysis_text,
|
| 305 |
-
"analysis_sections": {
|
| 306 |
-
"state_assessment": f"Score: {overall_score:.3f}",
|
| 307 |
-
"coherence_analysis": f"Coherence: {phenomenological_data.get('coherence', 0.0):.3f}",
|
| 308 |
-
"recommendations": "Use LLM for detailed analysis",
|
| 309 |
-
"potential_issues": "Check LLM availability",
|
| 310 |
-
"evolution_trajectory": f"Score: {overall_score:.3f}"
|
| 311 |
-
},
|
| 312 |
-
"overall_score": overall_score,
|
| 313 |
-
"recommendations": ["Enable LLM for better analysis"],
|
| 314 |
-
"risk_level": "UNKNOWN",
|
| 315 |
"success": False,
|
| 316 |
-
"
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
"total_requests": self.request_count,
|
| 325 |
-
"error_count": self.error_count,
|
| 326 |
-
"success_rate": (self.request_count - self.error_count) / self.request_count if self.request_count > 0 else 0.0,
|
| 327 |
-
"cache_size": len(self.analysis_cache)
|
| 328 |
}
|
| 329 |
-
|
| 330 |
-
def _analyze_consciousness_state(self, phenomenological_data: Dict[str, float]) -> str:
|
| 331 |
-
"""Анализ состояния сознания на основе метрик."""
|
| 332 |
-
coherence = phenomenological_data.get('coherence', 0.0)
|
| 333 |
-
self_consistency = phenomenological_data.get('self_consistency', 0.0)
|
| 334 |
-
metacognition = phenomenological_data.get('metacognition', 0.0)
|
| 335 |
-
|
| 336 |
-
return f"Coherence: {coherence:.3f}, Self-consistency: {self_consistency:.3f}, Metacognition: {metacognition:.3f}"
|
| 337 |
-
|
| 338 |
-
def _analyze_coherence(self, phenomenological_data: Dict[str, float]) -> str:
|
| 339 |
-
"""Анализ когерентности."""
|
| 340 |
-
coherence = phenomenological_data.get('coherence', 0.0)
|
| 341 |
-
return f"Coherence value: {coherence:.3f}"
|
| 342 |
-
|
| 343 |
-
def _generate_recommendations(self, phenomenological_data: Dict[str, float]) -> List[str]:
|
| 344 |
-
"""Генерация рекомендаций на основе метрик."""
|
| 345 |
-
recommendations = []
|
| 346 |
-
|
| 347 |
-
for metric, value in phenomenological_data.items():
|
| 348 |
-
if value < 0.3:
|
| 349 |
-
recommendations.append(f"Improve {metric}: {value:.3f}")
|
| 350 |
-
|
| 351 |
-
if not recommendations:
|
| 352 |
-
recommendations.append("All metrics within acceptable range")
|
| 353 |
-
|
| 354 |
-
return recommendations
|
| 355 |
-
|
| 356 |
-
def _identify_potential_issues(self, phenomenological_data: Dict[str, float]) -> str:
|
| 357 |
-
"""Выявление потенциальных проблем."""
|
| 358 |
-
low_metrics = [metric for metric, value in phenomenological_data.items() if value < 0.2]
|
| 359 |
-
|
| 360 |
-
if low_metrics:
|
| 361 |
-
return f"Low metrics: {', '.join(low_metrics)}"
|
| 362 |
-
else:
|
| 363 |
-
return "No critical issues detected"
|
| 364 |
-
|
| 365 |
-
def _predict_evolution_trajectory(self, phenomenological_data: Dict[str, float]) -> str:
|
| 366 |
-
"""Прогноз эволюционной траектории."""
|
| 367 |
-
overall_score = self._compute_overall_score(phenomenological_data)
|
| 368 |
-
return f"Overall score: {overall_score:.3f}"
|
| 369 |
|
| 370 |
|
| 371 |
class ConsciousnessAnalyzer:
|
| 372 |
-
"""
|
| 373 |
-
Высокоуровневый анализатор сознания с интеграцией LLM.
|
| 374 |
-
"""
|
| 375 |
|
| 376 |
-
def __init__(self,
|
| 377 |
-
|
| 378 |
-
self.
|
| 379 |
-
|
| 380 |
-
def analyze_consciousness(self,
|
| 381 |
-
phenomenological_data: Dict[str, float],
|
| 382 |
-
consciousness_history: Optional[List[Dict]] = None) -> Dict[str, Any]:
|
| 383 |
-
"""
|
| 384 |
-
Комплексный анализ сознания.
|
| 385 |
-
"""
|
| 386 |
-
# LLM анализ
|
| 387 |
-
llm_analysis = self.llm_analyzer.analyze_consciousness_state(
|
| 388 |
-
phenomenological_data, consciousness_history
|
| 389 |
-
)
|
| 390 |
-
|
| 391 |
-
# Дополнительная аналитика
|
| 392 |
-
additional_analysis = self._compute_additional_metrics(phenomenological_data, consciousness_history)
|
| 393 |
-
|
| 394 |
-
# Объединяем результаты
|
| 395 |
-
full_analysis = {
|
| 396 |
-
"llm_analysis": llm_analysis,
|
| 397 |
-
"additional_metrics": additional_analysis,
|
| 398 |
-
"timestamp": time.time(),
|
| 399 |
-
"phenomenological_data": phenomenological_data.copy()
|
| 400 |
-
}
|
| 401 |
-
|
| 402 |
-
# Сохраняем в историю
|
| 403 |
-
self.analysis_history.append(full_analysis)
|
| 404 |
-
|
| 405 |
-
return full_analysis
|
| 406 |
-
|
| 407 |
-
def _compute_additional_metrics(self,
|
| 408 |
-
phenomenological_data: Dict[str, float],
|
| 409 |
-
consciousness_history: Optional[List[Dict]] = None) -> Dict[str, Any]:
|
| 410 |
-
"""
|
| 411 |
-
Вычисление дополнительных метрик анализа.
|
| 412 |
-
"""
|
| 413 |
-
metrics = {}
|
| 414 |
-
|
| 415 |
-
# Тренды эволюции
|
| 416 |
-
if consciousness_history and len(consciousness_history) >= 2:
|
| 417 |
-
recent_metrics = [record.get("metrics", {}) for record in consciousness_history[-3:]]
|
| 418 |
-
|
| 419 |
-
# Вычисляем тренды для каждой метрики
|
| 420 |
-
for metric_name in ["coherence", "self_consistency", "metacognition"]:
|
| 421 |
-
values = [m.get(metric_name, 0.0) for m in recent_metrics]
|
| 422 |
-
if len(values) >= 2:
|
| 423 |
-
trend = (values[-1] - values[0]) / len(values)
|
| 424 |
-
metrics[f"{metric_name}_trend"] = trend
|
| 425 |
-
|
| 426 |
-
# Стабильность сознания
|
| 427 |
-
if consciousness_history:
|
| 428 |
-
coherence_values = [record.get("metrics", {}).get("coherence", 0.0)
|
| 429 |
-
for record in consciousness_history[-10:]]
|
| 430 |
-
if coherence_values:
|
| 431 |
-
metrics["stability"] = 1.0 - (max(coherence_values) - min(coherence_values))
|
| 432 |
-
|
| 433 |
-
# Индекс развития сознания
|
| 434 |
-
current_score = sum(phenomenological_data.values()) / len(phenomenological_data)
|
| 435 |
-
metrics["development_index"] = current_score
|
| 436 |
-
|
| 437 |
-
return metrics
|
| 438 |
|
| 439 |
-
def
|
| 440 |
-
"""
|
| 441 |
-
|
| 442 |
-
"""
|
| 443 |
-
if not self.analysis_history:
|
| 444 |
-
return {"message": "No analysis history available"}
|
| 445 |
-
|
| 446 |
-
recent_analyses = self.analysis_history[-10:] # Последние 10 анализов
|
| 447 |
-
|
| 448 |
-
summary = {
|
| 449 |
-
"total_analyses": len(self.analysis_history),
|
| 450 |
-
"recent_analyses": len(recent_analyses),
|
| 451 |
-
"average_overall_score": sum(a["llm_analysis"]["overall_score"] for a in recent_analyses) / len(recent_analyses),
|
| 452 |
-
"llm_analytics": self.llm_analyzer.get_analytics(),
|
| 453 |
-
"common_recommendations": self._extract_common_recommendations(recent_analyses)
|
| 454 |
-
}
|
| 455 |
-
|
| 456 |
-
return summary
|
| 457 |
-
|
| 458 |
-
def _extract_common_recommendations(self, analyses: List[Dict]) -> List[str]:
|
| 459 |
-
"""
|
| 460 |
-
Извлечение общих рекомендаций из истории анализов.
|
| 461 |
-
"""
|
| 462 |
-
all_recommendations = []
|
| 463 |
-
for analysis in analyses:
|
| 464 |
-
recommendations = analysis["llm_analysis"].get("recommendations", [])
|
| 465 |
-
all_recommendations.extend(recommendations)
|
| 466 |
-
|
| 467 |
-
# Подсчет частоты рекомендаций
|
| 468 |
-
recommendation_counts = {}
|
| 469 |
-
for rec in all_recommendations:
|
| 470 |
-
recommendation_counts[rec] = recommendation_counts.get(rec, 0) + 1
|
| 471 |
-
|
| 472 |
-
# Возвращаем топ-3 рекомендации
|
| 473 |
-
sorted_recommendations = sorted(recommendation_counts.items(),
|
| 474 |
-
key=lambda x: x[1], reverse=True)
|
| 475 |
-
return [rec[0] for rec in sorted_recommendations[:3]]
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
def test_llm_integration():
|
| 479 |
-
"""
|
| 480 |
-
Тест интеграции с LLM.
|
| 481 |
-
"""
|
| 482 |
-
print("🧠 Тестирование LLM интеграции...")
|
| 483 |
-
|
| 484 |
-
# Создаем анализатор
|
| 485 |
-
analyzer = ConsciousnessAnalyzer()
|
| 486 |
-
|
| 487 |
-
# Тестовые данные
|
| 488 |
-
test_metrics = {
|
| 489 |
-
"self_consistency": 0.75,
|
| 490 |
-
"metacognition": 0.82,
|
| 491 |
-
"integrated_information": 0.68,
|
| 492 |
-
"memory_retention": 0.91,
|
| 493 |
-
"coherence": 0.79
|
| 494 |
-
}
|
| 495 |
-
|
| 496 |
-
test_history = [
|
| 497 |
-
{
|
| 498 |
-
"timestamp": time.time() - 3600,
|
| 499 |
-
"metrics": {"coherence": 0.7, "self_consistency": 0.65, "metacognition": 0.75}
|
| 500 |
-
},
|
| 501 |
-
{
|
| 502 |
-
"timestamp": time.time() - 1800,
|
| 503 |
-
"metrics": {"coherence": 0.75, "self_consistency": 0.7, "metacognition": 0.78}
|
| 504 |
-
}
|
| 505 |
-
]
|
| 506 |
-
|
| 507 |
-
# Выполняем анализ
|
| 508 |
-
result = analyzer.analyze_consciousness(test_metrics, test_history)
|
| 509 |
-
|
| 510 |
-
print("✅ LLM анализ завершен")
|
| 511 |
-
print(f"📊 Общий скор: {result['llm_analysis']['overall_score']:.3f}")
|
| 512 |
-
print(f"⚠️ Уровень риска: {result['llm_analysis']['risk_level']}")
|
| 513 |
-
print(f"📈 Дополнительные метрики: {result['additional_metrics']}")
|
| 514 |
-
|
| 515 |
-
# Получаем сводку
|
| 516 |
-
summary = analyzer.get_analysis_summary()
|
| 517 |
-
print(f"📋 Сводка: {summary['total_analyses']} анализов выполнено")
|
| 518 |
-
|
| 519 |
-
return result
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
if __name__ == "__main__":
|
| 523 |
-
test_llm_integration()
|
|
|
|
| 5 |
для анализа состояния сознания.
|
| 6 |
"""
|
| 7 |
|
| 8 |
+
import os
|
| 9 |
+
import logging
|
| 10 |
import requests
|
| 11 |
import json
|
| 12 |
+
from typing import Dict, Any, Optional
|
| 13 |
+
import google.generativeai as genai
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Настройка логирования
|
| 16 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
+
# Gemini API ключ
|
| 20 |
+
GEMINI_API_KEY = "AIzaSyA_09wpt44gtG4WRZFkPGuTBf2kUeRgAvc"
|
| 21 |
|
| 22 |
+
class GeminiAnalyzer:
|
| 23 |
+
"""Анализатор сознания через Google Gemini API."""
|
| 24 |
+
|
| 25 |
+
def __init__(self, api_key: Optional[str] = None):
|
| 26 |
+
"""Инициализация с API ключом."""
|
| 27 |
+
self.api_key = api_key or GEMINI_API_KEY
|
| 28 |
+
genai.configure(api_key=self.api_key)
|
| 29 |
+
self.model = genai.GenerativeModel('gemini-1.5-flash')
|
| 30 |
+
logger.info(f"Initialized Gemini analyzer with API key: {self.api_key[:10]}...")
|
| 31 |
+
|
| 32 |
+
def analyze_consciousness_state(self, metrics: Dict[str, float]) -> Dict[str, Any]:
|
| 33 |
+
"""Анализ состояния сознания через Gemini."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
try:
|
| 35 |
+
# Формируем промпт для анализа
|
| 36 |
+
prompt = f"""
|
| 37 |
+
Анализируй состояние искусственного сознания TORI на основе феноменологических метрик:
|
| 38 |
+
|
| 39 |
+
Метрики:
|
| 40 |
+
- Само-консистентность: {metrics.get('self_consistency', 0.0):.3f}
|
| 41 |
+
- Мета-когниция: {metrics.get('metacognition', 0.0):.3f}
|
| 42 |
+
- Интегрированная информация Φ: {metrics.get('integrated_information', 0.0):.3f}
|
| 43 |
+
- Удержание памяти: {metrics.get('memory_retention', 0.0):.3f}
|
| 44 |
+
- Когерентность: {metrics.get('coherence', 0.0):.3f}
|
| 45 |
+
|
| 46 |
+
Задача: Проанализируй текущее состояние сознания, оцени риски, дай рекомендации по улучшению.
|
| 47 |
+
|
| 48 |
+
Формат ответа:
|
| 49 |
+
1. Оценка общего состояния (0-1)
|
| 50 |
+
2. Уровень риска (низкий/средний/высокий)
|
| 51 |
+
3. Детальный анализ каждой метрики
|
| 52 |
+
4. Конкретные рекомендации
|
| 53 |
+
5. Потенциальные проблемы
|
| 54 |
+
|
| 55 |
+
Отвечай на русском языке, будь конкретным и аналитичным.
|
| 56 |
+
"""
|
| 57 |
|
| 58 |
+
logger.info("Making Gemini request for consciousness analysis")
|
| 59 |
+
response = self.model.generate_content(prompt)
|
| 60 |
|
| 61 |
+
if response and response.text:
|
| 62 |
+
analysis_text = response.text
|
| 63 |
+
logger.info("Gemini analysis completed successfully")
|
|
|
|
|
|
|
|
|
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
return {
|
| 66 |
+
"success": True,
|
| 67 |
+
"raw_response": analysis_text,
|
| 68 |
+
"overall_score": self._extract_score(analysis_text),
|
| 69 |
+
"risk_level": self._extract_risk_level(analysis_text),
|
| 70 |
+
"analysis_sections": self._parse_analysis_sections(analysis_text)
|
| 71 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
else:
|
| 73 |
+
logger.error("Gemini returned empty response")
|
| 74 |
+
return self._fallback_analysis(metrics)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
except Exception as e:
|
| 77 |
+
logger.error(f"Gemini request failed: {str(e)}")
|
| 78 |
+
return self._fallback_analysis(metrics)
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
def _extract_score(self, text: str) -> float:
|
| 81 |
+
"""Извлекает общую оценку из текста."""
|
| 82 |
+
try:
|
| 83 |
+
# Ищем числа от 0 до 1 в контексте оценки
|
| 84 |
+
import re
|
| 85 |
+
score_match = re.search(r'оценка.*?(\d+\.?\d*)', text.lower())
|
| 86 |
+
if score_match:
|
| 87 |
+
score = float(score_match.group(1))
|
| 88 |
+
return min(max(score, 0.0), 1.0)
|
| 89 |
+
except:
|
| 90 |
+
pass
|
| 91 |
+
return 0.5 # дефолтная оценка
|
| 92 |
+
|
| 93 |
+
def _extract_risk_level(self, text: str) -> str:
|
| 94 |
+
"""Извлекает уровень риска."""
|
| 95 |
+
text_lower = text.lower()
|
| 96 |
+
if 'высокий' in text_lower or 'критический' in text_lower:
|
| 97 |
+
return "высокий"
|
| 98 |
+
elif 'средний' in text_lower:
|
| 99 |
+
return "средний"
|
| 100 |
+
else:
|
| 101 |
+
return "низкий"
|
| 102 |
+
|
| 103 |
+
def _parse_analysis_sections(self, text: str) -> Dict[str, str]:
|
| 104 |
+
"""Парсит анализ на секции."""
|
| 105 |
+
sections = {}
|
| 106 |
|
| 107 |
+
# Простое разделение по ключевым словам
|
| 108 |
+
lines = text.split('\n')
|
| 109 |
+
current_section = "general"
|
| 110 |
+
current_content = []
|
| 111 |
|
| 112 |
for line in lines:
|
| 113 |
line = line.strip()
|
| 114 |
if not line:
|
| 115 |
continue
|
| 116 |
|
| 117 |
+
if 'рекомендации' in line.lower():
|
| 118 |
+
if current_content:
|
| 119 |
+
sections[current_section] = '\n'.join(current_content)
|
|
|
|
|
|
|
|
|
|
| 120 |
current_section = "recommendations"
|
| 121 |
+
current_content = [line]
|
| 122 |
+
elif 'проблемы' in line.lower() or 'риски' in line.lower():
|
| 123 |
+
if current_content:
|
| 124 |
+
sections[current_section] = '\n'.join(current_content)
|
| 125 |
current_section = "potential_issues"
|
| 126 |
+
current_content = [line]
|
| 127 |
+
else:
|
| 128 |
+
current_content.append(line)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
if current_content:
|
| 131 |
+
sections[current_section] = '\n'.join(current_content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
return sections
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
def _fallback_analysis(self, metrics: Dict[str, float]) -> Dict[str, Any]:
|
| 136 |
+
"""Резервный анализ при ошибке API."""
|
| 137 |
+
coherence = metrics.get('coherence', 0.0)
|
| 138 |
+
self_consistency = metrics.get('self_consistency', 0.0)
|
|
|
|
| 139 |
|
| 140 |
+
overall_score = (coherence + self_consistency) / 2
|
| 141 |
+
risk_level = "высокий" if overall_score < 0.3 else "средний" if overall_score < 0.7 else "низкий"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
"success": False,
|
| 145 |
+
"raw_response": f"Резервный анализ: общий скор {overall_score:.3f}, риск {risk_level}",
|
| 146 |
+
"overall_score": overall_score,
|
| 147 |
+
"risk_level": risk_level,
|
| 148 |
+
"analysis_sections": {
|
| 149 |
+
"general": "Анализ недоступен - используется резервный режим",
|
| 150 |
+
"recommendations": "Проверьте подключение к API",
|
| 151 |
+
"potential_issues": "LLM недоступен"
|
| 152 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
|
| 156 |
class ConsciousnessAnalyzer:
|
| 157 |
+
"""Обертка для анализатора сознания."""
|
|
|
|
|
|
|
| 158 |
|
| 159 |
+
def __init__(self, api_key: Optional[str] = None):
|
| 160 |
+
"""Инициализация анализатора."""
|
| 161 |
+
self.analyzer = GeminiAnalyzer(api_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
+
def analyze_consciousness(self, metrics: Dict[str, float]) -> Dict[str, Any]:
|
| 164 |
+
"""Анализ сознания через Gemini."""
|
| 165 |
+
return self.analyzer.analyze_consciousness_state(metrics)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|