
    ~hG                        d dl Z d dlZd dlZd dlZd dlZd dlZd dl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lmZ d dlmZmZ erd dlmZ dgZed	ed
efd       Zg dZded
efdZ G d de      Z  G d de       Z! G d de       Z" G d de       Z# G d de"      Z$ G d de"      Z% G d de       Z&ded
efdZ'ded
e(e)eef   ef   fdZ*ded e(eef   d
edz  fd!Z+ded e(eef   d
efd"Z,d#Z-e-fd$ed%e.d
efd&Z/ G d' d(e j`                        Z1d) Z2d* Z3d+ Z4d7d,Z5d
efd-Z6d. Z7d/ Z8d0eez  fd1Z9d2ed
efd3Z:d4jw                         Z< G d5 d6      Z=y)8    N)	lru_cache)BytesIO)Path)dedent)TYPE_CHECKINGAny)AgentLogger
AgentErrorpackage_namereturnc                     	 t         j                  j                  |        y# t         j                  j                  $ r Y yw xY w)NTF)	importlibmetadataversionPackageNotFoundError)r   s    L/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/smolagents/utils.py_is_package_availabler   *   s<    ""<022 s   " AA)collectionsdatetime	itertoolsmathqueuerandomrestat
statisticstimeunicodedatatextc                 6    d }t        j                  d||       S )zLEscapes square brackets in code segments while preserving Rich styling tags.c                     | j                  d      }t        j                  dd|      }|j                         rd| dS d| dS )N   zQbold|red|green|blue|yellow|magenta|cyan|white|black|italic|dim|\s|#[0-9a-fA-F]{6} z\[z\][])groupr   substrip)matchcontentcleaneds      r   replace_bracketed_contentz7escape_code_brackets.<locals>.replace_bracketed_contentE   sL    ++a.&&`bdfm
 &-]]_WIS!HAgYa.H    z\[([^\]]*)\])r   r'   )r   r,   s     r   escape_code_bracketsr.   B   s    I 66/#<dCCr-   c                   :     e Zd ZdZd fdZdeeef   fdZ xZS )r
   z-Base class for other agent-related exceptionsc                 T    t         |   |       || _        |j                  |       y N)super__init__message	log_error)selfr4   logger	__class__s      r   r3   zAgentError.__init__R   s%    !!r-   r   c                 Z    | j                   j                  t        | j                        dS )N)typer4   )r8   __name__strr4   r6   s    r   dictzAgentError.dictW   s     //C<MNNr-   )r7   r	   )r;   
__module____qualname____doc__r3   r>   r<   __classcell__)r8   s   @r   r
   r
   O   s!    7"
Od38n Or-   c                       e Zd ZdZy)AgentParsingErrorz3Exception raised for errors in parsing in the agentNr;   r?   r@   rA    r-   r   rD   rD   [   s    =r-   rD   c                       e Zd ZdZy)AgentExecutionError5Exception raised for errors in execution in the agentNrE   rF   r-   r   rH   rH   a       ?r-   rH   c                       e Zd ZdZy)AgentMaxStepsErrorrI   NrE   rF   r-   r   rL   rL   g   rJ   r-   rL   c                       e Zd ZdZy)AgentToolCallErrorzKException raised for errors when incorrect arguments are passed to the toolNrE   rF   r-   r   rN   rN   m   s    Ur-   rN   c                       e Zd ZdZy)AgentToolExecutionErrorz1Exception raised for errors when executing a toolNrE   rF   r-   r   rP   rP   s   s    ;r-   rP   c                       e Zd ZdZy)AgentGenerationErrorz6Exception raised for errors in generation in the agentNrE   rF   r-   r   rR   rR   y   s    @r-   rR   objc           	      F   | yt        | t        t        t        t        f      ryt        | t              rg	 | j                  d      r| j                  d      s"| j                  d      r1| j                  d      r t        j                  |       }t        |      S | S | S t        | t        t        f      r| D cg c]  }t        |       c}S t        | t              r6| j                         D ci c]  \  }}t        |      t        |       c}}S t        | d      rOd| j                   j"                  i| j$                  j                         D ci c]  \  }}|t        |       c}}S t        |       S # t        j                  $ r Y | S w xY wc c}w c c}}w c c}}w )z4Recursive function to make objects JSON serializableN{}r$   r%   __dict___type)
isinstancer<   intfloatbool
startswithendswithjsonloadsmake_json_serializableJSONDecodeErrorlisttupler>   itemshasattrr8   r;   rW   )rS   parseditemkvs        r   ra   ra      sb   
{	C#sE40	1c3NN3'CLL,=3>>RUCV[^[g[ghk[l!ZZ_F1&99 
s
	C$	'9<=&t,==	C	>AiikJdaA.q11JJ	j	!//s]`]i]i]o]o]q3rUYUVXYA7Ma7P4P3rss 3x '' 
 >J 4ss$   A#E8 7F/FF8FF	json_blobc                    	 | j                  d      }t        t        j                  d|             D cg c]  }|j	                          c}d   }| ||dz    }t        j                  |d      }|| d| fS c c}w # t        $ r t        d      t
        j                  $ rH}|j                  }| |dz
  |d	z    d
k(  rt        d      t        d| d|  d| |dz
  |dz     d      d}~ww xY w)zZExtracts the JSON blob from the input and returns the JSON data and the rest of the input.rU   rV   r"   F)strictNz0The model output does not contain any JSON blob.   z},
zmJSON is invalid: you probably tried to provide multiple tool calls in one action. PROVIDE ONLY ONE TOOL CALL.z>The JSON blob you used is invalid due to the following error: z.
JSON blob was: z6, decoding failed on that specific part of the blob:
'      z'.)findrc   r   finditerstartr_   r`   
IndexError
ValueErrorrb   pos)rk   first_accolade_indexalast_accolade_indexjson_str	json_dataeplaces           r   parse_json_blobr      s   
(~~c226r{{3	7R2STQqwwyTUWX14G!4KLJJx6	)$9%9::: U  MKLL 

UQY+v5  LQC P'[ )%!)eai015
 	


s)   2A< A7+A< 7A< <&C*"AC%%C*code_block_tagsc                     |d    d|d    }t        j                  || t         j                        }|rdj                  d |D              S y)z#Extract code from the LLM's output.r   (.*?)r"   z

c              3   <   K   | ]  }|j                           y wr1   )r(   ).0r)   s     r   	<genexpr>z)extract_code_from_text.<locals>.<genexpr>   s     >U5;;=>s   N)r   findallDOTALLjoin)r   r   patternmatchess       r   extract_code_from_textr      sO    !!$%U?1+=*>?Gjj$		2G{{>g>>>r-   c                    t        | |      }|st        | d      }|r|S 	 t        j                  |        | S # t        $ r Y nw xY wd| v rBd| v r>t	        t        d|d    d|d    d|  d	|d    d
|d    d      j                               t	        t        d|d    d|d    d|  d|d    d|d    d      j                               )a*  Extract code blocs from the LLM's output.

    If a valid code block is passed, it returns it directly.

    Args:
        text (`str`): LLM's output text to parse.

    Returns:
        `str`: Extracted code block.

    Raises:
        ValueError: If no valid code block is found in the text.
    )z```(?:python|py)z
```finalanswerzI
                Your code snippet is invalid, because the regex pattern r   r   r"   zQ was not found in it.
                Here is your code snippet:
                zs
                It seems like you're trying to return the final answer, you can do it as follows:
                zH
                final_answer("YOUR FINAL ANSWER HERE")
                z
                zE
            Your code snippet is invalid, because the regex pattern zI was not found in it.
            Here is your code snippet:
            z
            Make sure to include code with the correct pattern, for instance:
            Thoughts: Your thoughts
            z1
            # Your python code here
            z
            )r   astparseSyntaxErrorrv   r   r(   )r   r   r   s      r   parse_code_blobsr      sK    %T?;G(/LM		$  $8t+IIXYZI[H\\abqrsbtau v  #$ % #$ %
 eg
 	
 EETUVEWDXX]^mno^p]q rF  Q  !Q  !		
 %' s   7 	AAi N  r*   
max_lengthc                 T    t        |       |k  r| S | d |dz   d| dz   | | dz  d  z   S )Nro   z3
..._This content has been truncated to stay below z characters_...
)len)r*   r   s     r   truncate_contentr      sS    
7|z! %jAo&DZLPabczkQ&()*	
r-   c                       e Zd Zd Zd Zd Zy)ImportFinderc                 "    t               | _        y r1   )setpackagesr=   s    r   r3   zImportFinder.__init__   s    r-   c                     |j                   D ];  }|j                  j                  d      d   }| j                  j	                  |       = y N.r   )namesnamesplitr   add)r6   nodealiasbase_packages       r   visit_ImportzImportFinder.visit_Import  s@    ZZ 	,E ::++C03LMMl+	,r-   c                     |j                   r:|j                   j                  d      d   }| j                  j                  |       y y r   )moduler   r   r   )r6   r   r   s      r   visit_ImportFromzImportFinder.visit_ImportFrom	  s9    ;;;;,,S1!4LMMl+ r-   N)r;   r?   r@   r3   r   r   rF   r-   r   r   r      s    ,,r-   r   c                 d    t        | t        j                        r| j                  } t	        |       S )z6Get source code for a method, including bound methods.)rY   types
MethodType__func__
get_source)methods    r   get_method_sourcer     s&    &%**+fr-   c                     	 t        |       }t        |      }dj                  d |j                  d      D              }dj                  d |j                  d      D              }||k(  S # t        t        f$ r Y yw xY w)z)Compare two methods by their source code.
c              3   `   K   | ]&  }|j                         j                  d       r#| ( yw@Nr(   r]   r   lines     r   r   z!is_same_method.<locals>.<genexpr>  $     eT

H_H_`cHdDe   $..c              3   `   K   | ]&  }|j                         j                  d       r#| ( ywr   r   r   s     r   r   z!is_same_method.<locals>.<genexpr>  r   r   F)r   r   r   	TypeErrorOSError)method1method2source1source2s       r   is_same_methodr     sy    
#G,#G, ))eW]]4-@ee))eW]]4-@ee'!!w s   A(A+ +A=<A=c                 P    t        |       rt        |      rt        | |      S | |k(  S )z=Compare two class items (methods or attributes) for equality.)callabler   )item1item2s     r   is_same_itemr   &  s&    8E?eU++~r-   c           	      
   | j                   }|j                  }g }|r#|j                  d| d|j                   d       n|j                  d| d       |j                  r:|r|j                  |j                  k7  r|j                  d|j                   d       |j                  j                         D ci c]A  \  }}|j                  d      s+t        |      s |rt        ||      rt        ||      |k(  s||C }}}|j                         D ]  \  }}t        |t              rZd|v r+|j                  dd	      }|j                  d
| d| d       E|j                  d
| dt        j                  |              p|j                  d
| dt        |               |r|j                  d       |j                  j                         D 	ci c]  \  }}	t        |	      rv|rYt        ||      rMt        |	t         t"        f      s7t        ||      j$                  j&                  |	j$                  j&                  k7  r|t        |	d      r|	j(                  n|	 }
}}	|
j                         D ]  \  }}t+        |      }|j-                  d      }|d   }t/        |      t/        |j1                               z
  }|D cg c]  }||d 	 }}dj3                  |D cg c]  }|j5                         rd
|z   n| c}      }|j                  |       |j                  d        t7               }|j9                  t;        j<                  dj3                  |                   |j>                  }g }|r+|j                  d|j@                   d|j                          |D ]  }|j                  d|         |r|j                  d       |jC                  |       dj3                  |      S c c}}w c c}	}w c c}w c c}w )z<Convert an instance to its class source code representation.zclass (z)::z    """z"""__r   z\"\"\"z    z = """z = r#   __wrapped__r   Nzfrom z import zimport )"r8   r;   appendrA   rW   re   r]   r   rf   getattrrY   r<   replacer_   dumpsreprstaticmethodclassmethod__code__co_coder   r   r   r   lstripr   r(   r   visitr   r   r   r?   extend)instancebase_clscls
class_nameclass_linesr   valueclass_attrsescaped_valuefuncmethodsr   method_sourcemethod_lines
first_lineindentr   import_finderrequired_importsfinal_linespackages                        r   instance_to_sourcer   .  s   


CJ KVJ<q1B1B0C2FGVJ<q12 {{Hx7G7G(GWS[[M56
 <<--/D%t$gh5'(D:QUZ:Z	 	eK  #((* 	>eeS!u} %eY ?""T$vm_C#HI""T$s4::e3D2E#FGdV3tE{m<=	> 2
 ,,,,.D$D>8T*4,!<=Hd+44<<@U@UU 	'$">dDHG    	f"6*$**40!!_
Z3z'8'8':#;;2>?$VW??		Wc"dtDJJL6D=d#J"de=)2	 !NM		$))K"89:$-- K U8#6#6"7x@Q@Q?RST $ 0WWI./0 2 {#99[!!M.( @"ds   8AO/BO5O;P 
c                    t        | t              s"t        |       st        dt        |              d}	 t	        | dd      xs t        j                  |       }t        |      j                         S # t        $ r}|}Y d}~nd}~ww xY w	 ddl
}|j                         }|st        d      dj                  |j                  j                  dg             j                         }|st!        d      t#        j$                  |      }t#        j&                  |      D ]  }t        |t"        j(                  t"        j*                  f      s.|j,                  | j.                  k(  sHt        dj                  |j1                  d      |j2                  d	z
  |j4                               j                         c S  t!        d
| j.                   d      # t        $ r |t         $ r}||d}~ww xY w)a  Get the source code of a class or callable object (e.g.: function, method).
    First attempts to get the source code using `inspect.getsource`.
    In a dynamic environment (e.g.: Jupyter, IPython), if this fails,
    falls back to retrieving the source code from the current interactive shell session.

    Args:
        obj: A class or callable object (e.g.: function, method)

    Returns:
        str: The source code of the object, dedented and stripped

    Raises:
        TypeError: If object is not a class or callable
        OSError: If source code cannot be retrieved from any source
        ValueError: If source cannot be found in IPython history

    Note:
        TODO: handle Python standard REPL
    z Expected class or callable, got N
__source__r   zNo active IPython shell foundr   Inz&No code cells found in IPython sessionr"   zCould not find source code for z in IPython history)rY   r:   r   r   r   inspect	getsourcer   r(   r   IPythonget_ipythonImportErrorr   user_nsgetrv   r   r   walkClassDefFunctionDefr   r;   r   lineno
end_lineno)	rS   inspect_errorsourcer}   r   shell	all_cellstreer   s	            r   r   r     s   ( sD!Xc]:49+FGGMlD1KW5F5Fs5Kf~##%% ###%=>>IIemm//b9:@@B	EFFyy#HHTN 	kD$s ?@TYYRUR^R^E^dii	(=dkkAoPTP_P_(`abhhjj	k :3<<.H[\]]  #]"#sC   <A3 3	B<BBB>G G %AG 8G G-%G((G-c                     t               }| j                  |d       t        j                  |j	                               j                  d      S )NPNG)formatzutf-8)r   savebase64	b64encodegetvaluedecode)imagebuffereds     r   encode_image_base64r
    s>    yH	JJxJ&H--/077@@r-   c                     d|  S )Nzdata:image/png;base64,rF   )base64_images    r   make_image_urlr    s    #L>22r-   folderc                     t        j                  | d       t        t         j                  j	                  | d      d      5  	 d d d        y # 1 sw Y   y xY w)NT)exist_okz__init__.pyw)osmakedirsopenpathr   )r  s    r   make_init_filer    sA    KK&	bggll6=13	7   s   AAr   c                 v    t        | t              r(| j                         xr t        j                  |        S dS )NF)rY   r<   isidentifierkeyword	iskeyword)r   s    r   is_valid_namer    s4    BLTSVBW4>w'8'8'>#>b]bbr-   a  import yaml
import os
from smolagents import GradioUI, {{ class_name }}, {{ agent_dict['model']['class'] }}

# Get current directory path
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))

{% for tool in tools.values() -%}
from {{managed_agent_relative_path}}tools.{{ tool.name }} import {{ tool.__class__.__name__ }} as {{ tool.name | camelcase }}
{% endfor %}
{% for managed_agent in managed_agents.values() -%}
from {{managed_agent_relative_path}}managed_agents.{{ managed_agent.name }}.app import agent_{{ managed_agent.name }}
{% endfor %}

model = {{ agent_dict['model']['class'] }}(
{% for key in agent_dict['model']['data'] if key not in ['class', 'last_input_token_count', 'last_output_token_count'] -%}
    {{ key }}={{ agent_dict['model']['data'][key]|repr }},
{% endfor %})

{% for tool in tools.values() -%}
{{ tool.name }} = {{ tool.name | camelcase }}()
{% endfor %}

with open(os.path.join(CURRENT_DIR, "prompts.yaml"), 'r') as stream:
    prompt_templates = yaml.safe_load(stream)

{{ agent_name }} = {{ class_name }}(
    model=model,
    tools=[{% for tool_name in tools.keys() if tool_name != "final_answer" %}{{ tool_name }}{% if not loop.last %}, {% endif %}{% endfor %}],
    managed_agents=[{% for subagent_name in managed_agents.keys() %}agent_{{ subagent_name }}{% if not loop.last %}, {% endif %}{% endfor %}],
    {% for attribute_name, value in agent_dict.items() if attribute_name not in ["model", "tools", "prompt_templates", "authorized_imports", "managed_agents", "requirements"] -%}
    {{ attribute_name }}={{ value|repr }},
    {% endfor %}prompt_templates=prompt_templates
)
if __name__ == "__main__":
    GradioUI({{ agent_name }}).launch()
c                   *    e Zd ZdZddedz  fdZd Zy)RateLimiteraJ  Simple rate limiter that enforces a minimum delay between consecutive requests.

    This class is useful for limiting the rate of operations such as API requests,
    by ensuring that calls to `throttle()` are spaced out by at least a given interval
    based on the desired requests per minute.

    If no rate is specified (i.e., `requests_per_minute` is None), rate limiting
    is disabled and `throttle()` becomes a no-op.

    Args:
        requests_per_minute (`float | None`): Maximum number of allowed requests per minute.
            Use `None` to disable rate limiting.
    Nrequests_per_minutec                 T    |d u| _         | j                   rd|z  nd| _        d| _        y )Ng      N@g        )_enabled	_interval
_last_call)r6   r  s     r   r3   zRateLimiter.__init__	  s*    +477;}} 33#r-   c                     | j                   syt        j                         }|| j                  z
  }|| j                  k  r"t        j                  | j                  |z
         t        j                         | _        y)z6Pause execution to respect the rate limit, if enabled.N)r   r   r"  r!  sleep)r6   nowelapseds      r   throttlezRateLimiter.throttle  sS    }}iik'T^^#JJt~~/0))+r-   r1   )r;   r?   r@   rA   r[   r3   r'  rF   r-   r   r  r    s    EDL 
&r-   r  r1   )>r   r  importlib.metadatar   importlib.utilr   r_   r  r  r   r   r   	functoolsr   ior   pathlibr   textwrapr   typingr   r   smolagents.memoryr	   __all__r<   r\   r   BASE_BUILTIN_MODULESr.   	Exceptionr
   rD   rH   rL   rN   rP   rR   ra   rd   r>   r   r   r   MAX_LENGTH_TRUNCATE_CONTENTrZ   r   NodeVisitorr   r   r   r   r   r   r
  r  r  r  r(   AGENT_GRADIO_APP_TEMPLATEr  rF   r-   r   <module>r6     s  "        	 	       % - .     
Ds 
Ds 
D	O 	O	
 		* 		 		, 		1 		: 	  4
s 
uT#s(^S-@'A 
. uS#X 3QU: 53 5sCx 5S 5p $  6Q 
c 
s 
UX 
,3?? ,"W"t3#s 3#lA33: c c c$H 
EGI N& &r-   