Skip to content

Add Cloudflare Provider #1627

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions pydantic_ai_slim/pydantic_ai/providers/cloudflare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from __future__ import annotations as _annotations

import os

from httpx import AsyncClient as AsyncHTTPClient

from pydantic_ai.exceptions import UserError
from pydantic_ai.models import cached_async_http_client
from pydantic_ai.providers import Provider

try:
from cloudflare import AsyncCloudflare
except ImportError as _import_error:
raise ImportError(
'Please install the `cloudflare` package to use the Cloudflare provider, '
'you can use the `cloudflare` optional group — `pip install "pydantic-ai-slim[cloudflare]"`'
) from _import_error


class CloudflareProvider(Provider[AsyncCloudflare]):
"""Provider for Cloudflare Workers AI."""

@property
def name(self) -> str:
return 'cloudflare'

@property
def base_url(self) -> str:
return str(self._client.base_url)

@property
def client(self) -> AsyncCloudflare:
return self._client

def __init__(
self,
*,
api_key: str | None = None,
cloudflare_client: AsyncCloudflare | None = None,
http_client: AsyncHTTPClient | None = None,
) -> None:
"""Create a new Cloudflare provider.

Args:
api_key: The API key to use for authentication, if not provided, the `CLOUDFLARE_API_KEY` env var is used.
account_id: Cloudflare account ID, or set via `CLOUDFLARE_ACCOUNT_ID` env var.
cloudflare_client: Pre-existing `AsyncCloudflare` client instance.
http_client: Optional custom `httpx.AsyncClient`.
"""
if cloudflare_client is not None:
assert api_key is None, 'Cannot provide both `cloudflare_client` and `api_key`'
assert http_client is None, 'Cannot provide both `cloudflare_client` and `http_client`'
self._client = cloudflare_client
self.account_id = '<from client>' # replace with real extraction if possible
else:
api_key = api_key or os.getenv('CLOUDFLARE_API_KEY')

if not api_key:
raise UserError(
'Set the `CLOUDFLARE_API_KEY` environment variable or pass it via `CloudflareProvider(api_key=...)`'
)

http_client = http_client or cached_async_http_client(provider='cloudflare')
self._client = AsyncCloudflare(api_key=api_key, http_client=http_client)
1 change: 1 addition & 0 deletions pydantic_ai_slim/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ anthropic = ["anthropic>=0.49.0"]
groq = ["groq>=0.15.0"]
mistral = ["mistralai>=1.2.5"]
bedrock = ["boto3>=1.35.74"]
cloudflare = ["cloudflare>=4.1.0"]
# Tools
duckduckgo = ["duckduckgo-search>=7.0.0"]
tavily = ["tavily-python>=0.5.0"]
Expand Down
41 changes: 41 additions & 0 deletions tests/providers/test_cloudflare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from __future__ import annotations as _annotations

import httpx
import pytest

from pydantic_ai.exceptions import UserError

from ..conftest import TestEnv, try_import

with try_import() as imports_successful:
from cloudflare import AsyncCloudflare

from pydantic_ai.providers.cloudflare import CloudflareProvider


pytestmark = pytest.mark.skipif(not imports_successful(), reason='cloudflare not installed')


def test_cloudflare_provider() -> None:
provider = CloudflareProvider(api_key='api-key')
assert provider.name == 'cloudflare'
assert isinstance(provider.client, AsyncCloudflare)
assert provider.base_url.startswith('https://api.cloudflare.com')


def test_cloudflare_provider_need_api_key(env: TestEnv) -> None:
env.remove('CLOUDFLARE_API_KEY')
with pytest.raises(UserError, match='CLOUDFLARE_API_KEY'):
CloudflareProvider()


def test_cloudflare_provider_pass_http_client() -> None:
http_client = httpx.AsyncClient()
provider = CloudflareProvider(api_key='api-key', http_client=http_client)
assert isinstance(provider.client, AsyncCloudflare)


def test_cloudflare_provider_pass_client() -> None:
cloudflare_client = AsyncCloudflare(api_key='test-api-key')
provider = CloudflareProvider(cloudflare_client=cloudflare_client)
assert provider.client == cloudflare_client
23 changes: 22 additions & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading