Get an API key

Before you can start using the SDK, you’ll need to obtain your API key from AI21 Studio.

Installation

Install ai21 Python SDK with your favorite package manager.
pip install ai21

Authentication

There are two ways to authenticate with the SDK:

Option 1: Pass the API key directly
from ai21 import AI21Client

client = AI21Client(api_key="your_api_key")
Option 2: Use an environment variable Set the variable in your terminal:
export AI21_API_KEY="your_api_key"
Then in your Python code, you can initialize the client without explicitly passing the key:
client = AI21Client()
For details on how authentication works at the HTTP level, see the API Refrence Autentication.

Example usage

This example demonstrates how to initialize the AI21 Python SDK client and send a simple chat message using the jamba-mini model.
from ai21 import AI21Client
from ai21.models.chat import ChatMessage

client = AI21Client(
    # defaults to os.environ.get('AI21_API_KEY')
    api_key='my_api_key',
)

system = "You're a support engineer in a SaaS company"
messages = [
    ChatMessage(content=system, role="system"),
    ChatMessage(content="Hello, I need help with a signup process.", role="user"),
]

chat_completions = client.chat.completions.create(
    messages=messages,
    model="jamba-mini",
)

Python SDK

For more examples and detailed usage, check out our Python library GitHub repository.