Spaces:
Sleeping
Sleeping
Islam Mamedov commited on
Commit ·
80a78e0
1
Parent(s): 546986c
Day 7: refusal-hardened prompt (7/7), strict citations; faithful 0.89, correct 0.91
Browse filesFiles changed (5)
- data/eval_cache.json
- data/rewrite_cache.jsonAdded+44
- src/ask.py+13-4
- src/eval.py+2-1
- src/retrieval.py+81-27
1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "How do I set a custom status code for an endpoint?": "How do I set a custom status code for an endpoint? `FastAPI custom status code endpoint response HTTPStatus`", "How do I receive an uploaded file in an endpoint?": "How do I receive an uploaded file in an endpoint? `FileResponse + UploadFile + endpoint FastAPI`", "How do I run a task in the background after returning a response?": "How do I run a task in the background after returning a response? `background task FastAPI run after response` \n\nor \n\n`background tasks fastapi response` \n\nor \n\n`asyncio.run_in_executor fastapi` \n\nor \n\n`\"BackgroundTasks\" \"add_task\" fastapi` \n\nor \n\n`fastapi.background`", "How do I enable CORS so my frontend can call the API?": "How do I enable CORS so my frontend can call the API? `cors fastapi enable + CORSMiddleware`", "How do I declare optional query parameters with default values?": "How do I declare optional query parameters with default values? `optional query parameters default value FastAPI Path Parameters`", "How do I declare a path parameter with a type like int?": "How do I declare a path parameter with a type like int? `path parameter type int FastAPI PathParam`", "How do I receive a JSON request body using a Pydantic model?": "How do I receive a JSON request body using a Pydantic model? `pydantic model json request body FastAPI` \n\nor \n\n`FastAPI request body JSON Pydantic BaseModel` \n\nor \n\n`from fastapi import FastAPI, Request; from pydantic import BaseModel;`", "How do I receive form data instead of JSON?": "How do I receive form data instead of JSON? `receive form data FastAPI` \n\nor \n\n`FastAPI request form data instead of JSON`\n\nor \n\n`python FastAPI form data Body` \n\nor \n\n`FastAPI FileResponse form data` \n\nor \n\n`\"Form data\" in: FastAPI Request`", "How do I return a custom error response with a specific status code and message?": "How do I return a custom error response with a specific status code and message? `HTTPException` `Response` `status_code` `FastAPI` `error handling` `exceptions`", "How do I use response_model to control which fields are returned?": "How do I use response_model to control which fields are returned? `response_model` `FastAPI` `pydantic` `response_model_exclude` `response_model_include` `main.py`", "How do I serve static files like images or CSS?": "How do I serve static files like images or CSS? `serving static files FastAPI StaticFiles`", "How do I write tests for my FastAPI endpoints?": "How do I write tests for my FastAPI endpoints? `test FastAPI endpoints pytest testclient`", "How do I use WebSockets in FastAPI?": "How do I use WebSockets in FastAPI? `FastAPI WebSockets WebSocket`", "How do I set a cookie in a response?": "How do I set a cookie in a response? `set cookie response FastAPI Response Cookies`", "How do I add custom headers to a response?": "How do I add custom headers to a response? `add custom headers response FastAPI ResponseHeader ResponseObject`", "How do I implement JWT token authentication?": "How do I implement JWT token authentication? `fastapi jwt authentication token`", "How does FastAPI's dependency injection system work?": "How does FastAPI's dependency injection system work? `FastAPI dependency injection` OR `FastAPI Depends` OR `fastapi.diplomatic` OR `fastapi.dependencies` OR `APIRouter dependencies`", "What does jsonable_encoder do and when do I need it?": "What does jsonable_encoder do and when do I need it? `jsonable_encoder` `FastAPI` `response` `encoder` `json` `pydantic`", "What is the difference between async def and def endpoints?": "What is the difference between async def and def endpoints? `async def vs def endpoints FastAPI`", "How can a dependency run cleanup code after the response is sent?": "How can a dependency run cleanup code after the response is sent? `FastAPI dependency cleanup after response sent` \n`yield response` \n`try-finally` \n`Request response cycle` \n`fastapi/dependencies.py` \n`APIRouter` \n`use_route_handlers` \n`BackgroundTasks`", "How can I customize or extend the generated OpenAPI schema?": "How can I customize or extend the generated OpenAPI schema? `openapi schema customization extend FastAPI get_openapi`", "What error does FastAPI return when request validation fails, and how do I customize it?": "What error does FastAPI return when request validation fails, and how do I customize it? `request validation error FastAPI RequestValidationError custom error handling`", "How does the OAuth2 password flow work in FastAPI?": "How does the OAuth2 password flow work in FastAPI? `OAuth2 password flow FastAPI` \n\nalternatively: \n`FastAPI OAuth2PasswordBearer` \nor \n`FastAPI security OAuth2 password` \nor \n`\"oauth2 password\" site:fastapi.tiangolo.com`", "How do I run code on application startup and shutdown?": "How do I run code on application startup and shutdown? `FastAPI startup shutdown code execution events`", "Can I mount another application under a path prefix?": "Can I mount another application under a path prefix? \"FastAPI mount application under path prefix\" OR \"FastAPI subapplication\" OR \"Mount subapp\" OR \"FastAPI include_router prefix\" OR \"FastAPI APP mount\"", "How does FastAPI run regular def endpoints without blocking the event loop?": "How does FastAPI run regular def endpoints without blocking the event loop? `run_in_threadpool def endpoint async event loop fastapi`", "How do I manage configuration and settings with environment variables?": "How do I manage configuration and settings with environment variables? `FastAPI env variables settings config`", "Where is the APIRouter class defined?": "Where is the APIRouter class defined? `APIRouter class definition FastAPI source code`", "Where is the OAuth2PasswordBearer class implemented?": "Where is the OAuth2PasswordBearer class implemented? `OAuth2PasswordBearer class FastAPI security`", "Where is the jsonable_encoder function implemented?": "Where is the jsonable_encoder function implemented? `jsonable_encoder function FastAPI source code`", "Where is the BackgroundTasks class defined?": "Where is the BackgroundTasks class defined? `BackgroundTasks class definition FastAPI` \n\nor \n\n`BackgroundTasks FastAPI python source code` \n\nor \n\n`BackgroundTasks definition in fastapi/background_tasks.py`", "Where is FastAPI's HTTPException defined?": "Where is FastAPI's HTTPException defined? `FastAPI HTTPException definition`", "Where is the main FastAPI application class defined?": "Where is the main FastAPI application class defined? `FastAPI main application class definition site:github.com/tiangolo/fastapi` \n\nor \n\n`FastAPI app class definition main.py` \n\nor \n\n`FastAPI __init__.py FastAPI class`", "Where are the Query, Path, and Body parameter functions defined?": "Where are the Query, Path, and Body parameter functions defined? `python fastapi Path Body parameter functions definition`", "Where is the TestClient that FastAPI provides for testing?": "Where is the TestClient that FastAPI provides for testing? `TestClient FastAPI testing`", "How do I connect FastAPI to MongoDB?": "How do I connect FastAPI to MongoDB? `FastAPI + MongoDB integration` \n`python motor async` \n`FastAPI MongoDB connection` \n`pydantic MongoDB` \n`main.py uvicorn mongo` \n`FastAPI Depends MongoClient` \n`path operation MongoDB` \n`python fastapi[all] motor`", "Does FastAPI have built-in rate limiting?": "Does FastAPI have built-in rate limiting? `FastAPI rate limiting` `Limit` `api` `dependencies` `fastapi/security`", "How do I integrate Celery task queues with FastAPI?": "How do I integrate Celery task queues with FastAPI? `Celery task queue integration FastAPI` \n\n Alternately: \n `asyncio Celery BackgroundTasks FastAPI` \n or \n `Celery broker FastAPI uvicorn` \n or \n `tasks queue async FastAPI` \n or \n `Celery FastAPI main.py`", "How do I use FastAPI with the Django ORM?": "How do I use FastAPI with the Django ORM? `FastAPI + Django ORM integration` \n`fastapi` `django` `orm` \n`main.py` `app` `models` \n`sqlalchemy` `database`", "Does FastAPI include a built-in admin dashboard?": "Does FastAPI include a built-in admin dashboard? `FastAPI admin dashboard`", "How do I schedule recurring cron jobs inside FastAPI?": "How do I schedule recurring cron jobs inside FastAPI? `fastapi cron job scheduling recurring apirouter BackgroundTasks`", "Does FastAPI have built-in database migration support?": "Does FastAPI have built-in database migration support? `FastAPI + database migration + SQLAlchemy`"}18 unmodified lines19202122232425262728293031323335 unmodified lines6970717273747518 unmodified linesfrom retrieval import retrieve as retrieve_chunksLLM_MODEL = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")TOP_K = 5SYSTEM_PROMPT = """\You are a precise assistant answering questions about the FastAPI codebase.Answer ONLY from the numbered context chunks provided. Rules:- Cite chunks inline like [1] or [2][3] after each claim they support.- If the context does not contain the answer, say exactly:"I couldn't find this in the indexed codebase." Do not guess.- Prefer short code examples when the context contains them.- Be concise."""35 unmodified linesargs = parser.parse_args()hits = retrieve_chunks(args.question, k=args.k, mode=args.mode)if args.show_chunks:for i, h in enumerate(hits, 1):print(f"\n=== [{i}] {h['meta']['path']} :: "18 unmodified lines192021222324252627282930313233343536373835 unmodified lines747576777879808182838418 unmodified linesfrom retrieval import retrieve as retrieve_chunksREFUSAL_TEXT = "I couldn't find this in the indexed codebase."LLM_MODEL = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")TOP_K = 5SYSTEM_PROMPT = """\You are a precise assistant answering questions about the FastAPI codebase.Answer ONLY from the numbered context chunks provided. Rules:- Cite chunks inline using square brackets like [1] or [2][3]. Never useany other citation format.- The context chunks are search results: they may be loosely RELATED tothe question without actually answering it. If they do not contain theanswer, reply with exactly:"I couldn't find this in the indexed codebase."Do not answer from general knowledge. Do not guess.- Prefer short code examples when the context contains them.- Be concise."""35 unmodified linesargs = parser.parse_args()hits = retrieve_chunks(args.question, k=args.k, mode=args.mode)top_score = hits[0].get("score")if top_score is not None and top_score < SCORE_THRESHOLD:print(f"\n{REFUSAL_TEXT}")returnif args.show_chunks:for i, h in enumerate(hits, 1):print(f"\n=== [{i}] {h['meta']['path']} :: "
70 unmodified lines7172737475767770 unmodified linesdef main() -> None:parser = argparse.ArgumentParser()parser.add_argument("--mode", default="dense",choices=["dense", "hybrid", "hybrid_rerank", "dense_rerank"])parser.add_argument("--answers", action="store_true",help="also generate answers and run the LLM judge")parser.add_argument("--k", type=int, default=K)70 unmodified lines717273747576777870 unmodified linesdef main() -> None:parser = argparse.ArgumentParser()parser.add_argument("--mode", default="dense",choices=["dense", "dense_rw", "dense_rerank","hybrid", "hybrid_rerank"])parser.add_argument("--answers", action="store_true",help="also generate answers and run the LLM judge")parser.add_argument("--k", type=int, default=K)
1234567891011121314151617181920218 unmodified lines303132333435363725 unmodified lines636465666768697071727374757611 unmodified lines8889909192937 unmodified lines101102103104105106107108109110111112113114115116117118119120121122"""Retrieval backends: dense, hybrid (dense + BM25), and hybrid + reranker.Modes:dense - embedding similarity only (the v0 baseline)hybrid - dense + BM25 keyword search, fused with Reciprocal RankFusion (RRF)hybrid_rerank - hybrid to get ~20 candidates, then a cross-encoderre-scores each (question, chunk) pair and keeps the bestWhy BM25 helps this corpus: code questions contain exact identifiers("APIRouter", "jsonable_encoder"). Embeddings blur those into meaning;BM25 matches them literally. The two are complementary, and RRF mergestheir rankings without needing to calibrate scores against each other.Why the reranker helps: the embedding compares question and chunk as twoseparate vectors. A cross-encoder reads them TOGETHER, token by token, soit is much better at judging true relevance - but too slow to run on all1300 chunks, which is why it only re-scores the top candidates."""import json8 unmodified linesEMBED_MODEL = "BAAI/bge-small-en-v1.5"RERANK_MODEL = "BAAI/bge-reranker-v2-m3"QUERY_PREFIX = "Represent this sentence for searching relevant passages: "CANDIDATES = 20 # how many candidates hybrid gathers before final cutRRF_K = 60 # standard RRF constant# Lazy singletons so models/indexes load once per process, not per query_embedder = None25 unmodified linesdef _get_reranker() -> CrossEncoder:global _rerankerif _reranker is None:_reranker = CrossEncoder(RERANK_MODEL) # first run downloads ~1GBreturn _rerankerdef _dense_ids(question: str, n: int) -> list[str]:emb = _embedder.encode(QUERY_PREFIX + question, normalize_embeddings=True)res = _collection.query(query_embeddings=[emb.tolist()], n_results=n)return res["ids"][0]def _bm25_ids(question: str, n: int) -> list[str]:11 unmodified linesreturn sorted(scores, key=scores.get, reverse=True)def _to_hit(cid: str) -> dict:c = _chunk_by_id[cid]return {7 unmodified lines},}def _rerank(question: str, candidates: list[str]) -> list[str]:pairs = [(question, _chunk_by_id[cid]["text"][:2000])for cid in candidates]scores = _get_reranker().predict(pairs)return [cid for _, cid in sorted(zip(scores, candidates), reverse=True)]def retrieve(question: str, k: int = 5, mode: str = "dense") -> list[dict]:_load()if mode == "dense":ids = _dense_ids(question, k)elif mode == "dense_rerank":ids = _rerank(question, _dense_ids(question, CANDIDATES))[:k]elif mode in ("hybrid", "hybrid_rerank"):fused = _rrf_fuse([_dense_ids(question, CANDIDATES),_bm25_ids(question, CANDIDATES)],weights=(2.0, 1.0))candidates = fused[:CANDIDATES]if mode == "hybrid_rerank":candidates = _rerank(question, candidates)123456789101112131415161718192021228 unmodified lines3132333435363738394041424344454647484925 unmodified lines7576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112211 unmodified lines1341351361371381391401411421431441451467 unmodified lines154155156157158159160161162163164165166167168169170171172173174175176"""Retrieval backends: dense, dense + query rewriting, hybrid, and reranked.Modes:dense - embedding similarity only (the v0 baseline)dense_rw - LLM expands the question with likely code identifiersand file names BEFORE embedding it (query rewriting)dense_rerank - dense candidates re-scored by a cross-encoderhybrid - dense + BM25 keyword search, fused with weighted RRFhybrid_rerank - hybrid candidates re-scored by a cross-encoderAblation findings on this corpus (42-question eval set):- dense won over hybrid: BM25 pulled in issue chunks that share commonquery words, displacing correct chunks from the top-5.- Two reranker generations (bge-reranker-base and v2-m3) both LOWEREDMRR: cross-encoders demote raw code chunks for "where is X defined"questions because code *is* the answer without discussing it.- dense_rw targets the remaining misses: questions whose words are alltoo common to retrieve well ("Query, Path, and Body parameterfunctions") get expanded with identifiers an LLM can guess."""import json8 unmodified linesEMBED_MODEL = "BAAI/bge-small-en-v1.5"RERANK_MODEL = "BAAI/bge-reranker-v2-m3"QUERY_PREFIX = "Represent this sentence for searching relevant passages: "CANDIDATES = 20 # how many candidates hybrid/rerank gather before final cutRRF_K = 60 # standard RRF constantRRF_WEIGHTS = (2.0, 1.0) # dense vs BM25 in the fused ranking# --- query rewriting ---REWRITE_CACHE = DATA_DIR / "rewrite_cache.json"REWRITE_PROMPT = """\You improve search queries for a search engine over the FastAPI repository(source code, docs, GitHub issues). Rewrite the question as a short searchquery, adding likely Python identifiers, class/function names, and filenames from FastAPI. Output ONLY the query, no explanation.Question: {question}"""# Lazy singletons so models/indexes load once per process, not per query_embedder = None25 unmodified linesdef _get_reranker() -> CrossEncoder:global _rerankerif _reranker is None:_reranker = CrossEncoder(RERANK_MODEL) # first run downloads ~2.3GBreturn _rerankerdef _rewrite(question: str) -> str:"""Expand the question with likely identifiers via one cached LLM call.Falls back to the original question on any failure (no key, ratelimit, network) so retrieval never breaks because of the rewriter."""import oscache = (json.loads(REWRITE_CACHE.read_text())if REWRITE_CACHE.exists() else {})if question in cache:return cache[question]try:from groq import Groqclient = Groq(api_key=os.environ["GROQ_API_KEY"])model = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")out = client.chat.completions.create(model=model,messages=[{"role": "user","content": REWRITE_PROMPT.format(question=question)}],temperature=0.0).choices[0].message.content.strip()expanded = f"{question} {out}"except Exception as e:print(f" [rewrite failed ({e.__class__.__name__}); using original]")return questioncache[question] = expandedREWRITE_CACHE.write_text(json.dumps(cache, ensure_ascii=False, indent=2))return expandeddef _dense_ids(question: str, n: int,with_scores: bool = False):emb = _embedder.encode(QUERY_PREFIX + question, normalize_embeddings=True)res = _collection.query(query_embeddings=[emb.tolist()], n_results=n)ids = res["ids"][0]if with_scores:# cosine distance -> similarity (1.0 = identical, 0.0 = unrelated)return ids, [1.0 - d for d in res["distances"][0]]return idsdef _bm25_ids(question: str, n: int) -> list[str]:11 unmodified linesreturn sorted(scores, key=scores.get, reverse=True)def _rerank(question: str, candidates: list[str]) -> list[str]:pairs = [(question, _chunk_by_id[cid]["text"][:2000])for cid in candidates]scores = _get_reranker().predict(pairs)return [cid for _, cid in sorted(zip(scores, candidates), reverse=True)]def _to_hit(cid: str) -> dict:c = _chunk_by_id[cid]return {7 unmodified lines},}def retrieve(question: str, k: int = 5, mode: str = "dense") -> list[dict]:_load()if mode == "dense":ids, scores = _dense_ids(question, k, with_scores=True)hits = [_to_hit(cid) for cid in ids]for h, s in zip(hits, scores):h["score"] = sreturn hitselif mode == "dense_rw":ids = _dense_ids(_rewrite(question), k)elif mode == "dense_rerank":ids = _rerank(question, _dense_ids(question, CANDIDATES))[:k]elif mode in ("hybrid", "hybrid_rerank"):fused = _rrf_fuse([_dense_ids(question, CANDIDATES),_bm25_ids(question, CANDIDATES)],weights=RRF_WEIGHTS)candidates = fused[:CANDIDATES]if mode == "hybrid_rerank":candidates = _rerank(question, candidates)
data/eval_cache.json
data/rewrite_cache.jsonAdded+44
src/ask.py+13-4
src/eval.py+2-1
src/retrieval.py+81-27