Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions claude-4-deep-research/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FIRECRAWL_API_KEY='fc-your-key-here'
ANTHROPIC_API_KEY='sk-ant-your-key-here'
1 change: 1 addition & 0 deletions claude-4-deep-research/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12
140 changes: 140 additions & 0 deletions claude-4-deep-research/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Application Architecture

The Claude 4 Deep Research Assistant has been designed with a clean, decoupled architecture that separates concerns and makes the codebase maintainable and extensible.

## Architecture Overview

```plaintext
src/
├── claude_deep_research_app.py # UI Layer (Streamlit interface)
├── config.py # Configuration settings
└── core/ # Business Logic Layer
├── __init__.py # Module exports
├── clients.py # API client management
├── research.py # Research functionality
└── chat.py # Chat and Claude interactions
```

## Layer Separation

### 1. UI Layer (`claude_deep_research_app.py`)

- **Responsibility**: Streamlit interface and user interactions
- **Dependencies**: Core modules, configuration
- **Contains**:
- Streamlit components and layout
- User input handling
- Display logic (including chat interface, research results, and API key status indicators)
- Session state management

### 2. Business Logic Layer (`core/`)

- **Responsibility**: Core application functionality
- **Dependencies**: External APIs (Anthropic, Firecrawl)
- **Modules**:

#### `clients.py` - API Client Management

- Manages Anthropic and Firecrawl API clients
- Handles authentication and connection
- Provides singleton-like client access
- API key validation

#### `research.py` - Research Engine

- Defines research tool schema
- Executes deep research operations
- Detects research requests
- Handles research results

#### `chat.py` - Chat Engine

- Manages Claude interactions
- Handles tool use workflow
- Provides streaming functionality
- Message preparation and formatting

### 3. Configuration Layer (`config.py`)

- **Responsibility**: Application settings and constants
- **Contains**:
- Model configuration
- Default parameters
- UI text and messages
- Feature flags

## Benefits of This Architecture

### 1. **Separation of Concerns**

- UI logic is separate from business logic
- Each module has a single responsibility
- Easy to understand and maintain

### 2. **Testability**

- Core logic can be tested independently of UI
- Mock clients for testing
- Isolated unit tests for each component

### 3. **Reusability**

- Core modules can be used in different interfaces
- Business logic is framework-agnostic
- Easy to create CLI, API, or other interfaces

### 4. **Maintainability**

- Changes to UI don't affect business logic
- Configuration changes are centralized
- Clear module boundaries

### 5. **Extensibility**

- Easy to add new research engines
- Simple to integrate additional AI models
- Straightforward to add new features

## Usage Examples

### Using Core Components Independently

```python
from core import ClientManager, ResearchEngine, ChatEngine

# Initialize components
client_manager = ClientManager()
research_engine = ResearchEngine(client_manager)
chat_engine = ChatEngine(client_manager, research_engine)

# Use research engine directly
result = research_engine.execute_research("quantum computing trends")

# Use chat engine for conversations
response = chat_engine.get_response_with_tools(
messages=[{"role": "user", "content": "Hello"}],
tools=[research_engine.get_tool_definition()]
)
```

### Creating Alternative Interfaces

The decoupled architecture makes it easy to create different interfaces:

- **CLI Interface**: Use core modules with argparse
- **API Server**: Use core modules with FastAPI/Flask
- **Jupyter Notebook**: Import and use core modules directly
- **Desktop App**: Use core modules with tkinter/PyQt

## Future Enhancements

The architecture supports easy addition of:

1. **New Research Engines**: Implement additional research providers
2. **Multiple AI Models**: Support for different LLM providers
3. **Caching Layer**: Add Redis/database caching
4. **Authentication**: User management and API key handling
5. **Analytics**: Usage tracking and metrics
6. **Plugin System**: Extensible tool framework

This architecture ensures the application remains maintainable, testable, and extensible as it grows in complexity.
130 changes: 130 additions & 0 deletions claude-4-deep-research/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Claude 4 Deep Research Assistant

A powerful AI assistant that combines Claude 4's conversational abilities with Firecrawl's deep research capabilities to provide comprehensive, well-sourced answers on any topic.

## Features

- 🤖 **Claude 4 Integration**: Powered by Anthropic's latest Claude 3.5 Sonnet model
- 🔍 **Deep Research**: Automatic web research using Firecrawl's deep research endpoint
- 💬 **Streaming Chat UI**: Real-time typewriter effect built with Streamlit
- 📚 **Message History**: Persistent conversation history within sessions
- ⚙️ **Configurable Research**: Adjustable research depth, time limits, and URL analysis
- 🎯 **Smart Tool Usage**: Automatically detects when research is needed
- 📊 **Source Attribution**: Comprehensive analysis with source citations

## How It Works

1. **General Conversations**: Ask any question for immediate Claude responses
2. **Research Requests**: When you ask for research, analysis, or current information, the assistant automatically uses Firecrawl's deep research tool
3. **Comprehensive Analysis**: The tool searches the web, analyzes multiple sources, and synthesizes findings into detailed insights
4. **Source Attribution**: All research comes with proper source citations and references

## Setup Instructions

### Prerequisites

- Python 3.12+
- Anthropic API key ([Get one here](https://console.anthropic.com/))
- Firecrawl API key ([Get one here](https://firecrawl.dev/))

### Installation

1. **Clone the repository**:

```bash
git clone <repository-url>
cd claude-4-deep-research
```

2. **Install dependencies**:

```bash
pip install -r requirements.txt
```

3. **Set up environment variables**:
- Copy `env.example` to `.env`
- Add your API keys:

```bash
ANTHROPIC_API_KEY=your_anthropic_api_key_here
FIRECRAWL_API_KEY=your_firecrawl_api_key_here
```

4. **Run the application**:

```bash
streamlit run src/claude_deep_research_app.py
```

### Alternative Setup with UV (Recommended)

If you have [uv](https://docs.astral.sh/uv/) installed:

```bash
uv sync
uv run streamlit run src/claude_deep_research_app.py
```

## Usage Examples

### General Questions

- "What is quantum computing?"
- "Explain machine learning concepts"
- "Help me write a Python function"

### Research Requests

- "Research the latest developments in quantum computing"
- "What are the current trends in renewable energy?"
- "Analyze the impact of AI on healthcare"
- "Investigate recent breakthroughs in space exploration"

### Current Information

- "What are the latest news in artificial intelligence?"
- "Current state of electric vehicle adoption"
- "Recent developments in climate change research"

## Configuration

Use the sidebar controls to adjust research parameters:

- **Research Depth** (1-10): Number of research iterations
- **Time Limit** (30-300 seconds): Maximum research duration
- **Max URLs** (1-100): Maximum number of sources to analyze

## Architecture

- **Frontend**: Streamlit for the web interface
- **AI Model**: Anthropic Claude 3.5 Sonnet via official SDK
- **Research Engine**: Firecrawl Deep Research API
- **Tool Integration**: Anthropic's tool use framework
- **Streaming**: Custom typewriter effect for better UX

## API Documentation

- [Firecrawl Deep Research API](https://docs.firecrawl.dev/features/alpha/deep-research)
- [Anthropic Tool Use](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/overview)
- [Anthropic Streaming](https://docs.anthropic.com/en/docs/build-with-claude/streaming)

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## License

MIT License - see LICENSE file for details

## Support

For issues and questions:

- Check the [Firecrawl documentation](https://docs.firecrawl.dev/)
- Review [Anthropic's tool use guide](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/implement-tool-use)
- Open an issue in this repository
17 changes: 17 additions & 0 deletions claude-4-deep-research/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[project]
name = "claude-4-deep-research"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"anthropic>=0.52.0",
"firecrawl-py>=2.7.0",
"python-dotenv>=1.1.0",
"streamlit>=1.45.1",
]

[dependency-groups]
notebook = [
"ipykernel>=6.29.5",
]
4 changes: 4 additions & 0 deletions claude-4-deep-research/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
streamlit>=1.28.0
anthropic>=0.52.0
firecrawl-py>=2.7.0
python-dotenv>=1.1.0
69 changes: 69 additions & 0 deletions claude-4-deep-research/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""
Launcher script for Claude 4 Deep Research Assistant
"""

import subprocess
import sys
import os
from pathlib import Path


def main():
"""Launch the Streamlit application."""
# Get the directory where this script is located
script_dir = Path(__file__).parent
app_path = script_dir / "src" / "app.py"

# Check if the app file exists
if not app_path.exists():
print(f"❌ Error: Application file not found at {app_path}")
sys.exit(1)

# Check for environment variables
if not os.getenv("ANTHROPIC_API_KEY"):
print("⚠️ Warning: ANTHROPIC_API_KEY not found in environment variables")
print(" Please set your API key in a .env file or environment variables")

if not os.getenv("FIRECRAWL_API_KEY"):
print("⚠️ Warning: FIRECRAWL_API_KEY not found in environment variables")
print(" Please set your API key in a .env file or environment variables")

print("🚀 Starting Claude 4 Deep Research Assistant...")
print(f"📁 App location: {app_path}")
print("🌐 The app will open in your default browser")
print("🛑 Press Ctrl+C to stop the application")
print("-" * 50)

try:
# Run the Streamlit app
subprocess.run(
[
sys.executable,
"-m",
"streamlit",
"run",
str(app_path),
"--server.headless",
"false",
"--server.port",
"8501",
"--browser.gatherUsageStats",
"false",
],
check=True,
)
except KeyboardInterrupt:
print("\n👋 Application stopped by user")
except subprocess.CalledProcessError as e:
print(f"❌ Error running application: {e}")
sys.exit(1)
except FileNotFoundError:
print(
"❌ Error: Streamlit not found. Please install it with: pip install streamlit"
)
sys.exit(1)


if __name__ == "__main__":
main()
Loading