02 - 代码生成¶
提示词设计、代码生成、代码优化
📖 章节概述¶
本章将深入介绍如何使用AI生成高质量代码,包括提示词设计技巧、代码生成方法、代码优化策略以及实际应用场景。通过详细的代码示例和实践指导,帮助读者掌握AI代码生成的核心技能。
🎯 学习目标¶
完成本章后,你将能够:
- 深入理解提示词工程的核心原理
- 掌握高质量代码生成的提示词设计技巧
- 学会不同类型代码的生成方法
- 理解代码优化和重构的策略
- 能够高效生成高质量、可维护的代码
- 掌握代码生成的最佳实践
1. 提示词设计¶
1.1 清晰描述¶
技术原理: 清晰的提示词是生成高质量代码的基础。提示词应该包含: - 明确的目标:说明要实现什么功能 - 具体的要求:指定技术栈、框架、约束条件 - 上下文信息:提供相关的代码或项目背景 - 输出格式:明确期望的输出格式
代码示例 - 清晰描述的提示词模板:
Python
from typing import List
class PromptTemplates:
"""提示词模板"""
@staticmethod
def function_prompt(description: str, language: str = "python",
requirements: List[str] = None) -> str:
"""
函数生成提示词模板
Args:
description: 函数描述
language: 编程语言
requirements: 额外要求
"""
prompt = f"""请用{language}语言实现以下功能:
功能描述:
{description}
技术要求:
- 使用类型注解
- 添加详细的文档字符串(docstring)
- 包含参数验证
- 实现错误处理
- 遵循{language}的编码规范
"""
if requirements:
prompt += "\n额外要求:\n"
for req in requirements:
prompt += f"- {req}\n"
prompt += "\n请提供完整的、可运行的代码实现。"
return prompt
@staticmethod
def class_prompt(description: str, class_name: str = None,
language: str = "python") -> str:
"""
类生成提示词模板
Args:
description: 类描述
class_name: 类名
language: 编程语言
"""
prompt = f"""请用{language}语言实现以下类:
类描述:
{description}
"""
if class_name:
prompt += f"类名:{class_name}\n"
prompt += """
技术要求:
- 实现__init__方法
- 使用类型注解
- 添加详细的文档字符串
- 实现必要的魔术方法(__str__, __repr__等)
- 包含参数验证
- 实现错误处理
- 提供使用示例
请提供完整的、可运行的代码实现。
"""
return prompt
@staticmethod
def api_prompt(description: str, framework: str = "Flask",
language: str = "python") -> str:
"""
API生成提示词模板
Args:
description: API描述
framework: Web框架
language: 编程语言
"""
prompt = f"""请用{language}语言和{framework}框架实现以下REST API:
API描述:
{description}
技术要求:
- 实现RESTful设计
- 包含数据验证
- 实现错误处理
- 添加API文档(Swagger/OpenAPI)
- 使用适当的HTTP状态码
- 实现CORS支持
- 添加日志记录
- 提供测试示例
请提供完整的、可运行的代码实现。
"""
return prompt
# 使用示例
if __name__ == "__main__":
# 生成函数提示词
function_prompt = PromptTemplates.function_prompt(
description="实现一个快速排序算法,支持自定义比较函数",
language="python",
requirements=[
"时间复杂度O(n log n)",
"空间复杂度O(log n)",
"支持降序排序"
]
)
print("函数生成提示词:")
print(function_prompt)
# 生成类提示词
class_prompt = PromptTemplates.class_prompt(
description="实现一个栈(Stack)数据结构,支持push、pop、peek、is_empty操作",
class_name="Stack",
language="python"
)
print("\n类生成提示词:")
print(class_prompt)
# 生成API提示词
api_prompt = PromptTemplates.api_prompt(
description="实现一个用户管理API,包括用户注册、登录、获取用户信息、更新用户信息",
framework="FastAPI",
language="python"
)
print("\nAPI生成提示词:")
print(api_prompt)
1.2 提供上下文¶
技术原理: 提供上下文信息可以帮助AI更好地理解需求,生成更准确的代码。上下文可以包括: - 现有代码:相关的函数、类或模块 - 项目结构:项目的组织方式 - 依赖关系:使用的库和框架 - 编码规范:项目的代码风格
代码示例 - 上下文感知的代码生成:
Python
import openai
from typing import Dict, List
class ContextAwareGenerator:
"""上下文感知的代码生成器"""
def __init__(self, api_key: str):
self.client = openai.OpenAI(api_key=api_key)
def generate_with_context(self, description: str,
existing_code: str = None,
project_structure: Dict = None,
dependencies: List[str] = None) -> str:
"""
基于上下文生成代码
Args:
description: 功能描述
existing_code: 现有代码
project_structure: 项目结构
dependencies: 依赖列表
"""
prompt = "请基于以下上下文生成代码:\n\n"
# 添加功能描述
prompt += f"功能描述:\n{description}\n\n"
# 添加现有代码
if existing_code:
prompt += "现有代码:\n```python\n"
prompt += existing_code
prompt += "\n```\n\n"
# 添加项目结构
if project_structure:
prompt += "项目结构:\n"
for key, value in project_structure.items():
prompt += f"- {key}: {value}\n"
prompt += "\n"
# 添加依赖
if dependencies:
prompt += "使用的依赖:\n"
for dep in dependencies:
prompt += f"- {dep}\n"
prompt += "\n"
prompt += "请生成与现有代码风格一致、符合项目结构的代码实现。"
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个专业的程序员,擅长理解上下文并生成一致的代码。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
def extend_existing_code(self, existing_code: str,
extension_description: str) -> str:
"""
扩展现有代码
Args:
existing_code: 现有代码
extension_description: 扩展描述
"""
prompt = f"""请扩展现有代码:
现有代码:
~~~python
{existing_code}
~~~
扩展需求:
{extension_description}
要求:
- 保持代码风格一致
- 重用现有函数和类
- 添加必要的类型注解
- 更新文档字符串
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个专业的程序员,擅长代码扩展和重构。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
# 使用示例
if __name__ == "__main__":
generator = ContextAwareGenerator(api_key="your_api_key_here")
# 示例1:基于上下文生成代码
existing_code = """
class User:
def __init__(self, username: str, email: str):
self.username = username
self.email = email
self.created_at = datetime.now()
def to_dict(self):
return {
'username': self.username,
'email': self.email,
'created_at': self.created_at
}
"""
project_structure = {
"models/": "数据模型",
"services/": "业务逻辑",
"utils/": "工具函数"
}
dependencies = ["SQLAlchemy", "Pydantic", "pytest"]
code = generator.generate_with_context(
description="实现一个UserService类,包含创建用户、获取用户、更新用户、删除用户的方法",
existing_code=existing_code,
project_structure=project_structure,
dependencies=dependencies
)
print("生成的代码:")
print(code)
# 示例2:扩展现有代码
extension = generator.extend_existing_code(
existing_code=existing_code,
extension_description="添加密码哈希和验证功能,支持用户登录"
)
print("\n扩展后的代码:")
print(extension)
2. 代码生成¶
2.1 基础生成¶
2.1.1 函数生成¶
代码示例 - 函数生成器:
Python
import openai
class FunctionGenerator:
"""函数生成器"""
def __init__(self, api_key: str):
self.client = openai.OpenAI(api_key=api_key)
def generate_sorting_function(self, algorithm: str = "quicksort") -> str:
"""
生成排序函数
Args:
algorithm: 排序算法类型
"""
prompt = f"""请用Python实现{algorithm}算法。
要求:
1. 函数名为{algorithm.lower()}
2. 使用类型注解
3. 添加详细的文档字符串
4. 包含时间复杂度和空间复杂度说明
5. 提供使用示例
6. 处理边界情况(空列表、单元素列表)
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个算法专家。"},
{"role": "user", "content": prompt}
],
temperature=0.2
)
return response.choices[0].message.content
def generate_data_processing_function(self, task: str) -> str:
"""
生成数据处理函数
Args:
task: 数据处理任务
"""
prompt = f"""请用Python实现以下数据处理功能:{task}
要求:
1. 使用类型注解
2. 添加详细的文档字符串
3. 处理异常情况
4. 提供使用示例
5. 考虑性能优化
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个数据处理专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
def generate_utility_function(self, description: str) -> str:
"""
生成工具函数
Args:
description: 函数描述
"""
prompt = f"""请用Python实现以下工具函数:{description}
要求:
1. 使用类型注解
2. 添加详细的文档字符串
3. 处理边界情况
4. 提供使用示例
5. 遵循Python最佳实践
"""
response = self.client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "你是一个Python工具函数专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
# 使用示例
if __name__ == "__main__":
generator = FunctionGenerator(api_key="your_api_key_here")
# 生成排序函数
print("生成快速排序函数:")
quicksort = generator.generate_sorting_function("quicksort")
print(quicksort)
# 生成数据处理函数
print("\n生成数据处理函数:")
data_processing = generator.generate_data_processing_function(
"实现一个函数,从CSV文件读取数据并计算每列的平均值、最大值、最小值"
)
print(data_processing)
# 生成工具函数
print("\n生成工具函数:")
utility = generator.generate_utility_function(
"实现一个函数,将字节大小转换为人类可读的格式(如1024转换为1KB)"
)
print(utility)
2.1.2 类生成¶
代码示例 - 类生成器:
Python
import openai
from typing import List
class ClassGenerator:
"""类生成器"""
def __init__(self, api_key: str):
self.client = openai.OpenAI(api_key=api_key)
def generate_data_class(self, description: str,
fields: List[str] = None) -> str:
"""
生成数据类
Args:
description: 类描述
fields: 字段列表
"""
prompt = f"""请用Python实现以下数据类:{description}
"""
if fields:
prompt += "\n字段:\n"
for field in fields:
prompt += f"- {field}\n"
prompt += """
要求:
1. 使用dataclass装饰器
2. 添加类型注解
3. 实现__str__和__repr__方法
4. 添加验证逻辑
5. 提供使用示例
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个Python数据类专家。"},
{"role": "user", "content": prompt}
],
temperature=0.2
)
return response.choices[0].message.content
def generate_service_class(self, description: str) -> str:
"""
生成服务类
Args:
description: 服务描述
"""
prompt = f"""请用Python实现以下服务类:{description}
要求:
1. 使用依赖注入
2. 添加类型注解
3. 实现错误处理
4. 添加日志记录
5. 提供使用示例
6. 考虑线程安全
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个服务层设计专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
def generate_manager_class(self, description: str) -> str:
"""
生成管理器类
Args:
description: 管理器描述
"""
prompt = f"""请用Python实现以下管理器类:{description}
要求:
1. 实现CRUD操作
2. 使用类型注解
3. 添加查询方法
4. 实现分页功能
5. 添加缓存支持
6. 提供使用示例
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个数据访问层专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
# 使用示例
if __name__ == "__main__":
generator = ClassGenerator(api_key="your_api_key_here")
# 生成数据类
print("生成用户数据类:")
user_class = generator.generate_data_class(
description="用户信息类",
fields=[
"id: int - 用户ID",
"username: str - 用户名",
"email: str - 邮箱",
"created_at: datetime - 创建时间",
"is_active: bool - 是否激活"
]
)
print(user_class)
# 生成服务类
print("\n生成邮件服务类:")
email_service = generator.generate_service_class(
description="邮件服务类,支持发送邮件、发送模板邮件、批量发送"
)
print(email_service)
# 生成管理器类
print("\n生成文章管理器类:")
article_manager = generator.generate_manager_class(
description="文章管理器,支持创建、查询、更新、删除文章,支持按分类、标签查询"
)
print(article_manager)
2.2 复杂生成¶
2.2.1 完整功能¶
代码示例 - 完整功能生成器:
Python
import openai
class FeatureGenerator:
"""完整功能生成器"""
def __init__(self, api_key: str):
self.client = openai.OpenAI(api_key=api_key)
def generate_auth_feature(self) -> str:
"""
生成认证功能
Returns:
完整的认证功能代码
"""
prompt = """请用Python实现完整的用户认证功能,包括以下功能:
1. 用户注册
2. 用户登录
3. 密码哈希
4. JWT Token生成和验证
5. 密码重置
6. 邮箱验证
技术要求:
- 使用Flask框架
- 使用SQLAlchemy ORM
- 使用Pydantic进行数据验证
- 实现JWT认证
- 添加日志记录
- 包含单元测试
- 提供API文档
请提供完整的、可运行的代码实现,包括:
- models.py(数据模型)
- schemas.py(Pydantic模式)
- services.py(业务逻辑)
- routes.py(API路由)
- auth.py(认证工具)
- tests.py(测试用例)
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个全栈开发专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3,
max_tokens=4000
)
return response.choices[0].message.content
def generate_file_upload_feature(self) -> str:
"""
生成文件上传功能
Returns:
完整的文件上传功能代码
"""
prompt = """请用Python实现完整的文件上传功能,包括以下功能:
1. 文件上传
2. 文件类型验证
3. 文件大小限制
4. 文件存储(本地存储和云存储)
5. 文件下载
6. 文件删除
7. 文件列表查询
技术要求:
- 使用Flask框架
- 支持多种文件类型
- 实现文件分片上传
- 添加病毒扫描
- 实现文件压缩
- 包含单元测试
- 提供API文档
请提供完整的、可运行的代码实现。
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个文件处理专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3,
max_tokens=4000
)
return response.choices[0].message.content
# 使用示例
if __name__ == "__main__":
generator = FeatureGenerator(api_key="your_api_key_here")
# 生成认证功能
print("生成认证功能:")
auth_feature = generator.generate_auth_feature()
print(auth_feature)
# 生成文件上传功能
print("\n生成文件上传功能:")
upload_feature = generator.generate_file_upload_feature()
print(upload_feature)
2.2.2 多文件生成¶
代码示例 - 多文件生成器:
Python
import openai
from typing import Dict, List
class MultiFileGenerator:
"""多文件生成器"""
def __init__(self, api_key: str):
self.client = openai.OpenAI(api_key=api_key)
def generate_flask_project(self, project_name: str,
features: List[str] = None) -> Dict[str, str]:
"""
生成Flask项目
Args:
project_name: 项目名称
features: 功能列表
"""
if features is None:
features = ["用户认证", "数据库集成", "API文档"]
prompt = f"""请生成一个完整的Flask项目,项目名称:{project_name}
功能需求:
{chr(10).join([f"- {f}" for f in features])}
请提供以下文件:
1. app.py(主应用文件)
2. config.py(配置文件)
3. models.py(数据模型)
4. routes.py(API路由)
5. requirements.txt(依赖列表)
6. README.md(项目说明)
7. .env.example(环境变量示例)
每个文件请用```filename标记,例如:
```app.py
# app.py内容
```
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个Flask项目架构专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3,
max_tokens=4000
)
content = response.choices[0].message.content
# 解析文件
files = {}
current_file = None
current_content = []
for line in content.split('\n'):
if line.startswith('```'):
if current_file:
files[current_file] = '\n'.join(current_content)
current_file = line[3:].strip()
current_content = []
elif current_file:
current_content.append(line)
if current_file:
files[current_file] = '\n'.join(current_content)
return files
def generate_react_component(self, component_name: str,
props: List[str] = None) -> Dict[str, str]:
"""
生成React组件
Args:
component_name: 组件名称
props: Props列表
"""
if props is None:
props = ["title", "content", "onClick"]
prompt = f"""请生成一个React组件,组件名称:{component_name}
Props:
{chr(10).join([f"- {p}" for p in props])}
请提供以下文件:
1. ComponentName.tsx(组件文件)
2. ComponentName.module.css(样式文件)
3. ComponentName.test.tsx(测试文件)
4. ComponentName.types.ts(类型定义)
每个文件请用```filename标记。
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个React组件开发专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3,
max_tokens=3000
)
content = response.choices[0].message.content
# 解析文件
files = {}
current_file = None
current_content = []
for line in content.split('\n'):
if line.startswith('```'):
if current_file:
files[current_file] = '\n'.join(current_content)
current_file = line[3:].strip()
current_content = []
elif current_file:
current_content.append(line)
if current_file:
files[current_file] = '\n'.join(current_content)
return files
# 使用示例
if __name__ == "__main__":
generator = MultiFileGenerator(api_key="your_api_key_here")
# 生成Flask项目
print("生成Flask项目:")
flask_project = generator.generate_flask_project(
project_name="my_flask_app",
features=["用户认证", "数据库集成", "API文档", "单元测试"]
)
for filename, content in flask_project.items():
print(f"\n文件:{filename}")
print(content[:200] + "..." if len(content) > 200 else content)
# 生成React组件
print("\n\n生成React组件:")
react_component = generator.generate_react_component(
component_name="Button",
props=["text", "variant", "size", "onClick"]
)
for filename, content in react_component.items():
print(f"\n文件:{filename}")
print(content[:200] + "..." if len(content) > 200 else content)
3. 代码优化¶
3.1 性能优化¶
代码示例 - 性能优化器:
Python
import openai
class PerformanceOptimizer:
"""性能优化器"""
def __init__(self, api_key: str):
self.client = openai.OpenAI(api_key=api_key)
def optimize_algorithm(self, code: str,
language: str = "python") -> str:
"""
优化算法
Args:
code: 待优化的代码
language: 编程语言
"""
prompt = f"""请优化以下{language}代码的性能:
```{language}
{code}
```
请提供:
1. 性能问题分析
2. 优化方案说明
3. 优化后的代码
4. 性能提升预期
5. 时间复杂度和空间复杂度对比
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个性能优化专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
def optimize_database_queries(self, code: str) -> str:
"""
优化数据库查询
Args:
code: 包含数据库查询的代码
"""
prompt = f"""请优化以下代码中的数据库查询:
````python
{code}
````
请提供:
1. 查询性能问题分析
2. 优化方案说明
3. 优化后的代码
4. 索引建议
5. 性能提升预期
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个数据库优化专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
# 使用示例
if __name__ == "__main__":
optimizer = PerformanceOptimizer(api_key="your_api_key_here")
# 示例代码
code = """
def find_duplicates(items):
duplicates = []
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]:
duplicates.append(items[i])
return duplicates
def process_large_list(data):
results = []
for item in data:
processed = item * 2
results.append(processed)
return results
"""
# 优化算法
print("算法优化:")
optimization = optimizer.optimize_algorithm(code, "python")
print(optimization)
3.2 代码质量¶
代码示例 - 代码质量改进:
Python
import openai
class QualityImprover:
"""代码质量改进器"""
def __init__(self, api_key: str):
self.client = openai.OpenAI(api_key=api_key)
def improve_readability(self, code: str,
language: str = "python") -> str:
"""
提高可读性
Args:
code: 待改进的代码
language: 编程语言
"""
prompt = f"""请提高以下{language}代码的可读性:
```{language}
{code}
```
请提供:
1. 可读性问题分析
2. 改进方案说明
3. 改进后的代码
4. 改进点说明
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个代码质量专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
def improve_maintainability(self, code: str,
language: str = "python") -> str:
"""
提高可维护性
Args:
code: 待改进的代码
language: 编程语言
"""
prompt = f"""请提高以下{language}代码的可维护性:
```{language}
{code}
```
请提供:
1. 可维护性问题分析
2. 重构建议
3. 改进后的代码
4. 设计模式应用建议
"""
response = self.client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个代码重构专家。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return response.choices[0].message.content
# 使用示例
if __name__ == "__main__":
improver = QualityImprover(api_key="your_api_key_here")
# 示例代码
code = """
def process_data(data):
r = []
for i in range(len(data)):
if data[i] > 0:
x = data[i] * 2
r.append(x)
return r
def calculate(a,b,c):
d = a + b
e = d * c
return e
"""
# 提高可读性
print("提高可读性:")
readability = improver.improve_readability(code, "python")
print(readability)
# 提高可维护性
print("\n提高可维护性:")
maintainability = improver.improve_maintainability(code, "python")
print(maintainability)
4. 练习题¶
基础练习¶
- 生成简单函数
- 描述功能需求
- 生成代码
- 验证功能
进阶练习¶
- 生成完整模块
- 设计模块结构
- 生成多个文件
- 编写测试用例
5. 最佳实践¶
✅ 推荐做法¶
- 详细描述
- 清晰的需求描述
- 完整的上下文信息
-
明确的约束条件
-
迭代优化
- 逐步改进提示词
- 测试生成的代码
- 根据结果调整
❌ 避免做法¶
- 模糊描述
- 避免歧义表达
- 提供具体示例
- 明确技术要求
6. 常见问题¶
Q1: 如何生成更准确的代码?¶
A: 提高准确性的方法: - 提供更多上下文:包含相关代码和项目信息 - 明确技术要求:指定框架、库、编码规范 - 分步骤描述:将复杂功能分解为多个步骤
Q2: 如何处理生成的代码错误?¶
A: 处理方法: - 仔细审查:检查语法和逻辑错误 - 运行测试:编写并运行测试用例 - 迭代改进:根据错误信息调整提示词
7. 总结¶
本章深入介绍了代码生成的核心内容,包括:
- 提示词设计:清晰描述、提供上下文
- 代码生成:函数生成、类生成、完整功能
- 代码优化:性能优化、代码质量改进
通过本章的学习,你应该能够高效生成高质量代码了。
8. 下一步¶
继续学习03-代码审查,深入了解代码审查的方法和技巧。


