Qianfan Python SDK
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
-
qianfan.common.exception.APIErrorCode: ErrorCode=2, ErrorMsg=Authentication failed: The Access Key or Secret Key is invalid.
cause The `QIANFAN_AK` or `QIANFAN_SK` environment variables are missing, incorrect, or not loaded, or `ak`/`sk` were not passed during client initialization.fixVerify that `QIANFAN_AK` and `QIANFAN_SK` environment variables are correctly set and valid, or explicitly pass `ak` and `sk` to the client constructor, e.g., `ChatCompletion(ak='YOUR_AK', sk='YOUR_SK')`. -
ImportError: cannot import name 'ChatCompletion' from 'qianfan'
cause This usually means the `qianfan` package is not installed, or you are running an outdated version that doesn't expose `ChatCompletion` at the top level, or there's a typo in the import.fixEnsure `qianfan` is installed (`pip install qianfan`) and up-to-date (`pip install --upgrade qianfan`). Verify the import statement for typos, it should be `from qianfan import ChatCompletion`. -
qianfan.common.exception.APIErrorCode: ErrorCode=17, ErrorMsg=The provided model name is invalid.
cause The specified model name is either incorrect, misspelled, not supported by your account, or uses incorrect casing (e.g., 'ernie-bot' instead of 'ERNIE-Bot').fixCheck the official Qianfan documentation for the exact, case-sensitive names of available models. Ensure the model is enabled for your account. For versions >=0.4.12.3, pay close attention to model name casing. -
TypeError: do() got an unexpected keyword argument 'stream'
cause You might be calling a method (e.g., for embeddings or non-streaming completion) that does not support the `stream` parameter, or using an older client version that doesn't support streaming for that specific API.fixRemove the `stream=...` parameter if the API endpoint does not support streaming (e.g., embedding generation). For chat/completion APIs that do support streaming, ensure your `qianfan` SDK version is up-to-date and the `stream` parameter is used correctly for that specific model.
Warnings
- gotcha Authentication requires 'QIANFAN_AK' and 'QIANFAN_SK' environment variables. If these are not set, the SDK client must be initialized by passing `ak` and `sk` keyword arguments directly, otherwise API calls will fail.
- breaking As of v0.4.12.3, the SDK removed the forced lowercase conversion of model names. This means you must now use the exact case-sensitive model names as specified in the Qianfan documentation (e.g., 'ERNIE-Bot-4' instead of 'ernie-bot-4').
- gotcha When using streaming (`stream=True`), the `do()` method returns an iterable. You must iterate over the response to receive partial results. Not iterating will result in no output.
- gotcha Some error messages from the Qianfan API might be returned in Chinese, which can be challenging for non-Chinese speakers to debug directly. Refer to the official documentation for common error codes.
Install
-
pip install qianfan
Imports
- ChatCompletion
from qianfan.chat import ChatCompletion
from qianfan import ChatCompletion
- Completion
from qianfan import Completion
- Embedding
from qianfan import Embedding
- QfMessages
from qianfan import Messages
from qianfan import QfMessages
Quickstart
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}")