Cerebras Python SDK

repository·main·Indexed 40 days ago

https://github.com/cerebras/cerebras-cloud-sdk-python

The official Python library for the Cerebras API, providing high-performance access to generative AI inference. Version 1.91.0 supports synchronous and asynchronous clients (via AsyncCerebras), streaming responses using Server Side Events (SSE), and advanced concurrency options via aiohttp. It includes interfaces for chat completions, text completions, and model management.

Tokens
12.3K
Snippets
43
Records
52
Agent score
51%

What's inside Cerebras

  1. Differentiate between `null` and missing fields in API responses

    main

    In API responses, a field that is explicitly null or missing entirely will both appear as None in the SDK. To distinguish between these two cases, use the .model_fields_set attribute on the response object. If the field name is not present in model_fields_set, the key was missing from the JSON; otherwise, the key was present with a null value.

    if response.my_field is None:
      if 'my_field' not in response.model_fields_set:
        print('Got json like {}, without a "my_field" key present at all.'.format(response.model_dump()))
      else:
        print('Got json like {"my_field": null}.')
  2. Enable logging for the Cerebras SDK

    main

    The SDK uses the standard Python logging module. You can control the verbosity of logs by setting the CEREBRAS_LOG environment variable.

    Set CEREBRAS_LOG to info for standard logging or debug for more verbose output.

    $ export CEREBRAS_LOG=info
  3. Manage HTTP resources and client lifecycle

    main

    While the SDK automatically closes connections when the client is garbage collected, it is best practice to manage the lifecycle manually using a context manager or by calling .close() to ensure resources are released promptly.

    from cerebras.cloud.sdk import Cerebras
    
    with Cerebras() as client:
      # make requests here
      ...
    
    # HTTP client is now closed
  4. Configure the CEREBRAS_API_KEY environment variable

    main

    To use the SDK, obtain an API Key from cloud.cerebras.ai and set it as an environment variable named CEREBRAS_API_KEY. The SDK will automatically look for this variable if no api_key is provided to the constructor.

    export CEREBRAS_API_KEY="your-api-key-here"
  5. Enable aiohttp backend for AsyncCerebras

    main

    By default, the async client uses httpx. To use aiohttp for improved concurrency performance, install the extra dependency and pass DefaultAioHttpClient() to the http_client parameter.

    pip install 'cerebras_cloud_sdk[aiohttp]'
    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"),
            http_client=DefaultAioHttpClient(),
        ) as client:
            chat_completion = await client.chat.completions.create(
                messages=[
                    {
                        "role": "user",
                        "content": "Why is fast inference important?",
                    }
                ],
                model="gpt-oss-120b",
            )
    
    asyncio.run(main())
  6. Construct conversation history using the Message type

    main

    The Message type is a union of several specific message request types, allowing you to build a structured conversation history. Each message must have a role.

    Supported Roles and Types

    • system: MessageSystemMessageRequest. Used to set the behavior of the assistant.
    • developer: MessageDeveloperMessageRequest. Functionally similar to system for OpenAI-compatible models.
    • user: MessageUserMessageRequest. The input from the end-user.
    • assistant: MessageAssistantMessageRequest. The model's responses, which can include content, reasoning, or tool_calls.
    • tool: MessageToolMessageRequest. The output from a tool execution, requiring a tool_call_id.

    Message Content

    Content can be a simple str or a complex Iterable of content objects, such as:

    • text: Standard text content.
    • image_url: An object containing a url and optional detail level.
    • image: An object containing raw image data.
    from typing import List
    from cerebras_cloud_sdk.types.chat import Message
    
    messages: List[Message] = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is in this image?"},  # If content is a string
        # Or complex content:
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe this image"},
                {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
            ]
        }
    ]
  7. Inspect Chat Completion usage and token details

    main

    You can monitor token consumption and performance via the usage and time_info fields in a ChatCompletionResponse or ChatChunkResponse.

    Usage Details:

    • prompt_tokens: Total tokens in the input.
    • prompt_tokens_details.cached_tokens: Number of tokens retrieved from cache.
    • completion_tokens: Total tokens in the output.
    • completion_tokens_details.reasoning_tokens: Tokens used specifically for model reasoning.
    • total_tokens: Sum of prompt and completion tokens.

    Time Information (in seconds):

    • prompt_time: Time spent processing the prompt.
    • queue_time: Time spent in the request queue.
    • completion_time: Time spent generating the completion.
    • total_time: Total end-to-end request time.
  8. Understand Chat Completion response structures

    main

    The Cerebras SDK provides two primary response structures for chat completions: one for standard (non-streaming) responses and one for streaming (chunked) responses. Both structures include metadata like id, model, and usage statistics.

    Standard Responses (ChatCompletionResponse)

    Used when stream=False. The response contains a list of choices, where each choice includes a full message object containing the role, content, and any tool_calls.

    Streaming Responses (ChatChunkResponse)

    Used when stream=True. Instead of a full message, the response provides a series of choices containing a delta. This delta object contains incremental updates to the role, content, reasoning, or tool_calls as they are generated.

    Common Metadata

    Both response types provide access to:

    • Usage: Token counts for prompt_tokens, completion_tokens, and total_tokens. Detailed breakdowns are available for reasoning_tokens and cached_tokens.
    • Time Info: Performance metrics in seconds, including prompt_time, queue_time, completion_time, and total_time.
  9. Understand the structure of ModelListResponse

    main

    The ModelListResponse is a union type that represents the response from a model listing operation. Depending on the provider or context, it can take one of three forms:

    1. ModelMetadataList: The standard Cerebras model list format.
    2. OpenRouterModelsResponse: A format compatible with OpenRouter, containing detailed pricing, datacenter info, and OpenRouter-specific metadata.
    3. HuggingFaceModelsResponse: A format compatible with HuggingFace, used for provider comparison and selection, including pricing in USD per million tokens and capability flags.

    When consuming the API, you should handle these different response shapes accordingly.

  10. Configure the HTTP client and proxies

    main

    You can customize the underlying httpx client by passing a DefaultHttpxClient instance to the Cerebras constructor. This allows for proxy configuration and custom transports. You can also apply these configurations to a specific client instance using .with_options().

    import httpx
    from cerebras.cloud.sdk import Cerebras, DefaultHttpxClient
    
    client = Cerebras(
        # Or use the `CEREBRAS_BASE_URL` env var
        base_url="http://my.test.server.example.com:8083",
        http_client=DefaultHttpxClient(
            proxy="http://my.test.proxy.example.com",
            transport=httpx.HTTPTransport(local_address="0.0.0.0"),
        ),
    )
    
    # Per-request customization
    client.with_options(http_client=DefaultHttpxClient(...))
  11. Understand the ModelRetrieveResponse data structures

    main

    The ModelRetrieveResponse is a union type that can return one of several model metadata formats depending on the provider or context. When retrieving model information, you should be prepared to handle one of the following structures:

    1. ModelMetadata: Basic model identification (id, created, object, owned_by).
    2. OpenRouterModel: A format compatible with OpenRouter, including pricing (as strings), datacenters, and openrouter specific metadata.
    3. HuggingFaceModel: A format used by HuggingFace inference providers, including pricing (as floats representing USD per million tokens) and capabilities (e.g., vision, streaming).
    4. PublicModel: A comprehensive OpenAI-compatible schema that includes detailed architecture, capabilities (e.g., function_calling, json_mode), limits (RPM/TPM), and supported_parameters (e.g., temperature, top_p).