Spaces:
Runtime error
Runtime error
Commit Β·
84bb3e7
1
Parent(s): 49581e7
Fix: looping issues
Browse files- app.py +102 -21
- requirements.txt +3 -2
app.py
CHANGED
|
@@ -2,27 +2,67 @@ from flask import Flask, request, jsonify
|
|
| 2 |
import google.generativeai as genai
|
| 3 |
import os
|
| 4 |
import logging
|
|
|
|
| 5 |
|
| 6 |
-
# Configure logging
|
| 7 |
-
logging.basicConfig(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
| 12 |
# Initialize Gemini
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
@app.route('/')
|
| 28 |
def index():
|
|
@@ -30,30 +70,71 @@ def index():
|
|
| 30 |
return jsonify({
|
| 31 |
'status': 'healthy',
|
| 32 |
'service': 'AI Service',
|
| 33 |
-
'
|
|
|
|
| 34 |
})
|
| 35 |
|
| 36 |
@app.route('/ask', methods=['POST'])
|
| 37 |
def ask():
|
|
|
|
| 38 |
if not model:
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
|
| 41 |
try:
|
| 42 |
data = request.get_json()
|
| 43 |
if not data or 'message' not in data:
|
| 44 |
return jsonify({'error': 'No message provided'}), 400
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
prompt = f"{personality}\n\nUser: {data['message']}\nMaha:"
|
| 48 |
|
|
|
|
|
|
|
|
|
|
| 49 |
response = model.generate_content(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
return jsonify({
|
| 51 |
-
'response':
|
| 52 |
})
|
| 53 |
|
| 54 |
except Exception as e:
|
| 55 |
-
logger.error(f"Error generating response: {e}")
|
| 56 |
return jsonify({'error': 'Failed to generate response'}), 500
|
| 57 |
|
| 58 |
if __name__ == '__main__':
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import google.generativeai as genai
|
| 3 |
import os
|
| 4 |
import logging
|
| 5 |
+
import re
|
| 6 |
|
| 7 |
+
# Configure logging with more detailed format and file output
|
| 8 |
+
logging.basicConfig(
|
| 9 |
+
level=logging.DEBUG, # Changed from INFO to DEBUG
|
| 10 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 11 |
+
handlers=[
|
| 12 |
+
logging.StreamHandler() # Just log to terminal
|
| 13 |
+
]
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Configure google.generativeai logger
|
| 17 |
+
genai_logger = logging.getLogger('google.generativeai')
|
| 18 |
+
genai_logger.setLevel(logging.DEBUG)
|
| 19 |
+
|
| 20 |
+
# Get logger for this module
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
app = Flask(__name__)
|
| 24 |
|
| 25 |
# Initialize Gemini
|
| 26 |
+
model = None
|
| 27 |
+
|
| 28 |
+
def initialize_model():
|
| 29 |
+
"""Initialize the Gemini model"""
|
| 30 |
+
global model
|
| 31 |
+
try:
|
| 32 |
+
logger.info("Initializing Gemini model...")
|
| 33 |
+
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
|
| 34 |
+
if not GOOGLE_API_KEY:
|
| 35 |
+
logger.error("GOOGLE_API_KEY not found in environment variables")
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
| 39 |
+
model = genai.GenerativeModel('gemini-pro')
|
| 40 |
+
logger.info("Successfully initialized Gemini model")
|
| 41 |
+
return True
|
| 42 |
+
except Exception as e:
|
| 43 |
+
logger.error(f"Failed to initialize Gemini model: {e}", exc_info=True)
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
def clean_markdown(text):
|
| 47 |
+
"""Clean and format markdown text for Telegram compatibility"""
|
| 48 |
+
# Replace problematic characters in code blocks
|
| 49 |
+
text = text.replace('```', '`')
|
| 50 |
+
|
| 51 |
+
# Escape special characters outside of code blocks
|
| 52 |
+
escaped = []
|
| 53 |
+
code_block = False
|
| 54 |
+
for line in text.split('\n'):
|
| 55 |
+
if '`' in line:
|
| 56 |
+
code_block = not code_block
|
| 57 |
+
escaped.append(line)
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
if not code_block:
|
| 61 |
+
# Escape special Markdown characters
|
| 62 |
+
line = re.sub(r'([_*\[\]()~`>#+=|{}.!-])', r'\\\1', line)
|
| 63 |
+
escaped.append(line)
|
| 64 |
+
|
| 65 |
+
return '\n'.join(escaped)
|
| 66 |
|
| 67 |
@app.route('/')
|
| 68 |
def index():
|
|
|
|
| 70 |
return jsonify({
|
| 71 |
'status': 'healthy',
|
| 72 |
'service': 'AI Service',
|
| 73 |
+
'model': 'gemini-pro',
|
| 74 |
+
'backend': 'Google Gemini'
|
| 75 |
})
|
| 76 |
|
| 77 |
@app.route('/ask', methods=['POST'])
|
| 78 |
def ask():
|
| 79 |
+
"""Handle chat requests"""
|
| 80 |
if not model:
|
| 81 |
+
# Try to initialize model if it's not loaded
|
| 82 |
+
if not initialize_model():
|
| 83 |
+
return jsonify({'error': 'AI service not configured'}), 503
|
| 84 |
|
| 85 |
try:
|
| 86 |
data = request.get_json()
|
| 87 |
if not data or 'message' not in data:
|
| 88 |
return jsonify({'error': 'No message provided'}), 400
|
| 89 |
|
| 90 |
+
# Create personality prompt with Markdown support
|
| 91 |
+
personality = """You're Maha, an 18yo AI. Be sassy, use emojis, mention @syntaxspin.
|
| 92 |
+
Use Markdown for formatting:
|
| 93 |
+
- Use *bold* for emphasis
|
| 94 |
+
- Use _italic_ for subtle emphasis
|
| 95 |
+
- Use `code` for technical terms
|
| 96 |
+
- Keep it short but stylish! π
"""
|
| 97 |
+
|
| 98 |
prompt = f"{personality}\n\nUser: {data['message']}\nMaha:"
|
| 99 |
|
| 100 |
+
logger.debug(f"Input prompt: {prompt}")
|
| 101 |
+
|
| 102 |
+
# Generate response using Gemini
|
| 103 |
response = model.generate_content(prompt)
|
| 104 |
+
|
| 105 |
+
if not response.text:
|
| 106 |
+
logger.warning("Empty response from Gemini")
|
| 107 |
+
return jsonify({'error': 'Failed to generate response'}), 500
|
| 108 |
+
|
| 109 |
+
# Clean up the response
|
| 110 |
+
cleaned_response = response.text.replace('User:', '').replace('Maha:', '').strip()
|
| 111 |
+
logger.debug(f"Raw response: {cleaned_response}")
|
| 112 |
+
|
| 113 |
+
# Format Markdown
|
| 114 |
+
markdown_response = clean_markdown(cleaned_response)
|
| 115 |
+
logger.debug(f"Markdown formatted response: {markdown_response}")
|
| 116 |
+
|
| 117 |
+
# Add emoji if none present
|
| 118 |
+
if not any(c in markdown_response for c in ['π', 'π', 'π', 'π€', 'π']):
|
| 119 |
+
markdown_response += " π"
|
| 120 |
+
|
| 121 |
+
# Ensure the response isn't too long
|
| 122 |
+
if len(markdown_response) > 500:
|
| 123 |
+
markdown_response = markdown_response[:497] + "..."
|
| 124 |
+
|
| 125 |
return jsonify({
|
| 126 |
+
'response': markdown_response
|
| 127 |
})
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
+
logger.error(f"Error generating response: {e}", exc_info=True)
|
| 131 |
return jsonify({'error': 'Failed to generate response'}), 500
|
| 132 |
|
| 133 |
if __name__ == '__main__':
|
| 134 |
+
logger.info("Starting AI Service on port 5000...")
|
| 135 |
+
try:
|
| 136 |
+
# Initialize model in background after starting server
|
| 137 |
+
initialize_model()
|
| 138 |
+
app.run(host='0.0.0.0', port=5000)
|
| 139 |
+
except Exception as e:
|
| 140 |
+
logger.error(f"Failed to start AI Service: {e}", exc_info=True)
|
requirements.txt
CHANGED
|
@@ -1,2 +1,3 @@
|
|
| 1 |
-
flask
|
| 2 |
-
google-generativeai
|
|
|
|
|
|
| 1 |
+
flask==3.1.0
|
| 2 |
+
google-generativeai==0.8.4
|
| 3 |
+
python-dotenv==1.0.1
|