Created
April 9, 2023 22:28
-
-
Save David256/f621e4e8452586c0d436d28c36f9f70f to your computer and use it in GitHub Desktop.
This code is a proof of context for a Python script that self-improves using the OpenAI API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Run this code under the Python interpreter. | |
""" | |
import os | |
import random | |
import re | |
import openai | |
PROMPT = '''Mejora el siguiente código en Python, agrégale comentarios, optimiza las líneas de códigos. No se suministra el resultado de la ejecución. | |
Código: | |
```python | |
{code} | |
``` | |
---- | |
Código optimizado: | |
```python | |
''' | |
def generate_prompt(code: str): | |
return PROMPT.format(code=code) | |
def parse_result(result: str): | |
regex = re.compile(r'(.+)(?=\n```\n*\Z)', re.DOTALL) | |
searched = regex.search(result) | |
return searched.group(1) | |
def matrix___multiply(A, B): | |
result = [[0,0,0,0], | |
[0,0,0,0], | |
[0,0,0,0], | |
[0,0,0,0]] | |
for i in range(len(A)): | |
for j in range(len(B[0])): | |
for k in range(len(B)): | |
result[i][j] += A[i][k] * B[k][j] | |
return result | |
def GenerateRandomMatrix4x4(): | |
random_matrix = [[random.randint(0, 9) for j in range(4)] for i in range(4)] | |
return random_matrix | |
def autoImprove(prompt: str): | |
"""This code use the OpenAI API to completion the task described at the prompt. Use as-is.""" | |
rRrR = openai.Completion.create( | |
model="text-davinci-003", | |
prompt=prompt, | |
temperature=0, | |
max_tokens=2048, | |
) | |
print(rRrR) | |
return rRrR["choices"][0]['text'] | |
def main(): | |
matrix1 = GenerateRandomMatrix4x4() | |
matrix2 = GenerateRandomMatrix4x4() | |
R = matrix___multiply(matrix1, | |
matrix2 | |
) | |
print('The result is:', R) | |
file = open(__file__, 'r', encoding='utf-8') | |
code = file.read() | |
proMPT = generate_prompt(code) | |
result = autoImprove(proMPT) | |
newCODE = parse_result(result) | |
file = open(__file__, 'w', encoding='utf-8') | |
file.write(newCODE) | |
file.close() | |
print('Code', 'auto', 'improved') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment