Spaces:
Sleeping
Sleeping
commit
Browse filesFiles changed (2)
- agent.py+68-63
- requirements.txt+15-18
3 unmodified lines456789101112139 unmodified lines232425262728293031323334353637383940414243442 unmodified lines4748495051525354555657583 unmodified lines6263646566676869707172734 unmodified lines7879808182838485868788899091929394959697986 unmodified lines1051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391402 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142153 unmodified lines# - OpenAI GPT-4o-mini ์ฌ์ฉ# - Wikipedia / Arxiv / DuckDuckGo ๊ฒ์ ๋๊ตฌ ํฌํจ# - HuggingFace Embedding + FAISS Retriever ์ ์ง# =========================================================import osimport pickle# ---------------------------------------------------------# LangChain / LangGraph ํต์ฌ ๊ตฌ์ฑ์์9 unmodified linesfrom langchain_core.tools import toolfrom langchain_community.tools import DuckDuckGoSearchRunfrom langgraph.graph import START, StateGraph, MessagesStatefrom langgraph.prebuilt import ToolNode, tools_condition# ---------------------------------------------------------# DuckDuckGo ๊ฒ์ ์ธ์คํด์ค# - API Key ๋ถํ์# - Space ํ๊ฒฝ์์ ์ฌ์ฉ ๊ฐ๋ฅ# ---------------------------------------------------------ddg = DuckDuckGoSearchRun()# =========================================================# TOOLS ์ ์# โป LangChain ์ต์ ๋ฒ์ ์์๋# @tool ํจ์์ "docstring"์ด ๋ฐ๋์ ํ์ํจ# =========================================================@tool2 unmodified linesSearch Wikipedia for factual information related to the query.Returns raw page content as text."""# Wikipedia์์ ์ต๋ 2๊ฐ ๋ฌธ์ ๋ก๋docs = WikipediaLoader(query=query, load_max_docs=2).load()# ๋ฌธ์ ๋ด์ฉ์ ํ๋์ ๋ฌธ์์ด๋ก ๋ณํฉtext = "\n\n".join(d.page_content for d in docs)return {"wiki": text}3 unmodified linesSearch Arxiv for academic papers related to the query.Returns truncated paper content."""# Arxiv์์ ์ต๋ 2๊ฐ ๋ ผ๋ฌธ ๋ก๋docs = ArxivLoader(query=query, load_max_docs=2).load()# ๋ ผ๋ฌธ์ ๊ธธ๊ธฐ ๋๋ฌธ์ ์๋ถ๋ถ๋ง ์ฌ์ฉtext = "\n\n".join(d.page_content[:1000] for d in docs)return {"arxiv": text}4 unmodified linesNo API key required. Suitable for Hugging Face Spaces."""try:# DuckDuckGo ๊ฒ์ ์คํresult = ddg.run(query)return {"web": result}except Exception:# ๊ฒ์ ์คํจ ์ ๋น ๊ฒฐ๊ณผ ๋ฐํ (๊ทธ๋ํ ์ค๋จ ๋ฐฉ์ง)return {"web": ""}# LangGraph์์ ์ฌ์ฉํ Tool ๋ชฉ๋กTOOLS = [wiki_search, arxiv_search, web_search]# =========================================================# SYSTEM PROMPT# - GAIA ํ๊ฐ ๊ท์น์ ๋ง๊ฒ ์ถ๋ ฅ ํ์ ๊ฐ์ # =========================================================SYSTEM_PROMPT = """You are solving GAIA benchmark questions.6 unmodified lines- No extra text.""".strip()# SystemMessage ๊ฐ์ฒด๋ก ๋ณํSYS_MSG = SystemMessage(content=SYSTEM_PROMPT)# =========================================================# RETRIEVER (FAISS + HuggingFace Embeddings)# - ์ด์ ์ง๋ฌธ๊ณผ ์ ์ฌํ ํจํด์ ์ ๊ณตํ๊ธฐ ์ํ ์ฉ๋# =========================================================# ๋ฌธ์ฅ ์๋ฒ ๋ฉ ๋ชจ๋ธ (768์ฐจ์)embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")# FAISS ์ธ๋ฑ์ค๊ฐ ์ด๋ฏธ ์์ผ๋ฉด ๋ก๋if os.path.exists("faiss.pkl"):with open("faiss.pkl", "rb") as f:vector_store = pickle.load(f)else:# ์ต์ด ์คํ ์ ๊ธฐ๋ณธ ์๋ ๋ฌธ์ ์์ฑseed_docs = [Document(page_content="GAIA questions require factual exact answers."),]vector_store = FAISS.from_documents(seed_docs, embeddings)# ๋ค์ ์คํ์ ์ํด ์ ์ฅwith open("faiss.pkl", "wb") as f:pickle.dump(vector_store, f)# Retriever Tool (ํ์ฌ ๊ทธ๋ํ์์๋ ๋ณด์กฐ ์ญํ )retriever_tool = create_retriever_tool(retriever=vector_store.as_retriever(),name="question_retriever",2 unmodified lines# =========================================================# LANGGRAPH ๊ทธ๋ํ ๋น๋# =========================================================def build_agent():"""LangGraph StateGraph๋ฅผ ๊ตฌ์ฑํ์ฌ- System Prompt ์ฃผ์- LLM โ Tool โ LLM ๋ฐ๋ณต ํ๋ฆ์ ์์ฑ"""# OpenAI GPT-4o-mini (Space์์ ์์ ์ ์ผ๋ก ์ฌ์ฉ ๊ฐ๋ฅ)llm = ChatOpenAI(model="gpt-4o-mini",temperature=0, # deterministicmax_tokens=128,)# LLM์ Tool ์ฌ์ฉ ๊ถํ ๋ถ์ฌllm_with_tools = llm.bind_tools(TOOLS)# ---------------------# Graph Node ์ ์# ---------------------def retriever(state: MessagesState):# ์์คํ ํ๋กฌํํธ๋ฅผ ํญ์ ๋ฉ์์ง ๋งจ ์์ ์ฝ์return {"messages": [SYS_MSG] + state["messages"]}def assistant(state: MessagesState):# LLM ์คํ (Tool ํธ์ถ ์ฌ๋ถ๋ tools_condition์ด ํ๋จ)return {"messages": [llm_with_tools.invoke(state["messages"])]}# ---------------------# Graph ๊ตฌ์ฑ# ---------------------builder = StateGraph(MessagesState)builder.add_node("retriever", retriever)builder.add_node("assistant", assistant)builder.add_node("tools", ToolNode(TOOLS))# START โ retriever โ assistantbuilder.add_edge(START, "retriever")builder.add_edge("retriever", "assistant")# assistant๊ฐ tool ํธ์ถ์ ์ํ๋ฉด tools๋ก ๋ถ๊ธฐbuilder.add_conditional_edges("assistant", tools_condition)# tool ์คํ ํ ๋ค์ assistant๋ก ๋ณต๊ทbuilder.add_edge("tools", "assistant")return builder.compile()# =========================================================# ์ธ๋ถ์์ ์ฌ์ฉํ๋ PUBLIC API# - app.py์์ ์ด ํด๋์ค๋ง import# =========================================================class BasicAgent:def __init__(self):# LangGraph ์ปดํ์ผself.graph = build_agent()print("โ LangGraph GPT-4o-mini Agent initialized")def __call__(self, question: str) -> str:# ์ง๋ฌธ์ HumanMessage๋ก ๊ฐ์ธ Graph ์คํresult = self.graph.invoke({"messages": [HumanMessage(content=question)]})# ์ต์ข assistant ๋ฉ์์ง๋ง ๋ฐํreturn result["messages"][-1].content.strip()3 unmodified lines4567891011121314159 unmodified lines2526272829303132333435363738394041424344454647484950512 unmodified lines54555657585960613 unmodified lines65666768697071724 unmodified lines777879808182838485868788899091926 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241252 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192203 unmodified lines# - OpenAI GPT-4o-mini ์ฌ์ฉ# - Wikipedia / Arxiv / DuckDuckGo ๊ฒ์ ๋๊ตฌ ํฌํจ# - HuggingFace Embedding + FAISS Retriever ์ ์ง# - Tool ๋ฌดํ ๋ฃจํ ์ฐจ๋จ (์ค์)# =========================================================import osimport picklefrom typing import TypedDict# ---------------------------------------------------------# LangChain / LangGraph ํต์ฌ ๊ตฌ์ฑ์์9 unmodified linesfrom langchain_core.tools import toolfrom langchain_community.tools import DuckDuckGoSearchRunfrom langgraph.graph import START, END, StateGraphfrom langgraph.prebuilt import ToolNode, tools_condition# =========================================================# State ์ ์# - tool์ ์ด๋ฏธ ์ฌ์ฉํ๋์ง ์ฌ๋ถ๋ฅผ ๊ธฐ๋ก# =========================================================class AgentState(TypedDict):messages: listused_tools: bool# ---------------------------------------------------------# DuckDuckGo ๊ฒ์ ์ธ์คํด์ค (API Key ๋ถํ์)# ---------------------------------------------------------ddg = DuckDuckGoSearchRun()# =========================================================# TOOLS ์ ์# =========================================================@tool2 unmodified linesSearch Wikipedia for factual information related to the query.Returns raw page content as text."""docs = WikipediaLoader(query=query, load_max_docs=2).load()text = "\n\n".join(d.page_content for d in docs)return {"wiki": text}3 unmodified linesSearch Arxiv for academic papers related to the query.Returns truncated paper content."""docs = ArxivLoader(query=query, load_max_docs=2).load()text = "\n\n".join(d.page_content[:1000] for d in docs)return {"arxiv": text}4 unmodified linesNo API key required. Suitable for Hugging Face Spaces."""try:return {"web": ddg.run(query)}except Exception:return {"web": ""}TOOLS = [wiki_search, arxiv_search, web_search]# =========================================================# SYSTEM PROMPT (GAIA ๊ท์น ๊ณ ์ )# =========================================================SYSTEM_PROMPT = """You are solving GAIA benchmark questions.6 unmodified lines- No extra text.""".strip()SYS_MSG = SystemMessage(content=SYSTEM_PROMPT)# =========================================================# FAISS Retriever (์ ์ง)# =========================================================embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")if os.path.exists("faiss.pkl"):with open("faiss.pkl", "rb") as f:vector_store = pickle.load(f)else:seed_docs = [Document(page_content="GAIA questions require factual exact answers."),]vector_store = FAISS.from_documents(seed_docs, embeddings)with open("faiss.pkl", "wb") as f:pickle.dump(vector_store, f)retriever_tool = create_retriever_tool(retriever=vector_store.as_retriever(),name="question_retriever",2 unmodified lines# =========================================================# LangGraph ๋น๋# =========================================================def build_agent():"""Tool์ ์ต๋ 1ํ๋ง ์ฌ์ฉํ๋๋ก ๊ฐ์ ํ LangGraph.๋ฌดํ ๋ฃจํ / recursion ์๋ฌ ์์ฒ ์ฐจ๋จ."""llm = ChatOpenAI(model="gpt-4o-mini",temperature=0,max_tokens=128,)llm_with_tools = llm.bind_tools(TOOLS)# ---------------------# Nodes# ---------------------def inject_system(state: AgentState):return {"messages": [SYS_MSG] + state["messages"],"used_tools": state.get("used_tools", False),}def assistant(state: AgentState):msg = llm_with_tools.invoke(state["messages"])return {"messages": [msg],"used_tools": state.get("used_tools", False),}def tools_node(state: AgentState):# Tool์ ์ฌ์ฉํ ์๊ฐ used_tools = Truereturn {"messages": state["messages"],"used_tools": True,}# ---------------------# Conditional (ํต์ฌ)# ---------------------def tool_condition_once(state: AgentState):"""Tool์ ๋ฑ ํ ๋ฒ๋ง ํ์ฉ.์ด๋ฏธ ์ฌ์ฉํ๋ค๋ฉด ๋ฌด์กฐ๊ฑด END."""if state.get("used_tools"):return ENDreturn tools_condition(state)# ---------------------# Graph# ---------------------builder = StateGraph(AgentState)builder.add_node("inject_system", inject_system)builder.add_node("assistant", assistant)builder.add_node("tools", ToolNode(TOOLS))builder.add_edge(START, "inject_system")builder.add_edge("inject_system", "assistant")builder.add_conditional_edges("assistant",tool_condition_once)builder.add_edge("tools", "assistant")# recursion_limit์ ์์ ์ฅ์นreturn builder.compile(recursion_limit=10)# =========================================================# Public API (app.py์์ ์ฌ์ฉ)# =========================================================class BasicAgent:def __init__(self):self.graph = build_agent()print("โ LangGraph GPT-4o-mini Agent initialized (tool loop fixed)")def __call__(self, question: str) -> str:result = self.graph.invoke({"messages": [HumanMessage(content=question)],"used_tools": False,})return result["messages"][-1].content.strip()
123456789101112131415161718gradio==5.25.2requests>=2.31.0langgraph>=0.2.40langchain-core>=0.3.30langchain-community>=0.3.15langchain-openai>=0.3.0langchain-huggingface>=0.1.2sentence-transformers>=3.0.0duckduckgo-search>=6.3.0ddgs>=6.1.0faiss-cpu>=1.8.0wikipedia>=1.4.0arxiv>=2.1.0123456789101112131415gradiorequestslanggraphlangchainlangchain_corelangchain-communitylangchain_openailangchain-huggingfacesentence-transformersfaiss-cpuddgsduckduckgo-searchwikipediaarxivpymupdf
agent.py+68-63
requirements.txt+15-18