
    hg5              "          d dl Z d dlmZ d dlmZmZmZmZmZ d dlZd dl	Z	d dl
Z
d dlmZ ddlmZ  ej                         d        Zej!                          ej"                  ded	
       ej"                  ded
       ej"                  ded
       ej"                  ded
       ej"                  ded
       ej"                  ded
       ej"                  ded
       ej"                  dddd       ej"                  ddd       ej"                  dd ej(                  d d!g      d d"#      ej*                  d$ej,                  d%ee   d&ee   d'ee   d(ee   d)ee   d*ee   d+ee   d,eded-   d.efd/                                                                                    Zej!                          ej"                  d0ed1
       ej"                  d2ed3
       ej"                  d4ed5
       ej"                  d6ed7
       ej"                  ded8
       ej"                  ded9
       ej"                  ded:
       ej"                  d;ed<
       ej"                  d=ed>
      ej*                  d$ej,                  d?ee   d@ee   dAee   dBee   d+ee   d(ee   d'ee   dCee   dDee   fdE                                                                             Zej!                          ej"                  dFedG
       ej"                  dHedI
      ej*                  d$ej,                  dJee   dKee   fdL                            ZdMee   dNee   fdOZdPedQedNeeeef      fdRZdSeeeef      dTee   dMedNeeeef      fdUZdSeeeef      dNdfdVZdWeeef   dNeeef   fdXZ dSeeeef      dYedNe!eef   fdZZ"ej!                  d[\       ej"                  d]dd^_       ej"                  d`dab       ej"                  dcddd       ej"                  dedfb      ej*                  d$ej,                  dQedgee   dhedMee   f
di                                          Z#y)j    N)datetime)LiteralOptionalListDictAny)Table   )KeysManagementClientc                       y)z,Manage API keys for the LiteLLM proxy serverN r       b/var/www/Befach/backend/env/lib/python3.12/site-packages/litellm/proxy/client/cli/commands/keys.pykeysr      s     	r   z--pagezPage number for pagination)typehelpz--sizezNumber of items per pagez	--user-idzFilter keys by user IDz	--team-idzFilter keys by team IDz--organization-idzFilter keys by organization IDz
--key-hashzFilter by specific key hashz--key-aliaszFilter by key aliasz--return-full-objectTzReturn the full key object)is_flagdefaultr   z--include-team-keysz!Include team keys in the response)r   r   z--formatoutput_formattablejsonzOutput format (table or json))r   r   r   ctxpagesizeuser_idteam_idorganization_idkey_hash	key_aliasinclude_team_keys)r   r   return_full_objectc                    t        | j                  d   | j                  d         }|j                  ||||||||
|	      }t        |t              sJ |	dk(  rt        j                  |       yt        j                  dt        |j                  dg              d|j                  d	d
              t        d      }|j                  dd       |j                  dd       |j                  dd       |j                  dd       |j                  dd       |j                  dg       D ]  }|j                  t        |j                  dd            t        |j                  dd            t        |j                  dd            t        |j                  dd            t        |j                  dd                    t        j                  |       y)zList all API keysbase_urlapi_key)	r   r   r   r   r   r   r   r!   r    r   datazShowing r   z keys out of total_countr   zAPI KeystitlezKey HashcyanstyleAliasgreenUser IDmagentazTeam IDyellowSpendredtoken r   r   r   spendN)r   objlist
isinstancedictrich
print_jsonprintlengetr	   
add_columnadd_rowstr)r   r   r   r   r   r   r   r   r    r   r!   clientresponser   keys                  r   r8   r8      s   @ "#''*"5swwy7IJF{{'-+  
H h%%%X&

Xc(,,vr":;<M(,,WdfgJhIijkJ'620)4(3.<<+CMMCGGGR()CGGK,-CGGIr*+CGGIr*+CGGGR() , 	

5r   z--modelsz&Comma-separated list of allowed modelsz	--aliasesz#JSON string of model alias mappingsz--spendz Maximum spend limit for this keyz
--durationz6Duration for which the key is valid (e.g. '24h', '7d')zAlias/name for the keyz!Team ID to associate the key withz!User ID to associate the key withz--budget-idz#Budget ID to associate the key withz--configz2JSON string of additional configuration parametersmodelsaliasesr6   duration	budget_idconfigc
                    t        | j                  d   | j                  d         }
	 |r-|j                  d      D cg c]  }|j                          c}nd}|rt	        j
                  |      nd}|	rt	        j
                  |	      nd}	 |
j                  |||||||||	      }t        j                  |       yc c}w # t        j                  $ r&}t        j                  dt        |             d}~ww xY w# t        j                  j                  $ r}t        j                   d|j"                  j$                   d	
       	 |j"                  j	                         }t        j                  |       t        j(                         # t        j                  $ rA t        j                   |j"                  j&                  d	
       Y t        j(                         w xY wd}~ww xY w)zGenerate a new API keyr#   r$   ,NzInvalid JSON: )	rF   rG   r6   rH   r   r   r   rI   rJ   r%   Error: HTTP Terr)r   r7   splitstripr   loadsJSONDecodeErrorclickBadParameterrB   generater;   r<   requests
exceptions	HTTPErrorechorD   status_codetextAbort)r   rF   rG   r6   rH   r   r   r   rI   rJ   rC   mmodels_listaliases_dictconfig_dicterD   
error_bodys                     r   rV   rV   V   s   0 "#''*"5swwy7IJF<@F&,,s*;<Qqwwy<D.5tzz'*4,2djj(??  # 

 	X&# =  <  >#a&!:;;< (( 

\!**"8"8!9:E	2*JOO, kkm ## 	2JJqzzD1kkm	2sd   C B=7C 0C> =C C;!C66C;>G*.G%
0F:G%>G"G%!G""G%%G*z--keysz*Comma-separated list of API keys to deletez--key-aliasesz-Comma-separated list of key aliases to deleter   key_aliasesc                 Z   t        | j                  d   | j                  d         }|r-|j                  d      D cg c]  }|j                          c}nd}|r-|j                  d      D cg c]  }|j                          c}nd}	 |j	                  ||      }t        j                  |       yc c}w c c}w # t        j                  j                  $ r}	t        j                  d|	j                  j                   d	       	 |	j                  j                         }
t        j                  |
       t        j"                         # t        j                  $ rA t        j                  |	j                  j                   d	       Y t        j"                         w xY wd}	~	ww xY w)
zDelete API keys by key or aliasr#   r$   rL   N)r   rd   r%   rM   TrN   )r   r7   rP   rQ   deleter;   r<   rW   rX   rY   rT   rZ   rD   r[   r   rS   r\   r]   )r   r   rd   rC   k	keys_listaaliases_listrD   rb   rc   s              r   rf   rf      s:    "#''*"5swwy7IJF8<DJJsO4q4$IBM{'8'8'=>!AGGI>SWL
==i\=JX&	 5> (( 

\!**"8"8!9:E	2*JOO, kkm ## 	2JJqzzD1kkm	2sG   B4-B9
)B> >F*.F%
0E:F%>F"F%!F""F%%F*created_sincereturnc                     | sy	 d| v rt        j                  | d      S t        j                  | d      S # t        $ r0 t        j                  d|  dd       t        j
                         w xY w)	z1Parse and validate the created_since date filter.N_z%Y-%m-%d_%H:%Mz%Y-%m-%dzError: Invalid date format 'z%'. Use YYYY-MM-DD_HH:MM or YYYY-MM-DDTrN   )r   strptime
ValueErrorrT   rZ   r]   )rk   s    r   _parse_created_since_filterrq      sq    -$$]4DEE$$]J?? 

1-@eflpqkkms   5 5 9A.source_clientsource_base_urlc                 ^   t        j                  d|        g }d}d}	 | j                  d||      }t        |t              sJ d       |j                  dg       }|s	 |S |j                  |       t        j                  d| d	t        |       d
       t        |      |k  r	 |S |dz  })z5Fetch all keys from source instance using pagination.z"Fetching keys from source server:    d   T)r!   r   r   z$Expected dict response from list APIr   zFetched page : z keys)rT   rZ   r8   r9   r:   r?   extendr>   )rr   rs   source_keysr   	page_sizesource_response	page_keyss          r   _fetch_all_keys_with_paginationr}      s    	JJ3O3DEFKDI
',,4V_,`/40X2XX0#''3	  	9%

]4&3y>*:%@A y>I%  		! r   ry   created_since_dtc                    |s| S g }| D ]  }|j                  d      }|st        |t              s(d|v r&t        j                  |j                  dd            }nt        j                  |      }|j                  r|j                  d      }||k\  s|j                  |        t        j                  dt        |        dt        |       d	|        |S )
z/Filter keys by created_since date if specified.
created_atTZ+00:00N)tzinfoz	Filtered z	 keys to z keys created since )r?   r9   rB   r   fromisoformatreplacer   appendrT   rZ   r>   )ry   r~   rk   filtered_keysrE   key_created_atkey_dts          r   _filter_keys_by_created_sincer      s     M..#..(%33N4J4J3PX4YZF%33NCF ==#^^4^8F--!((- " 
JJ3{+,Ic-6H5II]^k]lmnr   c           
      H   t        j                  d       t        d      }|j                  dd       |j                  dd       |j                  d	d
       | D ]  }|j	                  dd      }|rJt        |t              r:d|v r6t        j                  |j                  dd            }|j                  d      }|j                  t        |j	                  dd            t        |j	                  dd            t        |              t        j                  |       y)z?Display a table of keys that would be imported in dry-run mode.z
--- DRY RUN MODE ---zKeys that would be importedr(   z	Key Aliasr.   r+   r/   r0   Createdr*   r   r5   r   r   r   z%Y-%m-%d %H:%Mr   r   N)rT   rZ   r	   r@   r?   r9   rB   r   r   r   strftimerA   r;   r=   )ry   r   rE   r   dts        r   _display_dry_run_tabler      s    	JJ'(56E	[0	Yi0	Yf-WW\2.
*c**$!//
0B0B30QRB!#-=!>Jc#''+r23SB9O5PRUV`Rab  	JJur   rE   c                 L    i }dD ]  }| j                  |      s| |   ||<    |S )z:Prepare key data for import by extracting relevant fields.)rF   rG   r6   r   r   r   rI   rJ   )r?   )rE   import_datafields      r   _prepare_key_import_datar     s6    K j775>!$UK j r   dest_clientc           
         d}d}| D ]g  }	 t        |      } |j                  di |}t        j                  d|        |dz  }|j	                  dd      }t        j                  d|        i ||fS # t
        $ rG}|dz  }|j	                  dd      }t        j                  d| dt        |       d	
       Y d}~d}~ww xY w)z>Import each key to the destination instance and return counts.r   zGenerated key: ru   r   zN/Au   ✓ Imported key: u   ✗ Failed to import key rw   TrN   Nr   )r   rV   rT   rZ   r?   	ExceptionrB   )	ry   r   imported_countfailed_countrE   r   rD   r   rb   s	            r   _import_keys_to_destinationr     s     NL	T237K ,{++:k:HJJ
34aNU3IJJ+I;78 & <''  	TALU3IJJ29+RAxHdSS	Ts   A$A55	C>=C  Cimport)namez--source-base-urlz?Base URL of the source LiteLLM proxy server to import keys from)requiredr   z--source-api-keyz/API key for authentication to the source server)r   z	--dry-runz6Show what would be imported without actually importingz--created-sincezVOnly import keys created after this date/time (format: YYYY-MM-DD_HH:MM or YYYY-MM-DD)source_api_keydry_runc                    t        |      }t        ||      }t        | j                  d   | j                  d         }	 t        ||      }|rt	        |||      }|st        j                  d       yt        j                  dt        |       d       |rt        |       yt        ||      \  }	}
t        j                  d       t        j                  d|	        t        j                  d	|
        t        j                  d
t        |              y# t        j                  j                  $ r}t        j                  d|j                  j                   d       	 |j                  j                         }t!        j"                  |       t        j(                         # t        j$                  $ rA t        j                  |j                  j&                  d       Y t        j(                         w xY wd}~wt*        $ r<}t        j                  dt-        |       d       t        j(                         d}~ww xY w)z-Import API keys from another LiteLLM instancer#   r$   z!No keys found in source instance.NzFound z keys in source instance.z
Import completed:z  Successfully imported: z  Failed to import: z  Total keys processed: rM   TrN   r%   zError: )rq   r   r7   r}   r   rT   rZ   r>   r   r   rW   rX   rY   rD   r[   r   r;   r<   rS   r\   r]   r   rB   )r   rs   r   r   rk   r~   rr   r   ry   r   r   rb   rc   s                r   import_keysr   +  s    3=A ).IM&swwz':CGGI<NOK%5m_U 7EUWdeKJJ:;

VC,--FGH";/ (C;P['\$ 	

()

.~.>?@

),89

-c+.>-?@A(( 

\!**"8"8!9:E	2*JOO, kkm ## 	2JJqzzD1kkm	2  

WSVH%40kkmsT   2D 2/D "A5D I5.G?$0F(G?(>G<&G?;G<<G??I7II)$r   r   typingr   r   r   r   r   rT   r;   rW   
rich.tabler	   r   r   groupcommandoptionintrB   Choicepass_contextContextboolr8   floatrV   rf   rq   r}   r   r   r   tupler   r   r   r   r   <module>r      s     5 5     ( 	 	
 hS'CDhS'ABk*BCk*BC!2RSl+HIm#,AB$dDGcd#T8[\	w'	(	( .	.
3-. 3-. c]	.
 c]. c]. sm. }. . ?+. .  ] e C J T D D C E $.b js)QRk*OPie*LMl+cdm#,DEk*MNk*MNm#,QRjs)]^(	(SM( c]( E?	(
 sm( }( c]( c]( }( SM(  _ S O O F e N Q S (V hS'SToC.]^ Xc] #   _ U $x} (AS  3G Z] bfgkloqtltgubv 8d38n%9A(9K\_	$sCx.:T#s(^(<  .	$sCx. 	T#s(^ 	(d38n%(4H(
38_(: 8$-n  'XYk4.fgt 0	0),0>Fsm0VZ0kstwkx0  h Z 0r   