Spaces:
Sleeping
Sleeping
Your Name
commited on
Commit
·
3932389
1
Parent(s):
abba072
Fix: Use Instruction type for Pi-3.1 API, add nltk type stubs, improve error logging
Browse files- Changed system message type from 'System' to 'Instruction' (System requires event_type)
- Added nltk type stubs to resolve type checking warnings
- Enhanced logging in LLM wrapper for better debugging
- Fixed initialize_gemini method reference in app.py
- Updated .gitignore to exclude .venv and generated files
- .gitignore +7 -0
- agents/pi_agent.py +26 -16
- app.py +2 -3
- galatea_ai.py +0 -154
- llm_wrapper.py +4 -2
.gitignore
CHANGED
|
@@ -10,3 +10,10 @@ __pycache__/
|
|
| 10 |
venv/
|
| 11 |
env/
|
| 12 |
ENV/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
venv/
|
| 11 |
env/
|
| 12 |
ENV/
|
| 13 |
+
.venv/
|
| 14 |
+
|
| 15 |
+
# Generated files
|
| 16 |
+
*.log
|
| 17 |
+
chroma_db/
|
| 18 |
+
memory.json
|
| 19 |
+
"import random.md"
|
agents/pi_agent.py
CHANGED
|
@@ -42,39 +42,49 @@ class PiResponseAgent:
|
|
| 42 |
# Create context with emotional state
|
| 43 |
emotions_text = ", ".join([f"{emotion}: {value:.2f}" for emotion, value in emotional_state.items()])
|
| 44 |
|
| 45 |
-
# Build comprehensive context
|
| 46 |
-
# We'll incorporate system instructions into the first Human message
|
| 47 |
context_parts = []
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
|
| 52 |
# Add thinking context from Gemini if available
|
| 53 |
if thinking_context:
|
| 54 |
-
|
| 55 |
|
| 56 |
# Add retrieved memories if available
|
| 57 |
if retrieved_memories and len(retrieved_memories) > 0:
|
| 58 |
-
memory_text = "
|
| 59 |
for i, memory in enumerate(retrieved_memories[:3], 1): # Top 3 most relevant
|
| 60 |
-
memory_text += f"{i}. {memory['text'][:
|
| 61 |
-
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
# Add conversation history as context messages (Human/Assistant only)
|
| 66 |
if conversation_history and len(conversation_history) > 0:
|
| 67 |
-
#
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
context_parts.append({
|
| 70 |
"text": msg["content"],
|
| 71 |
"type": "Human" if msg["role"] == "user" else "Assistant"
|
| 72 |
})
|
| 73 |
|
| 74 |
-
# Add current user input
|
| 75 |
-
enhanced_user_input = f"{system_instructions}\n\n{user_input}"
|
| 76 |
context_parts.append({
|
| 77 |
-
"text":
|
| 78 |
"type": "Human"
|
| 79 |
})
|
| 80 |
|
|
|
|
| 42 |
# Create context with emotional state
|
| 43 |
emotions_text = ", ".join([f"{emotion}: {value:.2f}" for emotion, value in emotional_state.items()])
|
| 44 |
|
| 45 |
+
# Build comprehensive context with thinking insights, conversation history, and retrieved memories
|
|
|
|
| 46 |
context_parts = []
|
| 47 |
|
| 48 |
+
# Base system context - Inflection AI uses lowercase "system" type
|
| 49 |
+
base_context = f"You are Galatea, an AI assistant with the following emotional state: {emotions_text}. Respond in character as Galatea. Keep your response concise (under 50 words) and reflect your emotional state in your tone."
|
| 50 |
|
| 51 |
# Add thinking context from Gemini if available
|
| 52 |
if thinking_context:
|
| 53 |
+
base_context += f"\n\nInternal analysis: {thinking_context}"
|
| 54 |
|
| 55 |
# Add retrieved memories if available
|
| 56 |
if retrieved_memories and len(retrieved_memories) > 0:
|
| 57 |
+
memory_text = "\n\nRelevant context from past conversations:\n"
|
| 58 |
for i, memory in enumerate(retrieved_memories[:3], 1): # Top 3 most relevant
|
| 59 |
+
memory_text += f"{i}. {memory['text'][:150]}...\n"
|
| 60 |
+
base_context += memory_text
|
| 61 |
|
| 62 |
+
# Add conversation history context
|
|
|
|
|
|
|
| 63 |
if conversation_history and len(conversation_history) > 0:
|
| 64 |
+
recent_history = conversation_history[-4:] # Last 2 exchanges
|
| 65 |
+
history_text = "\n\nRecent conversation context:\n"
|
| 66 |
+
for msg in recent_history:
|
| 67 |
+
role = "User" if msg["role"] == "user" else "You (Galatea)"
|
| 68 |
+
history_text += f"{role}: {msg['content']}\n"
|
| 69 |
+
base_context += history_text
|
| 70 |
+
|
| 71 |
+
context_parts.append({
|
| 72 |
+
"text": base_context,
|
| 73 |
+
"type": "Instruction" # Use "Instruction" type for system instructions (System requires event_type)
|
| 74 |
+
})
|
| 75 |
+
|
| 76 |
+
# Add conversation history as context messages
|
| 77 |
+
if conversation_history and len(conversation_history) > 4:
|
| 78 |
+
# Add older messages as context (but not the most recent ones we already included)
|
| 79 |
+
for msg in conversation_history[-8:-4]:
|
| 80 |
context_parts.append({
|
| 81 |
"text": msg["content"],
|
| 82 |
"type": "Human" if msg["role"] == "user" else "Assistant"
|
| 83 |
})
|
| 84 |
|
| 85 |
+
# Add current user input
|
|
|
|
| 86 |
context_parts.append({
|
| 87 |
+
"text": user_input,
|
| 88 |
"type": "Human"
|
| 89 |
})
|
| 90 |
|
app.py
CHANGED
|
@@ -106,9 +106,8 @@ def initialize_gemini():
|
|
| 106 |
logging.error("GEMINI_API_KEY not found in environment variables")
|
| 107 |
return False
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
galatea_ai.
|
| 111 |
-
gemini_success = hasattr(galatea_ai, 'gemini_available') and galatea_ai.gemini_available
|
| 112 |
|
| 113 |
if gemini_success:
|
| 114 |
gemini_initialized = True
|
|
|
|
| 106 |
logging.error("GEMINI_API_KEY not found in environment variables")
|
| 107 |
return False
|
| 108 |
|
| 109 |
+
# Check if Gemini agent is ready (initialization happens automatically in GalateaAI.__init__)
|
| 110 |
+
gemini_success = hasattr(galatea_ai, 'gemini_agent') and galatea_ai.gemini_agent.is_ready()
|
|
|
|
| 111 |
|
| 112 |
if gemini_success:
|
| 113 |
gemini_initialized = True
|
galatea_ai.py
CHANGED
|
@@ -56,10 +56,6 @@ class GalateaAI:
|
|
| 56 |
self.emotional_agent = EmotionalStateAgent(config=self.config)
|
| 57 |
self.sentiment_agent = SentimentAgent(config=self.config)
|
| 58 |
|
| 59 |
-
# Run end-to-end chat simulation test - CRITICAL: Tests full workflow as if in a real chat
|
| 60 |
-
logging.info("Running end-to-end chat simulation test...")
|
| 61 |
-
self._run_chat_simulation_test()
|
| 62 |
-
|
| 63 |
# Track initialization status
|
| 64 |
self.memory_system_ready = self.memory_agent.is_ready()
|
| 65 |
self.sentiment_analyzer_ready = self.sentiment_agent.is_ready()
|
|
@@ -87,156 +83,6 @@ class GalateaAI:
|
|
| 87 |
|
| 88 |
logging.info("✓ All agents initialized and verified")
|
| 89 |
|
| 90 |
-
def _run_chat_simulation_test(self):
|
| 91 |
-
"""Run a full end-to-end chat simulation test - simulates real chat interaction"""
|
| 92 |
-
logging.info("=" * 60)
|
| 93 |
-
logging.info("RUNNING END-TO-END CHAT SIMULATION TEST")
|
| 94 |
-
logging.info("=" * 60)
|
| 95 |
-
|
| 96 |
-
test_messages = [
|
| 97 |
-
"Hello, how are you?",
|
| 98 |
-
"What can you help me with?",
|
| 99 |
-
"Tell me something interesting."
|
| 100 |
-
]
|
| 101 |
-
|
| 102 |
-
test_results = {
|
| 103 |
-
'sentiment_analysis': False,
|
| 104 |
-
'emotional_state_update': False,
|
| 105 |
-
'memory_retrieval': False,
|
| 106 |
-
'gemini_thinking': False,
|
| 107 |
-
'pi_response': False,
|
| 108 |
-
'full_workflow': False
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
try:
|
| 112 |
-
# Test with first message
|
| 113 |
-
test_input = test_messages[0]
|
| 114 |
-
logging.info(f"[Chat Simulation] Testing with message: '{test_input}'")
|
| 115 |
-
|
| 116 |
-
# Step 1: Test sentiment analysis
|
| 117 |
-
try:
|
| 118 |
-
sentiment_score = self.sentiment_agent.analyze(test_input)
|
| 119 |
-
if sentiment_score is not None and isinstance(sentiment_score, (int, float)):
|
| 120 |
-
test_results['sentiment_analysis'] = True
|
| 121 |
-
logging.info(f"[Chat Simulation] ✓ Sentiment analysis: {sentiment_score:.3f}")
|
| 122 |
-
else:
|
| 123 |
-
raise RuntimeError("Sentiment analysis returned invalid result")
|
| 124 |
-
except Exception as e:
|
| 125 |
-
logging.error(f"[Chat Simulation] ✗ Sentiment analysis failed: {e}")
|
| 126 |
-
raise RuntimeError(f"Sentiment analysis failed during chat simulation: {e}")
|
| 127 |
-
|
| 128 |
-
# Step 2: Test emotional state update
|
| 129 |
-
try:
|
| 130 |
-
initial_state = self.emotional_agent.get_state().copy()
|
| 131 |
-
self.emotional_agent.update_with_sentiment(sentiment_score)
|
| 132 |
-
updated_state = self.emotional_agent.get_state()
|
| 133 |
-
if updated_state and isinstance(updated_state, dict) and len(updated_state) > 0:
|
| 134 |
-
test_results['emotional_state_update'] = True
|
| 135 |
-
logging.info(f"[Chat Simulation] ✓ Emotional state updated: {updated_state}")
|
| 136 |
-
else:
|
| 137 |
-
raise RuntimeError("Emotional state update returned invalid state")
|
| 138 |
-
except Exception as e:
|
| 139 |
-
logging.error(f"[Chat Simulation] ✗ Emotional state update failed: {e}")
|
| 140 |
-
raise RuntimeError(f"Emotional state update failed during chat simulation: {e}")
|
| 141 |
-
|
| 142 |
-
# Step 3: Test memory retrieval
|
| 143 |
-
try:
|
| 144 |
-
keywords = self.extract_keywords(test_input)
|
| 145 |
-
retrieved_memories = self.memory_agent.retrieve_memories(test_input)
|
| 146 |
-
if retrieved_memories is not None:
|
| 147 |
-
test_results['memory_retrieval'] = True
|
| 148 |
-
logging.info(f"[Chat Simulation] ✓ Memory retrieval: {len(retrieved_memories)} memories found")
|
| 149 |
-
else:
|
| 150 |
-
raise RuntimeError("Memory retrieval returned None")
|
| 151 |
-
except Exception as e:
|
| 152 |
-
logging.error(f"[Chat Simulation] ✗ Memory retrieval failed: {e}")
|
| 153 |
-
raise RuntimeError(f"Memory retrieval failed during chat simulation: {e}")
|
| 154 |
-
|
| 155 |
-
# Step 4: Test Gemini thinking
|
| 156 |
-
try:
|
| 157 |
-
current_emotional_state = self.emotional_agent.get_state()
|
| 158 |
-
thinking_context = self.gemini_agent.think(
|
| 159 |
-
test_input,
|
| 160 |
-
current_emotional_state,
|
| 161 |
-
self.conversation_history,
|
| 162 |
-
retrieved_memories=retrieved_memories
|
| 163 |
-
)
|
| 164 |
-
if thinking_context and len(thinking_context) > 0:
|
| 165 |
-
test_results['gemini_thinking'] = True
|
| 166 |
-
logging.info(f"[Chat Simulation] ✓ Gemini thinking: {thinking_context[:100]}...")
|
| 167 |
-
else:
|
| 168 |
-
raise RuntimeError("Gemini thinking returned empty or None")
|
| 169 |
-
except Exception as e:
|
| 170 |
-
logging.error(f"[Chat Simulation] ✗ Gemini thinking failed: {e}")
|
| 171 |
-
raise RuntimeError(f"Gemini thinking failed during chat simulation: {e}")
|
| 172 |
-
|
| 173 |
-
# Step 5: Test Pi-3.1 response generation
|
| 174 |
-
try:
|
| 175 |
-
response = self.pi_agent.respond(
|
| 176 |
-
test_input,
|
| 177 |
-
current_emotional_state,
|
| 178 |
-
thinking_context=thinking_context,
|
| 179 |
-
conversation_history=self.conversation_history,
|
| 180 |
-
retrieved_memories=retrieved_memories
|
| 181 |
-
)
|
| 182 |
-
if response and len(response) > 0:
|
| 183 |
-
test_results['pi_response'] = True
|
| 184 |
-
logging.info(f"[Chat Simulation] ✓ Pi-3.1 response: {response[:100]}...")
|
| 185 |
-
else:
|
| 186 |
-
raise RuntimeError("Pi-3.1 response returned empty or None")
|
| 187 |
-
except Exception as e:
|
| 188 |
-
logging.error(f"[Chat Simulation] ✗ Pi-3.1 response failed: {e}")
|
| 189 |
-
raise RuntimeError(f"Pi-3.1 response generation failed during chat simulation: {e}")
|
| 190 |
-
|
| 191 |
-
# Step 6: Test full workflow using process_input
|
| 192 |
-
try:
|
| 193 |
-
# Reset conversation history for clean test
|
| 194 |
-
original_history = self.conversation_history.copy()
|
| 195 |
-
self.conversation_history = []
|
| 196 |
-
|
| 197 |
-
full_response = self.process_input(test_input)
|
| 198 |
-
if full_response and len(full_response) > 0:
|
| 199 |
-
test_results['full_workflow'] = True
|
| 200 |
-
logging.info(f"[Chat Simulation] ✓ Full workflow test: {full_response[:100]}...")
|
| 201 |
-
else:
|
| 202 |
-
raise RuntimeError("Full workflow test returned empty or None")
|
| 203 |
-
|
| 204 |
-
# Restore conversation history
|
| 205 |
-
self.conversation_history = original_history
|
| 206 |
-
except Exception as e:
|
| 207 |
-
logging.error(f"[Chat Simulation] ✗ Full workflow test failed: {e}")
|
| 208 |
-
raise RuntimeError(f"Full workflow test failed during chat simulation: {e}")
|
| 209 |
-
|
| 210 |
-
# Print summary
|
| 211 |
-
logging.info("=" * 60)
|
| 212 |
-
logging.info("CHAT SIMULATION TEST SUMMARY")
|
| 213 |
-
logging.info("=" * 60)
|
| 214 |
-
for test_name, result in test_results.items():
|
| 215 |
-
status = "✓ PASSED" if result else "✗ FAILED"
|
| 216 |
-
logging.info(f"{status} - {test_name.upper().replace('_', ' ')}")
|
| 217 |
-
logging.info("=" * 60)
|
| 218 |
-
|
| 219 |
-
# CRITICAL: Verify all tests passed
|
| 220 |
-
if not all(test_results.values()):
|
| 221 |
-
failed_tests = [name for name, result in test_results.items() if not result]
|
| 222 |
-
error_msg = f"CRITICAL: Chat simulation tests failed for: {', '.join(failed_tests).upper()}. Application cannot continue."
|
| 223 |
-
logging.error("=" * 60)
|
| 224 |
-
logging.error(error_msg)
|
| 225 |
-
logging.error("=" * 60)
|
| 226 |
-
raise RuntimeError(error_msg)
|
| 227 |
-
|
| 228 |
-
logging.info("✓ All chat simulation tests passed - system ready for production use")
|
| 229 |
-
|
| 230 |
-
except RuntimeError:
|
| 231 |
-
# Re-raise RuntimeError as-is (already has proper error message)
|
| 232 |
-
raise
|
| 233 |
-
except Exception as e:
|
| 234 |
-
error_msg = f"CRITICAL: Chat simulation test failed with unexpected error: {e}"
|
| 235 |
-
logging.error("=" * 60)
|
| 236 |
-
logging.error(error_msg)
|
| 237 |
-
logging.error("=" * 60)
|
| 238 |
-
raise RuntimeError(error_msg)
|
| 239 |
-
|
| 240 |
def _check_pre_initialization(self):
|
| 241 |
"""Check if components were pre-initialized by initialize_galatea.py"""
|
| 242 |
# Check if JSON memory exists
|
|
|
|
| 56 |
self.emotional_agent = EmotionalStateAgent(config=self.config)
|
| 57 |
self.sentiment_agent = SentimentAgent(config=self.config)
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
# Track initialization status
|
| 60 |
self.memory_system_ready = self.memory_agent.is_ready()
|
| 61 |
self.sentiment_analyzer_ready = self.sentiment_agent.is_ready()
|
|
|
|
| 83 |
|
| 84 |
logging.info("✓ All agents initialized and verified")
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
def _check_pre_initialization(self):
|
| 87 |
"""Check if components were pre-initialized by initialize_galatea.py"""
|
| 88 |
# Check if JSON memory exists
|
llm_wrapper.py
CHANGED
|
@@ -166,7 +166,8 @@ class LLMWrapper:
|
|
| 166 |
|
| 167 |
try:
|
| 168 |
logging.info(f"[LLMWrapper] Calling Inflection AI API: {model_config}")
|
| 169 |
-
logging.
|
|
|
|
| 170 |
logging.debug(f"[LLMWrapper] Request data: {data}")
|
| 171 |
response = requests.post(url, headers=headers, json=data, timeout=30)
|
| 172 |
|
|
@@ -180,8 +181,9 @@ class LLMWrapper:
|
|
| 180 |
logging.error(f"[LLMWrapper] Raw response text: {response.text[:500]}")
|
| 181 |
return None
|
| 182 |
|
| 183 |
-
logging.
|
| 184 |
logging.info(f"[LLMWrapper] Response type: {type(result)}")
|
|
|
|
| 185 |
|
| 186 |
# Extract response text - Inflection AI returns text in 'text' field
|
| 187 |
# Based on actual API response: {"created": ..., "text": "...", "tool_calls": [], "reasoning_content": null}
|
|
|
|
| 166 |
|
| 167 |
try:
|
| 168 |
logging.info(f"[LLMWrapper] Calling Inflection AI API: {model_config}")
|
| 169 |
+
logging.info(f"[LLMWrapper] Request URL: {url}")
|
| 170 |
+
logging.info(f"[LLMWrapper] Request context parts count: {len(context_parts)}")
|
| 171 |
logging.debug(f"[LLMWrapper] Request data: {data}")
|
| 172 |
response = requests.post(url, headers=headers, json=data, timeout=30)
|
| 173 |
|
|
|
|
| 181 |
logging.error(f"[LLMWrapper] Raw response text: {response.text[:500]}")
|
| 182 |
return None
|
| 183 |
|
| 184 |
+
logging.info(f"[LLMWrapper] Response JSON: {result}")
|
| 185 |
logging.info(f"[LLMWrapper] Response type: {type(result)}")
|
| 186 |
+
logging.info(f"[LLMWrapper] Response keys: {list(result.keys()) if isinstance(result, dict) else 'N/A'}")
|
| 187 |
|
| 188 |
# Extract response text - Inflection AI returns text in 'text' field
|
| 189 |
# Based on actual API response: {"created": ..., "text": "...", "tool_calls": [], "reasoning_content": null}
|