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
22 changes: 15 additions & 7 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ SERVE_STATIC_PAGES=true

# -----------------------------------------------------------------------------
# 2. LLM PROVIDERS (Choose ONE for LLM_PROVIDER)
# Options: "gemini" (recommended), "nvidia-nim", "groq", "openai", "mock" (offline & free)
# Options: "gemini", "nvidia-nim", "groq", "openai", "anthropic", "openrouter", "mock" (offline & free)
# -----------------------------------------------------------------------------
LLM_PROVIDER=mock

Expand All @@ -32,8 +32,8 @@ GEMINI_MODEL=gemini-3.5-flash-lite
GEMINI_BASE_URL=https://generativelanguage.googleapis.com/v1beta

# Gemini Live realtime interviews (direct browser audio with a constrained,
# one-use ephemeral token). For the local panel demo, set this to true and
# open http://localhost:8000/app/interview.html?demo=1.
# one-use ephemeral token). Set this to true to enable live interviews; open
# an interview from a real shortlisted application to exercise the full flow.
GEMINI_LIVE_ENABLED=true
GEMINI_LIVE_MODEL=gemini-3.8-live
GEMINI_LIVE_VOICE=Aoede
Expand All @@ -58,6 +58,14 @@ OPENAI_API_KEY=your_openai_api_key_here
OPENAI_MODEL=gpt-4-turbo-preview
# OPENAI_ORGANIZATION=your_org_id

# Anthropic Claude
ANTHROPIC_API_KEY=your_anthropic_api_key_here
ANTHROPIC_MODEL=claude-3-5-sonnet-latest

# OpenRouter (OpenAI-compatible endpoint)
OPENROUTER_API_KEY=your_openrouter_api_key_here
OPENROUTER_MODEL=openai/gpt-4o-mini

# -----------------------------------------------------------------------------
# 3. EMBEDDINGS & VECTOR STORE
# -----------------------------------------------------------------------------
Expand Down Expand Up @@ -101,9 +109,9 @@ DATABASE_URL=
# -----------------------------------------------------------------------------
# 6. AUTHENTICATION & SECURITY (JWT)
# -----------------------------------------------------------------------------
# AUTH_ENABLED=false serves all requests as anonymous principal (development default).
# In production, set AUTH_ENABLED=true and supply a secure JWT_SECRET_KEY.
AUTH_ENABLED=false
# Profile, account, and BYOK pages require authenticated user identities.
# Set false only for anonymous local API experiments; never for the frontend.
AUTH_ENABLED=true
AUTH_REQUIRED_BY_DEFAULT=false

# CRITICAL FOR PRODUCTION: Generate with python3 -c "import secrets; print(secrets.token_urlsafe(32))"
Expand All @@ -128,7 +136,7 @@ CORS_MAX_AGE=600
# -----------------------------------------------------------------------------
# 8. BRING YOUR OWN KEY (BYOK) ENCRYPTION
# -----------------------------------------------------------------------------
# 32-byte urlsafe base64 Fernet key used to encrypt candidate-provided API keys at rest.
# 32-byte urlsafe base64 Fernet key used to encrypt recruiter-provided LLM keys at rest.
# Optional: if unset, BYOK endpoints remain disabled.
# Generate with: python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
BYOK_ENCRYPTION_KEY=
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*.cert
*.dump
*.sql
!repositories/postgres/migrations/*.sql
scripts/restore_rds.sh

# Python Artifacts & Bytecode
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ GEMINI_API_KEY=your_gemini_api_key
Start the API and open:

```text
http://localhost:8000/app/interview.html?demo=1
Open an interview from a shortlisted application to exercise the live interview flow.
```

The demo endpoint is unavailable in staging and production.
The standalone demo endpoint is retired; live interviews require a persisted job and shortlisted application.

---

Expand Down
30 changes: 30 additions & 0 deletions api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,36 @@
from core.security import Principal, PrincipalType, require_authenticated


async def resolve_candidate_practice_llm_provider(
*, principal: Principal, job_id: str, candidate_id: str,
application_id: str | None, settings: AppSettings, container,
jobs, candidate_service,
):
"""Resolve candidate BYOK only for the owner's candidate-created mock job."""
if not (
settings.auth_enabled and settings.byok_encryption_key
and principal.principal_type is PrincipalType.CANDIDATE
and principal.subject_id and application_id is None
):
return None
from core.errors import NotFoundError

try:
job = await jobs.get_job(job_id)
except NotFoundError:
return None
if not job.is_practice or job.created_by_user_id != principal.subject_id:
return None
await candidate_service.validate_candidate_ownership(candidate_id, principal.subject_id)
from services.llm_credential_service import LLMCredentialService

service = LLMCredentialService(
credential_repository=container.llm_credential_repository,
encryption_key=settings.byok_encryption_key,
)
return await service.resolve_provider_for_user(principal.subject_id)


async def apply_llm_context_for_recruiter(
principal: Principal = Depends(require_authenticated),
settings: AppSettings = Depends(get_settings),
Expand Down
54 changes: 50 additions & 4 deletions api/models_llm_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,16 @@
from core.errors import BadRequestError
from repositories.interfaces import CredentialStatus, LLMCredentialRecord

# Gemini-only for now - the other three native providers remain fully
# supported in `build_provider` and can be re-enabled here later without a
# schema migration.
_SUPPORTED_PROVIDERS = {"gemini"}
_SUPPORTED_PROVIDERS = {"openai", "gemini", "anthropic", "groq", "nvidia_nim", "openrouter"}


class SaveLLMCredentialRequest(BaseModel):
model_config = ConfigDict(extra="forbid")

provider: str = Field(min_length=1)
api_key: str = Field(min_length=1)
name: Optional[str] = Field(default=None, min_length=1, max_length=80)
credential_id: Optional[str] = None
model: Optional[str] = None

def validate_provider(self) -> None:
Expand All @@ -31,22 +30,35 @@ def validate_provider(self) -> None:


class LLMCredentialResponse(BaseModel):
credential_id: str
name: str
provider: str
model: Optional[str]
key_hint: str
status: CredentialStatus
last_error: Optional[str]
last_error_at: Optional[str]
health_status: str = "not_tested"
auth_status: str = "unknown"
last_tested_at: Optional[str] = None
last_successful_test_at: Optional[str] = None
health_error_code: Optional[str] = None

@classmethod
def from_domain(cls, record: LLMCredentialRecord) -> "LLMCredentialResponse":
return cls(
credential_id=record.credential_id,
name=record.name,
provider=record.provider,
model=record.model,
key_hint=record.key_hint,
status=record.status,
last_error=record.last_error,
last_error_at=record.last_error_at.isoformat() if record.last_error_at else None,
health_status=record.health_status, auth_status=record.auth_status,
last_tested_at=record.last_tested_at.isoformat() if record.last_tested_at else None,
last_successful_test_at=record.last_successful_test_at.isoformat() if record.last_successful_test_at else None,
health_error_code=record.health_error_code,
)


Expand All @@ -56,6 +68,7 @@ class TestLLMCredentialRequest(BaseModel):
provider: Optional[str] = "gemini"
api_key: Optional[str] = None
model: Optional[str] = None
credential_id: Optional[str] = None

def validate_provider(self) -> None:
if self.provider and self.provider not in _SUPPORTED_PROVIDERS:
Expand All @@ -73,9 +86,42 @@ class TestLLMCredentialResponse(BaseModel):
message: str


class LLMCredentialSettingsRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
mode: str
default_credential_id: Optional[str] = None
provider: Optional[str] = None
fallback_to_other_keys: bool = True
fallback_to_platform: bool = True
model: Optional[str] = None

def validate_mode(self) -> None:
if self.mode not in {"byok", "platform"}:
raise BadRequestError("Mode must be 'byok' or 'platform'.")
if self.provider and self.provider not in _SUPPORTED_PROVIDERS:
raise BadRequestError(
f"Unsupported provider {self.provider!r}. "
f"Supported: {', '.join(sorted(_SUPPORTED_PROVIDERS))}."
)


class LLMCredentialMetadataRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: Optional[str] = Field(default=None, min_length=1, max_length=80)
model: Optional[str] = None
provider: Optional[str] = None
api_key: Optional[str] = Field(default=None, min_length=1)

def validate_provider(self) -> None:
if self.provider and self.provider not in _SUPPORTED_PROVIDERS:
raise BadRequestError(f"Unsupported provider {self.provider!r}.")


__all__ = [
"LLMCredentialResponse",
"SaveLLMCredentialRequest",
"TestLLMCredentialRequest",
"TestLLMCredentialResponse",
"LLMCredentialSettingsRequest",
"LLMCredentialMetadataRequest",
]
7 changes: 6 additions & 1 deletion api/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,12 @@ async def update_my_profile(
return UserProfileResponse.from_record(user)


@router.post("/me/password", status_code=status.HTTP_204_NO_CONTENT)
@router.post(
"/me/password",
response_class=Response,
response_model=None,
status_code=status.HTTP_204_NO_CONTENT,
)
async def change_my_password(
request: ChangePasswordRequest,
service: AuthService = Depends(get_auth_service),
Expand Down
60 changes: 53 additions & 7 deletions api/routes/interview.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from api.errors import InvalidRequestError
from api.exceptions import SessionNotFoundError
from core.errors import ConflictError, NotFoundError
from api.dependencies import resolve_candidate_practice_llm_provider
from api.models import (
CreateSessionRequest,
CreateSessionResponse,
Expand All @@ -41,14 +42,19 @@
get_candidate_service,
get_evaluation_service,
get_interview_service,
get_job_service,
)
from core.config import get_settings
from core.dependencies import get_container
from core.llm_context import reset_context_provider, set_context_provider
from core.security import Principal, get_principal, require_authenticated
from repositories.interfaces import EvaluationJob, EvaluationStatus
from schemas.application import ApplicationStatus
from services.application_service import ApplicationService
from services.candidate_service import CandidateService
from services.evaluation_service import EvaluationService
from services.interview_service import InterviewService
from services.job_service import JobService
from utils.interview_session import SessionStatus

router = APIRouter(prefix="/sessions", tags=["interview"])
Expand Down Expand Up @@ -132,6 +138,9 @@ async def create_session(
service: InterviewService = Depends(get_interview_service),
applications: ApplicationService = Depends(get_application_service),
candidate_service: CandidateService = Depends(get_candidate_service),
jobs: JobService = Depends(get_job_service),
container=Depends(get_container),
settings=Depends(get_settings),
principal: Principal = Depends(require_authenticated),
) -> CreateSessionResponse:
"""POST /sessions - create an interview session and ask the first
Expand Down Expand Up @@ -200,13 +209,28 @@ async def create_session(
application_id=payload.application_id,
)

session_id, runner = await service.create_session(
job_description=payload.job_description,
parsed_resume=payload.parsed_resume,
candidate_id=payload.candidate_id,
max_questions=payload.max_questions,
application_id=payload.application_id,
# Candidate-owned credentials are intentionally resolved only for a
# candidate's own practice job. Real interview sessions and evaluations
# retain the existing platform/recruiter resolution paths.
practice_provider = await resolve_candidate_practice_llm_provider(
principal=principal, job_id=payload.job_id,
candidate_id=payload.candidate_id, application_id=payload.application_id,
settings=settings, container=container, jobs=jobs,
candidate_service=candidate_service,
)

context_token = set_context_provider(practice_provider) if practice_provider is not None else None
try:
session_id, runner = await service.create_session(
job_description=payload.job_description,
parsed_resume=payload.parsed_resume,
candidate_id=payload.candidate_id,
max_questions=payload.max_questions,
application_id=payload.application_id,
)
finally:
if context_token is not None:
reset_context_provider(context_token)
# Available to the InterviewSessionError handler, which needs the
# runner's status to choose between 409 and 500 (api/errors.py).
request.state.runner = runner
Expand All @@ -231,6 +255,9 @@ async def get_session_state(
service: InterviewService = Depends(get_interview_service),
evaluations: EvaluationService = Depends(get_evaluation_service),
candidate_service: CandidateService = Depends(get_candidate_service),
jobs: JobService = Depends(get_job_service),
container=Depends(get_container),
settings=Depends(get_settings),
principal: Principal = Depends(get_principal),
) -> SessionStateResponse:
"""GET /sessions/{id} - a controlled snapshot of session state. Never
Expand Down Expand Up @@ -283,6 +310,9 @@ async def submit_answer(
service: InterviewService = Depends(get_interview_service),
evaluations: EvaluationService = Depends(get_evaluation_service),
candidate_service: CandidateService = Depends(get_candidate_service),
jobs: JobService = Depends(get_job_service),
container=Depends(get_container),
settings=Depends(get_settings),
principal: Principal = Depends(get_principal),
) -> SubmitAnswerResponse:
"""POST /sessions/{id}/answers - the candidate's answer is untrusted
Expand All @@ -302,14 +332,30 @@ async def submit_answer(
# Resolved before submitting so the error handler has the runner even if
# submit_answer() is what fails.
runner = await service.get_runner(session_id)
session_record = await service.get_record(session_id)
request.state.runner = runner
await _enforce_session_ownership(
session_id, runner.candidate_id, principal,
service=service, candidate_service=candidate_service, allow_recruiter=False,
allow_public_capability=True,
)

result = await service.submit_answer(session_id, payload.answer_text)
practice_provider = await resolve_candidate_practice_llm_provider(
principal=principal,
job_id=runner.job_description.job_id,
candidate_id=runner.candidate_id,
application_id=session_record.application_id,
settings=settings,
container=container,
jobs=jobs,
candidate_service=candidate_service,
)
context_token = set_context_provider(practice_provider) if practice_provider is not None else None
try:
result = await service.submit_answer(session_id, payload.answer_text)
finally:
if context_token is not None:
reset_context_provider(context_token)

response = SubmitAnswerResponse.from_domain(result)
# `runner` is the same object submit_answer() just advanced, so this
Expand Down
Loading
Loading