cmagganas commited on
Commit
d002559
1 Parent(s): 02f9db6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -143
app.py CHANGED
@@ -1,86 +1,138 @@
1
  import chainlit as cl
2
  from dotenv import load_dotenv
3
- import instructor
4
- from openai import OpenAI
5
  import os
6
  import json
7
- import logging
8
 
9
  load_dotenv()
10
 
11
- # Configure logging
12
- logging.basicConfig(level=logging.INFO)
13
- logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # Patch the OpenAI client with Instructor
16
- client = instructor.from_openai(OpenAI(api_key=os.environ['OPENAI_API_KEY']))
17
 
18
  # Define prompt templates
19
  PRD_PROMPT_TEMPLATE = """
20
  ### Product Requirements Document (PRD) for AI Applications
21
- #### Introduction
22
- - **Objective/Goal**:
23
- - Explain the purpose of the AI application and what it aims to achieve.
24
- - Provide a high-level overview of the release purpose.
25
- - User Proposal: {user_proposal}
26
- #### Features
27
- - **Feature 1**:
28
- - **Description**: Detailed description of the feature.
29
- - **Goal**: What this feature aims to achieve.
30
- - **Use Case**: Example of how a user would utilize this feature.
31
- - **Additional Details**: Specifics such as out-of-scope items and prompt structure.
32
-
33
- - **Feature 2**:
34
- - **Description**: Detailed description of the feature.
35
- - **Goal**: What this feature aims to achieve.
36
- - **Use Case**: Example of how a user would utilize this feature.
37
- - **Additional Details**: Specifics such as out-of-scope items and prompt structure.
38
- *(Repeat for each feature)*
39
- #### UX Flow & Design Notes
40
- - **Overview**: General guidance required to ensure the release objectives are met.
41
- - **User Workflow**: Describe the overall user workflow.
42
- - **Design Considerations**: Any specific design notes relevant at this stage.
43
- #### System & Environment Requirements
44
- - **Supported Environments**:
45
- - Browsers (e.g., Chrome, Firefox, Safari)
46
- - Operating Systems (e.g., Windows 10, macOS)
47
- - Memory and Processing Power requirements
48
- #### Assumptions, Constraints & Dependencies
49
- - **Assumptions**:
50
- - List anything expected to be in place (e.g., all users will have Internet connectivity).
51
-
52
- - **Constraints**:
53
- - Dictate limits for the implementation (e.g., budgetary constraints, technical limitations).
54
-
55
- - **Dependencies**:
56
- - Conditions or items the product will rely on (e.g., relying on Google Maps for directions).
57
- #### Prompt Engineering Practices
58
- - **Ambiguity Mitigation**: Ensure clear, specific prompts to avoid ambiguous outputs. Evaluate prompts using examples and test consistency with different inputs.
59
- - **Versioning**: Track and version each prompt to monitor performance changes over time.
60
- - **Optimization**: Apply techniques like chain-of-thought prompting, majority voting, and breaking tasks into smaller prompts to improve output quality.
61
- - **Cost & Latency Management**: Balance detailed prompts with cost efficiency and manage latency by optimizing token usage.
62
- #### Task Composability
63
- - **Multiple Tasks Composition**: Outline how multiple tasks interact, including sequential and parallel executions, and control flows like if statements and loops.
64
- - **Agents and Tools**: Describe the use of agents to manage tasks and the integration of tools such as SQL executors and web browsers.
65
- - **Control Flows**: Detail the use of control flows in managing tasks, including sequential, parallel, if statements, and loops.
66
- #### Review & Approval Process
67
- - **Initial Review**:
68
- - Steps for internal product team review.
69
- - Feedback incorporation.
70
-
71
- - **Business Side Stakeholders Review**:
72
- - Process for aligning with business stakeholders.
73
-
74
- - **Engineering Handoff**:
75
- - Clarifications and updates based on technical team feedback.
76
-
77
- - **Final Approval**:
78
- - Ensuring no surprises later on.
79
- - Agreement from all teams involved (UX design, engineering, QA).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  ---
 
81
  This PRD template is configured specifically for the user proposal: "{user_proposal}", ensuring a consistent format for every PRD, covering all necessary aspects from features to dependencies, review processes, and incorporating best practices in prompt engineering and task composability.
82
  """
83
 
 
84
  DESIGNER_PROMPT_TEMPLATE = """
85
  <System Message>
86
  You are the Engineer/Designer Agent responsible for creating a functional product.
@@ -111,86 +163,107 @@ https://raw.githubusercontent.com/AI-Maker-Space/Beyond-ChatGPT/main/README.md
111
  \n<>####<>\n
112
  """
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  # Function to format the templates with provided variables
115
  def format_template(template, **kwargs):
116
  return template.format(**kwargs)
117
 
118
- # Define functions
119
- def llm_call(user_prompt, system_prompt=None):
120
- messages = [
121
- {"role": "user", "content": user_prompt}
122
- ] if system_prompt is None else [
123
- {"role": "system", "content": system_prompt},
124
- {"role": "user", "content": user_prompt},
125
- ]
126
-
127
- try:
128
- response = client.chat.completions.create(
129
- model="gpt-4-turbo-preview",
130
- response_model=None,
131
- messages=messages,
132
- )
133
- return response
134
- except Exception as e:
135
- logger.error(f"Error during LLM call: {e}")
136
- return None
137
 
 
138
  @cl.on_chat_start
139
  async def start():
140
- try:
141
- # Welcome message
142
- wel_msg = cl.Message(content="Welcome to Build Advisor!\n\nBuild Advisor creates plan, production requirement spec and implementation for your AI application idea.\nQuickly create a PoC so you can determine whether an idea is worth starting, worth investing time and/or money in.")
143
- await wel_msg.send()
144
-
145
- # Ask user for AI application / business idea
146
- res = await cl.AskUserMessage(content="What is your AI application/business idea?", timeout=30).send()
147
- if res:
148
- await wel_msg.remove()
149
- await cl.Message(
150
- content=f"User Proposal: {res['content']}.\n\nStarting...",
151
- ).send()
152
-
153
- user_proposal = res['content']
154
-
155
- prd_sys1 = format_template(PRD_PROMPT_TEMPLATE, user_proposal=user_proposal) # system message to create PRD
156
- prd_response = llm_call(user_prompt=user_proposal, system_prompt=prd_sys1)
157
-
158
- if prd_response:
159
- prd_response_raw = prd_response.choices[0].message.content
160
-
161
- # send PRD output to UI
162
- prd_msg = cl.Message(content=prd_response_raw)
163
- await prd_msg.send()
164
-
165
- prd_json = json.dumps({
166
- "objective_goal": "Develop a chatbot...",
167
- "features": [],
168
- "ux_flow_design_notes": "...",
169
- "system_environment_requirements": "...",
170
- "assumptions": [],
171
- "constraints": [],
172
- "dependencies": [],
173
- "prompt_engineering_practices": "...",
174
- "task_composability": "...",
175
- "review_approval_process": "..."
176
- })
177
- designer_prompt = format_template(DESIGNER_PROMPT_TEMPLATE, prd_response_raw=prd_response_raw, prd_json=prd_json, user_proposal=user_proposal)
178
- designer_response = llm_call(designer_prompt)
179
-
180
- if designer_response:
181
- designer_output = designer_response.choices[0].message.content
182
-
183
- designer_output_msg = cl.Message(content=designer_output)
184
- await designer_output_msg.send()
185
-
186
- # update outputs in UI
187
- for secs in [1, 5, 10, 20]:
188
- await cl.sleep(secs)
189
- await prd_msg.update()
190
- await designer_output_msg.update()
191
- else:
192
- await cl.Message(content="Error generating designer output. Please try again.").send()
193
- else:
194
- await cl.Message(content="Error generating PRD. Please try again.").send()
195
- except Exception as e:
196
- logger.error(f"Error during chat start: {e}")
 
1
  import chainlit as cl
2
  from dotenv import load_dotenv
3
+ from openai import OpenAI, AsyncOpenAI
 
4
  import os
5
  import json
 
6
 
7
  load_dotenv()
8
 
9
+ # Async OpenAI
10
+ client = AsyncOpenAI(api_key=os.environ['OPENAI_API_KEY'])
11
+
12
+ async def llm_call(user_prompt, system_prompt=None):
13
+ # sourcery skip: inline-immediately-returned-variable
14
+ chat_completion = await client.chat.completions.create(
15
+ messages = [
16
+ {"role": "user", "content": user_prompt}
17
+ ] if system_prompt is None else [
18
+ {"role": "system", "content": system_prompt},
19
+ {"role": "user", "content": user_prompt},
20
+ ],
21
+ model="gpt-4o-mini"
22
+ )
23
+ return chat_completion
24
 
 
 
25
 
26
  # Define prompt templates
27
  PRD_PROMPT_TEMPLATE = """
28
  ### Product Requirements Document (PRD) for AI Applications
29
+
30
+ User Proposal: {user_proposal}
31
+
32
+ To generate a comprehensive Product Requirement Document (PRD) for your AI application, please provide detailed responses to the following prompts. The sections in **bold** are particularly important, and those marked with **[!]** are critical to get right. These sections should be prioritized in your responses and the generated PRD.
33
+
34
+ 1. **Product Name and Brief Description:**
35
+ - What is the name of your AI application?
36
+ - Provide a brief description (1-2 sentences) of your product.
37
+
38
+ 2. **Primary Problem:**
39
+ - What is the main problem your AI application aims to solve?
40
+ - Why is this problem significant?
41
+
42
+ 3. **Target Audience or User Base:**
43
+ - Who are the primary users of your AI application?
44
+ - Describe their key characteristics and needs.
45
+
46
+ 4. **Key Features:**
47
+ - List 3-5 key features you want to include in your AI application.
48
+ - Explain the importance of each feature.
49
+
50
+ 5. **Technical Requirements or Constraints:**
51
+ - Are there any specific technical requirements or constraints for your application?
52
+ - Include details about platforms, technologies, or integrations needed.
53
+
54
+ 6. **Development and Launch Timeline:**
55
+ - What is the expected timeline for development and launch?
56
+ - Include any important milestones.
57
+
58
+ Based on the information provided, the LLM will generate a comprehensive PRD following the structure outlined below. Prioritize and ensure thorough and accurate information in the **bold** sections and especially those marked with **[!]**:
59
+
60
+ 1. **Overview**
61
+ - **Problem Statement**
62
+ - The Problem Space section outlines the key challenges and issues that the product aims to address. It includes an analysis of the current limitations, pain points, and gaps in the existing solutions, providing a clear understanding of why the new product is necessary.
63
+ - **Proposed Solution**
64
+ - The Proposed Solution section describes the envisioned product and how it intends to solve the identified problems. It highlights the core functionalities, innovative features, and unique selling points that differentiate it from existing solutions.
65
+ - **Features Advantages**
66
+ - Highlights focus on the key advantages and positive aspects of the proposed solution. This includes major features, benefits to the users, expected improvements in user experience, and competitive advantages.
67
+ - **Feature Challenges**
68
+ - Challenges address the potential obstacles, limitations, and risks associated with the proposed solution. This section provides a realistic view of what might go wrong, areas that need careful attention, and any trade-offs made in the design and implementation of the product.
69
+
70
+ 2. **Strategic Context**
71
+ - **User Needs**
72
+ - User Needs identify and analyze the key requirements and pain points of the target users. This section provides detailed user personas, usage scenarios, and key features that users expect from the product. Understanding user needs is crucial for aligning the product development process with user expectations and delivering a solution that addresses real problems.
73
+ - **Business Driver**
74
+ - The Business Driver section outlines the primary business motivations behind developing the product. This includes strategic goals, revenue targets, market expansion, customer retention, and competitive advantages. It links the product's objectives to the broader business strategy, ensuring alignment and support from stakeholders.
75
+ - **[!] Research, Market Analysis, and Competitive Benchmarking**
76
+ - This section presents comprehensive research on market trends, user behavior, and industry standards. It includes competitive benchmarking to analyze the strengths and weaknesses of current market players and identify opportunities for differentiation. Market analysis helps in understanding the competitive landscape and positioning the product effectively.
77
+ - Current Product Analysis:
78
+ - The Current Product Analysis reviews the existing products and solutions within the organization and the market. It identifies gaps, overlaps, and areas for improvement. This section provides insights into what works well and what needs enhancement, guiding the development of new features and functionalities.
79
+ - **[!] Product Growth**
80
+ - Product Growth outlines the potential for the product to scale and expand. This includes projections for user adoption, market penetration, and revenue growth. It also addresses strategies for sustaining long-term growth, such as feature updates, new market entries, and partnerships.
81
+ - **[!] Brand Alignment**
82
+ - Brand Alignment ensures that the product's development and marketing strategies are consistent with the company's brand values and identity. This section discusses how the product will enhance the brand's reputation, align with brand messaging, and leverage brand equity to attract users.
83
+ - **[!] Roadmap**
84
+ - The Roadmap provides a high-level timeline and milestones for product development and launch. It outlines key phases, deliverables, and deadlines, helping to manage expectations and ensure timely execution. The roadmap is essential for coordinating efforts across different teams and keeping the project on track.
85
+
86
+ 3. **Product Definition**
87
+ - **Functional Requirements**
88
+ - Functional requirements describe the specific behaviors, features, and functionalities the product must have. These requirements define what the system should do and include detailed descriptions of each feature.
89
+ - **Non-Functional Requirements**
90
+ - Non-functional requirements specify the quality attributes, system performance, and operational constraints of the product. These requirements ensure that the system operates effectively and efficiently.
91
+ - User Stories:
92
+ - User stories are short, simple descriptions of a feature told from the perspective of the end user. They help to capture the functional requirements in a way that is easy to understand and relate to.
93
+ - User Experience:
94
+ - The User Experience section focuses on the design and interaction aspects of the product. It includes wireframes, mockups, and user flow diagrams to illustrate how users will interact with the system.
95
+
96
+ 4. **Data**
97
+ - Data Source (ETL):
98
+ - The Data Source (ETL) section describes the processes for extracting, transforming, and loading data from various sources. This includes identifying the data sources, defining the extraction methods, detailing the transformation processes, and explaining how the data will be loaded into the system for use by the AI models.
99
+ - Feature Data Collection:
100
+ - Feature Data Collection focuses on how data will be collected to create and refine the AI features. This involves identifying the types of data needed, defining the collection methods, and ensuring data quality and relevance.
101
+ - Features Metrics:
102
+ - Feature Metrics define the key performance indicators (KPIs) and other metrics used to measure and analyze the performance of the AI feature. These metrics help in evaluating the effectiveness, efficiency, and impact of the feature.
103
+
104
+ 5. **Acceptance Criteria**
105
+ - **Accuracy**
106
+ - The extent to which the AI model's outputs align with expected results. The level of importance and a score to achieve and how it's measured.
107
+ - **Performance/Latency**
108
+ - The speed and efficiency of the AI application, minimizing response times. SLAs on acceptable performance based on the target environment.
109
+ - Cost @ Scale:
110
+ - Scale and cost criteria assess the AI application's ability to handle increased load. Growth plan including DevOps, OPEX, and location.
111
+ - KPIs:
112
+ - Product-specific feature key performance indicators to grade health over time. Customer satisfaction rating and feedback.
113
+
114
+ 6. **Challenges and Considerations**
115
+ - Risks:
116
+ - Identification and analysis of potential risks. Impact assessment and mitigation strategies.
117
+ - Innovations:
118
+ - Innovative features and technologies being integrated. Potential challenges and benefits of these innovations.
119
+ - Dependencies:
120
+ - Internal and external dependencies critical to the project. Plans to manage and mitigate dependency-related issues.
121
+ - Events:
122
+ - Key events that could impact the project timeline or scope. Strategies to manage and leverage these events.
123
+ - Contingency Plans:
124
+ - Contingency strategies for managing unforeseen issues. Backup plans for critical project components.
125
+
126
+ 7. **Conclusion**
127
+ - Summary:
128
+ - Including key next steps.
129
+
130
  ---
131
+
132
  This PRD template is configured specifically for the user proposal: "{user_proposal}", ensuring a consistent format for every PRD, covering all necessary aspects from features to dependencies, review processes, and incorporating best practices in prompt engineering and task composability.
133
  """
134
 
135
+
136
  DESIGNER_PROMPT_TEMPLATE = """
137
  <System Message>
138
  You are the Engineer/Designer Agent responsible for creating a functional product.
 
163
  \n<>####<>\n
164
  """
165
 
166
+ # Example PRD Schema (JSON)
167
+ PRD_JSON_TEMPLATE = json.dumps({
168
+ "user_proposal": "Develop a chatbot...",
169
+ "overview": {
170
+ "problem_statement": "The Problem Space section outlines the key challenges and issues that the product aims to address...",
171
+ "proposed_solution": "The Proposed Solution section describes the envisioned product and how it intends to solve the identified problems...",
172
+ "features_advantages": "Highlights focus on the key advantages and positive aspects of the proposed solution...",
173
+ "feature_challenges": "Challenges address the potential obstacles, limitations, and risks associated with the proposed solution..."
174
+ },
175
+ "strategic_context": {
176
+ "user_needs": "User Needs identify and analyze the key requirements and pain points of the target users...",
177
+ "business_driver": "The Business Driver section outlines the primary business motivations behind developing the product...",
178
+ "research_market_analysis_and_competitive_benchmarking": "This section presents comprehensive research on market trends, user behavior, and industry standards...",
179
+ "current_product_analysis": "The Current Product Analysis reviews the existing products and solutions within the organization and the market...",
180
+ "product_growth": "Product Growth outlines the potential for the product to scale and expand...",
181
+ "brand_alignment": "Brand Alignment ensures that the product's development and marketing strategies are consistent with the company's brand values and identity...",
182
+ "roadmap": "The Roadmap provides a high-level timeline and milestones for product development and launch..."
183
+ },
184
+ "product_definition": {
185
+ "functional_requirements": "Functional requirements describe the specific behaviors, features, and functionalities the product must have...",
186
+ "non_functional_requirements": "Non-functional requirements specify the quality attributes, system performance, and operational constraints of the product...",
187
+ "user_stories": "User stories are short, simple descriptions of a feature told from the perspective of the end user...",
188
+ "user_experience": "The User Experience section focuses on the design and interaction aspects of the product..."
189
+ },
190
+ "data": {
191
+ "data_source_etl": "The Data Source (ETL) section describes the processes for extracting, transforming, and loading data from various sources...",
192
+ "feature_data_collection": "Feature Data Collection focuses on how data will be collected to create and refine the AI features...",
193
+ "features_metrics": "Feature Metrics define the key performance indicators (KPIs) and other metrics used to measure and analyze the performance of the AI feature..."
194
+ },
195
+ "acceptance_criteria": {
196
+ "accuracy": "The extent to which the AI model's outputs align with expected results...",
197
+ "performance_latency": "The speed and efficiency of the AI application, minimizing response times...",
198
+ "cost_at_scale": "Scale and cost criteria assess the AI application's ability to handle increased load...",
199
+ "kpis": "Product-specific feature key performance indicators to grade health over time..."
200
+ },
201
+ "challenges_and_considerations": {
202
+ "risks": "Identification and analysis of potential risks...",
203
+ "innovations": "Innovative features and technologies being integrated...",
204
+ "dependencies": "Internal and external dependencies critical to the project...",
205
+ "events": "Key events that could impact the project timeline or scope...",
206
+ "contingency_plans": "Contingency strategies for managing unforeseen issues..."
207
+ },
208
+ "conclusion": {
209
+ "summary": "Including key next steps..."
210
+ }
211
+ })
212
+
213
+
214
  # Function to format the templates with provided variables
215
  def format_template(template, **kwargs):
216
  return template.format(**kwargs)
217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
+ # Define the Chainlit message handler
220
  @cl.on_chat_start
221
  async def start():
222
+
223
+ # Welcome message
224
+ wel_msg = cl.Message(content="Welcome to Build Advisor!\n\nBuild Advisor creates a plan, prod req spec and implementation for you.\nQuickly create a PoC so you can determine whether an idea is \n1. worth starting\n2. worth investing time \n3. worth investing money")
225
+ await wel_msg.send()
226
+
227
+ # Ask user for AI application / business idea
228
+ res = await cl.AskUserMessage(content="What is your AI application/business idea?", timeout=30).send()
229
+ if res:
230
+ await wel_msg.remove()
231
+ await cl.Message(
232
+ content=f"User Proposal: {res['output']}.\n\nStarting...",
233
+ ).send()
234
+
235
+ user_proposal = res['output']
236
+
237
+ # populate the PRD template
238
+ prd_sys1 = format_template(PRD_PROMPT_TEMPLATE, user_proposal=user_proposal)
239
+
240
+ # call the PRD agent
241
+ prd_response = await llm_call(user_prompt=user_proposal, system_prompt=prd_sys1)
242
+ prd_response_raw = prd_response.choices[0].message.content # get PRD from LLM
243
+
244
+ # send PRD output to UI
245
+ prd_msg = cl.Message(content=prd_response_raw)
246
+ await prd_msg.send()
247
+
248
+ # populate the designer template
249
+ designer_prompt = format_template(DESIGNER_PROMPT_TEMPLATE, prd_response_raw=prd_response_raw, prd_json=PRD_JSON_TEMPLATE, user_proposal=user_proposal)
250
+
251
+ # call the designer agent
252
+ designer_response = await llm_call(designer_prompt)
253
+ designer_output = designer_response.choices[0].message.content
254
+
255
+ # send designer output to UI
256
+ designer_output_msg = cl.Message(content=designer_output)
257
+ await designer_output_msg.send()
258
+
259
+ # update messages
260
+ await prd_msg.update()
261
+ await designer_output_msg.update()
262
+
263
+
264
+ ####
265
+ # TO DO:
266
+ # ⭐⭐⭐⭐⭐ output message as download
267
+ # ⭐⭐⭐ have follow up messages revise the original output or give feedback
268
+ # ⭐⭐⭐ have starter message for users who don't have an idea yet
269
+ ####