
    g)                         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 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)_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     ]/var/www/openai/venv/lib/python3.12/site-packages/litellm/llms/bedrock/image/image_handler.pyr   r      s     
K
Jr    r   c                   <   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   fdZdedee	e
ej                  f      dededededefdZdeded
ee   dee   ded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_headersc
                 <   | j                  ||||	||      }
|du r| j                  |
|||||      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%   T)prepared_requestr)   r$   r(   r%   r&   urlheadersr   status_codemessage  Timeout error occurred.)r&   r$   r(   r%   responser   )_prepare_requestasync_image_generationr
   postr   r   r1   r   raise_for_statushttpxHTTPStatusErrorr7   r3   r   textTimeoutException+_transform_response_dict_to_openai_responser   )selfr$   r%   r&   r'   r(   r)   r*   r+   r,   r.   clientr7   err
error_codes                  r!   image_generationz'BedrockImageGeneration.image_generation+   sO     00+'# 1 
 d"..!1'- /   #$	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B- -D 7C77$Dr.   returnc                 .  K   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paramsr/   Nr2   r5   r6   )r$   r(   r%   r7   r   r&   )r   litellmLlmProvidersBEDROCKr:   r   r   r1   r   r;   r<   r=   r7   r3   r   r>   r?   r@   r   )rA   r.   r)   r$   r(   r%   r&   async_clientr7   rC   rD   s              r!   r9   z-BedrockImageGeneration.async_image_generation^   s     . --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77C..$DDc                    	 ddl m} ddlm} | j                  |      }	|}
| j                  ||	j                  |	j                        \  }}| d|
 d} ||	j                  d|	j                        }| j                  |||	      }t        j                  |      j                  d
      }ddi}|ddi|} |d|||      }|j                  |       |d|v r|d   |j                  d<   |j!                         }|j#                  |d|||j                  d       t%        ||||      S # t        $ r t	        d      w xY w)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   )	SigV4Auth)
AWSRequestz7Missing boto3 to call bedrock. Run 'pip install boto3'.)r+   aws_bedrock_runtime_endpointaws_region_namez/model/z/invokebedrock)r$   r%   r'   zutf-8zContent-Typezapplication/jsonPOST)methodr0   r   r1   Authorization )complete_input_dictr+   r1   )inputapi_keyadditional_args)r   r   r   r   )botocore.authrO   botocore.awsrequestrP   ImportError*_get_boto_credentials_from_optional_paramsget_runtime_endpointrQ   rR   credentials_get_request_bodyjsondumpsencodeadd_authr1   preparepre_callr   )rA   r$   r'   r+   r,   r(   r%   rO   rP   boto3_credentials_infomodelId_proxy_endpoint_urlsigv4r   r   r1   requestr   s                      r!   r8   z'BedrockImageGeneration._prepare_request   s   6	Y/6 "&!P!P"

  $ 9 9)?)\)\2BB !: !

 !3377)7K".."22
 %% & 

 zz$&&w/!#56$%'9K]KG1g
 	w%/]*J/<_/MGOOO,//# 	'+."?? 	 	
 ++	
 	
e  	YWXX	Ys   D, ,Ec                    |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 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   )r>   weighti  zUnsupported model=z, passed inr2   )splitcopydeepcopypoprJ   AmazonStability3Config_is_stability_3_modeltransform_request_bodyr   replaceoslinesepAmazonStabilityConfig
get_configitemsr   )rA   r$   r%   r'   providerinference_paramsr   request_bodyconfigkvs              r!   rb   z(BedrockImageGeneration._get_request_body   s    ;;s#A&==9D	
 {"--CCEJ&==TT!?  U   L))

C8 66AAC"LLNDAq!11./(+	 + #f%B$C&  +=eWK)P r    r7   r   c                 l   |!|j                  |d|j                  d|i       t        j                  d|j                         |j	                         }|t        d      t        j                  j                  |      rt        j                  nt        j                  }|j                  ||       |S )zX
        Transforms the Image Generation response from Bedrock to OpenAI format
        rW   rX   )rY   rZ   original_responser[   zraw model_response: %sz)Error in response object format, got None)r$   )r&   response_dict)	post_callr>   r   debugrc   
ValueErrorrJ   r{   r|   r   *transform_response_dict_to_openai_response)	rA   r&   r$   r(   r%   r7   r   r   config_classs	            r!   r@   zBBedrockImageGeneration._transform_response_dict_to_openai_response	  s     "!!"*--!6 =	 "  	5x}}E  HII --CC%CP **.. 	
 	??)' 	@ 	

 r    )FNN)r   r   r   r   r   r   r   LitellmLoggingr   r   floatr<   TimeoutboolrE   r   r9   r8   rb   Responser@   r   r    r!   r#   r#   &   s    !&"&(,11 1 &	1
 1 $1 %u}} 4561 1 3-1  ~1f%5% %u}} 456% 	%
 $% % &% 
%NU
U
 U
 3-	U

  ~U
 $U
 U
 
%U
n++ + 	+
 
+Z$%$ $ $	$
 $ ..$ $ 
$r    r#   )rx   rc   r   typingr   r   r   r   r<   pydanticr   rJ   litellm._loggingr   *litellm.litellm_core_utils.litellm_loggingr	   r   &litellm.llms.custom_httpx.http_handlerr
   r   litellm.types.utilsr   base_aws_llmr   common_utilsr   r]   r   r   r#   r   r    r!   <module>r      sY      	 6 6    + P . % '6) GZ Gr    