weizhiwang commited on
Commit
923dd91
·
1 Parent(s): 9542df6

update website

Browse files
example/backend/server.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import uvicorn
5
+ import json
6
+ import numpy as np
7
+ import torch
8
+ import faiss
9
+ import time
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ import voyageai
12
+ from typing import List, Dict, Any, Optional
13
+
14
+ # Initialize FastAPI
15
+ app = FastAPI(title="Research Paper RAG API")
16
+
17
+ # Configure CORS
18
+ app.add_middleware(
19
+ CORSMiddleware,
20
+ allow_origins=["*"], # In production, replace with your Svelte app's domain
21
+ allow_credentials=True,
22
+ allow_methods=["*"],
23
+ allow_headers=["*"],
24
+ )
25
+
26
+ # Load existing embeddings and papers
27
+ paper_embeddings = np.load("paper_embeddings/embeddings_final.npy")
28
+
29
+ dimension = paper_embeddings.shape[1] # Get embedding dimension
30
+
31
+ # Initialize FAISS index
32
+ index = faiss.IndexFlatIP(dimension) # Use Inner Product similarity
33
+ index.add(paper_embeddings)
34
+
35
+ with open("paper_embeddings/paper_final.json", "r") as f:
36
+ papers = json.load(f)
37
+
38
+ # Initialize models and tokenizer
39
+ llama_model_name = "OpenScholar/Llama-3.1_OpenScholar-8B"
40
+
41
+ # Initialize Llama model
42
+ llama_tokenizer = AutoTokenizer.from_pretrained(llama_model_name)
43
+ llama_model = AutoModelForCausalLM.from_pretrained(
44
+ llama_model_name,
45
+ torch_dtype=torch.float16,
46
+ device_map="cuda"
47
+ )
48
+
49
+ # Initialize VoyageAI client
50
+ voyage_client = voyageai.Client()
51
+
52
+ class QueryRequest(BaseModel):
53
+ message: str
54
+
55
+ class PaperInfo(BaseModel):
56
+ title: str
57
+ abstract: str
58
+ similarity: str
59
+
60
+ class QueryResponse(BaseModel):
61
+ response: str
62
+ papers: List[PaperInfo]
63
+
64
+ def get_voyage_embedding(text, model="voyage-3-lite"):
65
+ """Get embeddings for text using VoyageAI API with rate limiting and retry logic."""
66
+ max_retries = 3
67
+ retry_delay = 5
68
+
69
+ for attempt in range(max_retries):
70
+ try:
71
+ response = voyage_client.embed(
72
+ model=model,
73
+ texts=[text]
74
+ )
75
+ return np.array(response.embeddings[0])
76
+
77
+ except Exception as e:
78
+ if attempt == max_retries - 1: # Last attempt
79
+ print(f"Failed after {max_retries} attempts: {str(e)}")
80
+ return None
81
+ print(f"Attempt {attempt + 1} failed: {str(e)}. Retrying in {retry_delay} seconds...")
82
+ time.sleep(retry_delay)
83
+ retry_delay *= 2 # Exponential backoff
84
+
85
+ def find_relevant_papers(query_embedding, top_k=5):
86
+ # Perform similarity search using FAISS
87
+ scores, indices = index.search(query_embedding.reshape(1, -1), top_k)
88
+
89
+ # Get the papers and their similarity scores
90
+ relevant_papers = [papers[idx] for idx in indices[0]]
91
+ similarities = scores[0] # Scores are already cosine similarities
92
+
93
+ return relevant_papers, similarities
94
+
95
+ def format_papers_context(papers, similarities):
96
+ relevant_papers = []
97
+ context = "Based on the following relevant papers:\n\n"
98
+ for paper, similarity in zip(papers, similarities):
99
+ original_paper = json.load(open(paper['path']))
100
+ relevant_papers.append(original_paper)
101
+ context += f"Title: {original_paper['title']}\n"
102
+ context += f"Published Time: {original_paper['published_time']}\n"
103
+ context += f"Abstract: {original_paper['abstract']}\n\n"
104
+ return context, relevant_papers
105
+
106
+ @app.post("/api/generate", response_model=QueryResponse)
107
+ async def generate_response(request: QueryRequest):
108
+ try:
109
+ # Generate embedding for the query
110
+ query_embedding = get_voyage_embedding(request.message)
111
+
112
+ if query_embedding is None:
113
+ raise HTTPException(status_code=500, detail="Failed to generate embedding")
114
+
115
+ # Find relevant papers
116
+ relevant_papers, similarities = find_relevant_papers(query_embedding)
117
+
118
+ # Create context from relevant papers
119
+ context, paper_objects = format_papers_context(relevant_papers, similarities)
120
+
121
+ # Prepare the prompt with context
122
+ full_prompt = f"{context}\n\nQuestion: {request.message}\nAnswer:"
123
+
124
+ # Generate response using Llama model
125
+ inputs = llama_tokenizer(full_prompt, return_tensors="pt").to(llama_model.device)
126
+
127
+ with torch.no_grad():
128
+ outputs = llama_model.generate(
129
+ inputs.input_ids,
130
+ max_new_tokens=500,
131
+ num_return_sequences=1,
132
+ temperature=0.7,
133
+ do_sample=True,
134
+ pad_token_id=llama_tokenizer.eos_token_id
135
+ )
136
+
137
+ response = llama_tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True)
138
+
139
+ # Format paper info for response
140
+ paper_info = []
141
+ for i in range(min(3, len(paper_objects))):
142
+ paper_info.append(PaperInfo(
143
+ title=paper_objects[i]['title'],
144
+ abstract=paper_objects[i]['abstract'],
145
+ similarity=f"Similarity Score: {similarities[i]:.3f}"
146
+ ))
147
+
148
+ # Ensure we have exactly 3 papers in the response
149
+ while len(paper_info) < 3:
150
+ paper_info.append(PaperInfo(
151
+ title="",
152
+ abstract="",
153
+ similarity=""
154
+ ))
155
+
156
+ return QueryResponse(
157
+ response=response,
158
+ papers=paper_info
159
+ )
160
+
161
+ except Exception as e:
162
+ print(f"Error processing request: {str(e)}")
163
+ raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
164
+
165
+ if __name__ == "__main__":
166
+ uvicorn.run("server:app", host="0.0.0.0", port=8000, reload=True)
example/src/app.css ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Reset and base styles */
2
+ * {
3
+ margin: 0;
4
+ padding: 0;
5
+ box-sizing: border-box;
6
+ }
7
+
8
+ body {
9
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
10
+ Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
11
+ font-size: 16px;
12
+ line-height: 1.5;
13
+ color: #333;
14
+ background-color: #f9f9f9;
15
+ }
16
+
17
+ h1, h2, h3, h4, h5, h6 {
18
+ margin-bottom: 0.5em;
19
+ font-weight: 600;
20
+ line-height: 1.2;
21
+ }
22
+
23
+ h1 {
24
+ font-size: 2rem;
25
+ }
26
+
27
+ h2 {
28
+ font-size: 1.75rem;
29
+ }
30
+
31
+ h3 {
32
+ font-size: 1.5rem;
33
+ }
34
+
35
+ p {
36
+ margin-bottom: 1rem;
37
+ }
38
+
39
+ a {
40
+ color: #3498db;
41
+ text-decoration: none;
42
+ }
43
+
44
+ a:hover {
45
+ text-decoration: underline;
46
+ }
47
+
48
+ button {
49
+ cursor: pointer;
50
+ }
51
+
52
+ /* Utility classes */
53
+ .container {
54
+ max-width: 1200px;
55
+ margin: 0 auto;
56
+ padding: 0 20px;
57
+ }
58
+
59
+ .text-center {
60
+ text-align: center;
61
+ }
62
+
63
+ .mb-1 {
64
+ margin-bottom: 0.5rem;
65
+ }
66
+
67
+ .mb-2 {
68
+ margin-bottom: 1rem;
69
+ }
70
+
71
+ .mb-3 {
72
+ margin-bottom: 1.5rem;
73
+ }
74
+
75
+ .mb-4 {
76
+ margin-bottom: 2rem;
77
+ }
78
+
79
+ /* Form elements */
80
+ input, textarea, select {
81
+ width: 100%;
82
+ padding: 0.75rem;
83
+ border: 1px solid #ddd;
84
+ border-radius: 4px;
85
+ font-size: 1rem;
86
+ font-family: inherit;
87
+ }
88
+
89
+ input:focus, textarea:focus, select:focus {
90
+ outline: none;
91
+ border-color: #3498db;
92
+ box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
93
+ }
94
+
95
+ label {
96
+ display: block;
97
+ margin-bottom: 0.5rem;
98
+ font-weight: 500;
99
+ }
100
+
101
+ /* Button styles */
102
+ .btn {
103
+ display: inline-block;
104
+ background-color: #3498db;
105
+ color: white;
106
+ padding: 0.75rem 1.5rem;
107
+ border: none;
108
+ border-radius: 4px;
109
+ font-size: 1rem;
110
+ font-weight: 500;
111
+ text-align: center;
112
+ transition: background-color 0.2s, transform 0.1s;
113
+ }
114
+
115
+ .btn:hover {
116
+ background-color: #2980b9;
117
+ text-decoration: none;
118
+ }
119
+
120
+ .btn:active {
121
+ transform: translateY(1px);
122
+ }
123
+
124
+ .btn-secondary {
125
+ background-color: #95a5a6;
126
+ }
127
+
128
+ .btn-secondary:hover {
129
+ background-color: #7f8c8d;
130
+ }
131
+
132
+ /* Card style */
133
+ .card {
134
+ background-color: white;
135
+ border-radius: 8px;
136
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
137
+ overflow: hidden;
138
+ }
139
+
140
+ .card-header {
141
+ padding: 1rem;
142
+ border-bottom: 1px solid #eee;
143
+ }
144
+
145
+ .card-body {
146
+ padding: 1rem;
147
+ }
148
+
149
+ /* Responsive adjustments */
150
+ @media (max-width: 768px) {
151
+ h1 {
152
+ font-size: 1.75rem;
153
+ }
154
+
155
+ h2 {
156
+ font-size: 1.5rem;
157
+ }
158
+
159
+ h3 {
160
+ font-size: 1.25rem;
161
+ }
162
+ }
example/src/routes/+layout.svelte ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script>
2
+ import '../app.css';
3
+ </script>
4
+
5
+ <div class="app">
6
+ <header>
7
+ <div class="header-content">
8
+ <h1>Research Paper Assistant</h1>
9
+ <nav>
10
+ <a href="/">Home</a>
11
+ <a href="/about">About</a>
12
+ </nav>
13
+ </div>
14
+ </header>
15
+
16
+ <main>
17
+ <slot />
18
+ </main>
19
+
20
+ <footer>
21
+ <p>&copy; {new Date().getFullYear()} Research Paper RAG System - Built with Svelte</p>
22
+ </footer>
23
+ </div>
24
+
25
+ <style>
26
+ .app {
27
+ display: flex;
28
+ flex-direction: column;
29
+ min-height: 100vh;
30
+ }
31
+
32
+ header {
33
+ background-color: #2c3e50;
34
+ color: white;
35
+ padding: 1rem 0;
36
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
37
+ }
38
+
39
+ .header-content {
40
+ max-width: 1200px;
41
+ margin: 0 auto;
42
+ padding: 0 20px;
43
+ display: flex;
44
+ justify-content: space-between;
45
+ align-items: center;
46
+ }
47
+
48
+ header h1 {
49
+ margin: 0;
50
+ font-size: 1.5rem;
51
+ }
52
+
53
+ nav {
54
+ display: flex;
55
+ gap: 20px;
56
+ }
57
+
58
+ nav a {
59
+ color: white;
60
+ text-decoration: none;
61
+ font-weight: 500;
62
+ padding: 5px;
63
+ }
64
+
65
+ nav a:hover {
66
+ text-decoration: underline;
67
+ }
68
+
69
+ main {
70
+ flex: 1;
71
+ }
72
+
73
+ footer {
74
+ background-color: #f8f9fa;
75
+ padding: 1rem 0;
76
+ text-align: center;
77
+ font-size: 0.875rem;
78
+ color: #7f8c8d;
79
+ border-top: 1px solid #ecf0f1;
80
+ }
81
+ </style>
example/src/routes/+page.svelte CHANGED
@@ -1,2 +1,246 @@
1
- <h1>Welcome to SvelteKit</h1>
2
- <p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script>
2
+ import { onMount } from 'svelte';
3
+
4
+ // State variables
5
+ let question = '';
6
+ let isLoading = false;
7
+ let response = '';
8
+ let papers = [
9
+ { title: '', abstract: '', similarity: '' },
10
+ { title: '', abstract: '', similarity: '' },
11
+ { title: '', abstract: '', similarity: '' }
12
+ ];
13
+
14
+ // Example questions
15
+ const examples = [
16
+ "Can you recommend some papers about perovskite which are published in last 5 years?",
17
+ "Explain the concept of attention mechanisms in deep learning.",
18
+ "What are the main challenges in few-shot learning?"
19
+ ];
20
+
21
+ // Function to handle form submission
22
+ async function handleSubmit() {
23
+ if (!question.trim()) return;
24
+
25
+ isLoading = true;
26
+ response = '';
27
+
28
+ try {
29
+ const res = await fetch('/api/query', {
30
+ method: 'POST',
31
+ headers: {
32
+ 'Content-Type': 'application/json'
33
+ },
34
+ body: JSON.stringify({ message: question })
35
+ });
36
+
37
+ if (!res.ok) throw new Error('Failed to get response');
38
+
39
+ const data = await res.json();
40
+
41
+ // Update state with response data
42
+ response = data.response;
43
+ papers = [
44
+ {
45
+ title: data.papers[0].title,
46
+ abstract: data.papers[0].abstract,
47
+ similarity: data.papers[0].similarity
48
+ },
49
+ {
50
+ title: data.papers[1].title,
51
+ abstract: data.papers[1].abstract,
52
+ similarity: data.papers[1].similarity
53
+ },
54
+ {
55
+ title: data.papers[2].title,
56
+ abstract: data.papers[2].abstract,
57
+ similarity: data.papers[2].similarity
58
+ }
59
+ ];
60
+ } catch (error) {
61
+ console.error('Error:', error);
62
+ response = `An error occurred: ${error.message}`;
63
+ } finally {
64
+ isLoading = false;
65
+ }
66
+ }
67
+
68
+ // Function to use an example question
69
+ function useExample(example) {
70
+ question = example;
71
+ }
72
+ </script>
73
+
74
+ <svelte:head>
75
+ <title>RAG-Enhanced Llama-3.1 Chat Interface</title>
76
+ </svelte:head>
77
+
78
+ <main class="container">
79
+ <h1>RAG-Enhanced Llama-3.1 Chat Interface</h1>
80
+ <p>Ask questions about papers in the database. The system will find relevant papers and use them to generate informed responses.</p>
81
+
82
+ <div class="query-section">
83
+ <textarea
84
+ bind:value={question}
85
+ rows="3"
86
+ placeholder="Enter your question..."
87
+ aria-label="Question"
88
+ ></textarea>
89
+
90
+ <button on:click={handleSubmit} disabled={isLoading}>
91
+ {isLoading ? 'Processing...' : 'Submit'}
92
+ </button>
93
+ </div>
94
+
95
+ <div class="examples-section">
96
+ <h3>Examples:</h3>
97
+ <div class="examples-list">
98
+ {#each examples as example}
99
+ <button class="example-button" on:click={() => useExample(example)}>
100
+ {example}
101
+ </button>
102
+ {/each}
103
+ </div>
104
+ </div>
105
+
106
+ {#if response}
107
+ <div class="response-section">
108
+ <h2>Generated Response</h2>
109
+ <div class="response-box">
110
+ {response}
111
+ </div>
112
+ </div>
113
+ {/if}
114
+
115
+ {#if papers[0].title}
116
+ <div class="papers-section">
117
+ <h2>Relevant Papers</h2>
118
+ <div class="papers-grid">
119
+ {#each papers as paper, i}
120
+ <div class="paper-card">
121
+ <h3>Paper {i+1}</h3>
122
+ <h4>{paper.title}</h4>
123
+ <p class="similarity">{paper.similarity}</p>
124
+ <div class="abstract">
125
+ <h5>Abstract</h5>
126
+ <p>{paper.abstract}</p>
127
+ </div>
128
+ </div>
129
+ {/each}
130
+ </div>
131
+ </div>
132
+ {/if}
133
+ </main>
134
+
135
+ <style>
136
+ .container {
137
+ max-width: 1200px;
138
+ margin: 0 auto;
139
+ padding: 20px;
140
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
141
+ }
142
+
143
+ h1 {
144
+ color: #2c3e50;
145
+ margin-bottom: 10px;
146
+ }
147
+
148
+ .query-section {
149
+ margin: 20px 0;
150
+ }
151
+
152
+ textarea {
153
+ width: 100%;
154
+ padding: 12px;
155
+ border: 1px solid #ddd;
156
+ border-radius: 4px;
157
+ font-size: 16px;
158
+ margin-bottom: 10px;
159
+ font-family: inherit;
160
+ }
161
+
162
+ button {
163
+ background-color: #3498db;
164
+ color: white;
165
+ border: none;
166
+ padding: 10px 20px;
167
+ border-radius: 4px;
168
+ cursor: pointer;
169
+ font-size: 16px;
170
+ transition: background-color 0.3s;
171
+ }
172
+
173
+ button:hover:not(:disabled) {
174
+ background-color: #2980b9;
175
+ }
176
+
177
+ button:disabled {
178
+ background-color: #95a5a6;
179
+ cursor: not-allowed;
180
+ }
181
+
182
+ .examples-section {
183
+ margin: 20px 0;
184
+ }
185
+
186
+ .examples-list {
187
+ display: flex;
188
+ flex-direction: column;
189
+ gap: 10px;
190
+ }
191
+
192
+ .example-button {
193
+ background-color: #ecf0f1;
194
+ color: #2c3e50;
195
+ text-align: left;
196
+ padding: 10px;
197
+ }
198
+
199
+ .response-section, .papers-section {
200
+ margin-top: 30px;
201
+ }
202
+
203
+ .response-box {
204
+ background-color: #f8f9fa;
205
+ padding: 15px;
206
+ border-radius: 4px;
207
+ border-left: 4px solid #3498db;
208
+ white-space: pre-wrap;
209
+ }
210
+
211
+ .papers-grid {
212
+ display: grid;
213
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
214
+ gap: 20px;
215
+ margin-top: 20px;
216
+ }
217
+
218
+ .paper-card {
219
+ border: 1px solid #ddd;
220
+ border-radius: 4px;
221
+ padding: 15px;
222
+ background-color: #fff;
223
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
224
+ }
225
+
226
+ .similarity {
227
+ font-size: 14px;
228
+ color: #7f8c8d;
229
+ margin: 5px 0;
230
+ }
231
+
232
+ .abstract {
233
+ margin-top: 10px;
234
+ }
235
+
236
+ .abstract h5 {
237
+ margin-bottom: 5px;
238
+ }
239
+
240
+ .abstract p {
241
+ font-size: 14px;
242
+ line-height: 1.5;
243
+ max-height: 200px;
244
+ overflow-y: auto;
245
+ }
246
+ </style>
example/src/routes/about/+page.svelte ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script>
2
+ // Any specific about page logic can go here
3
+ </script>
4
+
5
+ <svelte:head>
6
+ <title>About - Research Paper Assistant</title>
7
+ </svelte:head>
8
+
9
+ <div class="container">
10
+ <h1>About This Project</h1>
11
+
12
+ <div class="card mb-4">
13
+ <div class="card-body">
14
+ <h2>RAG-Enhanced Research Paper Assistant</h2>
15
+ <p>
16
+ This application uses a Retrieval-Augmented Generation (RAG) system to provide intelligent responses
17
+ to research queries. The system searches through a database of scientific papers to find relevant
18
+ information and uses the Llama-3.1 language model to generate responses.
19
+ </p>
20
+ </div>
21
+ </div>
22
+
23
+ <div class="mb-4">
24
+ <h2>How It Works</h2>
25
+ <p>Our system follows these steps to answer your research questions:</p>
26
+
27
+ <ol>
28
+ <li>Your question is converted into a vector embedding using VoyageAI's embedding model.</li>
29
+ <li>This embedding is compared against our database of paper embeddings to find the most relevant papers.</li>
30
+ <li>The top papers are retrieved and provided as context to the Llama-3.1 language model.</li>
31
+ <li>The model generates a response based on the relevant papers and your question.</li>
32
+ <li>Both the response and the relevant papers are displayed to you.</li>
33
+ </ol>
34
+ </div>
35
+
36
+ <div class="mb-4">
37
+ <h2>Technology Stack</h2>
38
+ <div class="tech-grid">
39
+ <div class="tech-item">
40
+ <h3>Frontend</h3>
41
+ <ul>
42
+ <li>Svelte & SvelteKit</li>
43
+ <li>Modern CSS</li>
44
+ </ul>
45
+ </div>
46
+
47
+ <div class="tech-item">
48
+ <h3>Backend</h3>
49
+ <ul>
50
+ <li>Python</li>
51
+ <li>OpenScholar/Llama-3.1_OpenScholar-8B</li>
52
+ <li>VoyageAI Embeddings</li>
53
+ <li>FAISS Vector Database</li>
54
+ </ul>
55
+ </div>
56
+
57
+ <div class="tech-item">
58
+ <h3>Data</h3>
59
+ <ul>
60
+ <li>Scientific paper database</li>
61
+ <li>Pre-computed vector embeddings</li>
62
+ </ul>
63
+ </div>
64
+ </div>
65
+ </div>
66
+
67
+ <div>
68
+ <h2>Using The System</h2>
69
+ <p>
70
+ To use the system, simply enter your research question in the input field on the homepage and click "Submit".
71
+ Try to be specific with your questions to get the most relevant results. You can also use one of the example
72
+ questions to get started.
73
+ </p>
74
+ <p>
75
+ The system will display both the AI-generated response and the top relevant papers that were used to inform
76
+ that response. You can explore these papers further by reading their abstracts.
77
+ </p>
78
+ </div>
79
+ </div>
80
+
81
+ <style>
82
+ .tech-grid {
83
+ display: grid;
84
+ grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
85
+ gap: 20px;
86
+ margin-top: 20px;
87
+ }
88
+
89
+ .tech-item {
90
+ background-color: #f8f9fa;
91
+ border-radius: 8px;
92
+ padding: 20px;
93
+ border-left: 4px solid #3498db;
94
+ }
95
+
96
+ .tech-item h3 {
97
+ margin-bottom: 10px;
98
+ color: #2c3e50;
99
+ }
100
+
101
+ .tech-item ul {
102
+ list-style-type: disc;
103
+ padding-left: 20px;
104
+ }
105
+
106
+ .tech-item li {
107
+ margin-bottom: 5px;
108
+ }
109
+
110
+ ol {
111
+ padding-left: 20px;
112
+ margin: 15px 0;
113
+ }
114
+
115
+ ol li {
116
+ margin-bottom: 10px;
117
+ }
118
+ </style>
example/src/routes/api/query/+server.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { json } from '@sveltejs/kit';
2
+
3
+ // Replace this with your actual backend URL when deployed
4
+ const PYTHON_BACKEND_URL = 'http://localhost:8000/api/generate';
5
+
6
+ /**
7
+ * @type {import('@sveltejs/kit').RequestHandler}
8
+ */
9
+ export async function POST({ request }) {
10
+ try {
11
+ const { message } = await request.json();
12
+
13
+ if (!message?.trim()) {
14
+ return json({
15
+ error: 'No message provided'
16
+ }, { status: 400 });
17
+ }
18
+
19
+ // Option 1: Forward to Python backend (if running separately)
20
+ try {
21
+ const response = await fetch(PYTHON_BACKEND_URL, {
22
+ method: 'POST',
23
+ headers: {
24
+ 'Content-Type': 'application/json',
25
+ },
26
+ body: JSON.stringify({ message }),
27
+ });
28
+
29
+ if (!response.ok) {
30
+ throw new Error(`Backend responded with status: ${response.status}`);
31
+ }
32
+
33
+ const data = await response.json();
34
+ return json(data);
35
+
36
+ } catch (error) {
37
+ console.error('Error communicating with Python backend:', error);
38
+
39
+ // Fallback to dummy data if backend is not available (for development purposes)
40
+ // Remove this in production and handle errors appropriately
41
+ return json({
42
+ response: "This is a fallback response. The Python backend appears to be offline. Please ensure your backend server is running.",
43
+ papers: [
44
+ {
45
+ title: "Sample Paper 1",
46
+ abstract: "This is a placeholder abstract for development purposes only.",
47
+ similarity: "Similarity Score: 0.000"
48
+ },
49
+ {
50
+ title: "Sample Paper 2",
51
+ abstract: "This is a placeholder abstract for development purposes only.",
52
+ similarity: "Similarity Score: 0.000"
53
+ },
54
+ {
55
+ title: "Sample Paper 3",
56
+ abstract: "This is a placeholder abstract for development purposes only.",
57
+ similarity: "Similarity Score: 0.000"
58
+ }
59
+ ]
60
+ });
61
+ }
62
+ } catch (error) {
63
+ console.error('Error processing request:', error);
64
+ return json({
65
+ error: 'Internal server error'
66
+ }, { status: 500 });
67
+ }
68
+ }
example/src/routes/settings/+layout.svelte CHANGED
@@ -1,73 +1,81 @@
1
- <script lang="ts">
2
- /**
3
- * Developed by: Christopher S. Dunham
4
- * Contact: csdunham@ucsb.edu, csdunham@protonmail.com
5
- *
6
- * Copyright © Reagents of the University of California,
7
- * BioPACIFIC MIP, and their affiliates.
8
- *
9
- * This source code is licensed according to the LICENSE file
10
- * found in the root directory of this source tree and on the
11
- * project page on Github.
12
- *
13
- */
14
- interface Props {
15
- children?: import('svelte').Snippet;
16
- }
17
-
18
- let { children }: Props = $props();
19
  </script>
20
 
21
- <section class="settings">
22
- <section class="nav">
23
- <a class="nav-item" href="/settings">Settings Home</a>
24
- <a class="nav-item" href="/settings/ownership">Ownership</a>
25
- <a class="nav-item" href="/settings/publishing">Publishing</a>
26
- </section>
27
-
28
- <section class="display">
29
- {@render children?.()}
30
- </section>
31
- </section>
32
-
33
- <style lang="scss">
34
- .settings {
35
- display: flex;
36
- // gap: 10px;
37
- // margin-left: 20px;
38
- margin-top: 5px;
39
- }
40
-
41
- .nav {
42
- margin-top: 10px;
43
- height: 100%;
44
- display: flex;
45
- flex-direction: column;
46
- width: 250px;
47
- align-items: center;
48
- border-right: 1px solid black;
49
- }
50
-
51
- .nav-item {
52
- display: flex;
53
- align-items: center;
54
- justify-content: center;
55
- height: 60px;
56
- width: 100%;
57
- padding: 20px;
58
- text-decoration: none;
59
- color: #003660;
60
- }
61
-
62
- .nav-item:hover {
63
- background-color: #003660;
64
- color: white;
65
- font-weight: bold;
66
- }
67
 
68
- .display {
69
- display: flex;
70
- justify-content: center;
71
- width: 70%;
72
- }
73
- </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script>
2
+ import '../app.css';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  </script>
4
 
5
+ <div class="app">
6
+ <header>
7
+ <div class="header-content">
8
+ <h1>Research Paper Assistant</h1>
9
+ <nav>
10
+ <a href="/">Home</a>
11
+ <a href="/about">About</a>
12
+ </nav>
13
+ </div>
14
+ </header>
15
+
16
+ <main>
17
+ <slot />
18
+ </main>
19
+
20
+ <footer>
21
+ <p>&copy; {new Date().getFullYear()} Research Paper RAG System - Built with Svelte</p>
22
+ </footer>
23
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ <style>
26
+ .app {
27
+ display: flex;
28
+ flex-direction: column;
29
+ min-height: 100vh;
30
+ }
31
+
32
+ header {
33
+ background-color: #2c3e50;
34
+ color: white;
35
+ padding: 1rem 0;
36
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
37
+ }
38
+
39
+ .header-content {
40
+ max-width: 1200px;
41
+ margin: 0 auto;
42
+ padding: 0 20px;
43
+ display: flex;
44
+ justify-content: space-between;
45
+ align-items: center;
46
+ }
47
+
48
+ header h1 {
49
+ margin: 0;
50
+ font-size: 1.5rem;
51
+ }
52
+
53
+ nav {
54
+ display: flex;
55
+ gap: 20px;
56
+ }
57
+
58
+ nav a {
59
+ color: white;
60
+ text-decoration: none;
61
+ font-weight: 500;
62
+ padding: 5px;
63
+ }
64
+
65
+ nav a:hover {
66
+ text-decoration: underline;
67
+ }
68
+
69
+ main {
70
+ flex: 1;
71
+ }
72
+
73
+ footer {
74
+ background-color: #f8f9fa;
75
+ padding: 1rem 0;
76
+ text-align: center;
77
+ font-size: 0.875rem;
78
+ color: #7f8c8d;
79
+ border-top: 1px solid #ecf0f1;
80
+ }
81
+ </style>