-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanswer.py
131 lines (107 loc) · 4.08 KB
/
answer.py
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
129
130
131
import openai
from openai.embeddings_utils import distances_from_embeddings
import pandas as pd
import numpy as np
import json
from urllib.parse import urlparse
from config_parser import ConfigReader
config = ConfigReader()
config.loadConfig()
start_url = config.readConfigParam('start_url', '')
# Parse the URL and get the domain
local_domain = urlparse(start_url).netloc
################################################################################
# Step 11
################################################################################
df = pd.read_csv('processed/' + local_domain + '/embeddings.csv', index_col=0)
df['embeddings'] = df['embeddings'].apply(eval).apply(np.array)
df.head()
################################################################################
# Step 12
################################################################################
def create_context(
question, df, max_len=1800, size="ada"
):
"""
Create a context for a question by finding the most similar context from the dataframe
"""
# Get the embeddings for the question
q_embeddings = openai.Embedding.create(
input=question, engine='text-embedding-ada-002')['data'][0]['embedding']
# Get the distances from the embeddings
df['distances'] = distances_from_embeddings(
q_embeddings, df['embeddings'].values, distance_metric='cosine')
returns = []
cur_len = 0
# Sort by distance and add the text to the context until the context is too long
for i, row in df.sort_values('distances', ascending=True).iterrows():
# Add the length of the text to the current length
cur_len += row['n_tokens'] + 4
# If the context is too long, break
if cur_len > max_len:
break
# Else add it to the text that is being returned
returns.append(row["text"])
# Return the context
return "\n\n###\n\n".join(returns)
def answer_question(
df,
# model="text-davinci-003",
model="gpt-3.5-turbo",
question="Am I allowed to publish model outputs to Twitter, without a human review?",
max_len=1800,
size="ada",
debug=False,
max_tokens=150,
stop_sequence=None
):
"""
Answer a question based on the most similar context from the dataframe texts
"""
context = create_context(
question,
df,
max_len=max_len,
size=size,
)
# If debug, print the raw model response
if debug:
print("Context:\n" + context)
print("\n\n")
try:
# Create a completions using the questin and context
response = openai.ChatCompletion.create(
messages=[
{"role": "system", "content": f"Answer the question based on the context below, and if the question can't be answered based on the context, say \"I don't know\"\n\nContext: {context}"},
{"role": "user", "content": f"Question: {question}"},
],
# messages=[
# {"role": "system", "content": "Answer the question based on the context below, and if the question can't be answered based on the context, say \"I don't know\"\n\n"},
# {"role": "user", "content": f"Context: {context}\n\n---\n\nQuestion: {question}"},
# ],
temperature=0.2,
max_tokens=max_tokens,
top_p=0.8,
frequency_penalty=0,
presence_penalty=0,
stop=stop_sequence,
model=model,
)
message = response["choices"][0]["message"]
if message:
# print(message["role"] + ": " + message["content"])
# print(choice)
# return response["choices"][0]["text"].strip()
return message
else:
return ""
except Exception as e:
print(e)
return ""
################################################################################
# Step 13
################################################################################
text = input("Ask me a question: ")
while text:
print(answer_question(df, question=text, debug=True))
text = input("Ask me a question: ")