File size: 1,419 Bytes
182bc33
 
 
 
78bd8e4
470200d
182bc33
3af4c1f
 
fd74375
3af4c1f
fd74375
3af4c1f
182bc33
 
 
 
 
 
 
 
 
0fdfad8
 
baac347
182bc33
c759b04
a840aab
470200d
ad5d060
182bc33
 
 
cee3659
182bc33
 
a840aab
182bc33
 
 
baac347
182bc33
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from langchain import hub
from langchain.agents import AgentExecutor, create_react_agent
from langchain_openai import OpenAI
from langchain_community.tools import DuckDuckGoSearchResults
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain.tools import tool

@tool
def search(query: str) -> str:
    """Search things online"""
    retriever = DuckDuckGoSearchResults()
    return retriever.run(query)
    
class ReActAgent:
  """
  A LangChain agent class with conversation history for contextual processing.
  """

  def __init__(self):
    """
    Initializes the agent with default tools, OpenAI LLM, and an empty history.
    """
    self.tools = [TavilySearchResults(max_results=15)]
    # self.tools = [DuckDuckGoSearchResults()]
    self.prompt = hub.pull("hwchase17/react-chat")
    self.llm = OpenAI()
    agent = self.create_agent()
    self.agent_executor = AgentExecutor(agent=agent, tools=self.tools, verbose=True)
  
  def create_agent(self):
    """
    Creates a ReAct agent based on the defined prompt, LLM, and history.
    """
    agent = create_react_agent(self.llm, self.tools, self.prompt)
    return agent

  def run(self, question,history=""):
    """
    Executes the agent with the provided question, verbosity option, and updates history.
    """
    answer = self.agent_executor.invoke({"input": question, "chat_history": history})
    return answer