Coding Menggunakan ChatGPT – Part 1

Yang dimaksud dengan coding disini adalah membuat, konversi atau meminta penjelesan code program dalam bahasa pemograman tertentu.

Jika Anda masih menggunakan code-davinci model untuk bekerja dengan code, saatnya beralih menggunakan ChatGPT, karena per maret 2023 codex akan deprecated.

Berikut contoh sederhana menggunakan ChatGPT untuk menjelaskan sebuah baris code Python.

Contoh 1 – menjelaskan sebuah fungsi

import openai
from dotenv import dotenv_values

config = dotenv_values(".env")
openai.api_key = config["OPENAI_KEY"]


code = """
def remove_common_prefix(x, prefix, ws_prefix):
    x["completion"] = x["completion"].str[len(prefix):]
    if ws_prefix:
        x["completion"] = " " + x["completion"]
        
    return x
"""

messages = [
    {"role": "system", "content": "You are a Python explaining assistant"},
    {"role": "user", "content": f"Explain the following function: {code}"}

]

    
response = openai.ChatCompletion.create(
    model = "gpt-3.5-turbo",
    messages = messages,
    max_tokens= 200,
)

print(response.choices[0]["message"]["content"])

Berikut dua contoh response dari model:

This function `remove_common_prefix` takes in three arguments:

- `x`: a pandas DataFrame that has a column named "completion".
- `prefix`: a string representing the common prefix that the function should remove from the "completion" column of `x`.
- `ws_prefix`: a boolean value indicating whether or not to add a whitespace character before the "completion" value.

The function modifies the "completion" column of the DataFrame `x`: it removes the `prefix` string from the beginning of the "completion" column, effectively removing the common prefix. 

If `ws_prefix` is `True`, the function adds a whitespace character before the "completion" value. This is useful for example when using the modified "completion" column in a natural language processing task where we want to separate the suggested completion from the previous word. 

Finally, the function returns the modified DataFrame.
This function takes three arguments, namely x, prefix, and ws_prefix. The argument x is assumed to be a pandas DataFrame containing a column named "completion". 

The function removes the common prefix from the "completion" values in the DataFrame. The length of the prefix is specified by the second argument called 'prefix'. This is achieved using the string slice function by using the length of the prefix as the starting index. 

If the third argument called 'ws_prefix' is True, then the function adds a whitespace character before the "completion" value. This is achieved by concatenating a whitespace character with the "completion" string. 

Finally, the function returns the modified DataFrame x.

Contoh 2 – Menghitung performa code

Pada contoh dibawah, jika Anda programmer, akan mengetahui mengenai time complexity. Kita dapat menggunakan ChatGPT untuk menghitung time complexity sebuat algoritma. Pada contoh kita gunakan contoh bubble sort.

bubble_sort = """
def sort(array):
    for i in range(len(array)):
        for j in range(0, len(array)-i-1):
            if array[j] > array[j+1]:
                temp = array[j]
                array[j] = array[j+1]
                array[j+1] = temp
"""

messages = [
    {"role": "system", "content": "You are a Python explaining assistant"},
    {"role": "user", "content": f"Calculate the time complexity of the following function: {bubble_sort}"}

]

    
response = openai.ChatCompletion.create(
    model = "gpt-3.5-turbo",
    messages = messages,
)

print(response.choices[0]["message"]["content"])
The given function is performing a Bubble Sort operation to sort the input array in ascending order. 

The time complexity of this algorithm is O(n^2) in the worst-case scenario. This is because the function is using two nested loops to iterate through the array, resulting in n * n-1 comparisons and swaps.

In the best-case scenario, where the array is already sorted, the time complexity will be O(n), as the function would iterate through the array only once to check if all elements are already sorted.

Pada contoh diatas sengaja nama fungsi diberi nama sort, namun dari respon yang diberikan, dapat dilihat ChatGPT dapat mengenali code tersebut adalah bubble sort dan time complexity yang diberikan juga tepat.

Yang perlu diperhatikan ketika bekerja dengan code yang bersifat baku adalah hanya ada dua pilihan, apakah model berhasil memberikan result yang tepat atau salah sama sekali. Berbeda jika bekerja dengan natural language seperti Inggris atau bahasa lainnya.

Sharing is caring: