clarifai 11.6.5__py3-none-any.whl → 11.6.7__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.
clarifai/client/app.py CHANGED
@@ -14,6 +14,8 @@ from clarifai.client.input import Inputs
14
14
  from clarifai.client.lister import Lister
15
15
  from clarifai.client.model import Model
16
16
  from clarifai.client.module import Module
17
+ from clarifai.client.pipeline import Pipeline
18
+ from clarifai.client.pipeline_step import PipelineStep
17
19
  from clarifai.client.search import Search
18
20
  from clarifai.client.workflow import Workflow
19
21
  from clarifai.constants.model import TRAINABLE_MODEL_TYPES
@@ -198,6 +200,151 @@ class App(Lister, BaseClient):
198
200
  continue
199
201
  yield Workflow.from_auth_helper(auth=self.auth_helper, **workflow_info)
200
202
 
203
+ def list_pipelines(
204
+ self,
205
+ filter_by: Dict[str, Any] = {},
206
+ only_in_app: bool = True,
207
+ page_no: int = None,
208
+ per_page: int = None,
209
+ ) -> Generator[dict, None, None]:
210
+ """Lists all the pipelines for the user.
211
+
212
+ Args:
213
+ filter_by (dict): A dictionary of filters to apply to the list of pipelines.
214
+ only_in_app (bool): If True, only return pipelines that are in the app.
215
+ page_no (int): The page number to list.
216
+ per_page (int): The number of items per page.
217
+
218
+ Yields:
219
+ Dict: Dictionaries containing information about the pipelines.
220
+
221
+ Example:
222
+ >>> from clarifai.client.app import App
223
+ >>> app = App(app_id="app_id", user_id="user_id")
224
+ >>> all_pipelines = list(app.list_pipelines())
225
+
226
+ Note:
227
+ Defaults to 16 per page if page_no is specified and per_page is not specified.
228
+ If both page_no and per_page are None, then lists all the resources.
229
+ """
230
+ request_data = dict(user_app_id=self.user_app_id, **filter_by)
231
+ all_pipelines_info = self.list_pages_generator(
232
+ self.STUB.ListPipelines,
233
+ service_pb2.ListPipelinesRequest,
234
+ request_data,
235
+ per_page=per_page,
236
+ page_no=page_no,
237
+ )
238
+
239
+ for pipeline_info in all_pipelines_info:
240
+ pipeline = self._process_pipeline_info(
241
+ pipeline_info, self.auth_helper, self.id, only_in_app
242
+ )
243
+ if pipeline is not None:
244
+ yield pipeline
245
+
246
+ @staticmethod
247
+ def _process_pipeline_info(pipeline_info, auth_helper, app_id=None, only_in_app=False):
248
+ """Helper method to process pipeline info and create Pipeline objects.
249
+
250
+ Args:
251
+ pipeline_info: Raw pipeline info from API
252
+ auth_helper: Auth helper instance
253
+ app_id: App ID to filter by (if only_in_app is True)
254
+ only_in_app: Whether to filter by app_id
255
+
256
+ Returns:
257
+ Pipeline object or None if filtered out
258
+ """
259
+ if only_in_app and app_id:
260
+ if pipeline_info.get('app_id') != app_id:
261
+ return None
262
+
263
+ # Map API field names to constructor parameter names
264
+ pipeline_kwargs = pipeline_info.copy()
265
+ if 'id' in pipeline_kwargs:
266
+ pipeline_kwargs['pipeline_id'] = pipeline_kwargs.pop('id')
267
+ if 'pipeline_version' in pipeline_kwargs:
268
+ pipeline_version = pipeline_kwargs.pop('pipeline_version')
269
+ pipeline_kwargs['pipeline_version_id'] = pipeline_version.get('id', '')
270
+
271
+ return Pipeline.from_auth_helper(auth=auth_helper, **pipeline_kwargs)
272
+
273
+ @staticmethod
274
+ def _process_pipeline_step_info(
275
+ pipeline_step_info, auth_helper, app_id=None, only_in_app=False
276
+ ):
277
+ """Helper method to process pipeline step info and create PipelineStep objects.
278
+
279
+ Args:
280
+ pipeline_step_info: Raw pipeline step info from API
281
+ auth_helper: Auth helper instance
282
+ app_id: App ID to filter by (if only_in_app is True)
283
+ only_in_app: Whether to filter by app_id
284
+
285
+ Returns:
286
+ PipelineStep object or None if filtered out
287
+ """
288
+ if only_in_app and app_id:
289
+ if pipeline_step_info.get('app_id') != app_id:
290
+ return None
291
+
292
+ # Map API field names to constructor parameter names
293
+ step_kwargs = pipeline_step_info.copy()
294
+ if 'pipeline_step' in step_kwargs:
295
+ pipeline_step = step_kwargs.pop('pipeline_step')
296
+ step_kwargs['pipeline_step_id'] = pipeline_step.get('id', '')
297
+
298
+ return PipelineStep.from_auth_helper(auth=auth_helper, **step_kwargs)
299
+
300
+ def list_pipeline_steps(
301
+ self,
302
+ pipeline_id: str = None,
303
+ filter_by: Dict[str, Any] = {},
304
+ only_in_app: bool = True,
305
+ page_no: int = None,
306
+ per_page: int = None,
307
+ ) -> Generator[dict, None, None]:
308
+ """Lists all the pipeline steps for the user.
309
+
310
+ Args:
311
+ pipeline_id (str): If provided, only list pipeline steps from this pipeline.
312
+ filter_by (dict): A dictionary of filters to apply to the list of pipeline steps.
313
+ only_in_app (bool): If True, only return pipeline steps that are in the app.
314
+ page_no (int): The page number to list.
315
+ per_page (int): The number of items per page.
316
+
317
+ Yields:
318
+ Dict: Dictionaries containing information about the pipeline steps.
319
+
320
+ Example:
321
+ >>> from clarifai.client.app import App
322
+ >>> app = App(app_id="app_id", user_id="user_id")
323
+ >>> all_pipeline_steps = list(app.list_pipeline_steps())
324
+
325
+ Note:
326
+ Defaults to 16 per page if page_no is specified and per_page is not specified.
327
+ If both page_no and per_page are None, then lists all the resources.
328
+ """
329
+ request_data = dict(user_app_id=self.user_app_id, **filter_by)
330
+ if pipeline_id:
331
+ request_data['pipeline_id'] = pipeline_id
332
+
333
+ all_pipeline_steps_info = self.list_pages_generator(
334
+ self.STUB.ListPipelineStepVersions,
335
+ service_pb2.ListPipelineStepVersionsRequest,
336
+ request_data,
337
+ per_page=per_page,
338
+ page_no=page_no,
339
+ )
340
+
341
+ for pipeline_step_info in all_pipeline_steps_info:
342
+ pipeline_step = self._process_pipeline_step_info(
343
+ pipeline_step_info, self.auth_helper, self.id, only_in_app
344
+ )
345
+ if pipeline_step is not None:
346
+ yield pipeline_step
347
+
201
348
  def list_modules(
202
349
  self,
203
350
  filter_by: Dict[str, Any] = {},
@@ -76,7 +76,22 @@ class ModelClient:
76
76
  def __getattr__(self, name):
77
77
  if not self._defined:
78
78
  self.fetch()
79
- return self.__getattribute__(name)
79
+ try:
80
+ return self.__getattribute__(name)
81
+ except AttributeError as e:
82
+ # Provide helpful error message with available methods
83
+ available_methods = []
84
+ if self._method_signatures:
85
+ available_methods = list(self._method_signatures.keys())
86
+
87
+ error_msg = f"'{self.__class__.__name__}' object has no attribute '{name}'"
88
+
89
+ if available_methods:
90
+ error_msg += f". Available methods: {available_methods}"
91
+ raise AttributeError(error_msg) from e
92
+ else:
93
+ error_msg += ". This model is a non-pythonic model. Please use the old inference methods i.e. predict_by_url, predict_by_bytes, etc."
94
+ raise Exception(error_msg) from e
80
95
 
81
96
  def _fetch_signatures(self):
82
97
  '''
@@ -148,6 +163,10 @@ class ModelClient:
148
163
  self._define_compatability_functions()
149
164
  return
150
165
  if response.status.code != status_code_pb2.SUCCESS:
166
+ if response.outputs[0].status.description.startswith("cannot identify image file"):
167
+ raise Exception(
168
+ "Failed to fetch method signatures from model and backup method. This model is a non-pythonic model. Please use the old inference methods i.e. predict_by_url, predict_by_bytes, etc."
169
+ )
151
170
  raise Exception(f"Model failed with response {response!r}")
152
171
  self._method_signatures = signatures_from_json(response.outputs[0].data.text.raw)
153
172
 
@@ -94,7 +94,9 @@ class Nodepool(Lister, BaseClient):
94
94
  ), "worker info not found in the config file"
95
95
  assert "scheduling_choice" in deployment, "scheduling_choice not found in the config file"
96
96
  assert "nodepools" in deployment, "nodepools not found in the config file"
97
- deployment['user_id'] = self.user_app_id.user_id
97
+ deployment['user_id'] = (
98
+ deployment['user_id'] if 'user_id' in deployment else self.user_app_id.user_id
99
+ )
98
100
  if "autoscale_config" in deployment:
99
101
  deployment['autoscale_config'] = resources_pb2.AutoscaleConfig(
100
102
  **deployment['autoscale_config']
@@ -103,7 +105,10 @@ class Nodepool(Lister, BaseClient):
103
105
  resources_pb2.Nodepool(
104
106
  id=nodepool['id'],
105
107
  compute_cluster=resources_pb2.ComputeCluster(
106
- id=nodepool['compute_cluster']['id'], user_id=self.user_app_id.user_id
108
+ id=nodepool['compute_cluster']['id'],
109
+ user_id=nodepool['compute_cluster']['user_id']
110
+ if 'user_id' in nodepool['compute_cluster']
111
+ else self.user_app_id.user_id,
107
112
  ),
108
113
  )
109
114
  for nodepool in deployment['nodepools']
@@ -4,6 +4,7 @@ from typing import Dict, List
4
4
 
5
5
  from clarifai_grpc.grpc.api import resources_pb2, service_pb2
6
6
  from clarifai_grpc.grpc.api.status import status_code_pb2
7
+ from google.protobuf import json_format
7
8
 
8
9
  from clarifai.client.base import BaseClient
9
10
  from clarifai.client.lister import Lister
@@ -13,22 +14,6 @@ from clarifai.utils.constants import DEFAULT_BASE
13
14
  from clarifai.utils.logging import logger
14
15
 
15
16
 
16
- def _get_status_name(status_code: int) -> str:
17
- """Get the human-readable name for a status code."""
18
- status_mapping = {
19
- # Job status codes (these are the actual values based on the error message showing 64001)
20
- 64001: "JOB_QUEUED",
21
- 64002: "JOB_RUNNING",
22
- 64003: "JOB_COMPLETED",
23
- 64004: "JOB_FAILED",
24
- 64005: "JOB_UNEXPECTED_ERROR",
25
- # Standard status codes
26
- 10000: "SUCCESS",
27
- 10010: "MIXED_STATUS",
28
- }
29
- return status_mapping.get(status_code, f"UNKNOWN_STATUS_{status_code}")
30
-
31
-
32
17
  class Pipeline(Lister, BaseClient):
33
18
  """Pipeline is a class that provides access to Clarifai API endpoints related to Pipeline information."""
34
19
 
@@ -82,13 +67,17 @@ class Pipeline(Lister, BaseClient):
82
67
 
83
68
  self.pipeline_id = pipeline_id
84
69
  self.pipeline_version_id = pipeline_version_id
85
- self.pipeline_version_run_id = pipeline_version_run_id or str(uuid.uuid4())
70
+ self.pipeline_version_run_id = pipeline_version_run_id or str(uuid.uuid4().hex)
86
71
  self.user_id = user_id
87
72
  self.app_id = app_id
88
73
  self.nodepool_id = nodepool_id
89
74
  self.compute_cluster_id = compute_cluster_id
90
75
  self.log_file = log_file
91
76
 
77
+ # Store all kwargs as attributes for API data
78
+ for key, value in kwargs.items():
79
+ setattr(self, key, value)
80
+
92
81
  BaseClient.__init__(
93
82
  self,
94
83
  user_id=user_id,
@@ -152,9 +141,15 @@ class Pipeline(Lister, BaseClient):
152
141
  )
153
142
 
154
143
  if response.status.code != status_code_pb2.StatusCode.SUCCESS:
155
- raise UserError(
156
- f"Failed to start pipeline run: {response.status.description}. Details: {response.status.details}"
157
- )
144
+ if response.status.code == status_code_pb2.StatusCode.CONN_DOES_NOT_EXIST:
145
+ logger.error(
146
+ f"Pipeline {self.pipeline_id} does not exist, did you call 'clarifai pipeline upload' first? "
147
+ )
148
+ return json_format.MessageToDict(response, preserving_proto_field_name=True)
149
+ else:
150
+ raise UserError(
151
+ f"Failed to start pipeline run: {response.status.description}. Details: {response.status.details}. Code: {status_code_pb2.StatusCode.Name(response.status.code)}."
152
+ )
158
153
 
159
154
  if not response.pipeline_version_runs:
160
155
  raise UserError("No pipeline version run was created")
@@ -218,6 +213,9 @@ class Pipeline(Lister, BaseClient):
218
213
  continue
219
214
 
220
215
  pipeline_run = run_response.pipeline_version_run
216
+ pipeline_run_dict = json_format.MessageToDict(
217
+ pipeline_run, preserving_proto_field_name=True
218
+ )
221
219
 
222
220
  # Display new log entries
223
221
  self._display_new_logs(run_id, seen_logs)
@@ -233,7 +231,7 @@ class Pipeline(Lister, BaseClient):
233
231
  orch_status = pipeline_run.orchestration_status
234
232
  if hasattr(orch_status, 'status') and orch_status.status:
235
233
  status_code = orch_status.status.code
236
- status_name = _get_status_name(status_code)
234
+ status_name = status_code_pb2.StatusCode.Name(status_code)
237
235
  logger.info(f"Pipeline run status: {status_code} ({status_name})")
238
236
 
239
237
  # Display orchestration status details if available
@@ -241,23 +239,29 @@ class Pipeline(Lister, BaseClient):
241
239
  logger.info(f"Orchestration status: {orch_status.description}")
242
240
 
243
241
  # Success codes that allow continuation: JOB_RUNNING, JOB_QUEUED
244
- if status_code in [64001, 64002]: # JOB_QUEUED, JOB_RUNNING
242
+ if status_code in [
243
+ status_code_pb2.JOB_QUEUED,
244
+ status_code_pb2.JOB_RUNNING,
245
+ ]: # JOB_QUEUED, JOB_RUNNING
245
246
  logger.info(f"Pipeline run in progress: {status_code} ({status_name})")
246
247
  # Continue monitoring
247
248
  # Successful terminal state: JOB_COMPLETED
248
- elif status_code == 64003: # JOB_COMPLETED
249
+ elif status_code == status_code_pb2.JOB_COMPLETED: # JOB_COMPLETED
249
250
  logger.info("Pipeline run completed successfully!")
250
- return {"status": "success", "pipeline_version_run": pipeline_run}
251
+ return {"status": "success", "pipeline_version_run": pipeline_run_dict}
251
252
  # Failure terminal states: JOB_UNEXPECTED_ERROR, JOB_FAILED
252
- elif status_code in [64004, 64005]: # JOB_FAILED, JOB_UNEXPECTED_ERROR
253
+ elif status_code in [
254
+ status_code_pb2.JOB_FAILED,
255
+ status_code_pb2.JOB_UNEXPECTED_ERROR,
256
+ ]: # JOB_FAILED, JOB_UNEXPECTED_ERROR
253
257
  logger.error(
254
258
  f"Pipeline run failed with status: {status_code} ({status_name})"
255
259
  )
256
- return {"status": "failed", "pipeline_version_run": pipeline_run}
260
+ return {"status": "failed", "pipeline_version_run": pipeline_run_dict}
257
261
  # Handle legacy SUCCESS status for backward compatibility
258
262
  elif status_code == status_code_pb2.StatusCode.SUCCESS:
259
263
  logger.info("Pipeline run completed successfully!")
260
- return {"status": "success", "pipeline_version_run": pipeline_run}
264
+ return {"status": "success", "pipeline_version_run": pipeline_run_dict}
261
265
  elif status_code != status_code_pb2.StatusCode.MIXED_STATUS:
262
266
  # Log other unexpected statuses but continue monitoring
263
267
  logger.warning(
@@ -0,0 +1,72 @@
1
+ from clarifai.client.base import BaseClient
2
+ from clarifai.client.lister import Lister
3
+ from clarifai.urls.helper import ClarifaiUrlHelper
4
+ from clarifai.utils.constants import DEFAULT_BASE
5
+
6
+
7
+ class PipelineStep(Lister, BaseClient):
8
+ """PipelineStep is a class that provides access to Clarifai API endpoints related to PipelineStep information."""
9
+
10
+ def __init__(
11
+ self,
12
+ url: str = None,
13
+ pipeline_step_id: str = None,
14
+ pipeline_step_version_id: str = None,
15
+ user_id: str = None,
16
+ app_id: str = None,
17
+ pipeline_id: str = None,
18
+ base_url: str = DEFAULT_BASE,
19
+ pat: str = None,
20
+ token: str = None,
21
+ root_certificates_path: str = None,
22
+ **kwargs,
23
+ ):
24
+ """Initializes a PipelineStep object.
25
+
26
+ Args:
27
+ url (str): The URL to initialize the pipeline step object.
28
+ pipeline_step_id (str): The PipelineStep ID for the PipelineStep to interact with.
29
+ pipeline_step_version_id (str): The PipelineStep version ID for the PipelineStep to interact with.
30
+ user_id (str): The User ID for the PipelineStep to interact with.
31
+ app_id (str): The App ID for the PipelineStep to interact with.
32
+ pipeline_id (str): The Pipeline ID for the PipelineStep to interact with.
33
+ base_url (str): Base API url. Default "https://api.clarifai.com"
34
+ pat (str): A personal access token for authentication.
35
+ token (str): A session token for authentication.
36
+ root_certificates_path (str): Path to the SSL root certificates file.
37
+ **kwargs: Additional keyword arguments to be passed to the BaseClient.
38
+ """
39
+ if url:
40
+ user_id, app_id, _, pipeline_step_id, pipeline_step_version_id = (
41
+ ClarifaiUrlHelper.split_clarifai_url(url)
42
+ )
43
+
44
+ # Store all kwargs as attributes for API data
45
+ for key, value in kwargs.items():
46
+ setattr(self, key, value)
47
+
48
+ self.kwargs = {
49
+ "pipeline_step_id": pipeline_step_id,
50
+ "pipeline_step_version_id": pipeline_step_version_id,
51
+ "user_id": user_id,
52
+ "app_id": app_id,
53
+ "pipeline_id": pipeline_id,
54
+ **kwargs,
55
+ }
56
+
57
+ BaseClient.__init__(
58
+ self,
59
+ user_id=user_id,
60
+ app_id=app_id,
61
+ base=base_url,
62
+ pat=pat,
63
+ token=token,
64
+ root_certificates_path=root_certificates_path,
65
+ )
66
+ Lister.__init__(self)
67
+
68
+ self.pipeline_step_id = pipeline_step_id
69
+ self.pipeline_step_version_id = pipeline_step_version_id
70
+ self.pipeline_id = pipeline_id
71
+ self.user_id = user_id
72
+ self.app_id = app_id
clarifai/client/user.py CHANGED
@@ -153,6 +153,80 @@ class User(Lister, BaseClient):
153
153
  for compute_cluster_info in all_compute_clusters_info:
154
154
  yield ComputeCluster.from_auth_helper(self.auth_helper, **compute_cluster_info)
155
155
 
156
+ def list_pipelines(
157
+ self, page_no: int = None, per_page: int = None
158
+ ) -> Generator[dict, None, None]:
159
+ """List all pipelines for the user across all apps
160
+
161
+ Args:
162
+ page_no (int): The page number to list.
163
+ per_page (int): The number of items per page.
164
+
165
+ Yields:
166
+ Dict: Dictionaries containing information about the pipelines.
167
+
168
+ Example:
169
+ >>> from clarifai.client.user import User
170
+ >>> client = User(user_id="user_id")
171
+ >>> all_pipelines = list(client.list_pipelines())
172
+
173
+ Note:
174
+ Defaults to 16 per page if page_no is specified and per_page is not specified.
175
+ If both page_no and per_page are None, then lists all the resources.
176
+ """
177
+ request_data = dict(user_app_id=self.user_app_id)
178
+ all_pipelines_info = self.list_pages_generator(
179
+ self.STUB.ListPipelines,
180
+ service_pb2.ListPipelinesRequest,
181
+ request_data,
182
+ per_page=per_page,
183
+ page_no=page_no,
184
+ )
185
+
186
+ for pipeline_info in all_pipelines_info:
187
+ pipeline = App._process_pipeline_info(
188
+ pipeline_info, self.auth_helper, only_in_app=False
189
+ )
190
+ if pipeline is not None:
191
+ yield pipeline
192
+
193
+ def list_pipeline_steps(
194
+ self, page_no: int = None, per_page: int = None
195
+ ) -> Generator[dict, None, None]:
196
+ """List all pipeline steps for the user across all apps
197
+
198
+ Args:
199
+ page_no (int): The page number to list.
200
+ per_page (int): The number of items per page.
201
+
202
+ Yields:
203
+ Dict: Dictionaries containing information about the pipeline steps.
204
+
205
+ Example:
206
+ >>> from clarifai.client.user import User
207
+ >>> client = User(user_id="user_id")
208
+ >>> all_pipeline_steps = list(client.list_pipeline_steps())
209
+
210
+ Note:
211
+ Defaults to 16 per page if page_no is specified and per_page is not specified.
212
+ If both page_no and per_page are None, then lists all the resources.
213
+ """
214
+ request_data = dict(user_app_id=self.user_app_id)
215
+ all_pipeline_steps_info = self.list_pages_generator(
216
+ self.STUB.ListPipelineStepVersions,
217
+ service_pb2.ListPipelineStepVersionsRequest,
218
+ request_data,
219
+ per_page=per_page,
220
+ page_no=page_no,
221
+ )
222
+
223
+ for pipeline_step_info in all_pipeline_steps_info:
224
+ pipeline_step = App._process_pipeline_step_info(
225
+ pipeline_step_info, self.auth_helper, only_in_app=False
226
+ )
227
+ if pipeline_step is not None:
228
+ yield pipeline_step
229
+
156
230
  def create_app(self, app_id: str, base_workflow: str = 'Empty', **kwargs) -> App:
157
231
  """Creates an app for the user.
158
232
 
@@ -86,7 +86,7 @@ class PipelineBuilder:
86
86
 
87
87
  if not step_directories:
88
88
  logger.info("No pipeline steps to upload (step_directories is empty)")
89
- return True
89
+ return False # treat this as an error.
90
90
 
91
91
  logger.info(f"Uploading {len(step_directories)} pipeline steps...")
92
92
 
@@ -191,25 +191,38 @@ class PipelineBuilder:
191
191
  if "templateRef" in step:
192
192
  template_ref = step["templateRef"]
193
193
  name = template_ref["name"]
194
+ # Extract step name
195
+ parts = name.split('/')
194
196
 
195
197
  # Check if this is a templateRef without version that we uploaded
196
198
  if self.validator.TEMPLATE_REF_WITHOUT_VERSION_PATTERN.match(name):
197
- # Extract step name
198
- parts = name.split('/')
199
199
  step_name = parts[-1]
200
-
201
- # Find the corresponding directory and version
202
- for step_dir, version_id in self.uploaded_step_versions.items():
203
- # The step name should match the directory name or be derivable from it
204
- if step_name == step_dir:
205
- # Update the templateRef to include version
206
- new_name = f"{name}/versions/{version_id}"
207
- template_ref["name"] = new_name
208
- template_ref["template"] = new_name
209
- logger.info(
210
- f"Updated templateRef from {name} to {new_name}"
211
- )
212
- break
200
+ # The step name should match the directory name or be derivable from it
201
+ version_id = self.uploaded_step_versions.get(step_name, None)
202
+ if version_id is not None:
203
+ # Update the templateRef to include version
204
+ new_name = f"{name}/versions/{version_id}"
205
+ template_ref["name"] = new_name
206
+ template_ref["template"] = new_name
207
+ logger.info(f"Updated templateRef from {name} to {new_name}")
208
+ elif self.validator.TEMPLATE_REF_WITH_VERSION_PATTERN.match(name):
209
+ # strip the /versions/{version_id} from the end of name
210
+ # to get the name like above
211
+ orig_name = name
212
+ name = orig_name.rsplit('/versions/', 1)[0]
213
+ step_name = parts[-3] # Get the step name from the path
214
+
215
+ # if it already has a version, make sure it matches the uploaded
216
+ # version
217
+ version_id = self.uploaded_step_versions.get(step_name, None)
218
+ if version_id is not None:
219
+ # Update the templateRef to include version
220
+ new_name = f"{name}/versions/{version_id}"
221
+ template_ref["name"] = new_name
222
+ template_ref["template"] = new_name
223
+ logger.info(
224
+ f"Updated templateRef from {orig_name} to {new_name}"
225
+ )
213
226
 
214
227
  def create_pipeline(self) -> bool:
215
228
  """Create the pipeline using PostPipelines RPC."""
@@ -92,6 +92,7 @@ def serve(
92
92
  runner_id: str = os.environ.get("CLARIFAI_RUNNER_ID", None),
93
93
  base_url: str = os.environ.get("CLARIFAI_API_BASE", "https://api.clarifai.com"),
94
94
  pat: str = os.environ.get("CLARIFAI_PAT", None),
95
+ context=None, # This is the current context object that contains user_id, app_id, model_id, etc.
95
96
  ):
96
97
  builder = ModelBuilder(model_path, download_validation_only=True)
97
98
 
@@ -133,7 +134,35 @@ def serve(
133
134
  pat=pat,
134
135
  num_parallel_polls=num_threads,
135
136
  )
136
- logger.info("Runner started successfully and is waiting for work from the API...\n")
137
+
138
+ if context is None:
139
+ logger.debug("Context is None. Skipping code snippet generation.")
140
+ else:
141
+ method_signatures = builder.get_method_signatures(mocking=False)
142
+ from clarifai.runners.utils import code_script
143
+
144
+ snippet = code_script.generate_client_script(
145
+ method_signatures,
146
+ user_id=context.user_id,
147
+ app_id=context.app_id,
148
+ model_id=context.model_id,
149
+ deployment_id=context.deployment_id,
150
+ base_url=context.api_base,
151
+ )
152
+ logger.info(
153
+ "✅ Your model is running locally and is ready for requests from the API...\n"
154
+ )
155
+ logger.info(
156
+ f"> Code Snippet: To call your model via the API, use this code snippet:\n{snippet}"
157
+ )
158
+ logger.info(
159
+ f"> Playground: To chat with your model, visit: {context.ui}/playground?model={context.model_id}__{context.model_version_id}&user_id={context.user_id}&app_id={context.app_id}\n"
160
+ )
161
+ logger.info(
162
+ f"> API URL: To call your model via the API, use this model URL: {context.ui}/users/{context.user_id}/apps/{context.app_id}/models/{context.model_id}\n"
163
+ )
164
+ logger.info("Press CTRL+C to stop the runner.\n")
165
+
137
166
  runner.start() # start the runner to fetch work from the API.
138
167
 
139
168
 
@@ -112,7 +112,9 @@ print(response)
112
112
  deployment_id = None
113
113
  else:
114
114
  deployment_id = (
115
- 'os.environ["CLARIFAI_DEPLOYMENT_ID"]' if not deployment_id else repr(deployment_id)
115
+ 'os.environ.get("CLARIFAI_DEPLOYMENT_ID", None)'
116
+ if not deployment_id
117
+ else repr(deployment_id)
116
118
  )
117
119
 
118
120
  deployment_line = (
@@ -68,13 +68,13 @@ def kill_process_tree(parent_pid, include_parent: bool = True, skip_pid: int = N
68
68
  logger.warning(f"Failed to kill parent process {parent_pid}: {e}")
69
69
 
70
70
 
71
- def execute_shell_command(
72
- command: str,
73
- ) -> subprocess.Popen:
71
+ def execute_shell_command(command: str, stdout=None, stderr=subprocess.STDOUT) -> subprocess.Popen:
74
72
  """Execute a shell command and return its process handle.
75
73
 
76
74
  Args:
77
75
  command (str): The shell command to execute.
76
+ stdout : Verbose logging control,
77
+ stderr : Verbose error logging control
78
78
 
79
79
  Returns:
80
80
  subprocess.Popen: Process handle for the executed command.
@@ -90,7 +90,7 @@ def execute_shell_command(
90
90
  parts = shlex.split(command)
91
91
 
92
92
  try:
93
- process = subprocess.Popen(parts, text=True, stderr=subprocess.STDOUT)
93
+ process = subprocess.Popen(parts, text=True, stdout=stdout, stderr=stderr)
94
94
 
95
95
  return process
96
96
  except subprocess.SubprocessError as e:
@@ -11,10 +11,10 @@ class PipelineConfigValidator:
11
11
 
12
12
  # Regex patterns for templateRef validation
13
13
  TEMPLATE_REF_WITH_VERSION_PATTERN = re.compile(
14
- r'^users/([^/]+)/apps/([^/]+)/pipeline-steps/([^/]+)/versions/([^/]+)$'
14
+ r'^users/([^/]+)/apps/([^/]+)/pipeline_steps/([^/]+)/versions/([^/]+)$'
15
15
  )
16
16
  TEMPLATE_REF_WITHOUT_VERSION_PATTERN = re.compile(
17
- r'^users/([^/]+)/apps/([^/]+)/pipeline-steps/([^/]+)$'
17
+ r'^users/([^/]+)/apps/([^/]+)/pipeline_steps/([^/]+)$'
18
18
  )
19
19
 
20
20
  @classmethod
@@ -120,8 +120,8 @@ class PipelineConfigValidator:
120
120
  ):
121
121
  raise ValueError(
122
122
  f"templateRef name '{name}' must match either pattern:\n"
123
- f" - users/{{user_id}}/apps/{{app_id}}/pipeline-steps/{{step_id}}\n"
124
- f" - users/{{user_id}}/apps/{{app_id}}/pipeline-steps/{{step_id}}/versions/{{version_id}}"
123
+ f" - users/{{user_id}}/apps/{{app_id}}/pipeline_steps/{{step_id}}\n"
124
+ f" - users/{{user_id}}/apps/{{app_id}}/pipeline_steps/{{step_id}}/versions/{{version_id}}"
125
125
  )
126
126
 
127
127
  @classmethod