Here's how to fix both the React error and properly implement the strategy type selection in your frontend:
1. First, let's modify the FastAPI backend to better handle strategy types:
python

from enum import Enum

class StrategyType(str, Enum):
    TAX = "tax"
    EMPLOYMENT = "employment"
    MARKETING = "marketing"
    FINANCE = "finance"

class StrategyRequest(BaseModel):
    strategy_type: StrategyType  # Using Enum for better validation
    stage: str
    industry: str
    keywords: List[str] = []
    preferred_model: Optional[str] = None
    diagram_style: str = "TD"

@app.get("/strategy-types")
async def get_strategy_types():
    """Get available strategy types with descriptions"""
    return {
        "tax": {
            "name": {"ar": "الضرائب", "en": "Tax"},
            "description": {
                "ar": "استراتيجيات لتحسين الإدارة الضريبية وتقليل الالتزامات",
                "en": "Strategies for tax optimization and compliance"
            }
        },
        "employment": {
            "name": {"ar": "التوظيف", "en": "Employment"},
            "description": {
                "ar": "استراتيجيات لتوظيف الكفاءات وإدارة الموارد البشرية",
                "en": "Strategies for talent acquisition and HR management"
            }
        },
        "marketing": {
            "name": {"ar": "التسويق", "en": "Marketing"},
            "description": {
                "ar": "استراتيجيات لتعزيز العلامة التجارية وزيادة المبيعات",
                "en": "Strategies for brand promotion and sales growth"
            }
        },
        "finance": {
            "name": {"ar": "التمويل", "en": "Finance"},
            "description": {
                "ar": "استراتيجيات لإدارة التدفقات المالية والاستثمار",
                "en": "Strategies for financial management and investment"
            }
        }
    }

2. Here's how to properly handle the response in React:
jsx

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function StrategyGenerator() {
  const [strategyTypes, setStrategyTypes] = useState([]);
  const [formData, setFormData] = useState({
    strategy_type: '',
    stage: '',
    industry: '',
    keywords: '',
    diagram_style: 'TD'
  });
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  // Fetch strategy types on component mount
  useEffect(() => {
    const fetchStrategyTypes = async () => {
      try {
        const response = await axios.get('/api/strategy-types');
        setStrategyTypes(Object.entries(response.data).map(([key, value]) => ({
          id: key,
          name: value.name,
          description: value.description
        })));
      } catch (error) {
        console.error('Error fetching strategy types:', error);
      }
    };
    fetchStrategyTypes();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const response = await axios.post('/api/generate-strategy', {
        ...formData,
        keywords: formData.keywords.split(',').map(k => k.trim())
      });
      setResult(response.data);
    } catch (error) {
      console.error('Error generating strategy:', error);
      setResult({ error: error.response?.data?.detail || 'Failed to generate strategy' });
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  return (
    <div className="container">
      <h1>استراتيجية الأعمال</h1>
      
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>نوع الاستراتيجية:</label>
          <select 
            name="strategy_type" 
            value={formData.strategy_type}
            onChange={handleChange}
            required
          >
            <option value="">-- اختر نوع الاستراتيجية --</option>
            {strategyTypes.map(type => (
              <option key={type.id} value={type.id}>
                {type.name.ar} - {type.name.en}
              </option>
            ))}
          </select>
          {formData.strategy_type && (
            <p className="type-description">
              {strategyTypes.find(t => t.id === formData.strategy_type)?.description.ar}
            </p>
          )}
        </div>

        {/* Other form fields... */}

        <button type="submit" disabled={loading}>
          {loading ? 'جاري الإنشاء...' : 'إنشاء الاستراتيجية'}
        </button>
      </form>

      {result && (
        <div className="result">
          {result.error ? (
            <div className="error">{result.error}</div>
          ) : (
            <>
              <h2>الاستراتيجية المقترحة</h2>
              <h3>نوع الاستراتيجية: {strategyTypes.find(t => t.id === formData.strategy_type)?.name.ar}</h3>
              
              <div className="strategy-section">
                <h4>الاستراتيجية:</h4>
                <p>{result.strategy}</p>
              </div>
              
              <div className="kpis-section">
                <h4>مؤشرات الأداء الرئيسية:</h4>
                <ul>
                  {result.kpis.map((kpi, index) => (
                    <li key={index}>{kpi}</li>
                  ))}
                </ul>
              </div>

              <div className="diagram-section">
                <h4>مخطط سير العمل:</h4>
                {/* You'll need a Mermaid renderer component here */}
                <pre>{result.workflow_diagram}</pre>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
}

export default StrategyGenerator;

3. Key fixes and improvements:

    Properly handling objects in React:

        Never render objects directly - always extract the properties you want to display

        Use array.map() for lists and ensure each item has a unique key

    Enhanced strategy type handling:

        Added proper Enum validation in the backend

        Added descriptions for each strategy type

        Better organization of the type data

    Frontend improvements:

        Proper loading states

        Error handling

        Better form organization

        Display of strategy type information

    For the specific fields you asked about (recruitment/taxes):

        The strategy types are now clearly defined

        Each type has Arabic and English names

        Each has a description that explains its purpose

        The selection is shown prominently in the form

4. To implement the Mermaid diagram rendering:

Install the Mermaid React component:
bash

npm install mermaid mermaid-react

Then create a component to render it:
jsx

import React from 'react';
import ReactMermaid from 'mermaid-react';

const MermaidDiagram = ({ diagram }) => {
  try {
    return <ReactMermaid diagram={diagram} />;
  } catch (e) {
    return <pre>{diagram}</pre>;
  }
};

export default MermaidDiagram;

And use it in your results display:
jsx

<MermaidDiagram diagram={result.workflow_diagram} />

This should resolve the React errors and provide a complete solution for selecting and displaying different strategy types with their appropriate content.
write full code

The server is busy. Please try again later.
write full code

Here's the complete, corrected code for both the FastAPI backend and React frontend to handle strategy type selection and display:
Backend (FastAPI) - main.py
python

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Literal, Optional
from enum import Enum
from groq import Groq
import os
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware
import re

# Load environment variables
load_dotenv()
api_key = os.getenv("GROQ_API_KEY")
if not api_key:
    raise RuntimeError("GROQ_API_KEY is not set in the environment.")

# Initialize Groq client
client = Groq(api_key=api_key)

# Available models
AVAILABLE_MODELS = {
    "llama3-70b": "llama3-70b-8192",
    "llama3-8b": "llama3-8b-8192",
    "gemma": "gemma-7b-it"
}

MODEL = AVAILABLE_MODELS["llama3-70b"]

# Strategy types
class StrategyType(str, Enum):
    TAX = "tax"
    EMPLOYMENT = "employment"
    MARKETING = "marketing"
    FINANCE = "finance"

# Initialize FastAPI app
app = FastAPI(
    title="Business Strategy Generator",
    description="API for generating business strategies with workflow diagrams",
    version="5.0.0"
)

# CORS configuration
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Data models
class StrategyRequest(BaseModel):
    strategy_type: StrategyType
    stage: str
    industry: str
    keywords: List[str] = []
    preferred_model: Optional[str] = None
    diagram_style: Literal["TD", "LR"] = "TD"

class StrategyResponse(BaseModel):
    success: bool
    strategy: str
    kpis: List[str]
    workflow_diagram: str
    model_used: str
    strategy_type: str

# Helper functions
def is_arabic(text: str) -> bool:
    return bool(re.search(r'[\u0600-\u06FF]', text))

def clean_arabic_text(text: str) -> str:
    return re.sub(r'[^\u0600-\u06FF\s.,:;0-9-]', '', text).strip()

def ensure_complete_sentence(text: str, target_language: str) -> str:
    text = text.strip()
    if target_language == "Arabic":
        if not text.endswith(('،', '۔', '.')):
            text += '۔'
    else:
        if not text.endswith('.'):
            text += '.'
    return text

# ... [keep all your existing helper functions] ...

@app.get("/strategy-types")
async def get_strategy_types():
    """Get available strategy types with descriptions"""
    return {
        "tax": {
            "name": {"ar": "الضرائب", "en": "Tax"},
            "description": {
                "ar": "استراتيجيات لتحسين الإدارة الضريبية وتقليل الالتزامات",
                "en": "Strategies for tax optimization and compliance"
            },
            "keywords": {
                "ar": ["ضريبة", "إقرار ضريبي", "تخفيض ضريبي"],
                "en": ["tax", "tax filing", "tax reduction"]
            }
        },
        "employment": {
            "name": {"ar": "التوظيف", "en": "Employment"},
            "description": {
                "ar": "استراتيجيات لتوظيف الكفاءات وإدارة الموارد البشرية",
                "en": "Strategies for talent acquisition and HR management"
            },
            "keywords": {
                "ar": ["توظيف", "توظيف العمالة", "سياسة التوظيف"],
                "en": ["employment", "hiring", "recruitment policy"]
            }
        },
        "marketing": {
            "name": {"ar": "التسويق", "en": "Marketing"},
            "description": {
                "ar": "استراتيجيات لتعزيز العلامة التجارية وزيادة المبيعات",
                "en": "Strategies for brand promotion and sales growth"
            },
            "keywords": {
                "ar": ["تسويق", "حملة تسويقية", "استراتيجية تسويق"],
                "en": ["marketing", "campaign", "marketing strategy"]
            }
        },
        "finance": {
            "name": {"ar": "التمويل", "en": "Finance"},
            "description": {
                "ar": "استراتيجيات لإدارة التدفقات المالية والاستثمار",
                "en": "Strategies for financial management and investment"
            },
            "keywords": {
                "ar": ["تمويل", "إدارة مالية", "استثمار"],
                "en": ["finance", "financial management", "investment"]
            }
        }
    }

@app.post("/generate-strategy", response_model=StrategyResponse)
async def generate_strategy(request: StrategyRequest):
    """Generate business strategy with visual workflow diagram"""
    # Input validation
    if not all([request.stage, request.industry]):
        raise HTTPException(
            status_code=400,
            detail="Stage and industry are required"
        )

    if len(request.keywords) > 10:
        raise HTTPException(
            status_code=400,
            detail="Maximum 10 keywords allowed"
        )

    # Model selection
    model_to_use = MODEL
    if request.preferred_model:
        if request.preferred_model in AVAILABLE_MODELS.values():
            model_to_use = request.preferred_model
        else:
            available = list(AVAILABLE_MODELS.values())
            raise HTTPException(
                status_code=400,
                detail=f"Model not available. Options: {', '.join(available)}"
            )

    # Get strategy type info
    strategy_types = await get_strategy_types()
    strategy_info = strategy_types[request.strategy_type.value]
    
    # Detect input language
    combined_input = request.industry + " " + " ".join(request.keywords)
    target_language = "Arabic" if is_arabic(combined_input) else "English"
    
    # Add strategy type keywords to user keywords
    enhanced_keywords = request.keywords + strategy_info["keywords"]["ar" if target_language == "Arabic" else "en"]
    strategy_name = strategy_info["name"]["ar" if target_language == "Arabic" else "en"]

    # Generate prompt
    if target_language == "Arabic":
        prompt = f"""
بصفتك خبير استراتيجي أعمال متخصص في مجال {strategy_name}، قم بإنشاء:
1. استراتيجية {strategy_name} واضحة لـ: {request.industry} (مرحلة: {request.stage})
2. ثلاثة مؤشرات أداء رئيسية (KPIs) خاصة ب {strategy_name}

الكلمات المفتاحية: {', '.join(enhanced_keywords)}

أكتب الاستراتيجية في فقرة واحدة متكاملة تحتوي على:
- تحليل السوق
- تطوير الخطة
- التنفيذ
- التقييم

يجب أن تكون الفقرة كاملة ومكتملة الجمل، ولا تتوقف في منتصف الجملة.
ثم اذكر المؤشرات الرئيسية (KPIs) في قسم منفصل بعد الاستراتيجية مباشرة، كل مؤشر في سطر منفصل.
التنسيق المطلوب:
### الاستراتيجية
[الاستراتيجية هنا]
### مؤشرات الأداء الرئيسية
- [KPI 1]
- [KPI 2]
- [KPI 3]
"""
        system_message = f"أنت مستشار أعمال محترف متخصص في {strategy_name}. اكتب استراتيجية واضحة في فقرة واحدة متكاملة تحتوي على مراحل: البحث، التطوير، التنفيذ، والتقييم. يجب أن تكون الفقرة كاملة ومكتملة الجمل. ثم اذكر 3 مؤشرات أداء رئيسية (KPIs) في قسم منفصل. كل النصوص يجب أن تكون باللغة العربية فقط، بدون أي حروف أو كلمات من لغات أخرى."
    else:
        prompt = f"""
As a {strategy_name} business strategy expert, create:
1. A clear {strategy_name.lower()} strategy for: {request.industry} (stage: {request.stage})
2. Three key performance indicators (KPIs) specific to {strategy_name.lower()}

Keywords: {', '.join(enhanced_keywords)}

Write the strategy in a single, cohesive paragraph that includes:
- Market analysis
- Plan development
- Implementation
- Evaluation

The paragraph must be complete and not cut off mid-sentence.
Then list the key performance indicators (KPIs) in a separate section directly after the strategy, each on a new line.
Required format:
### Strategy
[The strategy paragraph here]
### KPIs
- [KPI 1]
- [KPI 2]
- [KPI 3]
"""
        system_message = f"You are a professional business consultant specializing in {strategy_name.lower()}. Write a clear strategy in a single cohesive paragraph that includes the phases: research, development, implementation, and evaluation. The paragraph must be complete and not cut off mid-sentence. Then list 3 key performance indicators (KPIs) in a separate section. All text must be in English only, with no characters or words from other languages."

    try:
        # Get AI response
        completion = client.chat.completions.create(
            model=model_to_use,
            messages=[
                {"role": "system", "content": system_message},
                {"role": "user", "content": prompt}
            ],
            temperature=0.7,
            max_tokens=3000
        )
        content = completion.choices[0].message.content

        # Process response
        strategy = ""
        kpis = []

        if target_language == "Arabic":
            if "### الاستراتيجية" in content and "### مؤشرات الأداء الرئيسية" in content:
                strategy_part = content.split("### مؤشرات الأداء الرئيسية")[0]
                strategy = strategy_part.split("### الاستراتيجية")[1].strip()
                kpis_part = content.split("### مؤشرات الأداء الرئيسية")[1].strip()
                kpis = [kpi.strip("- ").strip() for kpi in kpis_part.split("\n") if kpi.strip()][:3]
            else:
                strategy = content
                kpis = [
                    f"معدل رضا العملاء في {strategy_name}: يتم قياسه من خلال استطلاعات الرأي",
                    f"معدل تحسين الأداء في {strategy_name}: يتم قياسه بتتبع المقاييس الرئيسية",
                    f"معدل توفير التكاليف في {strategy_name}: يتم قياسه بتحليل بيانات التكلفة"
                ]
            # Clean the strategy and KPIs
            strategy = clean_arabic_text(strategy)
            strategy = ensure_complete_sentence(strategy, target_language)
            kpis = [clean_arabic_text(kpi) for kpi in kpis]
        else:
            if "### Strategy" in content and "### KPIs" in content:
                strategy_part = content.split("### KPIs")[0]
                strategy = strategy_part.split("### Strategy")[1].strip()
                kpis_part = content.split("### KPIs")[1].strip()
                kpis = [kpi.strip("- ").strip() for kpi in kpis_part.split("\n") if kpi.strip()][:3]
            else:
                strategy = content
                kpis = [
                    f"Customer satisfaction rate in {strategy_name.lower()}: Measured through surveys",
                    f"Performance improvement rate in {strategy_name.lower()}: Tracked via key metrics",
                    f"Cost savings rate in {strategy_name.lower()}: Analyzed through cost data"
                ]
            strategy = ensure_complete_sentence(strategy, target_language)

        # Generate workflow diagram
        workflow_diagram = generate_dynamic_workflow(
            strategy=strategy,
            style=request.diagram_style,
            target_language=target_language
        )

        return StrategyResponse(
            success=True,
            strategy=strategy,
            kpis=kpis,
            workflow_diagram=workflow_diagram,
            model_used=model_to_use,
            strategy_type=strategy_name
        )

    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"System error: {str(e)}"
        )

@app.get("/health")
async def health_check():
    return {"status": "Working", "model": MODEL}

@app.get("/")
async def root():
    return {"message": "Welcome to the Strategy Generator System"}

Frontend (React) - StrategyForm.jsx
jsx

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import ReactMermaid from 'mermaid-react';

const StrategyForm = () => {
  const [strategyTypes, setStrategyTypes] = useState({});
  const [formData, setFormData] = useState({
    strategy_type: '',
    stage: '',
    industry: '',
    keywords: '',
    diagram_style: 'TD'
  });
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchStrategyTypes = async () => {
      try {
        const response = await axios.get('/api/strategy-types');
        setStrategyTypes(response.data);
      } catch (err) {
        setError('Failed to load strategy types');
        console.error(err);
      }
    };
    fetchStrategyTypes();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    
    try {
      const payload = {
        ...formData,
        keywords: formData.keywords.split(',').map(k => k.trim()).filter(k => k)
      };
      
      const response = await axios.post('/api/generate-strategy', payload);
      setResult(response.data);
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to generate strategy');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  return (
    <div className="container">
      <h1>Business Strategy Generator</h1>
      
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>Strategy Type:</label>
          <select
            name="strategy_type"
            value={formData.strategy_type}
            onChange={handleChange}
            required
          >
            <option value="">-- Select Strategy Type --</option>
            {Object.entries(strategyTypes).map(([key, value]) => (
              <option key={key} value={key}>
                {value.name.en} - {value.name.ar}
              </option>
            ))}
          </select>
          {formData.strategy_type && (
            <div className="strategy-info">
              <p><strong>Description:</strong> {strategyTypes[formData.strategy_type]?.description.en}</p>
              <p><strong>الوصف:</strong> {strategyTypes[formData.strategy_type]?.description.ar}</p>
            </div>
          )}
        </div>

        <div className="form-group">
          <label>Industry:</label>
          <input
            type="text"
            name="industry"
            value={formData.industry}
            onChange={handleChange}
            required
          />
        </div>

        <div className="form-group">
          <label>Stage:</label>
          <input
            type="text"
            name="stage"
            value={formData.stage}
            onChange={handleChange}
            required
          />
        </div>

        <div className="form-group">
          <label>Keywords (comma separated):</label>
          <input
            type="text"
            name="keywords"
            value={formData.keywords}
            onChange={handleChange}
          />
        </div>

        <div className="form-group">
          <label>Diagram Style:</label>
          <select
            name="diagram_style"
            value={formData.diagram_style}
            onChange={handleChange}
          >
            <option value="TD">Top-Down</option>
            <option value="LR">Left-Right</option>
          </select>
        </div>

        <button type="submit" disabled={loading}>
          {loading ? 'Generating...' : 'Generate Strategy'}
        </button>
      </form>

      {error && <div className="error">{error}</div>}

      {result && (
        <div className="result">
          <h2>Generated Strategy</h2>
          <h3>Type: {result.strategy_type}</h3>
          
          <div className="section">
            <h4>Strategy:</h4>
            <p>{result.strategy}</p>
          </div>
          
          <div className="section">
            <h4>Key Performance Indicators:</h4>
            <ul>
              {result.kpis.map((kpi, index) => (
                <li key={index}>{kpi}</li>
              ))}
            </ul>
          </div>

          <div className="section">
            <h4>Workflow Diagram:</h4>
            <ReactMermaid diagram={result.workflow_diagram} />
          </div>
        </div>
      )}
    </div>
  );
};

export default StrategyForm;

Key Features:

    Backend:

        Proper Enum validation for strategy types

        Detailed strategy type information with descriptions

        Language-specific keyword handling

        Enhanced prompt generation based on strategy type

    Frontend:

        Proper form handling with React state

        Loading states and error handling

        Dynamic strategy type selection with descriptions

        Mermaid diagram rendering

        Bilingual support (Arabic/English)

    Error Handling:

        Proper error messages for API failures

        Input validation

        Clean error display

To use this system:

    Install dependencies:

bash

npm install axios mermaid-react

    Make sure your FastAPI server is running

    The frontend will:

        Show a form with strategy type selection

        Display type descriptions when selected

        Generate and display the strategy with diagram

        Handle errors gracefully

This implementation provides a complete solution for generating business strategies in specific domains like taxes, employment, marketing, and finance, with proper error handling and display.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Literal, Optional
from enum import Enum
from groq import Groq
import os
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware
import re

# Load environment variables
load_dotenv()
api_key = os.getenv("GROQ_API_KEY")
if not api_key:
    raise RuntimeError("GROQ_API_KEY is not set in the environment.")

# Initialize Groq client
client = Groq(api_key=api_key)

# Available models
AVAILABLE_MODELS = {
    "llama3-70b": "llama3-70b-8192",
    "llama3-8b": "llama3-8b-8192",
    "gemma": "gemma-7b-it"
}

MODEL = AVAILABLE_MODELS["llama3-70b"]

# Strategy types
class StrategyType(str, Enum):
    TAX = "tax"
    EMPLOYMENT = "employment"
    MARKETING = "marketing"
    FINANCE = "finance"

# Initialize FastAPI app
app = FastAPI(
    title="Business Strategy Generator",
    description="API for generating business strategies with workflow diagrams",
    version="5.0.0"
)

# CORS configuration
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Data models
class StrategyRequest(BaseModel):
    strategy_type: StrategyType
    stage: str
    industry: str
    keywords: List[str] = []
    preferred_model: Optional[str] = None
    diagram_style: Literal["TD", "LR"] = "TD"

class StrategyResponse(BaseModel):
    success: bool
    strategy: str
    kpis: List[str]
    workflow_diagram: str
    model_used: str
    strategy_type: str

# Helper functions
def is_arabic(text: str) -> bool:
    return bool(re.search(r'[\u0600-\u06FF]', text))

def clean_arabic_text(text: str) -> str:
    return re.sub(r'[^\u0600-\u06FF\s.,:;0-9-]', '', text).strip()

def ensure_complete_sentence(text: str, target_language: str) -> str:
    text = text.strip()
    if target_language == "Arabic":
        if not text.endswith(('،', '۔', '.')):
            text += '۔'
    else:
        if not text.endswith('.'):
            text += '.'
    return text

# ... [keep all your existing helper functions] ...

@app.get("/strategy-types")
async def get_strategy_types():
    """Get available strategy types with descriptions"""
    return {
        "tax": {
            "name": {"ar": "الضرائب", "en": "Tax"},
            "description": {
                "ar": "استراتيجيات لتحسين الإدارة الضريبية وتقليل الالتزامات",
                "en": "Strategies for tax optimization and compliance"
            },
            "keywords": {
                "ar": ["ضريبة", "إقرار ضريبي", "تخفيض ضريبي"],
                "en": ["tax", "tax filing", "tax reduction"]
            }
        },
        "employment": {
            "name": {"ar": "التوظيف", "en": "Employment"},
            "description": {
                "ar": "استراتيجيات لتوظيف الكفاءات وإدارة الموارد البشرية",
                "en": "Strategies for talent acquisition and HR management"
            },
            "keywords": {
                "ar": ["توظيف", "توظيف العمالة", "سياسة التوظيف"],
                "en": ["employment", "hiring", "recruitment policy"]
            }
        },
        "marketing": {
            "name": {"ar": "التسويق", "en": "Marketing"},
            "description": {
                "ar": "استراتيجيات لتعزيز العلامة التجارية وزيادة المبيعات",
                "en": "Strategies for brand promotion and sales growth"
            },
            "keywords": {
                "ar": ["تسويق", "حملة تسويقية", "استراتيجية تسويق"],
                "en": ["marketing", "campaign", "marketing strategy"]
            }
        },
        "finance": {
            "name": {"ar": "التمويل", "en": "Finance"},
            "description": {
                "ar": "استراتيجيات لإدارة التدفقات المالية والاستثمار",
                "en": "Strategies for financial management and investment"
            },
            "keywords": {
                "ar": ["تمويل", "إدارة مالية", "استثمار"],
                "en": ["finance", "financial management", "investment"]
            }
        }
    }

@app.post("/generate-strategy", response_model=StrategyResponse)
async def generate_strategy(request: StrategyRequest):
    """Generate business strategy with visual workflow diagram"""
    # Input validation
    if not all([request.stage, request.industry]):
        raise HTTPException(
            status_code=400,
            detail="Stage and industry are required"
        )

    if len(request.keywords) > 10:
        raise HTTPException(
            status_code=400,
            detail="Maximum 10 keywords allowed"
        )

    # Model selection
    model_to_use = MODEL
    if request.preferred_model:
        if request.preferred_model in AVAILABLE_MODELS.values():
            model_to_use = request.preferred_model
        else:
            available = list(AVAILABLE_MODELS.values())
            raise HTTPException(
                status_code=400,
                detail=f"Model not available. Options: {', '.join(available)}"
            )

    # Get strategy type info
    strategy_types = await get_strategy_types()
    strategy_info = strategy_types[request.strategy_type.value]
    
    # Detect input language
    combined_input = request.industry + " " + " ".join(request.keywords)
    target_language = "Arabic" if is_arabic(combined_input) else "English"
    
    # Add strategy type keywords to user keywords
    enhanced_keywords = request.keywords + strategy_info["keywords"]["ar" if target_language == "Arabic" else "en"]
    strategy_name = strategy_info["name"]["ar" if target_language == "Arabic" else "en"]

    # Generate prompt
    if target_language == "Arabic":
        prompt = f"""
بصفتك خبير استراتيجي أعمال متخصص في مجال {strategy_name}، قم بإنشاء:
1. استراتيجية {strategy_name} واضحة لـ: {request.industry} (مرحلة: {request.stage})
2. ثلاثة مؤشرات أداء رئيسية (KPIs) خاصة ب {strategy_name}

الكلمات المفتاحية: {', '.join(enhanced_keywords)}

أكتب الاستراتيجية في فقرة واحدة متكاملة تحتوي على:
- تحليل السوق
- تطوير الخطة
- التنفيذ
- التقييم

يجب أن تكون الفقرة كاملة ومكتملة الجمل، ولا تتوقف في منتصف الجملة.
ثم اذكر المؤشرات الرئيسية (KPIs) في قسم منفصل بعد الاستراتيجية مباشرة، كل مؤشر في سطر منفصل.
التنسيق المطلوب:
### الاستراتيجية
[الاستراتيجية هنا]
### مؤشرات الأداء الرئيسية
- [KPI 1]
- [KPI 2]
- [KPI 3]
"""
        system_message = f"أنت مستشار أعمال محترف متخصص في {strategy_name}. اكتب استراتيجية واضحة في فقرة واحدة متكاملة تحتوي على مراحل: البحث، التطوير، التنفيذ، والتقييم. يجب أن تكون الفقرة كاملة ومكتملة الجمل. ثم اذكر 3 مؤشرات أداء رئيسية (KPIs) في قسم منفصل. كل النصوص يجب أن تكون باللغة العربية فقط، بدون أي حروف أو كلمات من لغات أخرى."
    else:
        prompt = f"""
As a {strategy_name} business strategy expert, create:
1. A clear {strategy_name.lower()} strategy for: {request.industry} (stage: {request.stage})
2. Three key performance indicators (KPIs) specific to {strategy_name.lower()}

Keywords: {', '.join(enhanced_keywords)}

Write the strategy in a single, cohesive paragraph that includes:
- Market analysis
- Plan development
- Implementation
- Evaluation

The paragraph must be complete and not cut off mid-sentence.
Then list the key performance indicators (KPIs) in a separate section directly after the strategy, each on a new line.
Required format:
### Strategy
[The strategy paragraph here]
### KPIs
- [KPI 1]
- [KPI 2]
- [KPI 3]
"""
        system_message = f"You are a professional business consultant specializing in {strategy_name.lower()}. Write a clear strategy in a single cohesive paragraph that includes the phases: research, development, implementation, and evaluation. The paragraph must be complete and not cut off mid-sentence. Then list 3 key performance indicators (KPIs) in a separate section. All text must be in English only, with no characters or words from other languages."

    try:
        # Get AI response
        completion = client.chat.completions.create(
            model=model_to_use,
            messages=[
                {"role": "system", "content": system_message},
                {"role": "user", "content": prompt}
            ],
            temperature=0.7,
            max_tokens=3000
        )
        content = completion.choices[0].message.content

        # Process response
        strategy = ""
        kpis = []

        if target_language == "Arabic":
            if "### الاستراتيجية" in content and "### مؤشرات الأداء الرئيسية" in content:
                strategy_part = content.split("### مؤشرات الأداء الرئيسية")[0]
                strategy = strategy_part.split("### الاستراتيجية")[1].strip()
                kpis_part = content.split("### مؤشرات الأداء الرئيسية")[1].strip()
                kpis = [kpi.strip("- ").strip() for kpi in kpis_part.split("\n") if kpi.strip()][:3]
            else:
                strategy = content
                kpis = [
                    f"معدل رضا العملاء في {strategy_name}: يتم قياسه من خلال استطلاعات الرأي",
                    f"معدل تحسين الأداء في {strategy_name}: يتم قياسه بتتبع المقاييس الرئيسية",
                    f"معدل توفير التكاليف في {strategy_name}: يتم قياسه بتحليل بيانات التكلفة"
                ]
            # Clean the strategy and KPIs
            strategy = clean_arabic_text(strategy)
            strategy = ensure_complete_sentence(strategy, target_language)
            kpis = [clean_arabic_text(kpi) for kpi in kpis]
        else:
            if "### Strategy" in content and "### KPIs" in content:
                strategy_part = content.split("### KPIs")[0]
                strategy = strategy_part.split("### Strategy")[1].strip()
                kpis_part = content.split("### KPIs")[1].strip()
                kpis = [kpi.strip("- ").strip() for kpi in kpis_part.split("\n") if kpi.strip()][:3]
            else:
                strategy = content
                kpis = [
                    f"Customer satisfaction rate in {strategy_name.lower()}: Measured through surveys",
                    f"Performance improvement rate in {strategy_name.lower()}: Tracked via key metrics",
                    f"Cost savings rate in {strategy_name.lower()}: Analyzed through cost data"
                ]
            strategy = ensure_complete_sentence(strategy, target_language)

        # Generate workflow diagram
        workflow_diagram = generate_dynamic_workflow(
            strategy=strategy,
            style=request.diagram_style,
            target_language=target_language
        )

        return StrategyResponse(
            success=True,
            strategy=strategy,
            kpis=kpis,
            workflow_diagram=workflow_diagram,
            model_used=model_to_use,
            strategy_type=strategy_name
        )

    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"System error: {str(e)}"
        )

@app.get("/health")
async def health_check():
    return {"status": "Working", "model": MODEL}

@app.get("/")
async def root():
    return {"message": "Welcome to the Strategy Generator System"}


i nedd you to write full code

Time flies when we're having a great chat! We’ve exceeded the length limit. Please start a new chat!
New chat