added oauth
Browse files- .gitignore +4 -1
- LoggerSingleton.py +39 -0
- app.py +79 -1
- math_worker_agent.py +51 -0
- models.py +40 -0
- print_utils.py +41 -0
- workers/tavily_worker_agent.py +45 -0
.gitignore
CHANGED
|
@@ -1 +1,4 @@
|
|
| 1 |
-
.idea/
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.idea/
|
| 2 |
+
/logs/
|
| 3 |
+
__pycache__/
|
| 4 |
+
workers/__pycache__/
|
LoggerSingleton.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# chat_logger.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ChatLogger:
|
| 8 |
+
_instances = {}
|
| 9 |
+
|
| 10 |
+
@staticmethod
|
| 11 |
+
def get_logger(thread_id: str) -> logging.Logger:
|
| 12 |
+
"""Restituisce un logger singleton per il thread dato."""
|
| 13 |
+
if thread_id in ChatLogger._instances:
|
| 14 |
+
return ChatLogger._instances[thread_id]
|
| 15 |
+
|
| 16 |
+
# Crea directory dei log se non esiste
|
| 17 |
+
log_dir = "logs"
|
| 18 |
+
os.makedirs(log_dir, exist_ok=True)
|
| 19 |
+
|
| 20 |
+
# Configura logger
|
| 21 |
+
logger = logging.getLogger(f"chat_logger_{thread_id}")
|
| 22 |
+
logger.setLevel(logging.INFO)
|
| 23 |
+
logger.propagate = False # Evita log duplicati sulla root logger
|
| 24 |
+
|
| 25 |
+
if not logger.handlers:
|
| 26 |
+
formatter = logging.Formatter('%(asctime)s - %(message)s')
|
| 27 |
+
|
| 28 |
+
# Handler per file
|
| 29 |
+
file_handler = logging.FileHandler(os.path.join(log_dir, f"chat_{thread_id}.log"))
|
| 30 |
+
file_handler.setFormatter(formatter)
|
| 31 |
+
logger.addHandler(file_handler)
|
| 32 |
+
|
| 33 |
+
# Handler per console
|
| 34 |
+
console_handler = logging.StreamHandler()
|
| 35 |
+
console_handler.setFormatter(formatter)
|
| 36 |
+
logger.addHandler(console_handler)
|
| 37 |
+
|
| 38 |
+
ChatLogger._instances[thread_id] = logger
|
| 39 |
+
return logger
|
app.py
CHANGED
|
@@ -1,21 +1,99 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
|
|
|
|
|
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
print("BasicAgent initialized.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
fixed_answer = "This is a default answer."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
return fixed_answer
|
| 21 |
|
|
@@ -142,7 +220,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 142 |
|
| 143 |
# --- Build Gradio Interface using Blocks ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("# Agent Evaluation Runner
|
| 146 |
|
| 147 |
|
| 148 |
gr.LoginButton()
|
|
|
|
| 1 |
import os
|
| 2 |
+
from logging import Logger
|
| 3 |
+
from langgraph_supervisor import create_supervisor, supervisor
|
| 4 |
+
from langchain.chat_models import init_chat_model
|
| 5 |
import gradio as gr
|
| 6 |
import requests
|
| 7 |
import inspect
|
| 8 |
import pandas as pd
|
| 9 |
+
from LoggerSingleton import ChatLogger
|
| 10 |
+
from math_worker_agent import math_agent
|
| 11 |
+
from print_utils import pretty_print_messages
|
| 12 |
+
from workers.tavily_worker_agent import research_agent
|
| 13 |
|
| 14 |
# (Keep Constants as is)
|
| 15 |
# --- Constants ---
|
| 16 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 17 |
|
| 18 |
+
|
| 19 |
+
|
| 20 |
# --- Basic Agent Definition ---
|
| 21 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 22 |
+
# TODO:l'idea è creare n agenti o che interagiscono o coordinati da un supervisor. Si potrebbe avere ogni agente su un file separato, per pulizia. Incapsulare l'agente dentro una classe
|
| 23 |
+
#https://langchain-ai.github.io/langgraph/concepts/multi_agent/
|
| 24 |
+
#https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/
|
| 25 |
+
|
| 26 |
+
logger: Logger = ChatLogger.get_logger("0")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
class BasicAgent:
|
| 33 |
def __init__(self):
|
| 34 |
print("BasicAgent initialized.")
|
| 35 |
+
self.supervisor = create_supervisor(
|
| 36 |
+
model=init_chat_model("openai:gpt-4.1"),
|
| 37 |
+
agents=[research_agent, math_agent],
|
| 38 |
+
prompt=(
|
| 39 |
+
"You are a supervisor managing two agents:\n"
|
| 40 |
+
"- a research agent. Assign research-related tasks to this agent\n"
|
| 41 |
+
"- a math agent. Assign math-related tasks to this agent\n"
|
| 42 |
+
"Assign work to one agent at a time, do not call agents in parallel.\n"
|
| 43 |
+
"Do not do any work yourself."
|
| 44 |
+
),
|
| 45 |
+
add_handoff_back_messages=True,
|
| 46 |
+
output_mode="full_history",
|
| 47 |
+
).compile()
|
| 48 |
+
|
| 49 |
+
#from IPython.display import display, Image
|
| 50 |
+
|
| 51 |
+
#display(Image(self.supervisor.get_graph().draw_mermaid_png()))
|
| 52 |
+
|
| 53 |
+
def test_supervisor(self, user_input: str) -> str:
|
| 54 |
+
logger.info("test supervisor")
|
| 55 |
+
for chunk in supervisor.stream(
|
| 56 |
+
{
|
| 57 |
+
"messages": [
|
| 58 |
+
{
|
| 59 |
+
"role": "user",
|
| 60 |
+
"content": "find US and New York state GDP in 2024. what % of US GDP was New York state?",
|
| 61 |
+
}
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
):
|
| 65 |
+
pretty_print_messages(chunk, last_message=True)
|
| 66 |
+
|
| 67 |
+
final_message_history = chunk["supervisor"]["messages"]
|
| 68 |
+
|
| 69 |
+
def ask_supervisor(self, user_input: str) -> str:
|
| 70 |
+
final_message_history = None
|
| 71 |
+
|
| 72 |
+
# stream dell'elaborazione
|
| 73 |
+
for chunk in self.supervisor.stream(
|
| 74 |
+
{
|
| 75 |
+
"messages": [
|
| 76 |
+
{"role": "user", "content": user_input}
|
| 77 |
+
]
|
| 78 |
+
}
|
| 79 |
+
):
|
| 80 |
+
final_message_history = chunk["supervisor"]["messages"]
|
| 81 |
+
|
| 82 |
+
# estrai l'ultimo messaggio del supervisor
|
| 83 |
+
if final_message_history:
|
| 84 |
+
return final_message_history[-1]["content"]
|
| 85 |
+
else:
|
| 86 |
+
return ""
|
| 87 |
+
|
| 88 |
def __call__(self, question: str) -> str:
|
| 89 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 90 |
fixed_answer = "This is a default answer."
|
| 91 |
+
|
| 92 |
+
question = "find US and New York state GDP in 2024. what % of US GDP was New York state?"
|
| 93 |
+
|
| 94 |
+
#answer = self.test_supervisor(question)
|
| 95 |
+
answer = self.ask_supervisor(question)
|
| 96 |
+
|
| 97 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 98 |
return fixed_answer
|
| 99 |
|
|
|
|
| 220 |
|
| 221 |
# --- Build Gradio Interface using Blocks ---
|
| 222 |
with gr.Blocks() as demo:
|
| 223 |
+
gr.Markdown("# Agent Evaluation Runner")
|
| 224 |
|
| 225 |
|
| 226 |
gr.LoginButton()
|
math_worker_agent.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from langchain_nvidia_ai_endpoints import ChatNVIDIA
|
| 4 |
+
from langgraph.prebuilt import create_react_agent
|
| 5 |
+
import logging
|
| 6 |
+
from LoggerSingleton import ChatLogger
|
| 7 |
+
from models import RateLimitLLMHandler
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def add(a: float, b: float):
|
| 11 |
+
"""Add two numbers."""
|
| 12 |
+
return a + b
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def multiply(a: float, b: float):
|
| 16 |
+
"""Multiply two numbers."""
|
| 17 |
+
return a * b
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def divide(a: float, b: float):
|
| 21 |
+
"""Divide two numbers."""
|
| 22 |
+
return a / b
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger: logging.Logger = ChatLogger.get_logger("0")
|
| 26 |
+
|
| 27 |
+
handler = RateLimitLLMHandler(limit=40, chat_logger=logger)
|
| 28 |
+
nvidia_api_key = os.environ["NVIDIA_API_KEY"]
|
| 29 |
+
|
| 30 |
+
llm = ChatNVIDIA(
|
| 31 |
+
model="meta/llama-3.3-70b-instruct",
|
| 32 |
+
api_key=nvidia_api_key,
|
| 33 |
+
temperature=0.2,
|
| 34 |
+
top_p=0.7,
|
| 35 |
+
max_tokens=1024,
|
| 36 |
+
callbacks=[handler]
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
math_agent = create_react_agent(
|
| 41 |
+
model=llm,
|
| 42 |
+
tools=[add, multiply, divide],
|
| 43 |
+
prompt=(
|
| 44 |
+
"You are a math agent.\n\n"
|
| 45 |
+
"INSTRUCTIONS:\n"
|
| 46 |
+
"- Assist ONLY with math-related tasks\n"
|
| 47 |
+
"- After you're done with your tasks, respond to the supervisor directly\n"
|
| 48 |
+
"- Respond ONLY with the results of your work, do NOT include ANY other text."
|
| 49 |
+
),
|
| 50 |
+
name="math_agent",
|
| 51 |
+
)
|
models.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from langchain_core.callbacks import BaseCallbackHandler
|
| 4 |
+
from pydantic import BaseModel, Field
|
| 5 |
+
from collections import deque
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
class RateLimitLLMHandler(BaseCallbackHandler):
|
| 9 |
+
"""
|
| 10 |
+
Traccia le chiamate all'LLM e segnala se superano `limit` negli ultimi 60 s.
|
| 11 |
+
"""
|
| 12 |
+
def __init__(self, limit: int = 40, chat_logger: Optional["ChatLogger"] = None):
|
| 13 |
+
self.limit = limit # max richieste al minuto
|
| 14 |
+
self.events = deque() # timestamps delle chiamate
|
| 15 |
+
self.chat_logger = chat_logger
|
| 16 |
+
|
| 17 |
+
# ──────────────────── helper interno
|
| 18 |
+
def _prune_old(self, now: float):
|
| 19 |
+
"""Rimuove i timestamp più vecchi di 60 s."""
|
| 20 |
+
while self.events and now - self.events[0] > 60:
|
| 21 |
+
self.events.popleft()
|
| 22 |
+
|
| 23 |
+
# ──────────────────── hook di LangChain
|
| 24 |
+
def on_llm_start(self, serialized, prompts, **kwargs):
|
| 25 |
+
now = time.time()
|
| 26 |
+
self.events.append(now)
|
| 27 |
+
self._prune_old(now)
|
| 28 |
+
|
| 29 |
+
calls_last_minute = len(self.events)
|
| 30 |
+
self.chat_logger.info(f"Chiamate negli ultimi 60s: {calls_last_minute}")
|
| 31 |
+
|
| 32 |
+
# log dei prompt (opzionale)
|
| 33 |
+
for i, prompt in enumerate(prompts, 1):
|
| 34 |
+
self.chat_logger.info(f"Prompt #{i}:\n{prompt}\n")
|
| 35 |
+
|
| 36 |
+
# verifica superamento soglia
|
| 37 |
+
if calls_last_minute > self.limit:
|
| 38 |
+
self.chat_logger.info("Superato il limite di 40 richieste al minuto!")
|
| 39 |
+
# Se vuoi bloccare l’esecuzione:
|
| 40 |
+
# raise RuntimeError("Rate limit exceeded")
|
print_utils.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.messages import convert_to_messages
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def pretty_print_message(message, indent=False):
|
| 5 |
+
pretty_message = message.pretty_repr(html=True)
|
| 6 |
+
if not indent:
|
| 7 |
+
print(pretty_message)
|
| 8 |
+
return
|
| 9 |
+
|
| 10 |
+
indented = "\n".join("\t" + c for c in pretty_message.split("\n"))
|
| 11 |
+
print(indented)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def pretty_print_messages(update, last_message=False):
|
| 15 |
+
is_subgraph = False
|
| 16 |
+
if isinstance(update, tuple):
|
| 17 |
+
ns, update = update
|
| 18 |
+
# skip parent graph updates in the printouts
|
| 19 |
+
if len(ns) == 0:
|
| 20 |
+
return
|
| 21 |
+
|
| 22 |
+
graph_id = ns[-1].split(":")[0]
|
| 23 |
+
print(f"Update from subgraph {graph_id}:")
|
| 24 |
+
print("\n")
|
| 25 |
+
is_subgraph = True
|
| 26 |
+
|
| 27 |
+
for node_name, node_update in update.items():
|
| 28 |
+
update_label = f"Update from node {node_name}:"
|
| 29 |
+
if is_subgraph:
|
| 30 |
+
update_label = "\t" + update_label
|
| 31 |
+
|
| 32 |
+
print(update_label)
|
| 33 |
+
print("\n")
|
| 34 |
+
|
| 35 |
+
messages = convert_to_messages(node_update["messages"])
|
| 36 |
+
if last_message:
|
| 37 |
+
messages = messages[-1:]
|
| 38 |
+
|
| 39 |
+
for m in messages:
|
| 40 |
+
pretty_print_message(m, indent=is_subgraph)
|
| 41 |
+
print("\n")
|
workers/tavily_worker_agent.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tavily_worker_agent.py
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
from langchain_tavily import TavilySearch
|
| 9 |
+
from langgraph.prebuilt import create_react_agent
|
| 10 |
+
from langchain_nvidia_ai_endpoints import ChatNVIDIA
|
| 11 |
+
from LoggerSingleton import ChatLogger
|
| 12 |
+
from models import RateLimitLLMHandler
|
| 13 |
+
|
| 14 |
+
# Configurazione logging
|
| 15 |
+
logger: logging.Logger = ChatLogger.get_logger("0")
|
| 16 |
+
nvidia_api_key = os.environ["NVIDIA_API_KEY"]
|
| 17 |
+
tavily_api_key = os.environ["TAVILY_API_KEY"]
|
| 18 |
+
|
| 19 |
+
web_search = TavilySearch(tavily_api_key=tavily_api_key,max_results=3)
|
| 20 |
+
|
| 21 |
+
handler = RateLimitLLMHandler(limit=40, chat_logger=logger)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
llm = ChatNVIDIA(
|
| 25 |
+
model="meta/llama-3.3-70b-instruct",
|
| 26 |
+
api_key=nvidia_api_key,
|
| 27 |
+
temperature=0.2,
|
| 28 |
+
top_p=0.7,
|
| 29 |
+
max_tokens=1024,
|
| 30 |
+
callbacks=[handler]
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
research_agent = create_react_agent(
|
| 35 |
+
model=llm,
|
| 36 |
+
tools=[web_search],
|
| 37 |
+
prompt=(
|
| 38 |
+
"You are a research agent.\n\n"
|
| 39 |
+
"INSTRUCTIONS:\n"
|
| 40 |
+
"- Assist ONLY with research-related tasks, DO NOT do any math\n"
|
| 41 |
+
"- After you're done with your tasks, respond to the supervisor directly\n"
|
| 42 |
+
"- Respond ONLY with the results of your work, do NOT include ANY other text."
|
| 43 |
+
),
|
| 44 |
+
name="research_agent",
|
| 45 |
+
)
|