
    giJi#                         d dl Z d dlmZ d dlmZ d dlZd dlZd dlmZ d dlm	Z	m
Z
mZ  e         ej                  e      Z G d d      Zy)    N)OpenAI)load_dotenv)datetime)DictAnyOptionalc            !           e Zd Zd Z	 	 	 ddee   dededededed	ed
ededededededeee	f   deee	f   fdZ
dedededefdZ	 	 	 	 ddedededee   dedefdZy)	AIServicec                 L    t        t        j                  d            | _        y)z6Initialize OpenAI client with API key from environmentOPENAI_API_KEY)api_keyN)r   osgetenvclient)selfs    7/var/www/html/drjob-dev/drjob-ai/services/ai_service.py__init__zAIService.__init__   s    II./
    N
company_idservice_typefeaturemodelinput_tokensoutput_tokenstotal_tokensprompt_lengthcompletion_lengthcoststatusexecution_timeerror_messagerequest_dataresponse_datac                    	 ddl m}  |       }|d   }|||||||||	t        |
d      |t        |d      t        j                         d}|r|dd |d	<   |r<|j                         D ci c]  \  }}|t        |t              r|dd
 n| c}}|d<   |r<|j                         D ci c]  \  }}|t        |t              r|dd
 n| c}}|d<   |j                  |       t        j                  d| d| d|
        yc c}}w c c}}w # t        $ r+}t        j                  dt        |              Y d}~yd}~ww xY w)a  
        Log AI API usage to ai_usage_logs collection
        
        Args:
            company_id: Company ID (if available)
            service_type: 'openai', 'claude', etc.
            feature: 'resume_parsing', 'offer_letter', 'job_description', 'screening', etc.
            model: 'gpt-4', 'gpt-3.5-turbo', etc.
            input_tokens: Number of input tokens
            output_tokens: Number of output tokens
            total_tokens: Total tokens used
            prompt_length: Length of prompt in characters
            completion_length: Length of completion in characters
            cost: Calculated cost based on pricing
            status: 'success' or 'failed'
            execution_time: Time taken in milliseconds
            error_message: Error message if failed
            request_data: Request details (optional, truncated for storage)
            response_data: Response details (optional, truncated for storage)
        r   )get_databaseai_usage_logs      )r   r   r   r   r   r   r   r   r   r   r   r    
created_atNi  r!      r"   r#   zLogged AI usage: z - z tokens - $zError logging AI usage: )services.databaser%   roundr   utcnowitems
isinstancestr
insert_oneloggerdebug	Exceptionerror)r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r%   dbai_usage_logs_collectionlog_datakves                          r   _log_ai_usagezAIService._log_ai_usage   sl   L/	6B')/':$ ) ," ,!. ,!.%6dA "'":&oo/H" ,9$3,?) !- 2 2 4,1 :a#5$31<,(
  !. 3 3 5-1 :a#5$31<-) %//9LL,WISkRVQWXY,-  	LL3CF8<=	s6   A'D )"D D '"D	6D  D 	E !D;;E returnc                     ddddddddddddd	}|j                  ||d
         }|dz  |d   z  }|dz  |d   z  }||z   S )a;  
        Calculate cost based on model and token usage
        Prices as of 2024 (update as needed)
        
        Args:
            model: Model name
            input_tokens: Number of input tokens
            output_tokens: Number of output tokens
            
        Returns:
            Cost in USD
        gQ?gQ?)inputoutputg{Gz?gMb@?g~jtX?g~jth?gMbp?)zgpt-4zgpt-4-turbogpt-3.5-turbozgpt-3.5-turbo-16krA     r?   r@   )get)r   r   r   r   pricingmodel_pricing
input_costoutput_costs           r   _calculate_costzAIService._calculate_costn   su      $t4%)T:'-@+0E!B	
  E7?+CD"T)]7-CC
$t+}X/FFK''r   questionsystem_prompt
max_tokensc                    t        j                          }t        j                  dd      }d}|r	|dz   |z   }	n|}	|dv rd}
nd}
	 | j                  j                  j
                  j                  |d|	d	d
|d	g||
      }|j                  d   j                  j                  }|j                  }t        j                          |z
  dz  }| j                  ||j                  |j                        }| j                  |d|||j                  |j                  |j                  t!        |      t!        |	      z   t!        |      |d||dd |r|dd nddd|dd i       |S # t"        $ r}t        j                          |z
  dz  }| j                  |d||dddt!        |      t!        |xs d      z   ddd|t%        |      |dd |r|dd ndd       dt%        |       cY d}~S d}~ww xY w)a  
        Generate AI response with usage logging
        
        Args:
            question: User question/prompt
            system_prompt: System prompt for context
            max_tokens: Maximum tokens for response
            company_id: Company ID for tracking (optional)
            feature: Feature name for tracking (e.g., 'screening', 'offer_letter')
            
        Returns:
            AI generated response text
        OPENAI_API_MODELrA   zYou are a helpful assistant. )	screeningindexing_keywordsg?gffffff?system)rolecontentuser)r   messagesrK   temperaturer   rB   )r   r   r   openaisuccessNr*    )question_previewsystem_prompt_previewanswer_preview)r   r   r   r   r   r   r   r   r   r   r   r    r"   r#   g        failed)r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   zError: )timer   r   r   chatcompletionscreatechoicesmessagerS   usagerH   prompt_tokenscompletion_tokensr<   r   lenr4   r0   )r   rI   rJ   rK   r   r   
start_timer   base_system_promptfinal_system_promptrV   responseanswerrd   r    r   r;   s                    r   ai_responsezAIService.ai_response   sJ   * YY[
		,o> < "4s":]"J"4 88KKK	&{{''33::%2EF#9 &' ; H %%a(0088FNNE #iikJ6$>N ''"00#55 ( D %%"00#55"//!(mc2E.FF"%f+ -(0#DQ]4C-@WY
 %fTcl#  , M 	&"iikJ6$>N %%!(mc-2E2.FF"#-!!f(0#DQ]4C-@WY  ( SVH%%3	&s    DE 	G((A5G#G(#G()NNN)rY   rB   Ngeneral)__name__
__module____qualname__r   r   intr0   floatr   r   r<   rH   rm    r   r   r
   r
      sK   
( "'+(,!USMU U 	U
 U U U U U U U U U U 38nU  CH~!Un(S ( (C (TY (@  $( r&r& r& 	r&
 SMr& r& 
r&r   r
   )r   rW   r   dotenvr   loggingr^   r   typingr   r   r   	getLoggerro   r2   r
   rt   r   r   <module>ry      sD    	      & &  
		8	$m& m&r   