|
| 1 | +import os |
| 2 | +import re |
| 3 | +from typing import List, Optional |
| 4 | + |
| 5 | +import structlog |
| 6 | +from litellm.types.llms.openai import ChatCompletionRequest |
| 7 | + |
| 8 | +from codegate.pipeline.base import CodeSnippet, PipelineContext, PipelineResult, PipelineStep |
| 9 | + |
| 10 | +CODE_BLOCK_PATTERN = re.compile( |
| 11 | + r"```(?:(?P<language>\w+)\s+)?(?P<filename>[^\s\(]+)?(?:\s*\((?P<lineinfo>[^)]+)\))?\n(?P<content>(?:.|\n)*?)```" |
| 12 | +) |
| 13 | + |
| 14 | +logger = structlog.get_logger("codegate") |
| 15 | + |
| 16 | +def ecosystem_from_filepath(filepath: str) -> Optional[str]: |
| 17 | + """ |
| 18 | + Determine language from filepath. |
| 19 | +
|
| 20 | + Args: |
| 21 | + filepath: Path to the file |
| 22 | +
|
| 23 | + Returns: |
| 24 | + Determined language based on file extension |
| 25 | + """ |
| 26 | + # Implement file extension to language mapping |
| 27 | + extension_mapping = { |
| 28 | + ".py": "python", |
| 29 | + ".js": "javascript", |
| 30 | + ".ts": "typescript", |
| 31 | + ".tsx": "typescript", |
| 32 | + ".go": "go", |
| 33 | + ".rs": "rust", |
| 34 | + ".java": "java", |
| 35 | + } |
| 36 | + |
| 37 | + # Get the file extension |
| 38 | + ext = os.path.splitext(filepath)[1].lower() |
| 39 | + return extension_mapping.get(ext, None) |
| 40 | + |
| 41 | + |
| 42 | +def ecosystem_from_message(message: str) -> Optional[str]: |
| 43 | + """ |
| 44 | + Determine language from message. |
| 45 | +
|
| 46 | + Args: |
| 47 | + message: The language from the message. Some extensions send a different |
| 48 | + format where the language is present in the snippet, |
| 49 | + e.g. "py /path/to/file (lineFrom-lineTo)" |
| 50 | +
|
| 51 | + Returns: |
| 52 | + Determined language based on message content |
| 53 | + """ |
| 54 | + language_mapping = { |
| 55 | + "py": "python", |
| 56 | + "js": "javascript", |
| 57 | + "ts": "typescript", |
| 58 | + "tsx": "typescript", |
| 59 | + "go": "go", |
| 60 | + } |
| 61 | + return language_mapping.get(message, None) |
| 62 | + |
| 63 | + |
| 64 | +def extract_snippets(message: str) -> List[CodeSnippet]: |
| 65 | + """ |
| 66 | + Extract code snippets from a message. |
| 67 | +
|
| 68 | + Args: |
| 69 | + message: Input text containing code snippets |
| 70 | +
|
| 71 | + Returns: |
| 72 | + List of extracted code snippets |
| 73 | + """ |
| 74 | + # Regular expression to find code blocks |
| 75 | + |
| 76 | + snippets: List[CodeSnippet] = [] |
| 77 | + |
| 78 | + # Find all code block matches |
| 79 | + for match in CODE_BLOCK_PATTERN.finditer(message): |
| 80 | + filename = match.group("filename") |
| 81 | + content = match.group("content") |
| 82 | + matched_language = match.group("language") |
| 83 | + |
| 84 | + # Determine language |
| 85 | + lang = None |
| 86 | + if matched_language: |
| 87 | + lang = ecosystem_from_message(matched_language.strip()) |
| 88 | + if lang is None and filename: |
| 89 | + filename = filename.strip() |
| 90 | + # Determine language from the filename |
| 91 | + lang = ecosystem_from_filepath(filename) |
| 92 | + |
| 93 | + snippets.append(CodeSnippet(filepath=filename, code=content, language=lang)) |
| 94 | + |
| 95 | + return snippets |
| 96 | + |
| 97 | + |
| 98 | +class CodeSnippetExtractor(PipelineStep): |
| 99 | + """ |
| 100 | + Pipeline step that merely extracts code snippets from the user message. |
| 101 | + """ |
| 102 | + |
| 103 | + def __init__(self): |
| 104 | + """Initialize the CodeSnippetExtractor pipeline step.""" |
| 105 | + super().__init__() |
| 106 | + |
| 107 | + @property |
| 108 | + def name(self) -> str: |
| 109 | + return "code-snippet-extractor" |
| 110 | + |
| 111 | + async def process( |
| 112 | + self, |
| 113 | + request: ChatCompletionRequest, |
| 114 | + context: PipelineContext, |
| 115 | + ) -> PipelineResult: |
| 116 | + last_user_message = self.get_last_user_message(request) |
| 117 | + if not last_user_message: |
| 118 | + return PipelineResult(request=request, context=context) |
| 119 | + msg_content, _ = last_user_message |
| 120 | + snippets = extract_snippets(msg_content) |
| 121 | + |
| 122 | + logger.info(f"Extracted {len(snippets)} code snippets from the user message") |
| 123 | + |
| 124 | + if len(snippets) > 0: |
| 125 | + for snippet in snippets: |
| 126 | + logger.debug(f"Code snippet: {snippet}") |
| 127 | + context.add_code_snippet(snippet) |
| 128 | + |
| 129 | + return PipelineResult( |
| 130 | + context=context, |
| 131 | + ) |
0 commit comments