Athspi's picture
Update app.py
707c36e verified
raw
history blame
13.2 kB
import os
import time
import gradio as gr
import requests
import json
import numpy as np
import google.generativeai as genai
from openai import OpenAI
from typing import List, Dict, Tuple
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer
# Animation CSS and HTML
LOADING_ANIMATION = """
<style>
.thinking-animation {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
flex-direction: column;
}
.dot-flashing {
position: relative;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: #4CAF50;
color: #4CAF50;
animation: dotFlashing 1s infinite linear alternate;
animation-delay: .5s;
}
.dot-flashing::before, .dot-flashing::after {
content: '';
display: inline-block;
position: absolute;
top: 0;
}
.dot-flashing::before {
left: -15px;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: #4CAF50;
color: #4CAF50;
animation: dotFlashing 1s infinite alternate;
animation-delay: 0s;
}
.dot-flashing::after {
left: 15px;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: #4CAF50;
color: #4CAF50;
animation: dotFlashing 1s infinite alternate;
animation-delay: 1s;
}
@keyframes dotFlashing {
0% { background-color: #4CAF50; }
50%, 100% { background-color: rgba(76, 175, 80, 0.2); }
}
.thinking-text {
text-align: center;
margin-top: 20px;
font-weight: bold;
color: #4CAF50;
animation: textFade 2s infinite;
}
@keyframes textFade {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
</style>
<div class="thinking-animation">
<div class="dot-flashing"></div>
<div class="thinking-text">AGI Thinking...</div>
</div>
"""
class AGICognitiveSystem:
def __init__(self):
self.api_keys = {
"GEMINI": os.environ.get("GEMINI_API_KEY"),
"MISTRAL": os.environ.get("MISTRAL_API_KEY"),
"OPENROUTER": os.environ.get("OPENROUTER_API_KEY"),
"AZURE": os.environ.get("AZURE_API_KEY")
}
self.validate_keys()
# Initialize models and cognitive components
self.init_models()
self.init_cognitive_modules()
self.init_knowledge_graph()
# Initialize sentence transformer for semantic analysis
self.sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
# Cognitive configuration
self.cognitive_config = {
"depth": 5, # Levels of recursive reasoning
"temperature_strategy": "adaptive",
"confidence_threshold": 0.85,
"max_retries": 3,
"metacognition_interval": 2
}
self.thought_history = []
self.cognitive_metrics = {
"processing_time": [],
"confidence_scores": [],
"error_rates": []
}
def validate_keys(self):
for key, value in self.api_keys.items():
if not value:
raise ValueError(f"Missing API key: {key}")
def init_models(self):
"""Initialize all AI models with specialized roles"""
# Google Gemini
genai.configure(api_key=self.api_keys["GEMINI"])
self.gemini = genai.GenerativeModel(
"gemini-2.0-pro-exp-02-05",
generation_config={"temperature": 0.5, "max_output_tokens": 8192}
)
# Azure GPT-4o
self.gpt4o = OpenAI(
base_url="https://models.inference.ai.azure.com",
api_key=self.api_keys["AZURE"]
)
# Model registry with specialized roles
self.model_registry = {
"intuition": "mistral-large-latest",
"analysis": "gpt-4o",
"critique": "meta-llama/llama-3.3-70b-instruct:free",
"creativity": "gemini-2.0-pro-exp-02-05",
"validation": "deepseek/deepseek-chat:free",
"metacognition": "gpt-4o",
"emotional_intelligence": "qwen/qwen-vl-plus:free"
}
def init_cognitive_modules(self):
"""Initialize specialized cognitive processors"""
self.modules = {
"working_memory": [],
"long_term_memory": [],
"emotional_context": {"valence": 0.5, "arousal": 0.5},
"error_correction": [],
"metacognition_stack": []
}
def init_knowledge_graph(self):
"""Initialize semantic knowledge network"""
self.knowledge_graph = {
"nodes": [],
"edges": [],
"embeddings": np.array([])
}
def cognitive_flow(self, query: str) -> Tuple[str, dict]:
"""Multi-layered cognitive processing pipeline"""
try:
# Stage 1: Perception & Contextualization
context = self.perceive_context(query)
# Stage 2: Core Reasoning Process
solutions = self.recursive_reasoning(query, context)
# Stage 3: Emotional Alignment
emotionally_aligned = self.apply_emotional_intelligence(solutions)
# Stage 4: Metacognitive Review
validated = self.metacognitive_review(emotionally_aligned)
# Stage 5: Knowledge Integration
self.update_knowledge_graph(query, validated)
return validated, {
"reasoning_steps": self.thought_history[-5:],
"confidence": self.calculate_confidence(validated),
"semantic_coherence": self.analyze_coherence(validated)
}
except Exception as e:
self.handle_error(e)
return "Cognitive processing failed", {}
def recursive_reasoning(self, query: str, context: dict, depth: int = 0) -> List[dict]:
"""Deep recursive reasoning with backtracking"""
if depth >= self.cognitive_config["depth"]:
return []
# Generate initial hypotheses
hypotheses = self.generate_hypotheses(query, context)
# Evaluate hypotheses
evaluated = []
for hypothesis in hypotheses:
analysis = self.analyze_hypothesis(hypothesis, context)
critique = self.critique_analysis(analysis)
if self.evaluate_critique(critique):
refined = self.refine_hypothesis(hypothesis, critique)
evaluated.append({
"hypothesis": refined,
"confidence": self.calculate_confidence(refined),
"depth": depth
})
# Recursive deepening
evaluated += self.recursive_reasoning(refined, context, depth+1)
return self.rank_solutions(evaluated)
def generate_hypotheses(self, query: str, context: dict) -> List[str]:
"""Generate potential solutions using multiple models"""
hypotheses = []
# Intuitive generation
hypotheses.append(self.call_model(
"intuition",
f"Generate intuitive hypothesis for: {query}",
context
))
# Analytical generation
hypotheses.append(self.call_model(
"analysis",
f"Generate analytical solution for: {query}",
context
))
# Creative generation
hypotheses.append(self.call_model(
"creativity",
f"Generate creative approach for: {query}",
context
))
return [h for h in hypotheses if h]
def call_model(self, module: str, prompt: str, context: dict) -> str:
"""Advanced model caller with adaptive temperature and retry"""
temperature = self.calculate_temperature(context)
retries = 0
while retries < self.cognitive_config["max_retries"]:
try:
if module in ["intuition", "metacognition"]:
return self._call_mistral(prompt, temperature)
elif module == "analysis":
return self._call_gpt4o(prompt, temperature)
elif module == "creativity":
return self.gemini.generate_content(prompt).text
elif module == "emotional_intelligence":
return self._call_qwen(prompt)
elif module == "validation":
return self._call_deepseek(prompt)
except Exception as e:
retries += 1
self.handle_error(e)
return ""
def _call_mistral(self, prompt: str, temperature: float) -> str:
"""Call Mistral API"""
headers = {
"Authorization": f"Bearer {self.api_keys['MISTRAL']}",
"Content-Type": "application/json"
}
payload = {
"model": self.model_registry["intuition"],
"messages": [{"role": "user", "content": prompt}],
"temperature": temperature,
"max_tokens": 2000
}
response = requests.post(
"https://api.mistral.ai/v1/chat/completions",
headers=headers,
json=payload
)
return response.json()['choices'][0]['message']['content']
def _call_gpt4o(self, prompt: str, temperature: float) -> str:
"""Call GPT-4o via Azure"""
try:
response = self.gpt4o.chat.completions.create(
model=self.model_registry["analysis"],
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
max_tokens=2000
)
return response.choices[0].message.content
except Exception as e:
raise RuntimeError(f"GPT-4o Error: {str(e)}")
def calculate_confidence(self, response: str) -> float:
"""Calculate semantic confidence score"""
query_embed = self.sentence_model.encode(response)
knowledge_embeds = self.knowledge_graph["embeddings"]
if knowledge_embeds.size == 0:
return 0.5 # Neutral confidence
similarities = cosine_similarity([query_embed], knowledge_embeds)
return np.max(similarities)
def update_knowledge_graph(self, query: str, response: str):
"""Dynamic knowledge integration"""
embedding = self.sentence_model.encode(response)
if self.knowledge_graph["embeddings"].size == 0:
self.knowledge_graph["embeddings"] = np.array([embedding])
else:
self.knowledge_graph["embeddings"] = np.vstack(
[self.knowledge_graph["embeddings"], embedding]
)
self.knowledge_graph["nodes"].append({
"id": len(self.knowledge_graph["nodes"]),
"content": response,
"embedding": embedding.tolist()
})
def handle_error(self, error: Exception):
"""Error handling and recovery"""
self.cognitive_metrics["error_rates"].append(time.time())
print(f"System Error: {str(error)}")
def create_agi_interface():
try:
agi = AGICognitiveSystem()
except ValueError as e:
return gr.Blocks().launch(error_message=str(e))
with gr.Blocks(title="Advanced AGI System", theme=gr.themes.Soft(), css="""
.cognitive-node { padding: 15px; margin: 10px; border-radius: 8px; background: #f8f9fa; }
.confidence-meter { height: 10px; background: #eee; border-radius: 5px; margin: 10px 0; }
.confidence-fill { height: 100%; border-radius: 5px; background: #4CAF50; }
""") as demo:
gr.Markdown("# 🧠 Advanced AGI Cognitive System")
with gr.Row():
input_panel = gr.Textbox(label="Input Query", lines=3,
placeholder="Enter complex query...")
with gr.Accordion("Cognitive Controls", open=False):
depth = gr.Slider(1, 10, value=5, label="Reasoning Depth")
creativity = gr.Slider(0, 1, value=0.7, label="Creativity Level")
loading = gr.HTML(LOADING_ANIMATION, visible=False)
output_panel = gr.Markdown()
visualization = gr.HTML()
metrics = gr.DataFrame(headers=["Metric", "Value"])
def toggle_loading():
return gr.HTML(visible=True)
def process_query(query):
start_time = time.time()
result, metrics = agi.cognitive_flow(query)
return result, metrics
input_panel.submit(
fn=toggle_loading,
inputs=None,
outputs=loading,
queue=False
).then(
fn=process_query,
inputs=input_panel,
outputs=[output_panel, metrics],
).then(
lambda: gr.HTML(visible=False),
inputs=None,
outputs=loading,
queue=False
)
return demo
if __name__ == "__main__":
create_agi_interface().launch(server_port=7860)