Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -39,7 +39,7 @@ try: import whisper; WHISPER_AVAILABLE = True
|
|
| 39 |
except ImportError: WHISPER_AVAILABLE = False; print("WARNING: OpenAI Whisper not found, Audio Transcription tool will be disabled.")
|
| 40 |
|
| 41 |
# Google GenAI SDK types
|
| 42 |
-
from google.genai.types import HarmCategory, HarmBlockThreshold
|
| 43 |
from google.ai import generativelanguage as glm # For FileState enum
|
| 44 |
|
| 45 |
# LangChain
|
|
@@ -61,14 +61,14 @@ if TYPE_CHECKING:
|
|
| 61 |
LANGGRAPH_FLAVOR_AVAILABLE = False
|
| 62 |
LG_StateGraph: Optional[Type[Any]] = None
|
| 63 |
LG_ToolExecutor_Class: Optional[Type[Any]] = None
|
| 64 |
-
LG_END: Optional[Any]
|
| 65 |
LG_ToolInvocation: Optional[Type[Any]] = None
|
| 66 |
add_messages: Optional[Any] = None
|
| 67 |
MemorySaver_Class: Optional[Type[Any]] = None
|
| 68 |
|
| 69 |
AGENT_INSTANCE: Optional[Union[AgentExecutor, Any]] = None
|
| 70 |
TOOLS: List[BaseTool] = []
|
| 71 |
-
LLM_INSTANCE: Optional[ChatGoogleGenerativeAI]
|
| 72 |
LANGGRAPH_MEMORY_SAVER: Optional[Any] = None
|
| 73 |
|
| 74 |
# google-genai Client SDK
|
|
@@ -255,7 +255,6 @@ def _download_file(file_identifier: str, task_id_for_file: Optional[str] = None)
|
|
| 255 |
name_without_ext, current_ext = os.path.splitext(effective_save_path)
|
| 256 |
if not current_ext:
|
| 257 |
content_type_header = r.headers.get('content-type', '')
|
| 258 |
-
# FIX: Handle split correctly and take first part before stripping
|
| 259 |
content_type_val = content_type_header.split(';')[0].strip() if content_type_header else ''
|
| 260 |
if content_type_val:
|
| 261 |
guessed_ext = mimetypes.guess_extension(content_type_val)
|
|
@@ -366,9 +365,7 @@ TOOL USAGE:
|
|
| 366 |
- 'python_repl': `args` is like '{{"query": "python code string"}}'. Use print() for output.
|
| 367 |
RESPONSE FORMAT:
|
| 368 |
Final AIMessage should contain ONLY the answer in 'content' and NO 'tool_calls'. If using tools, 'content' can be thought process, with 'tool_calls'.
|
| 369 |
-
Begin!
|
| 370 |
-
Current Task Details (including Task ID and any associated files):
|
| 371 |
-
{input}"""
|
| 372 |
|
| 373 |
REACT_PROMPT_TEMPLATE_STR = """You are a highly intelligent agent for the GAIA benchmark.
|
| 374 |
Goal: EXACT MATCH answer. No extra text/markdown.
|
|
@@ -396,7 +393,6 @@ def initialize_agent_and_tools(force_reinit=False):
|
|
| 396 |
model=GEMINI_MODEL_NAME,
|
| 397 |
google_api_key=GOOGLE_API_KEY,
|
| 398 |
temperature=0.0,
|
| 399 |
-
# safety_settings parameter is removed to use model's default settings.
|
| 400 |
timeout=120,
|
| 401 |
convert_system_message_to_human=False # Explicitly set to False
|
| 402 |
)
|
|
@@ -413,29 +409,25 @@ def initialize_agent_and_tools(force_reinit=False):
|
|
| 413 |
else: logger.warning("'direct_multimodal_gemini_tool' NOT added (client or PIL missing).")
|
| 414 |
try: search_tool = DuckDuckGoSearchRun(name="web_search"); search_tool.description = "Web search. Input: query."; TOOLS.append(search_tool)
|
| 415 |
except Exception as e: logger.warning(f"DuckDuckGoSearchRun init failed: {e}")
|
| 416 |
-
try: python_repl = PythonREPLTool(name="python_repl"); python_repl.description = "Python REPL. print() for output."; TOOLS.append(python_repl)
|
| 417 |
except Exception as e: logger.warning(f"PythonREPLTool init failed: {e}")
|
| 418 |
logger.info(f"Final tools list for agent: {[t.name for t in TOOLS]}")
|
| 419 |
|
| 420 |
-
if LANGGRAPH_FLAVOR_AVAILABLE and all([LG_StateGraph, LG_ToolExecutor_Class, LG_END, LLM_INSTANCE, add_messages]):
|
| 421 |
if not LANGGRAPH_MEMORY_SAVER and MemorySaver_Class: LANGGRAPH_MEMORY_SAVER = MemorySaver_Class(); logger.info("LangGraph MemorySaver initialized.")
|
| 422 |
try:
|
| 423 |
logger.info(f"Attempting LangGraph init (Tool Executor type: {LG_ToolExecutor_Class.__name__ if LG_ToolExecutor_Class else 'None'})")
|
| 424 |
_TypedDict = getattr(__import__('typing_extensions'), 'TypedDict', dict)
|
| 425 |
-
# FIX: Remove 'input' key from state, only use 'messages' for conversational flow
|
| 426 |
class AgentState(_TypedDict):
|
| 427 |
messages: Annotated[List[Any], add_messages]
|
| 428 |
|
| 429 |
-
|
| 430 |
-
# The {input} placeholder for the actual task will be filled by the HumanMessage.
|
| 431 |
-
base_system_prompt_content_lg = LANGGRAPH_PROMPT_TEMPLATE_STR.split("{input}")[0].strip()
|
| 432 |
|
| 433 |
def agent_node(state: AgentState):
|
| 434 |
system_message_content = base_system_prompt_content_lg.format(
|
| 435 |
tools="\n".join([f"- {t.name}: {t.description}" for t in TOOLS])
|
| 436 |
)
|
| 437 |
|
| 438 |
-
# FIX: Construct message list from state, don't re-add original prompt
|
| 439 |
messages_for_llm = [SystemMessage(content=system_message_content)]
|
| 440 |
messages_for_llm.extend(state['messages'])
|
| 441 |
|
|
@@ -451,7 +443,7 @@ def initialize_agent_and_tools(force_reinit=False):
|
|
| 451 |
if not LG_ToolExecutor_Class: raise ValueError("LG_ToolExecutor_Class is None for LangGraph.")
|
| 452 |
tool_executor_instance_lg = LG_ToolExecutor_Class(tools=TOOLS)
|
| 453 |
|
| 454 |
-
def tool_node(state: AgentState):
|
| 455 |
last_msg = state['messages'][-1] if state.get('messages') and isinstance(state['messages'][-1], AIMessage) else None
|
| 456 |
if not last_msg or not last_msg.tool_calls: return {"messages": []}
|
| 457 |
tool_results = []
|
|
@@ -463,10 +455,10 @@ def initialize_agent_and_tools(force_reinit=False):
|
|
| 463 |
continue
|
| 464 |
try:
|
| 465 |
logger.info(f"LG Tool Invoking: '{name}' with {args} (ID: {tc_id})")
|
| 466 |
-
if LG_ToolInvocation and type(LG_ToolExecutor_Class).__name__ != 'ToolNode':
|
| 467 |
invocation = LG_ToolInvocation(tool=name, tool_input=args)
|
| 468 |
output_lg = tool_executor_instance_lg.invoke(invocation) # type: ignore
|
| 469 |
-
else:
|
| 470 |
output_lg = tool_executor_instance_lg.invoke(tc) # type: ignore
|
| 471 |
tool_results.append(ToolMessage(content=str(output_lg), tool_call_id=tc_id, name=name))
|
| 472 |
except Exception as e_tool_node_lg:
|
|
@@ -474,7 +466,6 @@ def initialize_agent_and_tools(force_reinit=False):
|
|
| 474 |
tool_results.append(ToolMessage(content=f"Error for tool {name}: {str(e_tool_node_lg)}", tool_call_id=tc_id, name=name))
|
| 475 |
return {"messages": tool_results}
|
| 476 |
|
| 477 |
-
|
| 478 |
workflow_lg = LG_StateGraph(AgentState) # type: ignore
|
| 479 |
workflow_lg.add_node("agent", agent_node)
|
| 480 |
workflow_lg.add_node("tools", tool_node)
|
|
@@ -506,7 +497,6 @@ def initialize_agent_and_tools(force_reinit=False):
|
|
| 506 |
if not AGENT_INSTANCE: raise RuntimeError("CRITICAL: Agent initialization completely failed.")
|
| 507 |
logger.info(f"Agent init finished. Active agent type: {type(AGENT_INSTANCE).__name__}")
|
| 508 |
|
| 509 |
-
# --- get_agent_response, construct_prompt_for_agent, run_and_submit_all (Unchanged) ---
|
| 510 |
def get_agent_response(prompt: str, task_id: Optional[str]=None, thread_id: Optional[str]=None) -> str:
|
| 511 |
global AGENT_INSTANCE, LLM_INSTANCE
|
| 512 |
thread_id_to_use = thread_id or (f"gaia_task_{task_id}" if task_id else hashlib.md5(prompt.encode()).hexdigest()[:8])
|
|
@@ -524,7 +514,6 @@ def get_agent_response(prompt: str, task_id: Optional[str]=None, thread_id: Opti
|
|
| 524 |
try:
|
| 525 |
if is_langgraph_agent_get:
|
| 526 |
logger.debug(f"Using LangGraph agent for thread: {thread_id_to_use}")
|
| 527 |
-
# FIX: The input should be a list of messages for the 'add_messages' reducer.
|
| 528 |
input_for_lg_get = {"messages": [HumanMessage(content=prompt)]}
|
| 529 |
logger.debug(f"Invoking LangGraph with input: {input_for_lg_get}")
|
| 530 |
final_state_lg_get = AGENT_INSTANCE.invoke(input_for_lg_get, {"configurable": {"thread_id": thread_id_to_use}})
|
|
|
|
| 39 |
except ImportError: WHISPER_AVAILABLE = False; print("WARNING: OpenAI Whisper not found, Audio Transcription tool will be disabled.")
|
| 40 |
|
| 41 |
# Google GenAI SDK types
|
| 42 |
+
from google.genai.types import HarmCategory, HarmBlockThreshold
|
| 43 |
from google.ai import generativelanguage as glm # For FileState enum
|
| 44 |
|
| 45 |
# LangChain
|
|
|
|
| 61 |
LANGGRAPH_FLAVOR_AVAILABLE = False
|
| 62 |
LG_StateGraph: Optional[Type[Any]] = None
|
| 63 |
LG_ToolExecutor_Class: Optional[Type[Any]] = None
|
| 64 |
+
LG_END: Optional[Any] = None
|
| 65 |
LG_ToolInvocation: Optional[Type[Any]] = None
|
| 66 |
add_messages: Optional[Any] = None
|
| 67 |
MemorySaver_Class: Optional[Type[Any]] = None
|
| 68 |
|
| 69 |
AGENT_INSTANCE: Optional[Union[AgentExecutor, Any]] = None
|
| 70 |
TOOLS: List[BaseTool] = []
|
| 71 |
+
LLM_INSTANCE: Optional[ChatGoogleGenerativeAI] = None
|
| 72 |
LANGGRAPH_MEMORY_SAVER: Optional[Any] = None
|
| 73 |
|
| 74 |
# google-genai Client SDK
|
|
|
|
| 255 |
name_without_ext, current_ext = os.path.splitext(effective_save_path)
|
| 256 |
if not current_ext:
|
| 257 |
content_type_header = r.headers.get('content-type', '')
|
|
|
|
| 258 |
content_type_val = content_type_header.split(';')[0].strip() if content_type_header else ''
|
| 259 |
if content_type_val:
|
| 260 |
guessed_ext = mimetypes.guess_extension(content_type_val)
|
|
|
|
| 365 |
- 'python_repl': `args` is like '{{"query": "python code string"}}'. Use print() for output.
|
| 366 |
RESPONSE FORMAT:
|
| 367 |
Final AIMessage should contain ONLY the answer in 'content' and NO 'tool_calls'. If using tools, 'content' can be thought process, with 'tool_calls'.
|
| 368 |
+
Begin!"""
|
|
|
|
|
|
|
| 369 |
|
| 370 |
REACT_PROMPT_TEMPLATE_STR = """You are a highly intelligent agent for the GAIA benchmark.
|
| 371 |
Goal: EXACT MATCH answer. No extra text/markdown.
|
|
|
|
| 393 |
model=GEMINI_MODEL_NAME,
|
| 394 |
google_api_key=GOOGLE_API_KEY,
|
| 395 |
temperature=0.0,
|
|
|
|
| 396 |
timeout=120,
|
| 397 |
convert_system_message_to_human=False # Explicitly set to False
|
| 398 |
)
|
|
|
|
| 409 |
else: logger.warning("'direct_multimodal_gemini_tool' NOT added (client or PIL missing).")
|
| 410 |
try: search_tool = DuckDuckGoSearchRun(name="web_search"); search_tool.description = "Web search. Input: query."; TOOLS.append(search_tool)
|
| 411 |
except Exception as e: logger.warning(f"DuckDuckGoSearchRun init failed: {e}")
|
| 412 |
+
try: python_repl = PythonREPLTool(name="python_repl"); python_repl.description = "Python REPL. print() for output. The input is a single string of code."; TOOLS.append(python_repl)
|
| 413 |
except Exception as e: logger.warning(f"PythonREPLTool init failed: {e}")
|
| 414 |
logger.info(f"Final tools list for agent: {[t.name for t in TOOLS]}")
|
| 415 |
|
| 416 |
+
if LANGGRAPH_FLAVOR_AVAILABLE and all([LG_StateGraph, LG_ToolExecutor_Class, LG_END, LLM_INSTANCE, add_messages]):
|
| 417 |
if not LANGGRAPH_MEMORY_SAVER and MemorySaver_Class: LANGGRAPH_MEMORY_SAVER = MemorySaver_Class(); logger.info("LangGraph MemorySaver initialized.")
|
| 418 |
try:
|
| 419 |
logger.info(f"Attempting LangGraph init (Tool Executor type: {LG_ToolExecutor_Class.__name__ if LG_ToolExecutor_Class else 'None'})")
|
| 420 |
_TypedDict = getattr(__import__('typing_extensions'), 'TypedDict', dict)
|
|
|
|
| 421 |
class AgentState(_TypedDict):
|
| 422 |
messages: Annotated[List[Any], add_messages]
|
| 423 |
|
| 424 |
+
base_system_prompt_content_lg = LANGGRAPH_PROMPT_TEMPLATE_STR
|
|
|
|
|
|
|
| 425 |
|
| 426 |
def agent_node(state: AgentState):
|
| 427 |
system_message_content = base_system_prompt_content_lg.format(
|
| 428 |
tools="\n".join([f"- {t.name}: {t.description}" for t in TOOLS])
|
| 429 |
)
|
| 430 |
|
|
|
|
| 431 |
messages_for_llm = [SystemMessage(content=system_message_content)]
|
| 432 |
messages_for_llm.extend(state['messages'])
|
| 433 |
|
|
|
|
| 443 |
if not LG_ToolExecutor_Class: raise ValueError("LG_ToolExecutor_Class is None for LangGraph.")
|
| 444 |
tool_executor_instance_lg = LG_ToolExecutor_Class(tools=TOOLS)
|
| 445 |
|
| 446 |
+
def tool_node(state: AgentState):
|
| 447 |
last_msg = state['messages'][-1] if state.get('messages') and isinstance(state['messages'][-1], AIMessage) else None
|
| 448 |
if not last_msg or not last_msg.tool_calls: return {"messages": []}
|
| 449 |
tool_results = []
|
|
|
|
| 455 |
continue
|
| 456 |
try:
|
| 457 |
logger.info(f"LG Tool Invoking: '{name}' with {args} (ID: {tc_id})")
|
| 458 |
+
if LG_ToolInvocation and type(LG_ToolExecutor_Class).__name__ != 'ToolNode':
|
| 459 |
invocation = LG_ToolInvocation(tool=name, tool_input=args)
|
| 460 |
output_lg = tool_executor_instance_lg.invoke(invocation) # type: ignore
|
| 461 |
+
else:
|
| 462 |
output_lg = tool_executor_instance_lg.invoke(tc) # type: ignore
|
| 463 |
tool_results.append(ToolMessage(content=str(output_lg), tool_call_id=tc_id, name=name))
|
| 464 |
except Exception as e_tool_node_lg:
|
|
|
|
| 466 |
tool_results.append(ToolMessage(content=f"Error for tool {name}: {str(e_tool_node_lg)}", tool_call_id=tc_id, name=name))
|
| 467 |
return {"messages": tool_results}
|
| 468 |
|
|
|
|
| 469 |
workflow_lg = LG_StateGraph(AgentState) # type: ignore
|
| 470 |
workflow_lg.add_node("agent", agent_node)
|
| 471 |
workflow_lg.add_node("tools", tool_node)
|
|
|
|
| 497 |
if not AGENT_INSTANCE: raise RuntimeError("CRITICAL: Agent initialization completely failed.")
|
| 498 |
logger.info(f"Agent init finished. Active agent type: {type(AGENT_INSTANCE).__name__}")
|
| 499 |
|
|
|
|
| 500 |
def get_agent_response(prompt: str, task_id: Optional[str]=None, thread_id: Optional[str]=None) -> str:
|
| 501 |
global AGENT_INSTANCE, LLM_INSTANCE
|
| 502 |
thread_id_to_use = thread_id or (f"gaia_task_{task_id}" if task_id else hashlib.md5(prompt.encode()).hexdigest()[:8])
|
|
|
|
| 514 |
try:
|
| 515 |
if is_langgraph_agent_get:
|
| 516 |
logger.debug(f"Using LangGraph agent for thread: {thread_id_to_use}")
|
|
|
|
| 517 |
input_for_lg_get = {"messages": [HumanMessage(content=prompt)]}
|
| 518 |
logger.debug(f"Invoking LangGraph with input: {input_for_lg_get}")
|
| 519 |
final_state_lg_get = AGENT_INSTANCE.invoke(input_for_lg_get, {"configurable": {"thread_id": thread_id_to_use}})
|