opengradient 0.2.8__py3-none-any.whl → 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
opengradient/__init__.py CHANGED
@@ -1,16 +1,16 @@
1
1
  from .client import Client
2
2
  from .defaults import *
3
3
  from .types import InferenceMode
4
-
5
- __version__ = "0.2.8"
4
+ from typing import List, Dict
5
+ __version__ = "0.3.1"
6
6
 
7
7
  _client = None
8
8
 
9
- def init(private_key=DEFAULT_PRIVATE_KEY,
9
+ def init(email: str,
10
+ password: str,
11
+ private_key: str,
10
12
  rpc_url=DEFAULT_RPC_URL,
11
- contract_address=DEFAULT_INFERENCE_CONTRACT_ADDRESS,
12
- email=DEFAULT_HUB_EMAIL,
13
- password=DEFAULT_HUB_PASSWORD):
13
+ contract_address=DEFAULT_INFERENCE_CONTRACT_ADDRESS):
14
14
  global _client
15
15
  _client = Client(private_key=private_key, rpc_url=rpc_url, contract_address=contract_address, email=email, password=password)
16
16
 
@@ -19,10 +19,18 @@ def upload(model_path, model_name, version):
19
19
  raise RuntimeError("OpenGradient client not initialized. Call og.init() first.")
20
20
  return _client.upload(model_path, model_name, version)
21
21
 
22
- def create_model(model_name, model_desc):
22
+ def create_model(model_name: str, model_desc: str, model_path: str = None):
23
23
  if _client is None:
24
24
  raise RuntimeError("OpenGradient client not initialized. Call og.init() first.")
25
- return _client.create_model(model_name, model_desc)
25
+
26
+ result = _client.create_model(model_name, model_desc)
27
+
28
+ if model_path:
29
+ version = "0.01"
30
+ upload_result = _client.upload(model_path, model_name, version)
31
+ result["upload"] = upload_result
32
+
33
+ return result
26
34
 
27
35
  def create_version(model_name, notes=None, is_major=False):
28
36
  if _client is None:
@@ -37,4 +45,9 @@ def infer(model_cid, inference_mode, model_input):
37
45
  def login(email: str, password: str):
38
46
  if _client is None:
39
47
  raise RuntimeError("OpenGradient client not initialized. Call og.init() first.")
40
- return _client.login(email, password)
48
+ return _client.login(email, password)
49
+
50
+ def list_files(model_name: str, version: str) -> List[Dict]:
51
+ if _client is None:
52
+ raise RuntimeError("OpenGradient client not initialized. Call og.init() first.")
53
+ return _client.list_files(model_name, version)
@@ -0,0 +1 @@
1
+ [{"anonymous":false,"inputs":[{"components":[{"components":[{"internalType":"string","name":"name","type":"string"},{"components":[{"internalType":"int128","name":"value","type":"int128"},{"internalType":"int128","name":"decimals","type":"int128"}],"internalType":"struct TensorLib.Number[]","name":"values","type":"tuple[]"},{"internalType":"uint32[]","name":"shape","type":"uint32[]"}],"internalType":"struct TensorLib.MultiDimensionalNumberTensor[]","name":"numbers","type":"tuple[]"},{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string[]","name":"values","type":"string[]"}],"internalType":"struct TensorLib.StringTensor[]","name":"strings","type":"tuple[]"},{"internalType":"bool","name":"is_simulation_result","type":"bool"}],"indexed":false,"internalType":"struct ModelOutput","name":"output","type":"tuple"}],"name":"InferenceResult","type":"event"},{"anonymous":false,"inputs":[{"components":[{"internalType":"string","name":"answer","type":"string"}],"indexed":false,"internalType":"struct LlmResponse","name":"response","type":"tuple"}],"name":"LLMResult","type":"event"},{"inputs":[{"internalType":"string","name":"modelId","type":"string"},{"internalType":"enum ModelInferenceMode","name":"inferenceMode","type":"uint8"},{"components":[{"components":[{"internalType":"string","name":"name","type":"string"},{"components":[{"internalType":"int128","name":"value","type":"int128"},{"internalType":"int128","name":"decimals","type":"int128"}],"internalType":"struct TensorLib.Number[]","name":"values","type":"tuple[]"},{"internalType":"uint32[]","name":"shape","type":"uint32[]"}],"internalType":"struct TensorLib.MultiDimensionalNumberTensor[]","name":"numbers","type":"tuple[]"},{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string[]","name":"values","type":"string[]"}],"internalType":"struct TensorLib.StringTensor[]","name":"strings","type":"tuple[]"}],"internalType":"struct ModelInput","name":"modelInput","type":"tuple"}],"name":"run","outputs":[{"components":[{"components":[{"internalType":"string","name":"name","type":"string"},{"components":[{"internalType":"int128","name":"value","type":"int128"},{"internalType":"int128","name":"decimals","type":"int128"}],"internalType":"struct TensorLib.Number[]","name":"values","type":"tuple[]"},{"internalType":"uint32[]","name":"shape","type":"uint32[]"}],"internalType":"struct TensorLib.MultiDimensionalNumberTensor[]","name":"numbers","type":"tuple[]"},{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string[]","name":"values","type":"string[]"}],"internalType":"struct TensorLib.StringTensor[]","name":"strings","type":"tuple[]"},{"internalType":"bool","name":"is_simulation_result","type":"bool"}],"internalType":"struct ModelOutput","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"enum LlmInferenceMode","name":"mode","type":"uint8"},{"internalType":"string","name":"modelCID","type":"string"},{"internalType":"string","name":"prompt","type":"string"},{"internalType":"uint32","name":"max_tokens","type":"uint32"},{"internalType":"string[]","name":"stop_sequence","type":"string[]"},{"internalType":"uint32","name":"temperature","type":"uint32"}],"internalType":"struct LlmInferenceRequest","name":"request","type":"tuple"}],"name":"runLLM","outputs":[{"components":[{"internalType":"string","name":"answer","type":"string"}],"internalType":"struct LlmResponse","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"}]
@@ -0,0 +1,37 @@
1
+ from eth_account import Account
2
+ import secrets
3
+ from collections import namedtuple
4
+ import os
5
+ import hashlib
6
+
7
+ EthAccount = namedtuple('EthAccount', ['address', 'private_key'])
8
+
9
+
10
+ def generate_eth_account() -> EthAccount:
11
+ user_seed = _get_user_random_seed()
12
+ private_key = _generate_secure_private_key(user_seed)
13
+
14
+ # derive account
15
+ account = Account.from_key(private_key)
16
+
17
+ # get the public key (address)
18
+ public_key = account.address
19
+
20
+ return EthAccount(address=public_key, private_key=private_key)
21
+
22
+ def _get_user_random_seed():
23
+ print("Please type a random string of characters (the longer and more random, the better):")
24
+ print("> ", end="") # Add a '>' prompt on a new line
25
+ return input().encode()
26
+
27
+ def _generate_secure_private_key(user_input):
28
+ # Combine multiple sources of entropy
29
+ system_random = secrets.token_bytes(32)
30
+ os_urandom = os.urandom(32)
31
+ timestamp = str(secrets.randbits(256)).encode()
32
+
33
+ # Add user input to the entropy sources
34
+ combined = system_random + os_urandom + timestamp + user_input
35
+
36
+ # Hash the combined entropy
37
+ return hashlib.sha256(combined).hexdigest()
opengradient/cli.py CHANGED
@@ -1,19 +1,30 @@
1
1
  import click
2
- import os
3
2
  import opengradient
4
3
  import json
5
4
  import ast
6
5
  from pathlib import Path
6
+ import logging
7
+ from pprint import pformat
8
+ import webbrowser
9
+ import sys
10
+
7
11
  from .client import Client
8
12
  from .defaults import *
9
- from .types import InferenceMode, ModelInput
13
+ from .types import InferenceMode
14
+ from .account import EthAccount, generate_eth_account
15
+
16
+ OG_CONFIG_FILE = Path.home() / '.opengradient_config.json'
17
+
10
18
 
11
- # Environment variable names
12
- PRIVATE_KEY_ENV = 'OPENGRADIENT_PRIVATE_KEY'
13
- RPC_URL_ENV = 'OPENGRADIENT_RPC_URL'
14
- CONTRACT_ADDRESS_ENV = 'OPENGRADIENT_CONTRACT_ADDRESS'
15
- EMAIL_ENV = 'OPENGRADIENT_EMAIL'
16
- PASSWORD_ENV = 'OPENGRADIENT_PASSWORD'
19
+ def load_og_config():
20
+ if OG_CONFIG_FILE.exists():
21
+ with OG_CONFIG_FILE.open('r') as f:
22
+ return json.load(f)
23
+ return {}
24
+
25
+ def save_og_config(ctx):
26
+ with OG_CONFIG_FILE.open('w') as f:
27
+ json.dump(ctx.obj, f)
17
28
 
18
29
  # Convert string to dictionary click parameter typing
19
30
  class DictParamType(click.ParamType):
@@ -45,117 +56,226 @@ InferenceModes = {
45
56
  "TEE": InferenceMode.TEE,
46
57
  }
47
58
 
48
- # TODO (Kyle): Once we're farther into development, we should remove the defaults for these options
59
+
60
+ def initialize_config(ctx):
61
+ """Interactively initialize OpenGradient config"""
62
+ if ctx.obj: # Check if config data already exists
63
+ click.echo("A config already exists. Please run 'opengradient config clear' first if you want to reinitialize.")
64
+ click.echo("You can view your current config with 'opengradient config show'.")
65
+
66
+ click.echo("Initializing OpenGradient config...")
67
+ click.secho(f"Config will be stored in: {OG_CONFIG_FILE}", fg='cyan')
68
+
69
+ # Check if user has an existing account
70
+ has_account = click.confirm("Do you already have an OpenGradient account?", default=True)
71
+
72
+ if not has_account:
73
+ eth_account = create_account_impl()
74
+ if eth_account is None:
75
+ click.echo("Account creation cancelled. Config initialization aborted.")
76
+ return
77
+ ctx.obj['private_key'] = eth_account.private_key
78
+ else:
79
+ ctx.obj['private_key'] = click.prompt("Enter your OpenGradient private key", type=str)
80
+
81
+ # Make email and password optional
82
+ email = click.prompt("Enter your OpenGradient Hub email address (optional, press Enter to skip)",
83
+ type=str, default='', show_default=False)
84
+ ctx.obj['email'] = email if email else None
85
+ password = click.prompt("Enter your OpenGradient Hub password (optional, press Enter to skip)",
86
+ type=str, hide_input=True, default='', show_default=False)
87
+ ctx.obj['password'] = password if password else None
88
+
89
+ ctx.obj['rpc_url'] = DEFAULT_RPC_URL
90
+ ctx.obj['contract_address'] = DEFAULT_INFERENCE_CONTRACT_ADDRESS
91
+
92
+ save_og_config(ctx)
93
+ click.echo("Config has been saved.")
94
+ click.secho("You can run 'opengradient config show' to see configs.", fg='green')
95
+
96
+
49
97
  @click.group()
50
- @click.option('--private_key',
51
- envvar=PRIVATE_KEY_ENV,
52
- help='Your OpenGradient private key',
53
- default=DEFAULT_PRIVATE_KEY)
54
- @click.option('--rpc_url',
55
- envvar=RPC_URL_ENV,
56
- help='OpenGradient RPC URL address',
57
- default=DEFAULT_RPC_URL)
58
- @click.option('--contract_address',
59
- envvar=CONTRACT_ADDRESS_ENV,
60
- help='OpenGradient inference contract address',
61
- default=DEFAULT_INFERENCE_CONTRACT_ADDRESS)
62
- @click.option('--email',
63
- envvar=EMAIL_ENV,
64
- help='Your OpenGradient Hub email address -- not required for inference',
65
- default=DEFAULT_HUB_EMAIL)
66
- @click.option('--password',
67
- envvar=PASSWORD_ENV,
68
- help='Your OpenGradient Hub password -- not required for inference',
69
- default=DEFAULT_HUB_PASSWORD)
70
98
  @click.pass_context
71
- def cli(ctx, private_key, rpc_url, contract_address, email, password):
72
- """CLI for OpenGradient SDK"""
73
- if not private_key:
74
- click.echo("Please provide a private key via flag or setting environment variable OPENGRADIENT_PRIVATE_KEY")
75
- if not rpc_url:
76
- click.echo("Please provide a RPC URL via flag or setting environment variable OPENGRADIENT_RPC_URL")
77
- if not contract_address:
78
- click.echo("Please provide a contract address via flag or setting environment variable OPENGRADIENT_CONTRACT_ADDRESS")
79
- if not private_key or not rpc_url or not contract_address:
99
+ def cli(ctx):
100
+ """CLI for OpenGradient SDK. Visit https://docs.opengradient.ai/developers/python_sdk/ for more documentation."""
101
+ # Load existing config
102
+ ctx.obj = load_og_config()
103
+
104
+ no_client_commands = ['config', 'create-account', 'version']
105
+
106
+ # Only create client if this is not a config management command
107
+ if ctx.invoked_subcommand in no_client_commands:
108
+ return
109
+
110
+ if all(key in ctx.obj for key in ['private_key', 'rpc_url', 'contract_address']):
111
+ try:
112
+ ctx.obj['client'] = Client(private_key=ctx.obj['private_key'],
113
+ rpc_url=ctx.obj['rpc_url'],
114
+ contract_address=ctx.obj['contract_address'],
115
+ email=ctx.obj.get('email'),
116
+ password=ctx.obj.get('password'))
117
+ except Exception as e:
118
+ click.echo(f"Failed to create OpenGradient client: {str(e)}")
119
+ ctx.exit(1)
120
+ else:
121
+ click.echo("Insufficient information to create client. Some commands may not be available.")
122
+ click.echo("Please run 'opengradient config clear' and/or 'opengradient config init' and to reinitialize your configs.")
80
123
  ctx.exit(1)
124
+
125
+
126
+ @cli.group()
127
+ def config():
128
+ """Manage your OpenGradient configuration (credentials etc)"""
129
+ pass
130
+
131
+
132
+ @config.command()
133
+ @click.pass_context
134
+ def init(ctx):
135
+ """Initialize or reinitialize the OpenGradient config"""
136
+ initialize_config(ctx)
137
+
138
+
139
+ @config.command()
140
+ @click.pass_context
141
+ def show(ctx):
142
+ """Display current config information"""
143
+ click.secho(f"Config file location: {OG_CONFIG_FILE}", fg='cyan')
144
+
145
+ if not ctx.obj:
146
+ click.echo("Config is empty. Run 'opengradient config init' to initialize it.")
81
147
  return
82
148
 
83
- try:
84
- ctx.obj = Client(private_key=private_key,
85
- rpc_url=rpc_url,
86
- contract_address=contract_address,
87
- email=email,
88
- password=password)
89
- except Exception as e:
90
- click.echo(f"Failed to create OpenGradient client: {str(e)}")
149
+ click.echo("Current config:")
150
+ for key, value in ctx.obj.items():
151
+ if key != 'client': # Don't display the client object
152
+ if key == 'password' and value is not None:
153
+ click.echo(f"{key}: {'*' * len(value)}") # Mask the password
154
+ elif value is None:
155
+ click.echo(f"{key}: Not set")
156
+ else:
157
+ click.echo(f"{key}: {value}")
91
158
 
92
- @cli.command()
159
+
160
+ @config.command()
93
161
  @click.pass_context
94
- def client_settings(ctx):
95
- """Display OpenGradient client settings"""
96
- client = ctx.obj
97
- if not client:
98
- click.echo("Client not initialized")
99
- ctx.exit(1)
100
-
101
- click.echo("Settings for OpenGradient client:")
102
- click.echo(f"\tPrivate key ({PRIVATE_KEY_ENV}): {client.private_key}")
103
- click.echo(f"\tRPC URL ({RPC_URL_ENV}): {client.rpc_url}")
104
- click.echo(f"\tContract address ({CONTRACT_ADDRESS_ENV}): {client.contract_address}")
105
- if client.user:
106
- click.echo(f"\tEmail ({EMAIL_ENV}): {client.user["email"]}")
162
+ def clear(ctx):
163
+ """Clear all saved configs"""
164
+ if not ctx.obj:
165
+ click.echo("No configs to clear.")
166
+ return
167
+
168
+ if click.confirm("Are you sure you want to clear all configs? This action cannot be undone.", abort=True):
169
+ ctx.obj.clear()
170
+ save_og_config(ctx)
171
+ click.echo("Configs cleared.")
107
172
  else:
108
- click.echo(f"\tEmail: not set")
173
+ click.echo("Config clear cancelled.")
174
+
109
175
 
110
176
  @cli.command()
111
- @click.argument('model_path', type=Path)
112
- @click.argument('model_id', type=str)
113
- @click.argument('version_id', type=str)
177
+ @click.option('--repo', '-r', '--name', 'repo_name', required=True, help='Name of the new model repository')
178
+ @click.option('--description', '-d', required=True, help='Description of the model')
114
179
  @click.pass_obj
115
- def upload(client, model_path, model_id, version_id):
116
- """Upload a model"""
180
+ def create_model_repo(obj, repo_name: str, description: str):
181
+ """
182
+ Create a new model repository.
183
+
184
+ This command creates a new model repository with the specified name and description.
185
+ The repository name should be unique within your account.
186
+
187
+ Example usage:
188
+
189
+ \b
190
+ opengradient create-model-repo --name "my_new_model" --description "A new model for XYZ task"
191
+ opengradient create-model-repo -n "my_new_model" -d "A new model for XYZ task"
192
+ """
193
+ client: Client = obj['client']
194
+
117
195
  try:
118
- result = client.upload(model_path, model_id, version_id)
119
- click.echo(f"Model uploaded successfully: {result}")
196
+ result = client.create_model(repo_name, description)
197
+ click.echo(f"Model repository created successfully: {result}")
120
198
  except Exception as e:
121
- click.echo(f"Error uploading model: {str(e)}")
199
+ click.echo(f"Error creating model: {str(e)}")
200
+
122
201
 
123
202
  @cli.command()
124
- @click.argument('model_name', type=str)
125
- @click.argument('model_desc', type=str)
203
+ @click.option('--repo', '-r', 'repo_name', required=True, help='Name of the existing model repository')
204
+ @click.option('--notes', '-n', help='Version notes (optional)')
205
+ @click.option('--major', '-m', is_flag=True, default=False, help='Flag to indicate a major version update')
126
206
  @click.pass_obj
127
- def create_model(client, model_name, model_desc):
128
- """Create a new model"""
207
+ def create_version(obj, repo_name: str, notes: str, major: bool):
208
+ """Create a new version in an existing model repository.
209
+
210
+ This command creates a new version for the specified model repository.
211
+ You can optionally provide version notes and indicate if it's a major version update.
212
+
213
+ Example usage:
214
+
215
+ \b
216
+ opengradient create-version --repo my_model_repo --notes "Added new feature X" --major
217
+ opengradient create-version -r my_model_repo -n "Bug fixes"
218
+ """
219
+ client: Client = obj['client']
220
+
129
221
  try:
130
- result = client.create_model(model_name, model_desc)
131
- click.echo(f"Model created successfully: {result}")
222
+ result = client.create_version(repo_name, notes, major)
223
+ click.echo(f"New version created successfully: {result}")
132
224
  except Exception as e:
133
- click.echo(f"Error creating model: {str(e)}")
225
+ click.echo(f"Error creating version: {str(e)}")
226
+
134
227
 
135
228
  @cli.command()
136
- @click.argument('model_id', type=str)
137
- @click.option('--notes', type=str, default=None, help='Version notes')
138
- @click.option('--is-major', default=False, is_flag=True, help='Is this a major version')
229
+ @click.argument('file_path', type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, path_type=Path),
230
+ metavar='FILE_PATH')
231
+ @click.option('--repo', '-r', 'repo_name', required=True, help='Name of the model repository')
232
+ @click.option('--version', '-v', required=True, help='Version of the model (e.g., "0.01")')
139
233
  @click.pass_obj
140
- def create_version(client, model_id, notes, is_major):
141
- """Create a new version of a model"""
234
+ def upload_file(obj, file_path: Path, repo_name: str, version: str):
235
+ """
236
+ Upload a file to an existing model repository and version.
237
+
238
+ FILE_PATH: Path to the file you want to upload (e.g., model.onnx)
239
+
240
+ Example usage:
241
+
242
+ \b
243
+ opengradient upload-file path/to/model.onnx --repo my_model_repo --version 0.01
244
+ opengradient upload-file path/to/model.onnx -r my_model_repo -v 0.01
245
+ """
246
+ client: Client = obj['client']
247
+
142
248
  try:
143
- result = client.create_version(model_id, notes, is_major)
144
- click.echo(f"Version created successfully: {result}")
249
+ result = client.upload(file_path, repo_name, version)
250
+ click.echo(f"File uploaded successfully: {result}")
145
251
  except Exception as e:
146
- click.echo(f"Error creating version: {str(e)}")
252
+ click.echo(f"Error uploading model: {str(e)}")
253
+
147
254
 
148
255
  @cli.command()
149
- @click.argument('model_cid', type=str)
150
- @click.argument('inference_mode', type=click.Choice(InferenceModes.keys()), default="VANILLA")
151
- @click.argument('input_data', type=Dict, required=False)
152
- @click.option('--input_file',
256
+ @click.option('--model', '-m', 'model_cid', required=True, help='CID of the model to run inference on')
257
+ @click.option('--mode', 'inference_mode', type=click.Choice(InferenceModes.keys()), default="VANILLA",
258
+ help='Inference mode (default: VANILLA)')
259
+ @click.option('--input', '-d', 'input_data', type=Dict, help='Input data for inference as a JSON string')
260
+ @click.option('--input-file', '-f',
153
261
  type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, path_type=Path),
154
- help="Optional file input for model inference -- must be JSON")
262
+ help="JSON file containing input data for inference")
155
263
  @click.pass_context
156
- def infer(ctx, model_cid, inference_mode, input_data, input_file):
157
- """Run inference on a model"""
158
- client = ctx.obj
264
+ def infer(ctx, model_cid: str, inference_mode: str, input_data, input_file: Path):
265
+ """
266
+ Run inference on a model.
267
+
268
+ This command runs inference on the specified model using the provided input data.
269
+ You must provide either --input or --input-file, but not both.
270
+
271
+ Example usage:
272
+
273
+ \b
274
+ opengradient infer --model Qm... --mode VANILLA --input '{"key": "value"}'
275
+ opengradient infer -m Qm... -i ZKML -f input_data.json
276
+ """
277
+ client: Client = ctx.obj['client']
278
+
159
279
  try:
160
280
  if not input_data and not input_file:
161
281
  click.echo("Must specify either input_data or input_file")
@@ -175,11 +295,12 @@ def infer(ctx, model_cid, inference_mode, input_data, input_file):
175
295
  model_input = json.load(file)
176
296
 
177
297
  # Parse input data from string to dict
178
- click.echo(f"Running {inference_mode} inference for {model_cid}...")
298
+ click.echo(f"Running {inference_mode} inference for model \"{model_cid}\"\n")
179
299
  tx_hash, model_output = client.infer(model_cid=model_cid, inference_mode=InferenceModes[inference_mode], model_input=model_input)
300
+
180
301
  click.secho("Success!", fg="green")
181
- click.echo(f"\nTransaction Hash: \n{tx_hash}")
182
- click.echo(f"\nInference result: \n{model_output}")
302
+ click.echo(f"Transaction hash: {tx_hash}")
303
+ click.echo(f"Inference result:\n{pformat(model_output, indent=2, width=120)}")
183
304
  except json.JSONDecodeError as e:
184
305
  click.echo(f"Error decoding JSON: {e}", err=True)
185
306
  click.echo(f"Error occurred on line {e.lineno}, column {e.colno}", err=True)
@@ -187,9 +308,83 @@ def infer(ctx, model_cid, inference_mode, input_data, input_file):
187
308
  click.echo(f"Error running inference: {str(e)}")
188
309
 
189
310
 
311
+ @cli.command()
312
+ def create_account():
313
+ """Create a new test account for OpenGradient inference and model management"""
314
+ create_account_impl()
315
+
316
+
317
+ def create_account_impl() -> EthAccount:
318
+ click.echo("\n" + "=" * 50)
319
+ click.echo("OpenGradient Account Creation Wizard".center(50))
320
+ click.echo("=" * 50 + "\n")
321
+
322
+ click.echo("\n" + "-" * 50)
323
+ click.echo("Step 1: Create Account on OpenGradient Hub")
324
+ click.echo("-" * 50)
325
+
326
+ click.echo(f"Please create an account on the OpenGradient Hub")
327
+ webbrowser.open(DEFAULT_HUB_SIGNUP_URL, new=2)
328
+ click.confirm("Have you successfully created your account on the OpenGradient Hub?", abort=True)
329
+
330
+ click.echo("\n" + "-" * 50)
331
+ click.echo("Step 2: Generate Ethereum Account")
332
+ click.echo("-" * 50)
333
+ eth_account = generate_eth_account()
334
+ click.echo(f"Generated OpenGradient chain account with address: {eth_account.address}")
335
+
336
+ click.echo("\n" + "-" * 50)
337
+ click.echo("Step 3: Fund Your Account")
338
+ click.echo("-" * 50)
339
+ click.echo(f"Please fund your account clicking 'Request' on the Faucet website")
340
+ webbrowser.open(DEFAULT_OG_FAUCET_URL + eth_account.address, new=2)
341
+ click.confirm("Have you successfully funded your account using the Faucet?", abort=True)
342
+
343
+ click.echo("\n" + "=" * 50)
344
+ click.echo("Account Creation Complete!".center(50))
345
+ click.echo("=" * 50)
346
+ click.echo("\nYour OpenGradient account has been successfully created and funded.")
347
+ click.secho(f"Address: {eth_account.address}", fg='green')
348
+ click.secho(f"Private Key: {eth_account.private_key}", fg='green')
349
+ click.secho("\nPlease save this information for your records.\n", fg='cyan')
350
+
351
+ return eth_account
352
+
353
+
190
354
  @cli.command()
191
355
  def version():
356
+ """Return version of OpenGradient CLI"""
192
357
  click.echo(f"OpenGradient CLI version: {opengradient.__version__}")
193
358
 
359
+
360
+ @cli.command()
361
+ @click.option('--repo', '-r', 'repo_name', required=True, help='Name of the model repository')
362
+ @click.option('--version', '-v', required=True, help='Version of the model (e.g., "0.01")')
363
+ @click.pass_obj
364
+ def list_files(client: Client, repo_name: str, version: str):
365
+ """
366
+ List files for a specific version of a model repository.
367
+
368
+ This command lists all files associated with the specified model repository and version.
369
+
370
+ Example usage:
371
+
372
+ \b
373
+ opengradient list-files --repo my_model_repo --version 0.01
374
+ opengradient list-files -r my_model_repo -v 0.01
375
+ """
376
+ try:
377
+ files = client.list_files(repo_name, version)
378
+ if files:
379
+ click.echo(f"Files for {repo_name} version {version}:")
380
+ for file in files:
381
+ click.echo(f" - {file['name']} (Size: {file['size']} bytes)")
382
+ else:
383
+ click.echo(f"No files found for {repo_name} version {version}")
384
+ except Exception as e:
385
+ click.echo(f"Error listing files: {str(e)}")
386
+
387
+
194
388
  if __name__ == '__main__':
389
+ logging.getLogger().setLevel(logging.WARN)
195
390
  cli()
opengradient/client.py CHANGED
@@ -11,8 +11,6 @@ from typing import Dict, Tuple, Union, List
11
11
  from web3.exceptions import ContractLogicError
12
12
  import firebase
13
13
 
14
- logging.basicConfig(level=logging.INFO)
15
-
16
14
  class Client:
17
15
  FIREBASE_CONFIG = {
18
16
  "apiKey": "AIzaSyDUVckVtfl-hiteBzPopy1pDD8Uvfncs7w",
@@ -23,7 +21,7 @@ class Client:
23
21
  "databaseURL": ""
24
22
  }
25
23
 
26
- def __init__(self, private_key: str, rpc_url: str, contract_address: str, email: str = "test@test.com", password: str = "Test-123"):
24
+ def __init__(self, private_key: str, rpc_url: str, contract_address: str, email: str, password: str):
27
25
  """
28
26
  Initialize the Client with private key, RPC URL, and contract address.
29
27
 
@@ -34,6 +32,8 @@ class Client:
34
32
  email (str, optional): Email for authentication. Defaults to "test@test.com".
35
33
  password (str, optional): Password for authentication. Defaults to "Test-123".
36
34
  """
35
+ self.email = email
36
+ self.password = password
37
37
  self.private_key = private_key
38
38
  self.rpc_url = rpc_url
39
39
  self.contract_address = contract_address
@@ -55,7 +55,8 @@ class Client:
55
55
  inference_abi = json.load(abi_file)
56
56
  self.abi = inference_abi
57
57
 
58
- self.login(email, password)
58
+ if email is not None:
59
+ self.login(email, password)
59
60
 
60
61
  def _initialize_web3(self):
61
62
  """
@@ -279,7 +280,6 @@ class Client:
279
280
  logging.error(f"Request exception during upload: {str(e)}")
280
281
  if hasattr(e, 'response') and e.response is not None:
281
282
  logging.error(f"Response status code: {e.response.status_code}")
282
- logging.error(f"Response headers: {e.response.headers}")
283
283
  logging.error(f"Response content: {e.response.text[:1000]}...") # Log first 1000 characters
284
284
  raise OpenGradientError(f"Upload failed due to request exception: {str(e)}",
285
285
  status_code=e.response.status_code if hasattr(e, 'response') else None)
@@ -408,4 +408,49 @@ class Client:
408
408
  return self.user
409
409
  except Exception as e:
410
410
  logging.error(f"Authentication failed: {str(e)}")
411
- raise
411
+ raise
412
+
413
+ def list_files(self, model_name: str, version: str) -> List[Dict]:
414
+ """
415
+ List files for a specific version of a model.
416
+
417
+ Args:
418
+ model_name (str): The unique identifier for the model.
419
+ version (str): The version identifier for the model.
420
+
421
+ Returns:
422
+ List[Dict]: A list of dictionaries containing file information.
423
+
424
+ Raises:
425
+ OpenGradientError: If the file listing fails.
426
+ """
427
+ if not self.user:
428
+ raise ValueError("User not authenticated")
429
+
430
+ url = f"https://api.opengradient.ai/api/v0/models/{model_name}/versions/{version}/files"
431
+ headers = {
432
+ 'Authorization': f'Bearer {self.user["idToken"]}'
433
+ }
434
+
435
+ logging.debug(f"List Files URL: {url}")
436
+ logging.debug(f"Headers: {headers}")
437
+
438
+ try:
439
+ response = requests.get(url, headers=headers)
440
+ response.raise_for_status()
441
+
442
+ json_response = response.json()
443
+ logging.info(f"File listing successful. Number of files: {len(json_response)}")
444
+
445
+ return json_response
446
+
447
+ except requests.RequestException as e:
448
+ logging.error(f"File listing failed: {str(e)}")
449
+ if hasattr(e, 'response') and e.response is not None:
450
+ logging.error(f"Response status code: {e.response.status_code}")
451
+ logging.error(f"Response content: {e.response.text[:1000]}...") # Log first 1000 characters
452
+ raise OpenGradientError(f"File listing failed: {str(e)}",
453
+ status_code=e.response.status_code if hasattr(e, 'response') else None)
454
+ except Exception as e:
455
+ logging.error(f"Unexpected error during file listing: {str(e)}", exc_info=True)
456
+ raise OpenGradientError(f"Unexpected error during file listing: {str(e)}")
opengradient/defaults.py CHANGED
@@ -1,7 +1,6 @@
1
1
 
2
2
  # Default variables
3
- DEFAULT_PRIVATE_KEY="cd09980ef6e280afc3900d2d6801f9e9c5d858a5deaeeab74a65643f5ff1a4c1"
4
3
  DEFAULT_RPC_URL="http://18.218.115.248:8545"
5
- DEFAULT_INFERENCE_CONTRACT_ADDRESS="0x75D0266DAb643417e9FFD828A1A31C1E039a966c"
6
- DEFAULT_HUB_EMAIL="test@test.com"
7
- DEFAULT_HUB_PASSWORD="Test-123"
4
+ DEFAULT_OG_FAUCET_URL="http://18.218.115.248:8080/?address="
5
+ DEFAULT_HUB_SIGNUP_URL="https://hub.opengradient.ai/signup"
6
+ DEFAULT_INFERENCE_CONTRACT_ADDRESS="0x350E0A430b2B1563481833a99523Cfd17a530e4e"
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: opengradient
3
- Version: 0.2.8
4
- Summary: A Python SDK for OpenGradient inference services
3
+ Version: 0.3.1
4
+ Summary: Python SDK for OpenGradient decentralized model management & inference services
5
5
  Author-email: OpenGradient <oliver@opengradient.ai>
6
6
  License: MIT License
7
7
 
@@ -136,66 +136,85 @@ Requires-Dist: xattr==1.1.0
136
136
  Requires-Dist: yarl==1.13.1
137
137
 
138
138
  # OpenGradient Python SDK
139
-
140
- Python SDK for OpenGradient inference services.
139
+ Python SDK for the OpenGradient platform provides decentralized model management & inference services. Python SDK allows programmatic access to our model repository and decentralized AI infrastructure.
141
140
 
142
141
  ## Installation
142
+
143
+ To install Python SDK and CLI, run the following command:
143
144
  ```python
144
145
  pip install opengradient
145
146
  ```
146
147
 
147
148
  ## Quick Start
149
+
150
+ To get started, run:
151
+
148
152
  ```python
149
153
  import opengradient as og
150
- og.init(private_key="x", rpc_url="y", contract_address="z")
154
+ og.init(private_key="<private_key>", email="<email>", password="<password>")
151
155
  ```
152
156
 
153
- ### Sign in with Email
157
+ The following commands show how to use Python SDK.
158
+
159
+ ### Create a Model
154
160
  ```python
155
- og.login(email="you@opengradient.ai", password="xyz")
161
+ og.create_model(model_name="<model_name>", model_desc="<model_description>")
156
162
  ```
157
163
 
158
- ### Create a Model
164
+ ### Create a Model (with file upload)
159
165
  ```python
160
- og.create_model(model_name="test-network-model", model_desc="testing upload to sdk")
166
+ og.create_model(model_name="<model_name>", model_desc="<model_description>", model_path="<model_path>")
161
167
  ```
162
168
 
163
169
  ### Create a Version of a Model
164
170
  ```python
165
- og.create_version(model_name="test-network-model", notes="test notes")
171
+ og.create_version(model_name="<model_name>", notes="<model_notes>")
166
172
  ```
167
173
 
168
174
  ### Upload Files to a Model
169
175
  ```python
170
- og.upload(model_path="local_path_to_your_model.onnx", model_name="test-network-model", version="0.01")
176
+ og.upload(model_path="<model_path>", model_name="<model_name>", version="<version>")
171
177
  ```
172
178
 
173
- ### Run Inference
179
+ ### List Files of a Model Version
174
180
  ```python
175
- inference_mode = og.InferenceMode.VANILLA
176
- inference_cid = og.infer(model_cid, model_inputs, inference_mode)
181
+ og.list_files(model_name="<model_name>", version="<version>")
177
182
  ```
178
183
 
184
+ ### Run Inference
179
185
  ```python
180
- og.infer(model_id, inference_mode, model_input)
186
+ inference_mode = og.InferenceMode.VANILLA
187
+ og.infer(model_cid, model_inputs, inference_mode)
181
188
  ```
189
+ - inference mode can be `VANILLA`, `ZKML`, or `TEE`
190
+
182
191
 
183
192
  ## Using the CLI
184
193
 
185
- #### Creating a Model
186
194
  ```bash
187
- opengradient create_model "<model_name>" "<description>"
195
+ export OPENGRADIENT_EMAIL="<email>"
196
+ export OPENGRADIENT_PASSWORD="<password>"
197
+ ```
198
+
199
+ #### Creating a Model Repo
200
+ ```bash
201
+ opengradient create_model_repo "<model_name>" "<description>"
188
202
  ```
189
203
  - creating a model automatically initializes version `v0.01`
190
204
 
191
205
  #### Creating a Version
192
206
  ```bash
193
- opengradient create_model "<model_name>" "<description>"
207
+ opengradient create_model_repo "<model_name>" "<description>"
194
208
  ```
195
209
 
196
210
  #### Upload a File
197
211
  ```bash
198
- opengradient upload "path/to/model.onnx" "<model_name>" "<version>"
212
+ opengradient upload "<model_path>" "<model_name>" "<version>"
213
+ ```
214
+
215
+ #### List Files of a Model Version
216
+ ```bash
217
+ opengradient list_files "<model_name>" "<version>"
199
218
  ```
200
219
 
201
220
  #### CLI infer using string
@@ -207,3 +226,5 @@ opengradient infer QmbUqS93oc4JTLMHwpVxsE39mhNxy6hpf6Py3r9oANr8aZ VANILLA '{"num
207
226
  ```bash
208
227
  opengradient infer QmbUqS93oc4JTLMHwpVxsE39mhNxy6hpf6Py3r9oANr8aZ VANILLA --input_file input.json
209
228
  ```
229
+
230
+ For more information read the OpenGradient [documentation](https://docs.opengradient.ai/).
@@ -0,0 +1,16 @@
1
+ opengradient/__init__.py,sha256=u1JMNG9VIcNppQsrqAClpdXxXCNOKi9ESY5i5ef-cZI,2013
2
+ opengradient/account.py,sha256=s1C4hAtc8vcHObWjwxwlYJA041S6DTbr7-rK6qiWPsQ,1149
3
+ opengradient/cli.py,sha256=YKctHMZhT_Y1fANWDnGo68QpIVLXqz5ifH5kQXIxD8A,14412
4
+ opengradient/client.py,sha256=VwlTSUAGj3kvmDtVxjnEVcnWHoN4D82MmZzHJwHqpuA,20141
5
+ opengradient/defaults.py,sha256=pDfsmPoUzdLG55n-hwh0CMBFxKR2rdNcjqCcwTWc6iw,267
6
+ opengradient/exceptions.py,sha256=v4VmUGTvvtjhCZAhR24Ga42z3q-DzR1Y5zSqP_yn2Xk,3366
7
+ opengradient/types.py,sha256=EoJN-DkQrJ2WTUv8OenlrlWJWFY2jPGTl-T8C_OVjp8,1849
8
+ opengradient/utils.py,sha256=F1Nj-GMNFQFxCtbGgWQq1RP4TSurbpQxJV3yKeEo1b0,6482
9
+ opengradient/abi/inference.abi,sha256=u8FsW0s1YeRjUb9eLS1k_qh_5f_cwOdr0bii-tAdxh0,2683
10
+ opengradient/abi/llm.abi,sha256=zhiPFyBT09EI3QU5DVoKHo7e8T9PFcfIQ3RHDYetm4M,3609
11
+ opengradient-0.3.1.dist-info/LICENSE,sha256=xEcvQ3AxZOtDkrqkys2Mm6Y9diEnaSeQRKvxi-JGnNA,1069
12
+ opengradient-0.3.1.dist-info/METADATA,sha256=FQkG5go46Z-lv-a2r0oMQFfYLA65b96yLfhnFZ2FRB8,7620
13
+ opengradient-0.3.1.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
14
+ opengradient-0.3.1.dist-info/entry_points.txt,sha256=yUKTaJx8RXnybkob0J62wVBiCp_1agVbgw9uzsmaeJc,54
15
+ opengradient-0.3.1.dist-info/top_level.txt,sha256=oC1zimVLa2Yi1LQz8c7x-0IQm92milb5ax8gHBHwDqU,13
16
+ opengradient-0.3.1.dist-info/RECORD,,
@@ -1,14 +0,0 @@
1
- opengradient/__init__.py,sha256=gMNHFVZRrzniZ7RrhUm02bJGFQ5U9RR7o7G2klgPQ8g,1576
2
- opengradient/cli.py,sha256=bM_mROx9xbhtJ2P1uBrdsRSlphkC93zuD5q6mC6E9WA,7430
3
- opengradient/client.py,sha256=9yhMLlqfRcIOk16P-9OOV2QR9UOfpkZYtaFExJQYxKw,18313
4
- opengradient/defaults.py,sha256=FDVOXlceTTU1G13KDf1Gg34UYhOU9VUBemqBVu99G5Y,298
5
- opengradient/exceptions.py,sha256=v4VmUGTvvtjhCZAhR24Ga42z3q-DzR1Y5zSqP_yn2Xk,3366
6
- opengradient/types.py,sha256=EoJN-DkQrJ2WTUv8OenlrlWJWFY2jPGTl-T8C_OVjp8,1849
7
- opengradient/utils.py,sha256=F1Nj-GMNFQFxCtbGgWQq1RP4TSurbpQxJV3yKeEo1b0,6482
8
- opengradient/abi/inference.abi,sha256=u8FsW0s1YeRjUb9eLS1k_qh_5f_cwOdr0bii-tAdxh0,2683
9
- opengradient-0.2.8.dist-info/LICENSE,sha256=xEcvQ3AxZOtDkrqkys2Mm6Y9diEnaSeQRKvxi-JGnNA,1069
10
- opengradient-0.2.8.dist-info/METADATA,sha256=99VuVVLSZlCT9tCx697XV75uwaZUBY39WxfETdpB5YQ,6871
11
- opengradient-0.2.8.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
12
- opengradient-0.2.8.dist-info/entry_points.txt,sha256=yUKTaJx8RXnybkob0J62wVBiCp_1agVbgw9uzsmaeJc,54
13
- opengradient-0.2.8.dist-info/top_level.txt,sha256=oC1zimVLa2Yi1LQz8c7x-0IQm92milb5ax8gHBHwDqU,13
14
- opengradient-0.2.8.dist-info/RECORD,,