Repository navigation
Expand file tree
/
Copy pathrag.py
More file actions
127 lines (90 loc) · 2.39 KB
/
Copy pathrag.py
File metadata and controls
127 lines (90 loc) · 2.39 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
import os
import chromadb
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.environ["OPEN_AI_API_KEY"])
# Vector database
chroma = chromadb.PersistentClient(path="./chroma")
collection = chroma.get_or_create_collection(
name="company_docs"
)
# -------------------------
# INDEXING
# -------------------------
documents = [
{
"id": "refund",
"text": """
Our refund policy allows customers to request a refund within
30 days of receiving their order. Shipping fees are not refundable.
Refunds are normally processed within 5 business days.
"""
},
{
"id": "shipping",
"text": """
Standard shipping usually takes 3 to 5 business days.
Express shipping takes 1 to 2 business days.
Express shipping is available only for orders above $20.
"""
}
]
def embed(text):
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
return response.data[0].embedding
# Add documents to vector DB
for document in documents:
collection.upsert(
ids=[document["id"]],
documents=[document["text"]],
embeddings=[embed(document["text"])]
)
# -------------------------
# RETRIEVAL
# -------------------------
def retrieve(question, k=2):
query_embedding = embed(question)
results = collection.query(
query_embeddings=[query_embedding],
n_results=k
)
return results["documents"][0]
# -------------------------
# GENERATION
# -------------------------
def answer(question):
chunks = retrieve(question)
context = "\n\n".join(chunks)
prompt = f"""
You are a helpful customer support assistant.
Answer the question using ONLY the information
provided in the context.
If the answer is not in the context, say:
"I don't know based on the available information."
Context:
{context}
Question:
{question}
"""
response = client.chat.completions.create(
model="gpt-5",
messages=[
{
"role": "user",
"content": prompt
}
]
)
return response.choices[0].message.content
# -------------------------
# CHAT
# -------------------------
while True:
question = input("\nYou: ")
if question.lower() in ["exit", "quit"]:
break
print("\nAI:", answer(question))