### Configure SDK with .env file Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Example of .env file for SDK configuration. Variables must start with 'SNET_'. ```dotenv SNET_PRIVATE_KEY=12345678... SNET_ETH_RPC_ENDPOINT=https://mainnet.infura.io/v3/12345678... SNET_FORCE_UPDATE=False SNET_LIGHTHOUSE_TOKEN=12345678... ``` -------------------------------- ### Install Dependencies Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Install the necessary Python dependencies for the project using pip. Ensure you have a requirements.txt file. ```bash $ pip install -r requirements.txt ``` -------------------------------- ### Install snet.sdk Package Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/calculator.md Install the necessary SingularityNET Python SDK package using pip. This is the first step before configuring the SDK. ```sh pip install snet.sdk ``` -------------------------------- ### Configure Snet SDK Instance Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/console_app.md Configure the SDK with your private key, Ethereum RPC endpoint, and other necessary parameters. This setup is crucial for initializing the SnetSDK instance. ```python from snet import sdk """ SDK configuration that is configured by the application provider. To run the application you need to change the 'private_key', 'eth_rpc_endpoint' and 'identity_name' values. """ config = sdk.config.Config(private_key="YOUR_PRIVATE_KEY", eth_rpc_endpoint=f"https://sepolia.infura.io/v3/YOUR_INFURA_KEY", concurrency=False, force_update=False) snet_sdk = sdk.SnetSDK(config) # the 'SnetSDK' instance ``` -------------------------------- ### Clone snet-sdk-python Repository Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Clone the project repository and navigate into the project directory. This is the first step to start development. ```bash $ git clone git@github.com:singnet/snet-sdk-python.git $ cd snet-sdk-python ``` -------------------------------- ### Install Package in Development Mode Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Install the snet-sdk-python package in editable mode using pip. This allows for changes to be reflected immediately without reinstallation. ```bash $ pip install -e . ``` -------------------------------- ### Create Service Client with Paid Call Strategy Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Example of creating a service client for regular paid calls. ```APIDOC ## Create Service Client with Paid Call Strategy ### Description This demonstrates how to instantiate a service client configured to use the `PAID_CALL` payment strategy for standard paid interactions. ### Method `snet_sdk.create_service_client` ### Parameters - `org_id` (string) - Required - The organization ID for the service. - `service_id` (string) - Required - The ID of the service. - `payment_strategy_type` (PaymentStrategyType) - Required - Set to `PaymentStrategyType.PAID_CALL`. ``` -------------------------------- ### Create Service Client with Free Call Strategy Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Example of creating a service client specifically for free calls. ```APIDOC ## Create Service Client with Free Call Strategy ### Description This demonstrates how to instantiate a service client configured to use the `FREE_CALL` payment strategy. ### Method `snet_sdk.create_service_client` ### Parameters - `org_id` (string) - Required - The organization ID for the service. - `service_id` (string) - Required - The ID of the service. - `payment_strategy_type` (PaymentStrategyType) - Required - Set to `PaymentStrategyType.FREE_CALL`. ``` -------------------------------- ### add_description Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/storage_provider/service_metadata.md Adds a new description to the service metadata, prompting for user guide URL and service descriptions. ```APIDOC ## add_description ### Description Adds a new description to the `description` field of the `m` dict. Prompts the user to enter user guide url, service long description and service short description. ### Method Not applicable (SDK method) ### Returns - None ``` -------------------------------- ### Config Class Get Method Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/config.md Retrieves a configuration value by its key, with an option to provide a default value if the key is not found. ```APIDOC ## `get` Config ### Description Returns the value associated with the given key from the `__config` dict or the default value if the key is not found. ### Method get ### Parameters #### Args - **key** (str) - Required - The key of the value to retrieve. - **default** (Any) - Optional - The default value to return if the key is not found. Defaults to None. ### Returns - The value associated with the given key or the default value if the key is not found. (Any) ``` -------------------------------- ### Config Class Get Item Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/config.md Retrieves a configuration value by its key using dictionary-like access. ```APIDOC ## `__getitem__` Config ### Description Overrides the `__getitem__` Python special method. Returns the value associated with the given key from the `__config` dict. ### Method __getitem__ ### Parameters #### Args - **key** (str) - Required - The key of the value to retrieve. ### Returns - The value associated with the given key. (Any) ``` -------------------------------- ### get Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/storage_provider/service_metadata.md Retrieves a value from the service metadata dictionary, with an optional default value. ```APIDOC ## get ### Description Returns the value associated with the given key from the `m` dict or the default value if the key is not found. ### Method Not applicable (Python method) ### Parameters #### Arguments - `key` (str) - Required - The name of the field. - `default` (Any) - Optional - The default value to return if the key is not found. Defaults to None. ### Returns - The value associated with the given key. (Any) ``` -------------------------------- ### Get Organization and Service Data Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Use these methods to retrieve lists of organizations and services, as well as metadata for specific organizations and services. Ensure the SnetSDK is initialized. ```python from snet.sdk import SnetSDK sdk = SnetSDK() org_id = "" service_id = "" orgs_list = sdk.get_organization_list() services_list = sdk.get_services_list(org_id=org_id) org_metadata = sdk.get_organization_metadata(org_id) service_metadata = sdk.get_service_metadata(org_id, service_id) ``` -------------------------------- ### Get Escrow Balance Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/account.md Retrieves the escrow balance for the current account in cogs. ```APIDOC ## escrow_balance Account ### Description Retrieves the escrow balance for the current account. ### Returns - The escrow balance in cogs. (int) ``` -------------------------------- ### Get Raw Service and Message Information Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Retrieve structured information about service methods and messages using `get_services_and_messages_info()`. This is useful for programmatic processing of service definitions. ```python services, messages = service_client.get_services_and_messages_info() print(services) print(messages) # {'Calculator': [('add', 'Numbers', 'Result'), ('sub', 'Numbers', 'Result'), ('mul', 'Numbers', 'Result'), ('div', 'Numbers', 'Result')]} # {'Numbers': [('float', 'a'), ('float', 'b')], 'Result': [('float', 'value')]} ``` -------------------------------- ### Get Service and Message Info Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Retrieve and print information about the available services and messages for a given service client. This helps in understanding the service's API. ```python print(service_client.get_services_and_messages_info_as_pretty_string()) ``` -------------------------------- ### Configure snet.sdk and Create Service Client Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/calculator.md Configure the SDK with your private key and Ethereum RPC endpoint. Then, create a client for the calculator service by specifying its organization ID, service ID, and group name. ```python from snet import sdk config = sdk.config.Config(private_key="YOUR_PRIVATE_KEY", eth_rpc_endpoint=f"https://sepolia.infura.io/v3/YOUR_INFURA_KEY", concurrency=False, force_update=False) snet_sdk = sdk.SnetSDK(config) calc_client = snet_sdk.create_service_client(org_id="26072b8b6a0e448180f8c0e702ab6d2f", service_id="Exampleservice", group_name="default_group") ``` -------------------------------- ### StorageProvider.__init__ Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/storage_provider/storage_provider.md Initializes a new instance of the StorageProvider class. It requires configuration details and a registry contract instance. ```APIDOC ## __init__ ### Description Initializes a new instance of the StorageProvider class. ### Parameters #### Args - **config** (Config) - Required - An instance of the `Config` class. - **registry_contract** (Contract) - Required - The contract instance of the registry. ### Returns - _None_ ``` -------------------------------- ### PaymentChannelProvider.__init__ Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/mpe/payment_channel_provider.md Initializes a new instance of the PaymentChannelProvider class. It requires instances of Web3, PaymentChannelStateService client, and MPEContract. ```APIDOC ## __init__ ### Description Initializes a new instance of the class. ### Parameters - **w3** (Web3) - Required - An instance of the `Web3` class for interacting with the Ethereum blockchain. - **payment_channel_state_service_client** (ServiceStub) - Required - A stub for interacting with PaymentChannelStateService via gRPC. - **mpe_contract** (MPEContract) - Required - An instance of the `MPEContract` class for interacting with the MultiPartyEscrow contract. ### Returns - None ``` -------------------------------- ### Config Class Get IPFS Endpoint Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/config.md Retrieves the configured IPFS endpoint. ```APIDOC ## `get_ipfs_endpoint` Config ### Description Returns the `ipfs_endpoint` field value from the `__config` dict. ### Method get_ipfs_endpoint ### Returns - The IPFS endpoint. (str) ``` -------------------------------- ### Configure SDK with Python function Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Configure the SDK using the configure() function with explicit parameters. Ensure required parameters like private_key and eth_rpc_endpoint are provided. ```python from snet.sdk.config import configure PRIVATE_KEY = "12345678..." INFURA_KEY = "12345678..." configure( private_key=PRIVATE_KEY, eth_rpc_endpoint=f"https://mainnet.infura.io/v3/{INFURA_KEY}", force_update=False, lighthouse_token="12345678...", ) ``` -------------------------------- ### Get Token Allowance Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/account.md Retrieves the allowance of the current account for the MPE contract in cogs. ```APIDOC ## allowance Account ### Description Retrieves the allowance of the current account for the MPE contract. ### Returns - The allowance in cogs. (int) ``` -------------------------------- ### Account Initialization Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/account.md Initializes a new instance of the Account class with provided Web3 instance, configuration, and MPE contract. ```APIDOC ## __init__ Account ### Description Initializes a new instance of the `Account` class. ### Parameters #### Arguments - **w3** (Web3) - An instance of the `Web3` class. - **config** (dict) - A dictionary containing the configuration settings. - **mpe_contract** (MPEContract) - An instance of the `MPEContract` class. ### Returns - _None_ ``` -------------------------------- ### Get Current Block Number Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Retrieve the latest block number from the blockchain using the `get_current_block_number()` method. ```python block_number = service_client.get_current_block_number() print(f"Current block is {block_number}") # Current block is 6574322 ``` -------------------------------- ### Create Service Client Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Create a service client instance using the SDK. Specify organization ID, service ID, and payment strategy type. ```python service_client = snet_sdk.create_service_client(org_id="26072b8b6a0e448180f8c0e702ab6d2f", service_id="Exampleservice", payment_strategy_type=PaymentStrategyType.PAID_CALL) ``` -------------------------------- ### Create Service Metadata Instance Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Instantiate and configure service metadata using chaining methods before publishing. This includes setting basic details, adding service groups with endpoints, and specifying contributors. ```python from snet.sdk import SnetSDK, ServiceMetadata sdk = SnetSDK() org_id = "" service_id = "" service_metadata = ( ServiceMetadata( version=1, display_name=service_id, service_type="grpc", tags=["first", "second"] ) .add_group(free_call_signer_address="0x123456qweasd", endpoints=["https://test-daemon.com"]) .add_contributor("me") ) ``` -------------------------------- ### Create Service Client with Free Call Strategy Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Instantiate a service client using the FREE_CALL payment strategy. This is suitable for services that offer free usage. ```python service_client = snet_sdk.create_service_client(org_id="26072b8b6a0e448180f8c0e702ab6d2f", service_id="Exampleservice", payment_strategy_type = PaymentStrategyType.FREE_CALL) ``` -------------------------------- ### Get Service Call Price Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Determine the cost in cogs for invoking a specific service function using the `get_price()` method. ```python price = service_client.get_price() print(f"The price in cogs for calling the service {service_client.service_id} is {price}") # The price in cogs for calling the service Exampleservice is 1 ``` -------------------------------- ### Display Commands Help Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/console_app.md This function displays a list of available commands and their descriptions. It is called when the user enters 'help' and dynamically shows commands based on the currently active menu. ```python def commands_help(): global active_commands print("Available commands:") for command in active_commands.items(): print(f'\t{command[0]} - {command[1][1]}') ``` -------------------------------- ### StorageProvider.fetch_and_extract_proto Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/storage_provider/storage_provider.md Fetches an archive containing .proto files from IPFS or FileCoin and extracts them to a specified directory. ```APIDOC ## fetch_and_extract_proto ### Description Retrieves archive with .proto files from IPFS or FileCoin depends on the `service_api_source` prefix and extracts it using `safe_extract_proto` function from `utils` module. ### Parameters #### Args - **service_api_source** (str) - Required - The hash link to the .proto files od the service with the prefix ('filecoin://' or 'ipfs://'). - **protodir** (str) - Required - The directory where the .proto files are saved ### Returns - _None_ ``` -------------------------------- ### Get Service Stub Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/init.md Retrieves the gRPC service stub for a specified organization and service ID, which is essential for making calls to the service. ```APIDOC ## `SnetSDK.get_service_stub` ### Description Retrieves the gRPC service stub for the given organization and service ID. ### Method `get_service_stub` ### Parameters #### Args - `org_id` (str): The ID of the organization. - `service_id` (str): The ID of the service. ### Returns - The gRPC service stub for the given organization and service ID. (ServiceStub) ### Raises - Exception: If an error occurs while importing a module. ``` -------------------------------- ### Config Class Initialization Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/config.md Initializes a new instance of the Config class with essential configuration parameters for the SDK. ```APIDOC ## `__init__` Config ### Description Initializes a new instance of the class. Sets `__config` fields from passed arguments. ### Method __init__ ### Parameters #### Args - **private_key** (str) - Required - Your wallet's private key that will be used to pay for calls. - **eth_rpc_endpoint** (str) - Required - RPC endpoint that is used to access the Ethereum network. - **wallet_index** (int) - Optional - The index of the wallet that will be used to pay for calls. Defaults to 0. - **ipfs_endpoint** (str) - Optional - IPFS endpoint that is used to access IPFS. Defaults to None. - **concurrency** (bool) - Optional - If set to True, will enable concurrency for the SDK. Defaults to True. - **force_update** (bool) - Optional - If set to False, will reuse the existing gRPC stubs (if any) instead of downloading proto and regenerating them every time. Defaults to False. - **mpe_contract_address** (str) - Optional - The address of the Multi-Party Escrow smart contract. Defaults to None. - **token_contract_address** (str) - Optional - The address of the SingularityNET token smart contract. Defaults to None. - **registry_contract_address** (str) - Optional - The address of the Registry smart contract. Defaults to None. - **signer_private_key** (str) - Optional - The private key of the signer. Used to sign the service call. Equals to `private_key` by default. ### Returns - None ``` -------------------------------- ### Get Service Metadata Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Fetch and display metadata for a service stored on IPFS. This includes details like version, display name, encoding, and endpoint information. ```python service_metadata = snet_sdk.get_service_metadata(org_id="26072b8b6a0e448180f8c0e702ab6d2f", service_id="Exampleservice") print(*service_metadata.m.items(), sep="\n", end="\n\n") print(*service_metadata.get_tags(), sep=",", end="\n\n") print(*service_metadata.get_all_endpoints_for_group(group_name="default_group"), sep=",", end="\n\n") # ('version', 1) # ('display_name', 'Example service') # ('encoding', 'proto') # ('service_type', 'grpc') # ('model_ipfs_hash', 'QmeyrQkEyba8dd4rc3jrLd5pEwsxHutfH2RvsSaeSMqTtQ') # ('mpe_address', '0x7E0aF8988DF45B824b2E0e0A87c6196897744970') # ('groups', [{'free_calls': 0, 'free_call_signer_address': '0x7DF35C98f41F3Af0df1dc4c7F7D4C19a71Dd059F', 'daemon_addresses': ['0x0709e9b78756b740ab0c64427f43f8305fd6d1a7'], 'pricing': [{'default': True, 'price_model': 'fixed_price', 'price_in_cogs': 1}], 'endpoints': ['http://node1.naint.tech:62400'], 'group_id': '/mb90Qs8VktxGQmU0uRu0bSlGgqeDlYrKrs+WbsOvOQ=', 'group_name': 'default_group'}]) # ('service_description', {'url': 'https://ropsten-v2-publisher.singularitynet.io/org', 'short_description': 'Example service', 'description': 'Example service'}) # ('media', [{'order': 1, 'url': 'https://ropsten-marketplace-service-assets.s3.us-east-1.amazonaws.com/26072b8b6a0e448180f8c0e702ab6d2f/services/d05c62bf9aa84843a195457d98417f4e/assets/20240327124952_asset.jpeg', 'file_type': 'image', 'asset_type': 'hero_image', 'alt_text': ''}]) # ('contributors', [{'name': 'test', 'email_id': ''}]) # ('tags', ['exampleservice']) # # exampleservice # # http://node1.naint.tech:62400 ``` -------------------------------- ### Create Service Client with Paid Call Strategy Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Instantiate a service client using the PAID_CALL payment strategy for regular metered usage. The SDK automatically manages payment channels. ```python service_client = snet_sdk.create_service_client(org_id="26072b8b6a0e448180f8c0e702ab6d2f", service_id="Exampleservice", payment_strategy_type = PaymentStrategyType.PAID_CALL) ``` -------------------------------- ### PrePaidPaymentStrategy.__init__ Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/payment_strategies/prepaid_payment_strategy.md Initializes a new instance of the PrePaidPaymentStrategy class. This constructor sets up the payment strategy with a concurrency manager, block offset, and a specified call allowance. ```APIDOC ## __init__ ### Description Initializes a new instance of the class. ### Parameters #### Args - **concurrency_manager**: The ConcurrencyManager instance. - **block_offset** (int): Block offset. - **call_allowance** (int): The amount of allowed calls. Defaults to 1. ### Returns - _None_ ``` -------------------------------- ### SnetSDK Initialization Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/init.md Initializes a new instance of the SnetSDK class. This involves setting up connections to the Ethereum blockchain, the MultiPartyEscrow contract, and the Registry contract. ```APIDOC ## `SnetSDK.__init__` ### Description Initializes a new instance of the `SnetSDK` class. Initializes `web3` with the specified Ethereum RPC endpoint. Instantiates the MPE contract with the specified contract address if provided, otherwise uses the default MPE contract. Instantiates the IPFS client with the specified IPFS endpoint if provided, otherwise uses the default IPFS endpoint. Instantiates the Registry contract with the specified contract address if provided, otherwise uses the default Registry contract. Instantiates the Account object with the specified Web3 client, SDK configuration, and MPE contract. ### Method `__init__` ### Parameters #### Args - `sdk_config` (Config): A `Config` object containing the SDK configuration. - `metadata_provider` (MetadataProvider): A `MetadataProvider` object. Defaults to _None_. ``` -------------------------------- ### Manage Payment Channel Funds and Expiration Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Demonstrates how to add funds to an existing payment channel, extend its expiration, or perform both actions simultaneously. ```python payment_channel = service_client.open_channel(amount=123456, expiration=33333) payment_channel.add_funds(amount=123456) payment_channel.extend_expiration(expiration=33333) payment_channel.extend_and_add_funds(amount=123456, expiration=33333) ``` -------------------------------- ### get_services_and_messages_info_as_pretty_string Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/service_client.md Retrieves service and message information from a protobuf file and formats it as a string. ```APIDOC ## get_services_and_messages_info_as_pretty_string ### Description Retrieves information about the services and messages defined in the protobuf file and returns it as a formatted string. It first calls `get_services_and_messages_info` and then formats the result. ### Method (Not specified, likely SDK method) ### Returns - A formatted string containing information about the services and messages defined in the protobuf file. (str) ``` -------------------------------- ### Main Calculator Application Loop Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/calculator.md The main function initializes the calculator interface, reads user input in a loop, parses expressions, and calls the remote service for calculations. It handles potential exceptions during parsing or calculation. ```python operators = { "+": "add", "-": "sub", "*": "mul", "/": "div" } def main(): print(""" Welcome to the calculator powered by SingularityNET platform! Please type the expression you want to calculate, e.g. 2 + 3. Type 'exit' to exit the program.""") while True: expression = input("Calculator> ") if expression == "exit": break try: a, b, op = parse_expression(expression) print(f"Calculating {a} {op} {b}...") result = calc_client.call_rpc(operators[op], "Numbers", a=a, b=b) print(f"{a} {op} {b} = {result}") except Exception as e: print(e) if __name__ == "__main__": main() ``` -------------------------------- ### Publish Service Comprehensively Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Publish a service to the blockchain, including saving proto files and service metadata to storage. Requires the organization ID, service ID, configured service metadata, the path to proto files, and the storage type. ```python sdk.publish_service_comprehensively( org_id, service_id, service_metadata, proto_dir="", storage_type=StorageType.FILECOIN, ) ``` -------------------------------- ### Train the Model Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Initiate model training with the `train_model` method, providing the model ID and the training price. This method returns the model's status as it enters the training phase. ```python train_price = service_client.training.train_model_price(model_id) model_status = service_client.training.train_model(model_id, train_price) print(model_status) # ModelStatus.TRAINING ``` -------------------------------- ### Create Service Client Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/init.md Creates a service client for a given organization and service ID. This method handles loading and compiling proto files if necessary and sets up the payment strategy. ```APIDOC ## `SnetSDK.create_service_client` ### Description If `force_update` is True or if there are no gRPC stubs for the given service, the proto files are loaded and compiled using the `generate_client_library()` method of the `ClientLibGenerator` class instance. It then initializes `payment_strategy` to `DefaultPaymentStrategy` if it is not specified. It also sets the `options` dictionary with some default values. If `self._metadata_provider` is not specified it is initialized by `IPFSMetadataProvider`. It also gets the service stub using the `self.get_service_stub` method and the pb2 module using the `self.get_module_by_keyword` method. Finally, it creates a new instance of the `ServiceClient` class with all the required parameters, which is then returned. ### Method `create_service_client` ### Parameters #### Args - `org_id` (str): The ID of the organization. - `service_id` (str): The ID of the service. - `group_name` (str): The name of the payment group. Defaults to _None_. - `payment_strategy` (PaymentStrategy): The payment channel management strategy. Defaults to _None_. - `payment_strategy_type` (PaymentStrategyType): The type of payment management strategy. Defaults to `PaymentStrategyType.DEFAULT`. - `options` (dict): Additional options for the service client. Defaults to _None_. - `concurrent_calls` (int): The number of concurrent calls allowed. Defaults to 1. ### Returns - The created service client instance. (ServiceClient) ``` -------------------------------- ### Create a New Model Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Call the `create_model` method to initialize a new model. This method requires the service method name and a unique model name. It returns a `Model` object containing model details. ```python new_model = service_client.training.create_model(method_name=grpc_method_name, model_name=model_name) model_id = new_model.model_id print(new_model.status) # ModelStatus.CREATED ``` -------------------------------- ### Create Service Client with Prepaid Calls Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Use this snippet to create a service client configured for prepaid calls. Specify the organization ID, service ID, group name, set the payment strategy to PREPAID_CALL, and define the number of concurrent calls. ```python service_client = snet_sdk.create_service_client( org_id="26072b8b6a0e448180f8c0e702ab6d2f", service_id="Exampleservice", group_name="default_group", payment_strategy_type=PaymentStrategyType.PREPAID_CALL, concurrent_calls=5 # Number of prepaid calls to allocate ) ``` -------------------------------- ### Deposit Funds to Escrow and Open Channel Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Opens a payment channel with a specified amount of funds and expiration. Funds are first deposited to the escrow account. ```python snet_sdk.account.deposit_to_escrow_account(123456) service_client.open_channel(amount=123456, expiration=33333) ``` -------------------------------- ### Determine and Use Training Method Prices Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Before calling paid training methods like upload_and_validate or train_model, determine their prices using the respective price methods. Then, pass the obtained price to the training method. ```python validate_price = service_client.training.validate_model_price(model_id) model_status = service_client.training.upload_and_validate(model_id, zip_path, validate_price) ``` ```python train_price = service_client.training.train_model_price(model_id) model_status = service_client.training.train_model(model_id, train_price) ``` -------------------------------- ### ServiceClient Class Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/service_client.md Initializes a new instance of the ServiceClient class. This client is used to interact with a specific service, manage payment channels, and make RPC calls. ```APIDOC ## __init__ ServiceClient ### Description Initializes a new instance of the ServiceClient class. ### Method __init__ ### Parameters #### args: - **org_id** (str): The ID of the organization. - **service_id** (str): The ID of the service. - **service_metadata** (MPEServiceMetadata): The metadata for the service. - **group** (dict): The payment group from the service metadata. - **service_stubs** (list[ServiceStub]): The gRPC service stubs. - **payment_strategy** (PaymentStrategy): The payment channel management strategy. - **options** (dict): Additional options for the service client. - **mpe_contract** (MPEContract): The MPE contract instance. - **account** (Account): An instance of the Account class. - **sdk_web3** (Web3): The Web3 instance. - **pb2_module** (str | ModuleType): The module containing the gRPC message definitions. - **payment_channel_provider** (PaymentChannelProvider): The payment channel provider instance. - **path_to_pb_files** (Path): The path to the protobuf files. - **training_added** (bool): Whether training enabled on the service or not. ### Returns - _None_ ``` -------------------------------- ### Deposit Funds and Open Channel Simultaneously Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md A convenience method that deposits the specified FET tokens into MPE and then opens a payment channel. ```python service_client.deposit_and_open_channel(amount=123456, expiration=33333) ``` -------------------------------- ### create_model Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Creates a new model for training. It requires the service method name and a unique model name, with optional parameters for description, public accessibility, and access control. ```APIDOC ## create_model ### Description Creates a new model for training purposes. This method is the first step in the model training pipeline. ### Method `create_model` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method_name** (string) - Required - The name of the service method for which to create a model. - **model_name** (string) - Required - A unique name for the new model. - **model_description** (string) - Optional - A description for the new model. - **is_public_accessible** (boolean) - Optional - Defaults to `False`. Determines if the model is publicly accessible. - **addresses_with_access** (list of strings) - Optional - A list of addresses that have access to the model. Only relevant if `is_public_accessible` is `False`. ### Request Example ```python new_model = service_client.training.create_model(method_name=grpc_method_name, model_name=model_name) ``` ### Response #### Success Response Returns a `Model` object containing information about the newly created model. - **model_id** (string) - The unique identifier for the model. - **status** (ModelStatus) - The current status of the model (e.g., `ModelStatus.CREATED`). #### Response Example ```json { "model_id": "some_model_id", "status": "CREATED" } ``` ``` -------------------------------- ### Upload and Validate Training Dataset Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Use `upload_and_validate` to upload your training dataset. Provide the model ID, the path to the dataset archive, and the validated price. The method returns the model's status during validation. ```python validate_price = service_client.training.validate_model_price(model_id) zip_path = "PATH_TO_YOUR_DATASET_FILE" model_status = service_client.training.upload_and_validate(model_id, zip_path, validate_price) print(model_status) # ModelStatus.VALIDATING ``` -------------------------------- ### load Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/storage_provider/service_metadata.md Loads service metadata from a file into the internal dictionary. ```APIDOC ## load ### Description Loads the service metadata from the specified file and sets it in the `m` dict. ### Method Not applicable (Python method) ### Parameters #### Arguments - `file_name` (str) - Required - The name of the file containing the service metadata. ### Returns - None ``` -------------------------------- ### train_model Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/training/training.md Initiates the training process for a specified model, setting the price for the training job. ```APIDOC ## train_model ### Description Initiates the training process for a specified model, setting the price for the training job. ### Method (Not specified, likely internal SDK method) ### Parameters #### Path Parameters - **model_id** (str) - Required - The model ID to train. #### Query Parameters - **price** (int) - Required - The price of the method call. ### Returns - Status of the model. (ModelStatus) ### Raises - `NoSuchModelException`: If the model with the specified ID does not exist. - `GRPCException`: If the gRPC call fails. ``` -------------------------------- ### deposit_and_open_channel Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/mpe/payment_channel_provider.md Opens a payment channel with a specified amount of FET tokens and expiration time. It deposits the tokens and returns the newly opened channel. ```APIDOC ## deposit_and_open_channel ### Description Opens a payment channel with the specified amount of FET tokens in cogs and expiration time. The channel is then returned. ### Method Not specified (likely SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `account` (Account): The account object used to send the transaction. - `amount` (int): The amount of FET tokens in cogs to deposit into the channel. - `expiration` (int): The expiration time of the payment channel in blocks. - `payment_address` (str): The address of the payment recipient. - `group_id` (str): The ID of the payment group. - `payment_channel_state_service_client` (Any): Stub for interacting with PaymentChannelStateService via gRPC to pass it to PaymentChannel instances. ### Returns - The newly opened payment channel. (PaymentChannel) ``` -------------------------------- ### get_services_and_messages_info Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/service_client.md Retrieves and parses information about services and messages from a protobuf file. ```APIDOC ## get_services_and_messages_info ### Description Retrieves information about services and messages defined in a protobuf file. This function reads the content of a protobuf file and extracts information about the services and messages defined in it using regular expressions. ### Method (Not specified, likely SDK method) ### Returns - A tuple containing: - services (dict): A dictionary with service names as keys and lists of RPC methods (name, input type, output type) as values. - messages (dict): A dictionary with message names as keys and lists of fields (type, name) as values. (tuple[dict[str, list], dict[str, list]]) ``` -------------------------------- ### training Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/service_client.md Provides access to the training object associated with the service, raising an exception if training is not implemented. ```APIDOC ## training ### Description Property that returns the training object associated with the service. ### Method (Not specified, likely SDK method) ### Returns - The training object associated with the service. (Training) ### Raises - NoTrainingException: If training is not implemented for the service. ``` -------------------------------- ### Command Dictionary Structure Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/console_app.md This dictionary maps command names to their corresponding functions and descriptions, organized by menu (main, service, channel). It defines the available commands and their associated actions for each menu. ```python """ Commands available in the application with their descriptions and functions to call. """ commands = { "main": { "organizations": (list_organizations, "print a list of organization ids from Registry"), "services": (list_services_for_org, "print a list of service ids for an organization from Registry"), "balance": (balance, "print the account balance and the escrow balance"), "deposit": (deposit, "deposit FET tokens into MPE"), "block": (block_number, "print the current block number"), "service": (lambda: None, "go to the services menu"), "channel": (lambda: None, "go to the channels menu"), "help": (commands_help, "print a list of available commands in the main menu"), "exit": (lambda: exit(0), "exit the application") }, "service": { "add": (create_service_client, "create a new service client. If it the first time, the new service becomes active"), "use": (switch_service, "switch the active service"), "call": (call, "call the active service method"), "info": (print_service_info, "output services, methods and messages in a service"), "list": (list_initialized_services, "print a list of initialized services"), "help": (commands_help, "print a list of available commands in the services menu"), "back": (lambda: None, "return to the main menu"), "exit": (lambda: exit(0), "exit the application") }, "channel": { "update": (update_channels, "update a list of initialized payment channels"), "list": (list_channels, "print a list of initialized payment channels"), "open": (open_channel, "open a new payment channel"), "add-funds": (add_funds, "add funds to a channel"), "extend-expiration": (extend_expiration, "extend expiration of a channel"), "help": (commands_help, "print a list of available commands in the channels menu"), "back": (lambda: None, "return to the main menu"), "exit": (lambda: exit(0), "exit the application") } } ``` -------------------------------- ### Deposit and Open Channel Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Deposits funds and opens a payment channel in a single operation. ```APIDOC ## Deposit and Open Channel ### Description Combines the functionality of depositing FET tokens into the MPE and opening a payment channel in one atomic operation. ### Method `service_client.deposit_and_open_channel` ### Parameters - `amount` (integer) - Required - The amount of FET tokens in cogs to deposit and allocate to the channel. - `expiration` (integer) - Required - The expiration time of the channel in blocks (TTL). ``` -------------------------------- ### group_init Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/storage_provider/service_metadata.md Initializes a new payment group within the service metadata, prompting for group details. ```APIDOC ## group_init ### Description Initializes a new payment group in the `m` dict. Prompts the user to enter several fields, such as fixed price, endpoints, etc. ### Method Not applicable (SDK method) ### Parameters #### Arguments - **group_name** (str) - Required - The name of the payment group. ### Returns - None ### Raises - Exception: If user enters same endpoints. - ValueError: If user enters non-integer fixed price. ``` -------------------------------- ### Main Application Loop Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/console_app.md The main function manages the console application's execution. It handles user input, calls corresponding functions based on the active commands, and manages menu switching. ```python def main(): """ The function, which is called when the application is started. Manages global variables and calls the appropriate functions. """ global active_commands print(""" Hello, welcome to the Snet SDK console application! To use the application, type the name of the command you want to execute.""") commands_help() print("To print a list of available commands, type 'help'") prefix = ">>> " while True: command = input(prefix).strip() if command in active_commands: active_commands[command][0]() else: print(f"Command '{command}' is not found. Please try again.") continue if command in ["back", "service", "channel"]: if command == "back": command = "main" prefix = ">>> " else: prefix = command + " >>> " active_commands = commands[command] commands_help() if __name__ == "__main__": main() ``` -------------------------------- ### PaymentChannelProvider.open_channel Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/mpe/payment_channel_provider.md Opens a payment channel with the specified amount of FET tokens in cogs and expiration time. It then returns the newly opened channel. ```APIDOC ## open_channel ### Description Opens a payment channel with the specified amount of FET tokens in cogs (taken from MPE) and expiration time. And then returns it. ### Parameters - **account** (Account) - Required - The account object used to send the transaction. - **amount** (int) - Required - The amount of FET tokens in cogs to deposit into the channel. - **expiration** (int) - Required - The expiration time of the payment channel in blocks. - **payment_address** (str) - Required - The address of the payment recipient. - **group_id** (str) - Required - The ID of the payment group. - **payment_channel_state_service_client** (Any) - Required - Stub for interacting with PaymentChannelStateService via gRPC to pass it to PaymentChannel instances. ### Returns - The newly opened payment channel. (PaymentChannel) ``` -------------------------------- ### Create Service Client Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/console_app.md This function creates a service client for a specified service and payment group within an organization. It prompts the user for organization ID, service ID, and payment group name, then uses `snet_sdk.create_service_client`. The created service is added to a list of initialized services and set as the active service if none is currently active. ```python def create_service_client(): org_id = input("Enter organization id: ").strip() service_id = input("Enter service id: ").strip() group_name = input("Enter payment group name: ").strip() service = snet_sdk.create_service_client(org_id=org_id, service_id=service_id, group_name=group_name) initialized_services.append(service) global active_service if active_service is None: active_service = service ``` -------------------------------- ### Active Commands Initialization Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/console_app.md This line initializes the 'active_commands' variable to point to the commands defined for the 'main' menu. This variable is updated when the user navigates between menus. ```python active_commands: dict = commands["main"] # the list of available commands in the active menu ``` -------------------------------- ### MPEContract Deposit and Open Channel Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/mpe/mpe_contract.md Opens a payment channel with the specified amount of FET tokens in cogs, depositing them first into MPE and then into the channel. ```APIDOC ## deposit_and_open_channel ### Description Opens a payment channel with the specified amount of FET tokens in cogs (which are previously deposited on MPE) and expiration time. The account must have sufficient allowance to perform the deposit, otherwise the account first approves the transfer. ### Method deposit_and_open_channel ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - `account` (Account): The account object used to send the transaction. - `payment_address` (str): The address of the payment recipient. - `group_id` (str): The ID of the payment group. - `amount` (int): The amount of FET tokens in cogs first for deposit on MPE, then for deposit on the channel. - `expiration` (int): The expiration time of the payment channel in blocks. ### Request Example None ### Response #### Success Response (200) - The transaction receipt of the transaction. (TxReceipt) #### Response Example None ``` -------------------------------- ### Global Variables for Service Clients and Channels Source: https://github.com/singnet/snet-sdk-python/blob/master/examples/examples_docs/console_app.md These global variables are used to store initialized service clients, the currently active service, and open payment channels within the application. ```python initialized_services = [] # the list of initialized service clients active_service: sdk.service_client.ServiceClient # the currently active service channels = [] # the list of open channels ``` -------------------------------- ### Make Concurrent Prepaid Service Calls Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md After setting up a prepaid service client, make RPC calls as usual. The SDK automatically manages the prepaid call pool internally for these invocations. ```python for i in range(5): response = service_client.call_rpc("add", "Numbers", a=1, b=2) print(f"Concurrent call {i+1} result:", response) ``` -------------------------------- ### Call Service with Trained Model Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md After training, invoke the service using `call_rpc`, specifying the gRPC method, message name, and the trained model's ID. Additional parameters can be passed using keyword arguments. ```python result = service_client.call_rpc(grpc_method_name, grpc_message_name, model_id=model_id, **parameters) ``` -------------------------------- ### open_channel Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/main/service_client.md Opens a payment channel with a specified amount of FET tokens and an expiration time. This is the primary method for initiating a new payment channel. ```APIDOC ## open_channel ### Description Opens a payment channel with the specified amount of FET tokens in cogs and expiration time. ### Method (Not specified, assumed to be a client method call) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - `amount` (int): The amount of FET tokens in cogs to deposit into the channel. - `expiration` (int): The expiration time of the payment channel in blocks. ### Returns - Newly opened payment channel. (PaymentChannel) ``` -------------------------------- ### compile_proto Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/utils/utils.md Compiles Protocol Buffer (protobuf) files into code for a specific target language. ```APIDOC ## Function `compile_proto` ### Description Compiles Protocol Buffer (protobuf) files into code for a specific target language. Generated files as well as .proto files are stored in the `~/.snet` directory. ### Parameters #### Args - `entry_path` (Path): The path to the .proto file. - `codegen_dir` (PurePath): The directory where the compiled code will be generated. - `proto_file` (str, optional): The name of the .proto file to compile. Defaults to `None`. - `target_language` (str, optional): The target language for the compiled code. Defaults to "python". - `add_training` (bool): Whether to include training.proto in the compilation. Defaults to False. ### Returns - True if the compilation is successful, False otherwise. (bool) ### Raises - `Exception`: If the error occurs while performing the function. ``` -------------------------------- ### get_json Source: https://github.com/singnet/snet-sdk-python/blob/master/docs/storage_provider/service_metadata.md Retrieves the entire service metadata as a JSON string. ```APIDOC ## get_json ### Description Returns the JSON representation of the `m` dict. ### Method (Not specified, likely a SDK method call) ### Returns - The JSON representation of the `m` dict. (str) ``` -------------------------------- ### Fetch and Edit Service Metadata Source: https://github.com/singnet/snet-sdk-python/blob/master/README.md Retrieve existing service metadata, modify its description (short and long), and prepare it for an update. Requires the organization ID and service ID to fetch the metadata. ```python from snet.sdk import SnetSDK sdk = SnetSDK() org_id = "" service_id = "" service_metadata = sdk.get_service_metadata(org_id, service_id) service_metadata.change_description( short_description="new_short_description", description="new_description" ) ```