
    g4                       d dl mZ d dlmZ d dlmZ d dlmZm	Z	 d dl
mZmZmZmZ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mZm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z) ddlm*Z*m+Z+m,Z,m-Z-m.Z. 	 d dl/m0Z0m1Z1m2Z2 d dl3m4Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ ed   ZC	 eeDeCf   ZE	  ed       G d de,             ZFe G d de*             ZGddZHddZIy# eA$ rZB eAd      eBdZB[Bww xY w)    )annotations)AsyncIterator)asynccontextmanager)	dataclassfield)AnyLiteralUnioncastoverload)AsyncClient)assert_never   )result)guard_tool_call_id)ArgsDictModelMessageModelRequestModelResponseModelResponsePartRetryPromptPartSystemPromptPartTextPartToolCallPartToolReturnPartUserPromptPart)ModelSettings)ToolDefinition   )
AgentModelEitherStreamedResponseModelcached_async_http_clientcheck_allow_model_requests)	NOT_GIVENAsyncAnthropicAsyncStream)MessageMessageParamRawMessageDeltaEventRawMessageStartEventRawMessageStreamEvent	TextBlockTextBlockParamToolChoiceParam	ToolParamToolResultBlockParamToolUseBlockToolUseBlockParamu   Please install `anthropic` to use the Anthropic model, you can use the `anthropic` optional group — `pip install 'pydantic-ai-slim[anthropic]'`N)zclaude-3-5-haiku-latestzclaude-3-5-sonnet-latestzclaude-3-opus-latestF)initc                      e Zd ZU dZded<    ed      Zded<   dddd		 	 	 	 	 	 	 dd
Z	 	 	 	 	 	 	 	 ddZddZ	e
dd       Zy)AnthropicModela  A model that uses the Anthropic API.

    Internally, this uses the [Anthropic Python client](https://github.com/anthropics/anthropic-sdk-python) to interact with the API.

    Apart from `__init__`, all methods are private or match those of the base class.

    !!! note
        The `AnthropicModel` class does not yet support streaming responses.
        We anticipate adding support for streaming responses in a near-term future release.
    AnthropicModelName
model_nameF)reprr&   clientN)api_keyanthropic_clienthttp_clientc                   || _         ||J d       |J d       || _        y|t        ||      | _        yt        |t                     | _        y)a  Initialize an Anthropic model.

        Args:
            model_name: The name of the Anthropic model to use. List of model names available
                [here](https://docs.anthropic.com/en/docs/about-claude/models).
            api_key: The API key to use for authentication, if not provided, the `ANTHROPIC_API_KEY` environment variable
                will be used if available.
            anthropic_client: An existing
                [`AsyncAnthropic`](https://github.com/anthropics/anthropic-sdk-python?tab=readme-ov-file#async-usage)
                client to use, if provided, `api_key` and `http_client` must be `None`.
            http_client: An existing `httpx.AsyncClient` to use for making HTTP requests.
        Nz8Cannot provide both `anthropic_client` and `http_client`z4Cannot provide both `anthropic_client` and `api_key`)r;   r=   )r8   r:   r&   r#   )selfr8   r;   r<   r=   s        Q/var/www/openai/venv/lib/python3.12/site-packages/pydantic_ai/models/anthropic.py__init__zAnthropicModel.__init__Z   s`    ( %'&b(bb&?Z$ZZ?*DK$(kRDK(F^F`aDK    c                  K   t                |D cg c]  }| j                  |       }}|r"||D cg c]  }| j                  |       c}z  }t        | j                  | j                  ||      S c c}w c c}w wN)r$   _map_tool_definitionAnthropicAgentModelr:   r8   )r?   function_toolsallow_text_resultresult_toolsrtoolss         r@   agent_modelzAnthropicModel.agent_modelx   s~      	#$7EF~!**1-~FLILqd//2LIIE"KKOO	
 	
 GIs   A;A1	A;A6
1A;c                     d| j                    S )Nz
anthropic:)r8   )r?   s    r@   namezAnthropicModel.name   s    DOO,--rB   c                J    | j                   | j                  | j                  dS )N)rN   descriptioninput_schema)rN   rP   parameters_json_schema)fs    r@   rE   z#AnthropicModel._map_tool_definition   s%     FF==44
 	
rB   )r8   r7   r;   z
str | Noner<   zAsyncAnthropic | Noner=   zAsyncHTTPClient | None)rG   list[ToolDefinition]rH   boolrI   rT   returnr    )rV   str)rS   r   rV   r0   )__name__
__module____qualname____doc____annotations__r   r:   rA   rL   rN   staticmethodrE    rB   r@   r6   r6   J   s    	 #"".FN. #26.2b&b 	b
 0b ,b<
 -
  	

 +
 

$. 
 
rB   r6   c                      e Zd ZU dZded<   ded<   ded<   ded	<   	 	 	 	 	 	 dd
Ze	 	 	 	 	 	 dd       Ze	 	 	 	 	 	 	 	 dd       Z	e	 	 	 	 	 	 	 	 dd       Z		 	 	 	 	 	 	 	 ddZ	e
dd       Ze
dd       Ze
dd       Zy)rF   z4Implementation of `AgentModel` for Anthropic models.r&   r:   rW   r8   rU   rH   zlist[ToolParam]rK   c                |   K   | j                  |d|       d {   }| j                  |      t        |      fS 7  w)NF)_messages_create_process_response
_map_usager?   messagesmodel_settingsresponses       r@   requestzAnthropicAgentModel.request   s@      ..xOO%%h/H1EEE Ps   <:!<c                  K   | j                  |d|       d {   }|4 d {    | j                  |       d {    d d d       d {    y 7 <7 37 7 # 1 d {  7  sw Y   y xY ww)NT)ra   _process_streamed_responserd   s       r@   request_streamz"AnthropicAgentModel.request_stream   s\      ..x~NN877AAA 88 OA 888sd   A3A
A3AA3AAAA3AA3A3AA3A0$A'%A0,A3c                   K   y wrD   r^   r?   re   streamrf   s       r@   ra   z$AnthropicAgentModel._messages_create         	   c                   K   y wrD   r^   rm   s       r@   ra   z$AnthropicAgentModel._messages_create   ro   rp   c                  K   | j                   sd }n| j                  sddi}nddi}| j                  |      \  }}|xs i }| j                  j                  j                  |j                  dd      |xs t        || j                  | j                   xs t        |xs t        ||j                  dt              |j                  dt              |j                  dt              	
       d {   S 7 w)
Ntypeanyauto
max_tokensi   temperaturetop_ptimeout)
rv   systemre   modelrK   tool_choicern   rw   rx   ry   )	rK   rH   _map_messager:   re   creategetr%   r8   )r?   re   rn   rf   r|   system_promptanthropic_messagess          r@   ra   z$AnthropicAgentModel._messages_create   s      zz26K''!5/K!6*K,0,=,=h,G))'-2[[))00%)),= -I'//**)	#0y&**=)D $$Wi8"&&y)< 1 
 
 	
 
s   C)C2+C0,C2c                   g }| j                   D ]  }t        |t              r%|j                  t	        |j
                               8t        |t              sJ d       |j                  t        j                  |j                  t        t        t        t        f   |j                        |j                                t!        |      S )zAProcess a non-streamed response, and prepare a message to return.zunexpected item type)content
isinstancer-   appendr   textr2   r   from_raw_argsrN   r   dictrW   r   inputidr   )rg   itemsitems      r@   rb   z%AnthropicAgentModel._process_response   s     *,$$D$	*Xdii01!$5M7MM5 ..		T#s(^TZZ8 % U##rB   c                    K   t        d      w)zNTODO: Process a streamed response, and prepare a streaming response to return.z>Streamed responses are not yet supported for Anthropic models.)RuntimeError)rg   s    r@   rj   z.AnthropicAgentModel._process_streamed_response   s      [\\s   c                :   d}g }| D ]  }t        |t              rK|j                  D ]9  }t        |t              r||j                  z  }$t        |t
              r'|j                  t        d|j                               [t        |t              rD|j                  t        dt        t        |d      d|j                         d      g             t        |t              s|j                  +|j                  t        d|j                                      |j                  t        dt        t        |d      d|j                         d	      g             < `t        |t              rg }|j                  D ]e  }t        |t               r'|j                  t#        |j                  d
             :t        |t$              sJ |j                  t'        |             g |j                  t        d|             t)        |        ||fS )zFJust maps a `pydantic_ai.Message` to a `anthropic.types.MessageParam`. user)roler   	Anthropictmodel_sourcetool_resultF)tool_use_idrs   r   is_errorTr   )r   rs   	assistant)r   r   partsr   r   r   r   r)   r   r1   _guard_tool_call_idmodel_response_strr   	tool_namemodel_responser   r   r.   r   _map_tool_callr   )re   r   r   mpartr   r   s          r@   r}   z AnthropicAgentModel._map_message   s     13A!\*GGD!$(89%5#D.9*11,FTXT`T`2ab#D.9*11(%+$84G$]h4i-:040G0G0I16	%&)"
 $D/:>>1.55lX\XkXkXm6no.55 ,)/(<8Kdal8m1>484G4G4I59	)*-&
!"/ $H A}-DFGGD!$1~4<<f'UV)$===~d';< $ #)),KQX*YZQa b 000rB   N)re   list[ModelMessage]rf   ModelSettings | NonerV   z"tuple[ModelResponse, result.Usage])re   r   rf   r   rV   z%AsyncIterator[EitherStreamedResponse])re   r   rn   zLiteral[True]rf   r   rV   "AsyncStream[RawMessageStreamEvent])re   r   rn   zLiteral[False]rf   r   rV   AnthropicMessage)re   r   rn   rU   rf   r   rV   z5AnthropicMessage | AsyncStream[RawMessageStreamEvent])rg   r   rV   r   )rg   r   rV   r!   )re   r   rV   ztuple[str, list[MessageParam]])rX   rY   rZ   r[   r\   rh   r   rk   r   ra   r]   rb   rj   r}   r^   rB   r@   rF   rF      s9   >OF*F<PF	+F B*B<PB	.B B *4ASg	+ 
 *4BTh	 

*
48
J^
	>
8 $ $$ ] ]$ 51 51rB   rF   c                    t        | j                  t              sJ d| j                          t        t	        | d      d| j
                  | j                               S )NzExpected ArgsDict, got r   r   tool_use)r   rs   rN   r   )r   argsr   r3   r   r   args_as_dict)r   s    r@   r   r   4  sR    affh'K+B166()KK'=[[nn	 rB   c                t   t        | t              r| j                  }nFt        | t              r| j                  j                  }nt        | t
              r| j                  }nd }|t        j                         S t        |dd       }t        j                  ||j                  |xs d|j                  z         S )Ninput_tokensr   )request_tokensresponse_tokenstotal_tokens)
r   r   usager+   messager*   r   Usagegetattroutput_tokens)r   r   r   s      r@   rc   rc   >  s    '+,g34OO))E!56MME E}||~UND9N<<%++$)U-@-@@	 rB   )r   r   rV   r3   )r   z(AnthropicMessage | RawMessageStreamEventrV   zresult.Usage)J
__future__r   _annotationscollections.abcr   
contextlibr   dataclassesr   r   typingr   r	   r
   r   r   httpxr   AsyncHTTPClienttyping_extensionsr   r   r   _utilsr   r   re   r   r   r   r   r   r   r   r   r   r   r   settingsr   rK   r   r    r!   r"   r#   r$   	anthropicr%   r&   r'   anthropic.typesr(   r   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   ImportError_import_errorLatestAnthropicModelNamesrW   r7   r6   rF   r   rc   r^   rB   r@   <module>r      s   2 ) * ( 6 6 0 *  >    % " @@   ( $ 
 %3 99:  H
U H
 H
V Z1* Z1 Z1zU  
	e s   6&C C-	C((C-