
    dh+                         S r SSKrSSKJr  SSKJrJrJrJr  SSK	J
r
Jr  SSKJr  SSKJrJrJr  SSKJr  SS	KJrJrJr  SS
KJrJr  \R6                  " \5      r " S S\5      r " S S\5      r " S S\5      r g)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            	          \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\
\S'   \" S	S
9r\\S'   \r\\   \S'   \" \S	S9r\\\
4   \S'   Sr\\S'   Sr\\S'   Sr\\   \S'   \" S	S9r\" SS9\S\S\4S j5       5       rS\S\\   4S jr S%S\S\\   S\
S\4S jjr S%S\S\\    S\
S\4S jjr!S \\\
4   S\"\\   \\
   4   4S! jr#S"\S\"\$\4   4S# jr%S$r&g)&QueryPowerBITool   z%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                     US   nUR                   R                   H)  nUS;  d  M  [        SUR                   R                  5      e   U$ )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       ^/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/tools/powerbi/tool.py"validate_llm_chain_input_variables3QueryPowerBITool.validate_llm_chain_input_variables.   sV     ;'	##33CII  I$$44  4     r,   c                 @    XR                   ;  a  gU R                   U   $ )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     r4   _check_cacheQueryPowerBITool._check_cache=   s$    
 ///!!*--r7   run_managerkwargsc                    U R                  U5      =n(       a  [        R                  SX5        U$  [        R                  SU5        U R                  R                  UU R                  R                  5       U R                  R                  5       U R                  U(       a  UR                  5       OSS9nUS:X  a  XPR                  U'   U R                  U   $ [        R                  SU5        [        5       nU R                  R                  US9n[        5       n	[        R                  S	U5        [        R                  S
X-
  S 35        U R                  U5      u  pUb$  SU;   a  SU R                  U'   U R                  U   $ UR!                  SS5      nU(       a6  XR"                  :  a'  U R%                  [&        R(                  " XUS9UUS-   S9$ U
(       a  U
O[*        R(                  " US9U R                  U'   U R                  U   $ ! [         a+  nSU 3U R                  U'   U R                  U   s SnA$ SnAff = f):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,   r<   rL   rO   )r:   loggerdebuginfor   predictr   get_table_namesget_schemasr   	get_child	Exceptionr    r   run_parse_outputgetr"   _runr   formatr   r9   r,   r<   r=   cacherN   exc
start_time
pbi_resultend_timeresultrO   rL   s                r4   r^   QueryPowerBITool._runF   s'    %%j1151LL9:ML	2KK?LNN**%||3350025@+//1d + E **-2z*%%j11$e,!^
\\%%e%4
>%z2+H,A$+GHI**:65!8U z* %%j11ZZa0
Z"5"5599)00)e (%>    F"6"="=E"J 	:& !!*--A  	2/EcU-KDz*%%j11	2s   BH 
I H?9I?Ic                   #    U R                  U5      =n(       a  [        R                  SX5        U S3$  [        R                  SU5        U R                  R                  UU R                  R                  5       U R                  R                  5       U R                  U(       a  UR                  5       OSS9I Sh  vN nUS:X  a  XPR                  U'   U R                  U   $ [        R                  SU5        [        5       nU R                  R                  US	9I Sh  vN n[        5       n	[        R                  S
U5        [        R                  SX-
  S 35        U R                  U5      u  pUb*  SU;   d  SU;   a  SU R                  U'   U R                  U   $ UR!                  SS5      nU(       a>  XR"                  :  a/  U R%                  [&        R(                  " XUS9UUS-   S9I Sh  vN $ U
(       a  U
O[*        R(                  " US9U R                  U'   U R                  U   $  GNt! [         a+  nSU 3U R                  U'   U R                  U   s SnA$ SnAff = f GNK N{7f)r?   r@   z3, from cache, you have already asked this question.rA   NrB   rD   rE   zPBI Query: %srF   rH   rI   rJ   rK   
TokenErrorzkAuthentication token expired or invalid, please try to reauthenticate or check the scope of the credential.rL   r   rM   rP   rQ   rR   )r:   rS   rT   rU   r   apredictr   rW   rX   r   rY   rZ   r    r   arunr\   r]   r"   _arunr   r_   r   r`   s                r4   rl   QueryPowerBITool._arun|   sU     %%j1151LL9:MWOPP	2KK?L..11%||3350025@+//1d 2  E **-2z*%%j11OU+!^
<<,,U,;;
>%z2+H,A$+GHI**:6.E"9\U=R} z* %%j11ZZa0
Z"5"55)00)e (%> $    F"6"="=E"J 	:& !!*--Q  	2/EcU-KDz*%%j11	2 <sg   4I2BH5 >H2?H5 AI2"I-#CI24I05=I22H5 5
I*? I%I* I2%I**I20I2rd   c                 h   SU;   at  US   S   S   S   S   n[        U5      S:X  a  [        R                  S5        g[        U5      nU R	                  U5      u  pEU(       a  SU SU R
                   S	3S
4$ US
4$ SU;   a/  SUS   ;   a  SUS   S   ;   a  S
US   S   S   S   S   4$ S
US   4$ S
U4$ )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.NrO   z	pbi.errordetailsdetail)lenrS   rU   r   _result_too_larger#   )r9   rd   rp   rf   too_longlengths         r4   r\   QueryPowerBITool._parse_output   s!    
"i(+H5a8@D4yA~CD  %F#55f=Hqrxqy  zU  VZ  Vm  Vm  Un  nv  w  4<j z'22G!4[!AAZ0=iHKHUUUG,,,Zr7   rf   c                     U R                   (       ae  [        5       nUR                  U R                   5      n[        UR	                  U5      5      n[
        R                  SU5        X@R                  :  U4$ g)z!Tokenize the output of the query.zResult length: %s)Fr   )r$   r   encoding_for_modelrs   encoderS   rU   r#   )r9   rf   	tiktoken_encodingrv   s        r4   rt   "QueryPowerBITool._result_too_large   sb    ##(*I 33D4L4LMH01FKK+V4333V;;r7    N)'__name__
__module____qualname____firstlineno____doc__r   str__annotations__r   r   r   r   r   r   r   r   r   dictr    r   r"   intr#   r$   r   model_configr   classmethodr5   r:   r	   r^   r   rl   r   r\   boolrt   __static_attributes__r~   r7   r4   r   r      s   /D#K 
 Is#D1G^16Hhsm6$)$$MM4S>MNC"")-#- $L (#	  $.s .x} . <@4.4. 784. 	4.
 
4.r AE4.4. <=4. 	4.
 
4.l sCx. 	x}hsm+	, < dCi0@ r7   r   c                       \ rS rSr% SrSr\\S'   Sr\\S'   \	" SS9r
\\S	'   \" SS
9r SS\S\\   S\4S jjr SS\S\\   S\4S jjrSrg)InfoPowerBITool   z2Tool 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,   r<   r*   c                 V    U R                   R                  UR                  S5      5      $ )z4Get the schema for tables in a comma-separated list., )r   get_table_infosplitr9   r,   r<   s      r4   r^   InfoPowerBITool._run   s$     ||**:+;+;D+ABBr7   c                 r   #    U R                   R                  UR                  S5      5      I S h  vN $  N7f)Nr   )r   aget_table_infor   r   s      r4   rl   InfoPowerBITool._arun   s-     
 \\11*2B2B42HIIIIs   .757r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	   r^   r   rl   r   r~   r7   r4   r   r      s    < D# K  $D1G^1 $L <@CC 78C 
	C AEJJ <=J 
	J Jr7   r   c                       \ rS rSr% SrSr\\S'   Sr\\S'   \	" SS9r
\\S	'   \" SS
9r  SS\\   S\\   S\4S jjr  SS\\   S\\   S\4S jjrSrg)ListPowerBITool   z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,   r<   r*   c                 T    SR                  U R                  R                  5       5      $ zGet the names of the tables.r   joinr   rW   r   s      r4   r^   ListPowerBITool._run  s      yy55788r7   c                 \   #    SR                  U R                  R                  5       5      $ 7fr   r   r   s      r4   rl   ListPowerBITool._arun  s#      yy55788s   *,r~   )NNr   r~   r7   r4   r   r      s    (%D#%nKn#D1G^1 $L %);?9SM9 789 
	9 %)@D9SM9 <=9 
	9 9r7   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   	getLoggerr   rS   r   r   r   r~   r7   r4   <module>r      sq    4   - - * 7 7 C 
 M			8	$x DJh J@9h 9r7   