| 
 | 1 | + | 
 | 2 | +import traceback  | 
 | 3 | +import google.generativeai as genai  | 
 | 4 | +from dotenv import load_dotenv  | 
 | 5 | +from libs.logger import logger  | 
 | 6 | +import streamlit as st  | 
 | 7 | + | 
 | 8 | +class GeminiAI:  | 
 | 9 | + def __init__(self, api_key, model="gemini-pro", temperature=0.1, max_output_tokens=2048,mode="balanced"):  | 
 | 10 | + self.api_key = api_key  | 
 | 11 | + self.model = model  | 
 | 12 | + self.temperature = temperature  | 
 | 13 | + self.max_output_tokens = max_output_tokens  | 
 | 14 | + self.mode = mode  | 
 | 15 | + self.top_k = 20  | 
 | 16 | + self.top_p = 0.85  | 
 | 17 | + self._configure()  | 
 | 18 | + | 
 | 19 | + # Dynamically construct guidelines based on session state  | 
 | 20 | + self.guidelines_list = []  | 
 | 21 | + | 
 | 22 | + if st.session_state["coding_guidelines"]["modular_code"]:  | 
 | 23 | + self.guidelines_list.append("- Ensure the method is modular in its approach.")  | 
 | 24 | + if st.session_state["coding_guidelines"]["exception_handling"]:  | 
 | 25 | + self.guidelines_list.append("- Integrate robust exception handling.")  | 
 | 26 | + if st.session_state["coding_guidelines"]["error_handling"]:  | 
 | 27 | + self.guidelines_list.append("- Add error handling to each module.")  | 
 | 28 | + if st.session_state["coding_guidelines"]["efficient_code"]:  | 
 | 29 | + self.guidelines_list.append("- Optimize the code to ensure it runs efficiently.")  | 
 | 30 | + if st.session_state["coding_guidelines"]["robust_code"]:  | 
 | 31 | + self.guidelines_list.append("- Ensure the code is robust against potential issues.")  | 
 | 32 | + if st.session_state["coding_guidelines"]["naming_conventions"]:  | 
 | 33 | + self.guidelines_list.append("- Follow standard naming conventions.")  | 
 | 34 | + | 
 | 35 | + # Convert the list to a string  | 
 | 36 | + self.guidelines = "\n".join(self.guidelines_list)  | 
 | 37 | +   | 
 | 38 | +   | 
 | 39 | + def _configure(self):  | 
 | 40 | + try:  | 
 | 41 | + logger.info("Configuring Gemini AI Pro...")  | 
 | 42 | + genai.configure(api_key=self.api_key)  | 
 | 43 | + self.generation_config = {  | 
 | 44 | + "temperature": self.temperature,  | 
 | 45 | + "top_p": self.top_p,  | 
 | 46 | + "top_k": self.top_k,  | 
 | 47 | + "max_output_tokens": self.max_output_tokens  | 
 | 48 | + }  | 
 | 49 | + self.model = genai.GenerativeModel(model_name=self.model,generation_config=self.generation_config)  | 
 | 50 | + logger.info("Gemini AI Pro configured successfully.")  | 
 | 51 | + except Exception as exception:  | 
 | 52 | + logger.error(f"Error configuring Gemini AI Pro: {str(exception)}")  | 
 | 53 | + traceback.print_exc()  | 
 | 54 | + | 
 | 55 | + def _extract_code(self, code):  | 
 | 56 | + """  | 
 | 57 | + Extracts the code from the provided string.  | 
 | 58 | + If the string contains '```', it extracts the code between them.  | 
 | 59 | + Otherwise, it returns the original string.  | 
 | 60 | + """  | 
 | 61 | + try:  | 
 | 62 | + if '```' in code:  | 
 | 63 | + start = code.find('```') + len('```\n')  | 
 | 64 | + end = code.find('```', start)  | 
 | 65 | + # Skip the first line after ```  | 
 | 66 | + start = code.find('\n', start) + 1  | 
 | 67 | + extracted_code = code[start:end]  | 
 | 68 | + logger.info("Code extracted successfully.")  | 
 | 69 | + return extracted_code  | 
 | 70 | + else:  | 
 | 71 | + logger.info("No special characters found in the code. Returning the original code.")  | 
 | 72 | + return code  | 
 | 73 | + except Exception as exception:  | 
 | 74 | + logger.error(f"Error occurred while extracting code: {exception}")  | 
 | 75 | + return None  | 
 | 76 | +   | 
 | 77 | + def generate_code(self, code_prompt,code_language):  | 
 | 78 | + """  | 
 | 79 | + Function to generate text using the Gemini API.  | 
 | 80 | + """  | 
 | 81 | + try:  | 
 | 82 | + # Define top_k and top_p based on the mode  | 
 | 83 | + if self.mode == "precise":  | 
 | 84 | + top_k = 40  | 
 | 85 | + top_p = 0.95  | 
 | 86 | + self.temprature = 0  | 
 | 87 | + elif self.mode == "balanced":  | 
 | 88 | + top_k = 20  | 
 | 89 | + top_p = 0.85  | 
 | 90 | + self.temprature = 0.3  | 
 | 91 | + elif self.mode == "creative":  | 
 | 92 | + top_k = 10  | 
 | 93 | + top_p = 0.75  | 
 | 94 | + self.temprature = 1  | 
 | 95 | + else:  | 
 | 96 | + raise ValueError("Invalid mode. Choose from 'precise', 'balanced', 'creative'.")  | 
 | 97 | + | 
 | 98 | + logger.info(f"Generating code with mode: {self.mode}, top_k: {top_k}, top_p: {top_p}")  | 
 | 99 | + | 
 | 100 | +   | 
 | 101 | + # check for valid prompt and language  | 
 | 102 | + if not code_prompt or len(code_prompt) == 0:  | 
 | 103 | + st.toast("Error in code generation: Please enter a valid prompt.", icon="❌")  | 
 | 104 | + logger.error("Error in code generation: Please enter a valid prompt.")  | 
 | 105 | + return  | 
 | 106 | +   | 
 | 107 | + logger.info(f"Generating code for prompt: {code_prompt} in language: {code_language}")  | 
 | 108 | + if code_prompt and len(code_prompt) > 0 and code_language and len(code_language) > 0:  | 
 | 109 | + logger.info(f"Generating code for prompt: {code_prompt} in language: {code_language}")  | 
 | 110 | +   | 
 | 111 | + # Plain and Simple Coding Task Prompt  | 
 | 112 | + prompt = f"""  | 
 | 113 | + Task: You're an experienced developer. Your mission is to create a program for {code_prompt} in {code_language} that takes {st.session_state.code_input} as input.  | 
 | 114 | +
  | 
 | 115 | + Your goal is clear: Craft a solution that showcases your expertise as a coder and problem solver.  | 
 | 116 | +
  | 
 | 117 | + Ensure that the program's output contains only the code you've written, with no extraneous information.  | 
 | 118 | +
  | 
 | 119 | + Show your skills and solve this challenge with confidence!  | 
 | 120 | +   | 
 | 121 | + And follow the proper coding guidelines and dont add comment unless instructed to do so.  | 
 | 122 | + {self.guidelines}  | 
 | 123 | + """  | 
 | 124 | +   | 
 | 125 | + gemini_completion = self.model.generate_content(prompt)  | 
 | 126 | + logger.info("Text generation completed successfully.")  | 
 | 127 | +   | 
 | 128 | + code = None  | 
 | 129 | + if gemini_completion:  | 
 | 130 | + # extract the code from the gemini completion  | 
 | 131 | + code = gemini_completion.text  | 
 | 132 | + logger.info(f"GeminiAI coder is initialized.")  | 
 | 133 | + logger.info(f"Generated code: {code[:100]}...")  | 
 | 134 | +   | 
 | 135 | + if gemini_completion:  | 
 | 136 | + # Extracted code from the gemini completion  | 
 | 137 | + extracted_code = self._extract_code(code)  | 
 | 138 | +   | 
 | 139 | + # Check if the code or extracted code is not empty or null  | 
 | 140 | + if not code or not extracted_code:  | 
 | 141 | + raise Exception("Error: Generated code or extracted code is empty or null.")  | 
 | 142 | +   | 
 | 143 | + return extracted_code  | 
 | 144 | + else:  | 
 | 145 | + raise Exception("Error in code generation: Please enter a valid code.")  | 
 | 146 | +   | 
 | 147 | + except Exception as exception:  | 
 | 148 | + st.toast(f"Error in code generation: {exception}", icon="❌")  | 
 | 149 | + logger.error(f"Error in code generation: {traceback.format_exc()}")  | 
0 commit comments