jamierpatterson commited on
Commit
7a6b77d
·
verified ·
1 Parent(s): 9461e13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -33
app.py CHANGED
@@ -3,11 +3,27 @@ st.set_page_config(page_title="B2B Problem Solver", layout="wide")
3
 
4
  import requests
5
  import os
 
6
  from bs4 import BeautifulSoup
7
 
8
- # Configure OpenAI API (using OPENAI_API_KEY)
9
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
10
- OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  # Define common business problem categories
13
  PROBLEM_CATEGORIES = [
@@ -25,6 +41,14 @@ PROBLEM_CATEGORIES = [
25
  "Other (Please Specify)"
26
  ]
27
 
 
 
 
 
 
 
 
 
28
  def scrape_company_info(url):
29
  """Scrapes business information from the given company website URL."""
30
  if not url.startswith("http"):
@@ -52,7 +76,7 @@ def scrape_company_info(url):
52
  return None
53
 
54
  def generate_problem_solution(business_info, problem_category, problem_description):
55
- """Generates a practical solution for the specified business problem using OpenAI GPT-4."""
56
  prompt = f"""As a senior B2B growth strategist with extensive experience helping sales and marketing executives overcome business challenges, provide a practical solution for the following scenario:
57
 
58
  COMPANY INFORMATION:
@@ -79,13 +103,35 @@ Please provide:
79
 
80
  Format your response in clear markdown with headers and bullet points, keeping it concise, practical, and immediately actionable for busy executives."""
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  headers = {
83
- "Authorization": f"Bearer {OPENAI_API_KEY}",
84
  "Content-Type": "application/json"
85
  }
86
 
87
  data = {
88
- "model": "gpt-4", # Using OpenAI GPT-4 model
89
  "messages": [
90
  {"role": "system", "content": "You are a senior B2B growth strategist who specializes in solving critical business challenges for sales and marketing executives."},
91
  {"role": "user", "content": prompt}
@@ -94,18 +140,82 @@ Format your response in clear markdown with headers and bullet points, keeping i
94
  "max_tokens": 3500
95
  }
96
 
97
- try:
98
- response = requests.post(OPENAI_ENDPOINT, json=data, headers=headers)
99
- response.raise_for_status()
100
- return response.json()["choices"][0]["message"]["content"]
101
- except Exception as e:
102
- st.error(f"API Error: {str(e)}")
103
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  # Streamlit UI
106
  st.title("🚀 B2B Problem Solver")
107
  st.markdown("### Get practical solutions to common business problems hindering your growth")
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  with st.expander("💡 How it works", expanded=True):
110
  st.markdown("""
111
  1. Enter your company details or website URL
@@ -133,6 +243,8 @@ if input_method == "Enter company details manually":
133
  if st.button("Generate Solution"):
134
  if not all([company_name, industry, company_description, problem_description]):
135
  st.error("Please fill in all required fields marked with *")
 
 
136
  else:
137
  with st.spinner("Analyzing your business challenge and crafting a solution..."):
138
  business_info = f"""
@@ -143,17 +255,24 @@ Company Size: {team_size}
143
  """
144
  solution = generate_problem_solution(business_info, problem_category, problem_description)
145
  if solution:
146
- st.markdown("## Your Customized Solution Plan")
147
- st.markdown(solution)
148
-
149
- with st.expander("Want expert help implementing this solution?"):
150
- st.markdown("""
151
- Our growth agency specializes in helping B2B companies implement these solutions and achieve measurable results.
152
 
153
- **Schedule a free 30-minute consultation** to discuss how we can help you overcome this challenge and accelerate your growth.
154
- """)
155
- st.text_input("Your Email")
156
- st.button("Request Consultation")
 
 
 
 
 
 
 
 
 
 
157
 
158
  else:
159
  website_url = st.text_input("Enter your company website URL*", placeholder="e.g., www.example.com")
@@ -169,23 +288,32 @@ else:
169
  if st.button("Generate Solution"):
170
  if not all([website_url, problem_description]):
171
  st.error("Please fill in all required fields marked with *")
 
 
172
  else:
173
  with st.spinner("Extracting company details and generating your solution..."):
174
  company_info = scrape_company_info(website_url)
175
  if company_info:
176
  solution = generate_problem_solution(company_info, problem_category, problem_description)
177
  if solution:
178
- st.markdown("## Your Customized Solution Plan")
179
- st.markdown(solution)
180
-
181
- with st.expander("Want expert help implementing this solution?"):
182
- st.markdown("""
183
- Our growth agency specializes in helping B2B companies implement these solutions and achieve measurable results.
184
 
185
- **Schedule a free 30-minute consultation** to discuss how we can help you overcome this challenge and accelerate your growth.
186
- """)
187
- st.text_input("Your Email")
188
- st.button("Request Consultation")
 
 
 
 
 
 
 
 
 
 
189
 
190
  # Add footer with branding
191
  st.markdown("---")
 
3
 
4
  import requests
5
  import os
6
+ import json
7
  from bs4 import BeautifulSoup
8
 
9
+ # API Configuration options
10
+ API_OPTIONS = {
11
+ "OpenAI": {
12
+ "endpoint": "https://api.openai.com/v1/chat/completions",
13
+ "env_key": "OPENAI_API_KEY",
14
+ "models": ["gpt-4", "gpt-3.5-turbo"]
15
+ },
16
+ "Anthropic": {
17
+ "endpoint": "https://api.anthropic.com/v1/messages",
18
+ "env_key": "ANTHROPIC_API_KEY",
19
+ "models": ["claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307"]
20
+ },
21
+ "Azure OpenAI": {
22
+ "endpoint": os.getenv("AZURE_OPENAI_ENDPOINT", "https://your-resource-name.openai.azure.com/openai/deployments/your-deployment-name/chat/completions?api-version=2023-05-15"),
23
+ "env_key": "AZURE_OPENAI_API_KEY",
24
+ "models": ["your-deployment-name"]
25
+ }
26
+ }
27
 
28
  # Define common business problem categories
29
  PROBLEM_CATEGORIES = [
 
41
  "Other (Please Specify)"
42
  ]
43
 
44
+ # Get API settings from session state or initialize them
45
+ if 'api_provider' not in st.session_state:
46
+ st.session_state.api_provider = "OpenAI"
47
+ if 'api_model' not in st.session_state:
48
+ st.session_state.api_model = API_OPTIONS["OpenAI"]["models"][0]
49
+ if 'api_key' not in st.session_state:
50
+ st.session_state.api_key = os.getenv(API_OPTIONS["OpenAI"]["env_key"], "")
51
+
52
  def scrape_company_info(url):
53
  """Scrapes business information from the given company website URL."""
54
  if not url.startswith("http"):
 
76
  return None
77
 
78
  def generate_problem_solution(business_info, problem_category, problem_description):
79
+ """Generates a practical solution for the specified business problem using the configured AI provider."""
80
  prompt = f"""As a senior B2B growth strategist with extensive experience helping sales and marketing executives overcome business challenges, provide a practical solution for the following scenario:
81
 
82
  COMPANY INFORMATION:
 
103
 
104
  Format your response in clear markdown with headers and bullet points, keeping it concise, practical, and immediately actionable for busy executives."""
105
 
106
+ provider = st.session_state.api_provider
107
+ model = st.session_state.api_model
108
+ api_key = st.session_state.api_key
109
+
110
+ if not api_key:
111
+ return f"Error: Missing API key for {provider}. Please configure your API key in the settings."
112
+
113
+ try:
114
+ if provider == "OpenAI":
115
+ return call_openai_api(prompt, model, api_key)
116
+ elif provider == "Anthropic":
117
+ return call_anthropic_api(prompt, model, api_key)
118
+ elif provider == "Azure OpenAI":
119
+ return call_azure_openai_api(prompt, model, api_key)
120
+ else:
121
+ return "Error: Invalid API provider selected"
122
+ except Exception as e:
123
+ error_message = str(e)
124
+ return f"API Error: {error_message}\n\nPlease check your API configuration in the settings panel."
125
+
126
+ def call_openai_api(prompt, model, api_key):
127
+ """Call the OpenAI API to generate a response."""
128
  headers = {
129
+ "Authorization": f"Bearer {api_key}",
130
  "Content-Type": "application/json"
131
  }
132
 
133
  data = {
134
+ "model": model,
135
  "messages": [
136
  {"role": "system", "content": "You are a senior B2B growth strategist who specializes in solving critical business challenges for sales and marketing executives."},
137
  {"role": "user", "content": prompt}
 
140
  "max_tokens": 3500
141
  }
142
 
143
+ response = requests.post(API_OPTIONS["OpenAI"]["endpoint"], json=data, headers=headers)
144
+ response.raise_for_status()
145
+ return response.json()["choices"][0]["message"]["content"]
146
+
147
+ def call_anthropic_api(prompt, model, api_key):
148
+ """Call the Anthropic API to generate a response."""
149
+ headers = {
150
+ "x-api-key": api_key,
151
+ "anthropic-version": "2023-06-01",
152
+ "content-type": "application/json"
153
+ }
154
+
155
+ data = {
156
+ "model": model,
157
+ "messages": [
158
+ {"role": "user", "content": prompt}
159
+ ],
160
+ "max_tokens": 3500
161
+ }
162
+
163
+ response = requests.post(API_OPTIONS["Anthropic"]["endpoint"], json=data, headers=headers)
164
+ response.raise_for_status()
165
+ return response.json()["content"][0]["text"]
166
+
167
+ def call_azure_openai_api(prompt, model, api_key):
168
+ """Call the Azure OpenAI API to generate a response."""
169
+ headers = {
170
+ "api-key": api_key,
171
+ "Content-Type": "application/json"
172
+ }
173
+
174
+ data = {
175
+ "messages": [
176
+ {"role": "system", "content": "You are a senior B2B growth strategist who specializes in solving critical business challenges for sales and marketing executives."},
177
+ {"role": "user", "content": prompt}
178
+ ],
179
+ "temperature": 0.7,
180
+ "max_tokens": 3500
181
+ }
182
+
183
+ response = requests.post(API_OPTIONS["Azure OpenAI"]["endpoint"], json=data, headers=headers)
184
+ response.raise_for_status()
185
+ return response.json()["choices"][0]["message"]["content"]
186
 
187
  # Streamlit UI
188
  st.title("🚀 B2B Problem Solver")
189
  st.markdown("### Get practical solutions to common business problems hindering your growth")
190
 
191
+ # API Configuration in sidebar
192
+ with st.sidebar:
193
+ st.header("API Settings")
194
+ st.session_state.api_provider = st.selectbox(
195
+ "Select AI Provider",
196
+ options=list(API_OPTIONS.keys()),
197
+ index=list(API_OPTIONS.keys()).index(st.session_state.api_provider)
198
+ )
199
+
200
+ st.session_state.api_model = st.selectbox(
201
+ "Select Model",
202
+ options=API_OPTIONS[st.session_state.api_provider]["models"],
203
+ index=min(API_OPTIONS[st.session_state.api_provider]["models"].index(st.session_state.api_model)
204
+ if st.session_state.api_model in API_OPTIONS[st.session_state.api_provider]["models"] else 0,
205
+ len(API_OPTIONS[st.session_state.api_provider]["models"]) - 1)
206
+ )
207
+
208
+ api_key_env = API_OPTIONS[st.session_state.api_provider]["env_key"]
209
+ api_key_input = st.text_input(
210
+ f"API Key (or set {api_key_env} environment variable)",
211
+ type="password",
212
+ value=st.session_state.api_key
213
+ )
214
+ if api_key_input:
215
+ st.session_state.api_key = api_key_input
216
+
217
+ st.info(f"Current status: {'✅ API key configured' if st.session_state.api_key else '❌ API key missing'}")
218
+
219
  with st.expander("💡 How it works", expanded=True):
220
  st.markdown("""
221
  1. Enter your company details or website URL
 
243
  if st.button("Generate Solution"):
244
  if not all([company_name, industry, company_description, problem_description]):
245
  st.error("Please fill in all required fields marked with *")
246
+ elif not st.session_state.api_key:
247
+ st.error(f"Please configure your {st.session_state.api_provider} API key in the sidebar")
248
  else:
249
  with st.spinner("Analyzing your business challenge and crafting a solution..."):
250
  business_info = f"""
 
255
  """
256
  solution = generate_problem_solution(business_info, problem_category, problem_description)
257
  if solution:
258
+ if not solution.startswith("Error") and not solution.startswith("API Error"):
259
+ st.markdown("## Your Customized Solution Plan")
260
+ st.markdown(solution)
 
 
 
261
 
262
+ with st.expander("Want expert help implementing this solution?"):
263
+ st.markdown("""
264
+ Our growth agency specializes in helping B2B companies implement these solutions and achieve measurable results.
265
+
266
+ **Schedule a free 30-minute consultation** to discuss how we can help you overcome this challenge and accelerate your growth.
267
+ """)
268
+ contact_email = st.text_input("Your Email")
269
+ if st.button("Request Consultation"):
270
+ if contact_email:
271
+ st.success("Thank you! We'll be in touch shortly to schedule your consultation.")
272
+ else:
273
+ st.warning("Please enter your email address.")
274
+ else:
275
+ st.error(solution)
276
 
277
  else:
278
  website_url = st.text_input("Enter your company website URL*", placeholder="e.g., www.example.com")
 
288
  if st.button("Generate Solution"):
289
  if not all([website_url, problem_description]):
290
  st.error("Please fill in all required fields marked with *")
291
+ elif not st.session_state.api_key:
292
+ st.error(f"Please configure your {st.session_state.api_provider} API key in the sidebar")
293
  else:
294
  with st.spinner("Extracting company details and generating your solution..."):
295
  company_info = scrape_company_info(website_url)
296
  if company_info:
297
  solution = generate_problem_solution(company_info, problem_category, problem_description)
298
  if solution:
299
+ if not solution.startswith("Error") and not solution.startswith("API Error"):
300
+ st.markdown("## Your Customized Solution Plan")
301
+ st.markdown(solution)
 
 
 
302
 
303
+ with st.expander("Want expert help implementing this solution?"):
304
+ st.markdown("""
305
+ Our growth agency specializes in helping B2B companies implement these solutions and achieve measurable results.
306
+
307
+ **Schedule a free 30-minute consultation** to discuss how we can help you overcome this challenge and accelerate your growth.
308
+ """)
309
+ contact_email = st.text_input("Your Email")
310
+ if st.button("Request Consultation"):
311
+ if contact_email:
312
+ st.success("Thank you! We'll be in touch shortly to schedule your consultation.")
313
+ else:
314
+ st.warning("Please enter your email address.")
315
+ else:
316
+ st.error(solution)
317
 
318
  # Add footer with branding
319
  st.markdown("---")