Skip to content

Latest commit

 

History

History
524 lines (391 loc) · 12.4 KB

File metadata and controls

524 lines (391 loc) · 12.4 KB

Getting Started

This guide will help you set up and run the AI Knowledge Graph Learning System on your local machine.

Prerequisites

Before you begin, ensure you have the following installed:

Backend Requirements

  • Python 3.9+ - Download
  • uv (Python package manager) - Install
  • Git (for cloning the repository)

Frontend Requirements

  • Node.js 18+ - Download
  • npm or pnpm (comes with Node.js)
  • Git (for cloning the repository)

Quick Start

The fastest way to get everything running:

1. Set Up Backend

# Navigate to backend directory
cd backend

# Install dependencies
uv sync

# Create environment file
cat > .env << 'EOF'
OPENAI_API_KEY=your_openai_api_key_here
LLM_MODEL=gpt-4
DEBUG=true
CORS_ORIGINS=["http://localhost:3000"]
EOF

# Start backend server
uv run uvicorn app.main:app --reload --port 8000 --host 0.0.0.0

The backend should now be running at http://localhost:8000

2. Set Up Frontend

# Navigate to frontend directory (in a new terminal)
cd frontend

# Install dependencies
pnpm install

# Create environment file
cat > .env << 'EOF'
NEXT_PUBLIC_API_URL=http://localhost:8000
EOF

# Start frontend development server
pnpm dev

The frontend should now be running at http://localhost:3000

3. Verify Installation

Option 1: Check the web interface

Open your browser and navigate to:

Option 2: Test LLM Connection

You can verify your LLM provider configuration by running:

cd /root/AIFeyman/backend

# Test the API connection
uv run python -m app.core.llm

This will test:

  • ✅ Base URL is reachable
  • ✅ API key is valid
  • ✅ Model name is recognized

Expected output:

============================================================
Testing LLM API Connection
============================================================

Provider: https://api.openai.com/v1
Model: gpt-4
Status: ✅ Connection successful! API is responding correctly.

============================================================

If you see errors, check:

  • OPENAI_API_KEY is set correctly
  • OPENAI_BASE_URL matches your provider
  • LLM_MODEL is valid for your provider

Detailed Setup Instructions

Backend Setup (Python + FastAPI)

Step 1: Install Dependencies

cd backend

# Install dependencies using uv
uv sync

Step 2: Configure Environment Variables

Create a .env file in the backend directory:

cat > .env << 'EOF'
# OpenAI API Configuration (Required)
OPENAI_API_KEY=sk-your-openai-api-key-here

# LLM Provider Configuration (Optional)
# Default: https://api.openai.com/v1 (Official OpenAI)
# You can use other OpenAI-compatible providers like OpenRouter, Together AI, DeepSeek, etc.
# Examples:
# - Official OpenAI:  https://api.openai.com/v1
# - OpenRouter:       https://openrouter.ai/api/v1
# - Together AI:      https://api.together.xyz/v1
# - DeepSeek:         https://api.deepseek.com/v1
OPENAI_BASE_URL=https://api.openai.com/v1

# LLM Settings (Optional)
LLM_MODEL=gpt-4
LLM_TEMPERATURE=0.3
LLM_MAX_TOKENS=2000

# Server Configuration (Optional)
API_HOST=0.0.0.0
API_PORT=8000
DEBUG=true
LOG_LEVEL=INFO

# Session Configuration (Optional)
SESSION_TIMEOUT_MINUTES=60
MAX_CONCEPTS_PER_SESSION=5

# CORS Configuration (Optional)
CORS_ORIGINS=["http://localhost:3000", "http://localhost:5173"]
EOF

⚠️ Important: Replace your-openai-api-key-here with your actual OpenAI API key.

Step 3: Start Backend Server

# From the backend directory
uv run uvicorn app.main:app --reload --port 8000 --host 0.0.0.0

# Or with more options:
uv run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload --log-level info

Expected Output:

INFO:     Started server process [12345]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)

API Documentation:

Frontend Setup (React + TypeScript)

Step 1: Install Dependencies

cd frontend

# Using pnpm (recommended)
pnpm install

Step 2: Configure Environment Variables

Create a .env file in the frontend directory:

cat > .env << 'EOF'
# Backend API URL
NEXT_PUBLIC_API_URL=http://localhost:8000
EOF

Step 3: Start Development Server

# Using pnpm
pnpm dev

Expected Output:

  Local:   http://localhost:3000
  Network: use --host to expose

  press h + enter to show help

Note: The app will automatically reload when you make changes to the code.

Common Setup Issues

Backend Issues

Issue: "OPENAI_API_KEY not found"

Solution:

  1. Check that you've created the .env file in the backend directory
  2. Verify the API key is set correctly
  3. Restart the backend server after adding the key

Issue: "Port 8000 already in use"

Solution:

# Kill process using port 8000
lsof -ti:8000 | xargs kill -9

# Or use a different port
uv run uvicorn app.main:app --reload --port 8001 --host 0.0.0.0

Issue: "Module not found" errors

Solution:

  1. Reinstall dependencies: uv sync
  2. Check Python version: python --version (should be 3.9+)

Frontend Issues

Issue: "Cannot resolve module" errors

Solution:

# Clear node_modules and reinstall
rm -rf node_modules
pnpm install

Issue: "Port 3000 already in use"

Solution:

# Use a different port
pnpm dev -- --port 3001

Issue: "API calls failing"

Solution:

  1. Check backend is running on http://localhost:8000
  2. Verify .env has correct NEXT_PUBLIC_API_URL
  3. Check browser console for CORS errors
  4. Restart frontend after changing environment variables

Testing the Application

Test Backend API

# Create a test session
curl -X POST http://localhost:8000/api/session/start \
  -H "Content-Type: application/json" \
  -d '{"source_text": "什么是闭包?"}'

# Expected response:
# {
#   "session_id": "some-uuid",
#   "initial_graph": { "nodes": [...], "edges": [...] }
# }

Test Frontend

  1. Open http://localhost:3000 in your browser

  2. You should see the main page with:

    • Title: "AI 知识图谱学习系统"
    • Text input area
    • "开始学习" button
  3. Test the full flow:

    • Enter some text (e.g., "什么是闭包?")
    • Click "开始学习"
    • Wait for session initialization
    • See the knowledge graph and chat interface

Development Workflow

Backend Development

# Navigate to backend
cd backend

# Run with auto-reload
uv run uvicorn app.main:app --reload --port 8000 --host 0.0.0.0

# In another terminal, run tests (if available)
uv run pytest

Frontend Development

# Navigate to frontend
cd frontend

# Install dependencies (if not already installed)
pnpm install

# Start development server with auto-reload
pnpm dev

# Build for production
pnpm build

# Preview production build
pnpm start

Project Structure

/root/AIFeyman
├── backend/
│   ├── app/
│   │   ├── api/           # API route handlers
│   │   │   ├── session.py
│   │   │   ├── chat.py
│   │   │   └── concept.py
│   │   ├── core/          # Core utilities
│   │   │   ├── config.py
│   │   │   ├── session.py
│   │   │   ├── llm.py
│   │   │   └── prompts.py
│   │   ├── models/        # Pydantic schemas
│   │   │   └── schema.py
│   │   └── services/      # Business logic
│   │       ├── graph_engine.py
│   │       └── tutor_engine.py
│   └── main.py            # FastAPI app entry point
│
├── frontend/
│   ├── components/        # React components
│   │   ├── ChatInterface.tsx
│   │   ├── ConceptDrawer.tsx
│   │   ├── KnowledgeGraph.tsx
│   │   └── MainPage.tsx
│   ├── hooks/             # Custom React hooks
│   │   └── useLearningSession.ts
│   ├── types/             # TypeScript types
│   │   └── api.ts
│   ├── utils/             # Utilities
│   │   ├── api-client.ts
│   │   └── network.tsx
│   └── package.json
│
├── CLAUDE.md              # Claude Code guidance
├── API.md                 # API documentation
└── GETTING_STARTED.md     # This file

Next Steps

Once you have the application running:

  1. Explore the API

  2. Understand the Code

    • Read CLAUDE.md for high-level architecture
    • Check API.md for detailed API reference
    • Explore the codebase structure above
  3. Customize

    • Modify prompts in backend/app/core/prompts.py
    • Adjust UI in frontend/components/
    • Add new features following the existing patterns

3a. Use Different LLM Providers

  • The application supports any OpenAI-compatible API provider
  • Edit backend/.env and set:
    # For OpenRouter (access to 100+ models)
    OPENAI_BASE_URL=https://openrouter.ai/api/v1
    OPENAI_API_KEY=sk-or-v1-your-key-here
    LLM_MODEL=meta-llama/llama-2-70b-chat
    
    # For Together AI
    OPENAI_BASE_URL=https://api.together.xyz/v1
    OPENAI_API_KEY=your-together-ai-key
    LLM_MODEL=mistralai/Mixtral-8x7B-Instruct-v0.1
    
    # For DeepSeek (cost-effective, good for coding)
    OPENAI_BASE_URL=https://api.deepseek.com/v1
    OPENAI_API_KEY=your-deepseek-key
    LLM_MODEL=deepseek-chat
    
    # For local deployment (Ollama)
    OPENAI_BASE_URL=http://localhost:11434/v1
    OPENAI_API_KEY=ollama
    LLM_MODEL=llama2
  • Restart the backend server after changing configuration
  1. Production Deployment
    • Set up a real database (PostgreSQL, MongoDB, or Redis)
    • Configure proper CORS origins
    • Set up SSL/TLS certificates
    • Deploy backend to a cloud provider (AWS, GCP, Azure)
    • Deploy frontend to Vercel, Netlify, or similar

Getting Help

If you encounter issues:

  1. Check the Common Setup Issues section above
  2. Review error messages in the terminal/console
  3. Check the browser's developer console (F12)
  4. Consult the API documentation at http://localhost:8000/docs
  5. Review the code comments and documentation

Performance Tips

Backend

  • Use uvicorn with --reload only for development
  • Consider using gunicorn with multiple workers for production
  • Set appropriate SESSION_TIMEOUT_MINUTES for your use case
  • Monitor memory usage with in-memory session storage

Frontend

  • Use production build (pnpm build) for testing performance
  • Enable code splitting for large applications
  • Use React DevTools Profiler to identify performance issues
  • Implement proper error boundaries

Security Notes

⚠️ Important Security Considerations:

  1. API Keys: Never commit API keys to version control
  2. CORS: Restrict CORS_ORIGINS in production
  3. Authentication: Add authentication before deploying to production
  4. Rate Limiting: Implement rate limiting for API endpoints
  5. Input Validation: All inputs are validated with Pydantic
  6. HTTPS: Use HTTPS in production environments

For production deployment, consult your cloud provider's security best practices.

Troubleshooting

Backend Won't Start

# Check Python version
python --version  # Should be 3.9+

# Check virtual environment is activated
which python  # Should show .venv path

# Verify dependencies
pip list

# Check for syntax errors
python -m py_compile main.py

Frontend Won't Start

# Check Node.js version
node --version  # Should be 18+

# Clear cache and reinstall
rm -rf node_modules .next
pnpm install

# Check for TypeScript errors
npx tsc --noEmit

API Calls Failing

# Check backend is running
curl http://localhost:8000/health

# Check CORS configuration
# Verify frontend URL is in CORS_ORIGINS

# Check network tab in browser devtools
# Look for 404, 500, or CORS errors

Summary

You should now have:

Happy coding! 🚀