
    h+                         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Zd dl	m
Z
 d dlZd dlmZ d dlmZ d dlmZmZmZmZ d dlmZ dd	lmZ dd
lmZ erd dlmZ neZ G d de
      Z G d de      Zy)    N)TYPE_CHECKINGAnyOptionalUnion)	BaseModel)verbose_logger)Logging)AsyncHTTPHandlerHTTPHandler_get_httpx_clientget_async_httpx_client)ImageResponse   )
BaseAWSLLM)BedrockError)AWSPreparedRequestc                   :    e Zd ZU dZeed<   eed<   eed<   eed<   y)BedrockImagePreparedRequestzV
    Internal/Helper class for preparing the request for bedrock image generation
    endpoint_urlpreppedbodydataN)	__name__
__module____qualname____doc__str__annotations__r   bytesdict     d/var/www/Befach/backend/env/lib/python3.12/site-packages/litellm/llms/bedrock/image/image_handler.pyr   r      s     
K
Jr"   r   c                   v   e Zd ZdZ	 	 	 	 	 ddedededededee	e
ej                  f      d	ed
ee   dee   dee	eef      dee   fdZ	 ddedee	e
ej                  f      dededededee   defdZdeded
ee   dee   dededee   defdZdedededefdZdededededej*                  dedefdZy)BedrockImageGenerationz*
    Bedrock Image Generation handler
    Nmodelpromptmodel_responseoptional_paramslogging_objtimeoutaimg_generationapi_baseextra_headersclientapi_keyc                    | j                  ||||	|||      }|du r1| j                  |||||||
t        |
t              r|
      S d       S |
t        |
t              s
t               }
	 |
j                  |j                  |j                  j                  |j                        }|j                          | j'                  ||||||j(                        }|S # t        j                  $ r<}|j                  j                  }t!        ||j                  j"                        d }~wt        j$                  $ r t!        dd      w xY w)	N)r&   r)   r-   r.   r*   r'   r0   T)prepared_requestr+   r&   r*   r'   r(   r/   urlheadersr   status_codemessage  Timeout error occurred.)r(   r&   r*   r'   responser   )_prepare_requestasync_image_generation
isinstancer
   r   r   postr   r   r5   r   raise_for_statushttpxHTTPStatusErrorr;   r7   r   textTimeoutException+_transform_response_dict_to_openai_responser   )selfr&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r2   r;   err
error_codes                   r#   image_generationz'BedrockImageGeneration.image_generation-   s     00+'# 1 
 d"..!1'- )jAQ.R  /    /   >FK!@&(F	S{{'7'D'DN^NfNfNnNn  vF  vK  vK{  LH%%' II)#!&& J 
  $$ 	R11J:s||?P?PQQ%% 	S38QRR	Ss   +AC E-7D$$$Er2   returnc                 6  K   |xs' t        t        j                  j                  d|i      }	 |j	                  |j
                  |j                  j                  |j                         d{   }	|	j                          | j#                  ||||	|j$                  |      }|S 7 7# t        j                  $ r<}
|
j                  j                  }t        ||
j                  j                        d}
~
wt        j                   $ r t        dd      w xY ww)	z
        Asynchronous handler for bedrock image generation

        Awaits the response from the bedrock image generation endpoint
        r+   )llm_providerparamsr3   Nr6   r9   r:   )r&   r*   r'   r;   r   r(   )r   litellmLlmProvidersBEDROCKr?   r   r   r5   r   r@   rA   rB   r;   r7   r   rC   rD   rE   r   )rF   r2   r+   r&   r*   r'   r(   r/   async_clientr;   rG   rH   s               r#   r=   z-BedrockImageGeneration.async_image_generationi   s"      
!7 --55w'"

	S)..3C3P3PZjZrZrZzZz  BR  BW  BW.  X  XH%%' II#!&&) J 
 # X$$ 	R11J:s||?P?PQQ%% 	S38QRR	Ss:   ,D?B( .B&/B( #D&B( (D;7C22$DDc           	         | j                  ||      }|}	| j                  ||j                  |j                        \  }
}| d|	 d}| j	                  |||      }t        j                  |      j                  d      }ddi}|ddi|}| j                  |j                  |j                  |||||      }|j                  |d	|||j                  d
       t        ||||      S )a  
        Prepare the request body, headers, and endpoint URL for the Bedrock Image Generation API

        Args:
            model (str): The model to use for the image generation
            optional_params (dict): The optional parameters for the image generation
            api_base (Optional[str]): The base URL for the Bedrock API
            extra_headers (Optional[dict]): The extra headers to include in the request
            logging_obj (LitellmLogging): The logging object to use for logging
            prompt (str): The prompt to use for the image generation
        Returns:
            BedrockImagePreparedRequest: The prepared request object

        The BedrockImagePreparedRequest contains:
            endpoint_url (str): The endpoint URL for the Bedrock Image Generation API
            prepped (httpx.Request): The prepared request object
            body (bytes): The request body
        )r-   aws_bedrock_runtime_endpointaws_region_namez/model/z/invoke)r&   r'   r)   zutf-8zContent-Typezapplication/json)credentialsrT   r.   r   r   r5   r0    )complete_input_dictr-   r5   )inputr0   additional_args)r   r   r   r   )*_get_boto_credentials_from_optional_paramsget_runtime_endpointrS   rT   _get_request_bodyjsondumpsencodeget_request_headersrU   pre_callr5   r   )rF   r&   r)   r-   r.   r*   r'   r0   boto3_credentials_infomodelId_proxy_endpoint_urlr   r   r5   r   s                   r#   r<   z'BedrockImageGeneration._prepare_request   s=   8 "&!P!PU"

  $ 9 9)?)\)\2BB !: !

 !3377)7K%% & 

 zz$&&w/!#56$%'9K]KG**.::2BB'+ + 
 	'+."?? 	 	
 ++	
 	
r"   c                 t   |j                  d      d   }t        j                  |      }|j                  dd       i }|dk(  rt        j
                  j                  |      r,t        j
                  j                  ||      }t        |      S |j                  t        j                  d      }t        j                  j                         }|j                         D ]  \  }	}
|	|vs|
||	<    d|d	d
gi|}|S |dk(  r*t        t        j                  j                  ||            S t!        dd| d      )z
        Get the request body for the Bedrock Image Generation API

        Checks the model/provider and transforms the request body accordingly

        Returns:
            dict: The request body to use for the Bedrock Image Generation API
        .r   userN	stability)r'   r)    text_prompts   )rC   weightamazon)rC   r)   i  zUnsupported model=z, passed inr6   )splitcopydeepcopypoprN   AmazonStability3Config_is_stability_3_modeltransform_request_bodyr    replaceoslinesepAmazonStabilityConfig
get_configitemsAmazonNovaCanvasConfigr   )rF   r&   r'   r)   providerinference_paramsr   request_bodyconfigkvs              r#   r\   z(BedrockImageGeneration._get_request_body   sS    ;;s#A&==9D	
 {"--CCEJ&==TT!?  U   L))

C8 66AAC"LLNDAq!11./(+	 + #f%B$C&  !..EE F   +=eWK)P r"   r;   r   c                    |!|j                  |d|j                  d|i       t        j                  d|j                         |j	                         }|t        d      t        j                  j                  |      rt        j                  n?t        j                  j                  |      rt        j                  nt        j                  }|j                  ||       |S )zX
        Transforms the Image Generation response from Bedrock to OpenAI format
        rV   rW   )rX   r0   original_responserY   zraw model_response: %sz)Error in response object format, got None)r&   )r(   response_dict)	post_callrC   r   debugr]   
ValueErrorrN   rs   rt   r|   _is_nova_modelry   *transform_response_dict_to_openai_response)	rF   r(   r&   r*   r'   r;   r   r   config_classs	            r#   rE   zBBedrockImageGeneration._transform_response_dict_to_openai_response  s     "!!"*--!6 =	 "  	5x}}E  HII --CC%CP ** 11@@u@M ..22 	 	??)' 	@ 	

 r"   )FNNNN)N)r   r   r   r   r   r   r    LitellmLoggingr   r   floatrA   Timeoutboolr   r
   rI   r   r=   r<   r\   ResponserE   r!   r"   r#   r%   r%   (   s    !&"&(,AE!%:: : &	:
 : $: %u}} 456: : 3-:  ~: {,<<=>: #:H .2&5& %u}} 456& 	&
 $& & && )*& 
&PK
K
 K
 3-	K

  ~K
 $K
 K
 #K
 
%K
Z11 1 	1
 
1f(%( ( $	(
 ( ..( ( 
(r"   r%   ) rp   r]   rw   typingr   r   r   r   rA   pydanticr   rN   litellm._loggingr   *litellm.litellm_core_utils.litellm_loggingr	   r   &litellm.llms.custom_httpx.http_handlerr
   r   r   r   litellm.types.utilsr   base_aws_llmr   common_utilsr   botocore.awsrequestr   r   r%   r!   r"   r#   <module>r      s^      	 6 6    + P  . % '6) QZ Qr"   