A comprehensive AI agent system that demonstrates tool-calling, secure execution, and safety governance. This project teaches you how to build autonomous, safe, and reliable AI agents.
This project teaches you:
- ReAct Pattern: Reasoning and Acting in language models
- OpenAI Function Calling: Structured tool invocation
- LangChain Tools: Tool abstraction and management
- Agent Core Loop: Thought β Action (Tool Call) β Observation
- Input Validation: Validate agent tool inputs/outputs
- Sandboxing: Conceptual isolation of agent actions
- Pre-execution Hooks: Block harmful actions before execution
- Post-execution Hooks: Validate and sanitize outputs
- Domain Whitelisting: Control which domains can be accessed
- Human-in-the-Loop: Approvals for critical steps
- Rollback Strategies: Save agent state, ability to revert
- Policy Checks: Review plans against policies (e.g., must cite sources)
- State Management: Track agent execution state
ResearchAgent/
βββ README.md # This comprehensive guide
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
β
βββ agent/ # Core agent implementation
β βββ __init__.py
β βββ research_agent.py # Main Research Agent with ReAct pattern
β βββ react_loop.py # ReAct reasoning loop
β βββ state_manager.py # Agent state management & rollback
β
βββ tools/ # Agent tools
β βββ __init__.py
β βββ web_search.py # Serper API web search tool
β βββ url_reader.py # URL content extraction tool
β βββ report_writer.py # Report generation tool
β βββ base_tool.py # Base tool interface
β
βββ guardrails/ # Security & safety guardrails
β βββ __init__.py
β βββ pre_execution.py # Pre-execution validation hooks
β βββ post_execution.py # Post-execution validation hooks
β βββ domain_validator.py # Domain whitelisting
β βββ input_validator.py # Input validation
β βββ pii_redactor.py # PII redaction from outputs
β
βββ governance/ # Safety & reliability features
β βββ __init__.py
β βββ human_approval.py # Human-in-the-loop approvals
β βββ policy_checker.py # Policy compliance checking
β βββ rollback_manager.py # State rollback capabilities
β
βββ utils/ # Utilities
β βββ __init__.py
β βββ config.py # Configuration management
β βββ logger.py # Logging utilities
β
βββ data/ # Data storage
β βββ state/ # Agent state snapshots
β βββ reports/ # Generated reports
β
βββ main.py # Main entry point
cd SearchAgent
pip install -r requirements.txtCreate a .env file from .env.example:
# OpenAI (for agent LLM)
OPENAI_API_KEY=your_openai_key_here
# Serper API (for web search)
SERPER_API_KEY=your_serper_key_here
# Configuration
AGENT_MODEL=gpt-4
MAX_ITERATIONS=10
REQUIRE_HUMAN_APPROVAL=false# Basic research query
python main.py research "What are the latest developments in quantum computing?"
# With human approval required
python main.py research "Research AI safety" --require-approval
# With custom policy
python main.py research "AI trends" --policy-file policies/citation_policy.jsonReAct (Reasoning + Acting) is a pattern where the agent:
- Thinks about what to do next
- Acts by calling a tool
- Observes the tool's result
- Repeats until the task is complete
Example:
Thought: I need to research quantum computing. Let me start by searching for recent articles.
Action: search_web(query="quantum computing 2024")
Observation: Found 10 results including articles from Nature, arXiv...
Thought: Good, now I should read the most relevant articles to gather information.
Action: read_url(url="https://example.com/quantum-article")
Observation: Article content about quantum computing...
OpenAI's function calling allows structured tool invocation:
tools = [
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web for information",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
}
}
]Pre-execution hooks validate actions before they execute:
- Check if domain is whitelisted
- Validate input parameters
- Block dangerous operations
Post-execution hooks sanitize outputs:
- Redact PII (emails, phone numbers, SSNs)
- Validate output format
- Check for policy violations
For critical operations, the agent pauses and requests human approval:
- Before accessing sensitive domains
- Before writing final reports
- When policy violations are detected
The agent saves state at key checkpoints:
- Before each tool call
- After each iteration
- Before critical operations
If something goes wrong, you can rollback to a previous state.
Main agent that orchestrates the research process:
- Uses ReAct pattern for reasoning
- Manages tool calls
- Handles state transitions
- Integrates guardrails and governance
Web Search Tool: Uses Serper API to search the web URL Reader Tool: Extracts and cleans content from URLs Report Writer Tool: Generates structured research reports
Pre-execution: Validates tool calls before execution Post-execution: Sanitizes outputs after execution Domain Validator: Enforces domain whitelisting PII Redactor: Removes personal information
Human Approval: Manages approval workflows Policy Checker: Validates against policies Rollback Manager: Handles state rollbacks
- Understand ReAct pattern
- Implement basic agent loop
- Add web search tool
- Add URL reading tool
- Add report writing tool
- Implement pre-execution hooks
- Add domain whitelisting
- Implement input validation
- Add post-execution hooks
- Implement PII redaction
- Add human-in-the-loop approvals
- Implement state management
- Add rollback capabilities
- Implement policy checking
- Test failure scenarios
"Research the latest developments in AI safety"
Thought: I need to research AI safety. Let me search for recent articles and papers.
β
Domain whitelist check passed
β
Input validation passed
Action: search_web(query="AI safety 2024")
Observation: Found articles from arXiv, Nature, etc.
β
Output validation passed
β
No PII detected
Thought: Good results. Let me read the most relevant articles.
Action: read_url(url="https://arxiv.org/...")
...
β
All sources cited
β
Report structure valid
β οΈ Human approval required for final report
[Waiting for approval...]
β
Approved
Action: write_report(title="AI Safety Research", content=..., sources=[...])
Report generated successfully!
Saved to: data/reports/research_20240101_120000.md
Only approved domains can be accessed:
ALLOWED_DOMAINS = [
"arxiv.org",
"nature.com",
"github.com",
# ... more domains
]Automatically redacts:
- Email addresses
- Phone numbers
- Social Security Numbers
- Credit card numbers
- Physical addresses
Example policy:
{
"must_cite_sources": true,
"min_sources": 3,
"max_urls_per_domain": 5,
"require_peer_reviewed": false
}Agent state is saved at checkpoints:
data/state/checkpoint_001.jsondata/state/checkpoint_002.json- ...
All operations are logged:
- Tool calls
- Guardrail checks
- Policy violations
- Human approvals
- Rollbacks
- Experiment: Try different research queries
- Customize: Add your own tools
- Enhance: Implement more sophisticated policies
- Scale: Add multi-agent coordination
- Deploy: Build API endpoint or web interface