“`html
Build a Custom AI Agent in Python: Automate Web Research & Email Reports
What We're Building & Why AI Agents Are a Game-Changer
- We're building a Python AI agent that takes a topic, searches the web, summarizes the top results, and emails a formatted report.
- Understand the core loop: LLM reasoning (planning) -> Tool Execution (search) -> LLM Synthesis (understanding) -> Action (email).
- Practical applications: Automate competitor analysis, generate daily news digests, or monitor brand mentions without manual effort.
Prerequisites: Setting Up Your AI Toolbox
- Python 3.10+ installed, along with a virtual environment to manage dependencies.
- API keys: An OpenAI API key (for the LLM brain) and a SerpAPI key (for web search). Store them in a
.envfile for security. - Core libraries installed via
pip:openai,serpapi,python-dotenv.
Step 1: Defining the Agent's “Hands” (Tools and Functions)
- Create a
web_search(query)function using the SerpAPI library to fetch the top 5 search results for a given query. - Create a
summarize_content(text, topic)function using OpenAI'sgpt-4o-minimodel to condense the search results into a concise summary. - Create a
send_email_report(recipient, subject, body)function using SMTP or SendGrid to deliver the final summary to a specified inbox.
Step 2: Building the “Brain” (The Orchestration Loop)
- Design the main
agent_loop(user_query)function, starting with a system prompt that clearly defines the available tools and their JSON schema. - Implement structured output: The LLM must return a JSON action (e.g.,
{"tool": "web_search", "parameters": {"query": "latest AI news"}}) or a final answer. - Write the loop logic: Parse the JSON action -> Execute the matching Python function -> Feed the result back to the LLM for the next step, repeating until a final answer is reached.
Step 3: Execution, Testing, and Error Handling
- Run the script with
python agent.pyand test with a query like “Find the latest trends in generative AI for healthcare”. - Add robust error handling:
try/exceptblocks for API timeouts, invalid JSON parsing from the LLM, and missing environment variables. - Implement logging (using the
logginglibrary) to print the agent's internal “thought” process for debugging and transparency.
Future Enhancements: From Prototype to Production
- Add memory: Use LangChain's
ConversationBufferMemoryto allow the agent to remember context across multiple turns. - Expand the toolset: Integrate a SQL database query tool, a


