Skip to main content
Glama
llm_generator.cpython-311.pyc9.37 kB
� �M�g3���ddlZddlZddlmZmZddlmZddlZddlZddl m Z m Z m Z ddl mZddlZGd�d��ZdS) �N)�Dict�Optional)�Path�)� MethodCache�MethodValidator�LLMMeter)�FunctionDefinitionc�f�eZdZdedefd�Zdededefd�Zdededefd�Zdefd �Z dededefd �Z d S) �LLMMethodGenerator� cache_dir�openai_api_keyc���tt|����|_t��|_t ��|_tjt��|_ |t_ dS)N) rr�cacher� validatorr �meter�logging� getLogger�__name__�logger�openai�api_key)�selfr rs �9/Users/arjun/repos/sparkmango/mcp_server/llm_generator.py�__init__zLLMMethodGenerator.__init__ sN�� ��i���1�1�� �(�*�*����Z�Z�� ��'��1�1�� �(������function� contract_abi�returnc��K�|j�|��}|r|S|�||���d{V��}|j�||��\}}|st d|�����|j�||��|S)zM Generate a method implementation, using cache if available. Nz"Invalid implementation generated: )r�get_cached_implementation�_generate_with_llmr�validate_implementation� ValueError�cache_implementation)rrr�cached�implementation�is_valid�errors r�generate_methodz"LLMMethodGenerator.generate_methods����� ��5�5�h�?�?�� � ��M� $�6�6�x��N�N�N�N�N�N�N�N���.�@�@��>�Z�Z���%�� K��I�%�I�I�J�J� J� � �'�'��.�A�A�A��rc ��XK�|�||��}d}d}t|��D�]�} tj�dd|���d�d|d�gd����d {V��}|j�|jj ��|j d j j }d |vr5|� d ��d � d ��d }n8d |vr4|� d ��d � d ��d }|���cS#tjj$r�} ||d z kr�d d l} |} | �dt'| ����} | r"t)| �d ����} |j�d| �d|d z�d|����t1j| ���d {V��|dz}Yd } ~ ���d } ~ wt4$r0} |j�dt'| �������d } ~ wwxYwd S)zD Generate method implementation using OpenAI's API. ��zgpt-4�system)�role�content�userg�������?)�model�messages� temperatureNrz ```pythonrz```zPlease try again in (\d+\.\d+)szRate limit hit, waiting zs before retry �/�zLLM generation failed: )�_create_prompt�ranger�ChatCompletion�acreate�_get_system_promptr� record_usage�usage� total_tokens�choices�messager0�split�stripr)�RateLimitError�re�search�str�float�groupr�warning�asyncio�sleep� Exception) rrr�prompt� max_retries� retry_delay�attempt�responser'�erD� wait_time�matchs rr"z%LLMMethodGenerator._generate_with_llm+s������$�$�X�|�<�<��� �� ��[�)�)�* �* �G�) �!'�!6�!>�!>�!�!)�d�6M�6M�6O�6O�P�P�!'�F�;�;��!$� "?�"�"��������� �'�'���(C�D�D�D�!)�!1�!�!4�!<�!D���.�0�0�%3�%9�%9�+�%F�%F�q�%I�%O�%O�PU�%V�%V�WX�%Y�N�N��n�,�,�%3�%9�%9�%�%@�%@��%C�%I�%I�%�%P�%P�QR�%S�N�%�+�+�-�-�-�-�-���<�.� !� !� !��k�A�o�-�-��� � � �'� �� � �"D�c�!�f�f�M�M���6� %�e�k�k�!�n�n� 5� 5�I�� �#�#�$t�y�$t�$t�Y`�cd�Yd�$t�$t�gr�$t�$t�u�u�u��m�I�.�.�.�.�.�.�.�.�.��q� � � � � � � ������ � � �� �!�!�"D�C��F�F�"D�"D�E�E�E������ ����Q* �* s%�DD4�4H'�BG*�* H'�7+H"�"H'c��dS)z"Get the system prompt for the LLM.a�You are a smart contract developer specializing in Web3.py implementations. Your task is to generate Python implementations of Solidity functions that follow the Model Context Protocol (MCP). You will be given a template and asked to fill in specific parts of it. Your response should ONLY include the filled-in template, with no additional text or explanations. The template will contain placeholders marked with <placeholder> that you need to replace with the appropriate values: 1. <function_name> - Replace with the actual function name from the Solidity contract 2. <params> - Replace with the function parameters, comma-separated (e.g., "owner, spender" for approve function) 3. <str(e)> - Leave as is, this is for error handling IMPORTANT: - For view functions, the template returns {"result": result} - For state-changing functions, the template returns {"type": "transaction_to_sign", "transaction": tx} - DO NOT modify the template structure, only replace the placeholders - Keep all dictionary keys and values exactly as shown in the template - Preserve all whitespace and indentation Your response should be a complete, valid Python function that can be used directly.�)rs rr;z%LLMMethodGenerator._get_system_prompt`s��X�Xrc���dg}|jD]&}|�|j�d|j�����'d�|��}d}|jjdkrd|j�d|�d|�d |j�d � }nd|j�d|�d|�d |j�d � }d |j�d|�d|j�d|jj�dd�|jD���dd�|jD���dtj |���d�S)zCreate the prompt for the LLM.z state: State�: z, r�viewz async def �(z) -> a: try: contract = web3.eth.contract(address=state.contract_address, abi=state.abi) result = await contract.functions.<function_name>(<params>).call() return {"result": result} except Exception as e: raise ValueError(f"Failed to execute z : <str(e)>")a�: try: contract = web3.eth.contract(address=state.contract_address, abi=state.abi) tx = await contract.functions.<function_name>(<params>).build_transaction({ "from": state.account, "gas": await contract.functions.<function_name>(<params>).estimate_gas() }) return { "type": "transaction_to_sign", "transaction": tx } except Exception as e: raise ValueError(f"Failed to build z transaction: <str(e)>")z'Fill in the following template for the z function: Template: z Function details: - Name: z - State mutability: z - Inputs: c�0�g|]}|j�d|j����S�rX��name�type��.0�ps r� <listcomp>z5LLMMethodGenerator._create_prompt.<locals>.<listcomp>�s*�� ;� ;� ;�a�q�v� !� !��� !� !� ;� ;� ;rz - Outputs: c�0�g|]}|j�d|j����Sr\r]r`s rrcz5LLMMethodGenerator._create_prompt.<locals>.<listcomp>�s*�� =� =� =�q��� "� "�!�&� "� "� =� =� =rz Contract ABI: z� Replace the placeholders in the template with the appropriate values. Your response should be a complete, valid Python function.) �inputs�appendr^r_�join�state_mutability�value�outputs�json�dumps)rrr�params�param� param_str� return_type�templates rr7z!LLMMethodGenerator._create_promptus���!�!���_� 9� 9�E� �M�M�U�Z�7�7�5�:�7�7� 8� 8� 8� 8��I�I�f�%�%� �� � � $� *�f� 4� 4�L�h�m�L�L�i�L�L�k�L�L� /7�m� L�L�L�H�H� V�h�m� V� V�i� V� V�k� V� V�-5�M� V� V� V�H� D�8�=� D� D� � D� D� �� D� D��.�4� D� D� <� ;�8�?� ;� ;� ;� D� D� >� =�H�,<� =� =� =� D� D��z�,�'�'� D� D� D� DrN) r� __module__� __qualname__rFrr rr*r"r;r7rVrrr r s�������(�#�(�s�(�(�(�(��.@��PT��Y\�����,3�1C�3�SW�3�\_�3�3�3�3�jX�C�X�X�X�X�*1D�'9�1D��1D�RU�1D�1D�1D�1D�1D�1Drr )rkr�typingrr�pathlibrrrJ� method_cacherrr � abi_analyzerr �web3r rVrr�<module>rys��� � � � �����!�!�!�!�!�!�!�!������� � � � �����@�@�@�@�@�@�@�@�@�@�,�,�,�,�,�,� � � � �[D�[D�[D�[D�[D�[D�[D�[D�[D�[Dr

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ArjunBhuptani/sparkmango'

If you have feedback or need assistance with the MCP directory API, please join our Discord server