K00B404 commited on
Commit
6965b32
·
verified ·
1 Parent(s): ed7fce0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import traceback
3
+ from langchain import LLMChain, PromptTemplate
4
+ from langchain.llms import VertexAI
5
+ from libs.logger import logger
6
+ import streamlit as st
7
+ from google.oauth2 import service_account
8
+ from langchain.prompts import ChatPromptTemplate
9
+ import libs.general_utils
10
+
11
+ class VertexAILangChain:
12
+ def __init__(self, project="", location="us-central1", model_name="code-bison", max_tokens=256, temperature:float=0.3, credentials_file_path=None):
13
+ self.project = project
14
+ self.location = location
15
+ self.model_name = model_name
16
+ self.max_tokens = max_tokens
17
+ self.temperature = temperature
18
+ self.credentials_file_path = credentials_file_path
19
+ self.vertexai_llm = None
20
+ self.utils = libs.general_utils.GeneralUtils()
21
+
22
+ def load_model(self, model_name, max_tokens, temperature):
23
+ try:
24
+ logger.info(f"Loading model... with project: {self.project} and location: {self.location}")
25
+ # Set the GOOGLE_APPLICATION_CREDENTIALS environment variable
26
+ credentials = service_account.Credentials.from_service_account_file(self.credentials_file_path)
27
+
28
+ logger.info(f"Trying to set Vertex model with parameters: {model_name or self.model_name}, {max_tokens or self.max_tokens}, {temperature or self.temperature}, {self.location}")
29
+ self.vertexai_llm = VertexAI(
30
+ model_name=model_name or self.model_name,
31
+ max_output_tokens=max_tokens or self.max_tokens,
32
+ temperature=temperature or self.temperature,
33
+ verbose=True,
34
+ location=self.location,
35
+ credentials=credentials,
36
+ )
37
+ logger.info("Vertex model loaded successfully.")
38
+ return True
39
+ except Exception as exception:
40
+ logger.error(f"Error loading Vertex model: {str(exception)}")
41
+ logger.error(traceback.format_exc()) # Add traceback details
42
+ return False
43
+
44
+ def generate_code(self, code_prompt, code_language):
45
+ try:
46
+ # Dynamically construct guidelines based on session state
47
+ guidelines_list = []
48
+ logger.info(f"Generating code with parameters: {code_prompt}, {code_language}")
49
+
50
+ # Check for empty or null code prompt and code language
51
+ if not code_prompt or len(code_prompt) == 0:
52
+ logger.error("Code prompt is empty or null.")
53
+ st.toast("Code prompt is empty or null.", icon="❌")
54
+ return None
55
+
56
+ if st.session_state["coding_guidelines"]["modular_code"]:
57
+ logger.info("Modular code is enabled.")
58
+ guidelines_list.append("- Ensure the method is modular in its approach.")
59
+ if st.session_state["coding_guidelines"]["exception_handling"]:
60
+ logger.info("Exception handling is enabled.")
61
+ guidelines_list.append("- Integrate robust exception handling.")
62
+ if st.session_state["coding_guidelines"]["error_handling"]:
63
+ logger.info("Error handling is enabled.")
64
+ guidelines_list.append("- Add error handling to each module.")
65
+ if st.session_state["coding_guidelines"]["efficient_code"]:
66
+ logger.info("Efficient code is enabled.")
67
+ guidelines_list.append("- Optimize the code to ensure it runs efficiently.")
68
+ if st.session_state["coding_guidelines"]["robust_code"]:
69
+ logger.info("Robust code is enabled.")
70
+ guidelines_list.append("- Ensure the code is robust against potential issues.")
71
+ if st.session_state["coding_guidelines"]["naming_conventions"]:
72
+ logger.info("Naming conventions is enabled.")
73
+ guidelines_list.append("- Follow standard naming conventions.")
74
+
75
+ logger.info("Guidelines: " + str(guidelines_list))
76
+
77
+ # Convert the list to a string
78
+ guidelines = "\n".join(guidelines_list)
79
+
80
+ # Setting Prompt Template.
81
+ input_section = f"Given the input for code: {st.session_state.code_input}" if st.session_state.code_input else "make sure the program doesn't ask for any input from the user"
82
+
83
+ template = f"""
84
+ Task: Design a program {{code_prompt}} in {{code_language}} with the following guidelines and
85
+ make sure the output is printed on the screen.
86
+ And make sure the output contains only the code and nothing else.
87
+ {input_section}
88
+
89
+ Guidelines:
90
+ {guidelines}
91
+ """
92
+
93
+ prompt = PromptTemplate(template=template,input_variables=["code_prompt", "code_language"])
94
+ formatted_prompt = prompt.format(code_prompt=code_prompt, code_language=code_language)
95
+ logger.info(f"Formatted prompt: {formatted_prompt}")
96
+
97
+ logger.info("Setting up LLMChain...")
98
+ llm_chain = LLMChain(prompt=prompt, llm=self.vertexai_llm)
99
+ logger.info("LLMChain setup successfully.")
100
+
101
+ # Pass the required inputs as a dictionary to the chain
102
+ logger.info("Running LLMChain...")
103
+ response = llm_chain.run({"code_prompt": code_prompt, "code_language": code_language})
104
+ if response or len(response) > 0:
105
+ logger.info(f"Code generated successfully: {response}")
106
+
107
+ # Extract text inside code block
108
+ if response.startswith("```") or response.endswith("```"):
109
+ try:
110
+ generated_code = re.search('```(.*)```', response, re.DOTALL).group(1)
111
+ except AttributeError:
112
+ generated_code = response
113
+ else:
114
+ st.toast(f"Error extracting code", icon="❌")
115
+ return response
116
+
117
+ if generated_code:
118
+ # Skip the language name in the first line.
119
+ response = generated_code.split("\n", 1)[1]
120
+ logger.info(f"Code generated successfully: {response}")
121
+ else:
122
+ logger.error(f"Error generating code: {response}")
123
+ st.toast(f"Error generating code: {response}", icon="❌")
124
+ return response
125
+ except Exception as exception:
126
+ stack_trace = traceback.format_exc()
127
+ logger.error(f"Error generating code: {str(exception)} stack trace: {stack_trace}")
128
+ st.toast(f"Error generating code: {str(exception)} stack trace: {stack_trace}", icon="❌")
129
+
130
+ def generate_code_completion(self, code_prompt, code_language):
131
+ try:
132
+ if not code_prompt or len(code_prompt) == 0:
133
+ logger.error("Code prompt is empty or null.")
134
+ st.error("Code generateration cannot be performed as the code prompt is empty or null.")
135
+ return None
136
+
137
+ logger.info(f"Generating code completion with parameters: {code_prompt}, {code_language}")
138
+ template = f"Complete the following {{code_language}} code: {{code_prompt}}"
139
+ prompt_obj = PromptTemplate(template=template, input_variables=["code_language", "code_prompt"])
140
+
141
+ max_tokens = st.session_state["vertexai"]["max_tokens"]
142
+ temprature = st.session_state["vertexai"]["temperature"]
143
+
144
+ # Check the maximum number of tokens of Gecko model i.e 65
145
+ if max_tokens > 65:
146
+ max_tokens = 65
147
+ logger.info(f"Maximum number of tokens for Model Gecko can't exceed 65. Setting max_tokens to 65.")
148
+ st.toast(f"Maximum number of tokens for Model Gecko can't exceed 65. Setting max_tokens to 65.", icon="⚠️")
149
+
150
+ self.model_name = "code-gecko" # Define the code completion model name.
151
+ self.llm = VertexAI(model_name=self.model_name,max_output_tokens=max_tokens, temperature=temprature)
152
+ logger.info(f"Initialized VertexAI with model: {self.model_name}")
153
+ llm_chain = LLMChain(prompt=prompt_obj, llm=self.llm)
154
+ response = llm_chain.run({"code_prompt": code_prompt, "code_language": code_language})
155
+
156
+ if response:
157
+ logger.info(f"Code completion generated successfully: {response}")
158
+ return response
159
+ else:
160
+ logger.warning("No response received from LLMChain.")
161
+ return None
162
+ except Exception as e:
163
+ logger.error(f"Error generating code completion: {str(e)}")
164
+ raise
165
+
166
+ def set_temperature(self, temperature):
167
+ self.temperature = temperature
168
+ self.vertexai_llm.temperature = temperature
169
+ # call load_model to reload the model with the new temperature and rest values should be same
170
+ self.load_model(self.model_name, self.max_tokens, self.temperature)
171
+
172
+ def set_max_tokens(self, max_tokens):
173
+ self.max_tokens = max_tokens
174
+ self.vertexai_llm.max_output_tokens = max_tokens
175
+ # call load_model to reload the model with the new max_output_tokens and rest values should be same
176
+ self.load_model(self.model_name, self.max_tokens, self.temperature)
177
+
178
+ def set_model_name(self, model_name):
179
+ self.model_name = model_name
180
+ # call load_model to reload the model with the new model_name and rest values should be same
181
+ self.load_model(self.model_name, self.max_tokens, self.temperature)