rsobieski commited on
Commit
052837d
Β·
verified Β·
1 Parent(s): 6a63b68

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +34 -33
agent.py CHANGED
@@ -2,11 +2,10 @@ import os
2
  import pandas as pd
3
  from langchain_core.messages import HumanMessage, AIMessage
4
  from langgraph.graph import StateGraph, MessagesState
5
- from langgraph.prebuilt import ToolNode, tools_condition
6
- from langchain_community.chat_models import ChatHuggingFace
7
- from tools import TOOLS
8
 
9
- # --- Load local QA metadata for retriever ---
10
  QA_PATH = "metadata.jsonl"
11
  qa_pairs = pd.read_json(QA_PATH, lines=True)
12
  qa_dict = {
@@ -15,14 +14,13 @@ qa_dict = {
15
  }
16
 
17
  def build_graph():
18
- # βœ… Use correct conversational wrapper for Hugging Face models
19
- llm = ChatHuggingFace(
20
  repo_id="mistralai/Mistral-7B-Instruct-v0.3",
21
- task="conversational",
22
  huggingfacehub_api_token=os.environ["HF_TOKEN"]
23
  )
24
 
25
- # Node 1: Retriever
26
  def retriever_node(state: MessagesState):
27
  query = state["messages"][-1].content.strip()
28
  if query in qa_dict:
@@ -31,45 +29,47 @@ def build_graph():
31
  print("πŸ” No match. Sending to LLM.")
32
  return {"messages": state["messages"]}
33
 
34
- # Node 2: Assistant
35
  def assistant_node(state: MessagesState):
36
  query = state["messages"][-1].content.strip()
37
- prompt = (
38
- "You are a helpful assistant in the GAIA benchmark.\n"
39
- "If you know the answer, reply directly with only the answer.\n"
40
- "If tool use is needed, reply in the format:\n"
41
- "use_tool: <tool_name>: <tool_input>\n"
42
- "Do not explain anything."
 
 
43
  )
 
44
  messages = [
45
- {"role": "system", "content": prompt},
46
  {"role": "user", "content": query},
47
  ]
48
- response = llm.invoke(messages).strip()
49
- print(f"🧠 LLM responded: {response}")
50
 
51
- if response.lower().startswith("use_tool:"):
52
- return {
53
- "messages": state["messages"] + [AIMessage(content=response)],
54
- "tool_call": response,
55
- }
56
- return {"messages": [AIMessage(content=response)]}
57
 
58
- # Node 3: Tool Executor
59
  def tool_node(state: MessagesState):
60
  try:
61
  tool_signal = state.get("tool_call", "")
62
  _, tool_name, tool_input = tool_signal.split(":", 2)
63
- tool_fn = TOOLS.get(tool_name.strip())
 
 
 
64
  if not tool_fn:
65
  print(f"❌ Unknown tool: {tool_name}")
66
  return {"messages": [AIMessage(content="Unknown")]}
67
- print(f"πŸ”§ Running tool {tool_name} with input: {tool_input}")
68
- result = tool_fn(tool_input.strip())
69
- return {"messages": [AIMessage(content=str(result))]}
 
 
70
  except Exception as e:
71
  print(f"⚠️ Tool error: {e}")
72
- return {"messages": [AIMessage(content="Unknown")]}
73
 
74
  # Build LangGraph
75
  builder = StateGraph(MessagesState)
@@ -85,8 +85,7 @@ def build_graph():
85
 
86
  return builder.compile()
87
 
88
-
89
- # --- Final Agent Wrapper ---
90
  class BasicAgent:
91
  def __init__(self):
92
  print("βœ… BasicAgent initialized with retriever + LLM + tools")
@@ -95,4 +94,6 @@ class BasicAgent:
95
  def __call__(self, question: str) -> str:
96
  print(f"πŸ“₯ Question: {question[:100]}")
97
  result = self.graph.invoke({"messages": [HumanMessage(content=question)]})
98
- return result["messages"][-1].content.strip()
 
 
 
2
  import pandas as pd
3
  from langchain_core.messages import HumanMessage, AIMessage
4
  from langgraph.graph import StateGraph, MessagesState
5
+ from langchain_huggingface import HuggingFaceEndpoint
6
+ from tools import TOOLS
 
7
 
8
+ # --- Read local QA data for retriever ---
9
  QA_PATH = "metadata.jsonl"
10
  qa_pairs = pd.read_json(QA_PATH, lines=True)
11
  qa_dict = {
 
14
  }
15
 
16
  def build_graph():
17
+ # Initialize Mistral model
18
+ llm = HuggingFaceEndpoint(
19
  repo_id="mistralai/Mistral-7B-Instruct-v0.3",
 
20
  huggingfacehub_api_token=os.environ["HF_TOKEN"]
21
  )
22
 
23
+ # Retriever node
24
  def retriever_node(state: MessagesState):
25
  query = state["messages"][-1].content.strip()
26
  if query in qa_dict:
 
29
  print("πŸ” No match. Sending to LLM.")
30
  return {"messages": state["messages"]}
31
 
32
+ # Assistant node (LLM)
33
  def assistant_node(state: MessagesState):
34
  query = state["messages"][-1].content.strip()
35
+
36
+ system_prompt = (
37
+ "You are a helpful assistant evaluated by the GAIA benchmark.\n"
38
+ "Only return the final answer, with no explanations.\n"
39
+ "- No prefixes like 'Final answer:'\n"
40
+ "- If it's a list, output comma-separated\n"
41
+ "- If unknown, say 'Unknown'\n"
42
+ "- Never justify or explain"
43
  )
44
+
45
  messages = [
46
+ {"role": "system", "content": system_prompt},
47
  {"role": "user", "content": query},
48
  ]
 
 
49
 
50
+ response = llm.invoke(messages)
51
+ return {"messages": [AIMessage(content=response.strip())]}
 
 
 
 
52
 
53
+ # Tool node
54
  def tool_node(state: MessagesState):
55
  try:
56
  tool_signal = state.get("tool_call", "")
57
  _, tool_name, tool_input = tool_signal.split(":", 2)
58
+ tool_name = tool_name.strip()
59
+ tool_input = tool_input.strip()
60
+ tool_fn = TOOLS.get(tool_name)
61
+
62
  if not tool_fn:
63
  print(f"❌ Unknown tool: {tool_name}")
64
  return {"messages": [AIMessage(content="Unknown")]}
65
+
66
+ print(f"πŸ”§ Using tool: {tool_name} with input: {tool_input}")
67
+ tool_result = tool_fn(tool_input)
68
+ return {"messages": [AIMessage(content=str(tool_result))]}
69
+
70
  except Exception as e:
71
  print(f"⚠️ Tool error: {e}")
72
+ return {"messages": [AIMessage(content="Unknown")]} # fail-safe
73
 
74
  # Build LangGraph
75
  builder = StateGraph(MessagesState)
 
85
 
86
  return builder.compile()
87
 
88
+ # Agent class
 
89
  class BasicAgent:
90
  def __init__(self):
91
  print("βœ… BasicAgent initialized with retriever + LLM + tools")
 
94
  def __call__(self, question: str) -> str:
95
  print(f"πŸ“₯ Question: {question[:100]}")
96
  result = self.graph.invoke({"messages": [HumanMessage(content=question)]})
97
+ answer = result["messages"][-1].content.strip()
98
+ print(f"πŸ“€ Answer: {answer}")
99
+ return answer