o
    h@D                     @   sx  d dl mZmZ d dlmZ d dlmZmZ d dlm	Z	m
Z
mZmZ d dlmZ d dlZd dlZd dlmZ e  d dlmZ d d	lmZ d d
lmZ d dlmZ eddddZejedgddgdgd e Ze Ze ZG dd deZG dd deZ G dd deZ!G dd deZ"G dd deZ#G dd deZ$G dd  d eZ%G d!d" d"eZ&e'd#d$d% Z(e'd&d'd( Z)ej*d)e"d*d+e!fd,d-Z+d+e!d.ee fd/d0Z,d1e-d2e-d.e-fd3d4Z.d5e-d.ee fd6d7Z/d8ed.e%fd9d:Z0d8ed.e-fd;d<Z1ej*d=e&d*d+e!fd>d?Z2e*d@d5e-fdAdBZ3e'dCd5e-fdDdEZ4e5dFkr:d dl6Z6e6j7edGdHdI dS dS )J    )FastAPIHTTPException)CORSMiddleware)	BaseModelField)ListDictAnyOptional)datetimeN)load_dotenv)ScenarioGenerator)RoleplayEngine)GroqService)RoleplayScenarioAI Roleplay Servicez,Simple AI service for roleplay functionalityz1.0.0)titledescriptionversion*T)allow_originsallow_credentialsallow_methodsallow_headersc                   @      e Zd ZU eed< eed< dS )	SkillDataskill_id
skill_nameN__name__
__module____qualname__str__annotations__ r$   r$   R/var/www/eduai.edurigo.com/doc_train/edurigo_ai/roleplay/prod/roleplay_fast_api.pyr   (      
 r   c                   @   sZ   e Zd ZU eed< eed< edddZeed< eed< edd	dZeed
< ee	 ed< dS )RoleplayDatacategory	objective.zLearner role)aliaslearner_roleadditional_info zConstraints/Policiescompany_policiesskills_for_roleplayN)
r   r    r!   r"   r#   r   r+   r.   r   r   r$   r$   r$   r%   r'   ,   s   
 r'   c                   @   s.   e Zd ZU eed< eed< eed< eed< dS )RoleplayRequest	client_id
session_idroleplay_dataqueryN)r   r    r!   r"   r#   r'   r$   r$   r$   r%   r0   4   s
   
 r0   c                   @   r   )RoleplayResponser2   responseNr   r$   r$   r$   r%   r5   :   r&   r5   c                   @   s6   e Zd ZU eed< eed< eed< eed< eed< dS )CharacterDetailsnamepersonalitygoals
backgroundemotional_stateNr   r$   r$   r$   r%   r7   >   s   
 r7   c                   @   s&   e Zd ZU eed< eed< eed< dS )ScenarioSetupcontextenvironmentconstraintsNr   r$   r$   r$   r%   r=   E   s   
 r=   c                   @   sz   e Zd ZU eed< eed< eed< eed< eed< ee ed< eed< eed< eed	< eeef ed
< eed< eed< dS )PreviewResponsescenario_idr(   r)   r+   ai_roleskills_to_assessscenario_setupcharacter_detailsconversation_startersuccess_criteriadifficulty_levelbackground_infoN)	r   r    r!   r"   r#   r   r=   r7   r   r$   r$   r$   r%   rA   J   s   
 rA   c                   @   s   e Zd ZU eed< dS )ScenarioPreviewResponser6   Nr   r$   r$   r$   r%   rK   X   s   
 rK   /c                      s   dddS )zHealth check endpointr   running)messagestatusr$   r$   r$   r$   r%   root[   s   
rP   z/healthc               
      s`   zt d} | sdddW S dt  dW S  ty/ } ztddt| d	d
}~ww )zHealth checkGROQ_API_KEYerrorzGROQ_API_KEY not configured)rO   rN   healthy)rO   	timestamp  zHealth check failed: status_codedetailN)osgetenvr   now	isoformat	Exceptionr   r"   )api_keyer$   r$   r%   health_check`   s   
r`   z	/roleplay)response_modelrequestc              
      s  z| j }td|  t|}td|du  |s<td t| }|s+tdddtd t| t||jd	W S td
| j	  t
|}td|du  |du rgtd t| t||jd	W S z!t||| j	}td|du  |stdddt||d	W W S  ty } z
tdt|   d}~ww  ty     ty } z%tdt|  tdt|  ddl}|  tddt| dd}~w ty     ty } ztddt| dd}~ww )zBHandle roleplay request - both first time and ongoing conversationz Processing request for session: zScenario found: NzCreating new scenario...rU   zFailed to create scenariorV   zStarting new session...)r2   r6   zAdding learner response: zConversation history exists: z.Starting conversation for existing scenario...zAI response generated: zFailed to generate AI responsezError in add_learner_response: zError in handle_roleplay: zError type: r   zInternal error: zError processing roleplay: )r2   printload_scenario_for_sessioncreate_scenario_from_requestr   roleplay_enginestart_sessionr5   rG   r4   get_conversation_historyadd_learner_responser]   r"   type	traceback	print_exc)rb   r2   scenarioconversation_historyai_responser_   rk   r$   r$   r%   handle_roleplayl   st   



rp   returnc              
   C   s   z:| j }dd |jD }|j|jddd}t|j|j}tj|j|j|||j	|d}|r8| j
|_tj|  |W S  tyT } ztd|  W Y d}~dS d}~ww )	z.Create scenario from the roleplay request datac                 S   s   g | ]}|j qS r$   )r   ).0skillr$   r$   r%   
<listcomp>   s    z0create_scenario_from_request.<locals>.<listcomp>zRoleplay conversationMedium)r;   r@   r?   rI   )r(   r)   detailsrC   r+   rD   zError creating scenario: N)r3   r/   r,   r.   generate_ai_roler(   scenario_generatorcreate_scenarior)   r+   r2   idjson_handlersave_scenarioto_dictr]   rc   )rb   r3   rD   rv   rC   rm   r_   r$   r$   r%   re      s4   
re   r(   r,   c                 C   s~   dddddd}| |  d}d| v rd	| S d
| v s'd| v r,d| S d| v s8d| v r=d| S |S )z:Generate appropriate AI role based on category and contextzPotential CustomerzCustomer with IssuezTeam MemberzNegotiation PartnerzUser with Technical Problem)saleszcustomer service
leadershipnegotiationztechnical supportzConversation Partner
enterprisezEnterprise budgetpricezBudget-Conscious 
frustrated	complaintzFrustrated )getlower)r(   r,   category_roles	base_roler$   r$   r%   rw      s   


rw   r2   c              
   C   sH   zt | W S  ty# } ztd|  d|  W Y d}~dS d}~ww )z"Load scenario for existing sessionz#Error loading scenario for session z: N)rx   load_scenarior]   rc   )r2   r_   r$   r$   r%   rd      s   rd   rm   c                 C   s  zmt | jdd| jdd| jdd| jdd| jddd}t| jd	d| jd
d| jddd}i }t| jtrE| j}ndt| ji}t	| j
| j| j| j| j| j||| j|| jdd| jdddW S  ty } ztd|   d}~ww )z.Convert scenario to formatted preview responser8   AI Characterr9   Not specifiedr:   r;   r<   )r8   r9   r:   r;   r<   r>   r?   r@   )r>   r?   r@   generalrI   ru   )rB   r(   r)   r+   rC   rD   rE   rF   rG   rH   rI   rJ   z'Error formatting scenario for preview: N)r7   ai_characterr   r=   rE   
isinstancerH   dictr"   rA   rz   r(   r)   r+   rC   rD   rG   rv   r]   rc   )rm   rF   rE   rH   r_   r$   r$   r%   format_scenario_for_preview  sH   	r   c                 C   s  zi d| j d| jd| jd| jd| jd| jddd| jddd	| jd	dd
| jddd| jddd| jddd| jddd| jddd| jd| j	d| j
ddd| j
dd}d| d}t|}|sd| j  d| j d| jdd d | j d!| j d"| jdd# d!| jdd$ d%| j W S | W S  ty } z+td&|  d| j  d| j d| jdd d | j d!| j d%| j W  Y d'}~S d'}~ww )(z4Convert scenario to natural paragraph text using LLMr(   r)   r+   rC   rD   r>   r   r?   r@   ai_character_namer8   r   ai_personalityr9   ai_backgroundr;   ai_goalsr:   ai_emotional_stater<   rG   rH   rJ   rI   ru   a  Convert the following roleplay scenario data into natural, flowing paragraphs without any headings, bullet points, or markdown formatting. Write it as a cohesive narrative description that explains everything about the scenario in a conversational manner.

Scenario Data:
a  

Requirements:
- Write in natural paragraphs only (no headings, no bullet points, no markdown)
- Make it flow like a story or description
- Include all the important information about the scenario, roles, characters, objectives, and success criteria
- Keep it engaging and easy to understand
- Don't use any formatting symbols like **, ##, -, etc.
- Write it as if you're explaining the scenario to someone in person

Write the complete scenario description in paragraph form:z
This is a z. roleplay scenario where you play the role of z and interact with zan AI characterz
 who is a z. z The scenario takes place in za roleplay settingr-   z# The conversation will begin with: z1Error formatting scenario as paragraph with LLM: N)r(   r)   r+   rC   rD   rE   r   r   rG   rH   rv   groq_serviceget_completionstripr]   rc   )rm   scenario_datapromptparagraph_responser_   r$   r$   r%   format_scenario_as_paragraph0  s`   	

^
Hr   z/roleplay_scenarioc              
      s   z;t d| j  t| j}|rt d t|}t|dW S t d t| }|s/tdddt|}t d t|dW S  tyD     tyk } zt d	t|  d
dl	}|
  tddt| dd}~ww )z<Generate and return formatted preview data as paragraph textz(Processing preview request for session: z#Using existing scenario for preview)r6   z!Creating new scenario for previewrU   z%Failed to create scenario for previewrV   z(Preview paragraph generated successfullyz(Error in get_roleplay_scenario_preview: r   NzError generating preview: )rc   r2   rd   r   rK   re   r   r]   r"   rk   rl   )rb   existing_scenarior   rm   r_   rk   r$   r$   r%   get_roleplay_scenario_previewg  s0   
r   z/end_sessionc              
      sX   zt | }|rd| dW S tddd ty+ } ztddt| dd}~ww )	zEnd a roleplay sessionzSession ended successfully)rN   r2     Session not foundrV   rU   zError ending session: N)rf   end_sessionr   r]   r"   )r2   successr_   r$   r$   r%   r     s   
r   z/session/{session_id}/historyc              
      s\   zt | }|du rtddd| |dW S  ty- } ztddt| dd}~ww )z&Get conversation history for a sessionNr   r   rV   )r2   rn   rU   zError retrieving history: )rf   rh   r   r]   r"   )r2   historyr_   r$   r$   r%   get_session_history  s   
r   __main__z0.0.0.0i@  )hostport)8fastapir   r   fastapi.middleware.corsr   pydanticr   r   typingr   r   r	   r
   r   uuidrY   dotenvr   services.scenario_generatorr   services.roleplay_enginer   services.groq_servicer   models.scenarior   appadd_middlewarerx   rf   r   r   r'   r0   r5   r7   r=   rA   rK   r   rP   r`   postrp   re   r"   rw   rd   r   r   r   r   r   r   uvicornrunr$   r$   r$   r%   <module>   sr    	

M)	.7!
