SoniAI commited on
Commit
f9267d4
·
verified ·
1 Parent(s): ad82b2d

Upload folder using huggingface_hub

Browse files
Files changed (12) hide show
  1. .gitignore +9 -0
  2. .python-version +1 -0
  3. README.md +2 -8
  4. deep_research.py +23 -0
  5. email_agent.py +31 -0
  6. main.py +6 -0
  7. planner_agent.py +23 -0
  8. pyproject.toml +13 -0
  9. research_manager.py +82 -0
  10. search_agent.py +17 -0
  11. uv.lock +0 -0
  12. writer_agent.py +27 -0
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+ .venv
9
+ .env
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Deep Research
3
- emoji: 😻
4
- colorFrom: red
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 6.2.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: deep-research
3
+ app_file: deep_research.py
 
 
4
  sdk: gradio
5
  sdk_version: 6.2.0
 
 
6
  ---
 
 
deep_research.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from dotenv import load_dotenv
3
+ from research_manager import ResearchManager
4
+
5
+ load_dotenv(override=True)
6
+
7
+
8
+ async def run(query: str):
9
+ async for chunk in ResearchManager().run(query):
10
+ yield chunk
11
+
12
+
13
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="sky")) as ui:
14
+ gr.Markdown("# Deep Research")
15
+ query_textbox = gr.Textbox(label="What topic would you like to research?")
16
+ run_button = gr.Button("Run", variant="primary")
17
+ report = gr.Markdown(label="Report")
18
+
19
+ run_button.click(fn=run, inputs=query_textbox, outputs=report)
20
+ query_textbox.submit(fn=run, inputs=query_textbox, outputs=report)
21
+
22
+ ui.launch(inbrowser=True)
23
+
email_agent.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Dict
3
+
4
+ import sendgrid
5
+ from sendgrid.helpers.mail import Email, Mail, Content, To
6
+ from agents import Agent, function_tool
7
+
8
+
9
+ @function_tool
10
+ def send_email(subject: str, html_body: str) -> Dict[str, str]:
11
+ """Send an email with the given subject and HTML body"""
12
+ sg = sendgrid.SendGridAPIClient(api_key=os.environ.get("SENDGRID_API_KEY"))
13
+ from_email = Email("evison.ndoni1@gmail.com")
14
+ to_email = To("endoni837@gmail.com")
15
+ content = Content("text/html", html_body)
16
+ mail = Mail(from_email, to_email, subject, content).get()
17
+ response = sg.client.mail.send.post(request_body=mail)
18
+ print("Email response", response.status_code)
19
+ return "success"
20
+
21
+
22
+ INSTRUCTIONS = """You are able to send a nicely formatted HTML email based on a detailed report.
23
+ You will be provided with a detailed report. You should use your tool to send one email, providing the
24
+ report converted into clean, well presented HTML with an appropriate subject line."""
25
+
26
+ email_agent = Agent(
27
+ name="Email agent",
28
+ instructions=INSTRUCTIONS,
29
+ tools=[send_email],
30
+ model="gpt-4o-mini",
31
+ )
main.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def main():
2
+ print("Hello from deep-research!")
3
+
4
+
5
+ if __name__ == "__main__":
6
+ main()
planner_agent.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from agents import Agent
3
+
4
+ HOW_MANY_SEARCHES = 1 # this number should be like 10 or more but i have left it at 1 because of api costs
5
+
6
+ INSTRUCTIONS = f"You are a helpful research assistant. Given a query, come up with a set of web searches \
7
+ to perform to best answer the query. Output {HOW_MANY_SEARCHES} terms to query for."
8
+
9
+
10
+ class WebSearchItem(BaseModel):
11
+ reason: str = Field(description="Your reasoning for why this search is important to the query.")
12
+ query: str = Field(description="The search term to use for the web search.")
13
+
14
+
15
+ class WebSearchPlan(BaseModel):
16
+ searches: list[WebSearchItem] = Field(description="A list of web searches to perform to best answer the query.")
17
+
18
+ planner_agent = Agent(
19
+ name="PlannerAgent",
20
+ instructions=INSTRUCTIONS,
21
+ model="gpt-4o-mini",
22
+ output_type=WebSearchPlan,
23
+ )
pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "deep-research"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ requires-python = ">=3.12"
6
+ dependencies = [
7
+ "gradio>=6.2.0",
8
+ "openai>=2.14.0",
9
+ "openai-agents>=0.6.4",
10
+ "pydantic>=2.12.5",
11
+ "python-dotenv>=1.2.1",
12
+ "sendgrid>=6.12.5",
13
+ ]
research_manager.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from agents import Runner, trace, gen_trace_id
2
+ from search_agent import search_agent
3
+ from planner_agent import planner_agent, WebSearchItem, WebSearchPlan
4
+ from writer_agent import writer_agent, ReportData
5
+ from email_agent import email_agent
6
+ import asyncio
7
+
8
+ class ResearchManager:
9
+
10
+ async def run(self, query: str):
11
+ """ Run the deep research process, yielding the status updates and the final report"""
12
+ trace_id = gen_trace_id()
13
+ with trace("Research trace", trace_id=trace_id):
14
+ print("Starting research...")
15
+ search_plan = await self.plan_searches(query)
16
+ yield "Searches planned, starting to search..."
17
+ search_results = await self.perform_searches(search_plan)
18
+ yield "Searches complete, writing report..."
19
+ report = await self.write_report(query, search_results)
20
+ yield "Report written, sending email..."
21
+ await self.send_email(report)
22
+ yield "Email sent, research complete"
23
+ yield report.markdown_report
24
+
25
+
26
+ async def plan_searches(self, query: str) -> WebSearchPlan:
27
+ """ Plan the searches to perform for the query """
28
+ print("Planning searches...")
29
+ result = await Runner.run(
30
+ planner_agent,
31
+ f"Query: {query}",
32
+ )
33
+ print(f"Will perform {len(result.final_output.searches)} searches")
34
+ return result.final_output_as(WebSearchPlan)
35
+
36
+ async def perform_searches(self, search_plan: WebSearchPlan) -> list[str]:
37
+ """ Perform the searches to perform for the query """
38
+ print("Searching...")
39
+ num_completed = 0
40
+ tasks = [asyncio.create_task(self.search(item)) for item in search_plan.searches]
41
+ results = []
42
+ for task in asyncio.as_completed(tasks):
43
+ result = await task
44
+ if result is not None:
45
+ results.append(result)
46
+ num_completed += 1
47
+ print(f"Searching... {num_completed}/{len(tasks)} completed")
48
+ print("Finished searching")
49
+ return results
50
+
51
+ async def search(self, item: WebSearchItem) -> str | None:
52
+ """ Perform a search for the query """
53
+ input = f"Search term: {item.query}\nReason for searching: {item.reason}"
54
+ try:
55
+ result = await Runner.run(
56
+ search_agent,
57
+ input,
58
+ )
59
+ return str(result.final_output)
60
+ except Exception:
61
+ return None
62
+
63
+ async def write_report(self, query: str, search_results: list[str]) -> ReportData:
64
+ """ Write the report for the query """
65
+ print("Thinking about report...")
66
+ input = f"Original query: {query}\nSummarized search results: {search_results}"
67
+ result = await Runner.run(
68
+ writer_agent,
69
+ input,
70
+ )
71
+
72
+ print("Finished writing report")
73
+ return result.final_output_as(ReportData)
74
+
75
+ async def send_email(self, report: ReportData) -> None:
76
+ print("Writing email...")
77
+ result = await Runner.run(
78
+ email_agent,
79
+ report.markdown_report,
80
+ )
81
+ print("Email sent")
82
+ return report
search_agent.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from agents import Agent, WebSearchTool, ModelSettings
2
+
3
+ INSTRUCTIONS = (
4
+ "You are a research assistant. Given a search term, you search the web for that term and "
5
+ "produce a concise summary of the results. The summary must be 2-3 paragraphs and less than 300 "
6
+ "words. Capture the main points. Write succintly, no need to have complete sentences or good "
7
+ "grammar. This will be consumed by someone synthesizing a report, so its vital you capture the "
8
+ "essence and ignore any fluff. Do not include any additional commentary other than the summary itself."
9
+ )
10
+
11
+ search_agent = Agent(
12
+ name="Search agent",
13
+ instructions=INSTRUCTIONS,
14
+ tools=[WebSearchTool(search_context_size="low")],
15
+ model="gpt-4o-mini",
16
+ model_settings=ModelSettings(tool_choice="required"),
17
+ )
uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
writer_agent.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from agents import Agent
3
+
4
+ INSTRUCTIONS = (
5
+ "You are a senior researcher tasked with writing a cohesive report for a research query. "
6
+ "You will be provided with the original query, and some initial research done by a research assistant.\n"
7
+ "You should first come up with an outline for the report that describes the structure and "
8
+ "flow of the report. Then, generate the report and return that as your final output.\n"
9
+ "The final output should be in markdown format, and it should be lengthy and detailed. Aim "
10
+ "for 5-10 pages of content, at least 1000 words."
11
+ )
12
+
13
+
14
+ class ReportData(BaseModel):
15
+ short_summary: str = Field(description="A short 2-3 sentence summary of the findings.")
16
+
17
+ markdown_report: str = Field(description="The final report")
18
+
19
+ follow_up_questions: list[str] = Field(description="Suggested topics to research further")
20
+
21
+
22
+ writer_agent = Agent(
23
+ name="WriterAgent",
24
+ instructions=INSTRUCTIONS,
25
+ model="gpt-4o-mini",
26
+ output_type=ReportData,
27
+ )