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
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12
94 changes: 50 additions & 44 deletions core/config.py
Original file line number Diff line number Diff line change
@@ -1,85 +1,91 @@
from pydantic_settings import BaseSettings, SettingConfigDict
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import field_validator
from typing import List


class Settings(BaseSettings):
model_config = SettingConfigDict(
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore"
extra="ignore",
)

# Application
APP_NAME:str = "VeritasAI"
DEBUG:bool = False
Environment:str = "production"
APP_NAME: str = "VeritasAI"
DEBUG: bool = False
Environment: str = "production"

#LLM
LLM_MODEL:str = "gpt-4o-mini"
TEMPERATURE:float = 0.4
OPENAI_API_KEY:str
API_BASE_URL:str = "https://api.openai.com/v1"
# LLM
LLM_MODEL: str = "gpt-4o-mini"
TEMPERATURE: float = 0.4
OPENAI_API_KEY: str
API_BASE_URL: str = "https://api.openai.com/v1"

#DB
MONGO_URI:str
DATABASE_NAME:str = "veritas_ai"
# DB
MONGO_URI: str
DATABASE_NAME: str = "veritas_ai"

# Authentication
GOOGLE_CLIENT_ID:str
GOOGLE_CLIENT_SECRET:str
JWT_SECRET:str
JWT_ALGORITHM:str = "HS256"
JWT_EXPIRY_HOURS:int = 24
SESSION_SECRET_KEY:str
GOOGLE_CLIENT_ID: str
GOOGLE_CLIENT_SECRET: str
JWT_SECRET: str
JWT_ALGORITHM: str = "HS256"
JWT_EXPIRY_HOURS: int = 24
SESSION_SECRET_KEY: str

#Security
ENCRYPTION_KEY:str
# Security
ENCRYPTION_KEY: str

#External APIs
COURTLISTENER_API_KEY:str
# External APIs
COURTLISTENER_API_KEY: str

#CORS
ALLOWED_ORIGINS:str = "http://localhost:3000"
# CORS
ALLOWED_ORIGINS: str = "http://localhost:3000"

#Logging
LOG_LEVEL:str = "INFO"
LOG_DIR:str = "./logs"
# Logging
LOG_LEVEL: str = "INFO"
LOG_DIR: str = "./logs"

#Redis
# Redis
REDIS_URL: str = "redis://localhost:6379/0"

@field_validator("TEMPERATURE")
@classmethod
def temperature_range(cls, v:float) -> float:
def temperature_range(cls, v: float) -> float:
if not (0.0 <= v <= 2.0):
raise ValueError("TEMPERATURE must be between 0.0 and 2.0")
return v

@field_validator("ENCRYPTION_KEY")
@classmethod
def validate_encryption_key(cls, v:str) -> str:
def validate_encryption_key(cls, v: str) -> str:
import base64

try:
base64.urlsafe_b64decode(v.encode())
if len(v) != 32:
raise ValueError("Encryption key must decode to exactly 32 bytes")
decoded = base64.urlsafe_b64decode(v.encode())
except Exception as exc:
raise ValueError(
"ENCRYPTION_KEY must be a valid Fernet key. "
) from exc
"ENCRYPTION_KEY must be a valid Fernet key "
"(generate with: python -c \"from cryptography.fernet import Fernet; "
"print(Fernet.generate_key().decode())\")"
) from exc

if len(decoded) != 32:
raise ValueError(
"ENCRYPTION_KEY must decode to exactly 32 bytes "
"(generate with: python -c \"from cryptography.fernet import Fernet; "
"print(Fernet.generate_key().decode())\")"
)
return v

@property
def allowed_origins_list(self) -> list[str]:
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",")]

@property
def is_development(self) -> bool:
return self.Environment.lower() == "development"

settings = Settings()




settings = Settings()
37 changes: 21 additions & 16 deletions core/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,29 @@
import sys
import structlog

from config import settings
from core.config import settings


def configure_logging() -> None:
os.makedirs(settings.LOG_DIR, exist_ok=True)

log_level = getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO)

handlers:list = [logging.StreamHandler(sys.stdout)]
handlers: list = [logging.StreamHandler(sys.stdout)]

if not settings.is_development:
log_file = os.path.join(settings.LOG_DIR, "veritas_ai.log")
handlers.append(logging.FileHandler(log_file, encoding="utf-8"))

logging.basicConfig(
format="%(message)s",
level=log_level,
handlers=handlers
)
logging.basicConfig(
format="%(message)s",
level=log_level,
handlers=handlers,
force=True,
)

# Structlog processors
processors = [
# Shared processors that run before rendering
shared_processors = [
structlog.contextvars.merge_contextvars,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
Expand All @@ -33,19 +35,22 @@ def configure_logging() -> None:
structlog.processors.format_exc_info,
]

# The renderer MUST be the last processor in the chain — it turns the
# event dict into the actual string that gets handed to the stdlib logger.
if settings.is_development:
structlog.dev.ConsoleRenderer()
renderer = structlog.dev.ConsoleRenderer()
else:
structlog.processors.JSONRenderer()
renderer = structlog.processors.JSONRenderer()

structlog.configure(
processors=processors,
wrapper_class=structlog.stdlib.BoundLogger, #helps to bind above processes data to the logger
context_class=dict, #where bound values are stored
processors=shared_processors + [renderer],
wrapper_class=structlog.stdlib.BoundLogger,
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)



configure_logging()

logger = structlog.get_logger("veritasai")
logger = structlog.get_logger("veritasai")
24 changes: 13 additions & 11 deletions db/user_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,35 @@ async def get_database() -> AsyncIOMotorDatabase:
)
logger.info("MongoDB Atlas Connected", db=settings.DATABASE_NAME)

return _client[settings.DATABASE_NAME]
return _client[settings.DATABASE_NAME]

# dependency injection
# Usage:
# db = await get_database() # connect once
# repo = UserRepository(db) # inject the connection
# await repo.get_by_email("x@y.com") # use it


class UserRepository:
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._users = db["users"]
self._results = db["results"]

async def upsert_user(self,user_data: dict[str, Any]) -> None:
async def upsert_user(self, user_data: dict[str, Any]) -> None:
await self._users.update_one(
{"email": user_data["email"]},
{"$set": user_data},
{"$setOnInsert": {"created_at": datetime.utcnow()}},
upsert=True,
)

async def get_by_email(self,email:str) ->Optional[Any]:
async def get_by_email(self, email: str) -> Optional[Any]:
return await self._users.find_one({"email": email}, {"_id": 0})

async def get_by_id(self,user_id:str) ->Optional[Any]:
async def get_by_id(self, user_id: str) -> Optional[Any]:
return await self._users.find_one({"user_id": user_id}, {"_id": 0})
async def store_results(self,user_id:str,query:str,result:dict[str,Any],timestamp:datetime,job_id:Optional[str]=None) -> None:

async def store_results(self, user_id: str, query: str, result: dict[str, Any], timestamp: datetime, job_id: Optional[str] = None) -> None:
await self._results.insert_one({
"user_id": user_id,
"query": query,
Expand All @@ -57,15 +58,16 @@ async def store_results(self,user_id:str,query:str,result:dict[str,Any],timestam
"job_id": job_id
})

async def get_results_by_job_id(self,user_id:str,job_id:str) -> Optional[dict]:
async def get_results_by_job_id(self, user_id: str, job_id: str) -> Optional[dict]:
return await self._results.find_one({"user_id": user_id, "job_id": job_id}, {"_id": 0})

async def get_user_results(self,user_id:str,limit:int=20) -> list[dict]:
cursor = self._results.find({"user_id": user_id}, {"_id": 1, "query": 1, "timestamp": 1, "result": 1}).sort("timestamp", -1).limit(limit)
async def get_user_results(self, user_id: str, limit: int = 20) -> list[dict]:
cursor = self._results.find({"user_id": user_id}, {
"_id": 1, "query": 1, "timestamp": 1, "result": 1}).sort("timestamp", -1).limit(limit)

results = []

async for doc in cursor:
doc["_id"] = str(doc["_id"])
results.append(doc)
return results
return results
6 changes: 6 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def main():
print("Hello from veritasai!")


if __name__ == "__main__":
main()
32 changes: 32 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[project]
name = "veritasai"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"arq>=0.25.0",
"authlib>=1.3.0",
"cryptography>=42.0.0",
"fastapi>=0.111.0",
"httpx>=0.27.0",
"langchain-core>=0.2.0",
"langgraph>=0.1.0",
"motor>=3.4.0",
"openai>=1.30.0",
"pdfminer-six>=20221105",
"pdfplumber>=0.11.0",
"pydantic>=2.7.0",
"pydantic-settings>=2.3.0",
"pyjwt>=2.8.0",
"pymongo>=4.7.0",
"pytest>=8.0.0",
"pytest-asyncio>=0.23.0",
"python-dotenv>=1.0.0",
"python-multipart>=0.0.9",
"redis>=5.0.0",
"ruff>=0.4.0",
"starlette>=0.37.0",
"structlog>=24.1.0",
"uvicorn[standard]>=0.29.0",
]
43 changes: 0 additions & 43 deletions requirements.txt

This file was deleted.

Loading
Loading