File size: 5,215 Bytes
912dd45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""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}")