o
    ưi#                     @   s  d 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T ddlmZ ddlmZmZ dd	lmZ dd
lmZ e ZejddgeegdeefdededefddZejddgeegdeefdedefddZejddgddefddZdS )z2
Unified /v1/messages endpoint - (Anthropic Spec)
    )	APIRouterDependsHTTPExceptionRequestResponse)verbose_proxy_logger)AnthropicExceptionMapping)ModifyResponseException)*)user_api_key_auth)ProxyBaseLLMRequestProcessingcreate_response)_read_request_body)TokenCountResponsez/v1/messagesz[beta] Anthropic `/v1/messages`)tagsdependenciesfastapi_responserequestuser_api_key_dictc                    s  ddl m}m}m}m}m}m}m}	m}
m	}m
} t|dI dH }t|d}z<|jd7i d|d| d|d	d
d|d|d|d|ddddd|	d|d|
d|d|d|I dH }|W S  ty } zi|j}|j|||dI dH  ddl}ddlm} |dt|  ddd|jdg|jddddd  |d!ddur|d! d"u rˇ fd#d$}tj| |||d%}t|d&i d'I dH W  Y d}~S  W  Y d}~S d}~w tyJ } zg|j|||dI dH  td(t| |d)i pi }|d*i pi }|d+d,pd,}tj||d-d,||dt |d.d,|t |d/ddd0	}t| }t!t |d|t |d1d2t |d3d2t |d4d5|d6d}~ww )8z
    Use `{PROXY_BASE_URL}/anthropic/v1/messages` instead - [Docs](https://docs.litellm.ai/docs/anthropic_completion).

    This was a BETA endpoint that calls 100+ LLMs in the anthropic format.
    r   )
general_settings
llm_routerproxy_configproxy_logging_objuser_api_baseuser_max_tokens
user_modeluser_request_timeoutuser_temperatureversionr   N)datar   r   r   Z
route_typeZanthropic_messagesr   r   r   r   Zselect_data_generatormodelr   r   r   r   r   r   )r   Zoriginal_exceptionrequest_data)AnthropicMessagesResponseZmsg_messageZ	assistanttext)typer%   Zend_turn)input_tokensZoutput_tokens)idr&   Zrolecontentr!   Zstop_reasonusagestreamTc                     s    V  d S )N r,   Z_anthropic_responser,   b/home/app/Keep/.python/lib/python3.10/site-packages/litellm/proxy/anthropic_endpoints/endpoints.py_passthrough_stream_generatorb   s   
z9anthropic_response.<locals>._passthrough_stream_generator)responser   r"   r   ztext/event-stream)	generator
media_typeheaderszGlitellm.proxy.proxy_server.anthropic_response(): Exception occured - {}litellm_metadata
model_infor(    Zlitellm_call_idZallowed_model_regiontimeout)	r   Zcall_idmodel_idr   Zresponse_costZmodel_regionr"   r7   Zlitellm_logging_objr&   Noneparamstatus_code  )r$   r&   r:   coder3   r,   )"litellm.proxy.proxy_serverr   r   r   r   r   r   r   r   r   r   r   r   Zbase_process_llm_requestr	   r"   Zpost_call_failure_hookuuidlitellm.types.utilsr#   struuid4r$   r!   getZasync_sse_data_generatorr   	Exceptionr   	exceptionformatZget_custom_headersgetattrProxyException)r   r   r   r   r   r   r   r   r   r   r   r   r   r    Zbase_llm_response_processorresulte_datar?   r#   r/   Zselected_data_generatorr4   r5   r8   r3   	error_msgr,   r-   r.   anthropic_response   s   0

	


	







rM   z/v1/messages/count_tokensz([beta] Anthropic Messages Token Countingc              
      s|  ddl m} zdt| dI dH }i |}|d}|dg }|s)tddd	id
|s3tdddid
ddlm} ||||d|dd}||ddI dH }	i }
t|	tr\|		 }
nt|	t
rc|	}
d|
ddiW S  tys     ty } z|jr|j rt|jnd}tj||jd}t||d
d}~w ty } ztdt| tdddt| id
d}~ww )a  
    Count tokens for Anthropic Messages API format.
    
    This endpoint follows the Anthropic Messages API token counting specification.
    It accepts the same parameters as the /v1/messages endpoint but returns
    token counts instead of generating a response.
    
    Example usage:
    ```
    curl -X POST "http://localhost:4000/v1/messages/count_tokens?beta=true"       -H "Content-Type: application/json"       -H "Authorization: Bearer your-key"       -d '{
        "model": "claude-3-sonnet-20240229",
        "messages": [{"role": "user", "content": "Hello Claude!"}]
      }'
    ```
    
    Returns: {"input_tokens": <number>}
    r   )token_counterr   Nr!   messagesi  errorzmodel parameter is required)r;   detailzmessages parameter is required)TokenCountRequesttoolssystem)r!   rO   rS   rT   T)r   Zcall_endpointr'   Ztotal_tokensr<   )r;   Zraw_messagezIlitellm.proxy.anthropic_endpoints.count_tokens(): Exception occurred - {}zInternal server error: )r>   rN   r   rC   r   litellm.proxy._typesrR   
isinstancer   Z
model_dumpdictrH   r=   isdigitintr   Ztransform_to_anthropic_errorr$   rD   r   rE   rF   rA   )r   r   Zinternal_token_counterr"   r    Z
model_namerO   rR   Ztoken_requestZtoken_responseZ_token_response_dictrJ   r;   rQ   r,   r,   r.   count_tokens   sp   



rZ   z/api/event_logging/batchz[beta] Anthropic Event Logging)r   c                    s
   ddiS )z
    Stubbed endpoint for Anthropic event logging batch requests.
    
    This endpoint accepts event logging requests but does nothing with them.
    It exists to prevent 404 errors from Claude Code clients that send telemetry.
    statusokr,   r   r,   r,   r.   event_logging_batch   s   r]   N)__doc__Zfastapir   r   r   r   r   Zlitellm._loggingr   Z&litellm.anthropic_interface.exceptionsr   Z%litellm.integrations.custom_guardrailr	   rU   Z$litellm.proxy.auth.user_api_key_authr   Z'litellm.proxy.common_request_processingr   r   Z-litellm.proxy.common_utils.http_parsing_utilsr   r@   r   ZrouterpostZUserAPIKeyAuthrM   rZ   r]   r,   r,   r,   r.   <module>   sV     [