zenaight commited on
Commit
10cd85d
·
1 Parent(s): a6261d0

larger token and also country of origin

Browse files
Files changed (1) hide show
  1. app/main.py +46 -27
app/main.py CHANGED
@@ -84,7 +84,7 @@ class GenerateRequest(BaseModel):
84
  model: str
85
  business_idea: Optional[str] = ""
86
 
87
- def generate_model_output(model: str, provider: str, api_key: str, prompt: str, max_tokens: int = 500) -> str:
88
  """
89
  A helper function that wraps the Hugging Face Inference API call.
90
  """
@@ -92,13 +92,13 @@ def generate_model_output(model: str, provider: str, api_key: str, prompt: str,
92
  logging.info(f"Initializing InferenceClient with provider: {provider}")
93
  client = InferenceClient(provider=provider, api_key=api_key)
94
 
95
- logging.info(f"Sending request to model: {model} with prompt length: {len(prompt)}")
96
  completion = client.chat.completions.create(
97
  model=model,
98
  messages=[{"role": "user", "content": prompt}],
99
  max_tokens=max_tokens,
100
  )
101
- logging.info(f"Successfully received response from model: {model}")
102
  return completion.choices[0].message.content
103
  except Exception as e:
104
  error_message = f"Error generating output with model {model}: {str(e)}"
@@ -113,9 +113,9 @@ class HFInferenceLLM(LLM):
113
  model: str = None
114
  provider: str = "hf-inference"
115
  api_key: str = ""
116
- max_tokens: int = 500
117
 
118
- def __init__(self, model: str, provider: str = "hf-inference", api_key: str = "", max_tokens: int = 500):
119
  super().__init__()
120
  self.model = model
121
  self.provider = provider
@@ -174,7 +174,7 @@ def get_llm(model_name: str):
174
  if not openai_api_key:
175
  logging.error("OPENAI_API_KEY environment variable not set")
176
  raise ValueError("OPENAI_API_KEY environment variable is required for GPT models")
177
- return ChatOpenAI(model_name="gpt-4o-mini-2024-07-18", temperature=0.7)
178
  elif model_name == "Llama":
179
  logging.info("Initializing Llama model - note this is a gated model and requires special access")
180
  try:
@@ -183,7 +183,7 @@ def get_llm(model_name: str):
183
  model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
184
  provider="hf-inference",
185
  api_key=hf_token,
186
- max_tokens=500
187
  )
188
  except Exception as e:
189
  logging.error(f"Failed to initialize Llama model: {str(e)}")
@@ -198,7 +198,7 @@ def get_llm(model_name: str):
198
  model="Qwen/Qwen1.5-0.5B-Chat", # Much smaller model (0.5B vs 7B)
199
  provider="hf-inference",
200
  api_key=hf_token,
201
- max_tokens=500
202
  )
203
  except Exception as e:
204
  error_msg = str(e)
@@ -217,7 +217,7 @@ def get_llm(model_name: str):
217
  model="mistralai/Mistral-7B-Instruct-v0.3",
218
  provider="hf-inference",
219
  api_key=hf_token,
220
- max_tokens=500
221
  )
222
  except Exception as e:
223
  error_msg = str(e)
@@ -231,7 +231,7 @@ def get_llm(model_name: str):
231
  model="mistralai/Mistral-7B-Instruct-v0.1",
232
  provider="hf-inference",
233
  api_key=hf_token,
234
- max_tokens=500
235
  )
236
  except Exception:
237
  pass
@@ -245,7 +245,7 @@ def get_llm(model_name: str):
245
  model="google/gemma-2b-it",
246
  provider="hf-inference",
247
  api_key=hf_token,
248
- max_tokens=500
249
  )
250
  except Exception as e:
251
  logging.error(f"Failed to initialize Gemma model: {str(e)}")
@@ -257,7 +257,7 @@ def get_llm(model_name: str):
257
  model="microsoft/phi-3-mini-4k-instruct", # Use mini-4k which is smaller
258
  provider="hf-inference",
259
  api_key=hf_token,
260
- max_tokens=500
261
  )
262
  except Exception as e:
263
  logging.error(f"Failed to initialize Phi-3 model: {str(e)}")
@@ -284,7 +284,7 @@ def get_llm(model_name: str):
284
  model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
285
  provider="hf-inference",
286
  api_key=hf_token,
287
- max_tokens=500
288
  )
289
  except Exception as fallback_error:
290
  logging.error(f"Fallback model also failed: {str(fallback_error)}")
@@ -379,38 +379,45 @@ async def generate_business_plan(data: GenerateRequest):
379
  if data.business_idea:
380
  business_context = f"\nBusiness Idea: {data.business_idea}\n"
381
 
 
 
 
 
382
  plan_template_str = (
383
  "Based on the following responses to business questions:{business_context}\n"
384
  "{q_and_a}\n\n"
385
- "Generate a detailed business plan in Markdown format. Your response must include exactly the following sections and subheadings using proper Markdown syntax:\n\n"
 
 
 
386
  "## Executive Summary\n"
387
  "Provide a brief summary of the business, its purpose, and key objectives.\n\n"
388
  "## Market Analysis\n"
389
  "### Industry Overview\n"
390
- "Describe the overall industry trends and market dynamics.\n\n"
391
  "### Target Market\n"
392
- "Define the primary target audience, including demographics and psychographics.\n\n"
393
  "### Competitive Analysis\n"
394
- "Analyze the competitive landscape and explain what differentiates the business from competitors.\n\n"
395
  "## Operations Plan\n"
396
  "### Location\n"
397
- "Specify the business location(s) and rationale for the choice.\n\n"
398
  "### Distribution\n"
399
- "Explain the distribution channels and logistics plan for delivering the product or service.\n\n"
400
  "### Staffing\n"
401
- "Outline the staffing requirements and key roles necessary for operations.\n\n"
402
  "## Financial Plan\n"
403
  "### Revenue Streams\n"
404
- "Identify the primary and secondary sources of revenue.\n\n"
405
  "### Cost Structure\n"
406
- "Detail the major cost components and how costs will be managed.\n\n"
407
  "### Funding Requirements\n"
408
- "Specify the funding needed to launch and sustain the business.\n\n"
409
  "### Profitability\n"
410
- "Outline the financial projections and timeline to profitability.\n\n"
411
  "## Conclusion\n"
412
- "Summarize the vision, key takeaways, and future direction of the business.\n\n"
413
- "Follow this template exactly, and be concise."
414
  )
415
 
416
  plan_prompt = PromptTemplate(
@@ -422,6 +429,13 @@ async def generate_business_plan(data: GenerateRequest):
422
  # Get the LLM instance based on the selected model.
423
  logging.info(f"Initializing model: {data.model}")
424
  llm_selected = get_llm(data.model)
 
 
 
 
 
 
 
425
  plan_chain = LLMChain(llm=llm_selected, prompt=plan_prompt)
426
 
427
  logging.info(f"Generated prompt for business plan with model {data.model}")
@@ -430,8 +444,13 @@ async def generate_business_plan(data: GenerateRequest):
430
  logging.info(f"Generating business plan with model: {data.model}")
431
  full_plan = await asyncio.to_thread(plan_chain.run, {"q_and_a": q_and_a, "business_context": business_context})
432
  logging.info(f"Successfully generated business plan with model: {data.model}")
 
 
 
 
 
433
  return {
434
- "summary": "Generated Business Plan",
435
  "plan": full_plan,
436
  }
437
  except Exception as e:
 
84
  model: str
85
  business_idea: Optional[str] = ""
86
 
87
+ def generate_model_output(model: str, provider: str, api_key: str, prompt: str, max_tokens: int = 4000) -> str:
88
  """
89
  A helper function that wraps the Hugging Face Inference API call.
90
  """
 
92
  logging.info(f"Initializing InferenceClient with provider: {provider}")
93
  client = InferenceClient(provider=provider, api_key=api_key)
94
 
95
+ logging.info(f"Sending request to model: {model} with prompt length: {len(prompt)} and max_tokens: {max_tokens}")
96
  completion = client.chat.completions.create(
97
  model=model,
98
  messages=[{"role": "user", "content": prompt}],
99
  max_tokens=max_tokens,
100
  )
101
+ logging.info(f"Successfully received response from model: {model} with content length: {len(completion.choices[0].message.content)}")
102
  return completion.choices[0].message.content
103
  except Exception as e:
104
  error_message = f"Error generating output with model {model}: {str(e)}"
 
113
  model: str = None
114
  provider: str = "hf-inference"
115
  api_key: str = ""
116
+ max_tokens: int = 4000 # Increased from 500 to 4000 by default
117
 
118
+ def __init__(self, model: str, provider: str = "hf-inference", api_key: str = "", max_tokens: int = 4000):
119
  super().__init__()
120
  self.model = model
121
  self.provider = provider
 
174
  if not openai_api_key:
175
  logging.error("OPENAI_API_KEY environment variable not set")
176
  raise ValueError("OPENAI_API_KEY environment variable is required for GPT models")
177
+ return ChatOpenAI(model_name="gpt-4o-mini-2024-07-18", temperature=0.7, max_tokens=4000)
178
  elif model_name == "Llama":
179
  logging.info("Initializing Llama model - note this is a gated model and requires special access")
180
  try:
 
183
  model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
184
  provider="hf-inference",
185
  api_key=hf_token,
186
+ max_tokens=4000 # Increased token limit
187
  )
188
  except Exception as e:
189
  logging.error(f"Failed to initialize Llama model: {str(e)}")
 
198
  model="Qwen/Qwen1.5-0.5B-Chat", # Much smaller model (0.5B vs 7B)
199
  provider="hf-inference",
200
  api_key=hf_token,
201
+ max_tokens=4000
202
  )
203
  except Exception as e:
204
  error_msg = str(e)
 
217
  model="mistralai/Mistral-7B-Instruct-v0.3",
218
  provider="hf-inference",
219
  api_key=hf_token,
220
+ max_tokens=4000
221
  )
222
  except Exception as e:
223
  error_msg = str(e)
 
231
  model="mistralai/Mistral-7B-Instruct-v0.1",
232
  provider="hf-inference",
233
  api_key=hf_token,
234
+ max_tokens=4000
235
  )
236
  except Exception:
237
  pass
 
245
  model="google/gemma-2b-it",
246
  provider="hf-inference",
247
  api_key=hf_token,
248
+ max_tokens=4000
249
  )
250
  except Exception as e:
251
  logging.error(f"Failed to initialize Gemma model: {str(e)}")
 
257
  model="microsoft/phi-3-mini-4k-instruct", # Use mini-4k which is smaller
258
  provider="hf-inference",
259
  api_key=hf_token,
260
+ max_tokens=4000
261
  )
262
  except Exception as e:
263
  logging.error(f"Failed to initialize Phi-3 model: {str(e)}")
 
284
  model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
285
  provider="hf-inference",
286
  api_key=hf_token,
287
+ max_tokens=4000
288
  )
289
  except Exception as fallback_error:
290
  logging.error(f"Fallback model also failed: {str(fallback_error)}")
 
379
  if data.business_idea:
380
  business_context = f"\nBusiness Idea: {data.business_idea}\n"
381
 
382
+ # Add South Africa as the country context
383
+ country_context = "\nCountry: South Africa\n"
384
+ business_context += country_context
385
+
386
  plan_template_str = (
387
  "Based on the following responses to business questions:{business_context}\n"
388
  "{q_and_a}\n\n"
389
+ "Generate a detailed business plan in Markdown format specifically for a South African business. "
390
+ "All financial figures should be in South African Rand (ZAR). Consider South African business regulations, "
391
+ "market conditions, economic factors, and cultural context throughout the plan.\n\n"
392
+ "Your response must include exactly the following sections and subheadings using proper Markdown syntax:\n\n"
393
  "## Executive Summary\n"
394
  "Provide a brief summary of the business, its purpose, and key objectives.\n\n"
395
  "## Market Analysis\n"
396
  "### Industry Overview\n"
397
+ "Describe the overall industry trends and market dynamics in South Africa.\n\n"
398
  "### Target Market\n"
399
+ "Define the primary target audience in South Africa, including demographics and psychographics.\n\n"
400
  "### Competitive Analysis\n"
401
+ "Analyze the South African competitive landscape and explain what differentiates the business from competitors.\n\n"
402
  "## Operations Plan\n"
403
  "### Location\n"
404
+ "Specify the business location(s) in South Africa and rationale for the choice.\n\n"
405
  "### Distribution\n"
406
+ "Explain the distribution channels and logistics plan for delivering the product or service within South Africa.\n\n"
407
  "### Staffing\n"
408
+ "Outline the staffing requirements and key roles necessary for operations, including considerations for South African labor laws.\n\n"
409
  "## Financial Plan\n"
410
  "### Revenue Streams\n"
411
+ "Identify the primary and secondary sources of revenue, with all figures in South African Rand (ZAR).\n\n"
412
  "### Cost Structure\n"
413
+ "Detail the major cost components and how costs will be managed, with consideration for South African pricing and expenses.\n\n"
414
  "### Funding Requirements\n"
415
+ "Specify the funding needed to launch and sustain the business in South Africa, including any local funding options.\n\n"
416
  "### Profitability\n"
417
+ "Outline the financial projections and timeline to profitability within the South African market.\n\n"
418
  "## Conclusion\n"
419
+ "Summarize the vision, key takeaways, and future direction of the business in South Africa.\n\n"
420
+ "Make sure to complete ALL sections above. Do not cut off your response in the middle of a section. All financial figures should be in South African Rand (ZAR) with appropriate market rates."
421
  )
422
 
423
  plan_prompt = PromptTemplate(
 
429
  # Get the LLM instance based on the selected model.
430
  logging.info(f"Initializing model: {data.model}")
431
  llm_selected = get_llm(data.model)
432
+
433
+ # Ensure max_tokens is set high enough to avoid truncation
434
+ if hasattr(llm_selected, 'max_tokens'):
435
+ original_max_tokens = llm_selected.max_tokens
436
+ llm_selected.max_tokens = 6000 # Increase max tokens to ensure full completion
437
+ logging.info(f"Increased max_tokens from {original_max_tokens} to {llm_selected.max_tokens}")
438
+
439
  plan_chain = LLMChain(llm=llm_selected, prompt=plan_prompt)
440
 
441
  logging.info(f"Generated prompt for business plan with model {data.model}")
 
444
  logging.info(f"Generating business plan with model: {data.model}")
445
  full_plan = await asyncio.to_thread(plan_chain.run, {"q_and_a": q_and_a, "business_context": business_context})
446
  logging.info(f"Successfully generated business plan with model: {data.model}")
447
+
448
+ # Check if plan seems truncated
449
+ if "## Conclusion" not in full_plan:
450
+ logging.warning("Business plan appears to be truncated (missing Conclusion section)")
451
+
452
  return {
453
+ "summary": "Generated Business Plan for South Africa",
454
  "plan": full_plan,
455
  }
456
  except Exception as e: