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

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +28 -42
agent.py CHANGED
@@ -2,9 +2,9 @@ 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
6
- from langchain_huggingface import HuggingFaceEndpoint
7
- from tools import TOOLS # your dictionary of tool functions
8
 
9
  # --- Load local QA metadata for retriever ---
10
  QA_PATH = "metadata.jsonl"
@@ -14,11 +14,11 @@ qa_dict = {
14
  for _, row in qa_pairs.iterrows()
15
  }
16
 
17
- # === LangGraph builder ===
18
  def build_graph():
19
- llm = HuggingFaceEndpoint(
 
20
  repo_id="mistralai/Mistral-7B-Instruct-v0.3",
21
- # task="text-generation",
22
  huggingfacehub_api_token=os.environ["HF_TOKEN"]
23
  )
24
 
@@ -31,58 +31,45 @@ def build_graph():
31
  print("πŸ” No match. Sending to LLM.")
32
  return {"messages": state["messages"]}
33
 
34
- # Node 2: Assistant (LLM response parsing)
35
  def assistant_node(state: MessagesState):
36
  query = state["messages"][-1].content.strip()
37
-
38
  prompt = (
39
- "You are a helpful assistant for GAIA benchmark.\n"
40
- "If you can answer directly, output ONLY the answer.\n"
41
- "If you need to use a tool, reply in this format:\n"
42
  "use_tool: <tool_name>: <tool_input>\n"
43
- "Never explain anything."
44
  )
45
-
46
- full_prompt = f"{prompt}\n\nQuestion: {query}\nAnswer:"
47
-
48
-
49
- chat_input = [
50
  {"role": "system", "content": prompt},
51
- {"role": "user", "content": query}
52
  ]
53
- response = llm.invoke(chat_input).strip()
54
-
55
- # response = llm.invoke(full_prompt).strip()
56
- print(f"🧠 LLM said: {response}")
57
 
58
- if response.startswith("use_tool:"):
59
  return {
60
  "messages": state["messages"] + [AIMessage(content=response)],
61
- "tool_call": response # carry tool signal
62
  }
63
- else:
64
- return {"messages": [AIMessage(content=response)]}
65
 
66
- # Node 3: Tool execution
67
  def tool_node(state: MessagesState):
68
  try:
69
  tool_signal = state.get("tool_call", "")
70
  _, tool_name, tool_input = tool_signal.split(":", 2)
71
- tool_name = tool_name.strip()
72
- tool_input = tool_input.strip()
73
- tool_fn = TOOLS.get(tool_name)
74
-
75
  if not tool_fn:
76
  print(f"❌ Unknown tool: {tool_name}")
77
  return {"messages": [AIMessage(content="Unknown")]}
78
-
79
- print(f"πŸ”§ Using tool: {tool_name} with input: {tool_input}")
80
- tool_result = tool_fn(tool_input)
81
- return {"messages": [AIMessage(content=str(tool_result))]}
82
-
83
  except Exception as e:
84
  print(f"⚠️ Tool error: {e}")
85
- return {"messages": [AIMessage(content="Unknown")]} # fail-safe
86
 
87
  # Build LangGraph
88
  builder = StateGraph(MessagesState)
@@ -98,15 +85,14 @@ def build_graph():
98
 
99
  return builder.compile()
100
 
101
- # === BasicAgent wrapper ===
 
102
  class BasicAgent:
103
  def __init__(self):
104
- print("BasicAgent initialized with retriever + LLM + manual tool logic.")
105
  self.graph = build_graph()
106
 
107
  def __call__(self, question: str) -> str:
108
  print(f"πŸ“₯ Question: {question[:100]}")
109
  result = self.graph.invoke({"messages": [HumanMessage(content=question)]})
110
- answer = result["messages"][-1].content.strip()
111
- print(f"πŸ“€ Answer: {answer}")
112
- return answer
 
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"
 
14
  for _, row in qa_pairs.iterrows()
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
 
 
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
 
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")
93
  self.graph = build_graph()
94
 
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()