-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion.py
More file actions
67 lines (58 loc) · 2.13 KB
/
question.py
File metadata and controls
67 lines (58 loc) · 2.13 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
import psycopg2
import openai
import os
from llama_index.embeddings.openai import OpenAIEmbedding
# --- Setup ---
openai.api_key = os.getenv("OPENAI_API_KEY")
embed_model = OpenAIEmbedding(model="text-embedding-ada-002")
client = openai.OpenAI()
connection_string = "postgresql://yugabyte:password@127.0.0.1:5433/yugabyte"
def ask_question(question, top_k=7):
# Connect to DB
conn = psycopg2.connect(connection_string)
cursor = conn.cursor()
# Get embedding of question
query_embedding = embed_model.get_query_embedding(question)
embedding_str = "[" + ",".join(map(str, query_embedding)) + "]"
# Vector search
search_sql = """
SELECT id, article_text, embedding <=> %s AS distance
FROM vectors
ORDER BY embedding <=> %s
LIMIT %s;
"""
cursor.execute(search_sql, (embedding_str, embedding_str, top_k))
results = cursor.fetchall()
cursor.close()
conn.close()
if not results:
return "No matching documents found."
# Print the first 40 characters of each retrieved chunk
print("\n🔍 Retrieved context snippets:")
for _, text, distance in results:
print(f"- {text[:40]!r} (distance: {distance:.4f})")
# Build context
context = "\n\n".join([f"{text}" for (_, text, _) in results])
# Ask GPT
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant that answers questions using the provided context."},
{"role": "user", "content": f"Context:\n{context}"},
{"role": "user", "content": f"Question: {question}"}
],
temperature=0.3,
)
return response.choices[0].message.content.strip()
# --- Interactive Loop ---
if __name__ == "__main__":
try:
print("Ask me a question (press Ctrl+C to quit):\n")
while True:
question = input("❓ Your question: ").strip()
if not question:
continue
answer = ask_question(question)
print("\n💡 Answer:\n" + answer + "\n")
except KeyboardInterrupt:
print("\nGoodbye! 👋")