Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
-
# app.py — ADN NEXUS V10.3.2 (
|
| 2 |
-
# Version stable, construite sur la base minimaliste validée
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import os
|
|
@@ -13,6 +12,7 @@ import sqlite3
|
|
| 13 |
import tempfile
|
| 14 |
import subprocess
|
| 15 |
import sys
|
|
|
|
| 16 |
from pathlib import Path
|
| 17 |
from typing import Dict, Any, Optional, List
|
| 18 |
from datetime import datetime
|
|
@@ -20,14 +20,9 @@ from contextlib import asynccontextmanager
|
|
| 20 |
import logging
|
| 21 |
from dataclasses import dataclass, field
|
| 22 |
|
| 23 |
-
import requests
|
| 24 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends, Header
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 27 |
-
import numpy as np
|
| 28 |
-
from sentence_transformers import SentenceTransformer
|
| 29 |
-
from bs4 import BeautifulSoup
|
| 30 |
-
|
| 31 |
import torch
|
| 32 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 33 |
|
|
@@ -74,6 +69,8 @@ class Config:
|
|
| 74 |
TOOL_RESULT_KEEP_CHARS = int(os.getenv("TOOL_RESULT_KEEP_CHARS", 300))
|
| 75 |
MEMORY_ENABLED = os.getenv("MEMORY_ENABLED", "true").lower() == "true"
|
| 76 |
MEMORY_MAX_RESULTS = int(os.getenv("MEMORY_MAX_RESULTS", 10))
|
|
|
|
|
|
|
| 77 |
|
| 78 |
def _valid_tokens() -> tuple:
|
| 79 |
toks = [Config.API_TOKEN]
|
|
@@ -262,7 +259,22 @@ TOOLS = [
|
|
| 262 |
{"name": "run_python", "description": "Execute Python code", "parameters": {"code": {"type": "string"}}}
|
| 263 |
]
|
| 264 |
|
| 265 |
-
# ===================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
class AgentV103:
|
| 267 |
MAX_NUDGES_PER_TASK = 3
|
| 268 |
_CONFUSION_MARKERS = (
|
|
@@ -316,6 +328,45 @@ Your response (JSON only):
|
|
| 316 |
REMEMBER: You are an expert agent. You have the tools. Use them.
|
| 317 |
"""
|
| 318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
async def run_task(self, session_id, task, websocket):
|
| 320 |
# Chargement du contexte mémoire
|
| 321 |
memory_context = await self._load_context_from_memory(task) if Config.MEMORY_ENABLED else ""
|
|
@@ -327,32 +378,21 @@ REMEMBER: You are an expert agent. You have the tools. Use them.
|
|
| 327 |
{"role": "user", "content": enriched_task}]
|
| 328 |
result = await self._continue_task(messages, websocket, start_iteration=0)
|
| 329 |
|
|
|
|
| 330 |
if Config.MEMORY_ENABLED:
|
| 331 |
await self._save_task_memory(task, result)
|
| 332 |
return result
|
| 333 |
|
| 334 |
-
def _looks_like_confusion(self, text: str) -> bool:
|
| 335 |
-
lowered = text.lower()
|
| 336 |
-
return any(marker in lowered for marker in self._CONFUSION_MARKERS)
|
| 337 |
-
|
| 338 |
-
def _score_candidate(self, tool_call: Optional[dict], result: Optional[dict], text: str) -> float:
|
| 339 |
-
score = 0.0
|
| 340 |
-
if tool_call:
|
| 341 |
-
score += 0.4
|
| 342 |
-
if result and result.get("success"):
|
| 343 |
-
score += 0.4
|
| 344 |
-
if result and not result.get("stderr"):
|
| 345 |
-
score += 0.1
|
| 346 |
-
elif not self._looks_like_confusion(text) and len(text.strip()) > 0:
|
| 347 |
-
score += 0.3
|
| 348 |
-
if self._looks_like_confusion(text):
|
| 349 |
-
score -= 0.3
|
| 350 |
-
return score
|
| 351 |
-
|
| 352 |
async def run_task_with_reasoning(self, session_id, task, websocket, max_candidates: Optional[int] = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
n = max_candidates or Config.SAMPLING_CANDIDATES
|
| 354 |
base_messages = [{"role": "system", "content": self.system_prompt},
|
| 355 |
-
{"role": "user", "content":
|
| 356 |
candidates = []
|
| 357 |
for i in range(n):
|
| 358 |
response = await self.inference.generate(
|
|
@@ -386,10 +426,39 @@ REMEMBER: You are an expert agent. You have the tools. Use them.
|
|
| 386 |
else:
|
| 387 |
messages.append({"role": "assistant", "content": best["response"]})
|
| 388 |
if not self._looks_like_confusion(best["response"] or ""):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
await websocket.send_json({"type": "complete", "result": best["response"]})
|
| 390 |
-
return
|
| 391 |
|
| 392 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
|
| 394 |
def _estimate_tokens(self, messages: list) -> int:
|
| 395 |
tok = getattr(self.inference, "tokenizer", None)
|
|
@@ -474,18 +543,25 @@ REMEMBER: You are an expert agent. You have the tools. Use them.
|
|
| 474 |
await websocket.send_json({"type": "error", "message": "Max iterations reached"})
|
| 475 |
return {"success": False, "error": "Max iterations"}
|
| 476 |
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
if isinstance(obj, dict) and "tool" in obj:
|
| 484 |
return obj
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
return None
|
| 488 |
|
|
|
|
| 489 |
async def _exec_tool(self, name, args):
|
| 490 |
if name == "read_file":
|
| 491 |
result = file_mgr.read(args.get("path", ""))
|
|
@@ -499,44 +575,6 @@ REMEMBER: You are an expert agent. You have the tools. Use them.
|
|
| 499 |
result = {"success": False, "error": f"Tool {name} unknown"}
|
| 500 |
return result
|
| 501 |
|
| 502 |
-
# === MÉMOIRE PERSISTANTE ===
|
| 503 |
-
async def _save_task_memory(self, task: str, result: Dict):
|
| 504 |
-
if not Config.MEMORY_ENABLED:
|
| 505 |
-
return
|
| 506 |
-
try:
|
| 507 |
-
success = 1 if result.get("success", False) else 0
|
| 508 |
-
await db_pool.execute(
|
| 509 |
-
"INSERT INTO agent_memory (task, result, success, created_at) VALUES (?, ?, ?, ?)",
|
| 510 |
-
(task[:500], json.dumps(result)[:1000], success, datetime.utcnow().isoformat())
|
| 511 |
-
)
|
| 512 |
-
except Exception as e:
|
| 513 |
-
logger.warning(f"Erreur sauvegarde mémoire: {e}")
|
| 514 |
-
|
| 515 |
-
async def _load_context_from_memory(self, task: str) -> str:
|
| 516 |
-
if not Config.MEMORY_ENABLED:
|
| 517 |
-
return ""
|
| 518 |
-
try:
|
| 519 |
-
rows = await db_pool.query(
|
| 520 |
-
"SELECT task, result, success, created_at FROM agent_memory ORDER BY created_at DESC LIMIT ?",
|
| 521 |
-
(Config.MEMORY_MAX_RESULTS,)
|
| 522 |
-
)
|
| 523 |
-
if not rows:
|
| 524 |
-
return ""
|
| 525 |
-
task_words = set(task.lower().split())
|
| 526 |
-
context = []
|
| 527 |
-
for row in rows:
|
| 528 |
-
row_words = set(row["task"].lower().split())
|
| 529 |
-
similarity = len(task_words & row_words) / max(len(task_words), 1)
|
| 530 |
-
if similarity > 0.1:
|
| 531 |
-
status = "réussi" if row["success"] else "échoué"
|
| 532 |
-
context.append(f"- Tâche similaire: {row['task'][:60]}... ({status})")
|
| 533 |
-
if context:
|
| 534 |
-
return "\n[Contexte historique (tâches similaires)]\n" + "\n".join(context[:3])
|
| 535 |
-
return ""
|
| 536 |
-
except Exception as e:
|
| 537 |
-
logger.warning(f"Erreur chargement mémoire: {e}")
|
| 538 |
-
return ""
|
| 539 |
-
|
| 540 |
# =================== FILE MANAGER ===================
|
| 541 |
class FileManager:
|
| 542 |
ROOT = Config.WORKSPACE_ROOT
|
|
|
|
| 1 |
+
# app.py — ADN NEXUS V10.3.2 (corrigé : parse_tool_call robuste, mémoire + raisonnement, similarité améliorée)
|
|
|
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import os
|
|
|
|
| 12 |
import tempfile
|
| 13 |
import subprocess
|
| 14 |
import sys
|
| 15 |
+
import unicodedata
|
| 16 |
from pathlib import Path
|
| 17 |
from typing import Dict, Any, Optional, List
|
| 18 |
from datetime import datetime
|
|
|
|
| 20 |
import logging
|
| 21 |
from dataclasses import dataclass, field
|
| 22 |
|
|
|
|
| 23 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends, Header
|
| 24 |
from fastapi.middleware.cors import CORSMiddleware
|
| 25 |
from fastapi.responses import HTMLResponse, JSONResponse
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
import torch
|
| 27 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 28 |
|
|
|
|
| 69 |
TOOL_RESULT_KEEP_CHARS = int(os.getenv("TOOL_RESULT_KEEP_CHARS", 300))
|
| 70 |
MEMORY_ENABLED = os.getenv("MEMORY_ENABLED", "true").lower() == "true"
|
| 71 |
MEMORY_MAX_RESULTS = int(os.getenv("MEMORY_MAX_RESULTS", 10))
|
| 72 |
+
# Seuil de similarité pour la récupération mémoire (Jaccard normalisé)
|
| 73 |
+
MEMORY_SIMILARITY_THRESHOLD = float(os.getenv("MEMORY_SIMILARITY_THRESHOLD", 0.15))
|
| 74 |
|
| 75 |
def _valid_tokens() -> tuple:
|
| 76 |
toks = [Config.API_TOKEN]
|
|
|
|
| 259 |
{"name": "run_python", "description": "Execute Python code", "parameters": {"code": {"type": "string"}}}
|
| 260 |
]
|
| 261 |
|
| 262 |
+
# =================== UTILITAIRES MÉMOIRE ===================
|
| 263 |
+
def normalize_text(text: str) -> str:
|
| 264 |
+
"""Normalise le texte : minuscule, suppression des accents, split sur non-alphanum."""
|
| 265 |
+
text = text.lower()
|
| 266 |
+
text = ''.join(c for c in unicodedata.normalize('NFKD', text) if not unicodedata.combining(c))
|
| 267 |
+
tokens = re.findall(r'\w+', text)
|
| 268 |
+
return set(tokens)
|
| 269 |
+
|
| 270 |
+
def jaccard_similarity(set1: set, set2: set) -> float:
|
| 271 |
+
if not set1 or not set2:
|
| 272 |
+
return 0.0
|
| 273 |
+
inter = len(set1 & set2)
|
| 274 |
+
union = len(set1 | set2)
|
| 275 |
+
return inter / union if union > 0 else 0.0
|
| 276 |
+
|
| 277 |
+
# =================== AGENT (AVEC MÉMOIRE PERSISTANTE ET RAISONNEMENT) ===================
|
| 278 |
class AgentV103:
|
| 279 |
MAX_NUDGES_PER_TASK = 3
|
| 280 |
_CONFUSION_MARKERS = (
|
|
|
|
| 328 |
REMEMBER: You are an expert agent. You have the tools. Use them.
|
| 329 |
"""
|
| 330 |
|
| 331 |
+
# ----- MÉMOIRE PERSISTANTE (partagée par run_task et run_task_with_reasoning) -----
|
| 332 |
+
async def _save_task_memory(self, task: str, result: Dict):
|
| 333 |
+
if not Config.MEMORY_ENABLED:
|
| 334 |
+
return
|
| 335 |
+
try:
|
| 336 |
+
success = 1 if result.get("success", False) else 0
|
| 337 |
+
await db_pool.execute(
|
| 338 |
+
"INSERT INTO agent_memory (task, result, success, created_at) VALUES (?, ?, ?, ?)",
|
| 339 |
+
(task[:500], json.dumps(result)[:1000], success, datetime.utcnow().isoformat())
|
| 340 |
+
)
|
| 341 |
+
except Exception as e:
|
| 342 |
+
logger.warning(f"Erreur sauvegarde mémoire: {e}")
|
| 343 |
+
|
| 344 |
+
async def _load_context_from_memory(self, task: str) -> str:
|
| 345 |
+
if not Config.MEMORY_ENABLED:
|
| 346 |
+
return ""
|
| 347 |
+
try:
|
| 348 |
+
rows = await db_pool.query(
|
| 349 |
+
"SELECT task, result, success, created_at FROM agent_memory ORDER BY created_at DESC LIMIT ?",
|
| 350 |
+
(Config.MEMORY_MAX_RESULTS,)
|
| 351 |
+
)
|
| 352 |
+
if not rows:
|
| 353 |
+
return ""
|
| 354 |
+
task_tokens = normalize_text(task)
|
| 355 |
+
context = []
|
| 356 |
+
for row in rows:
|
| 357 |
+
row_tokens = normalize_text(row["task"])
|
| 358 |
+
sim = jaccard_similarity(task_tokens, row_tokens)
|
| 359 |
+
if sim >= Config.MEMORY_SIMILARITY_THRESHOLD:
|
| 360 |
+
status = "réussi" if row["success"] else "échoué"
|
| 361 |
+
context.append(f"- Tâche similaire: {row['task'][:60]}... (similarité {sim:.2f}, {status})")
|
| 362 |
+
if context:
|
| 363 |
+
return "\n[Contexte historique (tâches similaires)]\n" + "\n".join(context[:3])
|
| 364 |
+
return ""
|
| 365 |
+
except Exception as e:
|
| 366 |
+
logger.warning(f"Erreur chargement mémoire: {e}")
|
| 367 |
+
return ""
|
| 368 |
+
|
| 369 |
+
# ----- TÂCHES PRINCIPALES -----
|
| 370 |
async def run_task(self, session_id, task, websocket):
|
| 371 |
# Chargement du contexte mémoire
|
| 372 |
memory_context = await self._load_context_from_memory(task) if Config.MEMORY_ENABLED else ""
|
|
|
|
| 378 |
{"role": "user", "content": enriched_task}]
|
| 379 |
result = await self._continue_task(messages, websocket, start_iteration=0)
|
| 380 |
|
| 381 |
+
# Sauvegarde mémoire
|
| 382 |
if Config.MEMORY_ENABLED:
|
| 383 |
await self._save_task_memory(task, result)
|
| 384 |
return result
|
| 385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
async def run_task_with_reasoning(self, session_id, task, websocket, max_candidates: Optional[int] = None):
|
| 387 |
+
# === AJOUT : chargement mémoire ===
|
| 388 |
+
memory_context = await self._load_context_from_memory(task) if Config.MEMORY_ENABLED else ""
|
| 389 |
+
enriched_task = task
|
| 390 |
+
if memory_context:
|
| 391 |
+
enriched_task = task + "\n\n" + memory_context
|
| 392 |
+
|
| 393 |
n = max_candidates or Config.SAMPLING_CANDIDATES
|
| 394 |
base_messages = [{"role": "system", "content": self.system_prompt},
|
| 395 |
+
{"role": "user", "content": enriched_task}]
|
| 396 |
candidates = []
|
| 397 |
for i in range(n):
|
| 398 |
response = await self.inference.generate(
|
|
|
|
| 426 |
else:
|
| 427 |
messages.append({"role": "assistant", "content": best["response"]})
|
| 428 |
if not self._looks_like_confusion(best["response"] or ""):
|
| 429 |
+
final_result = {"success": True, "result": best["response"], "best_score": best["score"]}
|
| 430 |
+
# === AJOUT : sauvegarde mémoire ===
|
| 431 |
+
if Config.MEMORY_ENABLED:
|
| 432 |
+
await self._save_task_memory(task, final_result)
|
| 433 |
await websocket.send_json({"type": "complete", "result": best["response"]})
|
| 434 |
+
return final_result
|
| 435 |
|
| 436 |
+
# Poursuite avec _continue_task (qui inclut déjà la sauvegarde mémoire via son appel final)
|
| 437 |
+
# Mais attention, _continue_task ne sauvegarde pas la mémoire ; c'est run_task qui le fait.
|
| 438 |
+
# On va donc appeler _continue_task et ensuite sauvegarder nous-mêmes.
|
| 439 |
+
result = await self._continue_task(messages, websocket, start_iteration=1)
|
| 440 |
+
if Config.MEMORY_ENABLED:
|
| 441 |
+
await self._save_task_memory(task, result)
|
| 442 |
+
return result
|
| 443 |
+
|
| 444 |
+
# ----- FONCTIONS INTERNES (inchangées sauf _parse_tool_call corrigé) -----
|
| 445 |
+
def _looks_like_confusion(self, text: str) -> bool:
|
| 446 |
+
lowered = text.lower()
|
| 447 |
+
return any(marker in lowered for marker in self._CONFUSION_MARKERS)
|
| 448 |
+
|
| 449 |
+
def _score_candidate(self, tool_call: Optional[dict], result: Optional[dict], text: str) -> float:
|
| 450 |
+
score = 0.0
|
| 451 |
+
if tool_call:
|
| 452 |
+
score += 0.4
|
| 453 |
+
if result and result.get("success"):
|
| 454 |
+
score += 0.4
|
| 455 |
+
if result and not result.get("stderr"):
|
| 456 |
+
score += 0.1
|
| 457 |
+
elif not self._looks_like_confusion(text) and len(text.strip()) > 0:
|
| 458 |
+
score += 0.3
|
| 459 |
+
if self._looks_like_confusion(text):
|
| 460 |
+
score -= 0.3
|
| 461 |
+
return score
|
| 462 |
|
| 463 |
def _estimate_tokens(self, messages: list) -> int:
|
| 464 |
tok = getattr(self.inference, "tokenizer", None)
|
|
|
|
| 543 |
await websocket.send_json({"type": "error", "message": "Max iterations reached"})
|
| 544 |
return {"success": False, "error": "Max iterations"}
|
| 545 |
|
| 546 |
+
# ==================== PARSEUR CORRIGÉ (boucle sur toutes les positions) ====================
|
| 547 |
+
def _parse_tool_call(self, text: str) -> Optional[Dict]:
|
| 548 |
+
decoder = json.JSONDecoder()
|
| 549 |
+
start = 0
|
| 550 |
+
while True:
|
| 551 |
+
idx = text.find("{", start)
|
| 552 |
+
if idx == -1:
|
| 553 |
+
break
|
| 554 |
+
try:
|
| 555 |
+
obj, end = decoder.raw_decode(text, idx)
|
| 556 |
+
except json.JSONDecodeError:
|
| 557 |
+
start = idx + 1
|
| 558 |
+
continue
|
| 559 |
if isinstance(obj, dict) and "tool" in obj:
|
| 560 |
return obj
|
| 561 |
+
start = end
|
| 562 |
+
return None
|
|
|
|
| 563 |
|
| 564 |
+
# ==================== EXÉCUTION DES OUTILS ====================
|
| 565 |
async def _exec_tool(self, name, args):
|
| 566 |
if name == "read_file":
|
| 567 |
result = file_mgr.read(args.get("path", ""))
|
|
|
|
| 575 |
result = {"success": False, "error": f"Tool {name} unknown"}
|
| 576 |
return result
|
| 577 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
# =================== FILE MANAGER ===================
|
| 579 |
class FileManager:
|
| 580 |
ROOT = Config.WORKSPACE_ROOT
|