BoddyGus commited on
Commit
aead7bf
·
verified ·
1 Parent(s): bc602f1

Updating BasicAgent by adding the DuckDuckGoSearch tool

Browse files
Files changed (1) hide show
  1. app.py +34 -1
app.py CHANGED
@@ -4,6 +4,16 @@ import requests
4
  import inspect
5
  import pandas as pd
6
 
 
 
 
 
 
 
 
 
 
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -13,9 +23,32 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
 
 
19
  print(f"Agent returning fixed answer: {fixed_answer}")
20
  return fixed_answer
21
 
 
4
  import inspect
5
  import pandas as pd
6
 
7
+ # LangGraph and LangChain imports
8
+
9
+ from langchain_community.tools import DuckDuckGoSearchRun
10
+ from langchain.tools import Tool
11
+ from langgraph.graph import START, StateGraph
12
+ from langgraph.prebuilt import ToolNode, tools_condition
13
+ from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
14
+ from typing import TypedDict, Annotated
15
+ from langgraph.graph.message import add_messages
16
+
17
  # (Keep Constants as is)
18
  # --- Constants ---
19
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
23
  class BasicAgent:
24
  def __init__(self):
25
  print("BasicAgent initialized.")
26
+
27
+ # initializing the DuckDuckGo tool
28
+ self.search_tool = DuckDuckGoSearchRun()
29
+ self.tools = [self.search_tool]
30
+
31
+ # building LangGraph agent
32
+ class AgentState(TypedDict):
33
+ messages: Annotated[list[AnyMessage], add_messages]
34
+
35
+ def assistant(state: AgentState):
36
+ user_message = state["messages"][-1]
37
+ if isinstance(user_message, HumanMessage):
38
+ result = self.search_tool.invoke(user_message.content)
39
+ return {"messages": [AIMessage(content=result)]}
40
+ return {"messages": [AIMessage(content="I can only answer human questions.")]}
41
+ builder = StateGraph(AgentState)
42
+ builder.add_node("assistant", assistant)
43
+ builder.add_edge(START, "assistant")
44
+ self.alfred = builder.compile()
45
+
46
+
47
  def __call__(self, question: str) -> str:
48
  print(f"Agent received question (first 50 chars): {question[:50]}...")
49
+ messages = [HumanMessage(content=question)]
50
+ response = self.alfred.invoke({"messages": messages})
51
+ fixed_answer = response["messages"][-1].content
52
  print(f"Agent returning fixed answer: {fixed_answer}")
53
  return fixed_answer
54