o
    fh!                      @   s   d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	m
Z
mZ d dlmZ d dlmZ d dlZejejd eeZG d	d
 d
eZddedee dededee	ee
f  f
ddZdd Zedkrke  dS dS )    N)Ollama)PromptTemplate)JsonOutputParser)ListDictAnyTuple)	dataclass)Enum)levelc                   @   s   e Zd ZdZdZdZdZdS )
SkillLevel            N)__name__
__module____qualname__BEGINNERINTERMEDIATEADVANCEDEXPERT r   r   J/var/www/eduai.edurigo.com/doc_train/edurigo_ai/TNA/production/tna_step.pyr      s
    r   
gemma3:12bpromptavailable_departments
model_nametemperaturereturnc                    s  t ||d}d|}d|  d| d| d| d	}ztd| d	| d
d  d ||}| }|dr@|dd
 }|drK|d
d }| }t	|}	g }
|	
d|r_|d nd}||vrwtd| d |ru|d nd}|	
dg D ] zqt fdddD std   W q} d  dd}|dd tD vrtd  d  d! d"}n d }t d# }d$|  krd%ksn td&| d' td$td%|}|
 d(  ||| 
d)d*d+ W q} ttfy } ztd,  d	|  W Y d
}~q}d
}~ww d-|	v r td.|	d-   td/t|
 d0| d1 |
W S  tjyV } ztd2|  td3|  g W  Y d
}~S d
}~w tyr } ztd4|  g W  Y d
}~S d
}~ww )5a  
    Extract required skills from a business prompt using Ollama LLM
    
    Args:
        prompt (str): Business objective or challenge description
        available_departments (List[str]): List of valid department names from your database
        model_name (str): Ollama model to use (default: "gemma3:12b")
        temperature (float): Model temperature for consistency (default: 0)
    
    Returns:
        List[Dict]: List of skills with name, required_level, weight, and department
        
    Example:
        departments = ["Sales", "Marketing", "Customer Service", "IT", "HR", "Finance"]
        skills = extract_skills_from_prompt("I want to improve my sales revenue", departments)
    )modelr   z, z
You are a Training Needs Analysis expert. Analyze the following business objective and identify the specific skills needed to achieve it.

Business Objective: zB

IMPORTANT: You must choose the department from this exact list: aR  
- Choose only ONE department that is most relevant to this objective
- Use the exact name from the list (case-sensitive)
- If multiple departments could be involved, pick the PRIMARY one most responsible for this objective

Return a JSON response with the following structure:
{
    "department": "ONE department from the provided list: as  ",
    "skills": [
        {
            "name": "Skill name",
            "required_level": "Beginner|Intermediate|Advanced|Expert",
            "weight": 0.0-1.0,
            "description": "Why this skill is needed"
        }
    ],
    "reasoning": "Brief explanation of why you chose this department and these skills"
}

Rules:
1. Department MUST be exactly one of: aN  
2. Focus on 3-6 most critical skills for the chosen department
3. Weight represents business importance (1.0 = most critical)
4. Required_level should match the complexity of the objective
5. Be specific with skill names (avoid generic terms)
6. Return ONLY valid JSON, no additional text

Example for "improve customer satisfaction" with departments [Sales, Marketing, Customer Service]:
{
    "department": "Customer Service",
    "skills": [
        {"name": "Active Listening", "required_level": "Expert", "weight": 0.9, "description": "Essential for understanding customer concerns"},
        {"name": "Problem Resolution", "required_level": "Advanced", "weight": 0.8, "description": "Needed to solve customer issues effectively"}
    ],
    "reasoning": "Customer Service is the primary department responsible for customer satisfaction"
}
zAnalyzing prompt with z: N2   z...z```json   z```
departmentr   Generalz!LLM returned invalid department 'z', using first availableskillsc                 3   s    | ]}| v V  qd S )Nr   ).0keyskillr   r   	<genexpr>v   s    z-extract_skills_from_prompt.<locals>.<genexpr>)namerequired_levelweightzSkipping incomplete skill: r-    _c                 S   s   g | ]}|j qS r   )r,   )r'   r   r   r   r   
<listcomp>|   s    z.extract_skills_from_prompt.<locals>.<listcomp>zInvalid skill level 'z', defaulting to INTERMEDIATEIntermediater.   g        g      ?zInvalid weight z, clamping to [0.0, 1.0]r,   description )r,   r-   r.   r$   r3   zError processing skill 	reasoningzLLM Analysis: zSuccessfully extracted z skills for z departmentzJSON parsing error: zRaw LLM response: zError extracting skills: )r   joinloggerinfoinvokestrip
startswithendswithjsonloadsgetwarningallupperreplacer   floatmaxminappend
ValueErrorKeyErrorerrorlenJSONDecodeError	Exception)r   r   r   r   llm	dept_listsystem_promptresponsecleaned_responseresultr&   r$   	level_strskill_levelr.   er   r)   r   extract_skills_from_prompt   s   
+ 






rW   c                  C   s   g d} g d}|D ]l}t dd  t d|  t d t|| }|rrt d|d d   t d	t| d
 t d t|dD ]-\}}t | d|d   t d|d   t d|d   t d|d   t   qCq
t d q
dS )zB
    Test the skills extraction function with various prompts
    )Sales	MarketingzCustomer ServiceITHRFinance
Operations)z"I want to improve my sales revenuez+We need to enhance customer service qualityz0How can we increase our marketing effectiveness?z&Our IT systems need better performancez+Improve team productivity and collaboration
z<============================================================zPROMPT: zDepartment: r   r$   zSkills needed (z):z(----------------------------------------r   z. r,   z
   Level: r-   z   Weight: r.   z   Reason: r3   zNo skills extractedN)printrW   rK   	enumerate)departmentstest_promptsr   r&   ir*   r   r   r   main   s(   

rd   __main__)r   r   )r=   langchain_community.llmsr   langchain_core.promptsr   langchain_core.output_parsersr   typingr   r   r   r   dataclassesr	   enumr
   loggingbasicConfigINFO	getLoggerr   r7   r   strrD   rW   rd   r   r   r   r   <module>   s"    
0 $
