shubhamgs commited on
Commit
81c2320
·
verified ·
1 Parent(s): 4b5ba84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -181
app.py CHANGED
@@ -1,184 +1,83 @@
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 = 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)
 
 
 
1
  import traceback
2
  import streamlit as st
 
 
 
 
 
3
  import streamlit.components.v1 as components
4
+ from deep_research_system import run_deep_research_system
5
+
6
+ if __name__ == "__main__":
7
+ # Define API base URL (Update for Hugging Face deployment)
8
+ API_URL = "http://localhost:8000/"
9
+
10
+ # Set page configuration
11
+ st.set_page_config(page_title="Deep Research AI", layout="centered")
12
+
13
+ # Title and instructions
14
+ st.title("Deep Research AI Agentic System")
15
+ st.write("Enter a question below to get the latest insights from web research. Click 'Reset' to start over.")
16
+
17
+ # Initialize session state
18
+ if "show_reset_button" not in st.session_state:
19
+ st.session_state.show_reset_button = False
20
+ if "question" not in st.session_state:
21
+ st.session_state.question = ""
22
+ if "reset_triggered" not in st.session_state:
23
+ st.session_state.reset_triggered = False
24
+
25
+ # JavaScript to clear the input field
26
+ clear_input_js = """
27
+ <script>
28
+ const input = document.querySelector('input[aria-label="Your Question"]');
29
+ if (input) {
30
+ input.value = '';
31
+ }
32
+ </script>
33
+ """
34
+
35
+ # Use a form to manage the question input and submission
36
+ with st.form(key="question_form"):
37
+ st.session_state.question = st.text_input(
38
+ "Your Question",
39
+ placeholder="e.g., What are the latest advancements in quantum computing?",
40
+ value=st.session_state.question,
41
+ key="question_input"
42
+ )
43
+ submit_button = st.form_submit_button("Get Answer")
44
+
45
+ # Process the form submission
46
+ if submit_button:
47
+ if st.session_state.question:
48
+ st.write(f"Research Agent: Searching for '{st.session_state.question}'...")
49
+ try:
50
+ with st.spinner("Gathering research data..."):
51
+ answer = run_deep_research_system(st.session_state.question)
52
+ st.write("Research Agent: Found 5 relevant sources.")
53
+ st.write("Answer Drafter Agent: Drafted the final answer.")
54
+ st.write("**Final Answer:**")
55
+ st.write(answer)
56
+ st.session_state.show_reset_button = True
57
+ except Exception as e:
58
+ st.error(f"An error occurred: {str(e)}\n{traceback.format_exc()}")
59
+ st.session_state.show_reset_button = True
60
+ else:
61
+ st.warning("Please enter a question!")
62
+ # Reset the trigger flag after submission
63
+ st.session_state.reset_triggered = False
64
+
65
+ # Function to clear the input state
66
+ def clear_input():
67
+ st.session_state.show_reset_button = False
68
+ st.session_state.question = ""
69
+ st.session_state.pop("question_input", None)
70
+ st.session_state.pop("question_form", None)
71
+ st.session_state.reset_triggered = True
72
+
73
+ # Show Reset button only if show_reset_button is True
74
+ if st.session_state.show_reset_button:
75
+ if st.button("Reset"):
76
+ # Clear the input and reset state
77
+ clear_input()
78
+ # Refresh the webpage
79
+ st.rerun()
80
+
81
+ # Execute JavaScript to clear the input field if reset was triggered
82
+ if st.session_state.reset_triggered:
83
+ components.html(clear_input_js, height=0)