Clarifai Python SDK
The Clarifai Python SDK provides a client library for interacting with the Clarifai platform, enabling developers to build and deploy AI models for computer vision, natural language processing, and multimodal applications. The current version is 12.4.0, and it maintains a rapid release cadence with frequent updates.
Common errors
-
ModuleNotFoundError: No module named 'clarifai.rest'
cause Attempting to import the `clarifai.rest` module, which was removed in Clarifai Python SDK v12.fixUpdate your code to use `from clarifai.client import ClarifaiClient` and the new client API. Consult the v12 migration guide for full details. -
clarifai_grpc.grpc.status.Status.StatusCode.UNAUTHENTICATED: Invalid authentication token.
cause The Personal Access Token (PAT) or API Key provided is missing, incorrect, expired, or lacks the necessary permissions.fixVerify that your `CLARIFAI_PAT` environment variable is correctly set, or that you are passing a valid PAT to `ClarifaiClient(pat='YOUR_PAT')`. Ensure the PAT has sufficient scopes for the operations you are performing. -
clarifai_grpc.grpc.status.Status.StatusCode.INVALID_ARGUMENT: Invalid request.
cause The input data or request parameters sent to the Clarifai API are malformed, missing required fields, or do not conform to the expected format (e.g., incorrect input type, bad URL, invalid model ID).fixCarefully review the arguments passed to your client methods, especially when constructing `Input` objects and calling `predict`. Ensure URLs are valid and accessible, and model IDs/versions are correct.
Warnings
- breaking The `clarifai.rest` module, including `ClarifaiApp`, was completely removed in version 12. The primary client is now `clarifai.client.ClarifaiClient`.
- gotcha Authentication token types (PAT vs. API Key) and initialization methods have evolved. Incorrect or missing tokens are a frequent source of errors.
- gotcha Input handling for models requires creating `Input` objects. Directly passing URLs or byte streams to `predict` methods without wrapping them will fail.
Install
-
pip install clarifai
Imports
- ClarifaiClient
from clarifai.client import ClarifaiClient
- Input
from clarifai.client.input import Input
- ClarifaiApp (deprecated)
from clarifai.rest import ClarifaiApp
from clarifai.client import ClarifaiClient
Quickstart
import os
from clarifai.client import ClarifaiClient
from clarifai.client.input import Input
# Initialize the Clarifai client with your Personal Access Token (PAT).
# It's highly recommended to set CLARIFAI_PAT as an environment variable.
# Alternatively, you can pass it directly: ClarifaiClient(pat="YOUR_PAT_HERE")
clarifai_pat = os.environ.get('CLARIFAI_PAT', 'YOUR_CLARIFAI_PAT_HERE')
if clarifai_pat == 'YOUR_CLARIFAI_PAT_HERE':
print("WARNING: CLARIFAI_PAT environment variable not set. Using placeholder.")
print("Please replace 'YOUR_CLARIFAI_PAT_HERE' or set the environment variable.")
client = ClarifaiClient(pat=clarifai_pat)
# Example: Predict with a public image recognition model
model_id = "general-image-recognition"
# model_version_id = "aa7f35c01e0642fda5ff3a5a3bcce187" # Optional, uses default if not specified
image_url = "https://samples.clarifai.com/wedding.jpg"
# Create an input object for prediction
input_obj = Input(url=image_url)
print(f"Predicting with model '{model_id}' using image from {image_url}...")
try:
# Get the model and make a prediction
model_prediction = client.get_model(model_id).predict(inputs=[input_obj])
# Access and print the prediction results
if model_prediction.outputs:
for concept in model_prediction.outputs[0].data.concepts:
print(f" {concept.name}: {concept.value:.2f}")
else:
print("No outputs found in the prediction.")
print(model_prediction) # Print full response for debugging if no outputs
except Exception as e:
print(f"An error occurred during prediction: {e}")
if "Invalid authentication token" in str(e):
print("Please check your CLARIFAI_PAT environment variable or provided PAT.")
elif "Invalid request" in str(e):
print("Please check your model ID, version ID, or input format.")