shubhamgs commited on
Commit
a6c98bd
·
verified ·
1 Parent(s): 295e974

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -78
app.py CHANGED
@@ -1,79 +1,184 @@
1
- import streamlit as st
2
- from deep_research_system import run_deep_research_system
3
- import traceback
4
- import streamlit.components.v1 as components
5
-
6
- # Set page configuration
7
- st.set_page_config(page_title="Deep Research AI", layout="centered")
8
-
9
- # Title and instructions
10
- st.title("Deep Research AI Agentic System")
11
- st.write("Enter a question below to get the latest insights from web research. Click 'Reset' to start over.")
12
-
13
- # Initialize session state
14
- if "show_reset_button" not in st.session_state:
15
- st.session_state.show_reset_button = False
16
- if "question" not in st.session_state:
17
- st.session_state.question = ""
18
- if "reset_triggered" not in st.session_state:
19
- st.session_state.reset_triggered = False
20
-
21
- # JavaScript to clear the input field
22
- clear_input_js = """
23
- <script>
24
- const input = window.parent.document.querySelector('input[aria-label="Your Question"]');
25
- if (input) {
26
- input.value = '';
27
- }
28
- </script>
29
- """
30
-
31
- # Use a form to manage the question input and submission
32
- with st.form(key="question_form"):
33
- st.session_state.question = st.text_input(
34
- "Your Question",
35
- placeholder="e.g., What are the latest advancements in quantum computing?",
36
- value=st.session_state.question,
37
- key="question_input"
38
- )
39
- submit_button = st.form_submit_button("Get Answer")
40
-
41
- # Process the form submission
42
- if submit_button:
43
- if st.session_state.question:
44
- st.write(f"Research Agent: Searching for '{st.session_state.question}'...")
45
- try:
46
- with st.spinner("Gathering research data..."):
47
- answer = run_deep_research_system(st.session_state.question)
48
- st.write("Research Agent: Found 5 relevant sources.")
49
- st.write("Answer Drafter Agent: Drafted the final answer.")
50
- st.write("**Final Answer:**")
51
- st.write(answer)
52
- st.session_state.show_reset_button = True
53
- except Exception as e:
54
- st.error(f"An error occurred: {str(e)}\n{traceback.format_exc()}")
55
- st.session_state.show_reset_button = True
56
- else:
57
- st.warning("Please enter a question!")
58
- # Reset the trigger flag after submission
59
- st.session_state.reset_triggered = False
60
-
61
- # Function to clear the input state
62
- def clear_input():
63
- st.session_state.show_reset_button = False
64
- st.session_state.question = ""
65
- st.session_state.pop("question_input", None)
66
- st.session_state.pop("question_form", None)
67
- st.session_state.reset_triggered = True
68
-
69
- # Show Reset button only if show_reset_button is True
70
- if st.session_state.show_reset_button:
71
- if st.button("Reset"):
72
- # Clear the input and reset state
73
- clear_input()
74
- # Refresh the webpage
75
- st.rerun()
76
-
77
- # Execute JavaScript to clear the input field if reset was triggered
78
- if st.session_state.reset_triggered:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  components.html(clear_input_js, height=0)
 
1
+
2
+ import os
3
+ import traceback
4
+ import streamlit as st
5
+ from dotenv import load_dotenv
6
+ from tavily import TavilyClient
7
+ from langchain_openai import ChatOpenAI
8
+ from typing import Dict, TypedDict, List
9
+ from langgraph.graph import StateGraph, END
10
+ import streamlit.components.v1 as components
11
+ from langchain_core.prompts import ChatPromptTemplate
12
+
13
+ # Load environment variables
14
+ load_dotenv()
15
+
16
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
17
+ TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
18
+
19
+ # Initialize the LLM (using OpenAI as an example, replace with your preferred model)
20
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
21
+
22
+ # Initialize Tavily client for web search
23
+ tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
24
+
25
+ # Define the shared state for the agents
26
+ class ResearchState(TypedDict):
27
+ query: str
28
+ research_data: List[Dict]
29
+ final_answer: str
30
+
31
+ # Research Agent: Crawls the web and gathers information
32
+ def research_agent(state: ResearchState) -> ResearchState:
33
+ query = state["query"]
34
+ print(f"Research Agent: Searching for '{query}'...")
35
+
36
+ # Use Tavily to search the web
37
+ search_results = tavily_client.search(query, max_results=5)
38
+
39
+ # Extract relevant information from search results
40
+ research_data = []
41
+ for result in search_results["results"]:
42
+ research_data.append({
43
+ "title": result["title"],
44
+ "url": result["url"],
45
+ "content": result["content"][:500] # Limit content length for brevity
46
+ })
47
+
48
+ print(f"Research Agent: Found {len(research_data)} relevant sources.")
49
+ return {"research_data": research_data}
50
+
51
+ # Answer Drafter Agent: Processes research data and drafts a response
52
+ def answer_drafter_agent(state: ResearchState) -> ResearchState:
53
+ research_data = state["research_data"]
54
+ query = state["query"]
55
+
56
+ # Create a prompt for the answer drafter
57
+ prompt = ChatPromptTemplate.from_template(
58
+ """
59
+ You are an expert at drafting concise and accurate answers. Based on the following research data, provide a clear and informative response to the query: "{query}".
60
+ Research Data:
61
+ {research_data}
62
+ Provide a well-structured answer in 3-5 sentences, citing the sources where relevant.
63
+ """
64
+ )
65
+
66
+ # Format the research data for the prompt
67
+ research_text = "\n".join([f"- {item['title']}: {item['content']} (Source: {item['url']})" for item in research_data])
68
+ chain = prompt | llm
69
+
70
+ # Generate the final answer
71
+ response = chain.invoke({"query": query, "research_data": research_text})
72
+ final_answer = response.content
73
+
74
+ print("Answer Drafter Agent: Drafted the final answer.")
75
+ return {"final_answer": final_answer}
76
+
77
+ # Define the LangGraph workflow
78
+ def create_workflow():
79
+ workflow = StateGraph(ResearchState)
80
+
81
+ # Add nodes for each agent
82
+ workflow.add_node("research_agent", research_agent)
83
+ workflow.add_node("answer_drafter_agent", answer_drafter_agent)
84
+
85
+ # Define the flow: Research Agent -> Answer Drafter Agent -> End
86
+ workflow.add_edge("research_agent", "answer_drafter_agent")
87
+ workflow.add_edge("answer_drafter_agent", END)
88
+
89
+ # Set the entry point
90
+ workflow.set_entry_point("research_agent")
91
+
92
+ return workflow.compile()
93
+
94
+ # Main function to run the system
95
+ def run_deep_research_system(query: str) -> str:
96
+ # Initialize the workflow
97
+ app = create_workflow()
98
+
99
+ # Initial state
100
+ initial_state = {
101
+ "query": query,
102
+ "research_data": [],
103
+ "final_answer": ""
104
+ }
105
+
106
+ # Run the workflow
107
+ final_state = app.invoke(initial_state)
108
+
109
+ return final_state["final_answer"]
110
+
111
+ # Set page configuration
112
+ st.set_page_config(page_title="Deep Research AI", layout="centered")
113
+
114
+ # Title and instructions
115
+ st.title("Deep Research AI Agentic System")
116
+ st.write("Enter a question below to get the latest insights from web research. Click 'Reset' to start over.")
117
+
118
+ # Initialize session state
119
+ if "show_reset_button" not in st.session_state:
120
+ st.session_state.show_reset_button = False
121
+ if "question" not in st.session_state:
122
+ st.session_state.question = ""
123
+ if "reset_triggered" not in st.session_state:
124
+ st.session_state.reset_triggered = False
125
+
126
+ # JavaScript to clear the input field
127
+ clear_input_js = """
128
+ <script>
129
+ const input = window.parent.document.querySelector('input[aria-label="Your Question"]');
130
+ if (input) {
131
+ input.value = '';
132
+ }
133
+ </script>
134
+ """
135
+
136
+ # Use a form to manage the question input and submission
137
+ with st.form(key="question_form"):
138
+ st.session_state.question = st.text_input(
139
+ "Your Question",
140
+ placeholder="e.g., What are the latest advancements in quantum computing?",
141
+ value=st.session_state.question,
142
+ key="question_input"
143
+ )
144
+ submit_button = st.form_submit_button("Get Answer")
145
+
146
+ # Process the form submission
147
+ if submit_button:
148
+ if st.session_state.question:
149
+ st.write(f"Research Agent: Searching for '{st.session_state.question}'...")
150
+ try:
151
+ with st.spinner("Gathering research data..."):
152
+ answer = run_deep_research_system(st.session_state.question)
153
+ st.write("Research Agent: Found 5 relevant sources.")
154
+ st.write("Answer Drafter Agent: Drafted the final answer.")
155
+ st.write("**Final Answer:**")
156
+ st.write(answer)
157
+ st.session_state.show_reset_button = True
158
+ except Exception as e:
159
+ st.error(f"An error occurred: {str(e)}\n{traceback.format_exc()}")
160
+ st.session_state.show_reset_button = True
161
+ else:
162
+ st.warning("Please enter a question!")
163
+ # Reset the trigger flag after submission
164
+ st.session_state.reset_triggered = False
165
+
166
+ # Function to clear the input state
167
+ def clear_input():
168
+ st.session_state.show_reset_button = False
169
+ st.session_state.question = ""
170
+ st.session_state.pop("question_input", None)
171
+ st.session_state.pop("question_form", None)
172
+ st.session_state.reset_triggered = True
173
+
174
+ # Show Reset button only if show_reset_button is True
175
+ if st.session_state.show_reset_button:
176
+ if st.button("Reset"):
177
+ # Clear the input and reset state
178
+ clear_input()
179
+ # Refresh the webpage
180
+ st.rerun()
181
+
182
+ # Execute JavaScript to clear the input field if reset was triggered
183
+ if st.session_state.reset_triggered:
184
  components.html(clear_input_js, height=0)