π¨ Deep Research Agent - Frontend
September 19, 2025 Β· View on GitHub
A modern, responsive Next.js frontend for the Deep Research Agent. Features real-time streaming research progress, multi-model support, and an intuitive chat-like interface similar to Perplexity and OpenAI's thinking mode.
πΉ Full YouTube Guide: Youtube link
π X Post: X link
π» Launch Full Stack Product: Github Repo
βοΈ Buy me a coffee: Cafe Latte
π€οΈ Discord: Invite link
β¨ Features
- Real-time Research Streaming: Live updates showing AI thinking process and research steps
- Multi-Model Support: Switch between Claude 4, GPT-5, and Kimi K2 0905 Preview
- Progressive Research Display: Detailed step-by-step research progress with visual indicators
- Google Docs Export: One-click export to Google Docs with proper formatting and sources
- Responsive Design: Mobile-friendly and adaptive to all screen sizes
- Persistent State: Research results preserved when switching tabs
- Source Linking: Clickable sources from research findings
- Model Comparison: Compare performance metrics across different AI models
- Smooth Animations: Loading states, progress bars, and transition effects
π Quick Start
Prerequisites
- Node.js 18+
- npm, yarn, or pnpm
- Backend API running (see Backend Setup)
Installation
-
Clone the repository
git clone https://github.com/ShenSeanChen/yt-deepresearch-frontend.git cd yt-deepresearch-frontend -
Install dependencies
npm install # or yarn install -
Configure backend URL
# For local development (backend on localhost:8080) ./switch-env.sh local # For production (deployed backend) ./switch-env.sh production # Or manually create .env.local: echo "NEXT_PUBLIC_BACKEND_URL=http://localhost:8080" > .env.local -
Start development server
npm run dev -
Open in browser
http://localhost:3000
ποΈ Architecture
Core Components
app/page.tsx: Main page with ResearchProvider wrappercomponents/ResearchInterface.tsx: Core research UI with streamingcontexts/ResearchContext.tsx: Global state managementlib/utils.ts: Utility functions and helpers
State Management
Uses React Context API for global state:
- Research messages and streaming events
- Current research stage and progress
- Model selection and API key management
- UI states (typing indicators, loading, etc.)
π§ Environment Configuration
Easy Environment Switching
Use the provided script to switch between local and production backends:
# Use local backend (localhost:8080)
./switch-env.sh local
# Use production backend
./switch-env.sh production
# Remove configuration (defaults to localhost:8080)
./switch-env.sh remove
Manual Configuration
Create .env.local with your preferred backend URL:
# Local development
NEXT_PUBLIC_BACKEND_URL=http://localhost:8080
# Production
NEXT_PUBLIC_BACKEND_URL=https://your-backend-url.run.app
Environment Files
env.local.example: Template for local developmentenv.production.example: Template for productionswitch-env.sh: Script to easily switch configurations
π API Key Management
Multi-Model Configuration
The Compare tab supports comprehensive API key management for all three models:
Method 1: Direct Input (Recommended)
- Navigate to the Compare tab
- Click "Configure" in the API Key Configuration section
- Enter API keys for each model you want to use:
- OpenAI: Your OpenAI API key for GPT-5
- Anthropic: Your Anthropic API key for Claude 4
- Kimi: Your Moonshot API key for Kimi K2 0905
- Keys are automatically saved in your browser's local storage
Method 2: Import/Export Keys
- Export: Save your configured keys to a JSON file for backup
- Import: Load keys from a previously exported JSON file
- Format:
{"openai": "sk-...", "anthropic": "sk-ant-...", "kimi": "sk-..."}
Method 3: Environment Variables (Development)
For development, you can set keys in .env.local:
# Not implemented yet - use direct input method
NEXT_PUBLIC_OPENAI_API_KEY=your_key_here
NEXT_PUBLIC_ANTHROPIC_API_KEY=your_key_here
NEXT_PUBLIC_KIMI_API_KEY=your_key_here
Security Best Practices
- β Local Storage: Keys are stored locally in your browser
- β No Server Storage: Keys are never stored on our servers
- β Encrypted Transit: Keys are sent securely to respective APIs
- β Clear Option: Easy one-click clear all keys
- β οΈ Browser Only: Keys are lost if you clear browser data
Getting API Keys
- OpenAI (GPT-5): platform.openai.com
- Anthropic (Claude 4): console.anthropic.com
- Kimi (Moonshot): platform.moonshot.cn
π¨ UI Components
Research Interface
- Model Selection: Dropdown to choose AI model (OpenAI, Anthropic, Kimi)
- API Key Input: Secure input for user's API key (single model)
- Progress Bar: Visual progress indicator during research
- Live Indicator: Shows when research is actively streaming
- Research Steps: Expandable cards showing detailed research process
Compare Interface
- Multi-Key Management: Configure API keys for all models simultaneously
- Model Selection: Choose which models to include in comparison
- Parallel Execution: Run the same query across multiple models
- Performance Metrics: Detailed timing and quality comparisons
- Result Export: Save comparison results and metrics
Research Progress Display
The interface shows detailed research steps:
- π― Planning: Research strategy and source identification
- π Queries: Individual research queries being executed
- π Analysis: Cross-referencing and analyzing findings
- π§ Synthesis: Combining findings into comprehensive analysis
- π Final Report: Complete research report with sources
Visual Elements
- Color-coded Events: Different colors for different types of research activities
- Smooth Animations: Entry animations for new research steps
- Hover Effects: Interactive elements with visual feedback
- Responsive Design: Adapts to mobile, tablet, and desktop screens
π Google Docs Export
The Deep Research Agent includes built-in Google Docs export functionality for seamless report sharing and collaboration.
One-time Setup (OAuth)
Follow these steps to enable oneβclick Google Docs export:
- Create/Select a GCP project
- Go to
https://console.cloud.google.comand select or create a project.
- Enable APIs
- Search for and enable:
- Google Docs API
- Google Drive API
- Configure OAuth consent screen
- User type: External
- App name, support email: fill in anything reasonable
- Scopes: add
https://www.googleapis.com/auth/documentshttps://www.googleapis.com/auth/drive.file
- Test users: add the Gmail accounts that will use the app (you can add more later)
- Create OAuth credentials (Web application)
- Navigation: Credentials β Create Credentials β OAuth client ID β Web application
- Authorized JavaScript origins:
http://localhost:3000(local dev)- your production domain (e.g.,
https://your-app.vercel.app)
- Redirect URIs: not required for this tokenβonly popup flow (GSI)
- Copy the generated Client ID.
- Add the Client ID to environment variables
- Local: create or update
.env.localinyt-DeepResearch-Frontendwith:NEXT_PUBLIC_GOOGLE_CLIENT_ID=your_client_id.apps.googleusercontent.com - Production (e.g., Vercel): add the same variable in the project settings, and include your prod domain in Authorized JavaScript origins.
- Restart the app
npm run dev
- Verify
- Run a research β click Export β Google popup should appear β consent β a new Doc opens with your report + sources.
Troubleshooting
- Popup blocked: allow popups for
localhost:3000. - Missing consent: ensure the signedβin Google account is added as a Test User on the OAuth consent screen.
- 400/unauthorized: confirm your domain is listed under Authorized JavaScript origins and the Client ID matches
.env.local.
Export Options
1. Copy to Clipboard (Recommended)
- Click the "Copy for Docs" button when research is complete
- Content is copied to your clipboard with proper formatting
- Open Google Docs and paste directly (Ctrl+V / Cmd+V)
2. Create Google Doc
- Click the "Export" button to sign in with Google and auto-create a Doc
- The new document opens in a new tab and contains the full report + sources
Export Content Includes
- Research Query: Original question/prompt
- Metadata: Generation timestamp and AI model used
- Full Report: Complete research findings with markdown formatting
- Sources: All referenced URLs and citations
- Branding: Deep Research Agent attribution
Formatting Features
The exported content maintains:
- β Headers and Structure: Proper heading hierarchy
- β Bold and Italic Text: Emphasis formatting preserved
- β Numbered Lists: Sequential information maintained
- β Source Links: Clickable URLs for easy reference
- β Professional Layout: Clean, readable document structure
Usage Tips
- Best Practice: Use "Copy for Docs" for fastest workflow
- Team Sharing: Export to Google Docs for real-time collaboration
- Archive: Save important research to Google Drive automatically
- Formatting: Google Docs will auto-detect and enhance markdown formatting
π Connecting to Backend
Backend Requirements
The frontend expects a backend with these endpoints:
GET /health- Health checkPOST /research/stream- Streaming research endpoint
Backend URL Configuration
The frontend automatically detects the backend URL:
- Environment Variable:
NEXT_PUBLIC_BACKEND_URL - Default Fallback:
http://localhost:8080
Streaming Protocol
The frontend expects Server-Sent Events (SSE) with these event types:
interface StreamingEvent {
type: string // Event type (session_start, research_step, etc.)
stage?: string // Research stage (clarification, research_brief, etc.)
content?: string // Event content/message
timestamp: string // ISO timestamp
research_id?: string // Unique research session ID
model?: string // AI model being used
error?: string // Error message if applicable
node_name?: string // LangGraph node name
node_count?: number // Node execution count
duration?: number // Event duration
}
π± Responsive Design
Breakpoints
- Mobile: < 768px
- Tablet: 768px - 1024px
- Desktop: > 1024px
Mobile Features
- Touch-friendly interface
- Optimized spacing and typography
- Collapsible sections for better space usage
- Swipe gestures for navigation
π§ͺ Testing
Development Testing
# Start development server
npm run dev
# Test with local backend
./switch-env.sh local
# Visit http://localhost:3000
# Test with production backend
./switch-env.sh production
# Visit http://localhost:3000
Build Testing
# Build for production
npm run build
# Test production build
npm start
π Deployment
Vercel (Recommended)
-
Connect to Vercel
# Install Vercel CLI npm i -g vercel # Deploy vercel -
Configure Environment Variables In Vercel dashboard, add:
NEXT_PUBLIC_BACKEND_URL=https://your-backend-url.run.app
Manual Deployment
# Build the application
npm run build
# Export static files (if needed)
npm run export
# Deploy the 'out' directory to your hosting provider
π― Usage Guide
Basic Research Flow
- Select AI Model: Choose from OpenAI GPT-4o, Anthropic Claude, or Kimi K2
- Enter API Key: Provide your API key for the selected model
- Ask Question: Type your research question
- Watch Progress: See real-time research steps and findings
- Review Results: Read the comprehensive final report
Advanced Features
- Expand Steps: Click on research steps to see detailed content
- Source Links: Click on sources to visit original content
- Progress Tracking: Monitor research progress with the progress bar
- Error Handling: Automatic retry suggestions for failed requests
ποΈ Database Integration (Optional)
The Deep Research Agent supports optional database integration for persistent research history and advanced model comparison tracking.
Supabase Integration
Why Add Database?
- π Research History: Save and review past research sessions
- π Model Performance Tracking: Compare model speed, accuracy, and quality over time
- π Session Persistence: Resume research sessions across devices
- π Analytics Dashboard: Track usage patterns and research topics
Setup Instructions:
-
Create Supabase Project
# Visit https://supabase.com and create a new project # Note your project URL and anon key -
Database Schema
-- Research sessions table CREATE TABLE research_sessions ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, query TEXT NOT NULL, model VARCHAR(50) NOT NULL, created_at TIMESTAMP DEFAULT NOW(), completed_at TIMESTAMP, duration_seconds INTEGER, final_report TEXT, sources JSONB, stage_timings JSONB, success BOOLEAN DEFAULT FALSE ); -- Model performance metrics CREATE TABLE model_metrics ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, model VARCHAR(50) NOT NULL, avg_duration FLOAT, success_rate FLOAT, total_runs INTEGER, last_updated TIMESTAMP DEFAULT NOW() ); -
Environment Variables
# Add to .env.local NEXT_PUBLIC_SUPABASE_URL=your-project-url NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key -
Install Dependencies
npm install @supabase/supabase-js
Benefits of Database Integration:
- β Persistent History: Never lose research results
- β Performance Analytics: Track which models work best for different query types
- β Team Collaboration: Share research sessions with team members
- β Usage Insights: Understand research patterns and optimize workflows
Note: Database integration is completely optional. The app works perfectly without it, but adding it unlocks powerful analytics and persistence features.
π Security
- API Keys: Never stored client-side, sent directly to backend
- HTTPS: Enforced in production
- Input Validation: Client-side validation for all inputs
- CORS: Configured for secure cross-origin requests
- Database Security: Supabase RLS (Row Level Security) recommended for multi-user setups
π Troubleshooting
Common Issues
-
Backend Connection Failed
- Check backend URL in
.env.local - Verify backend is running and accessible
- Check CORS configuration
- Check backend URL in
-
API Key Errors
- Verify API key is correct for selected model
- Check API key permissions and quotas
- Ensure model is supported by your API key
-
Streaming Issues
- Check network connectivity
- Verify browser supports Server-Sent Events
- Check for ad blockers or network filters
Debug Mode
Enable debug logging:
// In browser console
localStorage.setItem('debug', 'true')
π οΈ Development
Project Structure
βββ app/ # Next.js app directory
β βββ globals.css # Global styles
β βββ layout.tsx # Root layout
β βββ page.tsx # Main page
βββ components/ # React components
β βββ ResearchInterface.tsx
β βββ ui/ # UI components
βββ contexts/ # React contexts
β βββ ResearchContext.tsx
βββ lib/ # Utilities
β βββ utils.ts
βββ env.*.example # Environment templates
βββ switch-env.sh # Environment switching script
Key Dependencies
- Next.js 14: React framework
- TypeScript: Type safety
- Tailwind CSS: Styling
- Radix UI: Accessible components
- Lucide React: Icons
Code Style
- Google Standards: Code comments and formatting
- TypeScript: Strict type checking
- ESLint: Code linting
- Prettier: Code formatting
π License
MIT License - see LICENSE file for details.
π€ Contributing
- Fork the repository
- Create a feature branch
- Follow Google coding standards
- Add comments to all code
- Test on mobile and desktop
- Submit a pull request
π Support
- Create an issue for bugs or feature requests
- Check browser console for error messages
- Verify backend connectivity first
- Review environment configuration
Built with β€οΈ using Next.js, TypeScript, and Tailwind CSS.