Spaces:
Runtime error
Runtime error
Update supplemental.py
Browse files- supplemental.py +200 -168
supplemental.py
CHANGED
@@ -1,200 +1,232 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
def
|
19 |
-
# Placeholder for action selection logic
|
20 |
-
return {"tool": "Code Generation", "arguments": {"language": "python", "code": "print('Hello, World!')"}}
|
21 |
-
|
22 |
-
def observe(self, observation):
|
23 |
-
pass
|
24 |
-
|
25 |
-
def learn(self, data):
|
26 |
-
pass
|
27 |
-
|
28 |
-
def __str__(self):
|
29 |
-
return f"""Agent: {self.name} (Role: {self.role})"""
|
30 |
-
|
31 |
-
class Tool:
|
32 |
-
def __init__(self, name, description):
|
33 |
self.name = name
|
34 |
self.description = description
|
35 |
|
36 |
-
|
37 |
-
|
|
|
38 |
|
39 |
-
class
|
40 |
def __init__(self):
|
41 |
-
super().__init__("
|
42 |
|
43 |
-
def
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
47 |
|
48 |
-
class
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
def __init__(self):
|
50 |
-
super().__init__("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
-
def
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
self.tokenizer = AutoTokenizer.from_pretrained("bigcode/starcoder")
|
60 |
-
self.model = AutoModelForCausalLM.from_pretrained("bigcode/starcoder")
|
61 |
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
return {"output": self.tokenizer.decode(outputs[0], skip_special_tokens=True)}
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
-
def
|
73 |
-
|
74 |
-
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
|
80 |
-
|
81 |
-
|
82 |
-
return
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
95 |
|
96 |
-
|
97 |
-
|
98 |
-
return
|
99 |
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
|
108 |
-
class
|
109 |
-
|
110 |
-
|
|
|
111 |
|
112 |
-
|
113 |
-
|
114 |
-
return
|
115 |
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
|
124 |
-
|
125 |
-
|
126 |
-
|
|
|
|
|
127 |
|
128 |
-
|
129 |
-
|
130 |
-
return
|
131 |
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
|
146 |
-
|
147 |
-
return self.text_gen_tool.run({"prompt": prompt})
|
148 |
-
|
149 |
-
def create_agent_prompt(self) -> str:
|
150 |
-
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
|
151 |
-
agent_prompt = f"""
|
152 |
-
As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
|
153 |
-
{skills_str}
|
154 |
-
I am confident that I can leverage my expertise to assist you in developing and deploying cutting-edge web applications. Please feel free to ask any questions or present any challenges you may encounter.
|
155 |
"""
|
156 |
-
return
|
157 |
-
|
158 |
-
def autonomous_build(self, chat_history: List[tuple[str, str]], workspace_projects: Dict[str, Dict],
|
159 |
-
project_name: str, selected_model: str, hf_token: str) -> tuple[str, str]:
|
160 |
-
summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
161 |
-
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
162 |
-
return summary, next_step
|
163 |
-
|
164 |
-
def deploy_built_space_to_hf(self, project_name: str) -> str:
|
165 |
-
# Assuming you have a function that generates the space content
|
166 |
-
space_content = generate_space_content(project_name)
|
167 |
-
repository = self._hf_api.create_repo(
|
168 |
-
repo_id=project_name,
|
169 |
-
private=True,
|
170 |
-
token=hf_token,
|
171 |
-
exist_ok=True,
|
172 |
-
space_sdk="streamlit"
|
173 |
-
)
|
174 |
-
self._hf_api.upload_file(
|
175 |
-
path_or_fileobj=space_content,
|
176 |
-
path_in_repo="app.py",
|
177 |
-
repo_id=project_name,
|
178 |
-
repo_type="space",
|
179 |
-
token=hf_token
|
180 |
-
)
|
181 |
-
return repository.name
|
182 |
-
|
183 |
-
def has_valid_hf_token(self) -> bool:
|
184 |
-
return self._hf_api.whoami(token=hf_token) is not None
|
185 |
-
|
186 |
-
def generate_space_content(project_name: str) -> str:
|
187 |
-
# Logic to generate the Streamlit app content based on project_name
|
188 |
-
return f"""
|
189 |
-
import streamlit as st
|
190 |
-
|
191 |
-
st.title('{project_name}')
|
192 |
-
st.write('Hello, world!')
|
193 |
-
"""
|
194 |
-
|
195 |
-
# Example usage within your Streamlit app
|
196 |
-
if __name__ == "__main__":
|
197 |
-
llm = "bigcode/starcoder"
|
198 |
-
agent = EnhancedAIAgent(name="AI Assistant", description="Expert in code generation", skills=["Python", "Streamlit"], llm=llm)
|
199 |
-
response = agent.generate_agent_response("How can I help you today?")
|
200 |
-
print(response)
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
from typing import List, Dict, Tuple, Optional, Any
|
5 |
+
from dataclasses import dataclass
|
6 |
+
from abc import ABC, abstractmethod
|
7 |
+
from huggingface_hub import HfApi, InferenceApi
|
8 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
9 |
+
|
10 |
+
@dataclass
|
11 |
+
class ProjectConfig:
|
12 |
+
name: str
|
13 |
+
description: str
|
14 |
+
technologies: List[str]
|
15 |
+
structure: Dict[str, List[str]]
|
16 |
+
|
17 |
+
class WebDevelopmentTool(ABC):
|
18 |
+
def __init__(self, name: str, description: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
self.name = name
|
20 |
self.description = description
|
21 |
|
22 |
+
@abstractmethod
|
23 |
+
def generate_code(self, *args, **kwargs):
|
24 |
+
pass
|
25 |
|
26 |
+
class HTMLGenerator(WebDevelopmentTool):
|
27 |
def __init__(self):
|
28 |
+
super().__init__("HTML Generator", "Generates HTML code for web pages")
|
29 |
|
30 |
+
def generate_code(self, structure: Dict[str, Any]) -> str:
|
31 |
+
html = "<html><body>"
|
32 |
+
for tag, content in structure.items():
|
33 |
+
html += f"<{tag}>{content}</{tag}>"
|
34 |
+
html += "</body></html>"
|
35 |
+
return html
|
36 |
|
37 |
+
class CSSGenerator(WebDevelopmentTool):
|
38 |
+
def __init__(self):
|
39 |
+
super().__init__("CSS Generator", "Generates CSS code for styling web pages")
|
40 |
+
|
41 |
+
def generate_code(self, styles: Dict[str, Dict[str, str]]) -> str:
|
42 |
+
css = ""
|
43 |
+
for selector, properties in styles.items():
|
44 |
+
css += f"{selector} {{\n"
|
45 |
+
for prop, value in properties.items():
|
46 |
+
css += f" {prop}: {value};\n"
|
47 |
+
css += "}\n"
|
48 |
+
return css
|
49 |
+
|
50 |
+
class JavaScriptGenerator(WebDevelopmentTool):
|
51 |
def __init__(self):
|
52 |
+
super().__init__("JavaScript Generator", "Generates JavaScript code for web functionality")
|
53 |
+
|
54 |
+
def generate_code(self, functions: List[Dict[str, Any]]) -> str:
|
55 |
+
js = ""
|
56 |
+
for func in functions:
|
57 |
+
js += f"function {func['name']}({', '.join(func['params'])}) {{\n"
|
58 |
+
js += f" {func['body']}\n"
|
59 |
+
js += "}\n\n"
|
60 |
+
return js
|
61 |
+
|
62 |
+
class EnhancedAIAgent:
|
63 |
+
def __init__(self, name: str, description: str, skills: List[str], model_name: str):
|
64 |
+
self.name = name
|
65 |
+
self.description = description
|
66 |
+
self.skills = skills
|
67 |
+
self.model_name = model_name
|
68 |
+
self.html_gen_tool = HTMLGenerator()
|
69 |
+
self.css_gen_tool = CSSGenerator()
|
70 |
+
self.js_gen_tool = JavaScriptGenerator()
|
71 |
+
self.hf_api = HfApi()
|
72 |
+
self.inference_api = InferenceApi(repo_id=model_name, token=os.environ.get("HF_API_TOKEN"))
|
73 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
74 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_name)
|
75 |
+
self.text_generation = pipeline("text-generation", model=self.model, tokenizer=self.tokenizer)
|
76 |
+
self.logger = logging.getLogger(__name__)
|
77 |
|
78 |
+
def generate_agent_response(self, prompt: str) -> str:
|
79 |
+
try:
|
80 |
+
response = self.inference_api(prompt)
|
81 |
+
return response[0]['generated_text']
|
82 |
+
except Exception as e:
|
83 |
+
self.logger.error(f"Error generating response: {str(e)}")
|
84 |
+
return f"Error: Unable to generate response. {str(e)}"
|
85 |
+
|
86 |
+
def create_project_structure(self, project_config: ProjectConfig) -> Dict[str, str]:
|
87 |
+
project_files = {}
|
88 |
+
for directory, files in project_config.structure.items():
|
89 |
+
for file in files:
|
90 |
+
file_path = os.path.join(directory, file)
|
91 |
+
if file.endswith('.html'):
|
92 |
+
content = self.html_gen_tool.generate_code({"body": f"<h1>{project_config.name}</h1>"})
|
93 |
+
elif file.endswith('.css'):
|
94 |
+
content = self.css_gen_tool.generate_code({"body": {"font-family": "Arial, sans-serif"}})
|
95 |
+
elif file.endswith('.js'):
|
96 |
+
content = self.js_gen_tool.generate_code([{"name": "init", "params": [], "body": "console.log('Initialized');"}])
|
97 |
+
else:
|
98 |
+
content = f"// TODO: Implement {file}"
|
99 |
+
project_files[file_path] = content
|
100 |
+
return project_files
|
101 |
+
|
102 |
+
def generate_project_config(self, project_description: str) -> ProjectConfig:
|
103 |
+
prompt = f"""
|
104 |
+
Based on the following project description, generate a ProjectConfig object:
|
105 |
+
|
106 |
+
Description: {project_description}
|
107 |
+
|
108 |
+
The ProjectConfig should include:
|
109 |
+
- name: A short, descriptive name for the project
|
110 |
+
- description: A brief summary of the project
|
111 |
+
- technologies: A list of technologies to be used (e.g., ["HTML", "CSS", "JavaScript", "React"])
|
112 |
+
- structure: A dictionary representing the file structure, where keys are directories and values are lists of files
|
113 |
+
|
114 |
+
Respond with a JSON object representing the ProjectConfig.
|
115 |
+
"""
|
116 |
+
response = self.generate_agent_response(prompt)
|
117 |
+
config_dict = json.loads(response)
|
118 |
+
return ProjectConfig(**config_dict)
|
119 |
|
120 |
+
def implement_feature(self, feature_description: str, existing_code: Optional[str] = None) -> str:
|
121 |
+
prompt = f"""
|
122 |
+
Feature to implement: {feature_description}
|
|
|
|
|
123 |
|
124 |
+
Existing code:
|
125 |
+
```
|
126 |
+
{existing_code if existing_code else 'No existing code provided.'}
|
127 |
+
```
|
|
|
128 |
|
129 |
+
Please implement the described feature, modifying the existing code if provided.
|
130 |
+
Respond with only the code, no explanations.
|
131 |
+
"""
|
132 |
+
return self.generate_agent_response(prompt)
|
133 |
+
|
134 |
+
def review_code(self, code: str) -> str:
|
135 |
+
prompt = f"""
|
136 |
+
Please review the following code and provide feedback:
|
137 |
+
|
138 |
+
```
|
139 |
+
{code}
|
140 |
+
```
|
141 |
+
|
142 |
+
Consider the following aspects in your review:
|
143 |
+
1. Code quality and readability
|
144 |
+
2. Potential bugs or errors
|
145 |
+
3. Adherence to best practices
|
146 |
+
4. Suggestions for improvement
|
147 |
+
Provide your feedback in a structured format.
|
148 |
+
"""
|
149 |
+
return self.generate_agent_response(prompt)
|
150 |
|
151 |
+
def optimize_code(self, code: str, optimization_goal: str) -> str:
|
152 |
+
prompt = f"""
|
153 |
+
Please optimize the following code with the goal of improving {optimization_goal}:
|
154 |
|
155 |
+
```
|
156 |
+
{code}
|
157 |
+
```
|
158 |
|
159 |
+
Provide only the optimized code in your response, no explanations.
|
160 |
+
"""
|
161 |
+
return self.generate_agent_response(prompt)
|
162 |
|
163 |
+
def generate_documentation(self, code: str) -> str:
|
164 |
+
prompt = f"""
|
165 |
+
Please generate comprehensive documentation for the following code:
|
166 |
|
167 |
+
```
|
168 |
+
{code}
|
169 |
+
```
|
170 |
|
171 |
+
Include the following in your documentation:
|
172 |
+
1. Overview of the code's purpose
|
173 |
+
2. Description of functions/classes and their parameters
|
174 |
+
3. Usage examples
|
175 |
+
4. Any important notes or considerations
|
176 |
|
177 |
+
Provide the documentation in Markdown format.
|
178 |
+
"""
|
179 |
+
return self.generate_agent_response(prompt)
|
180 |
|
181 |
+
def suggest_tests(self, code: str) -> str:
|
182 |
+
prompt = f"""
|
183 |
+
Please suggest unit tests for the following code:
|
184 |
|
185 |
+
```
|
186 |
+
{code}
|
187 |
+
```
|
188 |
|
189 |
+
For each function or class, provide:
|
190 |
+
1. Test case description
|
191 |
+
2. Input values
|
192 |
+
3. Expected output or behavior
|
193 |
|
194 |
+
Provide the suggestions in a structured format.
|
195 |
+
"""
|
196 |
+
return self.generate_agent_response(prompt)
|
197 |
|
198 |
+
def explain_code(self, code: str) -> str:
|
199 |
+
prompt = f"""
|
200 |
+
Please provide a detailed explanation of the following code:
|
201 |
|
202 |
+
```
|
203 |
+
{code}
|
204 |
+
```
|
205 |
|
206 |
+
Include in your explanation:
|
207 |
+
1. Overall purpose of the code
|
208 |
+
2. Breakdown of each significant part
|
209 |
+
3. How different components interact
|
210 |
+
4. Any notable algorithms or design patterns used
|
211 |
|
212 |
+
Explain in a way that would be understandable to a junior developer.
|
213 |
+
"""
|
214 |
+
return self.generate_agent_response(prompt)
|
215 |
|
216 |
+
def suggest_refactoring(self, code: str) -> str:
|
217 |
+
prompt = f"""
|
218 |
+
Please suggest refactoring improvements for the following code:
|
219 |
|
220 |
+
```
|
221 |
+
{code}
|
222 |
+
```
|
223 |
|
224 |
+
Consider the following in your suggestions:
|
225 |
+
1. Improving code readability
|
226 |
+
2. Enhancing maintainability
|
227 |
+
3. Applying design patterns where appropriate
|
228 |
+
4. Optimizing performance (if applicable)
|
229 |
|
230 |
+
Provide specific suggestions and explain the benefits of each.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
231 |
"""
|
232 |
+
return self.generate_agent_response(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|