
    AHjg                        U d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZ ddlZddl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 dd
lmZ ddlmZ erddlm Z! ddl"m#Z#m$Z$m%Z% dZ&dZ'ee(d<   dZ)ee(d<   	 ddlm Z) dZ&ddl+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 e,Z'de	e2ef   de3de3ddfdZ4de	e2ef   de
e2   ddfdZ5dede	e2ef   de2fdZ6ddd e2d!e
e2   d"e	e2ef   def
d#Z7deded$ed%e
e2   d!e
e2   d&e
e2   defd'Z8e	 	 	 	 	 	 d7de
d(   de
d   d!e
e2   d"e
e	e2ef      de
e2   d)e
e	e2e2f      dedefd*       Z9edd(dddedeeeeeef   f   fd+       Z:dd,d&e2de
e2   d"e
e	e2ef      d-e
e	e2ef      d.e
e	e2ef      defd/Z;	 	 	 	 	 	 	 	 d8de
d(   de
d,   d!e
e2   d"e
e	e2ef      de
e2   d-e
e	e2ef      d.e
e	e2ef      d)e
e	e2e2f      dee   fd0Z<	 	 d9d1e2d2e=d3e
e	e2e2f      dd(fd4Z>edfd1e2d2e=d3e
e	e2e2f      dd5fd6Z?y# e*$ r Y w xY w):zs
LiteLLM A2A SDK functions.

Provides standalone functions with @client decorator for LiteLLM logging integration.
    N)TYPE_CHECKINGAnyAsyncIterator	CoroutineDictOptionalUnion)verbose_loggerverbose_proxy_logger)A2AStreamingIterator)A2ARequestUtils)DEFAULT_A2A_AGENT_TIMEOUT)Logging)get_async_httpx_clienthttpxSpecialProvider)LiteLLMSendMessageResponse)client)	A2AClient)	AgentCardSendMessageRequestSendStreamingMessageRequestFA2ACardResolver
_A2AClientT)LiteLLMA2ACardResolver)handle_a2a_localhost_retrymap_a2a_exception)A2ALocalhostURLErrorkwargsprompt_tokenscompletion_tokensreturnc                     | j                  d      }|+t        j                  ||||z         }||j                  d<   yy)z
    Set usage on litellm_logging_obj for standard logging payload.

    Args:
        kwargs: The kwargs dict containing litellm_logging_obj
        prompt_tokens: Number of input tokens
        completion_tokens: Number of output tokens
    litellm_logging_objN)r   r    total_tokensusage)getlitellmUsagemodel_call_details)r   r   r    r#   r%   s        Q/root/tools/cai/cai_env/lib/python3.12/site-packages/litellm/a2a_protocol/main.py_set_usage_on_logging_objr+   5   sP     !**%:;&'/&)::

 ;@..w7 '    agent_idc                 P    |y| j                  d      }|||j                  d<   yy)z
    Set agent_id on litellm_logging_obj for SpendLogs tracking.

    Args:
        kwargs: The kwargs dict containing litellm_logging_obj
        agent_id: The A2A agent ID
    Nr#   r-   )r&   r)   )r   r-   r#   s      r*   _set_agent_id_on_logging_objr/   L   s9      **%:;&=E..z: 'r,   
a2a_clientc                     d}t        | dd      }|t        | dd      }|t        |dd      xs d}d| }d}|j                  d      }|,||_        ||_        ||j                  d	<   ||j                  d
<   |S )z
    Extract agent info and set model/custom_llm_provider for cost tracking.

    Sets model info on the litellm_logging_obj if available.
    Returns the agent name for logging.
    unknown_litellm_agent_cardN
agent_cardname
a2a_agent/	a2a_agentr#   modelcustom_llm_provider)getattrr&   r8   r9   r)   )r0   r   
agent_namer4   r8   r9   r#   s          r*   _get_a2a_model_infor<   `   s     J %:DAJZt<
Z;Hy
 %E% !**%:;&$)!2E/:?..w7   	..!	
 r,   requestr   r9   api_baselitellm_paramsc                 h  K   t        j                  d| d|        ddlm} t	        | j
                  d      r| j
                  j                  d      nt        | j
                        }|j                  t        | j                        |||       d	{   }t        j                  |      S 7 w)
z
    Route a send_message through the LiteLLM completion bridge (e.g. LangGraph, Bedrock AgentCore).

    Requires request; api_base is optional for providers that derive endpoint from model.
    z&A2A using completion bridge: provider=z, api_base=r   A2ACompletionBridgeHandler
model_dumpjsonmode
request_idparamsr?   r>   N)r
   info6litellm.a2a_protocol.litellm_completion_bridge.handlerrB   hasattrrI   rC   dicthandle_non_streamingstridr   	from_dict)r=   r9   r>   r?   rB   rI   response_dicts          r*   #_send_message_via_completion_bridgerS      s      
01D0E[QYPZ[ 7>><0 	!!v!.'..!  5IIwzz?%	 J  M &//>>s   BB2B0B2r4   card_urlr;   c           	        K   d}t        d      D ]  }	 | j                  |       d{   } n |t        d      |S 7 # t        $ r)}t        ||| d      } |r|j                  nd}Y d}~^d}~wt
        $ r]}	 t        ||||       nB# t        $ r-}	t        |	|| d      } |r|j                  nd}Y d}	~	Y d}~d}	~	wt
        $ r  w xY wY d}~d}~ww xY ww)z>Send an A2A message with retry logic for localhost URL errors.N   Ferrorr4   r0   is_streamingr8   zCA2A send_message failed: no response received after retry attempts.)rangesend_messager   r   url	Exceptionr   RuntimeError)
r0   r=   r4   rT   r>   r;   a2a_response_elocalhost_errs
             r*   _execute_a2a_send_with_retryrd      s      L1X 	!+!8!8!AAL4 Q
 	
 9 B# 	>3%%"	J *4z~~H 	!!XxzJ' 7'))!&	
 .8:>>T  K	sw   CA?ACA	C
A.)C.C;B
C	C
B<3C7C<C

CCCCA2AClientTypeagent_extra_headersc                   K   |xs i }|j                  d      }|rt        |dd      nd}|j                  d      }	|	r$|t        d      t        ||	||       d{   S |t        d      | a|t        d      |xs t	        t        j                               }d	|i}
|r||
d
<   |r|
j                  |       t        ||
       d{   } | J t        | |      }t        j                  d|j                   d|        t        | dd      xs t        | dd      }|rt        |dd      nd}|xs t	        t        j                               }|j                  j                  }t        |t               r|j                  d      ||d<   nt        |dd      ||_        t%        | |||||       d{   }t        j                  d|j                          t'        j(                  |      }|j+                  dd      }t-        j.                  ||      \  }}}t1        |||       t3        ||       |S 7 7 w7 w)as  
    Async: Send a message to an A2A agent.

    Uses the @client decorator for LiteLLM logging and tracking.
    If litellm_params contains custom_llm_provider, routes through the completion bridge.

    Args:
        a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge)
        request: SendMessageRequest from a2a.types (optional if using completion bridge with api_base)
        api_base: API base URL (required for completion bridge, optional for standard A2A)
        litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge
        agent_id: Optional agent ID for tracking in SpendLogs
        **kwargs: Additional arguments passed to the client decorator

    Returns:
        LiteLLMSendMessageResponse (wraps a2a SendMessageResponse with _hidden_params)

    Example (standard A2A):
        ```python
        from litellm.a2a_protocol import asend_message, create_a2a_client
        from a2a.types import SendMessageRequest, MessageSendParams
        from uuid import uuid4

        a2a_client = await create_a2a_client(base_url="http://localhost:10001")
        request = SendMessageRequest(
            id=str(uuid4()),
            params=MessageSendParams(
                message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
            )
        )
        response = await asend_message(a2a_client=a2a_client, request=request)
        ```

    Example (completion bridge with LangGraph):
        ```python
        from litellm.a2a_protocol import asend_message
        from a2a.types import SendMessageRequest, MessageSendParams
        from uuid import uuid4

        request = SendMessageRequest(
            id=str(uuid4()),
            params=MessageSendParams(
                message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
            )
        )
        response = await asend_message(
            request=request,
            api_base="http://localhost:2024",
            litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
        )
        ```
    r#   litellm_trace_idNr9   )request is required for completion bridge)r=   r9   r>   r?   request is required?Either a2a_client or api_base is required for standard A2A flowX-LiteLLM-Trace-IdX-LiteLLM-Agent-Idbase_urlextra_headerszA2A send_message request_id=z, agent=r3   r4   r]   
context_id)r0   r=   r4   rT   r>   r;   z'A2A send_message completed, request_id=rD   T)rF   exclude_none)r=   rR   )r   r   r    )r   r-   )r&   r:   
ValueErrorrS   rO   uuiduuid4updatecreate_a2a_clientr<   r
   rJ   rP   rI   message
isinstancerM   rq   rd   r   from_a2a_responserC   r   %calculate_usage_from_request_responser+   r/   )r0   r=   r>   r?   r-   rf   r   logging_objtrace_idr9   rp   r;   r4   rT   rq   rx   r`   responserR   r   r    ra   s                         r*   asend_messager      s    | $)rN**23KALw{$6=RVH(,,-BC ?HII8 3)	
 
 	
 .// Q  0s4::<0)=x(H2:M./  !45,]
 


 !!!$Z8J6wzzl(:,WX %:DA WL$FJ 4>wz5$/4H.S.Jnn$$G'4 ;;|$,$.GL!7L$/7!+G5 L A'**NO *;;LIH !++d+KM
 	==#			 #+ !BOk
0
4s9   AI	IA/I	IC,I	:I;BI	I	I	c                     	 t        j                         }|t        d| |d|S t        j                  t        d| |d|      S # t        $ r d}Y >w xY w)a  
    Sync: Send a message to an A2A agent.

    Uses the @client decorator for LiteLLM logging and tracking.

    Args:
        a2a_client: An initialized a2a.client.A2AClient instance
        request: SendMessageRequest from a2a.types
        **kwargs: Additional arguments passed to the client decorator

    Returns:
        LiteLLMSendMessageResponse (wraps a2a SendMessageResponse with _hidden_params)
    N)r0   r=    )asyncioget_running_loopr_   r   run)r0   r=   r   loops       r*   r\   r\   o  sk    &'') N
GNvNN{{KZKFK
 	
  s   A AAr   metadataproxy_server_requestc                    t         j                   j                         }d| }t        |dddgdd|t        | j                        t        | j                              }||_        d|_        ||j                  d	<   d|j                  d
<   |r||j                  d<   |r|j                         ni }	|r||	d<   |r||	d<   |	|_	        |	|_
        |	|j                  d<   |xs i |j                  d<   |S )z0Build logging object for streaming A2A requests.r6   userzstreaming-request)rolecontentFasend_message_streaming)r8   messagesstream	call_type
start_timelitellm_call_idfunction_idr7   r8   r9   r-   r   r   r?   )datetimenowr   rO   rP   r8   r9   r)   copyr?   optional_params)
r=   r;   r-   r?   r   r   r   r8   r|   _litellm_paramss
             r*   _build_streaming_logging_objr     s
    ""&&(J%E!.ABC+GJJ

OK K&1K#.3K""7+<GK""#895=&&z2/=n))+2O&.
#2F./!0K"1K7FK""#3419RK"":.r,   c           	     2  K   |xs i }|j                  d      }|r|t        d      t        j                  d|        ddlm}	 t        |j                  d      r|j                  j                  d	      nt        |j                        }
|	j                  t        |j                        |
||
      2 3 d{   }| |t        d      | S|t        d      dt        |j                        i}|r||d<   |r|j                  |       t        ||       d{   } | J t        j                  d|j                          t        | dd      xs t        | dd      }|rt        |dd      nd}|rt        |dd      nd}t!        ||||||      }d}t#        d      D ]9  }| j%                  |      }t'        ||||      }	 d}|2 3 d{   }|rd}|  y7 ,6 y7 7 6  y# t(        $ r2}|r%|dk(  r t+        ||| d      } |r|j,                  nd}n Y d}~d}~wt.        $ r`}|rX|dk(  rS	 t1        ||||        # t(        $ r-}t+        ||| d      } |r|j,                  nd}Y d}~Y d}~d}~wt.        $ r  w xY w d}~ww xY ww)a  
    Async: Send a streaming message to an A2A agent.

    If litellm_params contains custom_llm_provider, routes through the completion bridge.

    Args:
        a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge)
        request: SendStreamingMessageRequest from a2a.types
        api_base: API base URL (required for completion bridge)
        litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge
        agent_id: Optional agent ID for tracking in SpendLogs
        metadata: Optional metadata dict (contains user_api_key, user_id, team_id, etc.)
        proxy_server_request: Optional proxy server request data

    Yields:
        SendStreamingMessageResponse chunks from the agent

    Example (completion bridge with LangGraph):
        ```python
        from litellm.a2a_protocol import asend_message_streaming
        from a2a.types import SendStreamingMessageRequest, MessageSendParams
        from uuid import uuid4

        request = SendStreamingMessageRequest(
            id=str(uuid4()),
            params=MessageSendParams(
                message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
            )
        )
        async for chunk in asend_message_streaming(
            request=request,
            api_base="http://localhost:2024",
            litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
        ):
            print(chunk)
        ```
    r9   Nri   z0A2A streaming using completion bridge: provider=r   rA   rC   rD   rE   rG   rj   rk   rl   rm   rn   z&A2A send_message_streaming request_id=r3   r4   r]   r5   r2   )r=   r;   r-   r?   r   r   TrV   )r   r=   r|   r;   FrW   rZ   )r&   rs   r
   rJ   rK   rB   rL   rI   rC   rM   handle_streamingrO   rP   rv   rw   r:   r   r[   send_message_streamingr   r   r   r]   r^   r   )r0   r=   r>   r?   r-   r   r   rf   r9   rB   rI   chunkstreaming_extra_headersr4   rT   r;   r|   first_chunkattemptr   iteratorrb   rc   s                          r*   r   r     s(    ^ $)rN(,,-BC ?HII 	>?R>ST	
	
 w~~|4 NN%%6%2gnn% 	 6FF7::)	 G 
 	 	% K .// Q 
 !#gjj/3
 <D#$89#**+>?,-D
 


 !!!@MN %:DA WL$FJ 4>wz5$/4H;EVY79J.%1K K8 .227;'#!	
%	K'  e"'K.o	 
 	(
Nx # 	w!|7))!%	
 .8:>>T   	w!|%a8:N  , 	!;+#-#-%)	"J 2<z~~HH   %	s   B4J6G):G&;G)>A$J"G+#B)JG2G/G-G/G2$J&G))J-G//G20J2	J;(H(#J(J4J<IJ	JI=4J8J=JJJJro   timeoutrp   c                   K   t         st        d      t        j                  d|         d|i}|r%t	        t        |j                                     |d<   t        t        j                  |      }|j                  }|rJ|j                  j                  |       t        j                  dt        |j!                                       t#        ||       }|j%                          d{   }t        j                  d	t'        |d
      r|j(                  nd        t+        ||      }||_        t        j                  d|         |S 7 bw)az  
    Create an A2A client for the given agent URL.

    This resolves the agent card and returns a ready-to-use A2A client.
    The client can be reused for multiple requests.

    Args:
        base_url: The base URL of the A2A agent (e.g., "http://localhost:10001")
        timeout: Request timeout in seconds (default: 60.0)
        extra_headers: Optional additional headers to include in requests

    Returns:
        An initialized a2a.client.A2AClient instance

    Example:
        ```python
        from litellm.a2a_protocol import create_a2a_client, asend_message

        # Create client once
        client = await create_a2a_client(base_url="http://localhost:10001")

        # Reuse for multiple requests
        response1 = await asend_message(a2a_client=client, request=request1)
        response2 = await asend_message(a2a_client=client, request=request2)
        ```
    \The 'a2a' package is required for A2A agent invocation. Install it with: pip install a2a-sdkzCreating A2A client for r   disable_aiohttp_transportllm_providerrI   z&A2A client created with extra_headers=httpx_clientro   NzResolved agent card: r5   r2   )r   r4   zA2A client created for )A2A_SDK_AVAILABLEImportErrorr
   rJ   rO   sorteditemsr   r   A2AProviderr   headersrv   r   debuglistkeysr   get_agent_cardrL   r5   r   r3   )	ro   r   rp   _client_params_async_handlerr   resolverr4   r0   s	            r*   rw   rw   h  sP    > 3
 	

 28*=> &w/N 7:&ATATAV:W6X23+)55N "((L##M2""4T-:L:L:N5O4PQ	

 !H  ..00J
7:v3N
T]^_
 !J &0J"1(<=# 1s   C(E*E+A#Er   c                 `  K   t         st        d      t        j                  d|         t	        t
        j                  d|i      }|j                  }t        ||       }|j                          d{   }t        j                  dt        |d      r|j                  nd	        |S 7 6w)
aF  
    Fetch the agent card from an A2A agent.

    Args:
        base_url: The base URL of the A2A agent (e.g., "http://localhost:10001")
        timeout: Request timeout in seconds (default: 60.0)
        extra_headers: Optional additional headers to include in requests

    Returns:
        AgentCard from the A2A agent
    r   zFetching agent card from r   r   r   NzFetched agent card: r5   r2   )r   r   r
   rJ   r   r   A2Ar   r   r   rL   r5   )ro   r   rp   http_handlerr   r   r4   s          r*   aget_agent_cardr     s       3
 	

 3H:>? *)--7#L  &&L!H  ..00J
'*f2MzS\]^  1s   A3B.5B,67B.)NNNNNN)NNNNNNNN)g      N@N)@__doc__r   r   rt   typingr   r   r   r   r   r   r	   r'   litellm._loggingr
   r   'litellm.a2a_protocol.streaming_iteratorr   litellm.a2a_protocol.utilsr   litellm.constantsr   *litellm.litellm_core_utils.litellm_loggingr   &litellm.llms.custom_httpx.http_handlerr   r   litellm.types.agentsr   litellm.utilsr   
a2a.clientr   re   	a2a.typesr   r   r   r   r   __annotations__r   r   "litellm.a2a_protocol.card_resolverr   ,litellm.a2a_protocol.exception_mapping_utilsr   r   litellm.a2a_protocol.exceptionsr   rO   intr+   r/   r<   rS   rd   r   r\   r   r   floatrw   r   r   r,   r*   <module>r      sw      V V V  A H 6 7 > <  5TT   
C 	2
 F A )@cN@@ @ 
	@.FcNFsmF 
F(C c3h C D ?! ? ? sm ? cN	 ?
   ?F((( ( sm	(
 sm( ( 	(V ,0.2"/3"48[)[*+[ sm[ T#s(^,	[
 sm[ "$sCx.1[ [  [ [| 

!
 
 %yc;U1U'VVW	
 
>'*'' sm' T#s(^,	'
 tCH~&' #4S>2' 'V -17;"/3")-5948l)l34l sml T#s(^,	l
 sml tCH~&l #4S>2l "$sCx.1l 3lb .2UUU DcN+U 	Ut /.2((( DcN+( 	(u  		s   =H   H	H	