Create generate_text.py
Browse files- generate_text.py +36 -0
generate_text.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import openai
|
2 |
+
import os
|
3 |
+
import dotenv
|
4 |
+
|
5 |
+
## Read the environment variables
|
6 |
+
dotenv.load_dotenv('.env')
|
7 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
8 |
+
llm_model = os.getenv('LLM_MODEL')
|
9 |
+
|
10 |
+
|
11 |
+
def call_gpt(prompt):
|
12 |
+
max_retry = 5
|
13 |
+
retry = 0
|
14 |
+
prompt = prompt.encode(encoding='ASCII',errors='ignore').decode()
|
15 |
+
while True:
|
16 |
+
try:
|
17 |
+
response = openai.ChatCompletion.create(
|
18 |
+
model=llm_model,
|
19 |
+
temperature=0.9,
|
20 |
+
messages=[
|
21 |
+
{"role": "user", "content": prompt}
|
22 |
+
]
|
23 |
+
)
|
24 |
+
|
25 |
+
text = response.choices[0].message.content
|
26 |
+
return response
|
27 |
+
except Exception as oops:
|
28 |
+
retry += 1
|
29 |
+
if retry >= max_retry:
|
30 |
+
return "GPT3 error: %s" % oops
|
31 |
+
print('Error communicating with OpenAI:', oops)
|
32 |
+
sleep(1)
|
33 |
+
|
34 |
+
def generate_text():
|
35 |
+
prompt = open_file('prompt_response.txt')
|
36 |
+
call_gpt(prompt)
|