Clarifai Python SDK

12.4.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Clarifai client, load a public image recognition model, and perform a prediction using an image URL. It emphasizes using environment variables for authentication and shows how to process the prediction results.

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.")

view raw JSON →