-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_answer.py
More file actions
74 lines (49 loc) · 1.3 KB
/
Copy pathgenerate_answer.py
File metadata and controls
74 lines (49 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from __future__ import annotations
from pathlib import Path
import ollama
from query_rag import search
DB_DIR = Path("vector_db")
def build_context(results: list[tuple[float, dict]]) -> str:
parts = []
for rank, (score, record) in enumerate(results, start=1):
parts.append(
f"""
[Result {rank}]
Chapter: {record['chapter']}
Subtopic: {record['subtopic']}
Pages: {record['page_start']} - {record['page_end']}
Content:
{record['text']}
"""
)
return "\n\n".join(parts)
def generate(question: str, top_k: int = 3) -> str:
results = search(DB_DIR, question, top_k=top_k)
context = build_context(results)
prompt = f"""
You are an Operating Systems tutor.
Answer the user's question ONLY using the retrieved textbook context.
If the answer is not present in the context, say:
"Information not found in retrieved context."
Retrieved Context:
{context}
Question:
{question}
Answer:
"""
response = ollama.chat(
model="phi3",
messages=[
{
"role": "user",
"content": prompt,
}
],
)
return response["message"]["content"]
if __name__ == "__main__":
question = input("Ask a question: ")
answer = generate(question)
print("\n")
print("=" * 80)
print(answer)