"""GAIA agent built with LangGraph. Lesson 4 version: the ReAct loop. START -> assistant --(tool calls?)--yes--> tools --+ ^ | +--------------------------------------+ --no--> END """ import os import re from dotenv import load_dotenv from langchain_core.messages import HumanMessage, SystemMessage from langchain_openai import ChatOpenAI from langgraph.graph import START, MessagesState, StateGraph from langgraph.prebuilt import ToolNode, tools_condition from prompts import SYSTEM_PROMPT from tools import TOOLS load_dotenv() # --- 1. State ----------------------------------------------------------------- # MessagesState is a TypedDict with one key, `messages`, whose reducer # (add_messages) APPENDS whatever a node returns instead of overwriting it. # That running message list is the agent's whole memory for one question. class AgentState(MessagesState): pass # --- 2. The model ------------------------------------------------------------- # temperature=0: we want the same, most-likely answer every run (exact match!). llm = ChatOpenAI(model=os.getenv("OPENAI_MODEL", "gpt-5.4-mini"), temperature=0) # bind_tools sends the tools' JSON schemas with every request, so the model # can reply with structured "tool_calls" instead of (or before) a final answer. llm_with_tools = llm.bind_tools(TOOLS) # --- 3. Nodes ----------------------------------------------------------------- # A node is just a function: state in -> partial state update out. def assistant(state: AgentState) -> dict: response = llm_with_tools.invoke(state["messages"]) return {"messages": [response]} # appended, thanks to add_messages # --- 4. Graph ----------------------------------------------------------------- def build_graph(): builder = StateGraph(AgentState) builder.add_node("assistant", assistant) # ToolNode: reads the tool_calls on the last AI message, runs each tool, # and appends the results as ToolMessages. # handle_tool_errors=True: if a tool raises, the error text is returned to # the LLM as a ToolMessage (so it can try another tool) instead of crashing. builder.add_node("tools", ToolNode(TOOLS, handle_tool_errors=True)) builder.add_edge(START, "assistant") # tools_condition: if the last message has tool_calls -> "tools", # otherwise -> END. This conditional edge is what makes it an agent. builder.add_conditional_edges("assistant", tools_condition) builder.add_edge("tools", "assistant") # results go back to the LLM return builder.compile() graph = build_graph() # --- 5. Answer extraction ----------------------------------------------------- def extract_final_answer(text: str) -> str: """Pull out what follows 'FINAL ANSWER:' and clean it for exact match.""" match = re.search(r"FINAL ANSWER:\s*(.+)", text, re.IGNORECASE | re.DOTALL) answer = (match.group(1) if match else text).strip() answer = answer.splitlines()[0].strip() if answer else answer answer = answer.strip("*`\"' ") # markdown bold / quotes the model may add return answer.rstrip(".").strip() # GAIA answers never end with a period def run_agent(question: str, task_id: str = "", file_name: str = "") -> tuple[str, list]: """Run the graph on one question. Returns (clean_answer, full_message_trace). If the question has an attachment, download it first and tell the model its local path — the LLM can't call the scoring API itself. """ if file_name and task_id: from questions import download_file path = download_file(task_id, file_name).resolve() question += (f"\n\nAttached file: {path}\n" "Use your file tools (read_file, transcribe_audio, analyze_image, " "python_repl) on this path.") result = graph.invoke( {"messages": [SystemMessage(SYSTEM_PROMPT), HumanMessage(question)]}, config={"recursion_limit": 25}, ) final_text = result["messages"][-1].content return extract_final_answer(final_text), result["messages"] def format_trace(messages: list, width: int = 300) -> str: """What the agent did step by step — your main debugging view.""" lines = [] for m in messages[1:]: # skip the system prompt kind = type(m).__name__.replace("Message", "") if getattr(m, "tool_calls", None): for tc in m.tool_calls: lines.append(f"[{kind}] -> calls {tc['name']}({tc['args']})") else: text = str(m.content).replace("\n", " ") lines.append(f"[{kind}] {text[:width]}{'…' if len(text) > width else ''}") return "\n".join(lines) def print_trace(messages: list) -> None: print(format_trace(messages)) if __name__ == "__main__": # Usage: python agent.py 6 -> run the agent on question #6 and show the trace import sys from questions import get_questions n = int(sys.argv[1]) if len(sys.argv) > 1 else 3 q = get_questions()[n - 1] answer, trace = run_agent(q["question"], q["task_id"], q.get("file_name", "")) print_trace(trace) print(f"\n>>> #{n} extracted answer: {answer!r}")