Skip to content

Haythem532002/ai-search-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– AI Search Agent

Intelligent Research Assistant with Multi-Tool Integration

An advanced AI-powered search and research agent that leverages multiple tools including web search, Wikipedia lookup, and file operations to provide comprehensive research capabilities with automatic output saving and structured responses.

Python LangChain OpenAI Pydantic

🌟 Features

  • 🧠 Intelligent Research - Multi-source research using web search and Wikipedia
  • πŸ” Web Search Integration - Real-time web search via DuckDuckGo
  • πŸ“š Wikipedia Integration - Comprehensive encyclopedia lookup
  • πŸ€– Tool-Calling Agent - Advanced LangChain agent with structured outputs
  • πŸ“Š Structured Responses - Pydantic-based response formatting with validation

πŸ“· Screenshots

Example screenshots (stored in imgs/):

Agent Screenshot 2

Agent Screenshot 1

Agent Screenshot 1

Agent Screenshot 2

πŸ› οΈ Tech Stack

Backend: Python 3.8+, LangChain, OpenAI GPT-4o
Search Tools: DuckDuckGo Search, Wikipedia API
Data Processing: Pydantic for structured outputs and validation
Agent Framework: LangChain tool-calling agent architecture

πŸ—οΈ Agent Architecture

The system uses a sophisticated tool-calling agent architecture built with LangChain:

Core Components

  • πŸ€– LangChain Agent - Tool-calling agent with GPT-4o integration
  • πŸ” Search Tools - Web search and Wikipedia lookup capabilities
  • οΏ½ Structured Output - Pydantic models for consistent response formatting
  • 🎯 Prompt Engineering - Optimized prompts for research tasks

Tool Integration

  1. 🌐 Web Search - DuckDuckGoSearchRun for real-time web information
  2. πŸ“– Wikipedia - WikipediaQueryRun for encyclopedia content

Data Flow

  1. πŸ“ Query Input - User provides research topic or question
  2. πŸ€– Agent Processing - LangChain agent analyzes query and selects appropriate tools
  3. οΏ½ Information Gathering - Tools execute searches and retrieve relevant data
  4. πŸ“Š Response Generation - GPT-4o synthesizes information into structured output
  5. πŸ“‹ Structured Output - Results returned in standardized ResearchResponse format

Response Schema

class ResearchResponse(BaseModel):
    topic: str              # Main research topic
    summary: str            # Comprehensive summary of findings
    sources: list[str]      # List of sources used
    tools_used: list[str]   # Tools utilized in research

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • OpenAI API key
  • Git

Environment Setup

  1. Clone the repository
git clone https://github.com/Haythem532002/ai-search-agent.git
cd ai-search-agent
  1. Set up Python virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies
pip install -r requirements.txt
  1. Configure environment variables

Create a .env file and add your OpenAI API key:

OPENAI_API_KEY=your_openai_api_key_here

Running the Application

Start the research agent

python main.py

The agent will automatically research the default query: "What is the capital of Tunisia"

Customizing Queries

Modify the query in main.py:

raw_response = agent_executor.invoke(
    {"query": "Your research question here"})

Example Usage

# Example queries you can try:
queries = [
    "What are the latest developments in AI?",
    "Explain quantum computing basics",
    "What is the history of machine learning?",
    "How does blockchain technology work?"
]

πŸ“ Project Structure

AI-Search-Agent/
β”œβ”€β”€ app.py                         # Flask API server (primary backend)
β”œβ”€β”€ main.py                        # Legacy or alternate entrypoint (may be duplicate)
β”œβ”€β”€ tools.py                       # Tool definitions and implementations
β”œβ”€β”€ my-app/                        # Next.js frontend application
β”œβ”€β”€ imgs/                          # Example screenshots and images
β”œβ”€β”€ requirements.txt               # Python dependencies
β”œβ”€β”€ .env                           # Environment variables (API keys) - not committed
β”œβ”€β”€ .gitignore                     # Git ignore configuration
β”œβ”€β”€ README.md                      # Project documentation
β”œβ”€β”€ venv/                          # Python virtual environment (optional)
└── .git/                          # Git repository metadata

Note: Prefer running app.py as the primary server (python app.py). If main.py exists it may be an older/duplicate server β€” run only one server to avoid port conflicts.

πŸ§ͺ Testing

Run Basic Tests

# Test the agent with a simple query
python main.py

# Test individual tools
python -c "from tools import search_tool, wiki_tool, save_tool; print('Tools imported successfully')"

# Test OpenAI connection
python -c "from langchain_openai import ChatOpenAI; llm = ChatOpenAI(model='gpt-4o'); print('OpenAI connection OK')"

Test Individual Components

# Test web search
python -c "from tools import search_tool; print(search_tool.run('Python programming'))"

# Test Wikipedia search
python -c "from tools import wiki_tool; print(wiki_tool.run('Artificial Intelligence'))"

# Test file saving
python -c "from tools import save_tool; print(save_tool.run('Test data'))"

Custom Query Testing

# Example test script
from main import agent_executor

test_queries = [
    "What is machine learning?",
    "History of the internet",
    "Climate change effects"
]

for query in test_queries:
    response = agent_executor.invoke({"query": query})
    print(f"Query: {query}")
    print(f"Response: {response}")
    print("-" * 50)

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Install development dependencies (pip install -r requirements.txt)
  4. Make your changes with proper tests
  5. Commit your changes (git commit -m 'Add AmazingFeature')
  6. Push to the branch (git push origin feature/AmazingFeature)
  7. Open a Pull Request

Development Guidelines

  • Follow PEP 8 for Python code
  • Use type hints where appropriate
  • Write docstrings for functions and classes
  • Test new features before submitting
  • Update documentation for new functionality
  • Use conventional commits for clear history

Adding New Tools

To add a new tool to the agent:

  1. Create the tool in tools.py:
def your_new_tool(query: str) -> str:
    # Your tool implementation
    return result

new_tool = Tool(
    name="YourTool",
    func=your_new_tool,
    description="Description of what your tool does"
)
  1. Add it to the tools list in main.py:
tools = [search_tool, wiki_tool, save_tool, new_tool]

πŸ“Š Performance & Monitoring

  • ⚑ Response Times: Typical query response under 10-15 seconds
  • 🎯 Accuracy: High-quality responses with multi-source validation
  • πŸ’Ύ Storage: Automatic research output persistence
  • πŸ” Search Quality: Dual-source information gathering (web + Wikipedia)
  • πŸ“ Output Format: Structured, validated responses with Pydantic

πŸ”’ Security & Best Practices

  • οΏ½ API Key Management: Store OpenAI API key in .env file
  • πŸ“ File Security: Research outputs saved locally with timestamps
  • πŸ›‘οΈ Input Validation: Pydantic models ensure data integrity
  • 🚫 Rate Limiting: Be mindful of OpenAI API usage limits
  • πŸ” Search Safety: DuckDuckGo provides safe web search results

πŸ“ˆ Future Enhancements

  • πŸ“„ PDF Processing - Add document ingestion capabilities
  • πŸ—„οΈ Database Integration - Store research results in database
  • 🌐 Web Interface - Add Flask/FastAPI web frontend
  • πŸ“Š Analytics Dashboard - Track research patterns and topics
  • πŸ”„ Batch Processing - Process multiple queries simultaneously
  • 🎯 Source Ranking - Implement source credibility scoring

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.

πŸ™ Acknowledgments

  • 🦜 LangChain for the excellent agent framework and tool integration
  • πŸ€– OpenAI for providing the powerful GPT-4o language model
  • πŸ” DuckDuckGo for privacy-focused web search capabilities
  • πŸ“š Wikipedia for comprehensive encyclopedia content
  • οΏ½ Pydantic for robust data validation and parsing

Built with ❀️ using Modern AI & Agent Architecture

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors