
    6iSJ                       d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ddZ	 	 	 	 	 	 dd	Z	 	 	 	 	 	 dd
ZddZddZddZ	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZej,                  eedej.                  eediZy)zAWS Bedrock-specific utilities.

This module contains utilities specific to the AWS Bedrock provider,
including reask functions, response handlers, and message formatting.
    )annotationsN)dedent)Any   )Modec                    | j                         }d| j                  | j                  xs d| j                   dd|idiS )aD  
    Generate Bedrock tool schema from a Pydantic model.

    Bedrock Converse API expects tools in this format:
    {
        "toolSpec": {
            "name": "tool_name",
            "description": "tool description",
            "inputSchema": {
                "json": { JSON Schema }
            }
        }
    }
    toolSpeczCorrectly extracted `z5` with all the required parameters with correct typesjson)namedescriptioninputSchema)model_json_schema__name____doc__)response_modelschemas     m/root/.openclaw/workspace/visionaryfx/venv/lib/python3.12/site-packages/instructor/providers/bedrock/utils.pygenerate_bedrock_schemar      sZ     --/F 	"++)11 v&~'>'>&??tu"F+	
     c                    | j                         } |d   d   g}|j                  ddd| igd       | d   j                  |       | S )z
    Handle reask for Bedrock JSON mode when validation fails.

    Kwargs modifications:
    - Adds: "messages" (user message requesting JSON correction)
    outputmessageusertextz@Correct your JSON ONLY RESPONSE, based on the following errors:
rolecontentmessagescopyappendextend)kwargsresponse	exception
reask_msgss       r   reask_bedrock_jsonr'   .   sl     [[]F8$Y/0J _`i_jk	
	 :j)Mr   c           	         | j                         } |d   d   }|g}d}d|v r|d   D ]  }d|v s|d   d   } n |r#|j                  dd|d	d
| digddigd       n|j                  dd	d| digd       | d   j                  |       | S )z
    Handle reask for Bedrock tools mode when validation fails.

    Kwargs modifications:
    - Adds: "messages" (assistant message with tool use, then user message with tool result error)
    r   r   Nr   toolUse	toolUseIdr   
toolResultr   zValidation Error found:
z.
Recall the function correctly, fix the errorserror)r*   r   statusr   z,Validation Error due to no tool invocation:
r   r   )r#   r$   r%   assistant_messager&   tool_use_idcontent_blocks          r   reask_bedrock_toolsr1   I   s    [[]F !*95#$J K%%.y9 	MM)+I6{C	  %)4 %+.G	{  SB  -C!"(
 '.'
	
( 	 "OPY{  [J  !K		
 :j)Mr   c                    | sy| j                         j                         }d|v r|j                  dd      d   }|dv ry|dv ry|dv ry|d	v ry
y)zy
    Map common/variant image types to Bedrock's required image.format enum:
    one of {'gif','jpeg','png','webp'}.
    jpeg/   )jpgpjpegzx-jpegzx-jpg)pngzx-pngr8   )gifzx-gifr9   )webpz
image/webpr:   )striplowersplit)mime_or_extvals     r   _normalize_bedrock_image_formatr@      sp    
 




#
#
%C
cziiQ"
11


$$r   c                f   | j                  d      xs i j                  d      }|st        d      t        j                  |      d   xs d}t	        |      }|j                  d      rA	 |j                  dd      \  }}d|vrt        d      d|dt        j                  |      idiS |j                  d      rg	 t        j                   |d      }|j                          |j                  j                  d      }|rd|v rt	        |      }d|d|j                  idiS t        d      # t        $ r}t        d	      |d
}~ww xY w# t        j                  j                  $ r}t        d|       |d
}~wt        j                  j                  $ r}t        d| d|       |d
}~wt        j                  j                   $ r}t        d| d|       |d
}~wt        j                  j"                  $ r}t        d| d|       |d
}~wt$        $ r}t        d| d|       |d
}~ww xY w)z
    Convert OpenAI-style image part:
      {"type":"image_url","image_url":{"url": "<data:... or http(s):...>"}}
    into Bedrock Converse image content:
      {"image":{"format": "<fmt>","source":{"bytes": <raw-bytes>}}}
    	image_urlurlz6image_url.url is required for OpenAI-style image partsr   z
image/jpegzdata:,r5   z!Invalid data URL in image_url.urlNz;base64z/Only base64 data URLs are supported for Bedrockimagebytes)formatsource)zhttp://zhttps://   )timeoutzContent-Typer4   z$Timed out while fetching image from z+Connection error while fetching image from z: z%HTTP error while fetching image from z(Request error while fetching image from z+Unexpected error while fetching image from zFUnsupported image_url scheme. Use http(s) or data:image/...;base64,...)get
ValueError	mimetypes
guess_typer@   
startswithr=   base64	b64decoderequestsraise_for_statusheadersr   
exceptionsTimeoutConnectionError	HTTPErrorRequestException	Exception)	partrB   guessed_mimefmtheaderb64erespctypes	            r   _openai_image_part_to_bedrockrc      s^    +&,"11%8IQRR''	215EL
),
7C G$	I#//#q1KFC F"NOOCGV=M=Mc=R3STUU 
		5	6	<<	26D!!#LL$$^4E5e<7NOPP( T
 	
E  	I@AqH	I ""** 	XCI;OPVWW""22 	=i[1#N "",, 	7	{"QCH ""33 	:9+RsK  	=i[1#N	sa   +D. =A%E .	E7EEH0(E77 H0F)) H0	G H0;HH0H++H0c                   t        | t              rd| igS t        | t              rg }| D ]  }t        |t              rd|v r|j	                  d      }|dv r<|j	                  d      xs |j	                  d      xs d}|j                  d|i       i|dk(  r|j                  t        |             t        d|       t        |t              rd|v rBt        |d   t              r/t        |j                               dhk(  r|j                  |       d|v r&t        |d   t              r|j                  |       d	|v r&t        |d	   t              r|j                  |       At        d
|       t        |t              r|j                  d|i       tt        dt        |              |S t        dt        |              )a  
    Normalize content into Bedrock Converse content list.

    Allowed inputs:
      - string -> [{"text": "..."}]
      - list of parts:
          OpenAI-style:
            {"type":"text","text":"..."}
            {"type":"input_text","text":"..."}
            {"type":"image_url","image_url":{"url":"<data:... or https:...>"}}
          Bedrock-native (passed through as-is):
            {"text":"..."}
            {"image":{"format":"jpeg|png|gif|webp","source":{"bytes": <raw bytes>}}}
            {"document":{"format":"pdf|csv|doc|docx|xls|xlsx|html|txt|md","name":"...","source":{"bytes": <raw bytes>}}}

    Note:
      - We do not validate or normalize Bedrock-native image/document blocks here.
        Caller is responsible for providing valid 'format' and raw 'bytes'.
    r   type)r   
input_textrf    rB   z0Unsupported OpenAI-style part type for Bedrock: rE   documentz&Unsupported dict content for Bedrock: z&Unsupported content part for Bedrock: z.Unsupported message content type for Bedrock: )
isinstancestrlistdictrK   r!   rc   rL   setkeysre   )r   itemspttxts        r   _to_bedrock_content_itemsrs      s   * '3!"" '4 &( '	QA!T"v{EE&M..%%-D155+>D"CLL&#/#LL!>q!AB #STUSV!WXX !T" aK"1V9c2AFFH&1LLOa<Jqz4$@LLO?z!J-'FLLO #I!!MNN !S!fa[)Ed1gYOPPO'	QP 
Ed7m_U
VVr   c                J   d| v rit        | d   t              rV| j                  d      }|rCt        |d   t              r0d|d   v r)|d   d   }d| vrg | d<   | d   j	                  dd|d       d| v rd| vr| j                  d      | d<   i }d| v r| j                  d      |d<   d	| v r| j                  d	      |d
<   nd
| v r| j                  d
      |d
<   d| v r| j                  d      |d<   nd| v r| j                  d      |d<   d| v r>| j                  d      }t        |t
              r|g|d<   nGt        |t              r7||d<   n1d| v r| j                  d      |d<   nd| v r| j                  d      |d<   |r1d| v r(| d   }|j                         D ]  \  }}||vs|||<    n|| d<   d| v rt        | d   t              r| j                  d      }g }	g }
|D ]  }t        |t              s|
j                  |       %|j                         }|j                  d      }|j                  d      }|dk(  r<t        |t
              r|	j                  d|i       t        dt        |       d      d|v rt        |      |d<   |
j                  |        |	r|	| d<   |
| d<   | S )a(  
    Prepare kwargs for the Bedrock Converse API.

    Kwargs modifications:
    - Moves: system list to messages as a system role
    - Renames: "model" -> "modelId"
    - Collects: temperature, max_tokens, top_p, stop into inferenceConfig
    - Converts: messages content to Bedrock format
    systemr   r   r   r   modelmodelIdtemperature
max_tokens	maxTokenstop_ptopPstopstopSequencesstop_sequencesinferenceConfigr   r   z\System message content must be a string for Bedrock processing by this handler. Found type: .)ri   rk   poprl   insertrj   ro   r!   r    rK   rL   re   rs   )call_kwargssystem_contentsystem_textinference_config_paramsstop_valexisting_inference_configkeyvalueoriginal_input_messagesbedrock_system_list$bedrock_user_assistant_messages_listmsg_dictcurrent_message_for_apir   r   s                  r   )_prepare_bedrock_converse_kwargs_internalr     sH    ;:k(.CT#J$2>!,d3.++ )+F3K,*,J'
#**H=
 +);">!,!9I ! #1<1O. {"/:|/L,		#/:{/K, +*5//'*B'	;	*5//&*A' ??6*h$8@z#O4$'7?#O4	[	(3>??CS3T0;&3>???3S0
 + )44E(F%5;;= ;
U775:-c2; .EK)* [ ZJ0G%N"-//*"=46EG,/ 	UHh-
 5;;HE '/mmo#*..v6D-11G xgs+'../@A$''+G}oQ8 
  779R:+I6 5;;<ST?	UB $7K!
 #GJr   c                ,   t        |      }t        dt        j                  | j	                         dd       d      }|j                  dd      }|sd|ig|d<   | |fS t        |t              st        d	      |j                  d|i       ||d<   | |fS )
z
    Handle Bedrock JSON mode.

    Kwargs modifications:
    - Adds: "response_format" with json_schema
    - Adds/Modifies: "system" (prepends JSON instructions)
    - Applies: _prepare_bedrock_converse_kwargs_internal transformations
    z
        As a genius expert, your task is to understand the content and provide
        the parsed objects in json that match the following json_schema:


           F)indentensure_asciiz

        Make sure to return an instance of the JSON, not the schema itself
        and don't include any other text in the response apart from the json
        ru   Nr   zsystem must be a list of SystemMessage, refer to:
                https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse.html
                )
r   r   r
   dumpsr   r   ri   rk   rL   r!   )r   
new_kwargsjson_messagesystem_messages       r   handle_bedrock_jsonr     s     ;:FJ	 
N446qu	UV W			
L  ^^Hd3N!' 67
8 :%% .$/ 
 	v|45-
8:%%r   c                p    t        |      }| d|fS t        |       }|gdd| j                  iid|d<   | |fS )ac  
    Handle Bedrock tools mode.

    Kwargs modifications:
    - When response_model is None: Only applies _prepare_bedrock_converse_kwargs_internal transformations
    - When response_model is provided:
      - Adds: "toolConfig" with tools list and toolChoice configuration
      - Applies: _prepare_bedrock_converse_kwargs_internal transformations
    Ntoolr   )tools
toolChoice
toolConfig)r   r   r   )r   r   tool_schemas      r   handle_bedrock_toolsr     s^     ;:FJZ *.9K (?(?@A J|
 :%%r   )reaskr$   )r   	type[Any]returndict[str, Any])r#   r   r$   r   r%   rZ   )r>   rj   r   rj   )r[   r   r   r   )r   r   r   zlist[dict[str, Any]])r   r   r   r   )r   r   r   r   r   z tuple[type[Any], dict[str, Any]])r   ztype[Any] | Noner   r   r   z'tuple[type[Any] | None, dict[str, Any]])r   
__future__r   rP   r
   rM   rR   textwrapr   typingr   moder   r   r'   r1   r@   rc   rs   r   r   r   BEDROCK_JSONBEDROCK_TOOLSBEDROCK_HANDLERS r   r   <module>r      s   #       6 6;;; ;|*6
rEWPAAAH$&$&+9$&%$&N&$&2@&,&> 	#' 	$(	 r   