
    i-                    <   d dl m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 d dlm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&ee'e   e'e   e'e   e'e   f   Z( G d de!      Z)y)    )annotationsN)TYPE_CHECKINGAnyOptionalUnion)	BaseModel)verbose_logger)Logging)AmazonNovaCanvasConfig)AmazonStabilityConfig)AmazonStability3Config) AmazonTitanImageGenerationConfig)AsyncHTTPHandlerHTTPHandler_get_httpx_clientget_async_httpx_client)ImageResponse   )
BaseAWSLLM)BedrockError)AWSPreparedRequestc                  :    e Zd ZU dZded<   ded<   ded<   ded	<   y
)BedrockImagePreparedRequestzV
    Internal/Helper class for preparing the request for bedrock image generation
    strendpoint_urlr   preppedbytesbodydictdataN)__name__
__module____qualname____doc____annotations__     /Users/manta/Documents/Projects/TheRoad-I1/.venv/lib/python3.12/site-packages/litellm/llms/bedrock/image_generation/image_handler.pyr   r   )   s     
K
Jr'   r   c                      e Zd ZdZed
d       Z	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ		 	 	 	 	 	 	 	 ddZ
	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	Zy)BedrockImageGenerationz*
    Bedrock Image Generation handler
    c                    t        j                  |      rt         S t        j                  |      rt        S t	        j
                  |      rt        S t        j                  S N)r   _is_titan_modelr   _is_nova_modelr   _is_stability_3_modellitellmr   )clsmodels     r(   get_config_classz'BedrockImageGeneration.get_config_classA   sJ    +;;EB33#2259))#99%@))000r'   Nc                   | 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)r2   optional_paramsapi_baseextra_headerslogging_objpromptapi_keyT)prepared_requesttimeoutr2   r8   r9   model_responseclienturlheadersr    status_codemessage  Timeout error occurred.)r=   r2   r8   r9   responser    )_prepare_requestasync_image_generation
isinstancer   r   r   postr   r   rA   r   raise_for_statushttpxHTTPStatusErrorrG   rC   r   textTimeoutException+_transform_response_dict_to_openai_responser    )selfr2   r9   r=   r5   r8   r<   aimg_generationr6   r7   r>   r:   r;   rG   err
error_codes                   r(   image_generationz'BedrockImageGeneration.image_generationL   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c                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paramsr?   NrB   rE   rF   )r2   r8   r9   rG   r    r=   )r   r0   LlmProvidersBEDROCKrK   r   r   rA   r   rL   rM   rN   rG   rC   r   rO   rP   rQ   r    )rR   r;   r<   r2   r8   r9   r=   r>   async_clientrG   rT   rU   s               r(   rI   z-BedrockImageGeneration.async_image_generation   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                n    i }|j                  dd      }|j                  dd      }|||d<   |||d<   |S )z`
        Extract guardrail parameters from optional_params and convert them to headers.
        guardrailIdentifierNguardrailVersionz"x-amz-bedrock-guardrail-identifierzx-amz-bedrock-guardrail-version)pop)rR   r5   rA   guardrail_identifierguardrail_versions        r(   %_extract_headers_from_optional_paramsz<BedrockImageGeneration._extract_headers_from_optional_params   sX     .223H$O+//0BDI+<PG89(9JG56r'   c           	     \   | j                  ||      }| j                  |      }	| j                  ||	|      }
| j                  ||j                  |j
                        \  }}| d|
 d}| j                  |||      }t        j                  |      j                  d      }ddi}|ddi|}| j                  |      }|j                  |       | 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
        )r2   providerr5   )r6   aws_bedrock_runtime_endpointaws_region_namez/model/z/invoke)r2   r9   r5   zutf-8zContent-Typezapplication/json)credentialsrg   r7   r   r    rA   r:    )complete_input_dictr6   rA   )inputr:   additional_args)r   r   r   r    )*_get_boto_credentials_from_optional_paramsget_bedrock_invoke_providerget_bedrock_model_idget_runtime_endpointrf   rg   _get_request_bodyjsondumpsencoderc   updateget_request_headersrh   pre_callrA   r   )rR   r2   r5   r6   r7   r8   r9   r:   boto3_credentials_infobedrock_providermodelId_proxy_endpoint_urlr    r   rA   guardrail_headersr   s                     r(   rH   z'BedrockImageGeneration._prepare_request   s   8 "&!P!PU"

  ;;EB++%+ , 

 !% 9 9)?)\)\2BB !: !

 !3377)7K%%+ & 
 zz$&&w/!#56$%'9K]KG !FFW()**.::2BB'+ + 
 	'+."?? 	 	
 ++	
 	
r'   c                b    | j                  |      }|j                  ||      }t        |      S )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
        r2   )rO   r5   )r3   transform_request_bodyr   )rR   r2   r9   r5   config_classrequest_bodys         r(   rq   z(BedrockImageGeneration._get_request_body  s>     ,,5,9#:: ; 
 L!!r'   c                   |!|j                  |d|j                  d|i       t        j                  d|j                         |j	                         }|t        d      | j                  |      }|j                  ||       |S )zX
        Transforms the Image Generation response from Bedrock to OpenAI format
        ri   rj   )rk   r:   original_responserl   zraw model_response: %sz)Error in response object format, got Noner   )r=   response_dict)	post_callrO   r	   debugrr   
ValueErrorr3   *transform_response_dict_to_openai_response)	rR   r=   r2   r8   r9   rG   r    r   r   s	            r(   rQ   zBBedrockImageGeneration._transform_response_dict_to_openai_response,  s     "!!"*--!6 =	 "  	5x}}E  HII,,5,9??)' 	@ 	

 r'   )r2   z
str | NonereturnBedrockImageConfigClass)FNNNN)r2   r   r9   r   r=   r   r5   r   r8   LitellmLoggingr<   %Optional[Union[float, httpx.Timeout]]rS   boolr6   Optional[str]r7   Optional[dict]r>   z.Optional[Union[HTTPHandler, AsyncHTTPHandler]]r:   r   r,   )r;   r   r<   r   r2   r   r8   r   r9   r   r=   r   r>   zOptional[AsyncHTTPHandler]r   r   )r5   r   r   r   )r2   r   r5   r   r6   r   r7   r   r8   r   r9   r   r:   r   r   r   )r2   r   r9   r   r5   r   r   r   )r=   r   r2   r   r8   r   r9   r   rG   zhttpx.Responser    r   r   r   )r!   r"   r#   r$   classmethodr3   rV   rI   rc   rH   rq   rQ   r&   r'   r(   r*   r*   <   s    1 1$ !&"&(,AE!%:: : &	:
 : $: 7: :  : &: ?: :H .2&5& 7& 	&
 $& & && +& 
&PW
W
 W
  	W

 &W
 $W
 W
 W
 
%W
r"" " 	"
 
"(!%! ! $	!
 ! !! ! 
!r'   r*   )*
__future__r   rr   typingr   r   r   r   rM   pydanticr   r0   litellm._loggingr	   *litellm.litellm_core_utils.litellm_loggingr
   r   Glitellm.llms.bedrock.image_generation.amazon_nova_canvas_transformationr   Flitellm.llms.bedrock.image_generation.amazon_stability1_transformationr   Flitellm.llms.bedrock.image_generation.amazon_stability3_transformationr   Alitellm.llms.bedrock.image_generation.amazon_titan_transformationr   &litellm.llms.custom_httpx.http_handlerr   r   r   r   litellm.types.utilsr   base_aws_llmr   common_utilsr   botocore.awsrequestr   r   typer   r*   r&   r'   r(   <module>r      s    "  6 6    + P  . % '6)   	)*	 	 	! QZ Qr'   