Skip to main content

Friendli Python SDK

Friendli Logo

Supercharge Generative AI Serving with Friendli 🚀

Token Setup

When using Friendli Python SDK, you need to provide a Friendli Token for authentication and authorization purposes. A Friendli Token serves as an alternative method of authorization to signing in with an email and a password. You can generate a new Friendli Token through the Friendli Suite, at your "Personal settings" page by following the steps below.

  1. Go to the Friendli Suite and sign in with your account.
  2. Click the profile icon at the top-right corner of the page.
  3. Click "Personal settings" menu.
  4. Go to the "Tokens" tab on the navigation bar.
  5. Create a new Friendli Token by clicking the "Create token" button.
  6. Copy the token and save it in a safe place. You will not be able to see this token again once the page is refreshed.

Table of Contents

SDK Installation

The SDK can be installed with uv, pip, or poetry package managers.

uv

uv is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities.

uv add friendli

PIP

PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.

pip install friendli

Poetry

Poetry is a modern tool that simplifies dependency management and package publishing by using a single pyproject.toml file to handle project metadata and dependencies.

poetry add friendli

Shell and script usage with uv

You can use this SDK in a Python shell with uv and the uvx command that comes with it like so:

uvx --from friendli python

It's also possible to write a standalone Python script without needing to set up a whole project like so:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "friendli",
# ]
# ///


from friendli import SyncFriendli

sdk = SyncFriendli(
    # SDK arguments
)

# Rest of script here...

Once that is saved to a file, you can run it with uv run script.py where script.py can be replaced with the actual file name.

SDK Example Usage

Chat completions

Generate a model response from a list of messages comprising a conversation. Compatible with the OpenAI Chat Completions API, with support for streaming, tool calls, and structured outputs.

# Synchronous Example

import os

from friendli import SyncFriendli

with SyncFriendli(
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.serverless.chat.complete(
        model="zai-org/GLM-5.3",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": "Hello!",
            },
        ],
    )

    # Handle response
    print(res)

The same SDK client can also be used to make asynchronous requests by importing asyncio.

# Asynchronous Example
import asyncio
import os

from friendli import AsyncFriendli


async def main():
    async with AsyncFriendli(
        token=os.getenv("FRIENDLI_TOKEN", ""),
    ) as friendli:
        res = await friendli.serverless.chat.complete(
            model="zai-org/GLM-5.3",
            messages=[
                {
                    "role": "system",
                    "content": "You are a helpful assistant.",
                },
                {
                    "role": "user",
                    "content": "Hello!",
                },
            ],
        )

        # Handle response
        print(res)


asyncio.run(main())

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
token http HTTP Bearer FRIENDLI_TOKEN

To authenticate with the API the token parameter must be set when initializing the SDK client instance. For example:

import os

from friendli import SyncFriendli

with SyncFriendli(
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.serverless.chat.complete(
        model="zai-org/GLM-5.3",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": "Hello!",
            },
        ],
    )

    # Handle response
    print(res)

Available Resources and Operations

Available methods

Container.Audio

Container.Chat

Container.Classification

Container.Completions

Container.Image

Container.Messages

Container.Responses

Container.Token

Cost

Dedicated.Audio

Dedicated.Chat

Dedicated.ChatRender

Dedicated.Classification

Dedicated.Completions

Dedicated.Embeddings

Dedicated.Endpoint

Dedicated.Image

Dedicated.Messages

Dedicated.Responses

Dedicated.Token

Serverless.Audio

Serverless.Chat

Serverless.ChatRender

Serverless.Completions

Serverless.Messages

Serverless.Model

Serverless.Responses

Serverless.Token

Usage

  • get_usage - Get usage details for the team.

Server-sent event streaming

Server-sent events are used to stream content from certain operations. These operations will expose the stream as Generator that can be consumed using a simple for loop. The loop will terminate when the server no longer has any events to send and closes the underlying connection.

The stream is also a Context Manager and can be used with the with statement and will close the underlying connection when the context is exited.

import os

from friendli import SyncFriendli

with SyncFriendli(
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.serverless.chat.stream(
        model="zai-org/GLM-5.3",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": "Hello!",
            },
        ],
        stream=True,
    )

    with res as event_stream:
        for event in event_stream:
            # handle event
            print(event, flush=True)

File uploads

Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.

import os

from friendli import SyncFriendli

with SyncFriendli(
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.serverless.audio.transcribe(
        model="openai/whisper-large-v3",
        file={
            "file_name": "example.file",
            "content": open("example.file", "rb"),
        },
    )

    # Handle response
    print(res)

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:

import os

from friendli import SyncFriendli
from friendli.utils import BackoffStrategy, RetryConfig

with SyncFriendli(
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.serverless.chat.complete(
        model="zai-org/GLM-5.3",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": "Hello!",
            },
        ],
        retries=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
    )

    # Handle response
    print(res)

If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:

import os

from friendli import SyncFriendli
from friendli.utils import BackoffStrategy, RetryConfig

with SyncFriendli(
    retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.serverless.chat.complete(
        model="zai-org/GLM-5.3",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": "Hello!",
            },
        ],
    )

    # Handle response
    print(res)

Error Handling

FriendliCoreError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
err.message str Error message
err.status_code int HTTP response status code eg 404
err.headers httpx.Headers HTTP response headers
err.body str HTTP body. Can be empty string if no body is returned.
err.raw_response httpx.Response Raw HTTP response
err.data Optional. Some errors may contain structured data. See Error Classes.

Example

import os
from typing import Literal

import friendli
from friendli import SyncFriendli, models

with SyncFriendli(
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = None
    try:
        res = friendli.serverless.messages.messages(
            messages=[
                {
                    "role": "user",
                    "content": "Hello, summarize what you can do in one sentence.",
                },
            ],
            model="zai-org/GLM-5.3",
            additional_properties={},
        )

        # Handle response
        print(res)

    except models.FriendliCoreError as e:
        # The base class for HTTP error responses
        print(e.message)
        print(e.status_code)
        print(e.body)
        print(e.headers)
        print(e.raw_response)

        # Depending on the method different errors may be thrown
        if isinstance(e, models.MessagesErrorResponse):
            print(e.data.type)  # Literal["error"]
            print(e.data.error)  # friendli.MessagesErrorObject
            print(e.data.request_id)  # OptionalNullable[str]

Error Classes

Primary error:

Less common errors (7)

Network errors:

Inherit from FriendliCoreError:

  • MessagesErrorResponse: Unprocessable Entity. Status code 422. Applicable to 6 of 60 methods.*
  • HTTPValidationError: Validation Error. Status code 422. Applicable to 1 of 60 methods.*
  • ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the cause attribute.

* Check the method documentation to see if the error is applicable.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:

import os

from friendli import SyncFriendli

with SyncFriendli(
    server_url="https://api.friendli.ai",
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.serverless.chat.complete(
        model="zai-org/GLM-5.3",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": "Hello!",
            },
        ],
    )

    # Handle response
    print(res)

Override Server URL Per-Operation

The server URL can also be overridden on a per-operation basis, provided a server list was specified for the operation. For example:

import os

from friendli import SyncFriendli

with SyncFriendli(
    token=os.getenv("FRIENDLI_TOKEN", ""),
) as friendli:
    res = friendli.container.chat.complete(
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": "Hello!",
            },
        ],
        model="(adapter-route)",
        server_url="http://localhost:8000",
    )

    # Handle response
    print(res)

Custom HTTP Client

The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.

For example, you could specify a header for every request that this sdk makes as follows:

import httpx

from friendli import SyncFriendli

http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = SyncFriendli(client=http_client)

or you could wrap the client with your own custom logic:

from typing import Any, Optional, Union

import httpx

from friendli import AsyncFriendli
from friendli.httpclient import AsyncHttpClient


class CustomClient(AsyncHttpClient):
    client: AsyncHttpClient

    def __init__(self, client: AsyncHttpClient):
        self.client = client

    async def send(
        self,
        request: httpx.Request,
        *,
        stream: bool = False,
        auth: Union[
            httpx._types.AuthTypes, httpx._client.UseClientDefault, None
        ] = httpx.USE_CLIENT_DEFAULT,
        follow_redirects: Union[
            bool, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
    ) -> httpx.Response:
        request.headers["Client-Level-Header"] = "added by client"

        return await self.client.send(
            request, stream=stream, auth=auth, follow_redirects=follow_redirects
        )

    def build_request(
        self,
        method: str,
        url: httpx._types.URLTypes,
        *,
        content: Optional[httpx._types.RequestContent] = None,
        data: Optional[httpx._types.RequestData] = None,
        files: Optional[httpx._types.RequestFiles] = None,
        json: Optional[Any] = None,
        params: Optional[httpx._types.QueryParamTypes] = None,
        headers: Optional[httpx._types.HeaderTypes] = None,
        cookies: Optional[httpx._types.CookieTypes] = None,
        timeout: Union[
            httpx._types.TimeoutTypes, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
        extensions: Optional[httpx._types.RequestExtensions] = None,
    ) -> httpx.Request:
        return self.client.build_request(
            method,
            url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            cookies=cookies,
            timeout=timeout,
            extensions=extensions,
        )


s = AsyncFriendli(async_client=CustomClient(httpx.AsyncClient()))

httpx2 (Pydantic's httpx fork)

httpx2 is Pydantic's maintained fork of httpx. To run this SDK on httpx2, call alias_httpx() at your program's entry point, before importing the SDK, so every import httpx — including the ones inside the SDK — resolves to httpx2:

import httpx2

httpx2.alias_httpx()


from friendli import SyncFriendli

s = SyncFriendli()

An SDK can also be generated against httpx2 directly, so it depends on the fork instead of httpx, by setting python.httpClientLibrary: httpx2 in gen.yaml.

Resource Management

The SyncFriendli class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.

from friendli import SyncFriendli, AsyncFriendli
import os
def main():
    with SyncFriendli(
        token=os.getenv("FRIENDLI_TOKEN", ""),
    ) as friendli:
        # Rest of application here...


# Or when using async:
async def amain():
    async with AsyncFriendli(
        token=os.getenv("FRIENDLI_TOKEN", ""),
    ) as friendli:
        # Rest of application here...

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass your own logger class directly into your SDK.

import logging

from friendli import SyncFriendli

logging.basicConfig(level=logging.DEBUG)
s = SyncFriendli(debug_logger=logging.getLogger("friendli"))

You can also enable a default debug logger by setting an environment variable FRIENDLI_DEBUG to true.

IDE Support

PyCharm

Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.

Metadata

Release files for friendli 0.15.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for friendli 0.15.4
File Size Uploaded Provenance
friendli-0.15.4.tar.gz 311.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for friendli 0.15.4
File Interpreter ABI Platform
friendli-0.15.4-py3-none-any.whl Python 3 none any Details

Total release size: 947.0 kB

Release files / friendli-0.15.4.tar.gz

Download URL friendli-0.15.4.tar.gz
Size 311.1 kB
Tags Source
SHA-256 checksum
How to use checksums
43397d696fc43258869b628e77128f6548a6030459e68238078dd14cc2b12be7
BLAKE2b-256 checksum
How to use checksums
2fa35eb20177c7511d53c6804c56cd80d3112b256ae16ac947405a11242f772c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / friendli-0.15.4-py3-none-any.whl

Download URL friendli-0.15.4-py3-none-any.whl
Size 635.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7a3608072ff1f77f217cfa02dc982cbfd7b5416f21aeb0b09a5e48e3649ed660
BLAKE2b-256 checksum
How to use checksums
c3c7168fe3ab6df272dafafc4efe5ab48502aa9983fd03faa1d2cc79f484afc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for friendli 0.15.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.15.4 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page