今天我們要打造一個智能程式碼生成助手!透過 AI 的程式理解能力,協助開發者快速生成程式碼、優化邏輯、撰寫測試,大幅提升開發效率。
現代軟體開發中,許多重複性的編碼工作可以自動化:
code_assistant/
├── main.py # 主程式
├── core/
│ ├── __init__.py
│ ├── code_generator.py # 程式碼生成器
│ └── code_analyzer.py # 程式碼分析器
├── generators/
│ ├── __init__.py
│ ├── function_generator.py # 函數生成器
│ ├── class_generator.py # 類別生成器
│ └── test_generator.py # 測試生成器
├── optimizers/
│ ├── __init__.py
│ ├── code_optimizer.py # 程式碼優化器
│ └── refactoring_engine.py # 重構引擎
└── utils/
├── __init__.py
├── syntax_validator.py # 語法驗證器
└── code_formatter.py # 程式碼格式化器
import google.generativeai as genai
import os
from typing import Dict, Any, List
import re
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
class CodeGenerator:
"""程式碼生成器"""
def __init__(self):
self.model = genai.GenerativeModel('gemini-2.5-flash')
self.generation_history = []
def generate_function(self, description: str,
language: str = "python",
parameters: List[Dict] = None,
return_type: str = None) -> Dict[str, Any]:
"""生成函數"""
param_str = ""
if parameters:
param_str = "\n參數:\n"
for param in parameters:
param_str += f" - {param['name']} ({param['type']}): {param.get('description', '')}\n"
return_str = f"\n返回值:{return_type}" if return_type else ""
prompt = f"""
請生成一個 {language} 函數,要求如下:
功能描述:{description}
{param_str}
{return_str}
要求:
1. 包含完整的型別提示(如果語言支援)
2. 添加清晰的註解
3. 包含錯誤處理
4. 遵循最佳實踐和編碼規範
5. 提供使用範例
請只回傳程式碼和必要的說明,不要其他內容。
"""
try:
response = self.model.generate_content(prompt)
code = self._extract_code(response.text)
result = {
'code': code,
'language': language,
'description': description,
'raw_response': response.text
}
self.generation_history.append(result)
return result
except Exception as e:
return {
'error': str(e),
'code': None
}
def generate_class(self, class_name: str,
description: str,
attributes: List[Dict] = None,
methods: List[str] = None,
language: str = "python") -> Dict[str, Any]:
"""生成類別"""
attr_str = ""
if attributes:
attr_str = "\n屬性:\n"
for attr in attributes:
attr_str += f" - {attr['name']} ({attr['type']}): {attr.get('description', '')}\n"
method_str = ""
if methods:
method_str = "\n方法:\n"
for method in methods:
method_str += f" - {method}\n"
prompt = f"""
請生成一個 {language} 類別,要求如下:
類別名稱:{class_name}
功能描述:{description}
{attr_str}
{method_str}
要求:
1. 包含 __init__ 建構函數
2. 實現所有指定的方法
3. 添加屬性的型別提示
4. 包含文件字串(docstring)
5. 遵循 PEP 8 規範(Python)
6. 提供使用範例
請只回傳程式碼和必要的說明。
"""
try:
response = self.model.generate_content(prompt)
code = self._extract_code(response.text)
return {
'code': code,
'class_name': class_name,
'language': language,
'raw_response': response.text
}
except Exception as e:
return {
'error': str(e),
'code': None
}
def generate_from_specification(self, spec: str,
language: str = "python") -> Dict[str, Any]:
"""根據規格書生成程式碼"""
prompt = f"""
請根據以下規格書生成完整的 {language} 程式碼:
{spec}
要求:
1. 實現所有描述的功能
2. 包含完整的錯誤處理
3. 添加適當的註解和文件
4. 遵循最佳實踐
5. 程式碼結構清晰
請提供:
- 完整的程式碼
- 使用說明
- 依賴套件(如果有)
"""
try:
response = self.model.generate_content(prompt)
return {
'code': self._extract_code(response.text),
'full_response': response.text,
'language': language
}
except Exception as e:
return {
'error': str(e),
'code': None
}
def _extract_code(self, text: str) -> str:
"""從回應中提取程式碼"""
# 提取程式碼區塊
code_blocks = re.findall(r'```[\w]*\n(.*?)```', text, re.DOTALL)
if code_blocks:
return code_blocks[0].strip()
# 如果沒有程式碼區塊,返回全部文字
return text.strip()
import google.generativeai as genai
import os
from typing import Dict, Any, List
import ast
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
class CodeAnalyzer:
"""程式碼分析器"""
def __init__(self):
self.model = genai.GenerativeModel('gemini-2.0-flash-exp')
def analyze_code(self, code: str, language: str = "python") -> Dict[str, Any]:
"""分析程式碼"""
prompt = f"""
請分析以下 {language} 程式碼,提供:
```{language}
{code}
```
分析項目:
1. 程式碼功能說明
2. 複雜度評估
3. 潛在問題和風險
4. 改進建議
5. 效能考量
請以結構化方式回應。
"""
try:
response = self.model.generate_content(prompt)
# 額外的語法檢查(針對 Python)
syntax_valid = True
syntax_error = None
if language.lower() == "python":
try:
ast.parse(code)
except SyntaxError as e:
syntax_valid = False
syntax_error = str(e)
return {
'analysis': response.text,
'syntax_valid': syntax_valid,
'syntax_error': syntax_error,
'language': language
}
except Exception as e:
return {
'error': str(e),
'analysis': None
}
def find_bugs(self, code: str, language: str = "python") -> Dict[str, Any]:
"""尋找程式碼錯誤"""
prompt = f"""
請仔細檢查以下 {language} 程式碼,找出所有可能的錯誤和問題:
```{language}
{code}
```
請列出:
1. 語法錯誤
2. 邏輯錯誤
3. 潛在的執行時錯誤
4. 安全性問題
5. 效能問題
對每個問題提供:
- 問題描述
- 嚴重程度(高/中/低)
- 修正建議
"""
try:
response = self.model.generate_content(prompt)
return {
'bugs_found': response.text,
'has_issues': '錯誤' in response.text or '問題' in response.text
}
except Exception as e:
return {
'error': str(e),
'bugs_found': None
}
def explain_code(self, code: str, language: str = "python") -> str:
"""解釋程式碼"""
prompt = f"""
請用淺顯易懂的方式解釋以下 {language} 程式碼:
```{language}
{code}
```
請包含:
1. 整體功能說明
2. 逐行或逐區塊解釋
3. 關鍵概念說明
4. 實際應用場景
用初學者能理解的語言說明。
"""
try:
response = self.model.generate_content(prompt)
return response.text
except Exception as e:
return f"解釋失敗:{str(e)}"
import google.generativeai as genai
import os
from typing import Dict, Any
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
class CodeOptimizer:
"""程式碼優化器"""
def __init__(self):
self.model = genai.GenerativeModel('gemini-2.0-flash-exp')
def optimize_performance(self, code: str,
language: str = "python") -> Dict[str, Any]:
"""優化程式碼效能"""
prompt = f"""
請優化以下 {language} 程式碼的效能:
原始程式碼:
```{language}
{code}
```
請提供:
1. 優化後的程式碼
2. 優化說明(為什麼這樣改進)
3. 預期的效能提升
4. 注意事項
優化重點:
- 時間複雜度
- 空間複雜度
- 資源使用
- 可讀性(在不犧牲效能的前提下)
"""
try:
response = self.model.generate_content(prompt)
return {
'optimized_code': response.text,
'original_code': code,
'language': language
}
except Exception as e:
return {
'error': str(e),
'optimized_code': None
}
def refactor_code(self, code: str,
refactor_type: str = "general",
language: str = "python") -> Dict[str, Any]:
"""重構程式碼"""
refactor_instructions = {
"general": "整體改進程式碼結構、可讀性和維護性",
"modular": "將程式碼模組化,提高重用性",
"clean": "套用 Clean Code 原則",
"solid": "套用 SOLID 設計原則"
}
instruction = refactor_instructions.get(refactor_type, refactor_instructions["general"])
prompt = f"""
請重構以下 {language} 程式碼,重構目標:{instruction}
原始程式碼:
```{language}
{code}
```
請提供:
1. 重構後的程式碼
2. 重構說明
3. 改進的地方
4. 使用範例
確保重構後的程式碼:
- 功能完全相同
- 更容易理解和維護
- 遵循最佳實踐
"""
try:
response = self.model.generate_content(prompt)
return {
'refactored_code': response.text,
'refactor_type': refactor_type,
'original_code': code
}
except Exception as e:
return {
'error': str(e),
'refactored_code': None
}
def add_documentation(self, code: str,
language: str = "python") -> Dict[str, Any]:
"""添加文件註解"""
prompt = f"""
請為以下 {language} 程式碼添加完整的文件註解:
```{language}
{code}
```
要求:
1. 為每個函數/方法添加文件字串
2. 說明參數和返回值
3. 添加行內註解解釋複雜邏輯
4. 添加模組級別的文件
5. 遵循語言的文件規範(如 Python 的 PEP 257)
保持程式碼功能不變,只添加文件。
"""
try:
response = self.model.generate_content(prompt)
return {
'documented_code': response.text,
'original_code': code
}
except Exception as e:
return {
'error': str(e),
'documented_code': None
}
import google.generativeai as genai
import os
from typing import Dict, Any
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
class TestGenerator:
"""測試生成器"""
def __init__(self):
self.model = genai.GenerativeModel('gemini-2.0-flash-exp')
def generate_unit_tests(self, code: str,
framework: str = "pytest",
language: str = "python") -> Dict[str, Any]:
"""生成單元測試"""
prompt = f"""
請為以下 {language} 程式碼生成完整的單元測試,使用 {framework} 框架:
被測試的程式碼:
```{language}
{code}
```
要求:
1. 測試所有主要功能
2. 包含正常情況和邊界情況
3. 測試錯誤處理
4. 使用適當的斷言
5. 清晰的測試命名
6. 包含測試說明
請提供:
- 完整的測試程式碼
- 測試覆蓋說明
- 執行指令
"""
try:
response = self.model.generate_content(prompt)
return {
'test_code': response.text,
'framework': framework,
'original_code': code
}
except Exception as e:
return {
'error': str(e),
'test_code': None
}
def generate_test_cases(self, function_description: str) -> List[Dict[str, Any]]:
"""生成測試案例"""
prompt = f"""
請為以下功能生成詳細的測試案例:
功能描述:{function_description}
對每個測試案例提供:
1. 測試名稱
2. 輸入參數
3. 預期輸出
4. 測試目的
5. 優先級(高/中/低)
包含:
- 正常流程測試
- 邊界值測試
- 異常情況測試
以結構化格式回應。
"""
try:
response = self.model.generate_content(prompt)
return {
'test_cases': response.text,
'function_description': function_description
}
except Exception as e:
return {
'error': str(e),
'test_cases': None
}
from core.code_generator import CodeGenerator
from core.code_analyzer import CodeAnalyzer
from optimizers.code_optimizer import CodeOptimizer
from generators.test_generator import TestGenerator
def print_header(title: str):
"""列印標題"""
print("\n" + "=" * 60)
print(f" {title}")
print("=" * 60)
def print_code_block(code: str, language: str = "python"):
"""列印程式碼區塊"""
print(f"\n```{language}")
print(code)
print("```\n")
def main():
"""程式碼生成助手主程式"""
print_header("💻 AI 程式碼生成助手")
print("""
功能列表:
📝 生成函數/類別
🔍 分析程式碼品質
⚡ 優化程式碼效能
🧪 生成單元測試
📚 添加文件註解
🐛 尋找程式碼錯誤
💡 解釋程式碼邏輯
""")
# 初始化組件
generator = CodeGenerator()
analyzer = CodeAnalyzer()
optimizer = CodeOptimizer()
test_gen = TestGenerator()
while True:
print("\n" + "─" * 60)
print("選擇功能:")
print("1. 📝 生成函數")
print("2. 🏗️ 生成類別")
print("3. 🔍 分析程式碼")
print("4. ⚡ 優化程式碼")
print("5. 🧪 生成測試")
print("6. 📚 添加文件")
print("7. 🐛 尋找錯誤")
print("8. 💡 解釋程式碼")
print("9. 🚪 退出")
try:
choice = input("\n請選擇 (1-9):").strip()
if choice == '1':
print_header("生成函數")
description = input("請描述函數功能:").strip()
language = input("程式語言 (預設 python):").strip() or "python"
if description:
print("\n🤖 生成中...")
result = generator.generate_function(description, language)
if result.get('code'):
print("\n✅ 生成成功!")
print_code_block(result['code'], language)
# 詢問是否儲存
save = input("是否儲存到檔案?(y/n):").strip().lower()
if save == 'y':
filename = input("檔案名稱:").strip()
if filename:
with open(filename, 'w', encoding='utf-8') as f:
f.write(result['code'])
print(f"✅ 已儲存到 {filename}")
else:
print(f"❌ 生成失敗:{result.get('error')}")
elif choice == '2':
print_header("生成類別")
class_name = input("類別名稱:").strip()
description = input("類別功能描述:").strip()
language = input("程式語言 (預設 python):").strip() or "python"
if class_name and description:
print("\n🤖 生成中...")
result = generator.generate_class(class_name, description, language=language)
if result.get('code'):
print("\n✅ 生成成功!")
print_code_block(result['code'], language)
else:
print(f"❌ 生成失敗:{result.get('error')}")
elif choice == '3':
print_header("分析程式碼")
print("請輸入要分析的程式碼(輸入空行結束):")
code_lines = []
while True:
line = input()
if not line:
break
code_lines.append(line)
code = '\n'.join(code_lines)
if code:
language = input("程式語言 (預設 python):").strip() or "python"
print("\n🔍 分析中...")
result = analyzer.analyze_code(code, language)
if result.get('analysis'):
print("\n📊 分析結果:")
print(result['analysis'])
if not result['syntax_valid']:
print(f"\n⚠️ 語法錯誤:{result['syntax_error']}")
else:
print(f"❌ 分析失敗:{result.get('error')}")
elif choice == '4':
print_header("優化程式碼")
print("請輸入要優化的程式碼(輸入空行結束):")
code_lines = []
while True:
line = input()
if not line:
break
code_lines.append(line)
code = '\n'.join(code_lines)
if code:
print("\n優化類型:")
print("1. 效能優化")
print("2. 程式碼重構")
print("3. 添加文件")
opt_choice = input("請選擇 (1-3):").strip()
language = input("程式語言 (預設 python):").strip() or "python"
print("\n⚡ 優化中...")
if opt_choice == '1':
result = optimizer.optimize_performance(code, language)
key = 'optimized_code'
elif opt_choice == '2':
result = optimizer.refactor_code(code, language=language)
key = 'refactored_code'
elif opt_choice == '3':
result = optimizer.add_documentation(code, language)
key = 'documented_code'
else:
print("❌ 無效的選擇")
continue
if result.get(key):
print("\n✅ 優化完成!")
print(result[key])
else:
print(f"❌ 優化失敗:{result.get('error')}")
elif choice == '5':
print_header("生成單元測試")
print("請輸入要測試的程式碼(輸入空行結束):")
code_lines = []
while True:
line = input()
if not line:
break
code_lines.append(line)
code = '\n'.join(code_lines)
if code:
framework = input("測試框架 (預設 pytest):").strip() or "pytest"
print("\n🧪 生成測試中...")
result = test_gen.generate_unit_tests(code, framework)
if result.get('test_code'):
print("\n✅ 測試生成成功!")
print(result['test_code'])
else:
print(f"❌ 生成失敗:{result.get('error')}")
elif choice == '6':
print_header("添加文件註解")
print("請輸入程式碼(輸入空行結束):")
code_lines = []
while True:
line = input()
if not line:
break
code_lines.append(line)
code = '\n'.join(code_lines)
if code:
language = input("程式語言 (預設 python):").strip() or "python"
print("\n📚 添加文件中...")
result = optimizer.add_documentation(code, language)
if result.get('documented_code'):
print("\n✅ 文件添加完成!")
print(result['documented_code'])
else:
print(f"❌ 處理失敗:{result.get('error')}")
elif choice == '7':
print_header("尋找程式碼錯誤")
print("請輸入程式碼(輸入空行結束):")
code_lines = []
while True:
line = input()
if not line:
break
code_lines.append(line)
code = '\n'.join(code_lines)
if code:
language = input("程式語言 (預設 python):").strip() or "python"
print("\n🐛 檢查中...")
result = analyzer.find_bugs(code, language)
if result.get('bugs_found'):
print("\n🔍 檢查結果:")
print(result['bugs_found'])
else:
print(f"❌ 檢查失敗:{result.get('error')}")
elif choice == '8':
print_header("解釋程式碼")
print("請輸入程式碼(輸入空行結束):")
code_lines = []
while True:
line = input()
if not line:
break
code_lines.append(line)
code = '\n'.join(code_lines)
if code:
language = input("程式語言 (預設 python):").strip() or "python"
print("\n💡 解釋中...")
explanation = analyzer.explain_code(code, language)
print("\n📖 程式碼解釋:")
print(explanation)
elif choice == '9':
print("\n👋 感謝使用!再見!")
break
else:
print("❌ 無效的選擇")
except KeyboardInterrupt:
print("\n\n👋 再見!")
break
except Exception as e:
print(f"\n❌ 發生錯誤:{e}")
if __name__ == "__main__":
main()
✅ 智能程式碼生成:根據需求自動生成高品質程式碼
✅ 多維度分析:檢查語法、邏輯、效能、安全性
✅ 自動化測試:生成完整的單元測試和測試案例
✅ 程式碼優化:效能優化、重構、文件化
✅ 多語言支援:支援 Python、JavaScript 等多種語言
💻 AI 程式碼生成助手
選擇功能:
1. 📝 生成函數
請描述函數功能:計算列表中所有數字的平均值
程式語言 (預設 python):
🤖 生成中...
✅ 生成成功!
```python
def calculate_average(numbers: list[float]) -> float:
"""
計算數字列表的平均值
參數:
numbers: 包含數字的列表
返回:
float: 平均值
異常:
ValueError: 如果列表為空
TypeError: 如果列表包含非數字元素
"""
if not numbers:
raise ValueError("列表不能為空")
try:
total = sum(numbers)
return total / len(numbers)
except TypeError:
raise TypeError("列表必須只包含數字")
# 使用範例
data = [10, 20, 30, 40, 50]
avg = calculate_average(data)
print(f"平均值:{avg}") # 輸出:30.0
是否儲存到檔案?(y/n):y
檔案名稱:calculate_average.py
✅ 已儲存到 calculate_average.py
## 💡 進階應用場景
### 1. API 端點生成
```python
# 輸入描述:
# "生成一個 FastAPI 端點,處理使用者註冊,包含郵箱驗證和密碼加密"
# 生成結果:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
from passlib.context import CryptContext
import re
app = FastAPI()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class UserRegister(BaseModel):
email: EmailStr
password: str
username: str
@app.post("/register")
async def register_user(user: UserRegister):
"""
使用者註冊端點
驗證郵箱格式、密碼強度,並加密儲存
"""
# 密碼強度檢查
if len(user.password) < 8:
raise HTTPException(status_code=400, detail="密碼至少 8 個字元")
# 加密密碼
hashed_password = pwd_context.hash(user.password)
# 儲存使用者資料(此處簡化)
return {
"message": "註冊成功",
"user_id": 12345
}
# 輸入描述:
# "生成資料清洗管道,處理 CSV 文件,移除重複項,填補缺失值"
# 生成結果:
import pandas as pd
from typing import Dict, Any
class DataCleaningPipeline:
"""資料清洗管道"""
def __init__(self, file_path: str):
self.df = pd.read_csv(file_path)
self.cleaning_report: Dict[str, Any] = {}
def remove_duplicates(self) -> 'DataCleaningPipeline':
"""移除重複資料"""
before = len(self.df)
self.df = self.df.drop_duplicates()
after = len(self.df)
self.cleaning_report['duplicates_removed'] = before - after
return self
def fill_missing_values(self, strategy: str = 'mean') -> 'DataCleaningPipeline':
"""填補缺失值"""
numeric_cols = self.df.select_dtypes(include=['number']).columns
if strategy == 'mean':
self.df[numeric_cols] = self.df[numeric_cols].fillna(
self.df[numeric_cols].mean()
)
elif strategy == 'median':
self.df[numeric_cols] = self.df[numeric_cols].fillna(
self.df[numeric_cols].median()
)
self.cleaning_report['missing_filled'] = strategy
return self
def get_report(self) -> Dict[str, Any]:
"""獲取清洗報告"""
return self.cleaning_report
def save(self, output_path: str):
"""儲存清洗後的資料"""
self.df.to_csv(output_path, index=False)
# 使用範例
pipeline = DataCleaningPipeline('data.csv')
pipeline.remove_duplicates().fill_missing_values().save('cleaned_data.csv')
print(pipeline.get_report())
原始程式碼:
def process_data(data):
result = []
for item in data:
if item > 0:
result.append(item * 2)
return result
重構後:
from typing import List
def process_positive_numbers(numbers: List[float]) -> List[float]:
"""
處理數字列表,將正數加倍
Args:
numbers: 輸入的數字列表
Returns:
處理後的數字列表,只包含加倍後的正數
Examples:
>>> process_positive_numbers([1, -2, 3, -4, 5])
[2, 6, 10]
"""
return [num * 2 for num in numbers if num > 0]
# 單元測試
def test_process_positive_numbers():
assert process_positive_numbers([1, 2, 3]) == [2, 4, 6]
assert process_positive_numbers([-1, -2, -3]) == []
assert process_positive_numbers([0, 1, -1]) == [2]
清晰的需求描述
程式碼審查
迭代改進
文件完整
生成的程式碼應該注意:
使用程式碼生成助手的效益:
今天我們打造了功能完整的程式碼生成助手,讓 AI 成為開發者的得力助手!這個系統能夠:
✅ 快速生成:根據需求自動產生高品質程式碼
✅ 智能分析:深度分析程式碼品質和潛在問題
✅ 自動優化:提升程式碼效能和可維護性
✅ 完整測試:自動生成單元測試和測試案例
✅ 文件化:添加清晰的註解和說明文件
明天我們將進入本週總結,學習如何打造專業領域的 AI 助理,整合本週所有進階技術!
程式碼生成助手不只是工具,更是提升開發效率、改善程式碼品質的智能夥伴!