
    *i                        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                  j                  d      Zes ed      dZ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 Fast API Integration
Switches RAG system from local LLM to Grok Fast Reasoning Model API
    N)OptionalDictAnyList)MAX_NEW_TOKENSTEMPERATUREGROK_API_KEYz,GROK_API_KEY environment variable is not setz$https://api.x.ai/v1/chat/completionszgrok-4-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extend
GROK_MODELtimerequestspostGROK_API_URL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/backtest/airagagent/grok_api.pycall_grok_apir7      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.)r7   )r8   r9   r:   r   user_promptanswers         r6   generate_answer_with_grokr>   k   sc      j ( 4 ,4M 		 
* K #	F VVV    )N)__doc__r%   r   r$   ostypingr   r   r   r   airagagent.configr   r   environgetr	   
ValueErrorr'   r#   strintfloatr7   r>    r?   r6   <module>rK      s   
    	 , , 9 zz~~n-
C
DD5$
 $($$;?RRC=R R 	R
 #4S#X#78R c]Rp *.-W-W-W "#-W 		-Wr?   