| 14 | PROMPT = open("src/agents/coder/prompt.jinja2", "r").read().strip() |
| 15 | |
| 16 | class Coder: |
| 17 | def __init__(self, base_model: str): |
| 18 | config = Config() |
| 19 | self.project_dir = config.get_projects_dir() |
| 20 | self.logger = Logger() |
| 21 | self.llm = LLM(model_id=base_model) |
| 22 | |
| 23 | def render( |
| 24 | self, step_by_step_plan: str, user_context: str, search_results: dict |
| 25 | ) -> str: |
| 26 | env = Environment(loader=BaseLoader()) |
| 27 | template = env.from_string(PROMPT) |
| 28 | return template.render( |
| 29 | step_by_step_plan=step_by_step_plan, |
| 30 | user_context=user_context, |
| 31 | search_results=search_results, |
| 32 | ) |
| 33 | |
| 34 | def validate_response(self, response: str) -> Union[List[Dict[str, str]], bool]: |
| 35 | response = response.strip() |
| 36 | |
| 37 | self.logger.debug(f"Response from the model: {response}") |
| 38 | |
| 39 | if "~~~" not in response: |
| 40 | return False |
| 41 | |
| 42 | response = response.split("~~~", 1)[1] |
| 43 | response = response[:response.rfind("~~~")] |
| 44 | response = response.strip() |
| 45 | |
| 46 | result = [] |
| 47 | current_file = None |
| 48 | current_code = [] |
| 49 | code_block = False |
| 50 | |
| 51 | for line in response.split("\n"): |
| 52 | if line.startswith("File: "): |
| 53 | if current_file and current_code: |
| 54 | result.append({"file": current_file, "code": "\n".join(current_code)}) |
| 55 | current_file = line.split(":")[1].strip() |
| 56 | current_code = [] |
| 57 | code_block = False |
| 58 | elif line.startswith("```"): |
| 59 | code_block = not code_block |
| 60 | else: |
| 61 | current_code.append(line) |
| 62 | |
| 63 | if current_file and current_code: |
| 64 | result.append({"file": current_file, "code": "\n".join(current_code)}) |
| 65 | |
| 66 | return result |
| 67 | |
| 68 | def save_code_to_project(self, response: List[Dict[str, str]], project_name: str): |
| 69 | file_path_dir = None |
| 70 | project_name = project_name.lower().replace(" ", "-") |
| 71 | |
| 72 | for file in response: |
| 73 | file_path = os.path.join(self.project_dir, project_name, file['file']) |