Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +83 -0
- deep_research_system.py +126 -0
app.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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)
|
deep_research_system.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
from tavily import TavilyClient
|
| 4 |
+
from langchain_openai import ChatOpenAI
|
| 5 |
+
from typing import Dict, TypedDict, List
|
| 6 |
+
from langgraph.graph import StateGraph, END
|
| 7 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 8 |
+
|
| 9 |
+
# Load environment variables
|
| 10 |
+
load_dotenv()
|
| 11 |
+
|
| 12 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 13 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 14 |
+
|
| 15 |
+
# Check if API keys are set
|
| 16 |
+
try:
|
| 17 |
+
if not OPENAI_API_KEY or not TAVILY_API_KEY:
|
| 18 |
+
raise ValueError("API keys for OpenAI and Tavily must be set in environment variables.")
|
| 19 |
+
except ValueError as e:
|
| 20 |
+
print(f"Error: {e}")
|
| 21 |
+
raise
|
| 22 |
+
|
| 23 |
+
# Initialize the LLM and Tavily client
|
| 24 |
+
try:
|
| 25 |
+
# Initialize the LLM (using OpenAI as an example, replace with your preferred model)
|
| 26 |
+
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
|
| 27 |
+
# Initialize Tavily client for web search
|
| 28 |
+
tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"Error initializing LLM or Tavily client: {e}")
|
| 31 |
+
raise
|
| 32 |
+
|
| 33 |
+
# Define the shared state for the agents
|
| 34 |
+
class ResearchState(TypedDict):
|
| 35 |
+
query: str
|
| 36 |
+
research_data: List[Dict]
|
| 37 |
+
final_answer: str
|
| 38 |
+
|
| 39 |
+
# Research Agent: Crawls the web and gathers information
|
| 40 |
+
def research_agent(state: ResearchState) -> ResearchState:
|
| 41 |
+
query = state["query"]
|
| 42 |
+
print(f"Research Agent: Searching for '{query}'...")
|
| 43 |
+
|
| 44 |
+
# Use Tavily to search the web
|
| 45 |
+
search_results = tavily_client.search(query, max_results=5)
|
| 46 |
+
|
| 47 |
+
# Extract relevant information from search results
|
| 48 |
+
research_data = []
|
| 49 |
+
for result in search_results["results"]:
|
| 50 |
+
research_data.append({
|
| 51 |
+
"title": result["title"],
|
| 52 |
+
"url": result["url"],
|
| 53 |
+
"content": result["content"][:500] # Limit content length for brevity
|
| 54 |
+
})
|
| 55 |
+
|
| 56 |
+
print(f"Research Agent: Found {len(research_data)} relevant sources.")
|
| 57 |
+
return {"research_data": research_data}
|
| 58 |
+
|
| 59 |
+
# Answer Drafter Agent: Processes research data and drafts a response
|
| 60 |
+
def answer_drafter_agent(state: ResearchState) -> ResearchState:
|
| 61 |
+
research_data = state["research_data"]
|
| 62 |
+
query = state["query"]
|
| 63 |
+
|
| 64 |
+
# Create a prompt for the answer drafter
|
| 65 |
+
prompt = ChatPromptTemplate.from_template(
|
| 66 |
+
"""
|
| 67 |
+
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}".
|
| 68 |
+
|
| 69 |
+
Research Data:
|
| 70 |
+
{research_data}
|
| 71 |
+
|
| 72 |
+
Provide a well-structured answer in 3-5 sentences, citing the sources where relevant.
|
| 73 |
+
"""
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Format the research data for the prompt
|
| 77 |
+
research_text = "\n".join([f"- {item['title']}: {item['content']} (Source: {item['url']})" for item in research_data])
|
| 78 |
+
chain = prompt | llm
|
| 79 |
+
|
| 80 |
+
# Generate the final answer
|
| 81 |
+
response = chain.invoke({"query": query, "research_data": research_text})
|
| 82 |
+
final_answer = response.content
|
| 83 |
+
|
| 84 |
+
print("Answer Drafter Agent: Drafted the final answer.")
|
| 85 |
+
return {"final_answer": final_answer}
|
| 86 |
+
|
| 87 |
+
# Define the LangGraph workflow
|
| 88 |
+
def create_workflow():
|
| 89 |
+
workflow = StateGraph(ResearchState)
|
| 90 |
+
|
| 91 |
+
# Add nodes for each agent
|
| 92 |
+
workflow.add_node("research_agent", research_agent)
|
| 93 |
+
workflow.add_node("answer_drafter_agent", answer_drafter_agent)
|
| 94 |
+
|
| 95 |
+
# Define the flow: Research Agent -> Answer Drafter Agent -> End
|
| 96 |
+
workflow.add_edge("research_agent", "answer_drafter_agent")
|
| 97 |
+
workflow.add_edge("answer_drafter_agent", END)
|
| 98 |
+
|
| 99 |
+
# Set the entry point
|
| 100 |
+
workflow.set_entry_point("research_agent")
|
| 101 |
+
|
| 102 |
+
return workflow.compile()
|
| 103 |
+
|
| 104 |
+
# Main function to run the system
|
| 105 |
+
def run_deep_research_system(query: str) -> str:
|
| 106 |
+
# Initialize the workflow
|
| 107 |
+
app = create_workflow()
|
| 108 |
+
|
| 109 |
+
# Initial state
|
| 110 |
+
initial_state = {
|
| 111 |
+
"query": query,
|
| 112 |
+
"research_data": [],
|
| 113 |
+
"final_answer": ""
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# Run the workflow
|
| 117 |
+
final_state = app.invoke(initial_state)
|
| 118 |
+
|
| 119 |
+
return final_state["final_answer"]
|
| 120 |
+
|
| 121 |
+
# Example usage
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
query = "What are the latest advancements in quantum computing?"
|
| 124 |
+
answer = run_deep_research_system(query)
|
| 125 |
+
print("\nFinal Answer:")
|
| 126 |
+
print(answer)
|