
    +j-                        U d Z ddlmZ ddlmZmZ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 ddlmZmZmZmZmZ dZdZdZd	d
ddddZeeef         ed<   dhZh dZ ddddZ!eee"f         ed<   g dZ#defdZ$dede%e&e&f         dz  fdZ'dede&dz  fdZ(dedefd Z)d!e*ej+                 d"e,ej-                 de,e         fd#Z. G d$ d%ej+                  Z/ G d& d'e          Z0de0fd(Z1dS ))z^API Nodes for Anthropic Claude (Messages API). See: https://docs.anthropic.com/en/api/messages    )override)IOComfyExtensionInput)
AnthropicImageContentAnthropicImageSourceUrlAnthropicMessageAnthropicMessagesRequestAnthropicMessagesResponseAnthropicOutputConfigAnthropicResponseTextBlockAnthropicRoleAnthropicTextContentAnthropicThinkingConfig)ApiEndpointget_number_of_imagessync_opupload_images_to_comfyapivalidate_stringz/proxy/anthropic/v1/messagesi %    zclaude-opus-4-7zclaude-opus-4-6zclaude-sonnet-4-6zclaude-sonnet-4-5-20250929zclaude-haiku-4-5-20251001)Opus 4.7Opus 4.6
Sonnet 4.6z
Sonnet 4.5	Haiku 4.5CLAUDE_MODELSr   >   r   r   r   i   i    i @  )lowmediumhigh_REASONING_BUDGET)offr   r   r   model_labelc           
      &   t           j                            dddddd          t           j                            dd	d
d	ddd          g}| t          vr<|                    t           j                            dt          ddd                     |S )N
max_tokens   i   i   zNMaximum number of tokens to generate (includes reasoning tokens when enabled).T)defaultminmaxtooltipadvancedtemperature      ?g        g{Gz?zControls randomness. 0.0 is deterministic, 1.0 is most random. Ignored for Opus 4.7 and any model when reasoning_effort is set.)r%   r&   r'   stepr(   r)   reasoning_effortr    z3Extended thinking effort. 'off' disables reasoning.)optionsr%   r(   r)   )r   Intr   Float_THINKING_UNSUPPORTEDappendCombo_REASONING_EFFORTS)r!   inputss     ?/home/wildlama/comfy/ComfyUI/comfy_api_nodes/nodes_anthropic.py_claude_model_inputsr7   5   s    
d 	 	
 	
 	S  	 	
 	
F, ///HNN"*M   	
 	
 	
 M    modelreturnNc                 :    d| v sd| v sd| v rdS d| v rdS d| v rdS d	S )
zPReturn (input_per_1M, output_per_1M) USD for a Claude model, or None if unknown.zopus-4-7zopus-4-6zopus-4-5)      @g      9@zsonnet-4)g      @g      .@z	haiku-4-5)r+   r<   N )r9   s    r6   _model_price_per_millionr>   Y   sK    UjE11Z55H5HyUyex4r8   responsec                 r   | j         r| j        sdS t          | j                  }|dS |\  }}| j         j        pd}| j         j        pd}| j         j        pd}d}d}| j         j        r&| j         j        j        pd}| j         j        j        pd}||z  ||z  z   ||z  dz  z   ||z  dz  z   ||z  dz  z   }	|	dz  S )zXCompute approximate USD price from response usage. Server-side billing is authoritative.Nr   g?g      ?g       @g    .A)	usager9   r>   input_tokensoutput_tokenscache_read_input_tokenscache_creationephemeral_5m_input_tokensephemeral_1h_input_tokens)
r?   rates
input_rateoutput_raterB   rC   
cache_readcache_5mcache_1htotals
             r6   calculate_tokens_pricerO   d   s   >  t$X^44E}t#J>.3!LN05AM7<1JHH~$ P>0JOa>0JOaz!
+
%	&
z
!C
'	( Z
$
&	' Z
#
%		& 
 ;r8   c                 \    | j         sdS d                    d | j         D                       S )N 
c              3   \   K   | ]'}t          |t                    |j        |j        V  (d S N)
isinstancer   text).0blocks     r6   	<genexpr>z*_get_text_from_response.<locals>.<genexpr>   sS        e788=BZ
     r8   )contentjoin)r?   s    r6   _get_text_from_responser\   ~   sG     r99   ( 0     r8   clsimage_tensorsc                 f   K   t          | |t          t          d           d {V }d |D             S )NzUploading reference images)
max_imagestotal_pixels
wait_labelc                 J    g | ] }t          t          |                     !S ))url)source)r   r   )rW   rd   s     r6   
<listcomp>z/_build_image_content_blocks.<locals>.<listcomp>   s0    [[[s!)@S)I)I)IJJJ[[[r8   )r   CLAUDE_MAX_IMAGESANTHROPIC_IMAGE_MAX_PIXELS)r]   r^   urlss      r6   _build_image_content_blocksrj      sa       +$//        D \[VZ[[[[r8   c                   n    e Zd ZdZed             Ze	 	 ddededededz  d	ed
e	j
        fd            ZdS )
ClaudeNodez7Generate text responses from an Anthropic Claude model.c                 j   t          j        dddddt           j                            dddd	
          t           j                            dd t
          D             d          t           j                            dddddd          t           j                            dt           j                            t           j	                            d          d t          dt          dz             D             d          dt           d          t           j                            dddddd          gt           j                                        gt           j        j        t           j        j        t           j        j        gdt          j        t          j        dg          d !          "
  
        S )#Nrl   zAnthropic Claudezpartner/text/AnthropiczText GenerationzGenerate text responses with Anthropic's Claude models. Provide a text prompt and optionally one or more images for multimodal context.promptTrQ   zText input to the model.)	multiliner%   r(   r9   c                 h    g | ]/}t           j                            |t          |                    0S r=   )r   DynamicComboOptionr7   )rW   labels     r6   rf   z,ClaudeNode.define_schema.<locals>.<listcomp>   sC       ! ..u6J56Q6QRR  r8   z/The Claude model used to generate the response.)r.   r(   seedr   iz_Seed controls whether the node should re-run; results are non-deterministic regardless of seed.)r%   r&   r'   control_after_generater(   imagesimagec                     g | ]}d | S )image_r=   )rW   is     r6   rf   z,ClaudeNode.define_schema.<locals>.<listcomp>   s    UUU|||UUUr8      )namesr&   z9Optional image(s) to use as context for the model. Up to z images.)templater(   system_promptz<Foundational instructions that dictate the model's behavior.)ro   r%   optionalr)   r(   )widgetsa  
                (
                  $m := widgets.model;
                  $contains($m, "opus") ? {
                    "type": "list_usd",
                    "usd": [0.005, 0.025],
                    "format": { "approximate": true, "separator": "-", "suffix": " per 1K tokens" }
                  }
                  : $contains($m, "sonnet") ? {
                    "type": "list_usd",
                    "usd": [0.003, 0.015],
                    "format": { "approximate": true, "separator": "-", "suffix": " per 1K tokens" }
                  }
                  : $contains($m, "haiku") ? {
                    "type": "list_usd",
                    "usd": [0.001, 0.005],
                    "format": { "approximate": true, "separator": "-", "suffix": " per 1K tokens" }
                  }
                  : {"type":"text", "text":"Token-based"}
                )
                )
depends_onexpr)
node_iddisplay_namecategoryessentials_categorydescriptionr5   outputshiddenis_api_nodeprice_badge)r   SchemaStringr   rq   r   r/   AutogrowTemplateNamesImagerangerg   OutputHiddenauth_token_comfy_orgapi_key_comfy_org	unique_id
PriceBadgePriceBadgeDepends)r]   s    r6   define_schemazClaudeNode.define_schema   s   y +- 1^ 	"6	     %% %2   N &   "+/H    !![66w//UUU1>ORS>S5T5TUUU 7  
 tXisss "   	#"!!Z    C)T Y%%''(	.	+	#
 /	BBB  qP
 P
 P
 P	
r8   NrQ   rn   r9   rt   rv   r~   r:   c                 L  K   t          |dd           |d         }|                    dd          }|                    dd          }|d	vo|t          v}	|	s|d
k    rd }
n|                    dd          }
d }d }|	ri|t          v r!t	          d          }t          |          }n?t          |         }t          |t          d|dz
                      }t	          d|          }d |pi 	                                D             }t          d |D                       t          k    rt          dt           d          g }|r)|                    t          | |           d {V            |                    t!          |                     t#          | t%          t&          d          t(          t+          t,          |         |t/          t0          j        |          g|pd |
||          t4                     d {V }t7          j        t;          |          pd          S )NTr{   )strip_whitespace
min_lengthr9   r#   r$   r-   r    )r    Nr   r*   r+   adaptive)type)efforti   enabled)r   budget_tokensc                     g | ]}||S rT   r=   rW   ts     r6   rf   z&ClaudeNode.execute.<locals>.<listcomp>  s    +`+`+`!RSR_AR_R_R_r8   c              3   4   K   | ]}t          |          V  d S rT   )r   r   s     r6   rY   z%ClaudeNode.execute.<locals>.<genexpr>  s+      >>1#A&&>>>>>>r8   zUp to z" images are supported per request.)rV   POST)pathmethod)rolerZ   )r9   r#   messagessystemr*   thinkingoutput_config)response_modeldataprice_extractorz!Empty response from Claude model.)r   getr1   _ADAPTIVE_THINKING_MODELSr   r   r   r&   r'   valuessumrg   
ValueErrorextendrj   r2   r   r   r   ANTHROPIC_MESSAGES_ENDPOINTr   r
   r   r	   r   userrO   r   
NodeOutputr\   )r]   rn   r9   rt   rv   r~   r!   r#   r-   thinking_enabledr*   thinking_cfg
output_cfgbudgetr^   rZ   r?   s                    r6   executezClaudeNode.execute   s      	!DDDDGnYY|U33
 99%7??+=@m[XmEm  	8{j88KK))M377K7;37
 		]7776JGGG2:JKKK

 ++;<VSzD/@%A%ABB6IU[\\\+`+`"7L7L7N7N+`+`+`>>>>>>>ARRR[&7[[[\\\FH 	RNN!<S-!P!PPPPPPPQQQ+888999 8HHH4)#K0%*0BGTTTU$,'%(   3
 
 
 
 
 
 
 
 
 }4X>>eBefffr8   )NrQ   )__name__
__module____qualname____doc__classmethodr   strdictintr   r   r   r=   r8   r6   rl   rl      s        AAQ
 Q
 [Q
f  #:g :g:g :g 	:g
 t:g :g 
:g :g :g [:g :g :gr8   rl   c                   L    e Zd Zedeeej                          fd            ZdS )AnthropicExtensionr:   c                    K   t           gS rT   )rl   )selfs    r6   get_node_listz AnthropicExtension.get_node_list,  s      |r8   N)	r   r   r   r   listr   r   	ComfyNoder   r=   r8   r6   r   r   +  sE        T$r|*<%=    X  r8   r   c                  "   K   t                      S rT   )r   r=   r8   r6   comfy_entrypointr   1  s      r8   )2r   typing_extensionsr   comfy_api.latestr   r   r   comfy_api_nodes.apis.anthropicr   r   r	   r
   r   r   r   r   r   r   comfy_api_nodes.utilr   r   r   r   r   r   rh   rg   r   r   r   __annotations__r1   r   r   r   r4   r7   tuplefloatr>   rO   r\   r   r   r   r   rj   rl   r   r   r=   r8   r6   <module>r      s
   d d d & & & & & & 6 6 6 6 6 6 6 6 6 6                                     = (   "!%.,! !tCH~    %  CBB 
 % % 4S>   
 655 !c ! ! ! !HC E%,,?$,F    %> 54<    4&? C    \	bl	\$\ 

 \ \ \ \Rg Rg Rg Rg Rg Rg Rg Rgj         2            r8   