Skip to content

Latest commit

 

History

History
555 lines (424 loc) · 10.8 KB

File metadata and controls

555 lines (424 loc) · 10.8 KB

Development Guide

This guide provides detailed information for developers working on the Clinical ChatBot project.

Development Environment Setup

Recommended Tools

  • IDE: VS Code, PyCharm, or WebStorm
  • Python: 3.10+
  • Node.js: 18+
  • Git: Latest version
  • Postman: For API testing (optional)

VS Code Extensions (Recommended)

  • Python
  • Pylance
  • ESLint
  • Prettier
  • TypeScript and JavaScript Language Features
  • REST Client

Project Standards

Code Style

Python (Backend)

  • Follow PEP 8 style guide
  • Maximum line length: 88 characters (Black formatter)
  • Use type hints
  • Docstrings for all functions/classes (Google style)

Example:

def process_document(
    file_path: str,
    document_type: str = "clinical_guideline"
) -> Dict[str, Any]:
    """
    Process and index a clinical document.

    Args:
        file_path: Path to the document file
        document_type: Type of clinical document

    Returns:
        Dict containing processing results

    Raises:
        ValueError: If file_path is invalid
    """
    pass

TypeScript (Frontend)

  • Follow Airbnb TypeScript Style Guide
  • Use explicit types (avoid any)
  • Use functional components with hooks
  • Document complex functions with JSDoc

Example:

/**
 * Send a chat message and update state
 *
 * @param message - User's message text
 * @returns Promise that resolves when message is sent
 */
async function sendMessage(message: string): Promise<void> {
  // Implementation
}

Git Workflow

Branch Naming

  • Feature: feature/description
  • Bug fix: fix/description
  • Hotfix: hotfix/description
  • Documentation: docs/description

Example:

git checkout -b feature/add-file-upload

Commit Messages

Follow conventional commits:

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation changes
  • style: Code style changes (formatting)
  • refactor: Code refactoring
  • test: Adding/updating tests
  • chore: Maintenance tasks

Example:

git commit -m "feat: add PDF document upload functionality"
git commit -m "fix: resolve CORS issue in production"
git commit -m "docs: update API documentation"

Testing Requirements

Backend Testing

  • Minimum 80% code coverage
  • Unit tests for all services
  • Integration tests for API endpoints
  • Mock external dependencies

Run tests:

cd backend
pytest --cov=app --cov-report=html

View coverage:

open htmlcov/index.html  # macOS
start htmlcov/index.html  # Windows

Frontend Testing

  • Test all components
  • Test user interactions
  • Test API integration
  • Snapshot tests for UI components

Run tests:

cd frontend
npm test
npm run test:watch  # Watch mode

Code Review Checklist

Before submitting a PR:

  • Code follows style guide
  • All tests pass
  • New features have tests
  • Documentation is updated
  • No console.log/print statements
  • No commented-out code
  • Error handling is implemented
  • Types are properly defined
  • Commit messages are clear

Development Workflow

1. Starting a New Feature

# Update main branch
git checkout main
git pull origin main

# Create feature branch
git checkout -b feature/new-feature

# Make changes and test
# ...

# Commit changes
git add .
git commit -m "feat: add new feature"

# Push to remote
git push origin feature/new-feature

# Create pull request on GitHub

2. Running Backend in Development

cd backend
source venv/bin/activate  # or venv\Scripts\activate on Windows

# Run with hot reload
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Or use the main.py
python -m app.main

3. Running Frontend in Development

cd frontend

# Run with hot reload
npm run dev

# Run on different port
npm run dev -- -p 3001

4. Debugging

Backend Debugging (VS Code)

Create .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: FastAPI",
      "type": "python",
      "request": "launch",
      "module": "uvicorn",
      "args": [
        "app.main:app",
        "--reload"
      ],
      "jinja": true,
      "justMyCode": false,
      "cwd": "${workspaceFolder}/backend"
    }
  ]
}

Frontend Debugging (VS Code)

Create .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Next.js: debug",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["run", "dev"],
      "port": 9229,
      "cwd": "${workspaceFolder}/frontend"
    }
  ]
}

API Development

Adding a New Endpoint

  1. Define Schema in backend/app/models/schemas.py:
class NewFeatureRequest(BaseModel):
    """Schema for new feature request"""
    param1: str
    param2: int = Field(default=0, ge=0)
  1. Create Service in backend/app/services/:
class NewFeatureService:
    """Service for new feature"""

    def process(self, request: NewFeatureRequest) -> Dict[str, Any]:
        """Process the new feature"""
        # Implementation
        pass
  1. Add Route in backend/app/api/routes/:
@router.post("/new-feature")
async def new_feature(request: NewFeatureRequest):
    """New feature endpoint"""
    result = service.process(request)
    return result
  1. Add Tests in backend/tests/:
def test_new_feature_success(test_client):
    """Test new feature endpoint"""
    response = test_client.post(
        "/api/new-feature",
        json={"param1": "value", "param2": 10}
    )
    assert response.status_code == 200
  1. Update Frontend API in frontend/src/services/api.ts:
async newFeature(param1: string, param2: number): Promise<any> {
  const response = await this.client.post('/api/new-feature', {
    param1,
    param2,
  });
  return response.data;
}

Component Development

Creating a New React Component

  1. Create Component File: frontend/src/components/NewComponent.tsx
/**
 * NewComponent description.
 * Detailed explanation of component purpose.
 */

import React from 'react';
import { Box, Typography } from '@mui/material';

interface NewComponentProps {
  /** Prop description */
  prop1: string;
  /** Optional prop */
  prop2?: number;
}

/**
 * Component description
 *
 * @param props - Component props
 * @returns JSX element
 */
export const NewComponent: React.FC<NewComponentProps> = ({
  prop1,
  prop2 = 0,
}) => {
  return (
    <Box>
      <Typography>{prop1}</Typography>
    </Box>
  );
};
  1. Add Tests: frontend/src/components/__tests__/NewComponent.test.tsx
import { render, screen } from '@testing-library/react';
import { NewComponent } from '../NewComponent';

describe('NewComponent', () => {
  it('renders correctly', () => {
    render(<NewComponent prop1="test" />);
    expect(screen.getByText('test')).toBeInTheDocument();
  });
});

Database Management

Pinecone Index Management

Create New Index

from app.services.pinecone_service import pinecone_service

# The index is automatically created on startup
# See: backend/app/services/pinecone_service.py

Query Index

# Search for similar documents
results = pinecone_service.similarity_search(
    query="medical query",
    k=5
)

Delete Documents

# Delete all documents in namespace
pinecone_service.delete_namespace("namespace_name")

Environment Variables

Backend Environment Variables

Variable Description Required Default
OPENAI_API_KEY OpenAI API key Yes -
PINECONE_API_KEY Pinecone API key Yes -
PINECONE_ENVIRONMENT Pinecone region Yes -
PINECONE_INDEX_NAME Index name No clinical-chatbot
APP_ENV Environment No development
APP_HOST Host address No 0.0.0.0
APP_PORT Port number No 8000
SECRET_KEY JWT secret Yes -
CHUNK_SIZE Text chunk size No 1000
CHUNK_OVERLAP Chunk overlap No 200
TEMPERATURE LLM temperature No 0.7

Frontend Environment Variables

Variable Description Required Default
NEXT_PUBLIC_API_URL Backend API URL No http://localhost:8000

Performance Optimization

Backend Optimization

  1. Caching:

    • Implement Redis for conversation memory
    • Cache frequently accessed documents
  2. Async Operations:

    • Use async/await for I/O operations
    • Parallelize independent operations
  3. Database Queries:

    • Optimize vector search parameters
    • Use appropriate index settings

Frontend Optimization

  1. Code Splitting:

    • Use dynamic imports
    • Lazy load components
  2. Memoization:

    • Use React.memo for expensive components
    • Use useMemo for expensive calculations
  3. Bundle Size:

    • Analyze bundle with npm run build
    • Remove unused dependencies

Troubleshooting

Common Development Issues

Issue: Import Errors in Backend

# Solution: Ensure virtual environment is activated
source venv/bin/activate  # or venv\Scripts\activate

# Reinstall dependencies
pip install -r requirements.txt

Issue: Module Not Found in Frontend

# Solution: Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

Issue: CORS Errors

# Solution: Check CORS settings in backend/app/main.py
# Ensure frontend origin is in CORS_ORIGINS env variable
CORS_ORIGINS=http://localhost:3000,http://localhost:3001

Issue: Pinecone Connection Timeout

# Solution: Check Pinecone status and API key
# Try increasing timeout in service initialization

Useful Commands

Backend

# Run server
python -m app.main

# Run tests
pytest

# Run tests with coverage
pytest --cov=app --cov-report=html

# Format code
black app/ tests/

# Type checking
mypy app/

# Lint code
flake8 app/ tests/

Frontend

# Run development server
npm run dev

# Build for production
npm run build

# Start production server
npm start

# Run tests
npm test

# Lint code
npm run lint

# Type check
npm run type-check  # if configured

Contributing

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

Resources

Getting Help

  • Check existing issues on GitHub
  • Review API documentation at /api/docs
  • Check logs for error messages
  • Ask questions in discussions

Happy coding! 🚀