Skip to main content

Professional Python SDK for Qwen Web - OpenAI-compatible API client and server

Project description

Qwen Web SDK

Python 3.11+ License: MIT Code style: black

A professional Python SDK that transforms Qwen Web into a programmable interface with OpenAI-compatible API support.

Features

  • Modern Python SDK - Similar developer experience to OpenAI SDK
  • OpenAI-compatible API Server - Drop-in replacement for OpenAI API
  • Multiple Authentication Methods:
    • Manual token from browser
    • Automatic browser token extraction (Chrome, Brave, Edge)
    • Programmatic login with email/password
  • Streaming Support - Real-time streaming for chat completions via SSE
  • Async Support - Full async/await support
  • Conversation Management - Create, list, rename, delete conversations
  • File Upload - Upload documents for context
  • Image Generation - Generate images through chat
  • Model Discovery - Auto-discover available models
  • CLI Tool - Command-line interface for all operations
  • Retry Logic - Automatic retry with exponential backoff
  • Type Hints - Fully typed for IDE support

Installation

# Basic installation
pip install qwen-web-sdk

# With browser extraction support
pip install qwen-web-sdk[browser]

# With Playwright automation support
pip install qwen-web-sdk[playwright]

# With API server
pip install qwen-web-sdk[server]

# All features
pip install qwen-web-sdk[all]

Quick Start

1. Get Your Token

Log in to chat.qwen.ai, open browser DevTools, and run:

localStorage.getItem("token")

2. Basic Usage

from qwen_web import QwenClient

client = QwenClient(token="your-token")

# Simple chat
response = client.chat("What is machine learning?")
print(response.text)

# With specific model
response = client.chat(
    messages=[{"role": "user", "content": "Explain quantum computing"}],
    model="qwen3.7-plus"
)
print(response.text)

3. Streaming

for chunk in client.chat_stream("Write a poem about AI"):
    if not chunk.done:
        print(chunk.text, end="", flush=True)

4. Async Usage

import asyncio
from qwen_web import AsyncQwenClient

async def main():
    async with AsyncQwenClient(token="your-token") as client:
        response = await client.chat("Hello!")
        print(response.text)

asyncio.run(main())

Authentication Methods

Manual Token

from qwen_web import QwenClient
client = QwenClient(token="your-token")

Browser Extraction (Chrome, Brave, Edge)

from qwen_web import QwenClient
client = QwenClient.from_browser()  # Auto-extracts token

Programmatic Login

from qwen_web.auth import login_with_password
token = login_with_password("your@email.com", "your-password")

from qwen_web import QwenClient
client = QwenClient(token=token)

Environment Variable

export QWEN_TOKEN="your-token"
from qwen_web import QwenClient
client = QwenClient()  # Reads from QWEN_TOKEN

OpenAI Compatibility

As Client Library

from qwen_web.openai import OpenAICompatibleClient

client = OpenAICompatibleClient(token="your-token")

response = client.chat.completions.create(
    model="qwen3.7-plus",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)

As API Server

Start the server:

qwen serve
# Or with options
qwen serve --host 0.0.0.0 --port 7080

Use with any OpenAI-compatible tool:

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:7080/v1",
    api_key="sk-local-qwen"
)

response = client.chat.completions.create(
    model="qwen3.7-plus",
    messages=[{"role": "user", "content": "Hello!"}]
)

Compatible Applications

  • OpenClaw - Set provider to "OpenAI Compatible", base URL to http://localhost:7080/v1
  • LiteLLM - Use as a custom provider
  • Open WebUI - Set OpenAI API base URL
  • LibreChat - Configure custom endpoint
  • Continue - Add as custom provider
  • Cline - Use OpenAI-compatible setting
  • Aider - Set --openai-api-base

CLI Commands

# Login
qwen login --token <your-token>
qwen login --browser  # Extract from browser

# User info
qwen whoami
qwen token

# List models
qwen models

# Interactive chat
qwen chat
qwen chat --message "Hello" --model qwen3.7-plus

# Manage conversations
qwen conversations
qwen conversations --delete <chat-id>

# Start API server
qwen serve
qwen serve --host 0.0.0.0 --port 7080

# Diagnostic
qwen doctor

Conversation Management

# List conversations
conversations = client.conversations_list()

# Create conversation
conv = client.conversation_create(title="My Chat")

# Get conversation
chat = client.conversation_get(conv["id"])

# Rename
client.conversation_rename(conv["id"], "New Title")

# Delete
client.conversation_delete(conv["id"])

File Upload

# Upload a file
file_info = client.upload_file("document.pdf")
print(file_info.id, file_info.url)

Advanced Configuration

from qwen_web import QwenClient
from qwen_web.utils import QwenConfig

config = QwenConfig(
    base_url="https://chat.qwen.ai",
    timeout=120.0,
    max_retries=3,
    locale="en-US",
    http2=True,
)

client = QwenClient(token="your-token", config=config)

Model Discovery

# List all models
models = client.models_list()
for model in models:
    print(f"{model.id}: {model.name}")
    print(f"  Context: {model.max_context_length}")
    print(f"  Vision: {model.capabilities.vision}")
    print(f"  Thinking: {model.capabilities.thinking}")

# Get specific model
model = client.models.get("qwen3.7-plus")

Error Handling

from qwen_web import QwenClient
from qwen_web.exceptions import (
    AuthenticationError,
    RateLimitError,
    QuotaExceededError,
    ModelNotFoundError,
)

client = QwenClient(token="your-token")

try:
    response = client.chat("Hello")
except AuthenticationError:
    print("Invalid token")
except RateLimitError as e:
    print(f"Rate limited. Retry after: {e.retry_after}s")
except QuotaExceededError:
    print("Quota exceeded")
except ModelNotFoundError as e:
    print(f"Model not found: {e.model_id}")

Development

# Clone repository
git clone https://github.com/qwen-web-sdk/qwen-web-sdk.git
cd qwen-web-sdk

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
pytest --cov=qwen_web --cov-report=term-missing

# Lint
ruff check qwen_web tests

# Type check
mypy qwen_web

API Endpoints

The API server provides these OpenAI-compatible endpoints:

Method Path Description
GET /v1/models List available models
POST /v1/chat/completions Chat completions (streaming supported)
POST /v1/responses Alias for chat completions
GET /health Health check
GET /version Server version

Architecture

qwen_web/
├── auth/           # Authentication (browser, login, session)
├── client/         # HTTP clients (sync, async)
├── chat/           # Chat completions
├── models/         # Model discovery
├── images/         # Image generation
├── files/          # File upload
├── openai/         # OpenAI compatibility layer
│   ├── compatibility.py  # Format converters
│   ├── client.py         # OpenAI-compatible client
│   └── server.py         # API server
├── types/          # Type definitions
├── utils/          # Utilities (config, headers, SSE parser)
├── exceptions.py   # Custom exceptions
└── cli.py          # Command-line interface

License

MIT License - see LICENSE file.

Disclaimer

This is an unofficial SDK. It is not affiliated with or endorsed by Alibaba Cloud or the Qwen team. Use at your own risk. The API may change without notice.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

qwen_web_sdk-0.1.0.tar.gz (27.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

qwen_web_sdk-0.1.0-py3-none-any.whl (42.0 kB view details)

Uploaded Python 3

File details

Details for the file qwen_web_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: qwen_web_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 27.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for qwen_web_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 821cb952f2d6572c5f1fbc149500d3ade13e116e4f909a0c287484a1a9ac013f
MD5 36d95f739c95fc3c6640c4d82f93a92e
BLAKE2b-256 3e5ad5e1d880e031223a9f7bcbb939dd8568c2189cf65ec4cf0cc2d46d5d4b15

See more details on using hashes here.

File details

Details for the file qwen_web_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: qwen_web_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 42.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for qwen_web_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9f9fc7f7560ba5fa1a1f9b758ded225a28d39eeb1ecaca21ff32f9e536ee3f56
MD5 c27172f01015aa63911ed68ae217be45
BLAKE2b-256 5e84ed8f1cbf2d2c99fc5da36cd1d10184421fdf9ef2524b0158bfd717be3d15

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page