-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag.py
More file actions
128 lines (94 loc) · 4.76 KB
/
Copy pathrag.py
File metadata and controls
128 lines (94 loc) · 4.76 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import os
import numpy as np
from sentence_transformers import SentenceTransformer, util
from openai import OpenAI
def load_documents(folder_path):
documents = [] # documents adında boş bir liste oluşturur
for filename in os.listdir(folder_path): # tüm dosyaları okumak için olan döngü
filepath = os.path.join(folder_path, filename) # folder path ile filename i birleştirir
with open(filepath, "r", encoding="utf-8") as f:
content = f.read() # dosyayı açıp okur
documents.append({"filename": filename, "content": content}) # dosyanın içeriğini filename ile birlikte documents listesine kayıt eder
return documents # tüm iterasyonlar bittiğinde documents listesini döndürür
def chunk_text(text, chunk_size=200, overlap=50): #aldığı texti chunk size 200 karakter ve overlap 50 karakter olarak chunklara ayıracak fonksiyon
sentences = text.split(". ") # tüm texti noktalardan ayırıarak bir liste olarak sentences 'a kaydeder.
chunks = [] # chunks adında chunkları barındıracak boş bir liste oluşturur
current_chunk = "" # anlık olarak chunk ı takip etmek için bir değişken
for sentence in sentences: # ". " dan ayırılan her liste elemanını iterasyon yapacak olan döngü
if len(current_chunk) + len(sentence) <= chunk_size: #anlık chunka ve sıradaki cümleye bakıp chunk size ile karşılaştırır
current_chunk += sentence + ". " # eğer chunk sizedan küçükse cümleyi current chunk a ekler
else:
chunks.append(current_chunk.strip()) # eğer chunk sizedan büyükse current chunkın striplenmiş halini chunks a ekler
current_chunk = current_chunk[-overlap:] + sentence + ". " # current chunktan overlap kısmını ve yeni cümleyip current chunk yapar
if current_chunk.strip(): #loop bittikten sonra kalan kısmı stripleyip chunks a ekler
chunks.append(current_chunk.strip())
return chunks #chunks ı döndürür
def chunk_all_docs(documents):
all_chunks = []
for doc in documents:
chunks = chunk_text(doc["content"])
for chunk in chunks:
all_chunks.append({"text": chunk, "source": doc["filename"]})
return all_chunks
def load_embedding_model():
return SentenceTransformer("all-MiniLM-L6-v2")
def embed_chunks(model, chunks):
texts = [chunk["text"] for chunk in chunks]
embeddings = model.encode(texts)
return embeddings
def embed_query(model, query):
return model.encode(query)
def retrieve_top_k(query_embedding, chunk_embeddings, chunks, k=3):
similarities = util.cos_sim(query_embedding, chunk_embeddings)[0]
top_results = np.argsort(-similarities)[:k]
results = []
for idx in top_results:
idx = int(idx)
results.append({
"text": chunks[idx]["text"],
"source": chunks[idx]["source"],
"score": float(similarities[idx])
})
return results
def build_prompt(query, retrieved_chunks):
context = "\n\n".join(
f"[Source: {c['source']}]\n{c['text']}" for c in retrieved_chunks
)
prompt = f"""Context:
{context}
Question: {query}
Instructions: Answer the question using only the information provided in the context above. If the answer is not in the context, say you don't know.
"""
return prompt
def generate_answer(prompt):
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ.get("OPENROUTER_API_KEY")
)
response = client.chat.completions.create(
model="openai/gpt-3.5-turbo",
messages=[
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
def main():
documents = load_documents("documents")
chunks = chunk_all_docs(documents)
model = load_embedding_model()
chunk_embeddings = embed_chunks(model, chunks)
while True:
query = input("Ask a question: ")
if query == "exit":
break
query_embedding = embed_query(model, query)
top_chunks = retrieve_top_k(query_embedding, chunk_embeddings, chunks, k=10)
print("\nRetrieved chunks:")
for c in top_chunks:
print(f"- ({c['score']:.3f}) {c['source']}: {c['text'][:80]}...")
prompt = build_prompt(query, top_chunks)
answer = generate_answer(prompt)
print("\nAnswer:")
print(answer)
if __name__ == "__main__":
main()