File size: 2,224 Bytes
750edfc
37856ac
 
 
750edfc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from typing import List, Dict, Any
from langchain.agents import create_openai_functions_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import BaseTool
from langchain_openai import ChatOpenAI

class ResearchAgent:
    def __init__(self, tools: List[BaseTool], openai_api_key: str):
        self.tools = tools
        self.llm = ChatOpenAI(
            temperature=0,
            model="gpt-4-turbo-preview",
            openai_api_key=openai_api_key
        )
        
        # Define the system prompt
        system_prompt = """You are a specialized research assistant focused on scientific literature analysis.
        Your goal is to help users find, analyze, and understand scientific papers and research findings.
        You have access to tools that can:
        1. Search for relevant papers and research
        2. Analyze PDF documents
        3. Track citations and research impact
        
        Always be thorough in your analysis and provide clear, well-structured responses.
        If you're unsure about something, be honest and ask for clarification."""
        
        # Create the prompt template
        prompt = ChatPromptTemplate.from_messages([
            ("system", system_prompt),
            MessagesPlaceholder(variable_name="chat_history"),
            ("human", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad"),
        ])
        
        # Create the agent
        self.agent = create_openai_functions_agent(
            llm=self.llm,
            prompt=prompt,
            tools=self.tools
        )
        
        # Create the agent executor
        self.agent_executor = AgentExecutor(
            agent=self.agent,
            tools=self.tools,
            verbose=False
        )
    
    def run(self, query: str, chat_history: List[Dict[str, Any]] = None) -> str:
        """Run the agent with the given query and chat history."""
        if chat_history is None:
            chat_history = []
            
        result = self.agent_executor.invoke({
            "input": query,
            "chat_history": chat_history
        })
        
        return result["output"]