
    HCi                        d Z ddlZddlZddlZddlZddlmZmZmZm	Z	 ddl
mZmZ  ej                  d      xs  ej                  d      xs dZ ej                  d      xs  ej                  d	      xs d
Z ej                  d      xs  ej                  d      xs dZdeedfdedee   dededee	eeef         dee   fdZ	 ddededee   defdZy)z
Grok API Integration (server-side).

SECURITY:
- Never hardcode API keys in this repository.
- Provide the key via environment variables on the server (systemd override recommended).
    N)OptionalDictAnyList)MAX_NEW_TOKENSTEMPERATUREXAI_API_KEYGROK_API_KEY XAI_API_URLGROK_API_URLz$https://api.x.ai/v1/chat/completions	XAI_MODEL
GROK_MODELzgrok-4-1-fast-reasoningpromptsystem_prompt
max_tokenstemperatureconversation_historyreturnc                 d   dt          dd}g }|r|j                  d|d       |r|j                  |       |j                  d| d       t        |||dd}	 t	        j                         }t        j                  t        ||d	
      }	t	        j                         |z
  }
|	j                  dk(  rB|	j                         }d|v rt        |d         dkD  r|d   d   d   d   S t        d|        yt        d|	j                   d|	j                          y# t
        j                  j                  $ r( t        dt	        j                         z
  dd       Y yt
        j                  j                  $ r}t        d|        Y d}~yd}~wt         $ r}t        d|        Y d}~yd}~ww xY w)a  
    Call Grok Fast API to generate a response
    
    Args:
        prompt: The user prompt/question
        system_prompt: Optional system prompt for context
        max_tokens: Maximum tokens to generate
        temperature: Sampling temperature
        conversation_history: Optional conversation history
        
    Returns:
        Generated response text or None if error
    zBearer zapplication/json)AuthorizationzContent-Typesystem)rolecontentuserF)modelmessagesr   r   stream-   )headersjsontimeout   choicesr   messager   z"Grok API: No choices in response: NzGrok API Error: z - zGrok API Timeout after z.2fszGrok API Request Error: zGrok API Unexpected Error: )r
   appendextendr   timerequestspostr   status_coder!   lenprinttext
exceptionsTimeoutRequestException	Exception)r   r   r   r   r   r    r   payload
start_timeresponsedurationdataes                ,/var/www/html/leadgen/airagagent/grok_api.pycall_grok_apir;   "   s   * #<.1*G
 H $
 	 ,- OO   "GYY[
==	
 99;+3&==?DD Si%9A%=Iq))4Y??:4&AB$X%9%9$:#hmm_MN&& '		j(@'EQGH// (,- +A3/0s8   B	D #D 2%D AF/F/8FF/F**F/contextquestionsystem_instructionsc                 P    | sy|xs d}d|  d| d}t        ||dd      }|xs d	S )
a  
    Generate an answer using Grok Fast API with RAG context
    
    Args:
        context: Formatted RAG context from vector search
        question: User's question
        system_instructions: Optional system instructions
        
    Returns:
        Generated answer
    zYI don't have enough information to answer that question based on the available documents.a  You are a helpful AI assistant that answers questions based on provided context.
    - Use only the information provided in the context
    - If the context doesn't contain relevant information, say so explicitly
    - Be concise and accurate
    - For technical questions (pH, temperature, measurements), extract specific numbers/ranges
    - Do NOT provide generic information if the specific answer isn't in the context
    - Cite sources when mentioned in the contextzFBased on the following context, answer the user's question.

CONTEXT:
z

QUESTION: z	

ANSWER:i   gffffff?)r   r   r   r   z?I encountered an error generating a response. Please try again.)r;   )r<   r=   r>   r   user_promptanswers         r:   generate_answer_with_grokrB   w   sc      j ( 4 ,4M 		 
* K #	F VVV    )N)__doc__osr*   r!   r)   typingr   r   r   r   configr   r   getenvr
   r   r   strintfloatr;   rB    rC   r:   <module>rM      sM   
    , , .
 BIIm 
ryy 
	 
 ryy'n9299^+DnHn BIIk !ryy!   $($$;?RRC=R R 	R
 #4S#X#78R c]Rp *.-W-W-W "#-W 		-WrC   