
    Nge+                     
   d Z ddlZddlmZ ddlmZmZmZmZ ddl	m
Z
mZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZmZmZ dd
lmZmZ  ej        e          Z G d de          Z G d de          Z G d de          Z dS )z.Tools for interacting with a Power BI dataset.    N)perf_counter)AnyDictOptionalTuple)AsyncCallbackManagerForToolRunCallbackManagerForToolRun)BaseTool)
ConfigDictFieldmodel_validator)_import_tiktoken)BAD_REQUEST_RESPONSEDEFAULT_FEWSHOT_EXAMPLESRETRY_RESPONSE)PowerBIDataset
json_to_mdc            	          e Zd ZU dZdZeed<   dZeed<   dZe	ed<    e
d	          Zeed
<   eZee         ed<    e
ed          Zeee	f         ed<   dZeed<   dZeed<   dZee         ed<    ed          Z ed          ededefd                        Zdedee         fdZ	 d#dedee         de	defdZ	 d#dedee         de	defdZ deee	f         de!ee         ee	         f         fd Z"d!ede!e#ef         fd"Z$dS )$QueryPowerBIToolz%Tool for querying a Power BI Dataset.query_powerbinamea  
    Input to this tool is a detailed question about the dataset, output is a result from the dataset. It will try to answer the question using the dataset, and if it cannot, it will ask for clarification.

    Example Input: "How many rows are in table1?"
    descriptionN	llm_chainTexcludepowerbiexamples)default_factoryr   session_cache   max_iterationsi  output_token_limittiktoken_model_namearbitrary_types_allowedbefore)modevaluesreturnc                 p    |d         }|j         j        D ] }|dvrt          d|j         j                  !|S )z8Make sure the LLM chain has the correct input variables.r   )
tool_inputtablesschemasr   zrLLM chain for QueryPowerBITool must have input variables ['tool_input', 'tables', 'schemas', 'examples'], found %s)promptinput_variables
ValueError)clsr(   r   vars       b/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/tools/powerbi/tool.py"validate_llm_chain_input_variablesz3QueryPowerBITool.validate_llm_chain_input_variables.   s]     ;'	#3 	 	CIII  I$4   J
     r+   c                 2    || j         vrdS | j         |         S )zCheck if the input is present in the cache.

        If the value is a bad request, overwrite with the escalated version,
        if not present return None.N)r   )selfr+   s     r3   _check_cachezQueryPowerBITool._check_cache=   s%    
 T///4!*--r5   run_managerkwargsc                    |                      |          x}rt                              d||           |S 	 t                              d|           | j                            || j                                        | j                                        | j	        |r|
                                nd          }n1# t          $ r$}d| | j        |<   | j        |         cY d}~S d}~ww xY w|dk    r|| j        |<   | j        |         S t                              d|           t                      }| j                            |          }t                      }	t                              d	|           t                              d
|	|z
  d           |                     |          \  }
}|d|v rd| j        |<   | j        |         S |                    dd          }|r;|| j        k     r0|                     t'          j        |||          ||dz             S |
r|
nt+          j        |          | j        |<   | j        |         S ):Execute the query, return the results or an error message.Found cached result for %s: %s%Running PBI Query Tool with input: %sNr+   r,   r-   r   	callbacksError on call to LLM: I cannot answer thiszPBI Query:
%scommandPBI Result: %sPBI Query duration: 0.6fTokenExpiredzCAuthentication token expired or invalid, please try reauthenticate.
iterationsr   r+   queryerror   r+   r9   rI   rL   )r8   loggerdebuginfor   predictr   get_table_namesget_schemasr   	get_child	Exceptionr   r   run_parse_outputgetr!   _runr   formatr   r7   r+   r9   r:   cacherK   exc
start_time
pbi_resultend_timeresultrL   rI   s                r3   r[   zQueryPowerBITool._runF   s    %%j1115 	LL9:uMMML	2KK?LLLN**%|335500225@J+//111d +  EE  	2 	2 	2-Kc-K-KDz*%j1111111	2 ***-2Dz*%j11$e,,,!^^
\%%e%44
>>%z222HHz,AHHHIII**:665!8!8U z* %j11ZZa00
 	Z$"55599)0)e   (%>     JFF"6"=E"J"J"J 	:& !*--s   BB; ;
C)C$C)$C)c                   K   |                      |          x}r!t                              d||           | dS 	 t                              d|           | j                            || j                                        | j                                        | j	        |r|
                                nd           d{V }n1# t          $ r$}d| | j        |<   | j        |         cY d}~S d}~ww xY w|dk    r|| j        |<   | j        |         S t                              d|           t                      }| j                            |	           d{V }t                      }	t                              d
|           t                              d|	|z
  d           |                     |          \  }
}|d|v sd|v rd| j        |<   | j        |         S |                    dd          }|rA|| j        k     r6|                     t'          j        |||          ||dz              d{V S |
r|
nt+          j        |          | j        |<   | j        |         S )r<   r=   z3, from cache, you have already asked this question.r>   Nr?   rA   rB   zPBI Query: %srC   rE   rF   rG   rH   
TokenErrorzkAuthentication token expired or invalid, please try to reauthenticate or check the scope of the credential.rI   r   rJ   rM   rN   rO   )r8   rP   rQ   rR   r   apredictr   rT   rU   r   rV   rW   r   r   arunrY   rZ   r!   _arunr   r\   r   r]   s                r3   rh   zQueryPowerBITool._arun|   s      %%j1115 	QLL9:uMMMPPPP	2KK?LLL.11%|335500225@J+//111d 2        EE  	2 	2 	2-Kc-K-KDz*%j1111111	2 ***-2Dz*%j11OU+++!^^
<,,U,;;;;;;;;
>>%z222HHz,AHHHIII**:66.E"9"9\U=R=R} z* %j11ZZa00
 	Z$"555)0)e   (%> $          JFF"6"=E"J"J"J 	:& !*--s   B	C 
C4C/)C4/C4ra   c                    d|v r|d         d         d         d         d         }t          |          dk    rt                              d           dS t          |          }|                     |          \  }}|rd| d| j         d	d
fS |d
fS d|v rFd|d         v r2d|d         d         v r"d
|d         d         d         d         d         fS d
|d         fS d
|fS )z2Parse the output of the query to a markdown table.resultsr   r,   rowsz%0 records in result, query was valid.)Nz^0 rows returned, this might be correct, but please validate if all filter values were correct?z[Result too large, please try to be more specific or use the `TOPN` function. The result is z tokens long, the limit is z tokens.NrL   z	pbi.errordetailsdetail)lenrP   rR   r   _result_too_larger"   )r7   ra   rk   rc   too_longlengths         r3   rY   zQueryPowerBITool._parse_output   sE    
""i(+H5a8@D4yyA~~CDDD   %%F#55f==Hf  wrx  w  w  VZ  Vm  w  w  w  4<j  z'222G!4[!AAAZ0=iHKHUUUG,,,Zr5   rc   c                     | j         rrt                      }|                    | j                   }t          |                    |                    }t
                              d|           || j        k    |fS dS )z!Tokenize the output of the query.zResult length: %s)Fr   )r#   r   encoding_for_modelrn   encoderP   rR   r"   )r7   rc   	tiktoken_encodingrq   s        r3   ro   z"QueryPowerBITool._result_too_large   st    # 	<(**I 33D4LMMH0011FKK+V444D33V;;xr5   N)%__name__
__module____qualname____doc__r   str__annotations__r   r   r   r   r   r   r   r   r   dictr   r   r!   intr"   r#   r   model_configr   classmethodr4   r8   r	   r[   r   rh   r   rY   boolro    r5   r3   r   r      sm        //D#K   
 Is#eD111G^1116Hhsm666$)E$$M$M$MM4S>MMMNC"""")-#---: $  L _(###	   [ $#.s .x} . . . . <@4. 4.4. 784. 	4.
 
4. 4. 4. 4.r AE4. 4.4. <=4. 	4.
 
4. 4. 4. 4.l sCx. 	x}hsm+	,       < dCi0@      r5   r   c                       e Zd ZU dZdZeed<   dZeed<    ed          Z	e
ed<    ed	          Z	 ddedee         defdZ	 ddedee         defdZd
S )InfoPowerBIToolz2Tool for getting metadata about a PowerBI Dataset.schema_powerbir   z
    Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.
    Be sure that the tables actually exist by calling list_tables_powerbi first!

    Example Input: "table1, table2, table3"
    r   Tr   r   r$   Nr+   r9   r)   c                 \    | j                             |                    d                    S )z4Get the schema for tables in a comma-separated list., )r   get_table_infosplitr7   r+   r9   s      r3   r[   zInfoPowerBITool._run   s(     |**:+;+;D+A+ABBBr5   c                 l   K   | j                             |                    d                     d {V S )Nr   )r   aget_table_infor   r   s      r3   rh   zInfoPowerBITool._arun   s>      
 \11*2B2B42H2HIIIIIIIIIr5   rw   rx   ry   rz   r{   r   r|   r}   r   r   r   r   r   r   r   r	   r[   r   rh   r   r5   r3   r   r      s        << D#   K    $eD111G^111: $  L <@C CC 78C 
	C C C C AEJ JJ <=J 
	J J J J J Jr5   r   c                       e Zd ZU dZdZeed<   dZeed<    ed          Z	e
ed<    ed	          Z	 	 ddee         dee         defdZ	 	 ddee         dee         defdZd
S )ListPowerBIToolzTool for getting tables names.list_tables_powerbir   zUInput is an empty string, output is a comma separated list of tables in the database.r   Tr   r   r$   Nr+   r9   r)   c                 Z    d                     | j                                                  S zGet the names of the tables.r   joinr   rT   r   s      r3   r[   zListPowerBITool._run  s$     yy5577888r5   c                 ^   K   d                     | j                                                  S r   r   r   s      r3   rh   zListPowerBITool._arun  s(       yy5577888r5   )NNr   r   r5   r3   r   r      s         ((%D#%%%nKnnn#eD111G^111: $  L %);?9 9SM9 789 
	9 9 9 9 %)@D9 9SM9 <=9 
	9 9 9 9 9 9r5   r   )!r{   loggingtimer   typingr   r   r   r   langchain_core.callbacksr   r	   langchain_core.toolsr
   pydanticr   r   r   &langchain_community.chat_models.openair   (langchain_community.tools.powerbi.promptr   r   r   %langchain_community.utilities.powerbir   r   	getLoggerrx   rP   r   r   r   r   r5   r3   <module>r      s   4 4        - - - - - - - - - - - -        * ) ) ) ) ) 7 7 7 7 7 7 7 7 7 7 C C C C C C         
 M L L L L L L L		8	$	$    x   DJ J J J Jh J J J@9 9 9 9 9h 9 9 9 9 9r5   