Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
346 lines (292 loc) · 11.8 KB
/
Copy pathapp.py
File metadata and controls
346 lines (292 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/env python3
"""
Prompt Optimizer Flask App - MLX API Server Version
Uses mlx_lm.server as a backend API instead of direct MLX integration.
This follows the recommended pattern from the MLX community.
"""
import os
import sys
import json
import logging
from typing import Dict, Any, Optional, Tuple
from flask import Flask, render_template, request, jsonify
import requests
import socket
from contextlib import closing
from dotenv import load_dotenv
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def get_available_port(preferred: int) -> int:
requested = int(os.environ.get('FLASK_PORT', preferred))
if _is_port_free(requested):
return requested
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(('', 0))
return s.getsockname()[1]
def _is_port_free(port: int) -> bool:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
return s.connect_ex(('0.0.0.0', port)) != 0
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'dev-key-change-in-production')
# Configuration
class Config:
# LLM Backend selection
LLM_BACKEND = os.environ.get('LLM_BACKEND', 'auto')
# MLX API Server Configuration (using mlx_lm.server)
MLX_API_URL = os.environ.get('MLX_API_URL', 'http://localhost:8080')
MLX_MODEL = os.environ.get('MLX_MODEL', 'mlx-community/Mistral-7B-Instruct-v0.3-4bit')
MLX_MAX_TOKENS = int(os.environ.get('MLX_MAX_TOKENS', '1024'))
MLX_TEMPERATURE = float(os.environ.get('MLX_TEMPERATURE', '0.7'))
# Ollama Configuration
OLLAMA_URL = os.environ.get('OLLAMA_URL', 'http://localhost:11434')
OLLAMA_MODEL = os.environ.get('OLLAMA_MODEL', 'llama2')
# LM Studio Configuration
LMSTUDIO_URL = os.environ.get('LMSTUDIO_URL', 'http://localhost:1234')
# Prompt refiners - load as class methods to handle errors properly
@classmethod
def load_prompt_template(cls, filename: str) -> str:
"""Load a prompt template file with proper error handling"""
try:
# Use absolute path relative to this script
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, 'templates', filename)
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
except FileNotFoundError:
logger.error(f"Prompt template file not found: {filename}")
return f"Error: Template file '{filename}' not found"
except Exception as e:
logger.error(f"Error reading prompt template {filename}: {e}")
return f"Error loading template: {e}"
@classmethod
def get_prompt_refiner_1(cls) -> str:
"""Get the first prompt refiner template"""
return cls.load_prompt_template('prompt.refiner.part1.md')
@classmethod
def get_prompt_refiner_2(cls) -> str:
"""Get the second prompt refiner template"""
return cls.load_prompt_template('prompt.refiner.part2.md')
class LLMBackend:
"""Abstract base for LLM backends"""
def generate(self, prompt: str) -> str:
raise NotImplementedError
def is_available(self) -> bool:
raise NotImplementedError
class MLXAPIBackend(LLMBackend):
"""MLX backend using mlx_lm.server API"""
def generate(self, prompt: str) -> str:
try:
response = requests.post(
f"{Config.MLX_API_URL}/v1/chat/completions",
json={
"model": Config.MLX_MODEL,
"max_completion_tokens": Config.MLX_MAX_TOKENS,
"temperature": Config.MLX_TEMPERATURE,
"messages": [
{"role": "user", "content": prompt}
]
},
timeout=180 # 3 minutes - generous timeout for analysis/optimization
)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
except Exception as e:
logger.error(f"MLX API generation failed: {e}")
raise
def is_available(self) -> bool:
try:
response = requests.get(f"{Config.MLX_API_URL}/health", timeout=2)
return response.status_code == 200
except:
# Try the chat endpoint if health endpoint doesn't exist
try:
response = requests.post(
f"{Config.MLX_API_URL}/v1/chat/completions",
json={
"model": Config.MLX_MODEL,
"max_completion_tokens": 1,
"messages": [{"role": "user", "content": "test"}]
},
timeout=2
)
return True # If it doesn't error immediately, server is up
except:
return False
class OllamaBackend(LLMBackend):
"""Ollama backend"""
def generate(self, prompt: str) -> str:
try:
print(f"Ollama model: {Config.OLLAMA_MODEL}")
response = requests.post(
f"{Config.OLLAMA_URL}/api/generate",
json={
"model": Config.OLLAMA_MODEL,
"prompt": prompt,
"stream": False
},
timeout=120
)
response.raise_for_status()
return response.json()["response"]
except Exception as e:
logger.error(f"Ollama generation failed: {e}")
raise
def is_available(self) -> bool:
try:
response = requests.get(f"{Config.OLLAMA_URL}/api/tags", timeout=2)
return response.status_code == 200
except:
return False
class LMStudioBackend(LLMBackend):
"""LM Studio backend"""
def generate(self, prompt: str) -> str:
try:
response = requests.post(
f"{Config.LMSTUDIO_URL}/v1/completions",
json={
"model": "local-model",
"prompt": prompt,
"max_tokens": 1024,
"temperature": 0.7
},
timeout=120
)
response.raise_for_status()
return response.json()["choices"][0]["text"]
except Exception as e:
logger.error(f"LM Studio generation failed: {e}")
raise
def is_available(self) -> bool:
try:
response = requests.get(f"{Config.LMSTUDIO_URL}/v1/models", timeout=2)
return response.status_code == 200
except:
return False
class PromptOptimizer:
"""Main prompt optimization logic"""
def __init__(self):
self.backend = self._select_backend()
if not self.backend:
raise RuntimeError("No LLM backend available")
def _select_backend(self) -> Optional[LLMBackend]:
"""Select the best available backend"""
backends = {
'mlx': MLXAPIBackend(),
'ollama': OllamaBackend(),
'lmstudio': LMStudioBackend()
}
# If specific backend requested, try it first
if Config.LLM_BACKEND != 'auto' and Config.LLM_BACKEND in backends:
backend = backends[Config.LLM_BACKEND]
if backend.is_available():
logger.info(f"Using requested backend: {Config.LLM_BACKEND}")
return backend
else:
logger.warning(f"Requested backend {Config.LLM_BACKEND} not available")
# Auto-select: prefer MLX API, then Ollama, then LM Studio
for name in ['mlx', 'ollama', 'lmstudio']:
backend = backends[name]
if backend.is_available():
logger.info(f"Auto-selected backend: {name}")
return backend
logger.error("No LLM backends available")
return None
def analyze_prompt(self, prompt: str) -> str:
"""Analyze a prompt using the selected backend"""
analysis_input = Config.get_prompt_refiner_1().format(prompt=prompt)
return self.backend.generate(analysis_input)
def optimize_prompt(self, original_prompt: str, analysis: str) -> str:
"""Optimize a prompt based on analysis"""
optimization_input = Config.get_prompt_refiner_2().format(
original_prompt=original_prompt,
analysis=analysis
)
return self.backend.generate(optimization_input)
def process_prompt(self, prompt: str) -> Tuple[str, str]:
"""Complete workflow: analyze then optimize"""
logger.info("Starting prompt analysis...")
analysis = self.analyze_prompt(prompt)
logger.info("Starting prompt optimization...")
optimized = self.optimize_prompt(prompt, analysis)
return analysis, optimized
# Global optimizer instance
optimizer = None
def init_optimizer():
"""Initialize the prompt optimizer"""
global optimizer
if optimizer is None:
try:
optimizer = PromptOptimizer()
logger.info(f"Prompt optimizer initialized with backend: {type(optimizer.backend).__name__}")
except Exception as e:
logger.error(f"Failed to initialize optimizer: {e}")
optimizer = None
return optimizer is not None
@app.route('/')
def index():
"""Main page"""
# Quick backend status check
backend_status = {
'MLX API': MLXAPIBackend().is_available(),
'Ollama': OllamaBackend().is_available(),
'LM Studio': LMStudioBackend().is_available()
}
return render_template('index.html', backend_status=backend_status)
@app.route('/api/optimize', methods=['POST'])
def optimize():
"""API endpoint for prompt optimization"""
try:
data = request.get_json()
if not data or 'prompt' not in data:
return jsonify({'error': 'No prompt provided'}), 400
prompt = data['prompt'].strip()
if not prompt:
return jsonify({'error': 'Empty prompt provided'}), 400
# Initialize optimizer if needed
if not init_optimizer():
return jsonify({'error': 'No LLM backend available'}), 503
# Process the prompt
analysis, optimized = optimizer.process_prompt(prompt)
return jsonify({
'success': True,
'analysis': analysis,
'optimized_prompt': optimized,
'backend': type(optimizer.backend).__name__
})
except Exception as e:
logger.error(f"Optimization failed: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/status')
def status():
"""API endpoint for checking system status"""
backend_status = {
'mlx_api': MLXAPIBackend().is_available(),
'ollama': OllamaBackend().is_available(),
'lmstudio': LMStudioBackend().is_available()
}
active_backend = None
if optimizer and optimizer.backend:
active_backend = type(optimizer.backend).__name__
return jsonify({
'backends': backend_status,
'active_backend': active_backend,
'config': {
'llm_backend': Config.LLM_BACKEND,
'mlx_api_url': Config.MLX_API_URL,
'mlx_model': Config.MLX_MODEL,
'ollama_url': Config.OLLAMA_URL,
'ollama_model': Config.OLLAMA_MODEL
}
})
if __name__ == '__main__':
port = get_available_port(5001)
print(f"🚀 Prompt Optimizer starting...")
print(f"📝 Will be available at http://127.0.0.1:{port}")
try:
app.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)
except Exception as e:
print(f"❌ Failed to start Flask: {e}")
import traceback
traceback.print_exc()