Delanoe Pirard commited on
Commit
69c2791
·
1 Parent(s): 6caec8d

Agent Improvment

Browse files
agents/advanced_validation_agent.py CHANGED
@@ -2,16 +2,12 @@ import os
2
  import logging
3
  import json
4
  from typing import List, Dict, Optional, Union
5
- from dotenv import load_dotenv
6
 
7
  from llama_index.core.agent.workflow import ReActAgent
8
  from llama_index.core.tools import FunctionTool
9
  from llama_index.llms.google_genai import GoogleGenAI
10
  # Assuming research_agent might be needed for handoff, but not directly imported
11
 
12
- # Load environment variables
13
- load_dotenv()
14
-
15
  # Setup logging
16
  logger = logging.getLogger(__name__)
17
 
 
2
  import logging
3
  import json
4
  from typing import List, Dict, Optional, Union
 
5
 
6
  from llama_index.core.agent.workflow import ReActAgent
7
  from llama_index.core.tools import FunctionTool
8
  from llama_index.llms.google_genai import GoogleGenAI
9
  # Assuming research_agent might be needed for handoff, but not directly imported
10
 
 
 
 
11
  # Setup logging
12
  logger = logging.getLogger(__name__)
13
 
agents/agent_types.py DELETED
@@ -1,32 +0,0 @@
1
- # agent_types.py
2
- from enum import Enum
3
- from datetime import datetime
4
- from typing import Any, Dict
5
- from pydantic import BaseModel
6
- import uuid
7
-
8
- class AgentRole(str, Enum):
9
- USER = "user"
10
- PLANNER = "planner"
11
- ROUTER = "router"
12
- # tu complèteras plus tard (research, reasoning, …)
13
-
14
- class AgentMessage(BaseModel):
15
- id: str
16
- role: AgentRole
17
- parent_id: str | None
18
- task: str # phrase courte qui décrit l’action
19
- payload: Dict[str, Any] # données brutes (texte, url, …)
20
- metadata: Dict[str, Any] = {}
21
- status: str = "created" # created / done / error …
22
- timestamp: str = datetime.utcnow().isoformat()
23
-
24
- def new_message(role: AgentRole, task: str, payload: Dict[str, Any] | str = "",
25
- parent_id: str | None = None) -> AgentMessage:
26
- return AgentMessage(
27
- id=str(uuid.uuid4()),
28
- role=role,
29
- parent_id=parent_id,
30
- task=task,
31
- payload=payload if isinstance(payload, dict) else {"text": payload},
32
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
agents/code_agent.py CHANGED
@@ -1,6 +1,5 @@
1
  import os
2
  import logging
3
- from dotenv import load_dotenv
4
 
5
  from llama_index.core.agent.workflow import CodeActAgent, ReActAgent
6
  from llama_index.core.tools import FunctionTool
@@ -8,9 +7,6 @@ from llama_index.llms.google_genai import GoogleGenAI
8
  from llama_index.llms.openai import OpenAI
9
  from llama_index.tools.code_interpreter import CodeInterpreterToolSpec
10
 
11
- # Load environment variables
12
- load_dotenv()
13
-
14
  # Setup logging
15
  logger = logging.getLogger(__name__)
16
 
@@ -47,12 +43,10 @@ def generate_python_code(prompt: str) -> str:
47
 
48
  # Configuration for code generation LLM
49
  gen_llm_model = os.getenv("CODE_GEN_LLM_MODEL", "o4-mini")
50
- gen_api_key_env = os.getenv("CODE_GEN_API_KEY_ENV", "ALPAFLOW_OPENAI_API_KEY")
51
- gen_api_key = os.getenv(gen_api_key_env)
52
 
53
  if not gen_api_key:
54
- logger.error(f"{gen_api_key_env} not found in environment variables for code generation LLM.")
55
- raise ValueError(f"{gen_api_key_env} must be set for code generation")
56
 
57
  # Load the prompt template
58
  default_gen_prompt_template = ("You are a helpful assistant that writes Python code. "
@@ -68,7 +62,10 @@ def generate_python_code(prompt: str) -> str:
68
  try:
69
  llm = OpenAI(
70
  model=gen_llm_model,
71
- api_key=gen_api_key
 
 
 
72
  )
73
  logger.info(f"Using code generation LLM: {gen_llm_model}")
74
  generated_code = llm.complete(input_prompt)
 
1
  import os
2
  import logging
 
3
 
4
  from llama_index.core.agent.workflow import CodeActAgent, ReActAgent
5
  from llama_index.core.tools import FunctionTool
 
7
  from llama_index.llms.openai import OpenAI
8
  from llama_index.tools.code_interpreter import CodeInterpreterToolSpec
9
 
 
 
 
10
  # Setup logging
11
  logger = logging.getLogger(__name__)
12
 
 
43
 
44
  # Configuration for code generation LLM
45
  gen_llm_model = os.getenv("CODE_GEN_LLM_MODEL", "o4-mini")
46
+ gen_api_key = os.getenv("OPENAI_API_KEY")
 
47
 
48
  if not gen_api_key:
49
+ raise ValueError("OPENAI_API_KEY environment variable is not set.")
 
50
 
51
  # Load the prompt template
52
  default_gen_prompt_template = ("You are a helpful assistant that writes Python code. "
 
62
  try:
63
  llm = OpenAI(
64
  model=gen_llm_model,
65
+ api_key=gen_api_key,
66
+ reasoning_effort="high",
67
+ temperature=0.25,
68
+ max_tokens=16384
69
  )
70
  logger.info(f"Using code generation LLM: {gen_llm_model}")
71
  generated_code = llm.complete(input_prompt)
agents/figure_interpretation_agent.py CHANGED
@@ -1,16 +1,11 @@
1
  import os
2
  import logging
3
- from typing import List, Dict, Optional, Union
4
- from dotenv import load_dotenv
5
 
6
  from llama_index.core.agent.workflow import ReActAgent
7
  from llama_index.core.schema import ImageDocument
8
  from llama_index.core.tools import FunctionTool
9
  from llama_index.llms.google_genai import GoogleGenAI
10
 
11
- # Load environment variables
12
- load_dotenv()
13
-
14
  # Setup logging
15
  logger = logging.getLogger(__name__)
16
 
 
1
  import os
2
  import logging
 
 
3
 
4
  from llama_index.core.agent.workflow import ReActAgent
5
  from llama_index.core.schema import ImageDocument
6
  from llama_index.core.tools import FunctionTool
7
  from llama_index.llms.google_genai import GoogleGenAI
8
 
 
 
 
9
  # Setup logging
10
  logger = logging.getLogger(__name__)
11
 
agents/image_analyzer_agent.py CHANGED
@@ -1,13 +1,9 @@
1
  import os
2
  import logging
3
- from dotenv import load_dotenv
4
 
5
  from llama_index.core.agent.workflow import FunctionAgent
6
  from llama_index.llms.google_genai import GoogleGenAI
7
 
8
- # Load environment variables
9
- load_dotenv()
10
-
11
  # Setup logging
12
  logger = logging.getLogger(__name__)
13
 
 
1
  import os
2
  import logging
 
3
 
4
  from llama_index.core.agent.workflow import FunctionAgent
5
  from llama_index.llms.google_genai import GoogleGenAI
6
 
 
 
 
7
  # Setup logging
8
  logger = logging.getLogger(__name__)
9
 
agents/long_context_management_agent.py CHANGED
@@ -2,7 +2,6 @@ import os
2
  import logging
3
  import json
4
  from typing import List, Dict, Optional, Union, Literal
5
- from dotenv import load_dotenv
6
 
7
  from llama_index.core.agent.workflow import ReActAgent
8
  from llama_index.core.tools import FunctionTool, QueryEngineTool
@@ -12,8 +11,6 @@ from llama_index.core.node_parser import SentenceSplitter
12
  from llama_index.core.query_engine import RetrieverQueryEngine
13
  from llama_index.core.retrievers import VectorIndexRetriever
14
 
15
- # Load environment variables
16
- load_dotenv()
17
 
18
  # Setup logging
19
  logger = logging.getLogger(__name__)
 
2
  import logging
3
  import json
4
  from typing import List, Dict, Optional, Union, Literal
 
5
 
6
  from llama_index.core.agent.workflow import ReActAgent
7
  from llama_index.core.tools import FunctionTool, QueryEngineTool
 
11
  from llama_index.core.query_engine import RetrieverQueryEngine
12
  from llama_index.core.retrievers import VectorIndexRetriever
13
 
 
 
14
 
15
  # Setup logging
16
  logger = logging.getLogger(__name__)
agents/math_agent.py CHANGED
@@ -1,14 +1,13 @@
1
  import os
2
  import logging
3
- from typing import List, Optional, Union, Dict
4
- from dotenv import load_dotenv
5
 
6
  import sympy as sp
7
  import numpy as np
8
  import scipy.linalg as la
9
  import scipy.special as special
10
  from llama_index.tools.code_interpreter import CodeInterpreterToolSpec
11
- from scipy.integrate import odeint, quad
12
  from scipy.stats import binom, norm, poisson
13
  import numpy.fft as fft
14
 
@@ -17,9 +16,6 @@ from llama_index.core.tools import FunctionTool
17
  from llama_index.llms.google_genai import GoogleGenAI
18
  from llama_index.tools.wolfram_alpha import WolframAlphaToolSpec
19
 
20
- # Load environment variables
21
- load_dotenv()
22
-
23
  # Setup logging
24
  logger = logging.getLogger(__name__)
25
 
 
1
  import os
2
  import logging
3
+ from typing import List, Dict
 
4
 
5
  import sympy as sp
6
  import numpy as np
7
  import scipy.linalg as la
8
  import scipy.special as special
9
  from llama_index.tools.code_interpreter import CodeInterpreterToolSpec
10
+ from scipy.integrate import quad
11
  from scipy.stats import binom, norm, poisson
12
  import numpy.fft as fft
13
 
 
16
  from llama_index.llms.google_genai import GoogleGenAI
17
  from llama_index.tools.wolfram_alpha import WolframAlphaToolSpec
18
 
 
 
 
19
  # Setup logging
20
  logger = logging.getLogger(__name__)
21
 
agents/planner_agent.py CHANGED
@@ -1,14 +1,11 @@
1
  import os
2
  import logging
3
  from typing import List, Dict
4
- from dotenv import load_dotenv
5
 
6
  from llama_index.core.agent.workflow import ReActAgent
7
  from llama_index.core.tools import FunctionTool
8
  from llama_index.llms.google_genai import GoogleGenAI
9
 
10
- # Load environment variables
11
- load_dotenv()
12
 
13
  # Setup logging
14
  logger = logging.getLogger(__name__)
 
1
  import os
2
  import logging
3
  from typing import List, Dict
 
4
 
5
  from llama_index.core.agent.workflow import ReActAgent
6
  from llama_index.core.tools import FunctionTool
7
  from llama_index.llms.google_genai import GoogleGenAI
8
 
 
 
9
 
10
  # Setup logging
11
  logger = logging.getLogger(__name__)
agents/reasoning_agent.py CHANGED
@@ -1,15 +1,11 @@
1
  import os
2
  import logging
3
- from dotenv import load_dotenv
4
 
5
  from llama_index.core.agent.workflow import ReActAgent
6
  from llama_index.core.tools import FunctionTool
7
  from llama_index.llms.google_genai import GoogleGenAI
8
  from llama_index.llms.openai import OpenAI
9
 
10
- # Load environment variables
11
- load_dotenv()
12
-
13
  # Setup logging
14
  logger = logging.getLogger(__name__)
15
 
@@ -45,7 +41,7 @@ def reasoning_tool_fn(context: str) -> str:
45
 
46
  # Configuration for the reasoning LLM (OpenAI in the original)
47
  reasoning_llm_model = os.getenv("REASONING_LLM_MODEL", "gpt-4o-mini") # Use gpt-4o-mini as default
48
- openai_api_key = os.getenv("ALPAFLOW_OPENAI_API_KEY") # Specific key from original code
49
 
50
  if not openai_api_key:
51
  logger.error("ALPAFLOW_OPENAI_API_KEY not found for reasoning tool LLM.")
 
1
  import os
2
  import logging
 
3
 
4
  from llama_index.core.agent.workflow import ReActAgent
5
  from llama_index.core.tools import FunctionTool
6
  from llama_index.llms.google_genai import GoogleGenAI
7
  from llama_index.llms.openai import OpenAI
8
 
 
 
 
9
  # Setup logging
10
  logger = logging.getLogger(__name__)
11
 
 
41
 
42
  # Configuration for the reasoning LLM (OpenAI in the original)
43
  reasoning_llm_model = os.getenv("REASONING_LLM_MODEL", "gpt-4o-mini") # Use gpt-4o-mini as default
44
+ openai_api_key = os.getenv("OPENAI_API_KEY")
45
 
46
  if not openai_api_key:
47
  logger.error("ALPAFLOW_OPENAI_API_KEY not found for reasoning tool LLM.")
agents/research_agent.py CHANGED
@@ -3,7 +3,6 @@ import time
3
  import logging
4
  import re # Import regex for video ID extraction
5
  from typing import List, Optional, Dict # Added Dict
6
- from dotenv import load_dotenv
7
 
8
  from llama_index.core.agent.workflow import ReActAgent
9
  from llama_index.core.tools import FunctionTool
@@ -27,8 +26,6 @@ except ImportError:
27
  logging.warning("Selenium or Helium not installed. Browser interaction tools will be unavailable.")
28
  SELENIUM_AVAILABLE = False
29
 
30
- # Load environment variables
31
- load_dotenv()
32
 
33
  # Setup logging
34
  logger = logging.getLogger(__name__)
 
3
  import logging
4
  import re # Import regex for video ID extraction
5
  from typing import List, Optional, Dict # Added Dict
 
6
 
7
  from llama_index.core.agent.workflow import ReActAgent
8
  from llama_index.core.tools import FunctionTool
 
26
  logging.warning("Selenium or Helium not installed. Browser interaction tools will be unavailable.")
27
  SELENIUM_AVAILABLE = False
28
 
 
 
29
 
30
  # Setup logging
31
  logger = logging.getLogger(__name__)
agents/role_agent.py CHANGED
@@ -1,6 +1,5 @@
1
  import os
2
  import logging
3
- from dotenv import load_dotenv
4
 
5
  import datasets
6
  from llama_index.core import Document, VectorStoreIndex
@@ -14,8 +13,6 @@ from llama_index.core.postprocessor import SentenceTransformerRerank
14
  from llama_index.llms.google_genai import GoogleGenAI
15
  from llama_index.retrievers.bm25 import BM25Retriever
16
 
17
- # Load environment variables
18
- load_dotenv()
19
 
20
  # Setup logging
21
  logger = logging.getLogger(__name__)
 
1
  import os
2
  import logging
 
3
 
4
  import datasets
5
  from llama_index.core import Document, VectorStoreIndex
 
13
  from llama_index.llms.google_genai import GoogleGenAI
14
  from llama_index.retrievers.bm25 import BM25Retriever
15
 
 
 
16
 
17
  # Setup logging
18
  logger = logging.getLogger(__name__)
agents/router.py DELETED
@@ -1,25 +0,0 @@
1
- # router.py
2
- from typing import List
3
- from agent_types import AgentMessage, AgentRole
4
- import logging
5
-
6
- logger = logging.getLogger(__name__)
7
-
8
- def route(messages: List[AgentMessage]) -> None:
9
- for msg in messages:
10
- if msg.role != AgentRole.PLANNER:
11
- continue # autre type de lettre → plus tard
12
- logger.info(f"Routing task: {msg.task}")
13
- # Appel de l’agent existant (il attend un string)
14
- # answer = research(msg.task)
15
- # Ici on pourrait créer une nouvelle AgentMessage 'answer', mais on garde ça pour S-2
16
-
17
-
18
- if __name__ == '__main__':
19
- from planner_agent import plan
20
-
21
- objective = "Comparer l’impact écologique des voitures électriques et thermiques."
22
- plan_msgs = plan(objective)
23
- assert isinstance(plan_msgs[0].task, str)
24
- route(plan_msgs)
25
- print("✅ Premier voyage des AgentMessages réussi !")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
agents/text_analyzer_agent.py CHANGED
@@ -3,7 +3,6 @@ import certifi
3
  import logging
4
  import subprocess # For calling ffmpeg if needed
5
  from typing import List, Dict, Optional
6
- from dotenv import load_dotenv
7
 
8
  from llama_index.core.agent.workflow import ReActAgent
9
  from llama_index.core.tools import FunctionTool
@@ -19,8 +18,6 @@ except ImportError:
19
  logging.warning("openai-whisper not installed. Audio transcription tool will be unavailable.")
20
  WHISPER_AVAILABLE = False
21
 
22
- # Load environment variables
23
- load_dotenv()
24
 
25
  # Setup logging
26
  logger = logging.getLogger(__name__)
 
3
  import logging
4
  import subprocess # For calling ffmpeg if needed
5
  from typing import List, Dict, Optional
 
6
 
7
  from llama_index.core.agent.workflow import ReActAgent
8
  from llama_index.core.tools import FunctionTool
 
18
  logging.warning("openai-whisper not installed. Audio transcription tool will be unavailable.")
19
  WHISPER_AVAILABLE = False
20
 
 
 
21
 
22
  # Setup logging
23
  logger = logging.getLogger(__name__)
agents/verifier_agent.py CHANGED
@@ -2,15 +2,11 @@ import os
2
  import logging
3
  import re
4
  from typing import List
5
- from dotenv import load_dotenv
6
 
7
  from llama_index.core.agent.workflow import FunctionAgent, ReActAgent
8
  from llama_index.core.tools import FunctionTool
9
  from llama_index.llms.google_genai import GoogleGenAI
10
 
11
- # Load environment variables
12
- load_dotenv()
13
-
14
  # Setup logging
15
  logger = logging.getLogger(__name__)
16
 
 
2
  import logging
3
  import re
4
  from typing import List
 
5
 
6
  from llama_index.core.agent.workflow import FunctionAgent, ReActAgent
7
  from llama_index.core.tools import FunctionTool
8
  from llama_index.llms.google_genai import GoogleGenAI
9
 
 
 
 
10
  # Setup logging
11
  logger = logging.getLogger(__name__)
12
 
agents/video_analyzer_agent.py CHANGED
@@ -9,7 +9,6 @@ from typing import Optional
9
 
10
  import cv2
11
  import yt_dlp
12
- from dotenv import load_dotenv
13
  from llama_index.core.agent.workflow import FunctionAgent
14
  from llama_index.core.base.llms.types import TextBlock, ImageBlock, ChatMessage
15
  from llama_index.core.tools import FunctionTool
@@ -20,7 +19,6 @@ from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, No
20
  # ---------------------------------------------------------------------------
21
  # Environment setup & logging
22
  # ---------------------------------------------------------------------------
23
- load_dotenv()
24
  logger = logging.getLogger(__name__)
25
 
26
 
 
9
 
10
  import cv2
11
  import yt_dlp
 
12
  from llama_index.core.agent.workflow import FunctionAgent
13
  from llama_index.core.base.llms.types import TextBlock, ImageBlock, ChatMessage
14
  from llama_index.core.tools import FunctionTool
 
19
  # ---------------------------------------------------------------------------
20
  # Environment setup & logging
21
  # ---------------------------------------------------------------------------
 
22
  logger = logging.getLogger(__name__)
23
 
24
 
app.py CHANGED
@@ -1,9 +1,6 @@
1
  import os
2
  import logging
3
  import mimetypes
4
- from cgitb import handler
5
-
6
- from dotenv import load_dotenv
7
 
8
  from typing import Any, List
9
 
@@ -58,9 +55,6 @@ except ImportError as e:
58
  # ... set all others to None ...
59
  raise RuntimeError(f"Failed to import agent modules: {e2}")
60
 
61
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
62
- load_dotenv() # Load environment variables from .env file
63
-
64
  # Setup logging
65
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
66
  logger = logging.getLogger(__name__)
 
1
  import os
2
  import logging
3
  import mimetypes
 
 
 
4
 
5
  from typing import Any, List
6
 
 
55
  # ... set all others to None ...
56
  raise RuntimeError(f"Failed to import agent modules: {e2}")
57
 
 
 
 
58
  # Setup logging
59
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
60
  logger = logging.getLogger(__name__)