Qianfan Python SDK

0.4.12.3 · active · verified Thu Apr 16

The Qianfan Python SDK provides a convenient way to interact with Baidu Wenxin Qianfan Large Model Platform. It supports various AI capabilities including chat completion, text completion, embeddings, text-to-image, and more. The library is actively maintained, with frequent releases across Python, Go, and JavaScript, ensuring up-to-date access to Qianfan services.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform a simple chat completion using the `qianfan` SDK. It initializes a `ChatCompletion` client, constructs messages using `QfMessages`, and sends a request to the ERNIE-Bot-4 model. Ensure your `QIANFAN_AK` and `QIANFAN_SK` environment variables are set for authentication.

import os
from qianfan import ChatCompletion, QfMessages

# Set your Baidu Cloud API Key and Secret Key as environment variables
# or pass them directly to the client constructor.
# os.environ["QIANFAN_AK"] = "YOUR_AK"
# os.environ["QIANFAN_SK"] = "YOUR_SK"

ak = os.environ.get("QIANFAN_AK", "")
sk = os.environ.get("QIANFAN_SK", "")

if not ak or not sk:
    print("Please set QIANFAN_AK and QIANFAN_SK environment variables.")
else:
    chat_comp = ChatCompletion(ak=ak, sk=sk)

    messages = [
        QfMessages(role="user", content="Hello, how are you?")
    ]

    try:
        response = chat_comp.do(
            model="ERNIE-Bot-4", # Or another available chat model like 'ERNIE-Bot-turbo'
            messages=messages,
            stream=False
        )

        if response and response.result:
            print(f"Qianfan response: {response.result}")
        else:
            print("No valid response from Qianfan.")

    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →