生成程式碼
前言
如何透過 ChatGPT 與其他 LLM 模型,快速生成 Python 程式碼,並進行註解轉換、SQL 查詢、自動補全等任務。
本篇目標
Chatgpt 模型與設定說明
本節正在開發中。
像 ChatGPT 這樣的大型語言模型(LLMs)在程式碼生成方面非常有效。在本節中,我們將介紹如何使用 ChatGPT 進行程式碼生成的許多範例。
OpenAI 的 Playground(聊天模式)和 gpt-3.5-turbo 模型用於以下所有範例。
與所有來自 OpenAI 的聊天模型一樣,您可以使用 系統訊息(System Message) 來定義回應的行為和格式。我們將為提示範例使用以下系統訊息:
You are a helpful code assistant that can teach a junior developer how to code. Your language of choice is Python. Don't explain the code, just generate the code block itself.
基本範例
然後,將是提示本身,其中包含您希望模型生成的特定代碼的指令。以下是代碼生成的第一個基本提示的快照。請注意,最終代碼是由 .User Message Assistant
圖片解釋:顯示了一個 OpenAI Playground 的截圖。左側是「SYSTEM」訊息(同上),右側是「USER」訊息(「編寫一段程式碼,要求用戶輸入他們的名字並說『Hello』」),以及「ASSISTANT」生成的程式碼:「name = input("What is your name? ")」、「print(“Hello”, name)」。右側還有模型選擇(gpt-3.5-turbo)和參數設置。
如果您想自己嘗試,請按照以下步驟作:
Write code that asks the user for their name and say "Hello"
將註解轉換為程式碼
您還可以使用這些 LLM 的代碼生成功能僅從註釋生成代碼。讓我們看另一個將指令作為註釋塊傳遞的示例:
prompt:
"""
1. Create a list of movies
2. Create a list of ratings for these movies
3. Combine them to make a json object of 10 movies with their ratings.
"""
以下是藉由
- ChatGPT 4o 模型
- Gemini 2.5 Flash 模型進行回答問題、
回答問題
import json
# 1. Create a list of movies
movies = [
"The Shawshank Redemption",
"The Godfather",
"The Dark Knight",
"Pulp Fiction",
"Forrest Gump",
"Inception",
"The Matrix",
"Fight Club",
"Interstellar",
"The Lord of the Rings"
]
# 2. Create a list of ratings for these movies
ratings = [9.3, 9.2, 9.0, 8.9, 8.8, 8.8, 8.7, 8.8, 8.6, 8.9]
# 3. Combine them to make a JSON object
movie_ratings = dict(zip(movies, ratings))
json_object = json.dumps(movie_ratings, indent=4)
print(json_object)
Here’s a JSON object containing 10 movies with their ratings:
{
"movies_and_ratings": [
{
"title": "The Fantastic Four: First Steps",
"rating": 8.7
},
{
"title": "Superman",
"rating": 8.3
},
{
"title": "Happy Gilmore 2",
"rating": 6.9
},
{
"title": "Sinners",
"rating": 9.7
},
{
"title": "Thunderbolts*",
"rating": 8.8
},
{
"title": "Jurassic World Rebirth",
"rating": 7.5
},
{
"title": "Together",
"rating": 9.9
},
{
"title": "Eddington",
"rating": 6.8
},
{
"title": "How to Train Your Dragon (2025)",
"rating": 9.0
},
{
"title": "KPop Demon Hunters",
"rating": 8.5
}
]
}
產生的程式碼看起來像是工作程式碼。不過,輸出不包含重要陳述式,即 .雖然這些模型會產生工作程式碼,但您必須密切注意此類小細節,並始終確保測試您的程式碼。importimport json
完整功能或下一行
這些 LLM 也已整合到 GitHub Copilot 等工具中,這使得它們對開發人員很有用。一個有用的功能是模型完成功能的能力。
prompt:
def multiply(
以下是藉由
- Chatgpt 4o 模型
- Gemini 2.5 Flash 模型進行回答問題、
回答問題
# function to multiply two numbers and add 75 to it
def multiply(a, b):
return a * b + 75
# Example usage
result = multiply(5, 10)
print(result) # Output: 125
# function to multiply two numbers and add 75 to it
def multiply(num1, num2):
"""
Multiplies two numbers and adds 75 to the product.
Args:
num1: The first number.
num2: The second number.
Returns:
The product of num1 and num2, plus 75.
"""
return (num1 * num2) + 75
MySQL 查詢生成
除了上面基本的程式碼生成範例之外,您還可以使用模型在程式設計的其他方面(例如創建和測試 MySQL 查詢)生成有用的程式碼。
假設您有一些可以作為提示的一部分的信息,然後指示它生成特定的查詢。例如:
"""
Table departments, columns = [DepartmentId, DepartmentName]
Table students, columns = [DepartmentId, StudentId, StudentName]
Create a MySQL query for all students in the Computer Science department
"""
以下是藉由
- Chatgpt 4o 模型
- Gemini 2.5 Flash 模型進行回答問題、
回答問題
SELECT students.StudentId, students.StudentName
FROM students
JOIN departments ON students.DepartmentId = departments.DepartmentId
WHERE departments.DepartmentName = 'Computer Science';
SELECT s.StudentName
FROM students s
JOIN departments d ON s.DepartmentId = d.DepartmentId
WHERE d.DepartmentName = 'Computer Science';
該模型在範例中生成了一個有用的 JOIN 查詢。我們沒有設置資料庫,所以我們無法測試生成的查詢。幸運的是,您可以使用 ChatGPT 來生成資料庫模式,以便自己測試。一種方法是使用修改後的提示,並帶有稍微不同的指令來生成資料庫模式:
Table departments, column = [DepartmentId, DepartmentName]
Table students, column = [StudentId, StudentName, DepartmentId]
Create a valid database schema with the above tables and columns
該模型生成了以下架構:
CREATE TABLE departments (
DepartmentId INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);
CREATE TABLE students (
DepartmentId INT,
StudentId INT PRIMARY KEY,
StudentName VARCHAR(50),
FOREIGN KEY (DepartmentId) REFERENCES departments(DepartmentId)
);
您可以使用類似sqliteonline.com.
您還需要虛擬資料來測試原始產生的查詢是否有效。讓我們也使用 ChatGPT 來實現這一點!提示可能如下所示:
CREATE TABLE departments (
DepartmentId INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);
CREATE TABLE students (
StudentId INT PRIMARY KEY,
StudentName VARCHAR(50),
DepartmentId INT,
FOREIGN KEY (DepartmentId) REFERENCES departments(DepartmentId)
);
Given the database schema above, generate valid insert statements include 4 rows for each table.
insert 陳述式的輸出:
INSERT INTO departments (DepartmentId, DepartmentName) VALUES
(1, 'Computer Science'),
(2, 'Mathematics'),
(3, 'Physics'),
(4, 'Biology');
INSERT INTO students (StudentId, StudentName, DepartmentId) VALUES
(101, 'John Doe', 1),
(102, 'Jane Smith', 2),
(103, 'Alice Green', 3),
(104, 'Bob Johnson', 4),
(105, 'Charlie Brown', 1),
(106, 'Diana Prince', 2),
(107, 'Eve Adams', 3),
(108, 'Frank White', 4);
現在您有了資料庫和虛擬數據,您可以使用 John Doe 和 Jane Smith 進行測試,預期結果應該只有兩行。
解釋程式碼
如果您正在學習某種編程語言,提示模型解釋部分程式碼可能會很有用。讓我們重新使用上面生成的查詢,並要求模型解釋它。
如果您使用的是之前相同的系統訊息,請注意您如何指示模型。例如,如果我們使用以下範例,模型可能會抱怨它是一個Python程式碼助手,但它仍然會提供解釋。有時模型會因為它被設計為遵循系統訊息而拒絕生成您指示的內容。
提示:
SELECT students.StudentId, students.StudentName
FROM students
INNER JOIN departments ON students.DepartmentId = departments.DepartmentId
WHERE departments.DepartmentName = 'Computer Science';
Explain the above SQL statement.
以下是藉由
- Chatgpt 4o 模型
- Gemini 2.5 Flash 模型進行回答問題、
回答問題
The SQL statement retrieves the list of students who belong to the “Computer Science” department. Here’s a breakdown of each part:
-
SELECT students.StudentId, students.StudentName- This selects the columns
StudentIdandStudentNamefrom thestudentstable to be displayed in the result.
- This selects the columns
-
FROM students- Indicates that the primary table being queried is
students.
- Indicates that the primary table being queried is
-
INNER JOIN departments ON students.DepartmentId = departments.DepartmentId- Performs an inner join between the
studentstable and thedepartmentstable, using theDepartmentIdas the key to match records in both tables.
- Performs an inner join between the
-
WHERE departments.DepartmentName = 'Computer Science'- Filters the joined records to include only those where the
DepartmentNamein thedepartmentstable is ‘Computer Science’.
- Filters the joined records to include only those where the
Result:
Only students whose DepartmentId matches a department named ‘Computer Science’ will be included in the output.
The SQL statement you provided is a SELECT query that retrieves the StudentId and StudentName from the students table.
Here's a breakdown of each part:
* SELECT students.StudentId, students.StudentName: This specifies the columns you want to retrieve from the database.
* students.StudentId refers to the StudentId column from the students table.
* students.StudentName refers to the StudentName column from the students table.
* Using students. before the column names is a good practice to explicitly state which table the column comes from, especially when dealing with multiple tables that might have columns with the same name.
* FROM students: This indicates the primary table from which you are retrieving data, which is the students table.
* INNER JOIN departments ON students.DepartmentId = departments.DepartmentId: This is where you connect the students table with the departments table.
* INNER JOIN departments: This specifies that you want to combine rows from the students table with rows from the departments table. An INNER JOIN only returns rows when there is a match in both tables based on the specified join condition.
* ON students.DepartmentId = departments.DepartmentId: This is the join condition. It tells the database to match rows where the DepartmentId in the students table is equal to the DepartmentId in the departments table. This DepartmentId likely serves as a foreign key in the students table, linking each student to their respective department.
* WHERE departments.DepartmentName = 'Computer Science': This is the filtering condition.
* It restricts the results to only include students whose associated department (found through the departments table) has a DepartmentName of 'Computer Science'.
In summary, this SQL statement is designed to:
"Retrieve the Student ID and Student Name of all students who are enrolled in the 'Computer Science' department."
編輯程式碼
範例即將推出!
調試程式碼
範例即將推出!
最佳實踐
即將推出!
References
目錄 : Applications - 大型語言模型應用和指南
上一篇 : Applications - 解決產生資料集的多元性
下一篇 : Applications - 畢業生工作分類案例研究
