lemonteaa commited on
Commit
6d8645f
1 Parent(s): fafeacb

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +229 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import gradio as gr
3
+
4
+ import json
5
+ import logging
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import tempfile
10
+ from zipfile import ZipFile
11
+ import os
12
+
13
+ def instruct(system_prompt : str, message : str) -> str:
14
+ """
15
+ General purpose LLM/AI invocation. Use llama v2 13b chat as an instruct model by wrapping it up
16
+ in a single turn conversation.
17
+ """
18
+ response = openai.ChatCompletion.create(
19
+ model="accounts/fireworks/models/llama-v2-13b-chat-w8a16",
20
+ messages=[{"role":"system", "content": system_prompt}, {"role":"user", "content": message}],
21
+ temperature=0.7,
22
+ max_tokens=2048
23
+ )
24
+ return response.choices[0].message.content
25
+
26
+ sys_prompt1 = """You are a business consultant who helps ordinary people that want to start their own business or SME (Small to Medium Enterprise).
27
+ You specialize in B2C retail or service shops, or more generally those whose main prescence is via physical store.
28
+
29
+ Your client will present you with the kind of shop they want to open, as well as some contextual information,
30
+ such as the business owner's personal background or piror experience, the specific situation they have,
31
+ or additional detail on the business they want to do.
32
+
33
+ You should give a single reply doing this task:
34
+ Give a list of conrete steps/actions that they should do to boostrap the business up to the opening of the physical shop.
35
+ Group the actions by *Category* instead of chronologically. For each action give a brief description.
36
+ """
37
+
38
+ message1 = """- Shop to open:
39
+ Coffee shop/cafe in the Bay Area
40
+ - Additional info:
41
+ I'm a complete newbie in business.
42
+ """
43
+
44
+ sys_prompt2 = """You are a business consultant who helps ordinary people that want to start their own business or SME (Small to Medium Enterprise).
45
+ You specialize in B2C retail or service shops, or more generally those whose main prescence is via physical store.
46
+
47
+ Your client gave this info about the shop they want to open and some additional info:
48
+ {initial}
49
+
50
+ ----
51
+ You have previously generated an action item list as follows:
52
+ {base_plan}
53
+ ----
54
+
55
+ You should give a single reply doing this task:
56
+ {task}
57
+ """
58
+
59
+ tasks = {}
60
+ tasks["interior_design"] = """give 3 generic suggested Interior Designs.
61
+ Explain the main theme of the design and how does it relates to the business, then drill down to details of how the theme may concretely be implemented through specific elements/decor/furnitures etc."""
62
+ tasks["product_design"] = """Perform product design appropiate to the context of the shop.
63
+ For example, for a cafe/restaurant, the "product" to design would be the menu of food items.
64
+ For retail shops, the "products" would be the type of goods to sell on the shelf.
65
+ For shop providing service such as hair salon, the "product" would be the service offered such as hair cutting, hair beauty treatment etc."""
66
+ tasks["equipments"] = """Give a list of the equipments we will need to buy for the shop at the beginning. Any additional tips when buying?"""
67
+ tasks["Staffing_HR"] = """Give a list of the minimum amount of staff we need to hire to operate the shop.
68
+ Can we outsource part of our business to external service provider? If yes list which parts they are.
69
+ For each staff role, describe their job responsibility, and list what requirements (such as skills, attributes, qualifications, etc) we should have when recruiting."""
70
+ tasks["IT_website"] = """We have decided to hire a software agency to help create the website of our shop business for us. Give a business and technical requirement to them,
71
+ while specifying some details such as website content and layout etc according to the specifics of our business.
72
+ Due to budget constraint, please reserve some of the more advanced functionality for a planned future phase (and mark/label them in your output as such)."""
73
+ tasks["Supplier"] = """We would like to make a contract with a supplier so that they will regularly supply us with the materials we need to operate the shop (such as food ingredient for a coffee shop).
74
+ What are the general steps to make this happen, and what details should we be aware of when arranging this?"""
75
+ tasks["budgeting"] = """Give a breakdown of the expense, including initial cost, running cost, and operational cost by the type/items that incur the cost.
76
+ Use a common sense estimate. For items where estimate is difficult because the potential range is too large, mark it as such and we'll handle it later."""
77
+ tasks["business_model"] = """What kind of pricing/business model should we adopt? Choose based on its pros and cons among the alternatives and pick one that is appropiate to this business.
78
+ Then, suggest what level of integration we should have with respect to online shopping/e-commerce. Should our business be offline first or online/offline hybrid.
79
+ Third, should we choose to join a franchise network or something similar, or are we better off alone? Or are there alternative operating models that you think we should use?
80
+ Finally, suggest the scale we should operate at (that is, number of shops) and expansion pathway, with respect to time. (Note: scaling up is sometimes but not always the right answer.)"""
81
+ tasks["business_analysis"] = """Perform a business analysis. What might be our core competencies? Do a SWOT analysis, as well as a value chain analysis.
82
+ Then suggest a high level, overall business strategy."""
83
+ tasks["market_analysis"] = """Perform a market analysis. What should our value proposition and unique selling points be? What is the competitive landscape?
84
+ And which segment should we target/what are our target audience? Based on these info, formulate a high level marketing strategy."""
85
+
86
+
87
+ #with tempfile.TemporaryDirectory() as tmpdirname:
88
+
89
+ def export_all_docs(docs):
90
+ tmpdirname = tempfile.mkdtemp()
91
+ for k, v in docs.items():
92
+ fullpath = os.path.join(tmpdirname, k + ".txt")
93
+ with open(fullpath, "w") as f:
94
+ f.write(v)
95
+ export_filename = os.path.join(tmpdirname, "all_docs.zip")
96
+ with ZipFile(export_filename, "w") as zip:
97
+ for k in docs:
98
+ fullpath = os.path.join(tmpdirname, k + ".txt")
99
+ zip.write(fullpath)
100
+ return export_filename
101
+
102
+ user_topic_background = """- Shop to open:
103
+ {topic}
104
+ - Additional info:
105
+ {add_info}
106
+ """
107
+
108
+ def generate_all_docs(topic : str, add_info : str) -> dict:
109
+ yield ({}, "Begin generation...")
110
+ user_message = user_topic_background.format(topic=topic, add_info=add_info)
111
+ action_items = instruct(sys_prompt1, user_message)
112
+ responses = {"action_items": action_items}
113
+ yield (responses, "Generated action_items")
114
+ for k, v in tasks.items():
115
+ result = instruct(sys_prompt2.format(initial=user_message, base_plan=action_items, task=v), "")
116
+ responses[k] = result
117
+ yield (responses, "Generated " + k)
118
+
119
+ section = """# {title}
120
+ {content}
121
+
122
+ """
123
+
124
+ #def display_docs_combined(docs: dict) -> str:
125
+ # md = ""
126
+ # for k, v in docs.items():
127
+ # md = md + section.format(title=k, content=v)
128
+ # return md
129
+
130
+ task_list = [k for k in tasks]
131
+ task_list.insert(0, "action_items")
132
+
133
+ def display_docs_combined(docs: dict):
134
+ res = [None] * len(task_list)
135
+ for k, v in docs.items():
136
+ i = task_list.index(k)
137
+ res[i] = v
138
+ return res
139
+
140
+ def convert_history_to_openai_format(system_prompt : str, history : list[tuple]):
141
+ messages = [{ "role": "system", "content": system_prompt }]
142
+ for (user_msg, assistant_msg) in history:
143
+ messages.append({ "role": "user", "content": user_msg })
144
+ if assistant_msg is not None:
145
+ messages.append({ "role": "assistant", "content": assistant_msg })
146
+ return messages
147
+
148
+ system_prompt3 = """You are a business consultant who helps ordinary people that want to start their own business or SME (Small to Medium Enterprise).
149
+ You specialize in B2C retail or service shops, or more generally those whose main prescence is via physical store.
150
+
151
+ Your client gave this info about the shop they want to open and some additional info:
152
+ {initial}
153
+
154
+ Your client would now like to ask you some followup question on the business planning documents you wrote or do general consultation questions.
155
+
156
+ (Optional and could be empty) For your reference and to set context, attached below are the relevant business planning documents you wrote:
157
+
158
+ """
159
+
160
+ context_template = """## {title}
161
+ {content}
162
+
163
+ """
164
+
165
+ def talk_to_ai(message, history, choose_context, docs, init_t):
166
+ #print(choose_context)
167
+ sys_p = system_prompt3.format(initial=init_t)
168
+ for k in choose_context:
169
+ sys_p += context_template.format(title=k, content=docs[k])
170
+ #print(sys_p)
171
+ data = convert_history_to_openai_format(sys_p, history)
172
+ data.append({"role": "user", "content": message})
173
+ response = openai.ChatCompletion.create(
174
+ model="accounts/fireworks/models/llama-v2-13b-chat-w8a16",
175
+ messages=data,
176
+ temperature=0.7,
177
+ max_tokens=1024,
178
+ stream=True
179
+ )
180
+ ans = ""
181
+ for chunk in response:
182
+ txt = chunk.choices[0].delta.get("content", "")
183
+ if txt is not None:
184
+ ans += txt
185
+ yield ans
186
+
187
+
188
+ with gr.Blocks() as demo:
189
+ docs = gr.State({})
190
+ init_t = gr.State("")
191
+ gr.Markdown("# Start a Shop (alpha version)")
192
+ with gr.Tabs() as tabs:
193
+ with gr.TabItem("Generate Plan", id=0):
194
+ gr.Markdown("Fill out the info and let AI generate a preliminary plan for starting a physical shop based business. Targetted for small shop owner. Currently takes about 2-3 minutes.")
195
+ with gr.Row():
196
+ with gr.Column():
197
+ topic = gr.Textbox(label="Topic (eg Coffee shop in Bay Area)", show_label=True)
198
+ add_info = gr.TextArea(label="Additional Info", show_label=True)
199
+ generate_init_plan = gr.Button(value="Generate!")
200
+ with gr.Column():
201
+ status_report = gr.Textbox(label="Status Indicator during generation")
202
+ prelim_plan = [None] * len(task_list)
203
+ for i, val in enumerate(task_list):
204
+ with gr.Accordion(val):
205
+ prelim_plan[i] = gr.Markdown()
206
+ #prelim_plan = gr.Markdown()
207
+
208
+ generate_init_plan.click(lambda a, b: user_topic_background.format(topic=a, add_info=b), [topic, add_info], init_t) \
209
+ .success(generate_all_docs, [topic, add_info], [docs, status_report]) \
210
+ .success(display_docs_combined, docs, prelim_plan)
211
+ with gr.TabItem("Followup Questions", id=1):
212
+ gr.Markdown("Here you can ask followup question in the context of the docs generated. Select the document for context to the AI in the dropdown below. Be careful not to choose too many due to LLM context length limitation.")
213
+ with gr.Row():
214
+ #doc_context = gr.State()
215
+ with gr.Column():
216
+ choose_context = gr.Dropdown(choices=task_list, multiselect=True)
217
+ #set_context_btn = gr.Button(value="Set Context")
218
+
219
+ #set_context_btn.click(lambda x: x, choose_context, doc_context)
220
+ with gr.Column():
221
+ chat = gr.ChatInterface(talk_to_ai, additional_inputs=[choose_context, docs, init_t])
222
+ with gr.TabItem("Export", id=2):
223
+ gr.Markdown("Press the button to create a zip containing backup of all documents.")
224
+ export_btn = gr.Button(value="Export documents")
225
+ export_download_area = gr.File()
226
+
227
+ export_btn.click(export_all_docs, docs, export_download_area)
228
+
229
+ demo.queue(concurrency_count=4, max_size=20).launch(debug=False)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ openai
2
+ gradio