2023-12-30 01:40:29 +00:00
from openai import OpenAI
2023-05-28 16:23:43 +00:00
import re
2023-12-30 01:40:29 +00:00
from . gpt_cst import SYSTEMPROMPTS
2023-05-29 10:11:40 +00:00
2023-05-28 16:23:43 +00:00
def post_process ( final_txt ) :
final_txt = re . findall (
r ' ```(.*?)``` ' , final_txt , re . DOTALL ) [ 0 ]
final_txt = re . sub (
r ' ^python ' , ' ' , final_txt , flags = re . MULTILINE )
return final_txt
2023-12-30 02:54:59 +00:00
def chatgpt ( context , api_key = ' ' ) :
if not api_key :
raise Exception ( " Please provide an OpenAI API key " )
2023-05-28 16:23:43 +00:00
scene = context . scene
2023-12-30 01:40:29 +00:00
# sysprompt preparation
messages = [ { " role " : " system " , " content " : system_prompt }
for system_prompt in SYSTEMPROMPTS ]
2023-05-28 16:23:43 +00:00
# add previous messages
for msg in scene . history [ - 8 : ] :
if msg . type == " GPT " :
messages . append (
{ " role " : " assistant " , " content " : " ``` \n " + msg . content + " \n ``` " } )
else :
2023-12-30 01:40:29 +00:00
messages . append ( { " role " : " user " , " content " : msg . content } )
2023-05-28 16:23:43 +00:00
2023-12-30 01:40:29 +00:00
# add the current user message
2023-05-28 16:23:43 +00:00
if messages [ - 1 ] [ " role " ] != " user " :
2023-12-30 01:40:29 +00:00
formatted_message = f " Please provide me with Blender (3D software) python code satisfying the following task: { scene . prompt_input } . \n . Do not provide with anything that is not Python code. Do not provide explanations and comments. "
messages . append ( { " role " : " user " , " content " : formatted_message } )
2023-05-28 16:23:43 +00:00
2023-12-30 01:40:29 +00:00
# send message to GPT
2023-12-30 02:54:59 +00:00
client = OpenAI ( api_key = api_key )
response = client . chat . completions . create (
2023-12-30 01:40:29 +00:00
model = scene . model ,
2023-05-28 16:23:43 +00:00
messages = messages ,
2023-12-30 01:40:29 +00:00
temperature = scene . creativity ,
2023-05-28 16:23:43 +00:00
)
try :
2023-12-30 02:54:59 +00:00
final_txt = response . choices [ 0 ] . message . content
2023-05-28 16:23:43 +00:00
return post_process ( final_txt )
except IndexError :
2023-12-30 01:40:29 +00:00
return ' '