nananie143 commited on
Commit
9f0042c
·
verified ·
1 Parent(s): bc0fdfa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +206 -0
app.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
4
+ from langchain.agents import initialize_agent, Tool
5
+ from langchain.chains import LLMChain
6
+ from langchain.prompts import PromptTemplate
7
+ from langchain.llms import HuggingFacePipeline
8
+ import json
9
+ import subprocess
10
+ import os
11
+ import logging
12
+
13
+ # Configure logging
14
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Load the LLM and tokenizer
18
+ MODEL_NAME = "unit-mesh/autodev-coder-deepseek-6.7b-finetunes"
19
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
20
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float16, device_map="auto")
21
+
22
+ # Create a Hugging Face pipeline
23
+ hf_pipeline = pipeline(
24
+ "text-generation",
25
+ model=model,
26
+ tokenizer=tokenizer,
27
+ device=0 if torch.cuda.is_available() else -1,
28
+ max_length=500,
29
+ temperature=0.7,
30
+ )
31
+
32
+ # Wrap the pipeline in a LangChain LLM
33
+ llm = HuggingFacePipeline(pipeline=hf_pipeline)
34
+
35
+ # Define tools for the agents
36
+ tools = [
37
+ Tool(
38
+ name="Code Formatter",
39
+ func=lambda x: subprocess.run(["black", "-"], input=x.encode(), capture_output=True).stdout.decode(),
40
+ description="Formats code using Black.",
41
+ ),
42
+ Tool(
43
+ name="API Generator",
44
+ func=lambda x: json.dumps({"endpoints": {"example": "POST - Example endpoint."}}),
45
+ description="Generates API details from code.",
46
+ ),
47
+ Tool(
48
+ name="Task Decomposer",
49
+ func=lambda x: json.dumps({"tasks": ["Design UI", "Develop Backend", "Test App", "Deploy App"]}),
50
+ description="Breaks down app requirements into smaller tasks.",
51
+ ),
52
+ ]
53
+
54
+ # Define prompt templates
55
+ ui_designer_prompt = PromptTemplate(
56
+ input_variables=["input"],
57
+ template="You are a UI Designer. Your task is: {input}",
58
+ )
59
+
60
+ backend_developer_prompt = PromptTemplate(
61
+ input_variables=["input"],
62
+ template="You are a Backend Developer. Your task is: {input}",
63
+ )
64
+
65
+ qa_engineer_prompt = PromptTemplate(
66
+ input_variables=["input"],
67
+ template="You are a QA Engineer. Your task is: {input}",
68
+ )
69
+
70
+ devops_engineer_prompt = PromptTemplate(
71
+ input_variables=["input"],
72
+ template="You are a DevOps Engineer. Your task is: {input}",
73
+ )
74
+
75
+ # Initialize agents
76
+ ui_designer_agent = initialize_agent(
77
+ tools=tools,
78
+ llm=llm,
79
+ agent="zero-shot-react-description",
80
+ verbose=True,
81
+ )
82
+
83
+ backend_developer_agent = initialize_agent(
84
+ tools=tools,
85
+ llm=llm,
86
+ agent="zero-shot-react-description",
87
+ verbose=True,
88
+ )
89
+
90
+ qa_engineer_agent = initialize_agent(
91
+ tools=tools,
92
+ llm=llm,
93
+ agent="zero-shot-react-description",
94
+ verbose=True,
95
+ )
96
+
97
+ devops_engineer_agent = initialize_agent(
98
+ tools=tools,
99
+ llm=llm,
100
+ agent="zero-shot-react-description",
101
+ verbose=True,
102
+ )
103
+
104
+ # Multi-Agent Workflow
105
+ def multi_agent_workflow(requirements: str) -> str:
106
+ """
107
+ Execute a multi-agent workflow to generate a complex app.
108
+ Args:
109
+ requirements (str): App requirements.
110
+ Returns:
111
+ str: Generated app code and API details.
112
+ """
113
+ global api_details
114
+
115
+ # Step 1: Task Decomposition
116
+ try:
117
+ task_decomposition = ui_designer_agent.run(
118
+ f"Break down the following app requirements into smaller tasks: {requirements}"
119
+ )
120
+ tasks = json.loads(task_decomposition)["tasks"]
121
+ except Exception as e:
122
+ logger.error(f"Task decomposition failed: {str(e)}")
123
+ return f"Task decomposition failed: {str(e)}"
124
+
125
+ # Step 2: Code Generation
126
+ try:
127
+ ui_code = ui_designer_agent.run(f"Generate the UI code for: {tasks[0]}")
128
+ backend_code = backend_developer_agent.run(f"Generate the backend code for: {tasks[1]}")
129
+ except Exception as e:
130
+ logger.error(f"Code generation failed: {str(e)}")
131
+ return f"Code generation failed: {str(e)}"
132
+
133
+ # Step 3: Code Formatting
134
+ try:
135
+ formatted_ui_code = ui_designer_agent.run(f"Format the following code: {ui_code}")
136
+ formatted_backend_code = backend_developer_agent.run(f"Format the following code: {backend_code}")
137
+ except Exception as e:
138
+ logger.error(f"Code formatting failed: {str(e)}")
139
+ return f"Code formatting failed: {str(e)}"
140
+
141
+ # Step 4: Integration
142
+ try:
143
+ combined_code = f"{formatted_ui_code}\n\n{formatted_backend_code}"
144
+ except Exception as e:
145
+ logger.error(f"Code integration failed: {str(e)}")
146
+ return f"Code integration failed: {str(e)}"
147
+
148
+ # Step 5: Testing
149
+ try:
150
+ test_results = qa_engineer_agent.run(f"Test the following app: {combined_code}")
151
+ except Exception as e:
152
+ logger.error(f"Testing failed: {str(e)}")
153
+ return f"Testing failed: {str(e)}"
154
+
155
+ # Step 6: Deployment
156
+ try:
157
+ deployment_status = devops_engineer_agent.run(f"Deploy the following app: {combined_code}")
158
+ except Exception as e:
159
+ logger.error(f"Deployment failed: {str(e)}")
160
+ return f"Deployment failed: {str(e)}"
161
+
162
+ # Step 7: API Documentation
163
+ try:
164
+ api_details = backend_developer_agent.run(f"Generate API details for: {combined_code}")
165
+ except Exception as e:
166
+ logger.error(f"API documentation failed: {str(e)}")
167
+ return f"API documentation failed: {str(e)}"
168
+
169
+ # Return the results
170
+ return f"""
171
+ Generated App Code:
172
+ {combined_code}
173
+
174
+ Test Results:
175
+ {test_results}
176
+
177
+ Deployment Status:
178
+ {deployment_status}
179
+
180
+ API Details:
181
+ {api_details}
182
+ """
183
+
184
+ # Gradio Interface
185
+ def app_generator(requirements: str):
186
+ """
187
+ Generate an app based on the provided requirements.
188
+ Args:
189
+ requirements (str): App requirements.
190
+ Returns:
191
+ str: Generated app code and API details.
192
+ """
193
+ return multi_agent_workflow(requirements)
194
+
195
+ # Gradio UI
196
+ with gr.Blocks() as ui:
197
+ gr.Markdown("# Autonomous App Generator with LangChain Agents")
198
+ with gr.Row():
199
+ requirements_input = gr.Textbox(label="App Requirements", placeholder="Describe the app you want to build...")
200
+ generate_button = gr.Button("Generate App")
201
+ output = gr.Textbox(label="Generated App Code and API Details", lines=20)
202
+ generate_button.click(app_generator, inputs=requirements_input, outputs=output)
203
+
204
+ # Run the Gradio app
205
+ if __name__ == "__main__":
206
+ ui.launch()