Code Prompting, hay còn gọi là prompt engineering cho code, là một kỹ thuật dùng để tạo ra các hướng dẫn (prompts) hiệu quả nhằm định hướng các mô hình ngôn ngữ lớn (LLMs), đặc biệt là các mô hình được đào tạo về code, tạo ra hoặc chỉnh sửa code.
Về cơ bản, bạn "nói chuyện" với AI bằng ngôn ngữ tự nhiên để yêu cầu nó viết code, sửa lỗi code, giải thích code, hoặc thực hiện các tác vụ liên quan đến code khác.
Gemini cũng có thể đóng vai trò là nhà phát triển và giúp bạn viết code bằng bất kỳ ngôn ngữ lập trình nào bạn chọn. Với vai trò là nhà phát triển, điều này có thể giúp bạn tăng tốc quá trình viết code.
Hãy tưởng tượng có một thư mục trên máy tính của bạn với hàng trăm tệp cần được đổi tên. Việc đổi tên từng tệp sẽ mất rất nhiều thời gian. Bạn biết một chút về Bash và có thể viết một script để tự động hóa việc này, nhưng điều đó cũng có thể mất khá lâu. Vì vậy, hãy viết một câu lệnh. Bạn có thể viết câu lệnh này trong chatbot Gemini công cộng dành cho người dùng phổ thông, hoặc nếu bạn quan tâm hơn đến tính bảo mật, bạn có thể viết những lời nhắc này trong tài khoản Google Cloud của mình và mở Vertex AI Studio. Ưu điểm của Vertex AI Studio là bạn có thể cấu hình nhiệt độ (temperature) v.v.
Name1_bash_rename_files_in_folderGoalWrite a prompt to write code in Bash to rename files in a folder.Modelgemini-proTemperature0.1Top-KN/APromptWrite a code snippet in Bash, which asks for a folder name. Then it takes the contents of the folder and renames all the files inside by prepending the name draft to the file name.Outputbash<br>#!/bin/bash<br><br># Ask for the folder name<br>echo "Enter the folder name: "<br>read folder_name<br><br># Check if the folder exists<br>if [ ! -d "$folder_name" ]; then<br> echo "Folder does not exist."<br> exit 1<br>fi<br><br># Get the list of files in the folder<br>files=( "$folder_name"/* )<br><br># Rename each file by prepending "draft" to the file name<br>for file in "${files[@]}"; do<br> new_file_name="draft_$(basename "$file")"<br> mv "$file" "$new_file_name"<br>done<br><br>echo "Files renamed successfully."<br>
Chắc chắn rồi, đây là bản dịch sang tiếng Việt của thông tin bạn cung cấp, sử dụng định dạng Markdown:
Name1_bash_rename_files_in_folder
Mục tiêu (Goal): Viết một câu lệnh (prompt) để tạo mã Bash nhằm đổi tên các tệp trong một thư mục.
Mô hình (Model): gemini-pro
Nhiệt độ (Temperature): 0.1
Top-K: Không áp dụng (N/A)
Câu lệnh (Prompt): Viết một đoạn mã Bash, hỏi tên thư mục. Sau đó, nó lấy nội dung của thư mục và đổi tên tất cả các tệp bên trong bằng cách thêm tiền tố "draft" vào tên tệp.
Kết quả (Output): bash
#!/bin/bash
# Hỏi tên thư mục (Ask for the folder name)
echo "Nhập tên thư mục: " # "Enter the folder name: "
read folder_name
# Kiểm tra xem thư mục có tồn tại không (Check if the folder exists)
if [ ! -d "$folder_name" ]; then
echo "Thư mục không tồn tại." # "Folder does not exist."
exit 1
fi
# Lấy danh sách các tệp trong thư mục (Get the list of files in the folder)
files=( "$folder_name"/* )
# Đổi tên từng tệp bằng cách thêm tiền tố "draft" vào tên tệp (Rename each file by prepending "draft" to the file name)
for file in "${files[@]}"; do
new_file_name="draft_$(basename "$file")"
mv "$file" "$new_file_name"
done
echo "Các tệp đã được đổi tên thành công." # "Files renamed successfully."
Bảng 16. Sử dụng Gemini để lập trình
Đây có vẻ là một đoạn code tốt đối với tôi - nó thậm chí còn được ghi chú! Tuy nhiên, vì các mô hình ngôn ngữ lớn (LLM) không thể suy luận và lặp lại dữ liệu đào tạo, việc đọc và kiểm tra mã của bạn trước là điều cần thiết.
Khoảnh khắc mà tất cả chúng ta đều chờ đợi, liệu nó có thực sự hoạt động không?
Hãy thử trước với một thư mục thử nghiệm chỉ có vài tệp trong đó, các tệp này cần được đổi tên từ filename.txt thành draft_filename.txt.
Sao chép đầu ra từ Bảng 16 (không có phần bash
bao quanh), và dán vào một tệp mới có tên: "rename_files.sh".
Mở cửa sổ terminal và gõ: . rename_files.sh
. Nó sẽ yêu cầu nhập tên thư mục, ví dụ: test. và nhấn enter.
Tập lệnh có vẻ chạy tốt. Bạn sẽ thấy thông báo: Files renamed successfully. Khi bạn nhìn vào thư mục test, hãy chú ý rằng tất cả các tệp đã được đổi tên hoàn hảo thành draft_filename.txt.
Nó đã hoạt động!
Với tư cách là một nhà phát triển, khi bạn làm việc theo nhóm, bạn sẽ phải đọc code của người khác. Gemini cũng có thể giúp bạn việc này. Hãy lấy output code từ Bảng 16, bỏ đi các comment và yêu cầu mô hình ngôn ngữ lớn giải thích những gì đang xảy ra, xem Bảng 17:
Tên_1_bash_giải_thích_code
Mục tiêu Viết một câu lệnh để giải thích code Bash
Mô hình gemini-pro
Nhiệt độ 0.1
Top-K Không áp dụng
Lời nhắc Giải thích cho tôi đoạn code Bash dưới đây:
#!/bin/bash
echo "Nhập tên thư mục: "
read folder_name
if [ ! -d "$folder_name" ]; then
echo "Thư mục không tồn tại."
exit 1
fi
files=( "$folder_name"/* )
for file in "${files[@]}"; do
new_file_name="draft_$(basename "$file")"
mv "$file" "$new_file_name"
done
echo "Đã đổi tên tệp thành công."
Output Đoạn script Bash này thực hiện các tác vụ sau:
1. Nhập dữ liệu từ người dùng:
- Nó nhắc người dùng nhập tên thư mục bằng cách sử dụng các lệnh echo và read. Tên thư mục đã nhập được lưu trữ trong biến folder_name.
2. Kiểm tra sự tồn tại của thư mục:
- Nó kiểm tra xem thư mục với tên đã chỉ định có tồn tại hay không bằng cách sử dụng điều kiện [ ! -d "$folder_name" ]. Nếu thư mục không tồn tại, nó hiển thị thông báo lỗi ("Thư mục không tồn tại.") và thoát script với mã thoát là 1.
3. Liệt kê tệp:
- Nó liệt kê tất cả các tệp bên trong thư mục đã chỉ định bằng cách sử dụng lệnh files=( "$folder_name"/* ). Lệnh này tạo một mảng có tên files chứa đường dẫn đến tất cả các tệp trong thư mục.
4. Đổi tên tệp:
- Nó lặp lại qua từng tệp trong mảng files bằng cách sử dụng vòng lặp for.
- Đối với mỗi tệp, nó tạo một tên tệp mới bằng cách sử dụng lệnh new_file_name="draft_$(basename "$file")". Tên tệp mới này được tạo bằng cách thêm tiền tố "draft_" vào tên tệp gốc.
- Sau đó, nó đổi tên tệp bằng cách sử dụng lệnh mv "$file" "$new_file_name", lệnh này di chuyển tệp đến tên tệp mới.
5. Thông báo thành công:
- Sau khi đổi tên tất cả các tệp, nó hiển thị thông báo thành công ("Đã đổi tên tệp thành công.") để cho biết rằng thao tác đổi tên đã thành công.
Bảng 17. Một câu lệnh để giải thích code
Đoạn code bash từ Bảng 16 dường như hoạt động tốt. Tuy nhiên, script này thực sự có thể tái sử dụng hơn nếu nó nhắc tôi nhập tên file, lý tưởng nhất là nó nên hoạt động như một ứng dụng riêng biệt với giao diện người dùng (UI). Là một điểm khởi đầu, Python sẽ là một ngôn ngữ tốt hơn cho ứng dụng (web) so với Bash. Các mô hình ngôn ngữ lớn (LLM) có thể giúp dịch code từ ngôn ngữ này sang ngôn ngữ khác. Xem ví dụ trong Bảng 18:
Tên: Name1_python_rename_files
Mục tiêu: Viết một lời nhắc để dịch mã Bash sang Python
Mô hình: gemini-pro
Nhiệt độ (Temperature): 0.1
Top-K: N/A
Lời nhắc: Dịch đoạn mã Bash dưới đây sang đoạn mã Python.
bash
#!/bin/bash
echo "Enter the folder name: "
read folder_name
if [ ! -d "$folder_name" ]; then
echo "Folder does not exist."
exit 1
fi
files=( "$folder_name"/* )
for file in "${files[@]}"; do
new_file_name="draft_$(basename "$file")"
mv "$file" "$new_file_name"
done
echo "Files renamed successfully."
Đầu ra:
python
import os
import shutil
# Get the folder name from the user
folder_name = input("Enter the folder name: ")
# Check if the folder exists
if not os.path.isdir(folder_name):
print("Folder does not exist.")
exit(1)
# Get a list of all files in the folder
files = os.listdir(folder_name)
# Iterate over the files
for file in files:
# Create a new file name with the prefix "draft_"
new_file_name = f"draft_{file}"
# Move the file to the new name
shutil.move(os.path.join(folder_name, file),
os.path.join(folder_name, new_file_name))
# Print a success message
print("Files renamed successfully.")
Bảng 18. Một câu lệnh (prompt) để dịch code từ Bash sang Python
Đọc và xem lại code. Sao chép kết quả từ prompt và dán vào một file mới: file_renamer.py. Kiểm tra code bằng cách mở cửa sổ Terminal và thực thi lệnh sau: python file_renamer.py
.
LƯU Ý: Khi tạo prompt cho code (Python) trong Language Studio ở Vertex AI, bạn sẽ cần nhấp vào nút 'Markdown'. Nếu không, bạn sẽ nhận được văn bản thuần túy bị thiếu phần lề phù hợp của các dòng, điều này quan trọng để chạy code Python.
Hãy chỉnh sửa thủ công một vài điểm trong code ở Bảng 18. Code này sẽ yêu cầu người dùng nhập tiền tố (prefix) cho tên tệp và viết tiền tố này bằng các ký tự in hoa. Hãy xem code ví dụ trong Đoạn *3, nhưng thật tệ. Bây giờ nó lại báo lỗi Python!
import os
import shutil
folder_name = input("Enter the folder name: ")
prefix = input("Enter the string to prepend to the filename: ")
text = toUpperCase(prefix)
if not os.path.isdir(folder_name):
print("Folder does not exist.")
exit(1)
files = os.listdir(folder_name)
for file in files:
new_filename = f"{text}_{file}"
shutil.move(os.path.join(folder_name, file),
os.path.joi(folder_name, new_file_name)) # Có lỗi chính tả ở đây: os.path.joi
print("Files renamed successfully.")
Đoạn code Python dưới đây báo lỗi:
Traceback (most recent call last):
File "/Users/leeboonstra/Documents/test_folder/rename_files.py", line 7,
in <module>
text = toUpperCase(prefix)
NameError: name 'toUpperCase' is not defined
Đoạn 3. Một script Python bị lỗi
Đoạn 4. Tôi đã làm hỏng code Python
Hãy xem liệu chúng ta có thể yêu cầu mô hình ngôn ngữ lớn (large language model) gỡ lỗi và xem xét (review) code hay không. Hãy xem Bảng 19:
Name1_python_debug_codeGoalWrite a prompt to debug and review Python code.Modelgemini-proTemperature0.1Top-KN/APromptThe below Python code gives an error:<br>Traceback (most recent call last):<br> File "/Users/leeboonstra/Documents/test_folder/rename_files.py", line 7, in <module><br> text = toUpperCase(prefix)<br>NameError: name 'toUpperCase' is not defined<br><br>Debug what's wrong and explain how I can improve the code.<br>python<br>import os<br>import shutil<br># Get the folder name from the user<br>folder_name = input("Enter the folder name: ")<br>prefix = input("Enter the string to prepend to the filename: ")<br>text = toUpperCase(prefix)<br># Check if the folder exists<br>if not os.path.isdir(folder_name):<br> print("Folder does not exist.")<br> exit(1)<br># Get a list of all files in the folder<br>files = os.listdir(folder_name)<br># Iterate over the files<br>for file in files:<br> # Create a new file name with the prefix "draft_"<br> new_filename = f"{text}_{file}"<br># Move the file to the new name<br>shutil.move(os.path.join(folder_name, file), <br>os.path.join(folder_name, new_file_name))<br># Print a success message<br>print("Files renamed successfully.")<br><br>OutputThe code calls the toUpperCase function to convert prefix to uppercase, but that function is not defined. To fix this issue, you can use the upper() method of the string class which converts a given string into uppercase. The modified code is shown below:<br><br>python<br>import os<br>import shutil<br># Get the folder name from the user<br>folder_name = input("Enter the folder name: ")<br>prefix = input("Enter the string to prepend to the filename: ")<br>text = prefix.upper()<br># Check if the folder exists<br>if not os.path.isdir(folder_name):<br> print("Folder does not exist.")<br> exit(1)<br># Get a list of all files in the folder<br>files = os.listdir(folder_name)<br># Iterate over the files<br>for file in files:<br> # Create a new file name with the prefix "draft_"<br> new_filename = f"{text}_{file}"<br> # Build the full paths for the original and new files<br> old_path = os.path.join(folder_name, file)<br> new_path = os.path.join(folder_name, new_filename)<br> # Try to move the file<br> try:<br> shutil.move(old_path, new_path)<br> except Exception as e:<br> print(f"An error occurred while moving the file {file}: {e}")<br># Print a success message<br>print("Files renamed successfully.")<br><br><br>These improvements make the code more robust and flexible while also making it easier to read and understand... (The response was truncated because it has reached the token limit. Try to increase the token limit if you need a longer response.)
Table 19. A prompt for debugging and reviewing Python code
Tuyệt vời. Dưới đây là bản dịch sang tiếng Việt của thông tin bạn cung cấp, sử dụng định dạng Markdown:
Name1\_python\_debug\_code
Mục tiêu: Viết một câu lệnh để gỡ lỗi và xem lại mã Python.
Mô hình: gemini-pro
Nhiệt độ: 0.1
Top-K: N/A
Câu lệnh:
Đoạn mã Python dưới đây gặp lỗi:
"Traceback (gần đây nhất):
File "/Users/leeboonstra/Documents/test_folder/rename_files.py", dòng 7, trong
text = toUpperCase(prefix)
NameError: tên 'toUpperCase' chưa được định nghĩa"
Hãy gỡ lỗi xem có gì sai và giải thích cách tôi có thể cải thiện mã.
```python
import os
import shutil
# Get the folder name from the user
folder_name = input("Enter the folder name: ")
prefix = input("Enter the string to prepend to the filename: ")
text = toUpperCase(prefix) # <-- Lỗi ở đây
# Check if the folder exists
if not os.path.isdir(folder_name):
print("Folder does not exist.")
exit(1)
# Get a list of all files in the folder
files = os.listdir(folder_name)
# Iterate over the files
for file in files:
# Create a new file name with the prefix "draft_"
new_filename = f"{text}_{file}"
# Move the file to the new name
shutil.move(os.path.join(folder_name, file),
os.path.join(folder_name, new_file_name))
# Print a success message
print("Files renamed successfully.")
Kết quả:
Đoạn mã gọi hàm toUpperCase để chuyển đổi prefix thành chữ hoa, nhưng hàm đó chưa được định nghĩa. Để khắc phục vấn đề này, bạn có thể sử dụng phương thức upper() của lớp string, phương thức này chuyển đổi một chuỗi đã cho thành chữ hoa. Đoạn mã đã sửa đổi được hiển thị dưới đây:
import os
import shutil
# Get the folder name from the user
folder_name = input("Enter the folder name: ")
prefix = input("Enter the string to prepend to the filename: ")
text = prefix.upper() # <-- Sử dụng phương thức .upper()
# Check if the folder exists
if not os.path.isdir(folder_name):
print("Folder does not exist.")
exit(1)
# Get a list of all files in the folder
files = os.listdir(folder_name)
# Iterate over the files
for file in files:
# Create a new file name with the prefix
new_filename = f"{text}_{file}"
# Build the full paths for the original and new files
old_path = os.path.join(folder_name, file)
new_path = os.path.join(folder_name, new_filename)
# Try to move the file
try:
shutil.move(old_path, new_path)
except Exception as e:
print(f"An error occurred while moving the file {file}: {e}")
# Print a success message
print("Files renamed successfully.")
Những cải tiến này giúp mã mạnh mẽ và linh hoạt hơn, đồng thời dễ đọc và dễ hiểu hơn... (Phản hồi bị cắt bớt do đã đạt giới hạn token. Hãy thử tăng giới hạn token nếu bạn cần phản hồi dài hơn.)
Bảng 19. Một câu lệnh để debug và review code Python
Tuyệt vời. Nó không chỉ cho tôi biết cách giải quyết vấn đề, nó còn phát hiện ra rằng mã của tôi có thêm lỗi và cách giải quyết chúng nữa. Phần cuối của lời nhắc đã đưa ra các gợi ý để cải thiện mã nói chung.
Câu lệnh cho code vẫn sử dụng mô hình ngôn ngữ lớn thông thường. Nhưng câu lệnh đa phương thức là một vấn đề riêng biệt, nó đề cập đến một kỹ thuật mà bạn sử dụng nhiều định dạng đầu vào để hướng dẫn một mô hình ngôn ngữ lớn, thay vì chỉ dựa vào văn bản. Điều này có thể bao gồm sự kết hợp của văn bản, hình ảnh, âm thanh, mã, hoặc thậm chí các định dạng khác, tùy thuộc vào khả năng của mô hình và tác vụ đang thực hiện.