
    j0                        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 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% G d de       Z&y)    N)TYPE_CHECKINGAnyOptionalUnion)	BaseModel) BEDROCK_INVOKE_PROVIDERS_LITERAL)verbose_logger)Logging)AmazonNovaCanvasConfig)AmazonStability3Config) AmazonTitanImageGenerationConfig)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     /Users/manta/Documents/Projects/TheRoad-I1/backend/.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   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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-   r1   r2   r.   r+   r4   T)prepared_requestr/   r*   r.   r+   r,   r3   urlheadersr   status_codemessage  Timeout error occurred.)r,   r*   r.   r+   responser   )_prepare_requestasync_image_generation
isinstancer   r   r   postr   r   r9   r   raise_for_statushttpxHTTPStatusErrorr?   r;   r   textTimeoutException+_transform_response_dict_to_openai_responser   )selfr*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r6   r?   err
error_codes                   r'   image_generationz'BedrockImageGeneration.image_generation7   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r6   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paramsr7   Nr:   r=   r>   )r*   r.   r+   r?   r   r,   )r   litellmLlmProvidersBEDROCKrC   r   r   r9   r   rD   rE   rF   r?   r;   r   rG   rH   rI   r   )rJ   r6   r/   r*   r.   r+   r,   r3   async_clientr?   rK   rL   s               r'   rA   z-BedrockImageGeneration.async_image_generations   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                  ||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*   providerr-   )r1   aws_bedrock_runtime_endpointaws_region_namez/model/z/invoke)r*   r+   r-   bedrock_providerzutf-8zContent-Typezapplication/json)credentialsrY   r2   r   r   r9   r4    )complete_input_dictr1   r9   )inputr4   additional_args)r   r   r   r   )*_get_boto_credentials_from_optional_paramsget_bedrock_invoke_providerget_bedrock_model_idget_runtime_endpointrX   rY   _get_request_bodyjsondumpsencodeget_request_headersr[   pre_callr9   r   )rJ   r*   r-   r1   r2   r.   r+   r4   boto3_credentials_inforZ   modelId_proxy_endpoint_urlr   r   r9   r   s                    r'   r@   z'BedrockImageGeneration._prepare_request   sn   8 "&!P!PU"

  ;;EB++%+ , 

 !% 9 9)?)\)\2BB !: !

 !3377)7K%%+-	 & 
 zz$&&w/!#56$%'9K]KG**.::2BB'+ + 
 	'+."?? 	 	
 ++	
 	
r&   rZ   c                    |dk(  s|dk(  rd}n|dk(  rd}n|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
        amazonnova	stability.r   userN)r+   r-    text_prompts   )rG   weight)rG   r-   i  zUnsupported model=z, passed inr:   )splitcopydeepcopypoprR   r   _is_stability_3_modeltransform_request_bodyr$   replaceoslinesepAmazonStabilityConfig
get_configitemsr   r   )rJ   r*   rZ   r+   r-   rW   inference_paramsr   request_bodyconfigkvs               r'   rd   z(BedrockImageGeneration._get_request_body   sw    x'+;v+EH,"H {{3'*H==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                  |      rt        }nJt        j                  |      rt        }n-t        j                  |      rt        }nt        j                  }|j                  ||       |S )zX
        Transforms the Image Generation response from Bedrock to OpenAI format
        r\   r]   )r^   r4   original_responser_   zraw model_response: %sz)Error in response object format, got None)r*   )r,   response_dict)	post_callrG   r	   debugre   
ValueErrorr   _is_titan_modelr   _is_nova_modelr   r|   rR   r   *transform_response_dict_to_openai_response)	rJ   r,   r*   r.   r+   r?   r   r   config_classs	            r'   rI   zBBedrockImageGeneration._transform_response_dict_to_openai_response,  s     "!!"*--!6 =	 "  	5x}}E  HII ,;;%H;L#22?1L#99F1L"88L??)' 	@ 	

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

  ~T
 $T
 T
 #T
 
%T
l99 ##CD9 	9
 9 
9v.%. . $	.
 . ... . 
.r&   r)   )'ry   re   r   typingr   r   r   r   rE   pydanticr   rR   r   litellm._loggingr	   *litellm.litellm_core_utils.litellm_loggingr
   r   <litellm.llms.bedrock.image.amazon_nova_canvas_transformationr   ;litellm.llms.bedrock.image.amazon_stability3_transformationr   6litellm.llms.bedrock.image.amazon_titan_transformationr   &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      sp      	 6 6    4 + P  . % '6) hZ hr&   