Q79. How do you write tests with pytest?
Name files test_*.py, write plain asserts, use fixtures for setup and parametrize for many cases.
import pytest
from mylib import chunk
@pytest.fixture
def text():
return "a" * 2000
@pytest.mark.parametrize("size,expected", [(1000, 3), (500, 5)])
def test_chunk_count(text, size, expected):
assert len(chunk(text, size=size, overlap=0)) >= expected - 1
def test_empty():
with pytest.raises(ValueError):
chunk(None)Q80. How do you test code that calls an LLM?
Never hit the real API in unit tests: mock the client so tests are fast, free, and deterministic. Keep a small separate set of evaluation runs for real model behavior.
from unittest.mock import patch
@patch("app.rag.llm", return_value="Paris")
def test_answer(mock_llm):
assert answer("Capital of France?") == "Paris"
mock_llm.assert_called_once()Q81. Why use logging instead of print?
Levels (DEBUG to ERROR), timestamps, handlers (file, console), and per-module control. Log latency, token counts, and request IDs in LLM apps.
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger(__name__)
log.info("retrieved %d chunks in %.2fs", len(chunks), elapsed)
log.exception("llm call failed") # includes tracebackQ82. Implement retries with exponential backoff and jitter.
Used for rate limits (429) and transient 5xx errors. Do not retry on invalid-request errors.
import random, time
from functools import wraps
def backoff(max_tries=5, base=1.0, retry_on=(Exception,)):
def deco(fn):
@wraps(fn)
def wrapper(*a, **kw):
for attempt in range(max_tries):
try:
return fn(*a, **kw)
except retry_on:
if attempt == max_tries - 1:
raise
time.sleep(base * 2 ** attempt + random.random())
return wrapper
return decoQ83. How do you cache LLM or embedding results?
Hash the input (plus model and params) and store the result in memory, disk, or Redis. Embeddings of unchanged text should never be recomputed.
import hashlib, json
from pathlib import Path
CACHE = Path(".cache"); CACHE.mkdir(exist_ok=True)
def cached(model: str, text: str, fn):
key = hashlib.sha256(f"{model}:{text}".encode()).hexdigest()
f = CACHE / f"{key}.json"
if f.exists():
return json.loads(f.read_text())
out = fn(text)
f.write_text(json.dumps(out))
return outQ84. What does a clean AI project structure look like?
project/
src/app/
api.py # FastAPI routes
rag/ # ingest.py, retrieve.py, generate.py
schemas.py # Pydantic models
config.py # settings from env
tests/
evals/ # eval datasets + scripts
.env.example
pyproject.toml / requirements.txt
README.mdKeep config out of code, separate I/O from logic so it is testable, and pin dependency versions.