ahnhs2k commited on
Commit
3f50999
ยท
1 Parent(s): 2b4efdd
Files changed (2) hide show
  1. agent.py +94 -130
  2. requirements.txt +1 -6
agent.py CHANGED
@@ -1,100 +1,92 @@
1
  # agent.py
2
  # =========================================================
3
- # GAIA Benchmark Agent (FINAL, STABLE)
4
- #
5
- # - OpenAI GPT-4o-mini
6
- # - Wikipedia / Arxiv / DuckDuckGo ๊ฒ€์ƒ‰ (API Key ๋ถˆํ•„์š”)
7
- # - HuggingFace Embeddings + FAISS Retriever ์œ ์ง€
8
- # - LangGraph ์‚ฌ์šฉ (๋‹จ์ผ ๋…ธ๋“œ, ์žฌ๊ท€/ํˆด์ฝœ๋ง ์™„์ „ ์ œ๊ฑฐ)
9
  # =========================================================
10
 
11
  import os
12
  import pickle
13
  from typing import TypedDict, List
14
 
15
- # ---------------------------------------------------------
16
- # LangChain / LangGraph ๊ธฐ๋ณธ ๊ตฌ์„ฑ
17
- # ---------------------------------------------------------
18
  from langchain_openai import ChatOpenAI
19
- from langchain_core.messages import SystemMessage, HumanMessage
20
  from langchain_core.documents import Document
 
21
 
22
  from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
23
  from langchain_community.tools import DuckDuckGoSearchRun
24
  from langchain_community.vectorstores import FAISS
25
- from langchain_huggingface import HuggingFaceEmbeddings
26
 
27
  from langgraph.graph import START, END, StateGraph
 
28
 
29
 
30
- # =========================================================
31
- # State ์ •์˜ (LangGraph์šฉ)
32
- # =========================================================
33
  class AgentState(TypedDict):
34
- messages: List
 
35
 
36
 
37
- # =========================================================
38
- # System Prompt (GAIA ๊ทœ์น™ ๊ณ ์ •)
39
- # =========================================================
40
- SYSTEM_PROMPT = """
41
- You are solving GAIA benchmark questions.
42
 
43
- You MUST:
44
- - Use the provided context as the only source of truth.
45
- - Reason internally but DO NOT reveal reasoning.
46
- - Output ONLY the final answer.
47
- - No explanation.
48
- - No extra text.
49
- """.strip()
50
 
51
- SYS_MSG = SystemMessage(content=SYSTEM_PROMPT)
 
 
 
 
 
 
 
52
 
53
 
54
- # =========================================================
55
- # ๊ฒ€์ƒ‰ ๋„๊ตฌ (Python ํ•จ์ˆ˜๋กœ๋งŒ ์‚ฌ์šฉ)
56
- # =========================================================
57
- ddg = DuckDuckGoSearchRun()
 
58
 
59
 
60
- def wiki_search_text(query: str) -> str:
61
- """
62
- Wikipedia ๊ฒ€์ƒ‰ (์ตœ๋Œ€ 2๋ฌธ์„œ).
63
- wikipedia ํŒจํ‚ค์ง€๊ฐ€ ์—†์œผ๋ฉด ์ž๋™์œผ๋กœ ๋นˆ ๋ฌธ์ž์—ด ๋ฐ˜ํ™˜.
64
- """
65
  try:
66
- docs = WikipediaLoader(query=query, load_max_docs=2).load()
67
- return "\n\n".join(d.page_content for d in docs)
68
  except Exception:
69
- return ""
70
 
71
 
72
- def arxiv_search_text(query: str) -> str:
73
- """
74
- Arxiv ๊ฒ€์ƒ‰ (์ตœ๋Œ€ 2๋…ผ๋ฌธ, ์•ž๋ถ€๋ถ„๋งŒ ์‚ฌ์šฉ).
75
- arxiv ํŒจํ‚ค์ง€๊ฐ€ ์—†์œผ๋ฉด ์ž๋™์œผ๋กœ ๋นˆ ๋ฌธ์ž์—ด ๋ฐ˜ํ™˜.
76
- """
77
- try:
78
- docs = ArxivLoader(query=query, load_max_docs=2).load()
79
- return "\n\n".join(d.page_content[:1000] for d in docs)
80
- except Exception:
81
- return ""
82
 
83
 
84
- def web_search_text(query: str) -> str:
85
- """
86
- DuckDuckGo ์›น ๊ฒ€์ƒ‰.
87
- API Key ๋ถˆํ•„์š”, Space ํ™˜๊ฒฝ์—์„œ ์•ˆ์ „.
88
- """
89
- try:
90
- return ddg.run(query)
91
- except Exception:
92
- return ""
 
 
 
 
 
93
 
94
 
95
- # =========================================================
96
- # FAISS Retriever (์š”๊ตฌ์‚ฌํ•ญ ๋•Œ๋ฌธ์— ์œ ์ง€)
97
- # =========================================================
98
  embeddings = HuggingFaceEmbeddings(
99
  model_name="sentence-transformers/all-mpnet-base-v2"
100
  )
@@ -103,101 +95,73 @@ if os.path.exists("faiss.pkl"):
103
  with open("faiss.pkl", "rb") as f:
104
  vector_store = pickle.load(f)
105
  else:
106
- seed_docs = [
107
- Document(page_content="GAIA questions require exact factual answers."),
108
- ]
109
- vector_store = FAISS.from_documents(seed_docs, embeddings)
110
  with open("faiss.pkl", "wb") as f:
111
  pickle.dump(vector_store, f)
112
 
113
 
114
- # =========================================================
115
- # LangGraph ๋นŒ๋” (๋‹จ์ผ assistant ๋…ธ๋“œ)
116
- # =========================================================
117
  def build_agent():
118
- """
119
- LangGraph๋ฅผ 'ํ˜•์‹๋งŒ' ์‚ฌ์šฉ.
120
- - START โ†’ assistant โ†’ END
121
- - tool node, conditional edge, recursion ์ „๋ถ€ ์—†์Œ
122
- """
123
-
124
  llm = ChatOpenAI(
125
  model="gpt-4o-mini",
126
  temperature=0,
127
  max_tokens=128,
128
  )
129
 
 
 
 
 
 
 
 
 
130
  def assistant(state: AgentState):
131
- # ๋งˆ์ง€๋ง‰ ๋ฉ”์‹œ์ง€๋Š” ํ•ญ์ƒ ์งˆ๋ฌธ
132
- question = state["messages"][-1].content
133
-
134
- # -----------------------------
135
- # ๊ฒ€์ƒ‰ (ํ•œ ๋ฒˆ๋งŒ ์‹คํ–‰)
136
- # -----------------------------
137
- wiki = wiki_search_text(question)
138
- arxiv = arxiv_search_text(question)
139
- web = web_search_text(question)
140
-
141
- # -----------------------------
142
- # ์ปจํ…์ŠคํŠธ ๊ตฌ์„ฑ
143
- # -----------------------------
144
- context = f"""
145
- [WIKIPEDIA]
146
- {wiki}
147
-
148
- [ARXIV]
149
- {arxiv}
150
-
151
- [WEB]
152
- {web}
153
- """.strip()
154
-
155
- # -----------------------------
156
- # LLM ํ”„๋กฌํ”„ํŠธ
157
- # -----------------------------
158
- prompt = [
159
- SYS_MSG,
160
- HumanMessage(
161
- content=f"""
162
- Question:
163
- {question}
164
-
165
- Context:
166
- {context}
167
-
168
- Answer with ONLY the final answer.
169
- """.strip()
170
- ),
171
- ]
172
-
173
- response = llm.invoke(prompt)
174
-
175
- return {"messages": [response]}
176
-
177
- # -----------------------------
178
- # Graph ์ •์˜
179
- # -----------------------------
180
  builder = StateGraph(AgentState)
 
 
181
  builder.add_node("assistant", assistant)
 
182
 
183
- builder.add_edge(START, "assistant")
184
- builder.add_edge("assistant", END)
 
 
185
 
186
  return builder.compile()
187
 
188
 
189
- # =========================================================
190
  # Public API (app.py์—์„œ import)
191
- # =========================================================
192
  class BasicAgent:
193
  def __init__(self):
194
  self.graph = build_agent()
195
- print("GAIA GPT-4o-mini Agent initialized (STABLE)")
196
 
197
  def __call__(self, question: str) -> str:
198
  result = self.graph.invoke(
199
  {
200
  "messages": [HumanMessage(content=question)],
201
- }
 
 
202
  )
203
  return result["messages"][-1].content.strip()
 
1
  # agent.py
2
  # =========================================================
3
+ # LangGraph ๊ธฐ๋ฐ˜ GAIA ๋ฌธ์ œ ํ•ด๊ฒฐ Agent (STABLE)
4
+ # - GPT-4o-mini
5
+ # - Wikipedia / Arxiv / DuckDuckGo
6
+ # - FAISS (CPU)
7
+ # - Tool 1ํšŒ ์ œํ•œ (๋ฌดํ•œ ๋ฃจํ”„ ์ฐจ๋‹จ)
 
8
  # =========================================================
9
 
10
  import os
11
  import pickle
12
  from typing import TypedDict, List
13
 
 
 
 
14
  from langchain_openai import ChatOpenAI
15
+ from langchain_core.messages import SystemMessage, HumanMessage, BaseMessage
16
  from langchain_core.documents import Document
17
+ from langchain_core.tools import tool
18
 
19
  from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
20
  from langchain_community.tools import DuckDuckGoSearchRun
21
  from langchain_community.vectorstores import FAISS
22
+ from langchain_community.embeddings import HuggingFaceEmbeddings
23
 
24
  from langgraph.graph import START, END, StateGraph
25
+ from langgraph.prebuilt import ToolNode, tools_condition
26
 
27
 
28
+ # ---------------------------------------------------------
29
+ # State ์ •์˜
30
+ # ---------------------------------------------------------
31
  class AgentState(TypedDict):
32
+ messages: List[BaseMessage]
33
+ used_tools: bool
34
 
35
 
36
+ # ---------------------------------------------------------
37
+ # Search tool instance (API key ๋ถˆํ•„์š”)
38
+ # ---------------------------------------------------------
39
+ ddg = DuckDuckGoSearchRun()
 
40
 
 
 
 
 
 
 
 
41
 
42
+ # ---------------------------------------------------------
43
+ # TOOLS (docstring ํ•„์ˆ˜)
44
+ # ---------------------------------------------------------
45
+ @tool
46
+ def wiki_search(query: str) -> dict:
47
+ """Search Wikipedia for factual information."""
48
+ docs = WikipediaLoader(query=query, load_max_docs=2).load()
49
+ return {"wiki": "\n\n".join(d.page_content for d in docs)}
50
 
51
 
52
+ @tool
53
+ def arxiv_search(query: str) -> dict:
54
+ """Search Arxiv for academic information."""
55
+ docs = ArxivLoader(query=query, load_max_docs=2).load()
56
+ return {"arxiv": "\n\n".join(d.page_content[:1000] for d in docs)}
57
 
58
 
59
+ @tool
60
+ def web_search(query: str) -> dict:
61
+ """Search the web using DuckDuckGo (no API key)."""
 
 
62
  try:
63
+ return {"web": ddg.run(query)}
 
64
  except Exception:
65
+ return {"web": ""}
66
 
67
 
68
+ TOOLS = [wiki_search, arxiv_search, web_search]
 
 
 
 
 
 
 
 
 
69
 
70
 
71
+ # ---------------------------------------------------------
72
+ # SYSTEM PROMPT (GAIA ๊ทœ์น™)
73
+ # ---------------------------------------------------------
74
+ SYS_MSG = SystemMessage(
75
+ content=(
76
+ "You are solving GAIA benchmark questions.\n\n"
77
+ "You MUST:\n"
78
+ "- Use tools if factual information is required.\n"
79
+ "- Reason internally but DO NOT reveal reasoning.\n"
80
+ "- Output ONLY the final answer.\n"
81
+ "- No explanation.\n"
82
+ "- No extra text."
83
+ )
84
+ )
85
 
86
 
87
+ # ---------------------------------------------------------
88
+ # FAISS Retriever (CPU)
89
+ # ---------------------------------------------------------
90
  embeddings = HuggingFaceEmbeddings(
91
  model_name="sentence-transformers/all-mpnet-base-v2"
92
  )
 
95
  with open("faiss.pkl", "rb") as f:
96
  vector_store = pickle.load(f)
97
  else:
98
+ vector_store = FAISS.from_documents(
99
+ [Document(page_content="GAIA questions require exact factual answers.")],
100
+ embeddings,
101
+ )
102
  with open("faiss.pkl", "wb") as f:
103
  pickle.dump(vector_store, f)
104
 
105
 
106
+ # ---------------------------------------------------------
107
+ # Graph Builder (Tool 1ํšŒ ์ œํ•œ)
108
+ # ---------------------------------------------------------
109
  def build_agent():
 
 
 
 
 
 
110
  llm = ChatOpenAI(
111
  model="gpt-4o-mini",
112
  temperature=0,
113
  max_tokens=128,
114
  )
115
 
116
+ llm_with_tools = llm.bind_tools(TOOLS)
117
+
118
+ def inject_system(state: AgentState):
119
+ return {
120
+ "messages": [SYS_MSG] + state["messages"],
121
+ "used_tools": state["used_tools"],
122
+ }
123
+
124
  def assistant(state: AgentState):
125
+ msg = llm_with_tools.invoke(state["messages"])
126
+ return {
127
+ "messages": [msg],
128
+ "used_tools": state["used_tools"],
129
+ }
130
+
131
+ def tool_condition_once(state: AgentState):
132
+ # Tool์€ ๋‹จ 1ํšŒ๋งŒ ํ—ˆ์šฉ
133
+ if state["used_tools"]:
134
+ return END
135
+ return tools_condition(state)
136
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  builder = StateGraph(AgentState)
138
+
139
+ builder.add_node("inject_system", inject_system)
140
  builder.add_node("assistant", assistant)
141
+ builder.add_node("tools", ToolNode(TOOLS))
142
 
143
+ builder.add_edge(START, "inject_system")
144
+ builder.add_edge("inject_system", "assistant")
145
+ builder.add_conditional_edges("assistant", tool_condition_once)
146
+ builder.add_edge("tools", "assistant")
147
 
148
  return builder.compile()
149
 
150
 
151
+ # ---------------------------------------------------------
152
  # Public API (app.py์—์„œ import)
153
+ # ---------------------------------------------------------
154
  class BasicAgent:
155
  def __init__(self):
156
  self.graph = build_agent()
157
+ print("GAIA LangGraph Agent initialized (CPU-safe)")
158
 
159
  def __call__(self, question: str) -> str:
160
  result = self.graph.invoke(
161
  {
162
  "messages": [HumanMessage(content=question)],
163
+ "used_tools": False,
164
+ },
165
+ config={"recursion_limit": 8},
166
  )
167
  return result["messages"][-1].content.strip()
requirements.txt CHANGED
@@ -1,21 +1,16 @@
1
  gradio
2
  requests
3
 
4
- # LangGraph / LangChain core
5
  langgraph
6
  langchain
7
  langchain-core
8
  langchain-community
9
  langchain-openai
10
 
11
- # Embedding / VectorStore
12
  sentence-transformers
13
  faiss-cpu
14
 
15
- # Search (API key ๋ถˆํ•„์š”)
16
  ddgs
17
  duckduckgo-search
18
-
19
- # Document loaders
20
  wikipedia
21
- arxiv
 
1
  gradio
2
  requests
3
 
 
4
  langgraph
5
  langchain
6
  langchain-core
7
  langchain-community
8
  langchain-openai
9
 
 
10
  sentence-transformers
11
  faiss-cpu
12
 
 
13
  ddgs
14
  duckduckgo-search
 
 
15
  wikipedia
16
+ arxiv