Skip to content
Merged
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
5 changes: 4 additions & 1 deletion backend/app/data/people.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
("São Paulo", "Brazil"),
("Tokyo", "Japan"),
]
# Every 13th generated attendee also studied here, so alumni matching has a second, smaller network to find.
# Assigned without the random generator, so every other generated value stays the same.
SECOND_SCHOOL, SECOND_SCHOOL_EVERY = "BUET", 13
COMPANIES = ["Wasatch Cloud", "Redwood Labs", "Northbeam", "Harborline", "Copperleaf", "Bluefin Data", "Lumen Grid"]
TITLES = ["Platform Engineer", "SRE", "Software Engineer", "ML Engineer", "DevOps Lead", "Engineering Manager"]
COMMUNITIES = ["CNCF Ambassadors", "Women in Cloud Native", "Kubernetes contributors", "Local meetup organisers"]
Expand Down Expand Up @@ -109,7 +112,7 @@ def sample_attendees(n: int = 80) -> list[dict]:
"company": rng.choice(COMPANIES),
"bio": f"Works on {interests[0].lower()} and {interests[3]}.",
"interests": interests,
"schools": [rng.choice(SCHOOLS)],
"schools": [rng.choice(SCHOOLS)] + ([SECOND_SCHOOL] if i % SECOND_SCHOOL_EVERY == 0 else []),
"past_companies": rng.sample(COMPANIES, 1),
"communities": rng.sample(COMMUNITIES, rng.randint(0, 2)),
"city": city,
Expand Down
13 changes: 13 additions & 0 deletions backend/app/embeddings.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
COST = meter.create_counter("confox.embeddings.cost", unit="USD", description="Estimated embedding cost")

BATCH = 100
EMBED_CHARS = 2000
# US dollars per million input tokens (OpenAI list prices).
PRICE_PER_MTOK = {"text-embedding-3-small": 0.02, "text-embedding-3-large": 0.13}

Expand All @@ -35,6 +36,18 @@ def _client() -> OpenAI:
return OpenAI(api_key=settings.openai_api_key.strip())


def join_text(*parts) -> str:
"""Non-empty parts on their own lines (lists joined with commas), trimmed to EMBED_CHARS."""
flat = [", ".join(p) if isinstance(p, list) else p for p in parts]
return "\n".join(str(p).strip() for p in flat if p)[:EMBED_CHARS]


def person_text(p: dict) -> str:
"""What a person is about, for their embedding. Shared by the loader and profile saves, so a saved profile is
embedded exactly like a loaded one."""
return join_text(p["name"], p.get("title"), p.get("company"), p.get("interests_text"), p.get("bio"))


def cost_usd(model: str, tokens: int) -> float:
return tokens * PRICE_PER_MTOK.get(model, 0.0) / 1_000_000

Expand Down
10 changes: 10 additions & 0 deletions backend/app/indices.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@
TEXT_KW = {"type": "text", "fields": {"raw": {"type": "keyword", "ignore_above": 512}}}
# Semantic search vector. Elasticsearch 9 keeps it out of `_source` unless a request asks for it.
EMBEDDING = {"type": "dense_vector", "dims": settings.embed_dims, "similarity": "cosine", "index": True}
# Fields only the profile editor writes. Kept separate so a save can add them to an index loaded before they existed.
PROFILE_FIELDS = {
"projects": {"type": "keyword"},
"tracks": {"type": "keyword"},
"looking_for": {"type": "text"},
"links": {"type": "keyword", "index": False},
"visibility": {"type": "keyword"},
"updated_at": LOCAL_TIME,
}

MAPPINGS: dict[str, dict] = {
settings.idx_sessions: {
Expand Down Expand Up @@ -58,6 +67,7 @@
# Speakers' published links, shown in session details; stored, never searched.
"links": {"type": "object", "enabled": False},
"embedding": EMBEDDING,
**PROFILE_FIELDS,
}
},
settings.idx_activity: {
Expand Down
15 changes: 2 additions & 13 deletions backend/app/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,18 @@
from .data.people import sample_attendees, speakers
from .data.samples import attendee_agendas, sample_activity
from .data.sessions import build_sessions
from .embeddings import embed, enabled
from .embeddings import embed, enabled, join_text, person_text
from .es import es
from .indices import rebuild
from .telemetry import setup_telemetry, shutdown_telemetry

log = logging.getLogger("confox.load")
tracer = trace.get_tracer("confox.load")

EMBED_CHARS = 2000


def _join(*parts) -> str:
flat = [", ".join(p) if isinstance(p, list) else p for p in parts]
return "\n".join(str(p).strip() for p in flat if p)[:EMBED_CHARS]


def session_text(s: dict) -> str:
"""What a session is about, for its embedding: title, track, projects, then the description."""
return _join(s["title"], s.get("track"), s.get("projects"), s.get("description"))


def person_text(p: dict) -> str:
return _join(p["name"], p.get("title"), p.get("company"), p.get("interests_text"), p.get("bio"))
return join_text(s["title"], s.get("track"), s.get("projects"), s.get("description"))


def with_embeddings(docs: list[dict], text) -> list[dict]:
Expand Down
24 changes: 5 additions & 19 deletions backend/app/routers/brief.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@
import logging
from datetime import datetime

from elasticsearch import ApiError
from fastapi import APIRouter, Query
from opentelemetry import trace

from ..clock import now as clock_now
from ..config import settings
from ..es import es
from ..now import next_food
from .people import SOURCE_EXCLUDES, _load_user, build_match_query, why
from .people import _load_user, rank_people, why
from .schedule import _day_sessions, _knn, annotate

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -293,23 +292,10 @@ def _agenda(user_id: str) -> list[dict]:


def _ranked_people(user_id: str, user: dict, vector: list | None) -> list[dict]:
"""The Match ranking (same query as /api/people/match), lexical if vector scoring fails."""

def run(vec: list | None) -> dict:
query = build_match_query(user_id, user, vector=vec)
return es.search(
index=settings.idx_people, query=query, size=PEOPLE_CANDIDATES, source_excludes=SOURCE_EXCLUDES
)

try:
res = run(vector)
except ApiError as exc:
if not vector:
raise
log.warning("brief: vector scoring failed, ranking people lexically: %s", exc)
trace.get_current_span().record_exception(exc)
res = run(None)
return [h["_source"] | {"id": h["_id"]} for h in res["hits"]["hits"]]
"""The Match ranking for the current profile (same pipeline as /api/people/match), best first."""
ranked, _, mode = rank_people(user_id, user, vector, size=PEOPLE_CANDIDATES)
trace.get_current_span().set_attribute("confox.brief.people_mode", mode)
return ranked


@router.get("")
Expand Down
Loading
Loading