-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_gen.py
More file actions
78 lines (56 loc) · 1.88 KB
/
code_gen.py
File metadata and controls
78 lines (56 loc) · 1.88 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
68
69
70
71
72
73
74
75
76
from prompts import CODE_GENERATION_PROMPT, TEST_GENERATION_PROMPT
from openai import OpenAI
from dotenv import load_dotenv
from pathlib import Path
import os, re, json, sys
load_dotenv(Path.cwd() / ".env")
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("""
OpenAI API Key Not Found!
You can get an OpenAI API key from: https://platform.openai.com/api-keys
""")
input("Press Enter to exit...")
sys.exit(1)
#OpenAI Client creation
def try_get_client(key : str) -> OpenAI:
try:
client = OpenAI(api_key= key)
return client
except Exception as e:
raise Exception("Failed to create OpenAI client") from e
client = try_get_client(api_key)
#Code generation
def generate_code(description: str) -> str:
messages = [
{"role": "user", "content": CODE_GENERATION_PROMPT.format(description= description)}
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.2
)
code = clean_code_output(response.choices[0].message.content)
test_messages = [
{"role": "user", "content": TEST_GENERATION_PROMPT.format(code= code)}
]
test_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=test_messages,
temperature=0.2
)
tests = clean_code_output(test_response.choices[0].message.content)
return code, tests
#Output cleaning
def clean_code_output(response : str) -> str:
match = re.search(r"```(?:python)?\s*(.*?)```", response, re.DOTALL)
if match:
return match.group(1).strip()
return response.strip()
#Save code to file
def save_code(code: str, filename: str):
if not filename.endswith(".py"):
filename = f"{filename}.py"
with open(filename, "w", encoding="utf-8") as f:
f.write(code)
print(f"Code saved to {os.path.abspath(filename)}")