Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesFiles changed (12)
- README.md+3-9
- __pycache__/email_agent.cpython-313.pycAdded
- __pycache__/planner_agent.cpython-313.pycAdded
- __pycache__/research_manager.cpython-313.pycAdded
- __pycache__/search_agent.cpython-313.pycAdded
- __pycache__/writer_agent.cpython-313.pycAdded
- deep_research.pyAdded+22
- email_agent.pyAdded+31
- planner_agent.pyAdded+29
- research_manager.pyAdded+84
- search_agent.pyAdded+19
- writer_agent.pyAdded+28
12345234789561112---title: Deep Researchemoji: 🌍colorFrom: bluecolorTo: yellowtitle: Deep_Researchapp_file: deep_research.pysdk: gradiosdk_version: 5.38.0app_file: app.pypinned: falsesdk_version: 5.35.0---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122import gradio as gr
from dotenv import load_dotenv
from research_manager import ResearchManager
load_dotenv(override=True)
async def run(query: str):
async for chunk in ResearchManager().run(query):
yield chunk
with gr.Blocks(theme=gr.themes.Default(primary_hue="sky")) as ui:
gr.Markdown("# Deep Research")
query_textbox = gr.Textbox(label="What topic would you like to research?")
run_button = gr.Button("Run", variant="primary")
report = gr.Markdown(label="Report")
run_button.click(fn=run, inputs=query_textbox, outputs=report)
query_textbox.submit(fn=run, inputs=query_textbox, outputs=report)
ui.launch(inbrowser=True)12345678910111213141516171819202122232425262728293031import os
from typing import Dict
import sendgrid
from sendgrid.helpers.mail import Email, Mail, Content, To
from agents import Agent, function_tool
@function_tool
def send_email(subject: str, html_body: str) -> Dict[str, str]:
""" Send out an email with the given subject and HTML body """
sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("jai.300012723027@csvtu.ac.in") # Change this to your verified email
to_email = To("ksharma9719@gmail.com") # Change this to your email
content = Content("text/html", html_body)
mail = Mail(from_email, to_email, subject, content).get()
response = sg.client.mail.send.post(request_body=mail)
return {"status": "success"}
INSTRUCTIONS = """
You are able to send a nicely formatted HTML email based on a detailed report.
You will be provided with detailed report. You should use your tool to send one email,
providing the report converted into clean, well presented HTML with an appropriate subject line.
"""
email_agent = Agent(
name = "Email Agent",
instructions = INSTRUCTIONS,
model='gpt-4o-mini',
tools=[send_email]
)1234567891011121314151617181920212223242526272829from pydantic import BaseModel
from agents import Agent
HOW_MANY_SEARCHES = 3
INSTRUCTIONS = f"You are a helpful research assistant. Given a query, come up with \
a set of web searches to perform to best answer the query. Output {HOW_MANY_SEARCHES} terms to query for"
class WebSearchItem(BaseModel):
reason: str
"""Your reasoning for why this search is important for this query."""
query: str
"""The search term to use for the web search."""
class WebSearchPlan(BaseModel):
searches: list[WebSearchItem]
"""A list of web searches to perform to best answer the query."""
planner_agent = Agent(
name="Planner Agent",
instructions=INSTRUCTIONS,
model = 'gpt-4o-mini',
output_type = WebSearchPlan
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384from agents import Runner, trace, gen_trace_id
from search_agent import search_agent
from planner_agent import planner_agent, WebSearchItem, WebSearchPlan
from writer_agent import writer_agent, ReportData
from email_agent import email_agent
import asyncio
class ResearchManager:
async def run(self, query: str):
""" Run the deep research process, yielding the status updates and the final report"""
trace_id = gen_trace_id()
with trace("Research trace", trace_id=trace_id):
print(f"View trace: https://platform.openai.com/traces/trace?trace_id={trace_id}")
yield f"View trace: https://platform.openai.com/traces/trace?trace_id={trace_id}"
print("Starting research...")
search_plan = await self.plan_searches(query)
yield "Searches planned, starting to search..."
search_results = await self.perform_searches(search_plan)
yield "Searches complete, writing report..."
report = await self.write_report(query, search_results)
yield "Report written, sending email..."
await self.send_email(report)
yield "Email sent, research complete"
yield report.markdown_report
async def plan_searches(self, query: str) -> WebSearchPlan:
""" Plan the searches to perform for the query """
print("Planning searches...")
result = await Runner.run(
planner_agent,
f"Query: {query}",
)
print(f"Will perform {len(result.final_output.searches)} searches")
return result.final_output_as(WebSearchPlan)
async def perform_searches(self, search_plan: WebSearchPlan) -> list[str]:
""" Perform the searches to perform for the query """
print("Searching...")
num_completed = 0
tasks = [asyncio.create_task(self.search(item)) for item in search_plan.searches]
results = []
for task in asyncio.as_completed(tasks):
result = await task
if result is not None:
results.append(result)
num_completed += 1
print(f"Searching... {num_completed}/{len(tasks)} completed")
print("Finished searching")
return results
async def search(self, item: WebSearchItem) -> str | None:
""" Perform a search for the query """
input = f"Search term: {item.query}\nReason for searching: {item.reason}"
try:
result = await Runner.run(
search_agent,
input,
)
return str(result.final_output)
except Exception:
return None
async def write_report(self, query: str, search_results: list[str]) -> ReportData:
""" Write the report for the query """
print("Thinking about report...")
input = f"Original query: {query}\nSummarized search results: {search_results}"
result = await Runner.run(
writer_agent,
input,
)
print("Finished writing report")
return result.final_output_as(ReportData)
async def send_email(self, report: ReportData) -> None:
print("Writing email...")
result = await Runner.run(
email_agent,
report.markdown_report,
)
print("Email sent")
return report12345678910111213141516171819from agents import Agent, WebSearchTool, ModelSettings
INSTRUCTIONS = """
You are a research assistant. Given a search term, you search the web for
that term and produce a concise summary of the results. The summary must be
2-3 paragraphs and less than 300 words. Capture the main points. Write succintly,
no need to have the complete sentence or good grammar. This will be consumed nt someone
synthesizing a report, so it's vital you capture the essence and ignore any fluff.
Do not include any addtional commentary other than the summary itself.
"""
search_agent = Agent(
name="Search Agent",
instructions=INSTRUCTIONS,
model = 'gpt-4o-mini',
tools=[WebSearchTool(search_context_size="low")],
model_settings=ModelSettings(tool_choice="required")
)12345678910111213141516171819202122232425262728from pydantic import BaseModel, Field
from agents import Agent
INSTRUCTIONS = (
"You are a senior researcher tasked with writing a cohesive report for a research query. "
"You will be provided with the original query, and some initial research done by a research assistant.\n"
"You should first come up with an outline for the report that describes the structure and "
"flow of the report. Then, generate the report and return that as your final output.\n"
"The final output should be in markdown format, and it should be lengthy and detailed. Aim "
"for 5-10 pages of content, at least 1000 words."
)
class ReportData(BaseModel):
short_summary: str = Field(description="A short 2-3 sentence summary of the findings.")
markdown_report: str = Field(description="The final report.")
follow_up_questions: list[str] = Field(description="Suggested topics to research further.")
writer_agent = Agent(
name ="Writer Agent",
instructions = INSTRUCTIONS,
model = 'gpt-4o-mini',
output_type = ReportData
)README.md+3-9
__pycache__/email_agent.cpython-313.pycAdded
__pycache__/planner_agent.cpython-313.pycAdded
__pycache__/research_manager.cpython-313.pycAdded
__pycache__/search_agent.cpython-313.pycAdded
__pycache__/writer_agent.cpython-313.pycAdded
deep_research.pyAdded+22
email_agent.pyAdded+31
planner_agent.pyAdded+29
research_manager.pyAdded+84
search_agent.pyAdded+19
writer_agent.pyAdded+28