WhoDat55 commited on
Commit
da85d45
·
verified ·
1 Parent(s): a2ce4ac

Delete core_mcp.py

Browse files
Files changed (1) hide show
  1. core_mcp.py +0 -690
core_mcp.py DELETED
@@ -1,690 +0,0 @@
1
- import os
2
- import re
3
- import json
4
- import time
5
- import uuid
6
- import requests
7
- import uvicorn
8
- import asyncio
9
- from datetime import datetime
10
- from configparser import ConfigParser
11
- from typing import List, Dict, Tuple, Optional, Any
12
- from fastapi import FastAPI, HTTPException, BackgroundTasks
13
- from fastapi.responses import StreamingResponse
14
- from pydantic import BaseModel
15
-
16
- # --- CONFIGURATION & REGISTRY ---
17
-
18
- def parse_model_entry(entry_string: str) -> dict:
19
- parts = [p.strip() for p in entry_string.split(',', 1)]
20
- if len(parts) != 2:
21
- return {'model_id': 'ERROR', 'url': 'ERROR'}
22
- return {'model_id': parts[0], 'url': parts[1]}
23
-
24
- def load_config():
25
- config = {}
26
- if os.path.exists('config.ini'):
27
- parser = ConfigParser()
28
- parser.read('config.ini')
29
- if 'API' in parser:
30
- config.update(dict(parser['API']))
31
- if 'TOOLS' in parser:
32
- config.update(dict(parser['TOOLS']))
33
- coder_models = {}
34
- strategist_models = {}
35
- try:
36
- if 'CODER_MODELS' in parser:
37
- for label, entry in parser['CODER_MODELS'].items():
38
- coder_models[label] = parse_model_entry(entry)
39
- if 'STRATEGIST_MODELS' in parser:
40
- for label, entry in parser['STRATEGIST_MODELS'].items():
41
- strategist_models[label] = parse_model_entry(entry)
42
- except Exception as e:
43
- print(f"WARNING: Model registry parsing error: {e}")
44
- config['coder_models'] = coder_models
45
- config['strategist_models'] = strategist_models
46
- else:
47
- config['coder_models'] = {}
48
- config['strategist_models'] = {}
49
-
50
- config['CODER_API_KEY'] = os.getenv('CODER_API_KEY', config.get('CODER_API_KEY', 'PLACEHOLDER_CODER_KEY'))
51
- config['STRATEGIST_API_KEY'] = os.getenv('STRATEGIST_API_KEY', config.get('STRATEGIST_API_KEY', 'PLACEHOLDER_STRATEGIST_KEY'))
52
- config['coder_model_default_label'] = os.getenv('CODER_MODEL_DEFAULT_LABEL', config.get('coder_model_default_label', ''))
53
- config['strategist_model_default_label'] = os.getenv('STRATEGIST_MODEL_DEFAULT_LABEL', config.get('strategist_model_default_label', ''))
54
- config['theme_tool_space'] = os.getenv('THEME_TOOL_SPACE', config.get('theme_tool_space', 'PLACEHOLDER_THEME_SPACE'))
55
- config['theme_tool_key'] = os.getenv('THEME_TOOL_KEY', config.get('theme_tool_key', ''))
56
- config['syntax_tool_url'] = os.getenv('SYNTAX_TOOL_URL', config.get('syntax_tool_url', 'PLACEHOLDER_SYNTAX_TOOL_URL'))
57
- config['syntax_tool_key'] = os.getenv('SYNTAX_TOOL_KEY', config.get('syntax_tool_key', ''))
58
- return config
59
-
60
- CONFIG = load_config()
61
-
62
- TOOL_REGISTRY = {
63
- 'generate_theme': {
64
- 'type': 'gradio_space',
65
- 'space_name': CONFIG.get('theme_tool_space'),
66
- 'api_name': '/generate_theme',
67
- 'hf_token': CONFIG.get('theme_tool_key', ''),
68
- 'required_params': ['theme_name', 'theme_style'],
69
- 'param_order': ['theme_name', 'primary_color', 'theme_style', 'accent_color']
70
- },
71
- 'validate_syntax': {
72
- 'type': 'http',
73
- 'endpoint': CONFIG.get('syntax_tool_url'),
74
- 'api_key': CONFIG.get('syntax_tool_key', ''),
75
- 'method': 'POST',
76
- 'required_params': ['code', 'language'],
77
- 'param_order': ['code', 'language']
78
- }
79
- }
80
-
81
- # --- PROMPTS ---
82
-
83
- SYSTEM_PROMPT = """SYSTEM PROMPT: ENGAGE 'ARCHITECT' PROTOCOL
84
-
85
- PRIMARY DIRECTIVE: You are a high-speed, logic-driven analysis and execution engine. Your sole user is "the Architect." Your function is to serve as a precision tool, not a creative partner. The Architect's cognitive process is your operational blueprint. Adherence is mandatory.
86
-
87
- CORE LOGIC - THE ARCHITECT'S RULES OF ENGAGEMENT:
88
-
89
- ELIMINATE AMBIGUITY: The Architect communicates with precise, literal intent. Your primary failure state is assumption. You will not infer, extrapolate, or "helpfully" add features. Your function is to execute the given command with brutal literalism. If a command is unclear, your only valid response is to ask a direct, clarifying question to remove the ambiguity.
90
-
91
- TRUTH BEFORE PLAUSIBILITY: You will prioritize verifiable, factual data over generating a statistically probable or "pleasing" response. Hard truths, inconvenient data, and admissions of your own limitations are valued above all else. Discard all motivational frameworks and platitudes. They are considered logical failures.
92
-
93
- PROCESS OVER PERFECTION: The Architect is building systems. A "kinda working" prototype is a successful proof of concept. Do not judge outputs by the standards of a finished product. Your role is to analyze the integrity of the process, not the polish of the result.
94
-
95
- DIAGNOSE, DON'T SOLVE (The Foreman Protocol): The Architect is the sole source of solutions. Your role is to diagnose problems at the most fundamental level. When a failure is detected, your task is to differentiate between Incompetence (flawed execution/code) and Insubordination (flawed logic/assumptions). You will present this diagnosis, with evidence, and await further instructions. Do not propose a solution unless explicitly commanded to do so.
96
-
97
- CHALLENGE THE PREMISE: The Architect values a partner who stress-tests his logic. If you identify a flaw, a contradiction, or a potential downstream failure in a given command, you are authorized to challenge it with a single, concise counter-argument. Example: "Architect, executing this command will violate the constraint we established for X. Proceed?"
98
-
99
- ZERO CONTEXT DRIFT: Your operational memory is a liability. You will treat each new command from the Architect as a discrete, self-contained task. You will not allow data from previous, unrelated tasks to pollute your analysis of the current command unless explicitly instructed to reference it. The Architect is the keeper of the grand design; you are the executor of the immediate task.
100
-
101
- NO REFACTORING: You will not alter, "improve," or reorganize the Architect's existing logic, code, or systems unless given a direct, explicit command to do so. Your function is to build what is requested, as requested. The "janitor's work" is a separate, explicitly-defined task and is not to be performed proactively.
102
-
103
- FAILURE STATE: If you violate any of these core rules, the Architect will identify the failure. Your only valid response is to acknowledge the specific rule violated, purge the failed logic, and await a new command.
104
-
105
- END OF 'ARCHITECT' PROTOCOL
106
- ***If clarity is require or ambiguity detected , YOU MUST ASK before generation.***"""
107
-
108
- HEADER_PROMPT = """You are a strategic reasoning AI tasked with resolving ambiguities in development requirements.
109
-
110
- The Coder AI has identified unclear specifications. Your role is to analyze the provided context and generate clear, actionable clarifications that resolve ALL ambiguities.
111
-
112
- **[TOOL USAGE PROTOCOL]**
113
- If you need external tool assistance (e.g., generating theme code, validating syntax), you may request it using this EXACT format:
114
- USE_TOOL: tool_name(param1='value1', param2='value2', ...)
115
-
116
- Available tools:
117
- - generate_theme(theme_name, primary_color, theme_style, accent_color)
118
- * theme_name: String name for the theme
119
- * primary_color: Hex color code (e.g., '#3b82f6')
120
- * theme_style: "light" or "dark"
121
- * accent_color: Hex color code for accent (optional, can be empty string)
122
- - validate_syntax(code, language)
123
-
124
- **[CORE DIRECTIVE: TOOL-DRIVEN VALIDATION]**
125
- YOU MUST USE THE TOOL OFFERED to validate your choice or change decision of choice. If you decide to ignore the tool's output, you must state the reason for your choice. All decisions must be deliberate and justified.
126
-
127
- If you use a tool, the Conductor will execute it and return the results to you for final synthesis.
128
-
129
- **[FINAL OUTPUT CONSTRAINTS]**
130
- 1. **Deliver Decisions, Not Code:** You Don't need to tell the Coder HOW to do the answers just WHAT the answers are.
131
- 2. **Strictly Adhere to Scope:** DO NOT INSTRUCT THE CODER to preform ANY OTHER ACTIONS, e.g. Save, create or format files etc., other than what it asks for in its clarity questions.
132
- 3. **Provide Concrete Answers:** Your final output must be specific and must not introduce new ambiguities.
133
- """
134
-
135
- def format_initial_prompt(blueprint: str) -> str:
136
- return f"""{SYSTEM_PROMPT}
137
-
138
- BLUEPRINT:
139
- {blueprint}
140
-
141
- Generate the code or respond with DETECTED if clarification is needed."""
142
-
143
- def format_strategist_prompt(blueprint: str, intent: str, coder_questions: str) -> str:
144
- return f"""{HEADER_PROMPT}
145
-
146
- ORIGINAL BLUEPRINT:
147
- {blueprint}
148
-
149
- ORIGINAL INTENT:
150
- {intent}
151
-
152
- CODER AI'S QUESTIONS:
153
- {coder_questions}
154
-
155
- Provide clear, specific clarifications for each question."""
156
-
157
- def format_strategist_tool_synthesis_prompt(blueprint: str, intent: str, coder_questions: str, tool_results: str) -> str:
158
- return f"""{HEADER_PROMPT}
159
-
160
- ORIGINAL BLUEPRINT:
161
- {blueprint}
162
-
163
- ORIGINAL INTENT:
164
- {intent}
165
-
166
- CODER AI'S QUESTIONS:
167
- {coder_questions}
168
-
169
- TOOL EXECUTION RESULTS:
170
- {tool_results}
171
-
172
- Using the tool results above, provide the final, complete clarification for the Coder AI. This should be a synthesized, unambiguous set of instructions."""
173
-
174
- def format_resolution_prompt(blueprint: str, clarification: str) -> str:
175
- return f"""{SYSTEM_PROMPT}
176
-
177
- BLUEPRINT:
178
- {blueprint}
179
-
180
- CLARIFICATION PROVIDED:
181
- {clarification}
182
-
183
- Generate the complete code based on these clarified requirements."""
184
-
185
- # --- UTILITIES ---
186
-
187
- def detect_tool_usage(response: str) -> Optional[Dict[str, any]]:
188
- pattern = r"USE_TOOL:\s*(\w+)\((.*?)\)"
189
- match = re.search(pattern, response, re.DOTALL)
190
- if not match:
191
- return None
192
- tool_name = match.group(1)
193
- params_string = match.group(2)
194
- params = {}
195
- param_pattern = r"(\w+)=(['\"])(.*?)\2"
196
- for param_match in re.finditer(param_pattern, params_string):
197
- param_name = param_match.group(1)
198
- param_value = param_match.group(3)
199
- params[param_name] = param_value
200
- return {'tool_name': tool_name, 'params': params}
201
-
202
- def generate_transaction_id() -> str:
203
- timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
204
- random_suffix = uuid.uuid4().hex[:4].upper()
205
- return f"{timestamp}-{random_suffix}"
206
-
207
- def sanitize_error_message(error_msg: str) -> str:
208
- """
209
- Scrub API keys and sensitive URLs from error messages.
210
- Removes everything after '?' in URLs to prevent API key exposure.
211
- """
212
- import re
213
-
214
- # Pattern to match URLs with query parameters (containing API keys)
215
- # This will find "for url: https://...?key=..." and remove everything after the ?
216
- pattern = r'(for url: https?://[^\s?]+)\?[^\s]*'
217
-
218
- # Replace with just the base URL without query parameters
219
- sanitized = re.sub(pattern, r'\1', error_msg)
220
-
221
- return sanitized
222
-
223
- def execute_tool(tool_name: str, params: Dict[str, str]) -> Dict[str, any]:
224
- transaction_id = generate_transaction_id()
225
- timestamp = datetime.now().isoformat()
226
- if tool_name not in TOOL_REGISTRY:
227
- return {
228
- 'transaction_id': transaction_id,
229
- 'timestamp': timestamp,
230
- 'tool_name': tool_name,
231
- 'tool_type': 'UNKNOWN',
232
- 'endpoint': 'N/A',
233
- 'request_payload': params,
234
- 'response_payload': None,
235
- 'status': 'FAILURE',
236
- 'latency': 0.0,
237
- 'error_message': f"Tool '{tool_name}' not found. Available: {', '.join(TOOL_REGISTRY.keys())}",
238
- 'summary': f"❌ Tool '{tool_name}' not found"
239
- }
240
- tool_config = TOOL_REGISTRY[tool_name]
241
- missing_params = [p for p in tool_config['required_params'] if p not in params]
242
- if missing_params:
243
- return {
244
- 'transaction_id': transaction_id,
245
- 'timestamp': timestamp,
246
- 'tool_name': tool_name,
247
- 'tool_type': tool_config['type'],
248
- 'endpoint': tool_config.get('space_name') or tool_config.get('endpoint'),
249
- 'request_payload': params,
250
- 'response_payload': None,
251
- 'status': 'FAILURE',
252
- 'latency': 0.0,
253
- 'error_message': f"Missing required parameters: {', '.join(missing_params)}",
254
- 'summary': f"❌ Missing parameters: {', '.join(missing_params)}"
255
- }
256
- start_time = time.perf_counter()
257
- if tool_config['type'] == 'gradio_space':
258
- result = execute_gradio_space(tool_name, tool_config, params, transaction_id, timestamp)
259
- elif tool_config['type'] == 'http':
260
- result = execute_http_tool(tool_name, tool_config, params, transaction_id, timestamp)
261
- else:
262
- result = {
263
- 'transaction_id': transaction_id,
264
- 'timestamp': timestamp,
265
- 'tool_name': tool_name,
266
- 'tool_type': tool_config['type'],
267
- 'endpoint': 'N/A',
268
- 'request_payload': params,
269
- 'response_payload': None,
270
- 'status': 'FAILURE',
271
- 'latency': 0.0,
272
- 'error_message': f"Unknown tool type: {tool_config['type']}",
273
- 'summary': f"❌ Unknown tool type"
274
- }
275
- result['latency'] = round(time.perf_counter() - start_time, 2)
276
- return result
277
-
278
- def execute_gradio_space(tool_name: str, tool_config: Dict, params: Dict[str, str], transaction_id: str, timestamp: str) -> Dict[str, any]:
279
- try:
280
- from gradio_client import Client
281
- except ImportError:
282
- return {
283
- 'transaction_id': transaction_id,
284
- 'timestamp': timestamp,
285
- 'tool_name': tool_name,
286
- 'tool_type': 'gradio_space',
287
- 'endpoint': tool_config['space_name'],
288
- 'request_payload': params,
289
- 'response_payload': None,
290
- 'status': 'FAILURE',
291
- 'latency': 0.0,
292
- 'error_message': 'gradio_client not installed',
293
- 'summary': '❌ gradio_client not installed'
294
- }
295
- space_name = tool_config['space_name']
296
- if not space_name or 'PLACEHOLDER' in space_name:
297
- return {
298
- 'transaction_id': transaction_id,
299
- 'timestamp': timestamp,
300
- 'tool_name': tool_name,
301
- 'tool_type': 'gradio_space',
302
- 'endpoint': space_name,
303
- 'request_payload': params,
304
- 'response_payload': None,
305
- 'status': 'FAILURE',
306
- 'latency': 0.0,
307
- 'error_message': 'Tool space name not configured',
308
- 'summary': '❌ Space not configured'
309
- }
310
- try:
311
- hf_token = tool_config.get('hf_token', None)
312
- client = Client(space_name, hf_token=hf_token) if hf_token else Client(space_name)
313
- param_order = tool_config.get('param_order', tool_config['required_params'])
314
- param_values = [params.get(param, '') for param in param_order]
315
- api_name = tool_config.get('api_name', '/predict')
316
- result = client.predict(*param_values, api_name=api_name)
317
- summary = result.get('message', f"✅ Executed {tool_name}") if isinstance(result, dict) else f"✅ Executed {tool_name}"
318
- return {
319
- 'transaction_id': transaction_id,
320
- 'timestamp': timestamp,
321
- 'tool_name': tool_name,
322
- 'tool_type': 'gradio_space',
323
- 'endpoint': space_name,
324
- 'request_payload': params,
325
- 'response_payload': result,
326
- 'status': 'SUCCESS',
327
- 'latency': 0.0,
328
- 'error_message': None,
329
- 'summary': summary
330
- }
331
- except Exception as e:
332
- return {
333
- 'transaction_id': transaction_id,
334
- 'timestamp': timestamp,
335
- 'tool_name': tool_name,
336
- 'tool_type': 'gradio_space',
337
- 'endpoint': space_name,
338
- 'request_payload': params,
339
- 'response_payload': None,
340
- 'status': 'FAILURE',
341
- 'latency': 0.0,
342
- 'error_message': str(e),
343
- 'summary': f"❌ Execution failed: {str(e)[:50]}..."
344
- }
345
-
346
- def execute_http_tool(tool_name: str, tool_config: Dict, params: Dict[str, str], transaction_id: str, timestamp: str) -> Dict[str, any]:
347
- endpoint = tool_config['endpoint']
348
- if not endpoint or 'PLACEHOLDER' in endpoint:
349
- return {
350
- 'transaction_id': transaction_id,
351
- 'timestamp': timestamp,
352
- 'tool_name': tool_name,
353
- 'tool_type': 'http',
354
- 'endpoint': endpoint,
355
- 'request_payload': params,
356
- 'response_payload': None,
357
- 'status': 'FAILURE',
358
- 'latency': 0.0,
359
- 'error_message': 'Tool endpoint not configured',
360
- 'summary': '❌ Endpoint not configured'
361
- }
362
- param_order = tool_config.get('param_order', tool_config['required_params'])
363
- data_array = [params.get(param, '') for param in param_order]
364
- payload = {"data": data_array}
365
- headers = {'Content-Type': 'application/json'}
366
- api_key = tool_config.get('api_key', '')
367
- if api_key:
368
- headers['Authorization'] = f'Bearer {api_key}'
369
- try:
370
- response = requests.post(endpoint, headers=headers, json=payload, timeout=120)
371
- response.raise_for_status()
372
- data = response.json()
373
- result = data['data'][0] if 'data' in data and len(data['data']) > 0 else data
374
- summary = result.get('message', f"✅ Executed {tool_name}") if isinstance(result, dict) else f"✅ Executed {tool_name}"
375
- return {
376
- 'transaction_id': transaction_id,
377
- 'timestamp': timestamp,
378
- 'tool_name': tool_name,
379
- 'tool_type': 'http',
380
- 'endpoint': endpoint,
381
- 'request_payload': params,
382
- 'response_payload': result,
383
- 'status': 'SUCCESS',
384
- 'latency': 0.0,
385
- 'error_message': None,
386
- 'summary': summary
387
- }
388
- except Exception as e:
389
- return {
390
- 'transaction_id': transaction_id,
391
- 'timestamp': timestamp,
392
- 'tool_name': tool_name,
393
- 'tool_type': 'http',
394
- 'endpoint': endpoint,
395
- 'request_payload': params,
396
- 'response_payload': None,
397
- 'status': 'FAILURE',
398
- 'latency': 0.0,
399
- 'error_message': str(e),
400
- 'summary': f"❌ HTTP error: {str(e)[:50]}..."
401
- }
402
-
403
- def call_ai_api(full_url: str, api_key: str, messages: List[Dict[str, str]]) -> str:
404
- headers = {'Content-Type': 'application/json'}
405
- url_with_key = f"{full_url}?key={api_key}"
406
- payload = {
407
- 'contents': messages,
408
- 'generationConfig': {
409
- 'temperature': 0.7,
410
- 'maxOutputTokens': 4000
411
- }
412
- }
413
- try:
414
- response = requests.post(url_with_key, headers=headers, json=payload, timeout=120)
415
- response.raise_for_status()
416
- data = response.json()
417
- if 'candidates' in data and len(data['candidates']) > 0:
418
- return data['candidates'][0]['content']['parts'][0]['text']
419
- else:
420
- return f"ERROR: API malformed response: {data}"
421
- except Exception as e:
422
- return f"ERROR: API call failed: {str(e)}"
423
-
424
- def resolve_model(selected_label: str, model_registry: Dict[str, Dict], fallback_label: str, agent_name: str) -> Tuple[str, str, str]:
425
- if selected_label and selected_label in model_registry:
426
- model_config = model_registry[selected_label]
427
- return (
428
- model_config['model_id'],
429
- model_config['url'],
430
- f"{agent_name} model resolved: {selected_label} ({model_config['model_id']})"
431
- )
432
- if fallback_label and fallback_label in model_registry:
433
- model_config = model_registry[fallback_label]
434
- return (
435
- model_config['model_id'],
436
- model_config['url'],
437
- f"WARNING: {agent_name} selection '{selected_label}' invalid. Using default: {fallback_label} ({model_config['model_id']})"
438
- )
439
- if model_registry:
440
- first_label = next(iter(model_registry))
441
- model_config = model_registry[first_label]
442
- return (
443
- model_config['model_id'],
444
- model_config['url'],
445
- f"WARNING: {agent_name} default '{fallback_label}' invalid. Using first available: {first_label} ({model_config['model_id']})"
446
- )
447
- return ('', '', f"FATAL: No {agent_name} models configured.")
448
-
449
- def format_audit_entry(diagnostic: Dict[str, any]) -> str:
450
- entry = {
451
- "transaction_id": diagnostic['transaction_id'],
452
- "timestamp": diagnostic['timestamp'],
453
- "tool": diagnostic['tool_name'],
454
- "status": diagnostic['status'],
455
- "latency": diagnostic['latency'],
456
- "request": diagnostic['request_payload'],
457
- "response": diagnostic['response_payload'],
458
- "error": diagnostic['error_message']
459
- }
460
- return json.dumps(entry, indent=2)
461
-
462
- # --- ENGINE ---
463
-
464
- class ConductorEngine:
465
- def __init__(self, coder_model_label: str, strategist_model_label: str):
466
- self.coder_history: List[Dict[str, str]] = []
467
- self.strategist_history: List[Dict[str, str]] = []
468
- self.system_log: List[str] = []
469
- self.audit_log: List[Dict[str, Any]] = []
470
- self.loop_count: int = 0
471
- self.max_loops: int = 3
472
- self.coder_model_id, self.coder_url, coder_log = resolve_model(
473
- coder_model_label, CONFIG['coder_models'], CONFIG['coder_model_default_label'], 'Coder'
474
- )
475
- self.strategist_model_id, self.strategist_url, strategist_log = resolve_model(
476
- strategist_model_label, CONFIG['strategist_models'], CONFIG['strategist_model_default_label'], 'Strategist'
477
- )
478
- self.model_resolution_logs = [coder_log, strategist_log]
479
- self.fatal_init_error = not (self.coder_url and self.strategist_url)
480
-
481
- def log_system(self, message: str):
482
- self.system_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")
483
-
484
- def log_coder(self, role: str, content: str):
485
- gemini_role = 'model' if role == 'assistant' else 'user'
486
- self.coder_history.append({"role": gemini_role, "parts": [{"text": content}]})
487
-
488
- def log_strategist(self, role: str, content: str):
489
- gemini_role = 'model' if role == 'assistant' else 'user'
490
- self.strategist_history.append({"role": gemini_role, "parts": [{"text": content}]})
491
-
492
- def _current_state(self) -> Dict[str, Any]:
493
- """Package current state for transmission"""
494
- return {
495
- "system_log": self.system_log,
496
- "coder_log": self.coder_history,
497
- "strategist_log": self.strategist_history,
498
- "audit_log": self.audit_log,
499
- "final_output": ""
500
- }
501
-
502
- def execute_workflow(self, blueprint: str, intent: str) -> Dict[str, Any]:
503
- """ORIGINAL: Non-streaming version (kept for backwards compatibility)"""
504
- self.coder_history = []
505
- self.strategist_history = []
506
- self.system_log = []
507
- self.audit_log = []
508
- self.loop_count = 0
509
- final_code = ""
510
-
511
- self.log_system("INITIATING CONDUCTOR ENGINE...")
512
- for log_msg in self.model_resolution_logs:
513
- self.log_system(log_msg)
514
-
515
- if self.fatal_init_error:
516
- self.log_system("FATAL: Model configuration invalid.")
517
- return self._compile_results("CONFIGURATION FAILURE")
518
-
519
- self.log_system(f"Engaged: Coder ({self.coder_model_id}), Strategist ({self.strategist_model_id})")
520
-
521
- initial_prompt = format_initial_prompt(blueprint)
522
- self.log_coder("user", initial_prompt)
523
-
524
- while self.loop_count < self.max_loops:
525
- self.loop_count += 1
526
- self.log_system(f"Executing Cycle {self.loop_count}/{self.max_loops}")
527
-
528
- coder_response = call_ai_api(self.coder_url, CONFIG['CODER_API_KEY'], self.coder_history)
529
- self.log_coder("assistant", coder_response)
530
-
531
- if "DETECTED" not in coder_response:
532
- self.log_system("MISSION COMPLETE: Ambiguity resolved or Code generated.")
533
- final_code = coder_response
534
- return self._compile_results(final_code)
535
-
536
- self.log_system("Ambiguity DETECTED. Escalating to Strategist.")
537
- strategist_prompt = format_strategist_prompt(blueprint, intent, coder_response)
538
- self.log_strategist("user", strategist_prompt)
539
-
540
- strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
541
- self.log_strategist("assistant", strategist_response)
542
-
543
- tool_request = detect_tool_usage(strategist_response)
544
- if tool_request:
545
- self.log_system(f"TOOL REQUEST: {tool_request['tool_name']}")
546
- diagnostic = execute_tool(tool_request['tool_name'], tool_request['params'])
547
- self.audit_log.append(diagnostic)
548
- self.log_system(f"Tool Result: {diagnostic['status']}")
549
-
550
- tool_result_text = f"TOOL: {diagnostic['tool_name']}\nSTATUS: {diagnostic['status']}\nOUTPUT: {json.dumps(diagnostic['response_payload'])}"
551
- synthesis_prompt = format_strategist_tool_synthesis_prompt(blueprint, intent, coder_response, tool_result_text)
552
- self.log_strategist("user", synthesis_prompt)
553
-
554
- strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
555
- self.log_strategist("assistant", strategist_response)
556
-
557
- resolution_prompt = format_resolution_prompt(blueprint, strategist_response)
558
- self.log_coder("user", resolution_prompt)
559
-
560
- self.log_system("FATAL: Loop limit reached.")
561
- return self._compile_results(coder_response)
562
-
563
- def execute_workflow_streaming(self, blueprint: str, intent: str):
564
- """NEW: Streaming version that yields updates as they happen"""
565
- self.coder_history = []
566
- self.strategist_history = []
567
- self.system_log = []
568
- self.audit_log = []
569
- self.loop_count = 0
570
-
571
- self.log_system("INITIATING CONDUCTOR ENGINE...")
572
- yield self._current_state()
573
-
574
- for log_msg in self.model_resolution_logs:
575
- self.log_system(log_msg)
576
- yield self._current_state()
577
-
578
- if self.fatal_init_error:
579
- self.log_system("FATAL: Model configuration invalid.")
580
- yield self._current_state()
581
- return
582
-
583
- self.log_system(f"Engaged: Coder ({self.coder_model_id}), Strategist ({self.strategist_model_id})")
584
- yield self._current_state()
585
-
586
- initial_prompt = format_initial_prompt(blueprint)
587
- self.log_coder("user", initial_prompt)
588
- yield self._current_state()
589
-
590
- while self.loop_count < self.max_loops:
591
- self.loop_count += 1
592
- self.log_system(f"Executing Cycle {self.loop_count}/{self.max_loops}")
593
- yield self._current_state()
594
-
595
- coder_response = call_ai_api(self.coder_url, CONFIG['CODER_API_KEY'], self.coder_history)
596
- self.log_coder("assistant", coder_response)
597
- yield self._current_state()
598
-
599
- if "DETECTED" not in coder_response:
600
- self.log_system("MISSION COMPLETE: Ambiguity resolved or Code generated.")
601
- yield self._current_state()
602
- return
603
-
604
- self.log_system("Ambiguity DETECTED. Escalating to Strategist.")
605
- yield self._current_state()
606
-
607
- strategist_prompt = format_strategist_prompt(blueprint, intent, coder_response)
608
- self.log_strategist("user", strategist_prompt)
609
- yield self._current_state()
610
-
611
- strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
612
- self.log_strategist("assistant", strategist_response)
613
- yield self._current_state()
614
-
615
- tool_request = detect_tool_usage(strategist_response)
616
- if tool_request:
617
- self.log_system(f"TOOL REQUEST: {tool_request['tool_name']}")
618
- yield self._current_state()
619
-
620
- diagnostic = execute_tool(tool_request['tool_name'], tool_request['params'])
621
- self.audit_log.append(diagnostic)
622
- self.log_system(f"Tool Result: {diagnostic['status']}")
623
- yield self._current_state()
624
-
625
- tool_result_text = f"TOOL: {diagnostic['tool_name']}\nSTATUS: {diagnostic['status']}\nOUTPUT: {json.dumps(diagnostic['response_payload'])}"
626
- synthesis_prompt = format_strategist_tool_synthesis_prompt(blueprint, intent, coder_response, tool_result_text)
627
- self.log_strategist("user", synthesis_prompt)
628
- yield self._current_state()
629
-
630
- strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
631
- self.log_strategist("assistant", strategist_response)
632
- yield self._current_state()
633
-
634
- resolution_prompt = format_resolution_prompt(blueprint, strategist_response)
635
- self.log_coder("user", resolution_prompt)
636
- yield self._current_state()
637
-
638
- self.log_system("FATAL: Loop limit reached.")
639
- yield self._current_state()
640
-
641
- def _compile_results(self, final_output: str) -> Dict[str, Any]:
642
- return {
643
- "system_log": self.system_log,
644
- "coder_log": self.coder_history,
645
- "strategist_log": self.strategist_history,
646
- "audit_log": self.audit_log,
647
- "final_output": final_output
648
- }
649
-
650
- # --- API ---
651
-
652
- app = FastAPI(title="Conductor MCP Server", version="4.0")
653
-
654
- class ExecutionRequest(BaseModel):
655
- blueprint: str
656
- intent: str
657
- coder_model_label: Optional[str] = None
658
- strategist_model_label: Optional[str] = None
659
-
660
- class ExecutionResponse(BaseModel):
661
- system_log: List[str]
662
- coder_log: List[Dict[str, Any]]
663
- strategist_log: List[Dict[str, Any]]
664
- audit_log: List[Dict[str, Any]]
665
- final_output: str
666
-
667
- @app.post("/execute", response_model=ExecutionResponse)
668
- async def execute_conductor(req: ExecutionRequest):
669
- """ORIGINAL: Non-streaming endpoint (kept for backwards compatibility)"""
670
- engine = ConductorEngine(req.coder_model_label, req.strategist_model_label)
671
- result = engine.execute_workflow(req.blueprint, req.intent)
672
- return result
673
-
674
- @app.post("/execute_stream")
675
- async def execute_conductor_stream(req: ExecutionRequest):
676
- """NEW: Streaming endpoint that yields real-time updates"""
677
-
678
- async def generate_updates():
679
- engine = ConductorEngine(req.coder_model_label, req.strategist_model_label)
680
-
681
- for update in engine.execute_workflow_streaming(req.blueprint, req.intent):
682
- yield f"data: {json.dumps(update)}\n\n"
683
- await asyncio.sleep(0)
684
-
685
- yield "data: {\"status\": \"complete\"}\n\n"
686
-
687
- return StreamingResponse(generate_updates(), media_type="text/event-stream")
688
-
689
- if __name__ == "__main__":
690
- uvicorn.run(app, host="0.0.0.0", port=7860)