Give AlbumentationsX a star on GitHub — it powers this leaderboard

Star on GitHub

cerebras-cloud-sdk

The official Python library for the cerebras API

Rank: #3833Downloads: 1,253,960 (30 days)Stars: 117Forks: 18

Description

Cerebras Python API library

<!-- prettier-ignore -->

PyPI version

The Cerebras Python library provides convenient access to the Cerebras REST API from any Python 3.9+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

It is generated with Stainless.

About Cerebras

At Cerebras, we've developed the world's largest and fastest AI processor, the Wafer-Scale Engine-3 (WSE-3). The Cerebras CS-3 system, powered by the WSE-3, represents a new class of AI supercomputer that sets the standard for generative AI training and inference with unparalleled performance and scalability.

With Cerebras as your inference provider, you can:

  • Achieve unprecedented speed for AI inference workloads
  • Build commercially with high throughput
  • Effortlessly scale your AI workloads with our seamless clustering technology

Our CS-3 systems can be quickly and easily clustered to create the largest AI supercomputers in the world, making it simple to place and run the largest models. Leading corporations, research institutions, and governments are already using Cerebras solutions to develop proprietary models and train popular open-source models.

Want to experience the power of Cerebras? Check out our website for more resources and explore options for accessing our technology through the Cerebras Cloud or on-premise deployments!

[!NOTE]
This SDK has a mechanism that sends a few requests to /v1/tcp_warming upon construction to reduce the TTFT. If this behaviour is not desired, set warm_tcp_connection=False in the constructor.

If you are repeatedly reconstructing the SDK instance it will lead to poor performance. It is recommended that you construct the SDK once and reuse the instance if possible.

Documentation

The REST API documentation can be found on inference-docs.cerebras.ai. The full API of this library can be found in api.md.

Installation

pip install cerebras_cloud_sdk

API Key

Get an API Key from cloud.cerebras.ai and add it to your environment variables:

export CEREBRAS_API_KEY="your-api-key-here"

Usage

The full API of this library can be found in api.md.

Chat Completion

<!-- RUN TEST: ChatStandard -->
import os
from cerebras.cloud.sdk import Cerebras

client = Cerebras(
    api_key=os.environ.get("CEREBRAS_API_KEY"),  # This is the default and can be omitted
)

chat_completion = client.chat.completions.create(
    model="llama3.1-8b",
    messages=[
        {
            "role": "user",
            "content": "Why is fast inference important?",
        }
    ],
)

print(chat_completion)

Text Completion

<!-- RUN TEST: TextStandard -->
import os
from cerebras.cloud.sdk import Cerebras

client = Cerebras(
    api_key=os.environ.get("CEREBRAS_API_KEY"),  # This is the default and can be omitted
)

completion = client.completions.create(
    prompt="It was a dark and stormy ",
    max_tokens=100,
    model="llama3.1-8b",
)

print(completion)

While you can provide an api_key keyword argument, we recommend using python-dotenv to add CEREBRAS_API_KEY="My API Key" to your .env file so that your API Key is not stored in source control.

Async usage

Simply import AsyncCerebras instead of Cerebras and use await with each API call:

<!-- RUN TEST: ChatAsync -->
import os
import asyncio
from cerebras.cloud.sdk import AsyncCerebras

client = AsyncCerebras(
    api_key=os.environ.get("CEREBRAS_API_KEY"),  # This is the default and can be omitted
)


async def main() -> None:
    chat_completion = await client.chat.completions.create(
        model="llama3.1-8b",
        messages=[
            {
                "role": "user",
                "content": "Why is fast inference important?",
            }
        ],
    )
    print(chat_completion)


asyncio.run(main())

Functionality between the synchronous and asynchronous clients is otherwise identical.

With aiohttp

By default, the async client uses httpx for HTTP requests. However, for improved concurrency performance you may also use aiohttp as the HTTP backend.

You can enable this by installing aiohttp:

pip install 'cerebras_cloud_sdk[aiohttp]'

Then you can enable it by instantiating the client with http_client=DefaultAioHttpClient():

import os
import asyncio
from cerebras.cloud.sdk import DefaultAioHttpClient
from cerebras.cloud.sdk import AsyncCerebras


async def main() -> None:
    async with AsyncCerebras(
        api_key=os.environ.get("CEREBRAS_API_KEY"),  # This is the default and can be omitted
        http_client=DefaultAioHttpClient(),
    ) as client:
        chat_completion = await client.chat.completions.create(
            model="llama3.1-8b",
            messages=[
                {
                    "role": "user",
                    "content": "Why is fast inference important?",
                }
            ],
        )


asyncio.run(main())

Streaming responses

We provide support for streaming responses using Server Side Events (SSE).

Note that when streaming, usage and time_info will be information will only be included in the final chunk.

Chat Completion

<!-- RUN TEST: ChatStreaming -->
import os
from cerebras.cloud.sdk import Cerebras

client = Cerebras(
    # This is the default and can be omitted
    api_key=os.environ.get("CEREBRAS_API_KEY"),
)

stream = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "Why is fast inference important?",
        }
    ],
    model="llama3.1-8b",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")

The async client uses the exact same interface.

<!-- RUN TEST: ChatAsyncStreaming -->
import os
import asyncio
from cerebras.cloud.sdk import AsyncCerebras

client = AsyncCerebras(
    # This is the default and can be omitted
    api_key=os.environ.get("CEREBRAS_API_KEY"),
)


async def main() -> None:
    stream = await client.chat.completions.create(
        messages=[
            {
                "role": "user",
                "content": "Why is fast inference important?",
            }
        ],
        model="llama3.1-8b",
        stream=True,
    )
    async for chunk in stream:
        print(chunk.choices[0].delta.content or "", end="")


asyncio.run(main())

Text Completion

<!-- RUN TEST: TextStreaming -->
import os
from cerebras.cloud.sdk import Cerebras

client = Cerebras(
    # This is the default and can be omitted
    api_key=os.environ.get("CEREBRAS_API_KEY"),
)

stream = client.completions.create(
    prompt="It was a dark and stormy ",
    max_tokens=100,
    model="llama3.1-8b",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].text or "", end="")

Using types

Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:

  • Serializing back into JSON, model.to_json()
  • Converting to a dictionary, model.to_dict()

Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set python.analysis.typeCheckingMode to basic.

Nested params

Nested parameters are dictionaries, typed using TypedDict, for example:

from cerebras.cloud.sdk import Cerebras

client = Cerebras()

chat_completion = client.chat.completions.create(
    model="model",
    prediction={
        "content": "string",
        "type": "content",
    },
)
print(chat_completion.prediction)

Handling errors

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of cerebras.cloud.sdk.APIConnectionError is raised.

When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of cerebras.cloud.sdk.APIStatusError is raised, containing status_code and response properties.

All errors inherit from cerebras.cloud.sdk.APIError.

<!-- RUN TEST: Error -->
import cerebras.cloud.sdk
from cerebras.cloud.sdk import Cerebras

client = Cerebras()

try:
    client.chat.completions.create(
        model="some-model-that-doesnt-exist",
        messages=[
            {
                "role": "user",
                "content": "This should cause an error!",
            }
        ],
    )
except cerebras.cloud.sdk.APIConnectionError as e:
    print("The server could not be reached")
    print(e.__cause__)  # an underlying Exception, likely raised within httpx.
except cerebras.cloud.sdk.RateLimitError as e:
    print("A 429 status code was received; we should back off a bit.")
except cerebras.cloud.sdk.APIStatusError as e:
    print("Another non-200-range status code was received")
    print(e.status_code)
    print(e.response)

Error codes are as follows:

Status CodeError Type
400BadRequestError
401AuthenticationError
403PermissionDeniedError
404NotFoundError
422UnprocessableEntityError
429RateLimitError
>=500InternalServerError