-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_searchgpt.py
78 lines (62 loc) · 2.04 KB
/
test_searchgpt.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
#Method2 for searching art Using Wikipedia
#need prompting for getting a good thinking or opinion from the professor of art
import os
import openai
import requests
from pprint import pprint
import dotenv
dotenv.load_dotenv()
openai_api_key = os.environ.get("OPENAI_API_KEY")
bing_search_api_key = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY']
bing_search_endpoint = os.environ['BING_SEARCH_V7_ENDPOINT'] + \
"v7.0/search"
def search(query):
# Construct a request
mkt = 'en-US'
params = {'q': query, 'mkt': mkt}
headers = {'Ocp-Apim-Subscription-Key': bing_search_api_key}
# Call the API
try:
response = requests.get(bing_search_endpoint,
headers=headers, params=params)
response.raise_for_status()
json = response.json()
return json["webPages"]["value"]
# print("\nJSON Response:\n")
# pprint(response.json())
except Exception as ex:
raise ex
# Prompt the user for a question
question = input("What is your question? ")
# Send a query to the Bing search engine and retrieve the results
results = search(question)
results_prompts = [
f"Source:\nTitle: {result['name']}\nURL: {result['url']}\nContent: {result['snippet']}" for result in results
]
prompt = "Use the following sources to answer the question:\n\n" + \
"\n\n".join(results_prompts) + "\n\nQuestion: " + question + "\n\nAnswer:"
print(prompt)
messages=[
{
"role": "system",
"content": prompt,
}
]
# Check if there are any results
if results:
# Use OpenAI's GPT-3 API to answer the question
openai.api_key = openai_api_key
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=messages,
max_tokens=1024,
n=1,
stop=None,
temperature=0.7,
)
# Print the answer from OpenAI
answer = response.choices[0].message['content']
print(f"Answer: {answer}")
else:
# Print an error message if there are no results
print("Error: No results found for the given query.")