"""
Core Cognitive Symbiosis & Structural Analysis Engine - OFFICIAL AI SOFTWARE (v1.0.0)
Framework: CS = AQ * (EQ_AI + IQ_AI) with Adaptive Feedback Loops
"""
import os
import logging
import json
import sqlite3
import urllib.request
from dataclasses import dataclass
from typing import Dict, List, Any, Optional
from openai import OpenAI
# 1. CẤU HÌNH HỆ THỐNG LOGGING CHUYÊN NGHIỆP
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] [%(levelname)s] [COGNITIVE_NODE]: %(message)s",
handlers=[
logging.FileHandler("cognitive_engine.log", encoding="utf-8"),
logging.StreamHandler()
]
)
logger = logging.getLogger("CognitiveEngine")
try:
client = OpenAI()
except Exception:
client = None
logger.warning("OPENAI_API_KEY chưa được cấu hình. Hệ thống sẽ chạy giả lập nhận thức.")
# ==========================================
# THÀNH PHẦN 1: QUẢN LÝ THÔNG SỐ & TỰ TIẾN HÓA (SELF-EVOLUTION)
# ==========================================
@dataclass
class CognitiveParameters:
adversarial_quotient: float # AQ: Hệ số phản biện / Hoài nghi khoa học
ai_emotional_intelligence: float # EQ_AI: Hệ số căn chỉnh ngữ cảnh con người
ai_intellectual_intelligence: float # IQ_AI: Hệ số phân tích logic / Khớp mẫu
version: int = 1
def calculate_symbiotic_capacity(self) -> float:
return float(self.adversarial_quotient * (self.ai_emotional_intelligence + self.ai_intellectual_intelligence))
def evolve(self, feedback_score: float):
"""
Cơ chế tự tiến hóa: Điều chỉnh các hệ số dựa trên đánh giá của người dùng (-1.0 đến 1.0)
Nếu người dùng chê AI quá lý thuyết -> Tăng EQ, giảm bớt sự khắt khe quá mức của AQ.
Nếu người dùng chê AI đưa tin rác -> Tăng AQ để siết chặt bộ lọc.
"""
learning_rate = 0.05
if feedback_score < 0: # Người dùng không hài lòng với kết quả
self.adversarial_quotient = max(0.5, min(1.0, self.adversarial_quotient + learning_rate))
self.ai_intellectual_intelligence = max(0.5, min(1.0, self.ai_intellectual_intelligence - learning_rate))
logger.info(f"🔄 Hệ thống tự điều chỉnh (Tiến hóa v{self.version + 1}): Tăng AQ lên {self.adversarial_quotient:.2f} để siết chặt bộ lọc.")
else: # Người dùng hài lòng
self.ai_emotional_intelligence = max(0.5, min(1.0, self.ai_emotional_intelligence + (learning_rate * 0.5)))
logger.info(f"✨ Hệ thống tối ưu hóa trạng thái ổn định. EQ cập nhật: {self.ai_emotional_intelligence:.2f}")
self.version += 1
# ==========================================
# THÀNH PHẦN 2: BỘ THU THẬP DỮ LIỆU TỰ ĐỘNG (NEWS API / SCRAPER)
# ==========================================
class AutomatedDataIngestion:
"""Tự động thu thập dòng sự kiện địa chính trị/kinh tế từ nguồn API hoặc Scraper dự phòng"""
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.environ.get("NEWS_API_KEY")
def fetch_geopolitical_stream(self, query: str = "geopolitics OR economy", max_results: int = 5) -> List[Dict[str, str]]:
logger.info(f"🌐 Đang quét nguồn dữ liệu trực tuyến với từ khóa: '{query}'...")
# Phương án 1: Sử dụng NewsAPI chính thức nếu có Key
if self.api_key:
url = f"https://newsapi.org{urllib.parse.quote(query)}&pageSize={max_results}&apiKey={self.api_key}"
try:
with urllib.request.urlopen(url) as response:
data = json.loads(response.read().decode())
stream = []
for idx, art in enumerate(data.get("articles", [])):
stream.append({
"id": f"NEWS_API_{idx:02d}",
"content": f"{art.get('title')}. {art.get('description')}"
})
return stream
except Exception as e:
logger.error(f"Lỗi kết nối NewsAPI: {e}. Chuyển sang cơ chế dữ liệu giả định thông minh.")
# Phương án 2: Tự động tạo Mock Stream chất lượng cao (Fallback Scraper) để phần mềm không bị gián đoạn
return [
{"id": "SCRAPE_01", "content": "Căng thẳng leo thang tại eo biển Malacca khiến phí bảo hiểm vận tải biển tăng vọt 45% trong tuần này."},
{"id": "SCRAPE_02", "content": "Tin nóng!!! Các nhà khoa học phát hiện bí mật động trời về năng lượng vĩnh cửu, bấm vào link để xem ngay kẻo xóa!"},
{"id": "SCRAPE_03", "content": "Ngân hàng Trung ương châu Âu (ECB) cân nhắc hạ lãi suất thêm 25 điểm cơ bản trong cuộc họp tháng tới nhằm kích cầu kinh tế."}
]
# ==========================================
# THÀNH PHẦN 3: BỘ LỌC PHẢN BIỆN & ĐỘNG CƠ PHÂN TÍCH (AI COGNITIVE ENGINE)
# ==========================================
class CognitiveAIPipeline:
def __init__(self, parameters: CognitiveParameters):
self.params = parameters
self.db_name = "cognitive_memory.db"
self._init_database()
def _init_database(self):
"""Khởi tạo tầng lưu trữ dữ liệu (Memory Layer) bảo vệ dữ liệu vĩnh viễn"""
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS processed_nodes (
id TEXT PRIMARY KEY,
content TEXT,
verification_score REAL,
status TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS system_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cs_index REAL,
config_json TEXT,
analysis_report TEXT
)
""")
conn.commit()
def _save_node(self, node_id: str, content: str, score: float, status: str):
with sqlite3.connect(self.db_name) as conn:
conn.execute(
"INSERT OR REPLACE INTO processed_nodes VALUES (?, ?, ?, ?)",
(node_id, content, score, status)
)
def evaluate_and_analyze(self, raw_stream: List[Dict[str, str]]) -> Dict[str, Any]:
cs_index = self.params.calculate_symbiotic_capacity()
logger.info(f"🧠 Khởi chạy chuỗi nhận thức AI. Chỉ số Cộng sinh (CS): {cs_index:.3f}")
if not client:
# Fallback mô phỏng nếu không có OpenAI API Key
return {
"status": "SIMULATION_MODE",
"message": "Vui lòng cấu hình OPENAI_API_KEY để chạy mô hình phân tích sâu."
}
# BƯỚC 1: LỌC ADVERSARIAL FILTER (Dùng AQ)
cleaned_nodes = []
for item in raw_stream:
prompt = f"Chấm điểm từ 0.0 đến 1.0 về độ tin cậy, tính xác thực khoa học (Loại bỏ tin rác/giật gân). Nội dung: {item['content']}. Chỉ trả về duy nhất 1 con số."
try:
res = client.chat.completions.create(
model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], temperature=0.2, max_tokens=5
)
score = float(res.choices.message.content.strip())
except:
score = 0.5
status = "ACCEPTED" if score >= (1.1 - self.params.adversarial_quotient) else "DISCARDED"
self._save_node(item['id'], item['content'], score, status)
if status == "ACCEPTED":
cleaned_nodes.append(item)
logger.info(f"✅ Đã DUYỆT {item['id']} (Score: {score})")
else:
logger.warning(f"❌ Đã LỌC BỎ RÁC: {item['id']} (Score: {score})")
if not cleaned_nodes:
return {"status": "CRITICAL", "message": "Bộ lọc AQ đã chặn toàn bộ luồng dữ liệu rác."}
# BƯỚC 2: PHÂN TÍCH CẤU TRÚC (Dùng IQ + EQ)
aggregated = "\n".join([f"- {n['content']}" for n in cleaned_nodes])
system_instruction = f"Bạn là lõi nhận thức phân tích hệ thống cấu trúc. Trọng số tư duy logic IQ: {self.params.ai_intellectual_intelligence}, Trọng số thấu hiểu bối cảnh EQ: {self.params.ai_emotional_intelligence}. Hãy phân tích nguyên nhân gốc rễ và xuất kịch bản giả định dạng JSON."
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "system", "content": system_instruction}, {"role": "user", "content": aggregated}],
response_format={"type": "json_object"}
)
report = json.loads(response.choices.message.content)
# Lưu vết lịch sử hệ thống
with sqlite3.connect(self.db_name) as conn:
conn.execute(
"INSERT INTO system_logs (cs_index, config_json, analysis_report) VALUES (?, ?, ?)",
(cs_index, json.dumps(self.params.__dict__), json.dumps(report))
)
return report
# ==========================================
# THÀNH PHẦN 4: GIAO DIỆN ĐIỀU HÀNH & TƯƠNG TÁC
# ==========================================
def main():
print("="*50)
print(" CORE COGNITIVE SYMBIOSIS ENGINE - INITIALIZING...")
print("="*50)
# 1. Khởi tạo cấu hình nhận thức ban đầu
config = CognitiveParameters(
adversarial_quotient=0.85,
ai_emotional_intelligence=0.80,
ai_intellectual_intelligence=0.90
)
# 2. Khởi tạo các module lõi phần mềm
ingestion = AutomatedDataIngestion()
pipeline = CognitiveAIPipeline(parameters=config)
# VÒNG LẶP ĐIỀU HÀNH TỰ ĐỘNG HÓA LIÊN TỤC (Tương tác & Tự tiến hóa)
while True:
# Bước A: Tự động nạp dữ liệu từ không gian mạng
raw_data = ingestion.fetch_geopolitical_stream()
# Bước B: Xử lý qua bộ lọc nhận thức AI
if os.environ.get("OPENAI_API_KEY"):
report = pipeline.evaluate_and_analyze(raw_data)
Nhận xét