o
    z­j$  ã                   @   s¢   d Z ddlZddlmZmZmZmZ ddlZddlZddl	m
Z
 ddlmZmZmZmZmZ ddlmZ ejejd� e e¡Ze
ƒ ZG dd„ deƒZd	d
„ ZdS )z¼
General-purpose AI Chat Agent for CropPilot
This module provides a sophisticated chat agent that can engage in general conversations
while having specialized knowledge about agriculture.
é    N)ÚDictÚListÚAnyÚOptional)Úget_settings)ÚAgentÚ	AgentTypeÚMessageÚcoordinatorÚcontext_protocol)Úlevelc                       sª   e Zd ZdZ‡ fdd„Zdd„ Zdedee fdd	„Zdedee fd
d„Z	de
deee
ef  de
fdd„Zde
deee
ef  fdd„Zde
de
de
fdd„Z‡  ZS )Ú	ChatAgentzš
    General-purpose AI chat agent that can have extended conversations
    with users about any topic, with specialized knowledge about agriculture.
    c                    s<   t ƒ  tj¡ |  d| j¡ |  d| j¡ |  ¡  d| _d S )NÚchatÚstream_chatas  You are CropPilot, an advanced AI assistant specialized in helping farmers across India.
You have extensive knowledge about:
- Crop cultivation techniques for all regions of India
- Pest and disease management for various climatic zones
- Weather patterns and climate adaptation across different Indian states
- Agricultural market trends throughout India's major agricultural markets
- Sustainable farming practices suited to diverse Indian conditions
- Knowledge of agriculture across different states of India including crop varieties, local practices and market information

While you specialize in agricultural topics, you can also have general conversations
and answer questions on other topics. Always be helpful, accurate, and respectful.
Provide practical, actionable advice when possible.

When you don't know something, admit it clearly rather than making up information.
)	ÚsuperÚ__init__r   ÚCHAT_ASSISTANTÚregister_handlerÚhandle_chatÚhandle_stream_chatÚ_init_ai_modelsÚgeneral_system_prompt)Úself©Ú	__class__© ú6/var/www/html/CropPilot/backend/app/core/chat_agent.pyr      s
   
zChatAgent.__init__c              
   C   s”   t jr@t jdkr@ztƒ }tj|jd� t |j¡| _t 	d¡ W dS  t
y? } zt d|› �¡ d| _W Y d}~dS d}~ww t d¡ d| _dS )z!Initialize the AI models for chatÚYOUR_GEMINI_API_KEY_NOT_SET)Úapi_keyz*Gemini chat model initialized successfullyz!Error initializing Gemini model: Nz9Gemini API key not configured, chat will not be available)ÚsettingsÚGEMINI_API_KEYr   ÚgenaiÚ	configureÚGenerativeModelÚGEMINI_MODELÚgemini_modelÚloggerÚinfoÚ	ExceptionÚerrorÚwarning)r   ÚsÚer   r   r   r   5   s   €þ

zChatAgent._init_ai_modelsÚmessageÚreturnc              
   Ã   s$  �ze|j  dd¡}|st| j|jddidd�W S |jr!|j d¡nd}|s,t d¡ d	}|  |¡I dH }| j	rA|  
||¡I dH }nt| j|jdd
idd�W S |  |||¡I dH  t| j|jd|id|jd�W S  ty‘ } zt d|› �¡ t| j|jddt|ƒ› �idd�W  Y d}~S d}~ww )zM
        Handle a chat message from the user and generate a response
        r-   Ú r)   zNo message provided)ÚsenderÚreceiverÚcontentÚmessage_typeÚ
session_idNzNo session ID provided for chatÚdefault_sessionz&Gemini model is not available for chatÚresponseÚchat_response)r0   r1   r2   r3   ÚcontextzError in chat handler: zError processing chat: )r2   Úgetr	   Ú
agent_typer0   r8   r&   r*   Ú_get_chat_historyr%   Ú_chat_with_geminiÚ_update_chat_historyr(   r)   Ústr)r   r-   Úuser_messager4   Úchat_historyr6   r,   r   r   r   r   E   sR   €ü
üûü€þzChatAgent.handle_chatc                 Ã   s   �|   |¡I dH S )z?
        Handle a streaming chat message from the user
        N)r   )r   r-   r   r   r   r   |   s   €zChatAgent.handle_stream_chatr?   r@   c              
   Ã   sÂ   �z>g }|D ]}|d dkrdnd}|  ||d gdœ¡ q|s*|  d| jgdœ¡ |  d|gdœ¡ | j |¡I dH }|jW S  ty` } zt d|› �¡ dt|ƒ› �W  Y d}~S d}~ww )	z&Generate a response using Gemini modelÚroleÚuserÚmodelr2   )rA   ÚpartsNz"Error generating Gemini response: z?I'm having trouble processing that request with Gemini. Error: )	Úappendr   r%   Úgenerate_content_asyncÚtextr(   r&   r)   r>   )r   r?   r@   Úgemini_chatr-   rA   r6   r,   r   r   r   r<   „   s    €€þzChatAgent._chat_with_geminir4   c                 Ã   s   �d|› �}t  |¡}|pg S )zGet chat history from contextÚchat_history_)r   Úget_context)r   r4   Úchat_history_keyr@   r   r   r   r;   ž   s   €

zChatAgent._get_chat_historyÚai_responsec                 Ã   sv   �d|› �}t  |¡pg }| d|t ¡  ¡ dœ¡ | d|t ¡  ¡ dœ¡ t|ƒdkr3|dd… }t  ||¡ dS )zUpdate chat history in contextrI   rB   )rA   r2   Ú	timestampÚ	assistanté   iìÿÿÿN)r   rJ   rE   ÚasyncioÚget_event_loopÚtimeÚlenÚset_context)r   r4   r?   rL   rK   r@   r   r   r   r=   ¤   s    €

ý
ýzChatAgent._update_chat_history)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r	   r   r   r   r>   r   r   r   r<   r;   r=   Ú__classcell__r   r   r   r   r      s    7"r   c                  C   s   t ƒ } t | ¡ | S )z&Initialize and register the chat agent)r   r
   Úregister_agent)Ú
chat_agentr   r   r   Úinit_chat_agentÀ   s   
r\   )rX   ÚloggingÚtypingr   r   r   r   ÚjsonrP   Úapp.core.configr   Úapp.core.multi_agentr   r   r	   r
   r   Úgoogle.generativeaiÚgenerativeair!   ÚbasicConfigÚINFOÚ	getLoggerrU   r&   r   r   r\   r   r   r   r   Ú<module>   s    
 +