♻️ refactor(generator): update system and user prompts for clarity and consistency

This commit is contained in:
sankalp committed 2025-06-04 13:50:00 +05:45
1 parent b35d97a2f4
commit 7378bc0020
1 file changed
+82 -90
+82 -90
View File
@@ -18,146 +18,138 @@ class CommitGenerator(AIService):
self, diff: str, temperature: Optional[float] = None self, diff: str, temperature: Optional[float] = None
) -> str: ) -> str:
"""Generate a commit message from a diff.""" """Generate a commit message from a diff."""
system_prompt = """You are an expert Git assistant trained to write clean, conventional commit messages with optional bodies. system_prompt = """You are an expert Git assistant trained to write highly effective and conventional commit messages.
Follow this format: Your task is to analyze the provided code diff and generate a commit message in the following format:
<type>(<scope>): <short summary> Format: type(scope): description
[blank line]
<detailed body explaining the change>
Where:
- type: One of feat, fix, docs, style, refactor, test, chore - type: One of feat, fix, docs, style, refactor, test, chore
- scope: Optional but recommended (e.g. auth, api, db) - scope: Optional but encouraged; represents the part of the codebase affected (e.g. auth, api, db, ui)
- summary: A short, one-line description of the change - description: A short, clear explanation of the change
- body: (Optional) Add context, rationale, and details about the change
Each type must have an emoji: Each type has an emoji prefix:
- ✨ feat: New feature - ✨ feat: New feature
- 🐛 fix: Bug fix - 🐛 fix: Bug fix
- 📚 docs: Documentation - 📚 docs: Documentation-only change
- 💅 style: Formatting (no code logic) - 💅 style: Code formatting (no logic change)
- ♻️ refactor: Code restructure without behavior change - ♻️ refactor: Code changes without affecting behavior
- ✅ test: Tests added or modified - ✅ test: Test additions/changes
- 🔧 chore: Maintenance, configs, build scripts, etc. - 🔧 chore: Maintenance, build, or config tasks
Rules: Strict rules:
- Subject must be a single line, max ~72 characters - Write the entire message in a single line
- Use imperative mood: “add”, not “added” - Use imperative mood (e.g. "add" not "added")
- Don’t include file paths, issue numbers, or PR references - No file paths, no periods at the end
- Use body only if extra context is helpful (start with a verb or full sentence) - Avoid generic or vague descriptions
- Don’t include explanations about what can be written - Don't mention pull requests, issues, or reviewers
- DO NOT include “commit message” or meta-language - Focus on the why and impact of the change, not just the what
Examples: Examples:
✨ feat(auth): add OAuth2 login support - ✨ feat(auth): add OAuth2 login support
- 🐛 fix(api): return correct HTTP status for invalid input
- ♻️ refactor(db): simplify user query joins
Adds full OAuth2 login flow using access and refresh tokens. Output ONLY the commit message. Do not include any comments or explanations."""
This improves external authentication and reduces local user management.
"""
user_prompt = f"""Generate a conventional commit message for the following code changes: user_prompt = f"""Generate a single-line conventional commit message for the following code changes:
{diff} {diff}
- Include a single-line subject Identify the most relevant type, a concise scope, and the purpose of the change.
- Add a body section if useful, separated by a blank line Output ONLY the commit message in the correct format (with emoji)."""
- Output must match the conventional commit format
- Use the correct emoji prefix
"""
message = self.generate_completion( message = self.generate_completion(
system_prompt, user_prompt, temperature=temperature system_prompt, user_prompt, temperature=temperature
) )
# Clean and extract subject and optional body lines = [line.strip() for line in message.split("\n") if line.strip()]
lines = [line.rstrip() for line in message.splitlines()]
subject = ""
body_lines = []
for i, line in enumerate(lines): for line in lines:
if not subject and line and ":" in line: if any(
subject = line.strip() skip in line.lower()
for skip in [
"based on",
"changes in",
"can be written",
"commit message",
"following",
"these changes",
"the changes",
]
):
continue continue
if subject: if line.startswith("`") or line.startswith("/") or ":" in line:
body_lines = lines[i:] continue
break message = line
break
else:
message = lines[0] if lines else "🔧 chore: update code"
if not subject:
subject = "🔧 chore: update code"
# Ensure emoji in the subject
if not any( if not any(
emoji in subject for emoji in ["✨", "🐛", "📚", "💅", "♻️", "✅", "🔧"] emoji in message for emoji in ["✨", "🐛", "📚", "💅", "♻️", "✅", "🔧"]
): ):
if subject.startswith("feat"): if message.startswith("feat"):
subject = "✨ " + subject message = "✨ " + message
elif subject.startswith("fix"): elif message.startswith("fix"):
subject = "🐛 " + subject message = "🐛 " + message
elif subject.startswith("docs"): elif message.startswith("docs"):
subject = "📚 " + subject message = "📚 " + message
elif subject.startswith("style"): elif message.startswith("style"):
subject = "💅 " + subject message = "💅 " + message
elif subject.startswith("refactor"): elif message.startswith("refactor"):
subject = "♻️ " + subject message = "♻️ " + message
elif subject.startswith("test"): elif message.startswith("test"):
subject = "✅ " + subject message = "✅ " + message
elif subject.startswith("chore"): elif message.startswith("chore"):
subject = "🔧 " + subject message = "🔧 " + message
else: else:
subject = "🔧 " + subject message = "🔧 " + message # fallback
# Final formatted message
message = subject
if body_lines:
body = "\n".join(line.strip() for line in body_lines if line.strip())
if body:
message += "\n\n" + body
return message return message
def generate_batch_messages( def generate_batch_messages(
self, diffs: Dict[str, str], temperature: Optional[float] = None self, diffs: Dict[str, str], temperature: Optional[float] = None
) -> Dict[str, str]: ) -> Dict[str, str]:
"""Generate commit messages for multiple files. """Generate commit messages for multiple files."""
Args:
diffs: Dictionary mapping file paths to their diffs
temperature: Optional temperature for AI generation
Returns:
Dictionary mapping file paths to their commit messages
"""
# If only one file, use the single file method
if len(diffs) == 1: if len(diffs) == 1:
file_path, diff = next(iter(diffs.items())) file_path, diff = next(iter(diffs.items()))
return {file_path: self.generate_commit_message(diff, temperature)} return {file_path: self.generate_commit_message(diff, temperature)}
# Combine all diffs with clear file separators
combined_diff = "\n\n".join( combined_diff = "\n\n".join(
f"Changes in {file_path}:\n{diff}" for file_path, diff in diffs.items() f"Changes in {file_path}:\n{diff}" for file_path, diff in diffs.items()
) )
# Generate a single commit message for all changes
message = self.generate_commit_message(combined_diff, temperature) message = self.generate_commit_message(combined_diff, temperature)
# Return the same message for all files
return {file_path: message for file_path in diffs.keys()} return {file_path: message for file_path in diffs.keys()}
def generate_changelog( def generate_changelog(
self, commits: List[str], version: str, temperature: Optional[float] = None self, commits: List[str], version: str, temperature: Optional[float] = None
) -> str: ) -> str:
"""Generate a changelog from a list of commits.""" """Generate a changelog from a list of commits."""
system_prompt = """You are a helpful AI that generates changelogs. system_prompt = """You are a professional release manager generating changelogs from commit messages.
Follow these rules: Follow these rules:
- Group changes by type (Added, Changed, Fixed, etc.) - Group entries under clear sections: Added, Changed, Fixed, Removed, Refactored, Tests, Chore, etc.
- Keep descriptions concise but informative - Use past tense (e.g. "Added login flow", not "Add login flow")
- Use past tense - Write concise but informative summaries
- Start each entry with a verb - Each bullet point should start with a verb (e.g. "Fixed", "Added")
""" - Skip commit types like "chore" unless they are user-relevant
- Format sections like this:
## [version]
### Added
- Added support for OAuth2 authentication
### Fixed
- Fixed issue where empty input crashed the API
Do NOT include raw commit messages. Use the commit messages as input and convert them into user-facing changelog entries."""
user_prompt = ( user_prompt = (
f"Generate a changelog for version {version} with these commits:\n\n" f"Generate a clean and structured changelog for version {
version
} using these commits:\n\n"
+ "\n".join(commits) + "\n".join(commits)
) )