Deploy backend
Browse files- Dockerfile +15 -0
- README.md +6 -6
- app/__init__.py +0 -0
- app/api/__init__.py +0 -0
- app/api/deps.py +33 -0
- app/api/v1/__init__.py +0 -0
- app/api/v1/chat.py +15 -0
- app/api/v1/health.py +8 -0
- app/api/v1/ingest.py +55 -0
- app/api/v1/search.py +15 -0
- app/core/__init__.py +0 -0
- app/core/config.py +46 -0
- app/core/lifespan.py +20 -0
- app/main.py +33 -0
- app/models/__init__.py +0 -0
- app/models/chat.py +17 -0
- app/models/ingest.py +42 -0
- app/models/search.py +23 -0
- app/repositories/__init__.py +0 -0
- app/repositories/pinecone_repo.py +125 -0
- app/services/__init__.py +0 -0
- app/services/chat.py +81 -0
- app/services/embedding.py +35 -0
- app/services/github.py +86 -0
- app/services/ingestion.py +362 -0
- app/services/retrieval.py +27 -0
- pyproject.toml +31 -0
Dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 6 |
+
ENV PYTHONUNBUFFERED=1
|
| 7 |
+
|
| 8 |
+
COPY pyproject.toml /app/
|
| 9 |
+
RUN pip install --no-cache-dir .[dev]
|
| 10 |
+
|
| 11 |
+
COPY app /app/app
|
| 12 |
+
|
| 13 |
+
EXPOSE 7860
|
| 14 |
+
|
| 15 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
-
|
| 10 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
+
@"
|
| 2 |
---
|
| 3 |
+
title: Codebase Analyzer API
|
| 4 |
+
emoji: 🔍
|
| 5 |
+
colorFrom: orange
|
| 6 |
+
colorTo: red
|
| 7 |
sdk: docker
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
+
"@ | Set-Content README.md
|
|
|
app/__init__.py
ADDED
|
File without changes
|
app/api/__init__.py
ADDED
|
File without changes
|
app/api/deps.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
|
| 3 |
+
from fastapi import Depends
|
| 4 |
+
|
| 5 |
+
from app.repositories.pinecone_repo import PineconeRepository
|
| 6 |
+
from app.services.chat import ChatService
|
| 7 |
+
from app.services.embedding import EmbeddingService, get_embedding_service
|
| 8 |
+
from app.services.ingestion import IngestionService
|
| 9 |
+
from app.services.retrieval import RetrievalService
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@lru_cache(maxsize=1)
|
| 13 |
+
def get_pinecone_repo() -> PineconeRepository:
|
| 14 |
+
return PineconeRepository()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_retrieval_service(
|
| 18 |
+
embedder: EmbeddingService = Depends(get_embedding_service),
|
| 19 |
+
repo: PineconeRepository = Depends(get_pinecone_repo),
|
| 20 |
+
) -> RetrievalService:
|
| 21 |
+
return RetrievalService(embedder=embedder, repo=repo)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@lru_cache(maxsize=1)
|
| 25 |
+
def get_chat_service() -> ChatService:
|
| 26 |
+
return ChatService()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_ingestion_service(
|
| 30 |
+
embedder: EmbeddingService = Depends(get_embedding_service),
|
| 31 |
+
repo: PineconeRepository = Depends(get_pinecone_repo),
|
| 32 |
+
) -> IngestionService:
|
| 33 |
+
return IngestionService(embedder=embedder, repo=repo)
|
app/api/v1/__init__.py
ADDED
|
File without changes
|
app/api/v1/chat.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends
|
| 2 |
+
|
| 3 |
+
from app.api.deps import get_chat_service
|
| 4 |
+
from app.models.chat import ChatRequest, ChatResponse
|
| 5 |
+
from app.services.chat import ChatService
|
| 6 |
+
|
| 7 |
+
router = APIRouter(prefix="/chat", tags=["chat"])
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@router.post("", response_model=ChatResponse)
|
| 11 |
+
async def chat(
|
| 12 |
+
payload: ChatRequest,
|
| 13 |
+
service: ChatService = Depends(get_chat_service),
|
| 14 |
+
) -> ChatResponse:
|
| 15 |
+
return await service.chat(payload)
|
app/api/v1/health.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter
|
| 2 |
+
|
| 3 |
+
router = APIRouter(prefix="/health", tags=["health"])
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@router.get("/")
|
| 7 |
+
async def health() -> dict[str, str]:
|
| 8 |
+
return {"status": "ok"}
|
app/api/v1/ingest.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 2 |
+
|
| 3 |
+
from app.api.deps import get_ingestion_service
|
| 4 |
+
from app.models.ingest import (
|
| 5 |
+
AnalyzeRequest,
|
| 6 |
+
AnalyzeResponse,
|
| 7 |
+
IngestRequest,
|
| 8 |
+
IngestResponse,
|
| 9 |
+
ProgressResponse,
|
| 10 |
+
)
|
| 11 |
+
from app.services.ingestion import IngestionService, progress_store
|
| 12 |
+
|
| 13 |
+
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@router.post("", response_model=IngestResponse)
|
| 17 |
+
async def ingest(
|
| 18 |
+
payload: IngestRequest,
|
| 19 |
+
service: IngestionService = Depends(get_ingestion_service),
|
| 20 |
+
) -> IngestResponse:
|
| 21 |
+
try:
|
| 22 |
+
return await service.ingest(payload)
|
| 23 |
+
except ValueError as exc:
|
| 24 |
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@router.post("/analyze", response_model=AnalyzeResponse)
|
| 28 |
+
async def analyze(
|
| 29 |
+
payload: AnalyzeRequest,
|
| 30 |
+
service: IngestionService = Depends(get_ingestion_service),
|
| 31 |
+
) -> AnalyzeResponse:
|
| 32 |
+
try:
|
| 33 |
+
return await service.analyze(payload)
|
| 34 |
+
except ValueError as exc:
|
| 35 |
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@router.get("/progress/{job_id}", response_model=ProgressResponse)
|
| 39 |
+
async def ingest_progress(job_id: str) -> ProgressResponse:
|
| 40 |
+
state = progress_store.get(job_id)
|
| 41 |
+
if not state:
|
| 42 |
+
raise HTTPException(status_code=404, detail="Ingest job not found.")
|
| 43 |
+
|
| 44 |
+
percent = 0
|
| 45 |
+
if state.files_total > 0:
|
| 46 |
+
percent = int(state.files_processed / state.files_total * 100)
|
| 47 |
+
|
| 48 |
+
return ProgressResponse(
|
| 49 |
+
job_id=state.job_id,
|
| 50 |
+
status=state.status,
|
| 51 |
+
files_total=state.files_total,
|
| 52 |
+
files_processed=state.files_processed,
|
| 53 |
+
chunks_indexed=state.chunks_indexed,
|
| 54 |
+
percent=percent,
|
| 55 |
+
)
|
app/api/v1/search.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends
|
| 2 |
+
|
| 3 |
+
from app.api.deps import get_retrieval_service
|
| 4 |
+
from app.models.search import SearchRequest, SearchResponse
|
| 5 |
+
from app.services.retrieval import RetrievalService
|
| 6 |
+
|
| 7 |
+
router = APIRouter(prefix="/search", tags=["search"])
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@router.post("", response_model=SearchResponse)
|
| 11 |
+
async def search(
|
| 12 |
+
payload: SearchRequest,
|
| 13 |
+
service: RetrievalService = Depends(get_retrieval_service),
|
| 14 |
+
) -> SearchResponse:
|
| 15 |
+
return await service.search(payload)
|
app/core/__init__.py
ADDED
|
File without changes
|
app/core/config.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
|
| 3 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Settings(BaseSettings):
|
| 7 |
+
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
| 8 |
+
|
| 9 |
+
app_name: str = "Codebase Analyzer API"
|
| 10 |
+
debug: bool = False
|
| 11 |
+
frontend_origin: str = "http://localhost:5173"
|
| 12 |
+
|
| 13 |
+
pinecone_api_key: str
|
| 14 |
+
pinecone_index_name: str
|
| 15 |
+
pinecone_cloud: str = "aws"
|
| 16 |
+
pinecone_region: str = "us-east-1"
|
| 17 |
+
pinecone_max_request_bytes: int = 1_900_000
|
| 18 |
+
|
| 19 |
+
hf_api_token: str | None = None
|
| 20 |
+
hf_embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2"
|
| 21 |
+
hf_embedding_dimension: int = 384
|
| 22 |
+
hf_device: str = "cpu"
|
| 23 |
+
|
| 24 |
+
hf_generation_model: str = "google/flan-t5-base"
|
| 25 |
+
hf_generation_max_new_tokens: int = 256
|
| 26 |
+
hf_generation_temperature: float = 0.7
|
| 27 |
+
|
| 28 |
+
github_token: str | None = None
|
| 29 |
+
ingest_max_repo_mb: int = 200
|
| 30 |
+
ingest_chunk_size: int = 1000
|
| 31 |
+
ingest_chunk_overlap: int = 200
|
| 32 |
+
ingest_batch_size: int = 16
|
| 33 |
+
ingest_embed_timeout_sec: int = 120
|
| 34 |
+
ingest_ignored_dirs: tuple[str, ...] = (
|
| 35 |
+
"node_modules",
|
| 36 |
+
"dist",
|
| 37 |
+
"build",
|
| 38 |
+
"venv",
|
| 39 |
+
".venv",
|
| 40 |
+
"__pycache__",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@lru_cache(maxsize=1)
|
| 45 |
+
def get_settings() -> Settings:
|
| 46 |
+
return Settings()
|
app/core/lifespan.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import asynccontextmanager
|
| 2 |
+
from typing import AsyncIterator
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
from fastapi import FastAPI
|
| 6 |
+
|
| 7 |
+
from app.services.embedding import get_embedding_service
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@asynccontextmanager
|
| 13 |
+
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
| 14 |
+
try:
|
| 15 |
+
# Attempt to pre-warm the embedding model, but don't fail startup
|
| 16 |
+
# if the model cannot be downloaded (e.g., network-restricted env).
|
| 17 |
+
get_embedding_service()
|
| 18 |
+
except Exception as exc: # pragma: no cover - defensive guard
|
| 19 |
+
logger.warning("Embedding model pre-warm failed: %s", exc)
|
| 20 |
+
yield
|
app/main.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
|
| 4 |
+
from app.api.v1 import chat, health, ingest, search
|
| 5 |
+
from app.core.config import get_settings
|
| 6 |
+
from app.core.lifespan import lifespan
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def create_app() -> FastAPI:
|
| 10 |
+
settings = get_settings()
|
| 11 |
+
origins = {
|
| 12 |
+
settings.frontend_origin, # from .env
|
| 13 |
+
"http://localhost:5173",
|
| 14 |
+
"http://127.0.0.1:5173",
|
| 15 |
+
"https://codelens-analyzer.netlify.app/", # ← add this
|
| 16 |
+
}
|
| 17 |
+
app = FastAPI(title=settings.app_name, debug=settings.debug, lifespan=lifespan)
|
| 18 |
+
app.add_middleware(
|
| 19 |
+
CORSMiddleware,
|
| 20 |
+
allow_origins=sorted(origins),
|
| 21 |
+
allow_credentials=True,
|
| 22 |
+
allow_methods=["*"],
|
| 23 |
+
allow_headers=["*"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
app.include_router(health.router, prefix="/api/v1")
|
| 27 |
+
app.include_router(search.router, prefix="/api/v1")
|
| 28 |
+
app.include_router(chat.router, prefix="/api/v1")
|
| 29 |
+
app.include_router(ingest.router, prefix="/api/v1")
|
| 30 |
+
return app
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
app = create_app()
|
app/models/__init__.py
ADDED
|
File without changes
|
app/models/chat.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ChatTurn(BaseModel):
|
| 5 |
+
user: str = Field(..., min_length=1, max_length=4000)
|
| 6 |
+
assistant: str = Field(..., min_length=1, max_length=4000)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ChatRequest(BaseModel):
|
| 10 |
+
question: str = Field(..., min_length=1, max_length=4000)
|
| 11 |
+
history: list[ChatTurn] = Field(default_factory=list)
|
| 12 |
+
filter: dict | None = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ChatResponse(BaseModel):
|
| 16 |
+
answer: str
|
| 17 |
+
sources: list[dict] = Field(default_factory=list)
|
app/models/ingest.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class IngestRequest(BaseModel):
|
| 5 |
+
repo_url: str = Field(..., min_length=1, max_length=500)
|
| 6 |
+
branch: str | None = Field(default=None, max_length=200)
|
| 7 |
+
job_id: str | None = Field(default=None, max_length=100)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class IngestResponse(BaseModel):
|
| 11 |
+
repo: str
|
| 12 |
+
branch: str
|
| 13 |
+
files_indexed: int
|
| 14 |
+
chunks_indexed: int
|
| 15 |
+
reused: bool = False
|
| 16 |
+
warnings: list[str] = Field(default_factory=list)
|
| 17 |
+
top_level_entries: list[str] = Field(default_factory=list)
|
| 18 |
+
sample_files: list[str] = Field(default_factory=list)
|
| 19 |
+
job_id: str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class AnalyzeRequest(BaseModel):
|
| 23 |
+
repo_url: str = Field(..., min_length=1, max_length=500)
|
| 24 |
+
branch: str | None = Field(default=None, max_length=200)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class AnalyzeResponse(BaseModel):
|
| 28 |
+
repo: str
|
| 29 |
+
branch: str
|
| 30 |
+
file_count: int
|
| 31 |
+
total_bytes: int
|
| 32 |
+
top_level_entries: list[str] = Field(default_factory=list)
|
| 33 |
+
file_paths: list[str] = Field(default_factory=list)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ProgressResponse(BaseModel):
|
| 37 |
+
job_id: str
|
| 38 |
+
status: str
|
| 39 |
+
files_total: int
|
| 40 |
+
files_processed: int
|
| 41 |
+
chunks_indexed: int
|
| 42 |
+
percent: int
|
app/models/search.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
from pydantic import BaseModel, Field
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class SearchRequest(BaseModel):
|
| 7 |
+
query: str = Field(..., min_length=1, max_length=500)
|
| 8 |
+
top_k: int = Field(default=5, ge=1, le=20)
|
| 9 |
+
filter: dict[str, Any] | None = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SearchResult(BaseModel):
|
| 13 |
+
id: str
|
| 14 |
+
score: float
|
| 15 |
+
title: str | None = None
|
| 16 |
+
content: str | None = None
|
| 17 |
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SearchResponse(BaseModel):
|
| 21 |
+
query: str
|
| 22 |
+
results: list[SearchResult]
|
| 23 |
+
total: int
|
app/repositories/__init__.py
ADDED
|
File without changes
|
app/repositories/pinecone_repo.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
from typing import Any, Iterable
|
| 4 |
+
|
| 5 |
+
from pinecone import Pinecone
|
| 6 |
+
|
| 7 |
+
from app.core.config import get_settings
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class PineconeRepository:
|
| 11 |
+
def __init__(self) -> None:
|
| 12 |
+
settings = get_settings()
|
| 13 |
+
self._client = Pinecone(api_key=settings.pinecone_api_key)
|
| 14 |
+
self._index_name = settings.pinecone_index_name
|
| 15 |
+
self._index = self._client.Index(self._index_name)
|
| 16 |
+
self._dimension: int | None = None
|
| 17 |
+
|
| 18 |
+
def get_dimension(self) -> int:
|
| 19 |
+
if self._dimension is not None:
|
| 20 |
+
return self._dimension
|
| 21 |
+
|
| 22 |
+
description = self._client.describe_index(self._index_name)
|
| 23 |
+
dimension = getattr(description, "dimension", None)
|
| 24 |
+
if dimension is None and isinstance(description, dict):
|
| 25 |
+
dimension = description.get("dimension")
|
| 26 |
+
if not dimension:
|
| 27 |
+
raise ValueError("Unable to resolve Pinecone index dimension.")
|
| 28 |
+
|
| 29 |
+
self._dimension = int(dimension)
|
| 30 |
+
return self._dimension
|
| 31 |
+
|
| 32 |
+
async def query(
|
| 33 |
+
self,
|
| 34 |
+
vector: list[float],
|
| 35 |
+
top_k: int = 5,
|
| 36 |
+
filter: dict[str, Any] | None = None,
|
| 37 |
+
) -> list[dict[str, Any]]:
|
| 38 |
+
loop = asyncio.get_event_loop()
|
| 39 |
+
response = await loop.run_in_executor(
|
| 40 |
+
None,
|
| 41 |
+
lambda: self._index.query(
|
| 42 |
+
vector=vector,
|
| 43 |
+
top_k=top_k,
|
| 44 |
+
include_metadata=True,
|
| 45 |
+
filter=filter,
|
| 46 |
+
),
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
return [
|
| 50 |
+
{
|
| 51 |
+
"id": match.id,
|
| 52 |
+
"score": match.score,
|
| 53 |
+
**(match.metadata or {}),
|
| 54 |
+
}
|
| 55 |
+
for match in response.matches
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
async def upsert(self, vectors: list[dict[str, Any]]) -> None:
|
| 59 |
+
loop = asyncio.get_event_loop()
|
| 60 |
+
settings = get_settings()
|
| 61 |
+
for batch in _chunk_vectors_by_size(vectors, settings.pinecone_max_request_bytes):
|
| 62 |
+
await loop.run_in_executor(
|
| 63 |
+
None,
|
| 64 |
+
lambda payload=batch: self._index.upsert(vectors=payload),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
async def count_by_filter(self, filter: dict[str, Any]) -> int:
|
| 68 |
+
loop = asyncio.get_event_loop()
|
| 69 |
+
try:
|
| 70 |
+
response = await loop.run_in_executor(
|
| 71 |
+
None,
|
| 72 |
+
lambda: self._index.describe_index_stats(filter=filter),
|
| 73 |
+
)
|
| 74 |
+
except Exception as exc:
|
| 75 |
+
message = str(exc)
|
| 76 |
+
if "do not support describing index stats with metadata filtering" in message:
|
| 77 |
+
return -1
|
| 78 |
+
raise
|
| 79 |
+
|
| 80 |
+
total = getattr(response, "total_vector_count", None)
|
| 81 |
+
if total is None and isinstance(response, dict):
|
| 82 |
+
total = response.get("total_vector_count")
|
| 83 |
+
|
| 84 |
+
if total is not None:
|
| 85 |
+
return int(total)
|
| 86 |
+
|
| 87 |
+
namespaces = getattr(response, "namespaces", None)
|
| 88 |
+
if namespaces is None and isinstance(response, dict):
|
| 89 |
+
namespaces = response.get("namespaces")
|
| 90 |
+
if isinstance(namespaces, dict):
|
| 91 |
+
return int(sum(item.get("vector_count", 0) for item in namespaces.values()))
|
| 92 |
+
|
| 93 |
+
return 0
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _chunk_vectors_by_size(
|
| 97 |
+
vectors: Iterable[dict[str, Any]],
|
| 98 |
+
max_bytes: int,
|
| 99 |
+
) -> list[list[dict[str, Any]]]:
|
| 100 |
+
batches: list[list[dict[str, Any]]] = []
|
| 101 |
+
current_batch: list[dict[str, Any]] = []
|
| 102 |
+
current_size = 0
|
| 103 |
+
|
| 104 |
+
for vector in vectors:
|
| 105 |
+
vector_size = _estimate_vector_size(vector)
|
| 106 |
+
if vector_size > max_bytes:
|
| 107 |
+
raise ValueError("Vector exceeds Pinecone request size limit.")
|
| 108 |
+
|
| 109 |
+
if current_batch and current_size + vector_size > max_bytes:
|
| 110 |
+
batches.append(current_batch)
|
| 111 |
+
current_batch = [vector]
|
| 112 |
+
current_size = vector_size
|
| 113 |
+
else:
|
| 114 |
+
current_batch.append(vector)
|
| 115 |
+
current_size += vector_size
|
| 116 |
+
|
| 117 |
+
if current_batch:
|
| 118 |
+
batches.append(current_batch)
|
| 119 |
+
|
| 120 |
+
return batches
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _estimate_vector_size(vector: dict[str, Any]) -> int:
|
| 124 |
+
payload = json.dumps(vector, separators=(",", ":"), ensure_ascii=True)
|
| 125 |
+
return len(payload.encode("utf-8"))
|
app/services/__init__.py
ADDED
|
File without changes
|
app/services/chat.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
|
| 4 |
+
from huggingface_hub import InferenceClient
|
| 5 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 6 |
+
from langchain_pinecone import PineconeVectorStore
|
| 7 |
+
from pinecone import Pinecone
|
| 8 |
+
|
| 9 |
+
from app.core.config import get_settings
|
| 10 |
+
from app.models.chat import ChatRequest, ChatResponse
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@lru_cache(maxsize=1)
|
| 14 |
+
def _build_client() -> InferenceClient:
|
| 15 |
+
settings = get_settings()
|
| 16 |
+
if not settings.hf_api_token:
|
| 17 |
+
raise ValueError("HF_API_TOKEN is required for Hugging Face Inference API.")
|
| 18 |
+
return InferenceClient(token=settings.hf_api_token)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ChatService:
|
| 22 |
+
def __init__(self) -> None:
|
| 23 |
+
settings = get_settings()
|
| 24 |
+
|
| 25 |
+
embeddings = HuggingFaceEmbeddings(
|
| 26 |
+
model_name=settings.hf_embedding_model,
|
| 27 |
+
model_kwargs={"device": settings.hf_device},
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
client = Pinecone(api_key=settings.pinecone_api_key)
|
| 31 |
+
index = client.Index(settings.pinecone_index_name)
|
| 32 |
+
vector_store = PineconeVectorStore(index=index, embedding=embeddings)
|
| 33 |
+
|
| 34 |
+
self._vector_store = vector_store
|
| 35 |
+
self._client = _build_client()
|
| 36 |
+
self._model = settings.hf_generation_model
|
| 37 |
+
self._max_new_tokens = settings.hf_generation_max_new_tokens
|
| 38 |
+
self._temperature = settings.hf_generation_temperature
|
| 39 |
+
|
| 40 |
+
async def chat(self, payload: ChatRequest) -> ChatResponse:
|
| 41 |
+
loop = asyncio.get_event_loop()
|
| 42 |
+
|
| 43 |
+
filter_payload = payload.filter or None
|
| 44 |
+
documents = await loop.run_in_executor(
|
| 45 |
+
None,
|
| 46 |
+
lambda: self._vector_store.similarity_search(
|
| 47 |
+
payload.question,
|
| 48 |
+
k=4,
|
| 49 |
+
filter=filter_payload,
|
| 50 |
+
),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
context = "\n\n".join(
|
| 54 |
+
doc.page_content for doc in documents if doc.page_content
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
messages = [
|
| 58 |
+
{
|
| 59 |
+
"role": "system",
|
| 60 |
+
"content": (
|
| 61 |
+
"You are a codebase assistant. Use the context below to answer the question. "
|
| 62 |
+
"If the context is empty, say you do not have enough information.\n\n"
|
| 63 |
+
f"Context:\n{context}"
|
| 64 |
+
),
|
| 65 |
+
},
|
| 66 |
+
{"role": "user", "content": payload.question},
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
response = await loop.run_in_executor(
|
| 70 |
+
None,
|
| 71 |
+
lambda: self._client.chat_completion(
|
| 72 |
+
messages=messages,
|
| 73 |
+
model=self._model,
|
| 74 |
+
max_tokens=self._max_new_tokens,
|
| 75 |
+
temperature=self._temperature,
|
| 76 |
+
),
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
answer = response.choices[0].message.content
|
| 80 |
+
sources = [doc.metadata or {} for doc in documents]
|
| 81 |
+
return ChatResponse(answer=answer.strip(), sources=sources)
|
app/services/embedding.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
|
| 4 |
+
from huggingface_hub import InferenceClient
|
| 5 |
+
|
| 6 |
+
from app.core.config import get_settings
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class EmbeddingService:
|
| 10 |
+
def __init__(self) -> None:
|
| 11 |
+
settings = get_settings()
|
| 12 |
+
if not settings.hf_api_token:
|
| 13 |
+
raise ValueError("HF_API_TOKEN is required for Hugging Face Inference API.")
|
| 14 |
+
|
| 15 |
+
self._client = InferenceClient(token=settings.hf_api_token)
|
| 16 |
+
self._model = settings.hf_embedding_model
|
| 17 |
+
|
| 18 |
+
async def embed(self, text: str) -> list[float]:
|
| 19 |
+
loop = asyncio.get_event_loop()
|
| 20 |
+
return await loop.run_in_executor(
|
| 21 |
+
None,
|
| 22 |
+
lambda: self._client.feature_extraction(text, model=self._model).tolist(),
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
async def embed_batch(self, texts: list[str]) -> list[list[float]]:
|
| 26 |
+
loop = asyncio.get_event_loop()
|
| 27 |
+
return await loop.run_in_executor(
|
| 28 |
+
None,
|
| 29 |
+
lambda: self._client.feature_extraction(texts, model=self._model).tolist(),
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@lru_cache(maxsize=1)
|
| 34 |
+
def get_embedding_service() -> EmbeddingService:
|
| 35 |
+
return EmbeddingService()
|
app/services/github.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import tempfile
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
from urllib.parse import urlparse
|
| 7 |
+
|
| 8 |
+
import httpx
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def parse_github_repo_url(repo_url: str) -> tuple[str, str, str | None]:
|
| 12 |
+
normalized = repo_url.strip()
|
| 13 |
+
if not normalized.startswith("http"):
|
| 14 |
+
normalized = f"https://{normalized}"
|
| 15 |
+
|
| 16 |
+
parsed = urlparse(normalized)
|
| 17 |
+
if parsed.netloc not in {"github.com", "www.github.com"}:
|
| 18 |
+
raise ValueError("Only github.com repositories are supported.")
|
| 19 |
+
|
| 20 |
+
parts = [segment for segment in parsed.path.split("/") if segment]
|
| 21 |
+
if len(parts) < 2:
|
| 22 |
+
raise ValueError("Repository URL must include owner and repo name.")
|
| 23 |
+
|
| 24 |
+
owner = parts[0]
|
| 25 |
+
repo = parts[1].removesuffix(".git")
|
| 26 |
+
branch = None
|
| 27 |
+
|
| 28 |
+
if len(parts) >= 4 and parts[2] == "tree":
|
| 29 |
+
branch = parts[3]
|
| 30 |
+
|
| 31 |
+
return owner, repo, branch
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
async def fetch_repo_metadata(
|
| 35 |
+
owner: str,
|
| 36 |
+
repo: str,
|
| 37 |
+
token: str | None,
|
| 38 |
+
) -> dict[str, Any]:
|
| 39 |
+
headers = {
|
| 40 |
+
"Accept": "application/vnd.github+json",
|
| 41 |
+
"User-Agent": "codebase-analyzer",
|
| 42 |
+
}
|
| 43 |
+
if token:
|
| 44 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 45 |
+
|
| 46 |
+
url = f"https://api.github.com/repos/{owner}/{repo}"
|
| 47 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 48 |
+
response = await client.get(url, headers=headers)
|
| 49 |
+
response.raise_for_status()
|
| 50 |
+
return response.json()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
async def download_repo_zip(
|
| 54 |
+
owner: str,
|
| 55 |
+
repo: str,
|
| 56 |
+
branch: str,
|
| 57 |
+
token: str | None,
|
| 58 |
+
max_bytes: int,
|
| 59 |
+
) -> Path:
|
| 60 |
+
headers = {
|
| 61 |
+
"Accept": "application/vnd.github+json",
|
| 62 |
+
"User-Agent": "codebase-analyzer",
|
| 63 |
+
}
|
| 64 |
+
if token:
|
| 65 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 66 |
+
|
| 67 |
+
url = f"https://api.github.com/repos/{owner}/{repo}/zipball/{branch}"
|
| 68 |
+
temp_dir = Path(tempfile.mkdtemp())
|
| 69 |
+
zip_path = temp_dir / "repo.zip"
|
| 70 |
+
|
| 71 |
+
async with httpx.AsyncClient(timeout=None, follow_redirects=True) as client:
|
| 72 |
+
async with client.stream("GET", url, headers=headers) as response:
|
| 73 |
+
response.raise_for_status()
|
| 74 |
+
content_length = response.headers.get("Content-Length")
|
| 75 |
+
if content_length and int(content_length) > max_bytes:
|
| 76 |
+
raise ValueError("Repository archive exceeds size limit.")
|
| 77 |
+
|
| 78 |
+
downloaded = 0
|
| 79 |
+
with zip_path.open("wb") as handle:
|
| 80 |
+
async for chunk in response.aiter_bytes():
|
| 81 |
+
downloaded += len(chunk)
|
| 82 |
+
if downloaded > max_bytes:
|
| 83 |
+
raise ValueError("Repository archive exceeds size limit.")
|
| 84 |
+
handle.write(chunk)
|
| 85 |
+
|
| 86 |
+
return zip_path
|
app/services/ingestion.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import uuid
|
| 5 |
+
import zipfile
|
| 6 |
+
import asyncio
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from threading import Lock
|
| 10 |
+
from typing import Iterable
|
| 11 |
+
|
| 12 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 13 |
+
|
| 14 |
+
from app.core.config import get_settings
|
| 15 |
+
from app.models.ingest import (
|
| 16 |
+
AnalyzeRequest,
|
| 17 |
+
AnalyzeResponse,
|
| 18 |
+
IngestRequest,
|
| 19 |
+
IngestResponse,
|
| 20 |
+
)
|
| 21 |
+
from app.repositories.pinecone_repo import PineconeRepository
|
| 22 |
+
from app.services.embedding import EmbeddingService
|
| 23 |
+
from app.services.github import (
|
| 24 |
+
download_repo_zip,
|
| 25 |
+
fetch_repo_metadata,
|
| 26 |
+
parse_github_repo_url,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class IngestionService:
|
| 31 |
+
def __init__(self, embedder: EmbeddingService, repo: PineconeRepository) -> None:
|
| 32 |
+
self._embedder = embedder
|
| 33 |
+
self._repo = repo
|
| 34 |
+
|
| 35 |
+
async def analyze(self, payload: AnalyzeRequest) -> AnalyzeResponse:
|
| 36 |
+
settings = get_settings()
|
| 37 |
+
owner, repo_name, url_branch = parse_github_repo_url(payload.repo_url)
|
| 38 |
+
metadata = await fetch_repo_metadata(owner, repo_name, settings.github_token)
|
| 39 |
+
branch = payload.branch or url_branch or metadata.get("default_branch")
|
| 40 |
+
if not branch:
|
| 41 |
+
raise ValueError("Unable to resolve repository branch.")
|
| 42 |
+
|
| 43 |
+
max_bytes = settings.ingest_max_repo_mb * 1024 * 1024
|
| 44 |
+
zip_path = await download_repo_zip(
|
| 45 |
+
owner=owner,
|
| 46 |
+
repo=repo_name,
|
| 47 |
+
branch=branch,
|
| 48 |
+
token=settings.github_token,
|
| 49 |
+
max_bytes=max_bytes,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
extract_dir = zip_path.parent / "repo"
|
| 53 |
+
extract_dir.mkdir(parents=True, exist_ok=True)
|
| 54 |
+
with zipfile.ZipFile(zip_path, "r") as archive:
|
| 55 |
+
archive.extractall(extract_dir)
|
| 56 |
+
|
| 57 |
+
root_dir = next(extract_dir.iterdir())
|
| 58 |
+
file_count = 0
|
| 59 |
+
total_bytes = 0
|
| 60 |
+
top_level_entries: set[str] = set()
|
| 61 |
+
file_paths: list[str] = []
|
| 62 |
+
|
| 63 |
+
for file_path in _iter_files(root_dir, settings.ingest_ignored_dirs):
|
| 64 |
+
file_count += 1
|
| 65 |
+
total_bytes += file_path.stat().st_size
|
| 66 |
+
relative_path = str(file_path.relative_to(root_dir))
|
| 67 |
+
root_segment = Path(relative_path).parts[0]
|
| 68 |
+
top_level_entries.add(root_segment)
|
| 69 |
+
if len(file_paths) < 5000:
|
| 70 |
+
file_paths.append(relative_path)
|
| 71 |
+
|
| 72 |
+
return AnalyzeResponse(
|
| 73 |
+
repo=f"{owner}/{repo_name}",
|
| 74 |
+
branch=branch,
|
| 75 |
+
file_count=file_count,
|
| 76 |
+
total_bytes=total_bytes,
|
| 77 |
+
top_level_entries=sorted(top_level_entries),
|
| 78 |
+
file_paths=file_paths,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
async def ingest(self, payload: IngestRequest) -> IngestResponse:
|
| 82 |
+
settings = get_settings()
|
| 83 |
+
owner, repo_name, url_branch = parse_github_repo_url(payload.repo_url)
|
| 84 |
+
metadata = await fetch_repo_metadata(owner, repo_name, settings.github_token)
|
| 85 |
+
branch = payload.branch or url_branch or metadata.get("default_branch")
|
| 86 |
+
if not branch:
|
| 87 |
+
raise ValueError("Unable to resolve repository branch.")
|
| 88 |
+
|
| 89 |
+
repo_key = f"{owner}/{repo_name}"
|
| 90 |
+
job_id = payload.job_id or str(uuid.uuid4())
|
| 91 |
+
reuse_filter = {
|
| 92 |
+
"repo": repo_key,
|
| 93 |
+
"repo_url": payload.repo_url,
|
| 94 |
+
"branch": branch,
|
| 95 |
+
}
|
| 96 |
+
existing_count = await self._repo.count_by_filter(reuse_filter)
|
| 97 |
+
if existing_count == -1:
|
| 98 |
+
probe_vector = await self._embedder.embed("reuse-check")
|
| 99 |
+
matches = await self._repo.query(
|
| 100 |
+
probe_vector,
|
| 101 |
+
top_k=1,
|
| 102 |
+
filter=reuse_filter,
|
| 103 |
+
)
|
| 104 |
+
if not matches:
|
| 105 |
+
matches = await self._repo.query(
|
| 106 |
+
probe_vector,
|
| 107 |
+
top_k=1,
|
| 108 |
+
filter={"repo_url": payload.repo_url},
|
| 109 |
+
)
|
| 110 |
+
existing_count = 1 if matches else 0
|
| 111 |
+
elif existing_count == 0:
|
| 112 |
+
existing_count = await self._repo.count_by_filter({"repo_url": payload.repo_url})
|
| 113 |
+
if existing_count > 0:
|
| 114 |
+
progress_store.start(job_id=job_id, files_total=0)
|
| 115 |
+
progress_store.finish(job_id=job_id, files_processed=0, chunks_indexed=existing_count)
|
| 116 |
+
return IngestResponse(
|
| 117 |
+
repo=repo_key,
|
| 118 |
+
branch=branch,
|
| 119 |
+
files_indexed=0,
|
| 120 |
+
chunks_indexed=existing_count,
|
| 121 |
+
reused=True,
|
| 122 |
+
warnings=["Existing index found. Reusing stored vectors."],
|
| 123 |
+
top_level_entries=[],
|
| 124 |
+
sample_files=[],
|
| 125 |
+
job_id=job_id,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
max_bytes = settings.ingest_max_repo_mb * 1024 * 1024
|
| 129 |
+
zip_path = await download_repo_zip(
|
| 130 |
+
owner=owner,
|
| 131 |
+
repo=repo_name,
|
| 132 |
+
branch=branch,
|
| 133 |
+
token=settings.github_token,
|
| 134 |
+
max_bytes=max_bytes,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
extract_dir = zip_path.parent / "repo"
|
| 138 |
+
extract_dir.mkdir(parents=True, exist_ok=True)
|
| 139 |
+
with zipfile.ZipFile(zip_path, "r") as archive:
|
| 140 |
+
archive.extractall(extract_dir)
|
| 141 |
+
|
| 142 |
+
root_dir = next(extract_dir.iterdir())
|
| 143 |
+
file_list = list(_iter_files(root_dir, settings.ingest_ignored_dirs))
|
| 144 |
+
progress_store.start(job_id=job_id, files_total=len(file_list))
|
| 145 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 146 |
+
chunk_size=settings.ingest_chunk_size,
|
| 147 |
+
chunk_overlap=settings.ingest_chunk_overlap,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
vectors: list[dict] = []
|
| 151 |
+
warnings: list[str] = []
|
| 152 |
+
files_processed = 0
|
| 153 |
+
files_indexed = 0
|
| 154 |
+
chunks_indexed = 0
|
| 155 |
+
top_level_entries: set[str] = set()
|
| 156 |
+
sample_files: list[str] = []
|
| 157 |
+
try:
|
| 158 |
+
for file_path in file_list:
|
| 159 |
+
files_processed += 1
|
| 160 |
+
try:
|
| 161 |
+
content = file_path.read_text(encoding="utf-8")
|
| 162 |
+
except UnicodeDecodeError:
|
| 163 |
+
progress_store.update(
|
| 164 |
+
job_id=job_id,
|
| 165 |
+
files_processed=files_processed,
|
| 166 |
+
chunks_indexed=chunks_indexed,
|
| 167 |
+
)
|
| 168 |
+
continue
|
| 169 |
+
|
| 170 |
+
files_indexed += 1
|
| 171 |
+
relative_path = str(file_path.relative_to(root_dir))
|
| 172 |
+
root_segment = Path(relative_path).parts[0]
|
| 173 |
+
top_level_entries.add(root_segment)
|
| 174 |
+
if len(sample_files) < 40:
|
| 175 |
+
sample_files.append(relative_path)
|
| 176 |
+
chunks = splitter.split_text(content)
|
| 177 |
+
if chunks:
|
| 178 |
+
for index, chunk in enumerate(chunks):
|
| 179 |
+
vectors.append(
|
| 180 |
+
{
|
| 181 |
+
"id": str(uuid.uuid4()),
|
| 182 |
+
"values": None,
|
| 183 |
+
"metadata": {
|
| 184 |
+
"repo": repo_key,
|
| 185 |
+
"repo_url": payload.repo_url,
|
| 186 |
+
"branch": branch,
|
| 187 |
+
"path": relative_path,
|
| 188 |
+
"chunk_index": index,
|
| 189 |
+
"title": relative_path,
|
| 190 |
+
"text": chunk,
|
| 191 |
+
},
|
| 192 |
+
}
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
if len(vectors) >= settings.ingest_batch_size:
|
| 196 |
+
chunks_indexed += await self._flush_vectors(
|
| 197 |
+
vectors,
|
| 198 |
+
embed_timeout_sec=settings.ingest_embed_timeout_sec,
|
| 199 |
+
)
|
| 200 |
+
vectors = []
|
| 201 |
+
|
| 202 |
+
progress_store.update(
|
| 203 |
+
job_id=job_id,
|
| 204 |
+
files_processed=files_processed,
|
| 205 |
+
chunks_indexed=chunks_indexed,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
if vectors:
|
| 209 |
+
chunks_indexed += await self._flush_vectors(
|
| 210 |
+
vectors,
|
| 211 |
+
embed_timeout_sec=settings.ingest_embed_timeout_sec,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
progress_store.finish(
|
| 215 |
+
job_id=job_id,
|
| 216 |
+
files_processed=files_processed,
|
| 217 |
+
chunks_indexed=chunks_indexed,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
if files_indexed == 0:
|
| 221 |
+
warnings.append("No indexable text files found.")
|
| 222 |
+
|
| 223 |
+
return IngestResponse(
|
| 224 |
+
repo=repo_key,
|
| 225 |
+
branch=branch,
|
| 226 |
+
files_indexed=files_indexed,
|
| 227 |
+
chunks_indexed=chunks_indexed,
|
| 228 |
+
reused=False,
|
| 229 |
+
warnings=warnings,
|
| 230 |
+
top_level_entries=sorted(top_level_entries),
|
| 231 |
+
sample_files=sample_files,
|
| 232 |
+
job_id=job_id,
|
| 233 |
+
)
|
| 234 |
+
except Exception:
|
| 235 |
+
progress_store.fail(
|
| 236 |
+
job_id=job_id,
|
| 237 |
+
files_processed=files_processed,
|
| 238 |
+
chunks_indexed=chunks_indexed,
|
| 239 |
+
)
|
| 240 |
+
raise
|
| 241 |
+
|
| 242 |
+
async def _flush_vectors(self, vectors: list[dict], embed_timeout_sec: int) -> int:
|
| 243 |
+
if not vectors:
|
| 244 |
+
return 0
|
| 245 |
+
|
| 246 |
+
total_indexed = 0
|
| 247 |
+
batch_size = min(len(vectors), 16)
|
| 248 |
+
index_dimension = self._repo.get_dimension()
|
| 249 |
+
|
| 250 |
+
for start in range(0, len(vectors), batch_size):
|
| 251 |
+
batch = vectors[start : start + batch_size]
|
| 252 |
+
texts = [vector["metadata"]["text"] for vector in batch]
|
| 253 |
+
embeddings = await asyncio.wait_for(
|
| 254 |
+
self._embedder.embed_batch(texts),
|
| 255 |
+
timeout=embed_timeout_sec,
|
| 256 |
+
)
|
| 257 |
+
if embeddings:
|
| 258 |
+
embedding_dimension = len(embeddings[0])
|
| 259 |
+
if embedding_dimension != index_dimension:
|
| 260 |
+
raise ValueError(
|
| 261 |
+
"Embedding dimension does not match Pinecone index dimension. "
|
| 262 |
+
f"Index={index_dimension}, embedding={embedding_dimension}."
|
| 263 |
+
)
|
| 264 |
+
for vector, embedding in zip(batch, embeddings, strict=False):
|
| 265 |
+
vector["values"] = embedding
|
| 266 |
+
|
| 267 |
+
await self._repo.upsert(batch)
|
| 268 |
+
total_indexed += len(batch)
|
| 269 |
+
|
| 270 |
+
return total_indexed
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _iter_files(root: Path, ignored_dirs: Iterable[str]) -> Iterable[Path]:
|
| 274 |
+
ignored_set = set(ignored_dirs)
|
| 275 |
+
|
| 276 |
+
for dirpath, dirnames, filenames in os.walk(root):
|
| 277 |
+
dirnames[:] = [
|
| 278 |
+
name for name in dirnames if name not in ignored_set and not name.startswith(".")
|
| 279 |
+
]
|
| 280 |
+
for filename in filenames:
|
| 281 |
+
if filename.startswith("."):
|
| 282 |
+
continue
|
| 283 |
+
path = Path(dirpath) / filename
|
| 284 |
+
if _is_binary_file(path):
|
| 285 |
+
continue
|
| 286 |
+
yield path
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _is_binary_file(path: Path) -> bool:
|
| 290 |
+
try:
|
| 291 |
+
with path.open("rb") as handle:
|
| 292 |
+
chunk = handle.read(2048)
|
| 293 |
+
return b"\x00" in chunk
|
| 294 |
+
except OSError:
|
| 295 |
+
return True
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
@dataclass
|
| 299 |
+
class ProgressState:
|
| 300 |
+
job_id: str
|
| 301 |
+
status: str
|
| 302 |
+
files_total: int
|
| 303 |
+
files_processed: int
|
| 304 |
+
chunks_indexed: int
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class ProgressStore:
|
| 308 |
+
def __init__(self) -> None:
|
| 309 |
+
self._lock = Lock()
|
| 310 |
+
self._items: dict[str, ProgressState] = {}
|
| 311 |
+
|
| 312 |
+
def start(self, job_id: str, files_total: int) -> None:
|
| 313 |
+
with self._lock:
|
| 314 |
+
self._items[job_id] = ProgressState(
|
| 315 |
+
job_id=job_id,
|
| 316 |
+
status="running",
|
| 317 |
+
files_total=files_total,
|
| 318 |
+
files_processed=0,
|
| 319 |
+
chunks_indexed=0,
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
def update(self, job_id: str, files_processed: int, chunks_indexed: int) -> None:
|
| 323 |
+
with self._lock:
|
| 324 |
+
state = self._items.get(job_id)
|
| 325 |
+
if not state:
|
| 326 |
+
return
|
| 327 |
+
state.files_processed = files_processed
|
| 328 |
+
state.chunks_indexed = chunks_indexed
|
| 329 |
+
|
| 330 |
+
def finish(self, job_id: str, files_processed: int, chunks_indexed: int) -> None:
|
| 331 |
+
with self._lock:
|
| 332 |
+
state = self._items.get(job_id)
|
| 333 |
+
if not state:
|
| 334 |
+
return
|
| 335 |
+
state.files_processed = files_processed
|
| 336 |
+
state.chunks_indexed = chunks_indexed
|
| 337 |
+
state.status = "completed"
|
| 338 |
+
|
| 339 |
+
def fail(self, job_id: str, files_processed: int, chunks_indexed: int) -> None:
|
| 340 |
+
with self._lock:
|
| 341 |
+
state = self._items.get(job_id)
|
| 342 |
+
if not state:
|
| 343 |
+
return
|
| 344 |
+
state.files_processed = files_processed
|
| 345 |
+
state.chunks_indexed = chunks_indexed
|
| 346 |
+
state.status = "failed"
|
| 347 |
+
|
| 348 |
+
def get(self, job_id: str) -> ProgressState | None:
|
| 349 |
+
with self._lock:
|
| 350 |
+
state = self._items.get(job_id)
|
| 351 |
+
if not state:
|
| 352 |
+
return None
|
| 353 |
+
return ProgressState(
|
| 354 |
+
job_id=state.job_id,
|
| 355 |
+
status=state.status,
|
| 356 |
+
files_total=state.files_total,
|
| 357 |
+
files_processed=state.files_processed,
|
| 358 |
+
chunks_indexed=state.chunks_indexed,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
progress_store = ProgressStore()
|
app/services/retrieval.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.models.search import SearchRequest, SearchResponse, SearchResult
|
| 2 |
+
from app.repositories.pinecone_repo import PineconeRepository
|
| 3 |
+
from app.services.embedding import EmbeddingService
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class RetrievalService:
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
embedder: EmbeddingService,
|
| 10 |
+
repo: PineconeRepository,
|
| 11 |
+
) -> None:
|
| 12 |
+
self._embedder = embedder
|
| 13 |
+
self._repo = repo
|
| 14 |
+
|
| 15 |
+
async def search(self, payload: SearchRequest) -> SearchResponse:
|
| 16 |
+
vector = await self._embedder.embed(payload.query)
|
| 17 |
+
matches = await self._repo.query(
|
| 18 |
+
vector,
|
| 19 |
+
top_k=payload.top_k,
|
| 20 |
+
filter=payload.filter,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
return SearchResponse(
|
| 24 |
+
query=payload.query,
|
| 25 |
+
results=[SearchResult(**match) for match in matches],
|
| 26 |
+
total=len(matches),
|
| 27 |
+
)
|
pyproject.toml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "codebase-analyzer-backend"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "FastAPI backend for codebase analyzer"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.11"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"fastapi>=0.116.0",
|
| 9 |
+
"uvicorn[standard]>=0.35.0",
|
| 10 |
+
"pydantic-settings>=2.10.0",
|
| 11 |
+
"httpx>=0.28.0",
|
| 12 |
+
"langchain==0.2.17",
|
| 13 |
+
"langchain-community==0.2.18",
|
| 14 |
+
"langchain-huggingface>=0.0.3",
|
| 15 |
+
"langchain-pinecone>=0.1.0",
|
| 16 |
+
"pinecone>=5.0.0",
|
| 17 |
+
"sentence-transformers>=3.0.1",
|
| 18 |
+
"torch>=2.3.0",
|
| 19 |
+
"transformers>=4.45.0",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
[project.optional-dependencies]
|
| 23 |
+
dev = [
|
| 24 |
+
"pytest>=8.4.0",
|
| 25 |
+
"httpx>=0.28.0",
|
| 26 |
+
"pytest-asyncio>=0.23.7",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
[build-system]
|
| 30 |
+
requires = ["setuptools>=68", "wheel"]
|
| 31 |
+
build-backend = "setuptools.build_meta"
|