Ryan commited on
Commit
5e093e7
·
1 Parent(s): 44ba4b0

Replace Gradio RAG app with static redirect to new Vercel site

Browse files

Switch Space SDK from gradio to static and serve a single index.html with
a button to https://80000-hrs-ai-assistant.vercel.app/. Remove all Python
and model-loading code so the Space loads instantly.

Files changed (13) hide show
  1. README.md +8 -91
  2. app.py +0 -98
  3. chunk_articles_cli.py +0 -108
  4. citations.py +0 -355
  5. config.py +0 -11
  6. extract_content_cli.py +0 -241
  7. index.html +94 -0
  8. pipeline.py +0 -37
  9. query.py +0 -317
  10. requirements.txt +0 -14
  11. test_fuzzy.py +0 -42
  12. test_url.py +0 -18
  13. upload_to_qdrant_cli.py +0 -143
README.md CHANGED
@@ -1,102 +1,19 @@
1
  ---
2
- title: 80,000 Hours RAG Q&A
3
  emoji: 🎯
4
  colorFrom: blue
5
  colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- # 🎯 80,000 Hours Career Advice Q&A
13
 
14
- A Retrieval-Augmented Generation (RAG) system that answers career-related questions using content from [80,000 Hours](https://80000hours.org/), with validated citations.
15
 
16
- ## Features
17
 
18
- - 🔍 **Semantic Search**: Retrieves relevant content from 80,000 Hours articles
19
- - 🤖 **AI-Powered Answers**: Uses GPT-4o-mini to generate comprehensive responses
20
- - ✅ **Citation Validation**: Automatically validates that quotes exist in source material
21
- - 📚 **Source Attribution**: Every answer includes validated citations with URLs
22
 
23
- ## How It Works
24
-
25
- 1. Your question is converted to a vector embedding
26
- 2. Relevant article chunks are retrieved from Qdrant vector database
27
- 3. GPT-4o generates an answer with citations
28
- 4. Citations are validated against source material
29
- 5. You get an answer with verified quotes and source links
30
-
31
- ## Configuration for Hugging Face Spaces
32
-
33
- To deploy this app, you need to configure the following **Secrets** in your Space settings:
34
-
35
- 1. Go to your Space → Settings → Variables and Secrets
36
- 2. Add these secrets:
37
- - `QDRANT_URL`: Your Qdrant cloud instance URL
38
- - `QDRANT_API_KEY`: Your Qdrant API key
39
- - `OPENAI_API_KEY`: Your OpenAI API key
40
-
41
- ## Local Development
42
-
43
- ### Setup
44
-
45
- 1. Install dependencies:
46
- ```bash
47
- pip install -r requirements.txt
48
- ```
49
-
50
- 2. Create `.env` file with:
51
- ```
52
- QDRANT_URL=your_url
53
- QDRANT_API_KEY=your_key
54
- OPENAI_API_KEY=your_key
55
- ```
56
-
57
- ### First Time Setup (run in order):
58
-
59
- 1. **Extract articles** → `python extract_articles_cli.py`
60
- - Scrapes 80,000 Hours articles from sitemap
61
- - Only needed once (or to refresh content)
62
-
63
- 2. **Chunk articles** → `python chunk_articles_cli.py`
64
- - Splits articles into semantic chunks
65
-
66
- 3. **Upload to Qdrant** → `python upload_to_qdrant_cli.py`
67
- - Generates embeddings and uploads to vector DB
68
-
69
- ### Running Locally
70
-
71
- **Web Interface:**
72
- ```bash
73
- python app.py
74
- ```
75
-
76
- **Command Line:**
77
- ```bash
78
- python rag_chat.py "your question here"
79
- python rag_chat.py "your question" --show-context
80
- ```
81
-
82
- ## Project Structure
83
-
84
- - `app.py` - Main Gradio web interface
85
- - `rag_chat.py` - RAG logic and CLI interface
86
- - `citation_validator.py` - Citation validation system
87
- - `extract_articles_cli.py` - Article scraper
88
- - `chunk_articles_cli.py` - Article chunking
89
- - `upload_to_qdrant_cli.py` - Vector DB uploader
90
- - `config.py` - Shared configuration
91
-
92
- ## Tech Stack
93
-
94
- - **Frontend**: Gradio 4.0+
95
- - **LLM**: OpenAI GPT-4o-mini
96
- - **Vector DB**: Qdrant Cloud
97
- - **Embeddings**: sentence-transformers (all-MiniLM-L6-v2)
98
- - **Citation Validation**: rapidfuzz for fuzzy matching
99
-
100
- ## Credits
101
-
102
- Content sourced from [80,000 Hours](https://80000hours.org/), a nonprofit that provides research and support to help people find careers that effectively tackle the world's most pressing problems.
 
1
  ---
2
+ title: 80,000 Hours AI Assistant
3
  emoji: 🎯
4
  colorFrom: blue
5
  colorTo: purple
6
+ sdk: static
7
+ app_file: index.html
 
8
  pinned: false
9
  ---
10
 
11
+ # 80,000 Hours AI Assistant
12
 
13
+ This Space now redirects to the new, faster version of the assistant:
14
 
15
+ 👉 **https://80000-hrs-ai-assistant.vercel.app/**
16
 
17
+ The previous Gradio + RAG backend was retired here in favour of a static landing page so the Space loads instantly. The full RAG application (retrieval, synthesis, and citation validation) runs at the URL above.
 
 
 
18
 
19
+ Content sourced from [80,000 Hours](https://80000hours.org/).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py DELETED
@@ -1,98 +0,0 @@
1
- import gradio as gr
2
- import os
3
- from query import ask
4
-
5
- print("🚀 Starting 80,000 Hours RAG system...")
6
- from query import is_model_ready
7
- print("✅ App ready! Model loading in background...")
8
-
9
- def chat_interface(message: str, history):
10
- """Process question and return formatted response for chatbot.
11
-
12
- Args:
13
- message: User's question (string or dict with 'content' key)
14
- history: Chat history (list of message dicts with 'role' and 'content')
15
-
16
- Returns:
17
- Formatted response with answer and citations
18
- """
19
- # Handle both string and dict message formats
20
- if isinstance(message, dict):
21
- message = message.get('text', message.get('content', ''))
22
-
23
- if not message or not message.strip():
24
- return ""
25
-
26
- result = ask(message, show_context=False)
27
-
28
- # Format response: answer first, then divider, then citations
29
- response = result["answer"]
30
-
31
- # Add citations after divider
32
- if result["citations"]:
33
- response += "\n\n---\n\n**Citations:**\n\n"
34
- for i, citation in enumerate(result["citations"], 1):
35
- # Replace bullet points in citation text with newline + bullet icon
36
- response += f"**[{i}]** [{citation['title']}]({citation['url']})\n\n"
37
-
38
- return response
39
-
40
-
41
- # --- Build Gradio UI ---
42
- with gr.Blocks(title="80,000 Hours Q&A", theme=gr.themes.Soft(), css="""
43
- footer {display: none !important;}
44
- .examples button {
45
- background: linear-gradient(to bottom, #ffffff, #f8f9fa) !important;
46
- border: 2px solid #dee2e6 !important;
47
- border-radius: 8px !important;
48
- padding: 12px 16px !important;
49
- box-shadow: 0 2px 4px rgba(0,0,0,0.05) !important;
50
- transition: all 0.2s ease !important;
51
- }
52
- .examples button:hover {
53
- border-color: #adb5bd !important;
54
- box-shadow: 0 4px 8px rgba(0,0,0,0.1) !important;
55
- transform: translateY(-1px) !important;
56
- }
57
- """) as demo:
58
- # Title section
59
- gr.Markdown("# 80,000 Hours Q&A")
60
- gr.Markdown("*Ask questions about career planning and get answers backed by citations from 80,000 Hours articles.*")
61
-
62
- gr.ChatInterface(
63
- fn=chat_interface,
64
- type="messages",
65
- chatbot=gr.Chatbot(
66
- height=400,
67
- show_copy_button=True,
68
- render_markdown=True,
69
- layout="bubble",
70
- type="messages"
71
- ),
72
- textbox=gr.MultimodalTextbox(
73
- placeholder="Ask about career planning...",
74
- show_label=False,
75
- submit_btn=True,
76
- sources=[]
77
- ),
78
- examples=[
79
- "What skills will be most in demand in the next 5–10 years?",
80
- "How can I work on the world's most pressing problems?",
81
- "How do I figure out what I want to do with my life?",
82
- ],
83
- cache_examples=False
84
- )
85
-
86
- # --- Launch Logic ---
87
- if __name__ == "__main__":
88
- # Detect if running on Hugging Face Spaces (or other managed env)
89
- in_spaces = os.environ.get("SPACE_ID") is not None or os.environ.get("SYSTEM") == "spaces"
90
-
91
- if in_spaces:
92
- demo.launch() # Use platform defaults
93
- else:
94
- demo.launch(
95
- server_name="0.0.0.0",
96
- server_port=7860,
97
- share=False
98
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
chunk_articles_cli.py DELETED
@@ -1,108 +0,0 @@
1
- import json
2
- import os
3
- from llama_index.core.node_parser import SemanticSplitterNodeParser
4
- from llama_index.core.schema import Document
5
- from llama_index.embeddings.huggingface import HuggingFaceEmbedding
6
- from config import MODEL_NAME
7
-
8
- BUFFER_SIZE = 3
9
- BREAKPOINT_PERCENTILE_THRESHOLD = 87
10
- NUMBER_OF_ARTICLES = 86
11
- INPUT_FOLDER = "extracted_content"
12
- OUTPUT_FILE = "chunks.jsonl"
13
-
14
- def load_articles(json_path="articles.json", n=None):
15
- """Load articles from JSON file. Optionally load only first N articles."""
16
- with open(json_path, "r", encoding="utf-8") as f:
17
- articles = json.load(f)
18
- return articles[:n] if n else articles
19
-
20
- def chunk_text_semantic(text, embed_model):
21
- """Chunk text using semantic similarity with sentence buffer for overlap."""
22
- splitter = SemanticSplitterNodeParser(
23
- embed_model=embed_model,
24
- buffer_size=BUFFER_SIZE,
25
- breakpoint_percentile_threshold=BREAKPOINT_PERCENTILE_THRESHOLD
26
- )
27
- doc = Document(text=text)
28
- nodes = splitter.get_nodes_from_documents([doc])
29
- return [node.text for node in nodes]
30
-
31
- def make_jsonl(articles, out_path="chunks.jsonl"):
32
- """Create JSONL with semantic chunks from multiple articles."""
33
- print("Loading embedding model for semantic chunking...")
34
- embed_model = HuggingFaceEmbedding(model_name=MODEL_NAME)
35
-
36
- with open(out_path, "w", encoding="utf-8") as f:
37
- for idx, article in enumerate(articles, 1):
38
- print(f"Chunking ({idx}/{len(articles)}): {article['title']}")
39
- chunks = chunk_text_semantic(article["text"], embed_model)
40
- for i, chunk in enumerate(chunks, 1):
41
- record = {
42
- "url": article["url"],
43
- "title": article["title"],
44
- "date": article.get("date"),
45
- "chunk_id": i,
46
- "text": chunk,
47
- }
48
- f.write(json.dumps(record, ensure_ascii=False) + "\n")
49
-
50
- def chunk_from_json_files(input_folder=INPUT_FOLDER, output_file=OUTPUT_FILE):
51
- """Load articles from JSON files in folder and chunk them to JSONL."""
52
- if not os.path.exists(input_folder):
53
- print(f"Input folder '{input_folder}' not found")
54
- return
55
-
56
- # Load all articles from JSON files
57
- all_articles = []
58
- json_files = [f for f in os.listdir(input_folder) if f.endswith('.json')]
59
-
60
- if not json_files:
61
- print(f"No JSON files found in {input_folder}")
62
- return
63
-
64
- for json_file in json_files:
65
- json_path = os.path.join(input_folder, json_file)
66
- with open(json_path, "r", encoding="utf-8") as f:
67
- articles = json.load(f)
68
- all_articles.extend(articles)
69
- print(f"Loaded {len(articles)} articles from {json_file}")
70
-
71
- if not all_articles:
72
- print("No articles found to chunk")
73
- return
74
-
75
- print(f"\nTotal articles to chunk: {len(all_articles)}")
76
- print("Loading embedding model for semantic chunking...")
77
- embed_model = HuggingFaceEmbedding(model_name=MODEL_NAME)
78
-
79
- chunk_count = 0
80
- with open(output_file, "w", encoding="utf-8") as f:
81
- for idx, article in enumerate(all_articles, 1):
82
- print(f"Chunking ({idx}/{len(all_articles)}): {article['title']}")
83
- chunks = chunk_text_semantic(article["text"], embed_model)
84
- for i, chunk in enumerate(chunks, 1):
85
- record = {
86
- "url": article["url"],
87
- "title": article["title"],
88
- "date": article.get("date"),
89
- "chunk_id": i,
90
- "text": chunk,
91
- }
92
- chunk_count += 1
93
- f.write(json.dumps(record, ensure_ascii=False) + "\n")
94
-
95
- print(f"\n✓ Created {chunk_count} chunks from {len(all_articles)} articles")
96
- print(f"💾 Saved to {output_file}")
97
-
98
- def main():
99
- articles = load_articles(n=NUMBER_OF_ARTICLES)
100
- if not articles:
101
- print("No articles found in articles.json")
102
- return
103
-
104
- make_jsonl(articles)
105
- print(f"Chunks from {len(articles)} articles written to chunks.jsonl")
106
-
107
- if __name__ == "__main__":
108
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
citations.py DELETED
@@ -1,355 +0,0 @@
1
- """Citation validation and formatting for RAG system.
2
-
3
- This module handles structured citations with validation to prevent hallucination.
4
- """
5
-
6
- import json
7
- from typing import List, Dict, Any, Tuple
8
- from urllib.parse import quote
9
- from rapidfuzz import fuzz
10
-
11
-
12
- FUZZY_THRESHOLD = 90
13
-
14
- def create_highlighted_url(base_url: str, quote_text: str) -> str:
15
- """Create a URL with text fragment that highlights the quoted text.
16
-
17
- Uses the :~:text= URL fragment feature to scroll to and highlight text.
18
-
19
- Args:
20
- base_url: The base article URL
21
- quote_text: The text to highlight (should be the exact text from source)
22
-
23
- Returns:
24
- URL with text fragment
25
- """
26
- # Take only the first line/paragraph (text fragments can't match across elements)
27
- first_line = quote_text.split('\n')[0].strip()
28
-
29
- # Remove bullet point markers (they're formatting, not content)
30
- if first_line.startswith('- '):
31
- first_line = first_line[2:].strip()
32
-
33
- # Extract a meaningful snippet (first ~80 chars work better for text fragments)
34
- # Cut at word boundaries to avoid breaking words mid-way
35
- max_length = 80
36
- if len(first_line) > max_length:
37
- # Find the last space before the cutoff
38
- text_fragment = first_line[:max_length]
39
- last_space = text_fragment.rfind(' ')
40
- if last_space > 0: # If we found a space, cut there
41
- text_fragment = text_fragment[:last_space]
42
- else:
43
- text_fragment = first_line
44
-
45
- text_fragment = text_fragment.strip()
46
-
47
- encoded_text = quote(text_fragment, safe='')
48
- # Manually encode the unreserved chars that quote() preserves
49
- encoded_text = encoded_text.replace('-', '%2D')
50
- encoded_text = encoded_text.replace('.', '%2E')
51
- encoded_text = encoded_text.replace('_', '%5F')
52
- encoded_text = encoded_text.replace('~', '%7E')
53
- return f"{base_url}#:~:text={encoded_text}"
54
-
55
- def parse_llm_response(response_content: str) -> Dict[str, Any]:
56
- """Parse and validate LLM JSON response.
57
-
58
- Args:
59
- response_content: Raw JSON string from LLM
60
-
61
- Returns:
62
- Dict with answer and citations, or error information
63
- """
64
- try:
65
- result = json.loads(response_content)
66
- # Enforce strict shape: must have 'answer' (str) and 'citations' (list of dicts)
67
- if not isinstance(result, dict) or 'answer' not in result or 'citations' not in result:
68
- return {
69
- "answer": response_content,
70
- "citations": [],
71
- "validation_errors": ["Response JSON missing required keys 'answer' and/or 'citations'."]
72
- }
73
- if not isinstance(result['answer'], str) or not isinstance(result['citations'], list):
74
- return {
75
- "answer": response_content,
76
- "citations": [],
77
- "validation_errors": ["Response JSON has incorrect types for 'answer' or 'citations'."]
78
- }
79
- return result
80
- except json.JSONDecodeError:
81
- return {
82
- "answer": response_content,
83
- "citations": [],
84
- "validation_errors": ["Failed to parse JSON response"]
85
- }
86
-
87
- def build_citation_entry(citation: Dict[str, Any], validation_result: Dict[str, Any]) -> Dict[str, Any]:
88
- """Build a citation entry from validation result.
89
-
90
- Args:
91
- citation: Raw citation dict from LLM with citation_id, source_id, quote
92
- validation_result: Result from validate_citation()
93
-
94
- Returns:
95
- Complete citation entry with URL and metadata
96
- """
97
- matched_text = validation_result["matched_text"]
98
- highlighted_url = create_highlighted_url(
99
- validation_result["url"],
100
- matched_text
101
- )
102
- citation_entry = {
103
- "citation_id": citation.get("citation_id", 0),
104
- "source_id": validation_result["source_id"],
105
- "quote": citation.get("quote", ""), # AI's claimed quote
106
- "matched_text": matched_text, # Actual text from source
107
- "title": validation_result["title"],
108
- "url": highlighted_url,
109
- "fuzzy_match_score": validation_result["fuzzy_match_score"],
110
- "remapped": validation_result.get("remapped", False)
111
- }
112
- return citation_entry
113
-
114
- def process_citations(citations: List[Dict[str, Any]], source_chunks: List[Any]) -> Dict[str, Any]:
115
- """Validate and process a batch of citations.
116
-
117
- Args:
118
- citations: List of citation dicts from LLM
119
- source_chunks: List of source chunks from Qdrant
120
-
121
- Returns:
122
- Dict with validated_citations and validation_errors lists
123
- """
124
- validated_citations = []
125
- validation_errors = []
126
-
127
- for citation in citations:
128
- quote = citation.get("quote", "")
129
- source_id = citation.get("source_id", 0)
130
- citation_id = citation.get("citation_id", 0)
131
-
132
- validation_result = validate_citation(quote, source_chunks, source_id)
133
-
134
- if validation_result["valid"]:
135
- citation_entry = build_citation_entry(citation, validation_result)
136
- validated_citations.append(citation_entry)
137
- else:
138
- # Add citation_id to validation result for tracking
139
- validation_result["citation_id"] = citation_id
140
- validation_errors.append(validation_result)
141
-
142
- return {
143
- "validated_citations": validated_citations,
144
- "validation_errors": validation_errors
145
- }
146
-
147
- def _is_word_char(char: str) -> bool:
148
- """Check if character is part of a word (alphanumeric, comma, hyphen, apostrophe)."""
149
- return char.isalnum() or char in (',', '-', "'", "'")
150
-
151
- def _find_best_match_position(quote: str, source_text: str, alignment_hint=None) -> Tuple[int, int, float]:
152
- """Find the best matching position for a quote in source text using sliding window.
153
-
154
- This method is better than partial_ratio_alignment because it:
155
- 1. Uses word boundaries naturally
156
- 2. Finds the best matching substring at the token level
157
- 3. Returns positions that align with actual text segments
158
-
159
- Args:
160
- quote: The text to find
161
- source_text: The text to search in
162
- alignment_hint: Optional alignment result from partial_ratio_alignment to focus search
163
-
164
- Returns:
165
- Tuple of (start_pos, end_pos, score). Returns (-1, -1, 0) if no good match.
166
- """
167
- import re
168
-
169
- # Normalize whitespace for matching
170
- quote_normalized = ' '.join(quote.split())
171
-
172
- # Split source into words with their positions
173
- # This regex splits on whitespace while preserving positions
174
- word_pattern = re.compile(r'\S+')
175
- source_words = []
176
- for match in word_pattern.finditer(source_text):
177
- source_words.append({
178
- 'word': match.group(),
179
- 'start': match.start(),
180
- 'end': match.end()
181
- })
182
-
183
- quote_words = quote_normalized.split()
184
-
185
- if not quote_words or not source_words:
186
- return -1, -1, 0
187
-
188
- # Determine search range based on alignment hint
189
- if alignment_hint:
190
- # Find which word index contains the alignment position
191
- center_word_idx = 0
192
- for idx, word_info in enumerate(source_words):
193
- if word_info['start'] <= alignment_hint.dest_start < word_info['end']:
194
- center_word_idx = idx
195
- break
196
-
197
- # Search within +/- 5 words of the hint position
198
- search_start_idx = max(0, center_word_idx - 5)
199
- search_end_idx = min(len(source_words), center_word_idx + len(quote_words) + 5)
200
- else:
201
- # No hint found, search entire text (fallback)
202
- search_start_idx = 0
203
- search_end_idx = len(source_words)
204
-
205
- best_score = 0
206
- best_start = -1
207
- best_end = -1
208
-
209
- # Try different window sizes around the quote length
210
- # Quote should never be longer than source, so only check smaller windows
211
- min_window = max(1, len(quote_words) - 3)
212
- max_window = min(search_end_idx - search_start_idx, len(quote_words))
213
-
214
- for window_size in range(min_window, max_window + 1):
215
- for i in range(search_start_idx, min(search_end_idx - window_size + 1, len(source_words) - window_size + 1)):
216
- # Get window of words
217
- window_words = [source_words[j]['word'] for j in range(i, i + window_size)]
218
- window_text = ' '.join(window_words)
219
-
220
- # Calculate similarity score
221
- score = fuzz.ratio(quote_normalized, window_text)
222
-
223
- if score > best_score:
224
- best_score = score
225
- # Use the start of the first word and end of the last word
226
- best_start = source_words[i]['start']
227
- best_end = source_words[i + window_size - 1]['end']
228
-
229
- # Strip trailing punctuation from the end position
230
- while best_end > best_start and source_text[best_end - 1] in '.,;:!?)':
231
- best_end -= 1
232
-
233
- return best_start, best_end, best_score
234
-
235
- def _build_valid_result(quote: str, chunk: Any, chunk_id: int, score: float,
236
- matched_text: str, remapped: bool = False) -> Dict[str, Any]:
237
- """Build a valid citation result dict."""
238
- result = {
239
- "valid": True,
240
- "quote": quote,
241
- "matched_text": matched_text,
242
- "source_id": chunk_id,
243
- "title": chunk.payload['title'],
244
- "url": chunk.payload['url'],
245
- "fuzzy_match_score": score
246
- }
247
- if remapped:
248
- result["remapped"] = True
249
- return result
250
-
251
- def validate_citation(quote: str, source_chunks: List[Any], source_id: int) -> Dict[str, Any]:
252
- """Validate that a quote exists in the specified source chunk.
253
-
254
- Args:
255
- quote: The quoted text to validate
256
- source_chunks: List of source chunks from Qdrant
257
- source_id: 1-indexed source ID
258
-
259
- Returns:
260
- Dict with validation result and metadata
261
- """
262
- if source_id < 1 or source_id > len(source_chunks):
263
- return {
264
- "valid": False,
265
- "quote": quote,
266
- "source_id": source_id,
267
- "reason": "Invalid source ID",
268
- "source_text": None
269
- }
270
-
271
- # If quote contains ellipsis, only match the part before it
272
- if '...' in quote:
273
- quote = quote.split('...')[0].strip()
274
-
275
- # Step 1: Check the AI's cited source first (fast path)
276
- source_text = source_chunks[source_id - 1].payload['text']
277
-
278
- # Get alignment hint from partial_ratio_alignment
279
- alignment_hint = fuzz.partial_ratio_alignment(quote, source_text, score_cutoff=70)
280
- start, end, score = _find_best_match_position(quote, source_text, alignment_hint)
281
-
282
- if score >= FUZZY_THRESHOLD and start != -1:
283
- matched_text = source_text[start:end].strip()
284
- return _build_valid_result(quote, source_chunks[source_id - 1], source_id, score, matched_text)
285
-
286
- # Step 2: Search other sources for remapping (AI cited wrong source)
287
- for idx, chunk in enumerate(source_chunks, 1):
288
- if idx == source_id:
289
- continue # Already checked
290
-
291
- # Get alignment hint for this chunk
292
- alignment_hint = fuzz.partial_ratio_alignment(quote, chunk.payload['text'], score_cutoff=70)
293
- start, end, score = _find_best_match_position(quote, chunk.payload['text'], alignment_hint)
294
- if score >= FUZZY_THRESHOLD and start != -1:
295
- matched_text = chunk.payload['text'][start:end].strip()
296
- return _build_valid_result(quote, chunk, idx, score, matched_text, remapped=True)
297
-
298
- # Validation failed - find closest match for debugging
299
- matched_text = ""
300
- actual_score = 0
301
- try:
302
- debug_hint = fuzz.partial_ratio_alignment(quote, source_text, score_cutoff=60)
303
- debug_start, debug_end, debug_score = _find_best_match_position(quote, source_text, debug_hint)
304
- if debug_score >= 70 and debug_start != -1:
305
- matched_text = source_text[debug_start:debug_end].strip()
306
- actual_score = debug_score
307
- except:
308
- pass
309
-
310
- # If no decent match found, show snippet of source
311
- if not matched_text:
312
- matched_text = source_text[:200].strip() + "..." if len(source_text) > 200 else source_text
313
-
314
- return {
315
- "valid": False,
316
- "quote": quote,
317
- "source_id": source_id,
318
- "reason": f"Quote not found in any source (AI's cited source: {actual_score:.1f}% fuzzy match)",
319
- "matched_text": matched_text,
320
- "fuzzy_match_score": actual_score
321
- }
322
-
323
-
324
- def format_citations_display(citations: List[Dict[str, Any]]) -> str:
325
- """Format validated citations in order with article title, URL, and quoted text.
326
-
327
- Args:
328
- citations: List of validated citation dicts
329
-
330
- Returns:
331
- Formatted string for display
332
- """
333
- if not citations:
334
- return "No citations available."
335
-
336
- # Sort citations by citation_id to display in order
337
- sorted_citations = sorted(citations, key=lambda x: x.get('citation_id', 0))
338
-
339
- citation_parts = []
340
- for cit in sorted_citations:
341
- marker = f"[{cit['citation_id']}]"
342
- score = cit.get('fuzzy_match_score', 100)
343
-
344
- if cit.get('remapped'):
345
- note = f" ({score:.1f}% fuzzy match, remapped)"
346
- else:
347
- note = f" ({score:.1f}% fuzzy match)"
348
-
349
- citation_parts.append(
350
- f"{marker} {cit['title']}{note}\n"
351
- f" URL: {cit['url']}\n"
352
- f" Quote: \"{cit['matched_text']}\"\n"
353
- )
354
- return "\n".join(citation_parts)
355
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
config.py DELETED
@@ -1,11 +0,0 @@
1
- """Shared configuration constants for the 80k RAG system."""
2
-
3
- # Embedding model used across the system
4
- MODEL_NAME = 'all-MiniLM-L6-v2'
5
-
6
- # Qdrant collection name
7
- COLLECTION_NAME = "80k_articles"
8
-
9
- # Embedding dimension for the model
10
- EMBEDDING_DIM = 384
11
-
 
 
 
 
 
 
 
 
 
 
 
 
extract_content_cli.py DELETED
@@ -1,241 +0,0 @@
1
- import requests, re, json
2
- import trafilatura
3
- from typing import List, Dict, Optional
4
- from time import sleep
5
- from dateutil import parser as date_parser
6
- from concurrent.futures import ThreadPoolExecutor, as_completed
7
- import random
8
- import os
9
- import threading
10
- import time
11
- from requests.adapters import HTTPAdapter
12
- from urllib3.util.retry import Retry
13
-
14
- # Parallel processing settings
15
- USE_PARALLEL = True
16
- MAX_WORKERS = 3
17
-
18
- # Rate limiting settings
19
- MIN_DELAY = 1.0
20
- MAX_DELAY = 3.0
21
- RATE_LOCK = threading.Lock()
22
- _next_request_time = 0.0
23
-
24
- # Output settings
25
- OUTPUT_FOLDER = "extracted_content"
26
- TEST_LIMIT = None
27
-
28
- # HTTP settings
29
- HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}
30
-
31
- # All content sitemaps (excluding category/author which are just metadata)
32
- SITEMAPS = {
33
- "ai_career_guide_pages": "https://80000hours.org/ai_career_guide_page-sitemap.xml",
34
- # "articles": "https://80000hours.org/article-sitemap.xml",
35
- # "career_guide_pages": "https://80000hours.org/careerguidepage-sitemap.xml",
36
- "career_profiles": "https://80000hours.org/career_profile-sitemap.xml",
37
- # "career_reports": "https://80000hours.org/career_report-sitemap.xml",
38
- # "case_studies": "https://80000hours.org/case_study-sitemap.xml",
39
- "posts": "https://80000hours.org/post-sitemap.xml",
40
- "problem_profiles": "https://80000hours.org/problem_profile-sitemap.xml",
41
- # "podcasts": "https://80000hours.org/podcast-sitemap.xml",
42
- # "podcast_after_hours": "https://80000hours.org/podcast_after_hours-sitemap.xml",
43
- "skill_sets": "https://80000hours.org/skill_set-sitemap.xml",
44
- # "videos": "https://80000hours.org/video-sitemap.xml",
45
- }
46
-
47
- # Thread-local session with retries and backoff
48
- thread_local = threading.local()
49
-
50
- def get_session():
51
- """Get or create a thread-local requests session with retries and connection pooling."""
52
- s = getattr(thread_local, "session", None)
53
- if s is None:
54
- s = requests.Session()
55
- s.headers.update(HEADERS)
56
- retry = Retry(
57
- total=5, connect=3, read=3, status=3,
58
- status_forcelist=[429, 500, 502, 503, 504],
59
- allowed_methods={"GET", "HEAD"},
60
- backoff_factor=0.8,
61
- raise_on_status=False,
62
- respect_retry_after_header=True,
63
- )
64
- adapter = HTTPAdapter(
65
- max_retries=retry,
66
- pool_connections=MAX_WORKERS * 2,
67
- pool_maxsize=MAX_WORKERS * 2,
68
- )
69
- s.mount("http://", adapter)
70
- s.mount("https://", adapter)
71
- thread_local.session = s
72
- return s
73
-
74
- def throttle():
75
- """Enforce rate limiting across all threads."""
76
- global _next_request_time
77
- delay = random.uniform(MIN_DELAY, MAX_DELAY)
78
- with RATE_LOCK:
79
- now = time.monotonic()
80
- wait = max(0.0, _next_request_time - now)
81
- _next_request_time = max(now, _next_request_time) + delay
82
- if wait > 0:
83
- time.sleep(wait)
84
-
85
- def get_urls_from_sitemap(sitemap_url: str) -> List[str]:
86
- """Extract all URLs from a sitemap."""
87
- throttle()
88
- r = get_session().get(sitemap_url, timeout=20)
89
- r.raise_for_status()
90
- return re.findall(r"<loc>(.*?)</loc>", r.text)
91
-
92
- def parse_custom_date(html_content: str) -> Optional[str]:
93
- """
94
- Extract and parse publication date from 80,000 Hours HTML content.
95
-
96
- Priority:
97
- 1. "Updated [date]" if present
98
- 2. "Published [date]" otherwise
99
-
100
- Returns date in YYYY-MM-DD format, or None if not found.
101
- """
102
- # Date pattern: month + optional day (with ordinal) + year
103
- date_pattern = r'([A-Za-z]+\s+(?:\d{1,2}(?:st|nd|rd|th)?,?\s+)?\d{4})'
104
-
105
- # Try "Updated" first, then "Published"
106
- for keyword in ['Updated', 'Published']:
107
- match = re.search(f'{keyword}\\s+{date_pattern}', html_content, re.IGNORECASE)
108
- if match:
109
- try:
110
- parsed_date = date_parser.parse(match.group(1), fuzzy=True)
111
- return parsed_date.strftime('%Y-%m-%d')
112
- except:
113
- pass
114
-
115
- return None
116
-
117
- def extract_content(url: str) -> Optional[Dict]:
118
- """Extract content and metadata from a URL."""
119
- try:
120
- throttle()
121
- r = get_session().get(url, timeout=30)
122
- r.raise_for_status()
123
- except Exception as e:
124
- print(f" ❌ Request failed: {e}")
125
- return None
126
-
127
- data = trafilatura.extract(
128
- r.content, url=url, with_metadata=True,
129
- include_links=False, include_comments=False,
130
- include_formatting=False, output_format="json"
131
- )
132
-
133
- if not data:
134
- return None
135
-
136
- result = json.loads(data)
137
- if custom_date := parse_custom_date(r.text):
138
- result['date'] = custom_date
139
-
140
- return result
141
-
142
-
143
- def process_record(record: Optional[Dict], url: str, sitemap_name: str) -> Optional[Dict]:
144
- """Convert extraction record to final output format."""
145
- if not (record and record.get("text")):
146
- return None
147
- return {
148
- "url": url,
149
- "title": record.get("title", ""),
150
- "date": record.get("date"),
151
- "author": record.get("author"),
152
- "text": record.get("text", "").strip(),
153
- "content_type": sitemap_name
154
- }
155
-
156
- def handle_extraction_result(record: Optional[Dict], url: str, sitemap_name: str, index: int, total: int, items: List[Dict]) -> None:
157
- """Process extraction result and add to items list if successful."""
158
- try:
159
- result = process_record(record, url, sitemap_name)
160
- if result:
161
- items.append(result)
162
- status = "✓" if result else "⚠️ Failed:"
163
- print(f"[{index}/{total}] {status} {url}")
164
- except Exception as e:
165
- print(f"[{index}/{total}] ❌ {url}: {e}")
166
-
167
- def extract_from_sitemap(sitemap_name: str, sitemap_url: str, limit: int = None, parallel: bool = True, max_workers: int = 5) -> List[Dict]:
168
- """Extract content from a sitemap using either parallel or sequential processing."""
169
- print(f"\n{'='*80}")
170
- print(f"Processing {sitemap_name}...")
171
- print(f"{'='*80}")
172
-
173
- urls = get_urls_from_sitemap(sitemap_url)
174
- print(f"Found {len(urls)} URLs in sitemap")
175
-
176
- if limit:
177
- urls = urls[:limit]
178
- print(f"Limiting to first {limit} URL(s)")
179
-
180
- items = []
181
-
182
- if parallel and len(urls) > 1:
183
- print(f"🚀 Using parallel processing with {max_workers} workers")
184
- completed = 0
185
-
186
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
187
- # Submit all tasks
188
- future_to_url = {
189
- executor.submit(extract_content, url): url
190
- for url in urls
191
- }
192
-
193
- # Process completed tasks
194
- for future in as_completed(future_to_url):
195
- url = future_to_url[future]
196
- completed += 1
197
- handle_extraction_result(future.result(), url, sitemap_name, completed, len(urls), items)
198
- else:
199
- print("📝 Using sequential processing")
200
- for i, url in enumerate(urls, 1):
201
- handle_extraction_result(extract_content(url), url, sitemap_name, i, len(urls), items)
202
-
203
- print(f"✓ Successfully extracted {len(items)}/{len(urls)} items")
204
- return items
205
-
206
- def extract_all_to_json():
207
- """Extract all content from sitemaps and save to individual JSON files."""
208
- os.makedirs(OUTPUT_FOLDER, exist_ok=True)
209
-
210
- print("Starting 80,000 Hours content extraction...")
211
- print(f"Total content types: {len(SITEMAPS)}")
212
- print(f"Output folder: {OUTPUT_FOLDER}/")
213
- if TEST_LIMIT:
214
- print(f"⚠️ TEST MODE: Extracting only {TEST_LIMIT} item(s) per content type\n")
215
-
216
- all_stats = {}
217
- for content_type, sitemap_url in SITEMAPS.items():
218
- items = extract_from_sitemap(
219
- content_type, sitemap_url,
220
- limit=TEST_LIMIT, parallel=USE_PARALLEL, max_workers=MAX_WORKERS
221
- )
222
- all_stats[content_type] = len(items)
223
-
224
- if items:
225
- output_file = os.path.join(OUTPUT_FOLDER, f"{content_type}.json")
226
- with open(output_file, "w", encoding="utf-8") as f:
227
- json.dump(items, f, ensure_ascii=False, indent=2)
228
- print(f"💾 Saved to {output_file}")
229
-
230
- print(f"\n{'='*80}\nEXTRACTION COMPLETE\n{'='*80}")
231
- print(f"Total items extracted: {sum(all_stats.values())}")
232
- print("\nBreakdown by content type:")
233
- for content_type, count in sorted(all_stats.items(), key=lambda x: x[1], reverse=True):
234
- print(f" {content_type:25s}: {count:4d} items → {OUTPUT_FOLDER}/{content_type}.json")
235
-
236
- def main():
237
- extract_all_to_json()
238
-
239
- if __name__ == "__main__":
240
- main()
241
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
index.html ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>80,000 Hours AI Assistant</title>
7
+ <meta name="description" content="The 80,000 Hours AI Assistant has moved to a new home." />
8
+ <style>
9
+ :root {
10
+ --bg: #f7f6f3;
11
+ --fg: #1a1a1a;
12
+ --muted: #6b6b6b;
13
+ --accent: #1a1a1a;
14
+ --accent-fg: #ffffff;
15
+ }
16
+ * { box-sizing: border-box; margin: 0; padding: 0; }
17
+ html, body { height: 100%; }
18
+ body {
19
+ background: var(--bg);
20
+ color: var(--fg);
21
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
22
+ display: flex;
23
+ align-items: center;
24
+ justify-content: center;
25
+ padding: 24px;
26
+ line-height: 1.5;
27
+ -webkit-font-smoothing: antialiased;
28
+ }
29
+ main {
30
+ max-width: 560px;
31
+ width: 100%;
32
+ text-align: center;
33
+ }
34
+ .badge {
35
+ font-size: 13px;
36
+ letter-spacing: 0.08em;
37
+ text-transform: uppercase;
38
+ color: var(--muted);
39
+ margin-bottom: 20px;
40
+ }
41
+ h1 {
42
+ font-size: clamp(28px, 6vw, 44px);
43
+ font-weight: 700;
44
+ letter-spacing: -0.02em;
45
+ margin-bottom: 16px;
46
+ }
47
+ p {
48
+ font-size: clamp(15px, 2.5vw, 18px);
49
+ color: var(--muted);
50
+ margin-bottom: 36px;
51
+ }
52
+ .btn {
53
+ display: inline-flex;
54
+ align-items: center;
55
+ gap: 10px;
56
+ background: var(--accent);
57
+ color: var(--accent-fg);
58
+ text-decoration: none;
59
+ font-size: clamp(16px, 2.5vw, 19px);
60
+ font-weight: 600;
61
+ padding: 18px 32px;
62
+ border-radius: 9999px;
63
+ transition: transform 0.15s ease, opacity 0.15s ease;
64
+ box-shadow: 0 6px 20px rgba(0,0,0,0.12);
65
+ }
66
+ .btn:hover { transform: translateY(-2px); opacity: 0.92; }
67
+ .btn:active { transform: translateY(0); }
68
+ .btn svg { width: 20px; height: 20px; }
69
+ footer {
70
+ margin-top: 40px;
71
+ font-size: 13px;
72
+ color: var(--muted);
73
+ }
74
+ footer a { color: var(--muted); }
75
+ </style>
76
+ </head>
77
+ <body>
78
+ <main>
79
+ <div class="badge">80,000 Hours</div>
80
+ <h1>The AI Assistant has a new home</h1>
81
+ <p>We've moved to a faster, redesigned version. Click below to start asking about career planning.</p>
82
+ <a class="btn" href="https://80000-hrs-ai-assistant.vercel.app/" rel="noopener">
83
+ Open the new assistant
84
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
85
+ <path d="M5 12h14" />
86
+ <path d="m12 5 7 7-7 7" />
87
+ </svg>
88
+ </a>
89
+ <footer>
90
+ Powered by <a href="https://80000hours.org/" rel="noopener" target="_blank">80,000 Hours</a> content.
91
+ </footer>
92
+ </main>
93
+ </body>
94
+ </html>
pipeline.py DELETED
@@ -1,37 +0,0 @@
1
- """Combined pipeline: Extract → Chunk → Upload to Qdrant (additive)"""
2
- from extract_content_cli import extract_all_to_json
3
- from chunk_articles_cli import chunk_from_json_files
4
- from upload_to_qdrant_cli import upload_chunks_additive
5
-
6
-
7
- def main():
8
- print("="*80)
9
- print("80,000 HOURS RAG PIPELINE")
10
- print("Extract → Chunk → Upload (Additive)")
11
- print("="*80)
12
-
13
- # Step 1: Extract to individual JSON files
14
- print("\n" + "="*80)
15
- print("STEP 1: EXTRACTING CONTENT")
16
- print("="*80)
17
- extract_all_to_json()
18
-
19
- # Step 2: Chunk from JSON files
20
- print("\n" + "="*80)
21
- print("STEP 2: CHUNKING ARTICLES")
22
- print("="*80)
23
- chunk_from_json_files()
24
-
25
- # Step 3: Upload to Qdrant from chunks file (additive)
26
- print("\n" + "="*80)
27
- print("STEP 3: UPLOADING TO QDRANT (ADDITIVE)")
28
- print("="*80)
29
- upload_chunks_additive()
30
-
31
- print("\n" + "="*80)
32
- print("PIPELINE COMPLETE ✓")
33
- print("="*80)
34
-
35
-
36
- if __name__ == "__main__":
37
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
query.py DELETED
@@ -1,317 +0,0 @@
1
- """Query module for RAG system with background model loading."""
2
-
3
- import os
4
- import json
5
- import time
6
- import threading
7
- from typing import Dict, Any, List
8
-
9
- from dotenv import load_dotenv
10
- from openai import OpenAI
11
- from qdrant_client import QdrantClient
12
- from sentence_transformers import SentenceTransformer
13
-
14
- from citations import parse_llm_response, process_citations, format_citations_display
15
- from config import MODEL_NAME, COLLECTION_NAME
16
-
17
- load_dotenv()
18
-
19
- # ============================================================================
20
- # Configuration
21
- # ============================================================================
22
-
23
- LLM_MODEL = "gpt-4o"
24
- SOURCE_COUNT = 10
25
- SCORE_THRESHOLD = 0.4
26
-
27
- # ============================================================================
28
- # Background Model Loading
29
- # ============================================================================
30
-
31
- EMBEDDING_MODEL = None
32
- _model_loaded = threading.Event()
33
-
34
- def _load_model_background():
35
- """Load the embedding model in a background thread."""
36
- global EMBEDDING_MODEL
37
- print("🔄 Loading embedding model in background...")
38
- EMBEDDING_MODEL = SentenceTransformer(MODEL_NAME)
39
- _model_loaded.set()
40
- print("✅ Embedding model loaded!")
41
-
42
- def is_model_ready():
43
- """Check if the embedding model is ready to use."""
44
- return _model_loaded.is_set()
45
-
46
- # Start loading immediately when module is imported
47
- _loading_thread = threading.Thread(target=_load_model_background, daemon=True)
48
- _loading_thread.start()
49
-
50
- # ============================================================================
51
- # Context Retrieval
52
- # ============================================================================
53
-
54
- def retrieve_context(question):
55
- """Retrieve relevant chunks from Qdrant."""
56
- start = time.time()
57
-
58
- client = QdrantClient(
59
- url=os.getenv("QDRANT_URL"),
60
- api_key=os.getenv("QDRANT_API_KEY"),
61
- )
62
-
63
- # Wait for model to be loaded (if still loading)
64
- if not _model_loaded.is_set():
65
- print("⏳ Waiting for embedding model to finish loading...")
66
- if not _model_loaded.wait(timeout=120):
67
- raise Exception("Model loading timeout - please try again")
68
-
69
- query_vector = EMBEDDING_MODEL.encode(question).tolist()
70
-
71
- results = client.query_points(
72
- collection_name=COLLECTION_NAME,
73
- query=query_vector,
74
- limit=SOURCE_COUNT,
75
- score_threshold=SCORE_THRESHOLD,
76
- )
77
-
78
- elapsed = (time.time() - start) * 1000
79
- print(f"[TIMING] Retrieval: {elapsed:.0f}ms")
80
-
81
- return results.points
82
-
83
- def format_context(results):
84
- """Format retrieved chunks into context string for LLM."""
85
- context_parts = []
86
- for i, hit in enumerate(results, 1):
87
- context_parts.append(
88
- f"[Source {i}]\n"
89
- f"Title: {hit.payload['title']}\n"
90
- f"URL: {hit.payload['url']}\n"
91
- f"Content: {hit.payload['text']}\n"
92
- )
93
- return "\n---\n".join(context_parts)
94
-
95
- # ============================================================================
96
- # LLM Answer Generation
97
- # ============================================================================
98
-
99
- def generate_answer_with_citations(
100
- question: str,
101
- context: str,
102
- results: List[Any],
103
- llm_model: str,
104
- openai_api_key: str
105
- ) -> Dict[str, Any]:
106
- """Generate answer with structured citations using OpenAI.
107
-
108
- Args:
109
- question: User's question
110
- context: Formatted context from source chunks
111
- results: Source chunks from Qdrant
112
- llm_model: OpenAI model name
113
- openai_api_key: OpenAI API key
114
-
115
- Returns:
116
- Dict with answer and validated citations
117
- """
118
- client = OpenAI(api_key=openai_api_key)
119
-
120
- system_prompt = """Answer the user's question using ONLY the provided sources from 80,000 Hours articles.
121
-
122
- STEP 1: Write your answer
123
- - Write a clear, concise answer to the question
124
- - Use a natural, conversational tone
125
- - After EACH substantive claim, add [1], [2], [3], etc. in order
126
- - Example: "Career capital is important [1]. You can build it through work [2]."
127
-
128
- STEP 2: Provide citations
129
- - For each [N] in your answer, provide a citation with:
130
- * citation_id: The number from your answer (1 for [1], 2 for [2], etc.)
131
- * source_id: Which source it came from (match the [Source N] label exactly)
132
- * quote: Copy the EXACT sentences from that source, word-for-word
133
-
134
- EXAMPLE - If you found text in [Source 3]:
135
- - Your answer: "Career capital helps you succeed [1]."
136
- - Your citation: {"citation_id": 1, "source_id": 3, "quote": "Career capital includes..."}
137
-
138
- CRITICAL RULES:
139
- 1. Number citations in ORDER: [1] is first, [2] is second, [3] is third, etc.
140
- 2. Copy quotes EXACTLY - No changes, NO ellipses, No paraphrasing
141
- 3. source_id MUST match the source number: [Source 1] → source_id: 1, [Source 5] → source_id: 5
142
- 4. Each quote must be complete sentences from the source
143
-
144
- OUTPUT FORMAT (valid JSON):
145
- {
146
- "answer": "Your answer with [1], [2], [3] after each claim.",
147
- "citations": [
148
- {
149
- "citation_id": 1,
150
- "source_id": 2,
151
- "quote": "Exact sentence from the source."
152
- },
153
- {
154
- "citation_id": 2,
155
- "source_id": 5,
156
- "quote": "Another exact sentence from a different source."
157
- }
158
- ]
159
- }"""
160
-
161
- user_prompt = f"""Context from 80,000 Hours articles:
162
-
163
- {context}
164
-
165
- Question: {question}
166
-
167
- Provide your answer in JSON format with exact quotes from the sources."""
168
-
169
- llm_start = time.time()
170
- response = client.chat.completions.create(
171
- model=llm_model,
172
- messages=[
173
- {"role": "system", "content": system_prompt},
174
- {"role": "user", "content": user_prompt}
175
- ],
176
- response_format={"type": "json_object"}
177
- )
178
- llm_time = (time.time() - llm_start) * 1000
179
- print(f"[TIMING] LLM call: {llm_time:.0f}ms")
180
-
181
- # Parse LLM response
182
- parsed = parse_llm_response(response.choices[0].message.content)
183
- if "validation_errors" in parsed:
184
- return {
185
- "answer": parsed["answer"], # raw llm response
186
- "citations": [],
187
- "validation_errors": parsed["validation_errors"],
188
- "total_citations": 0,
189
- "valid_citations": 0
190
- }
191
-
192
- answer = parsed.get("answer", "")
193
- citations = parsed.get("citations", [])
194
-
195
- # Validate citations
196
- validation_start = time.time()
197
- result = process_citations(citations, results)
198
- validation_time = (time.time() - validation_start) * 1000
199
- print(f"[TIMING] Validation: {validation_time:.0f}ms")
200
-
201
- return {
202
- "answer": answer,
203
- "citations": result["validated_citations"],
204
- "validation_errors": result["validation_errors"],
205
- "total_citations": len(citations),
206
- "valid_citations": len(result["validated_citations"])
207
- }
208
-
209
- # ============================================================================
210
- # Results Processing & Display
211
- # ============================================================================
212
-
213
- def save_validation_results(question: str, result: Dict[str, Any], results: List[Any], _unused_time: float):
214
- """Save detailed validation results to JSON file for debugging."""
215
- validation_output = {
216
- "question": question,
217
- "answer": result["answer"],
218
- "citations": result["citations"],
219
- "validation_errors": result["validation_errors"],
220
- "stats": {
221
- "total_citations": result["total_citations"],
222
- "valid_citations": result["valid_citations"]
223
- },
224
- "sources": [
225
- {
226
- "source_id": i,
227
- "title": hit.payload['title'],
228
- "url": hit.payload['url'],
229
- "chunk_id": hit.payload.get('chunk_id'),
230
- "cosine_similarity": hit.score, # Vector similarity from Qdrant
231
- "text": hit.payload['text']
232
- }
233
- for i, hit in enumerate(results, 1)
234
- ]
235
- }
236
-
237
- with open("validation_results.json", "w", encoding="utf-8") as f:
238
- json.dump(validation_output, f, ensure_ascii=False, indent=2)
239
- print("\n[INFO] Validation results saved to validation_results.json")
240
-
241
- def display_results(question: str, result: Dict[str, Any], context: str = None):
242
- """Display query results to console."""
243
- print(f"Question: {question}\n")
244
-
245
- if context:
246
- print("=" * 80)
247
- print("RETRIEVED CONTEXT:")
248
- print("=" * 80)
249
- print(context)
250
- print("\n")
251
-
252
- print("=" * 80)
253
- print("ANSWER:")
254
- print("=" * 80)
255
- print(result["answer"])
256
- print("\n")
257
-
258
- print("=" * 80)
259
- print("CITATIONS (Verified Quotes):")
260
- print("=" * 80)
261
- print(format_citations_display(result["citations"]))
262
-
263
- if result["validation_errors"]:
264
- print("\n" + "=" * 80)
265
- print("VALIDATION WARNINGS:")
266
- print("=" * 80)
267
- for error in result["validation_errors"]:
268
- print(f"⚠ [Citation {error['citation_id']}] {error['reason']}")
269
-
270
- print("\n" + "=" * 80)
271
- print(f"Citation Stats: {result['valid_citations']}/{result['total_citations']} citations validated")
272
- print("=" * 80)
273
-
274
- # ============================================================================
275
- # Main Public API
276
- # ============================================================================
277
-
278
- def ask(question: str, show_context: bool = False) -> Dict[str, Any]:
279
- """Main RAG function: retrieve context and generate answer with validated citations."""
280
- total_start = time.time()
281
-
282
- results = retrieve_context(question)
283
- if not results:
284
- print("No relevant sources found above the score threshold.")
285
- return {
286
- "question": question,
287
- "answer": "No relevant information found in the knowledge base.",
288
- "citations": [],
289
- "sources": []
290
- }
291
-
292
- context = format_context(results)
293
-
294
- result = generate_answer_with_citations(
295
- question=question,
296
- context=context,
297
- results=results,
298
- llm_model=LLM_MODEL,
299
- openai_api_key=os.getenv("OPENAI_API_KEY")
300
- )
301
-
302
- total_time = (time.time() - total_start) * 1000
303
- print(f"[TIMING] Total: {total_time:.0f}ms")
304
-
305
- # Display results
306
- # display_results(question, result, context if show_context else None)
307
-
308
- # Save debug output
309
- save_validation_results(question, result, results, 0)
310
-
311
- return {
312
- "question": question,
313
- "answer": result["answer"],
314
- "citations": result["citations"],
315
- "validation_errors": result["validation_errors"],
316
- "sources": results
317
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,14 +0,0 @@
1
- openai>=1.0.0
2
- qdrant-client>=1.7.0
3
- sentence-transformers>=2.2.0
4
- python-dotenv>=1.0.0
5
- beautifulsoup4>=4.12.0
6
- requests>=2.31.0
7
- gradio>=5.0.0
8
- rapidfuzz>=3.0.0
9
- fuzzysearch>=0.7.3
10
- trafilatura>=1.6.0
11
- python-dateutil>=2.8.0
12
- --extra-index-url https://download.pytorch.org/whl/cpu
13
- torch>=2.0.0
14
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_fuzzy.py DELETED
@@ -1,42 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Test fuzzy matching through the full validate_citation function."""
3
-
4
- from citations import validate_citation
5
-
6
- # Paste your test strings here
7
- ai_claimed_quote = """As of this writing, the top eight problem areas are: Risks from artificial intelligence, Catastrophic pandemics, Building effective altruism, Global priorities research, Nuclear war, and Improving decision making"""
8
- source_1_text = """As of this writing, the top eight problem areas are:\n- Risks from artificial intelligence\n- Catastrophic pandemics\n- Building effective altruism\n- Global priorities research\n- Nuclear war\n- Improving decision making (especially in important institutions)\n- Climate change\n- Great power conflict\nWe’ve already given few examples of concrete ways to tackle these issues above.\nThe above list is provisional, and it is likely to change as we learn more. We also list many other pressing problems that we believe are highly important from a longtermist point of view, as well as a few that would be high priorities if we rejected longtermism.\nWe hope more people will challenge our ideas and help us think more clearly about them."""
9
-
10
- source_2_text = """Another article about something else entirely."""
11
-
12
- # Create fake source chunks (minimal objects with payload attribute)
13
- class FakeChunk:
14
- def __init__(self, text, title="Test Article", url="https://example.com/test"):
15
- self.payload = {
16
- 'text': text,
17
- 'title': title,
18
- 'url': url
19
- }
20
-
21
- source_chunks = [
22
- FakeChunk(source_1_text, "Career Capital Article", "https://80000hours.org/career-capital"),
23
- FakeChunk(source_2_text, "Other Article", "https://80000hours.org/other"),
24
- ]
25
-
26
- # Test validation (source_id is 1-indexed)
27
- source_id_to_test = 1
28
- result = validate_citation(ai_claimed_quote, source_chunks, source_id_to_test)
29
-
30
- print(f"AI's claimed quote:\n\"{ai_claimed_quote}\"\n")
31
- print(f"Source {source_id_to_test} text:\n\"{source_chunks[source_id_to_test-1].payload['text']}\"\n")
32
- print(f"Valid: {result['valid']}")
33
- print(f"Fuzzy Score: {result['fuzzy_match_score']:.1f}%")
34
-
35
- if result['valid']:
36
- print(f"Matched Text: \"{result['matched_text']}\"")
37
- if result.get('remapped'):
38
- print(f"Remapped: source {result.get('original_source_id')} → {result['source_id']}")
39
- else:
40
- print(f"Reason: {result['reason']}")
41
- if result.get('matched_text'):
42
- print(f"Closest Match: \"{result['matched_text']}\"")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_url.py DELETED
@@ -1,18 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Simple test for create_highlighted_url function."""
3
-
4
- from urllib.parse import urlparse
5
- from citations import create_highlighted_url
6
-
7
- def extract_base_url(full_url: str) -> str:
8
- """Extract base URL without fragments."""
9
- parsed = urlparse(full_url)
10
- return f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
11
-
12
- # Paste your URL and text here
13
- full_url = "https://80000hours.org/articles/future-generations/"
14
- quote_text = '''- Risks from'''
15
-
16
- base_url = extract_base_url(full_url)
17
- result = create_highlighted_url(base_url, quote_text)
18
- print(result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
upload_to_qdrant_cli.py DELETED
@@ -1,143 +0,0 @@
1
- import json
2
- import os
3
- from dotenv import load_dotenv
4
- from qdrant_client import QdrantClient
5
- from qdrant_client.models import Distance, VectorParams, PointStruct
6
- from sentence_transformers import SentenceTransformer
7
- from config import MODEL_NAME, COLLECTION_NAME, EMBEDDING_DIM
8
-
9
- load_dotenv()
10
-
11
- def load_chunks(jsonl_path="chunks.jsonl"):
12
- chunks = []
13
- with open(jsonl_path, "r", encoding="utf-8") as f:
14
- for line in f:
15
- if line.strip():
16
- chunks.append(json.loads(line))
17
- return chunks
18
-
19
- def create_qdrant_client():
20
- return QdrantClient(
21
- url=os.getenv("QDRANT_URL"),
22
- api_key=os.getenv("QDRANT_API_KEY"),
23
- )
24
-
25
- def load_embedding_model():
26
- print("Loading embedding model...")
27
- return SentenceTransformer(MODEL_NAME)
28
-
29
- def create_collection(client, collection_name=COLLECTION_NAME, embedding_dim=EMBEDDING_DIM):
30
- print(f"Creating collection '{collection_name}'...")
31
- try:
32
- if client.collection_exists(collection_name):
33
- print(f"Collection '{collection_name}' exists. Deleting...")
34
- client.delete_collection(collection_name)
35
-
36
- client.create_collection(
37
- collection_name=collection_name,
38
- vectors_config=VectorParams(size=embedding_dim, distance=Distance.COSINE),
39
- )
40
- return True
41
- except Exception as e:
42
- print(f"Error creating collection: {e}")
43
- return False
44
-
45
- def generate_embeddings(model, chunks):
46
- print("Generating embeddings...")
47
- texts = [chunk["text"] for chunk in chunks]
48
- return model.encode(texts, show_progress_bar=True)
49
-
50
- def create_points(chunks, embeddings):
51
- points = []
52
- for idx, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
53
- point = PointStruct(
54
- id=idx,
55
- vector=embedding.tolist(),
56
- payload={
57
- "url": chunk["url"],
58
- "title": chunk["title"],
59
- "date": chunk["date"],
60
- "chunk_id": chunk["chunk_id"],
61
- "text": chunk["text"],
62
- }
63
- )
64
- points.append(point)
65
- return points
66
-
67
- def upload_points(client, points, collection_name=COLLECTION_NAME, batch_size=100):
68
- print(f"Uploading {len(points)} points in batches of {batch_size}...")
69
- total_batches = (len(points) + batch_size - 1) // batch_size
70
-
71
- for i in range(0, len(points), batch_size):
72
- batch = points[i:i + batch_size]
73
- batch_num = (i // batch_size) + 1
74
- print(f" Batch {batch_num}/{total_batches}: Uploading {len(batch)} points...")
75
- client.upsert(collection_name=collection_name, points=batch)
76
-
77
- print(f"✓ Uploaded {len(points)} chunks to collection '{collection_name}'")
78
-
79
- def verify_upload(client, collection_name=COLLECTION_NAME):
80
- collection_info = client.get_collection(collection_name)
81
- print(f"Collection now has {collection_info.points_count} points")
82
- return collection_info.points_count
83
-
84
- def ensure_collection_exists(client, collection_name=COLLECTION_NAME, embedding_dim=EMBEDDING_DIM):
85
- """Ensure collection exists, create if it doesn't. Returns starting ID for new points."""
86
- if not client.collection_exists(collection_name):
87
- print(f"Collection '{collection_name}' doesn't exist. Creating...")
88
- client.create_collection(
89
- collection_name=collection_name,
90
- vectors_config=VectorParams(size=embedding_dim, distance=Distance.COSINE),
91
- )
92
- return 0
93
- else:
94
- collection_info = client.get_collection(collection_name)
95
- point_count = collection_info.points_count
96
- print(f"Collection '{collection_name}' exists with {point_count} points")
97
- return point_count
98
-
99
- def offset_point_ids(points, start_id):
100
- """Update point IDs to start from a given offset."""
101
- print(f"Setting point IDs starting from {start_id}...")
102
- for i, point in enumerate(points):
103
- point.id = start_id + i
104
- return points
105
-
106
- def print_upload_summary(start_id, added_count, new_count):
107
- """Print upload summary statistics."""
108
- print(f"\n✓ Upload complete!")
109
- print(f" Previous: {start_id} points")
110
- print(f" Added: {added_count} points")
111
- print(f" Total now: {new_count} points")
112
-
113
- def upload_chunks_additive(chunks_file="chunks.jsonl"):
114
- """Upload chunks to Qdrant additively (preserves existing data)."""
115
- if not os.path.exists(chunks_file):
116
- print(f"Chunks file '{chunks_file}' not found")
117
- return
118
-
119
- chunks = load_chunks(chunks_file)
120
- print(f"Found {len(chunks)} chunks")
121
-
122
- if not chunks:
123
- print("No chunks to upload")
124
- return
125
-
126
- client = create_qdrant_client()
127
- start_id = ensure_collection_exists(client)
128
-
129
- model = load_embedding_model()
130
- embeddings = generate_embeddings(model, chunks)
131
- points = create_points(chunks, embeddings)
132
- points = offset_point_ids(points, start_id)
133
-
134
- upload_points(client, points)
135
-
136
- new_count = verify_upload(client)
137
- print_upload_summary(start_id, len(points), new_count)
138
-
139
- def main():
140
- upload_chunks_additive()
141
-
142
- if __name__ == "__main__":
143
- main()