This package provides a simple and comprehensive way to interact with Cloudflare Workers AI from Python.
Install the package using pip:
pip install cloudflare-ai-pythonOr from a local directory:
pip install -e .from cloudflare_ai_python import CloudflareAI
# Replace with your actual values
account_id = "your_account_id"
api_token = "your_api_token"
client = CloudflareAI(account_id, api_token)models = client.list_models()
for model in models['result']:
print(f"Model: {model['name']}, Description: {model.get('description', 'N/A')}")response = client.run_model("@cf/meta/llama-3.1-8b-instruct", "Where did the phrase Hello World come from")
print(response['result']['response'])For backward compatibility, you can still use the old function:
from cloudflare_ai_python import call_cloudflare_ai
response = call_cloudflare_ai(account_id, api_token, "@cf/meta/llama-3.1-8b-instruct", "Hello World")__init__(account_id, api_token): Initialize the client.list_models(): Returns a list of available models with detailed information.run_model(model, prompt, **kwargs): Run a specific model with a prompt and optional parameters.
account_id: Your Cloudflare Account IDapi_token: Your Cloudflare API Tokenmodel: The model identifier (e.g., "@cf/meta/llama-3.1-8b-instruct")prompt: The text prompt to send to the model**kwargs: Additional parameters like max_tokens, temperature, etc.
- Go to the Cloudflare Dashboard
- Select "Use REST API"
- Click "Create a Workers AI API Token"
- Review the prefilled information and select "Create API Token"
- Copy the API Token and Account ID
Important: Ensure your API token has the following permissions:
- Workers AI - Read
- Workers AI - Edit
If you get a 401 Unauthorized error, your token may be invalid or expired. Create a new one following the steps above.
To automatically publish to PyPI when pushing to main branch, you need to configure authentication. Choose one of the following methods:
- Create a PyPI account at https://pypi.org/
- Go to Account Settings → API tokens → Add API token
- Create a token with scope "Entire account (all projects)"
- Copy the token
- In your GitHub repository, go to Settings → Secrets and variables → Actions
- Add a new repository secret named
PYPI_API_TOKENwith the token value
- First, manually publish your package to PyPI once using Method 1 above
- Go to your project on PyPI → Publishing
- Click "Add publisher" → "GitHub"
- Configure with these settings:
- Repository name:
him6794/cloudflare-ai - Workflow name:
publish.yml - Environment name: Leave empty
- Repository name:
- The workflow will then use Trusted Publishing automatically
pip install -e .[dev]
pytestIf you want to test publishing manually before setting up automated publishing:
# Install twine
pip install twine
# Build the package
python -m build
# Upload to PyPI (you'll be prompted for credentials)
twine upload dist/*Or use the provided script:
python publish_manual.py