Update app.py
Browse files
app.py
CHANGED
|
@@ -1,140 +1,140 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import os
|
| 3 |
-
from dotenv import load_dotenv
|
| 4 |
-
from tavily import TavilyClient
|
| 5 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 6 |
-
from langchain.agents import AgentExecutor, Tool
|
| 7 |
-
from langchain.agents import create_tool_calling_agent
|
| 8 |
-
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 9 |
-
from langgraph.graph import END, Graph
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
load_dotenv()
|
| 13 |
-
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 14 |
-
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 15 |
-
|
| 16 |
-
llm = ChatGoogleGenerativeAI(
|
| 17 |
-
model="gemini-2.0-flash",
|
| 18 |
-
temperature=0.7,
|
| 19 |
-
google_api_key=GOOGLE_API_KEY
|
| 20 |
-
)
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
|
| 24 |
-
|
| 25 |
-
def tavily_search(query: str):
|
| 26 |
-
try:
|
| 27 |
-
result = tavily_client.search(
|
| 28 |
-
query=query,
|
| 29 |
-
search_depth="advanced",
|
| 30 |
-
include_raw_content=True
|
| 31 |
-
)
|
| 32 |
-
return str(result)
|
| 33 |
-
except Exception as e:
|
| 34 |
-
return f"Error searching Tavily: {str(e)}"
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
tavily_tool = Tool(
|
| 38 |
-
name="tavily_search",
|
| 39 |
-
func=tavily_search,
|
| 40 |
-
description="A premium search engine that returns high-quality, up-to-date information."
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def create_researcher_agent():
|
| 45 |
-
prompt = ChatPromptTemplate.from_messages([
|
| 46 |
-
("system", """You are a senior research analyst. Your job:
|
| 47 |
-
1. Use Tavily for authoritative info.
|
| 48 |
-
2. Cross-validate across multiple sources.
|
| 49 |
-
3. Extract key facts, stats & quotes.
|
| 50 |
-
4. Always include source URLs."""),
|
| 51 |
-
("user", "{input}"),
|
| 52 |
-
MessagesPlaceholder(variable_name="agent_scratchpad")
|
| 53 |
-
])
|
| 54 |
-
agent = create_tool_calling_agent(llm, [tavily_tool], prompt)
|
| 55 |
-
return AgentExecutor(agent=agent, tools=[tavily_tool])
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def generate_final_report(research_output: str) -> str:
|
| 59 |
-
prompt = ChatPromptTemplate.from_messages([
|
| 60 |
-
("system", """You are a technical writer. Structure and present the research:
|
| 61 |
-
- Use markdown formatting
|
| 62 |
-
- Academic tone
|
| 63 |
-
- Include proper citations
|
| 64 |
-
- Highlight insights.
|
| 65 |
-
- Make sure to answer the user's original query completely."""),
|
| 66 |
-
("user", "{input}")
|
| 67 |
-
])
|
| 68 |
-
formatted_prompt = prompt.format_messages(input=research_output)
|
| 69 |
-
return llm.invoke(formatted_prompt).content
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def create_workflow():
|
| 73 |
-
workflow = Graph()
|
| 74 |
-
|
| 75 |
-
def research_node(state):
|
| 76 |
-
agent = create_researcher_agent()
|
| 77 |
-
output = agent.invoke({"input": state["query"], "agent_scratchpad": []})
|
| 78 |
-
return {"research_output": output["output"]}
|
| 79 |
-
|
| 80 |
-
def write_node(state):
|
| 81 |
-
report = generate_final_report(state["research_output"])
|
| 82 |
-
return {"final_report": report}
|
| 83 |
-
|
| 84 |
-
workflow.add_node("research", research_node)
|
| 85 |
-
workflow.add_node("write", write_node)
|
| 86 |
-
workflow.add_edge("research", "write")
|
| 87 |
-
workflow.add_edge("write", END)
|
| 88 |
-
workflow.set_entry_point("research")
|
| 89 |
-
return workflow
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
def main():
|
| 93 |
-
st.set_page_config(page_title="AI Research Assistant", page_icon="π", layout="wide")
|
| 94 |
-
st.title("
|
| 95 |
-
st.markdown("""Enter a query and let the AI prepare a research-backed report:
|
| 96 |
-
- Searches authoritative sources
|
| 97 |
-
- Validates information
|
| 98 |
-
- Delivers a professional markdown report.
|
| 99 |
-
""")
|
| 100 |
-
|
| 101 |
-
query = st.text_area("Enter your research query:",
|
| 102 |
-
placeholder="e.g., 'Impact of AI on healthcare jobs in 2024'",
|
| 103 |
-
height=100)
|
| 104 |
-
|
| 105 |
-
if st.button("Research", type="primary"):
|
| 106 |
-
if not query:
|
| 107 |
-
st.warning("Please enter a research query first.")
|
| 108 |
-
return
|
| 109 |
-
|
| 110 |
-
if not GOOGLE_API_KEY or not TAVILY_API_KEY:
|
| 111 |
-
st.error(" API keys missing! Check your `.env` file.")
|
| 112 |
-
return
|
| 113 |
-
|
| 114 |
-
with st.spinner("Researching your topic..."):
|
| 115 |
-
try:
|
| 116 |
-
workflow = create_workflow()
|
| 117 |
-
app = workflow.compile()
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
final_output = app.invoke({"query": query})
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
with st.expander(" Research Report", expanded=True):
|
| 124 |
-
if "final_report" in final_output:
|
| 125 |
-
st.markdown(final_output["final_report"])
|
| 126 |
-
elif "research_output" in final_output:
|
| 127 |
-
st.markdown("### Research Findings (Unformatted)")
|
| 128 |
-
st.markdown(final_output["research_output"])
|
| 129 |
-
else:
|
| 130 |
-
st.warning("No results were generated")
|
| 131 |
-
|
| 132 |
-
st.success(" Research completed!")
|
| 133 |
-
|
| 134 |
-
except Exception as e:
|
| 135 |
-
st.error(f" An error occurred: {str(e)}")
|
| 136 |
-
st.exception(e)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
if __name__ == "__main__":
|
| 140 |
main()
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from tavily import TavilyClient
|
| 5 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 6 |
+
from langchain.agents import AgentExecutor, Tool
|
| 7 |
+
from langchain.agents import create_tool_calling_agent
|
| 8 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 9 |
+
from langgraph.graph import END, Graph
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 14 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 15 |
+
|
| 16 |
+
llm = ChatGoogleGenerativeAI(
|
| 17 |
+
model="gemini-2.0-flash",
|
| 18 |
+
temperature=0.7,
|
| 19 |
+
google_api_key=GOOGLE_API_KEY
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
|
| 24 |
+
|
| 25 |
+
def tavily_search(query: str):
|
| 26 |
+
try:
|
| 27 |
+
result = tavily_client.search(
|
| 28 |
+
query=query,
|
| 29 |
+
search_depth="advanced",
|
| 30 |
+
include_raw_content=True
|
| 31 |
+
)
|
| 32 |
+
return str(result)
|
| 33 |
+
except Exception as e:
|
| 34 |
+
return f"Error searching Tavily: {str(e)}"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
tavily_tool = Tool(
|
| 38 |
+
name="tavily_search",
|
| 39 |
+
func=tavily_search,
|
| 40 |
+
description="A premium search engine that returns high-quality, up-to-date information."
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def create_researcher_agent():
|
| 45 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 46 |
+
("system", """You are a senior research analyst. Your job:
|
| 47 |
+
1. Use Tavily for authoritative info.
|
| 48 |
+
2. Cross-validate across multiple sources.
|
| 49 |
+
3. Extract key facts, stats & quotes.
|
| 50 |
+
4. Always include source URLs."""),
|
| 51 |
+
("user", "{input}"),
|
| 52 |
+
MessagesPlaceholder(variable_name="agent_scratchpad")
|
| 53 |
+
])
|
| 54 |
+
agent = create_tool_calling_agent(llm, [tavily_tool], prompt)
|
| 55 |
+
return AgentExecutor(agent=agent, tools=[tavily_tool])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def generate_final_report(research_output: str) -> str:
|
| 59 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 60 |
+
("system", """You are a technical writer. Structure and present the research:
|
| 61 |
+
- Use markdown formatting
|
| 62 |
+
- Academic tone
|
| 63 |
+
- Include proper citations
|
| 64 |
+
- Highlight insights.
|
| 65 |
+
- Make sure to answer the user's original query completely."""),
|
| 66 |
+
("user", "{input}")
|
| 67 |
+
])
|
| 68 |
+
formatted_prompt = prompt.format_messages(input=research_output)
|
| 69 |
+
return llm.invoke(formatted_prompt).content
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def create_workflow():
|
| 73 |
+
workflow = Graph()
|
| 74 |
+
|
| 75 |
+
def research_node(state):
|
| 76 |
+
agent = create_researcher_agent()
|
| 77 |
+
output = agent.invoke({"input": state["query"], "agent_scratchpad": []})
|
| 78 |
+
return {"research_output": output["output"]}
|
| 79 |
+
|
| 80 |
+
def write_node(state):
|
| 81 |
+
report = generate_final_report(state["research_output"])
|
| 82 |
+
return {"final_report": report}
|
| 83 |
+
|
| 84 |
+
workflow.add_node("research", research_node)
|
| 85 |
+
workflow.add_node("write", write_node)
|
| 86 |
+
workflow.add_edge("research", "write")
|
| 87 |
+
workflow.add_edge("write", END)
|
| 88 |
+
workflow.set_entry_point("research")
|
| 89 |
+
return workflow
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def main():
|
| 93 |
+
st.set_page_config(page_title="AI Research Assistant", page_icon="π", layout="wide")
|
| 94 |
+
st.title(" AI Research Assistant")
|
| 95 |
+
st.markdown("""Enter a query and let the AI prepare a research-backed report:
|
| 96 |
+
- Searches authoritative sources
|
| 97 |
+
- Validates information
|
| 98 |
+
- Delivers a professional markdown report.
|
| 99 |
+
""")
|
| 100 |
+
|
| 101 |
+
query = st.text_area("Enter your research query:",
|
| 102 |
+
placeholder="e.g., 'Impact of AI on healthcare jobs in 2024'",
|
| 103 |
+
height=100)
|
| 104 |
+
|
| 105 |
+
if st.button("Research", type="primary"):
|
| 106 |
+
if not query:
|
| 107 |
+
st.warning("Please enter a research query first.")
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
if not GOOGLE_API_KEY or not TAVILY_API_KEY:
|
| 111 |
+
st.error(" API keys missing! Check your `.env` file.")
|
| 112 |
+
return
|
| 113 |
+
|
| 114 |
+
with st.spinner("Researching your topic..."):
|
| 115 |
+
try:
|
| 116 |
+
workflow = create_workflow()
|
| 117 |
+
app = workflow.compile()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
final_output = app.invoke({"query": query})
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
with st.expander(" Research Report", expanded=True):
|
| 124 |
+
if "final_report" in final_output:
|
| 125 |
+
st.markdown(final_output["final_report"])
|
| 126 |
+
elif "research_output" in final_output:
|
| 127 |
+
st.markdown("### Research Findings (Unformatted)")
|
| 128 |
+
st.markdown(final_output["research_output"])
|
| 129 |
+
else:
|
| 130 |
+
st.warning("No results were generated")
|
| 131 |
+
|
| 132 |
+
st.success(" Research completed!")
|
| 133 |
+
|
| 134 |
+
except Exception as e:
|
| 135 |
+
st.error(f" An error occurred: {str(e)}")
|
| 136 |
+
st.exception(e)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
main()
|