polyflux 0.0.1a0
An elegant, agentic-first, fully typed and configurable Python client that provides a seamless interface for any communication protocol (HTTP, WebSocket, gRPC, GraphQL, SSE, etc), with built-in auth and plugin hooks.
Requires Python: >=3.12
Keywords: agentic, async, client, graphql, grpc, http, protocol, typed, websocket

# Polyflux

[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)

<div align="center">
  <img src="assets/logo.svg" alt="Polyflux Logo" width="133" height="133">
  <br><br>
</div>

Polyflux is a modern evolution of unified network interfaces, engineered for autonomous systems. It provides a
protocol-agnostic communication layer that enables agentic entities to interact seamlessly with networked services.

Inspired by libwww (the first universal network API from CERN's WWW project) and libcurl, Polyflux
advances this vision by allowing AI agents to independently interact with and utilize networked resources without human
guidance or protocol-specific programming.

## Features

- **Protocol-agnostic interfaces** - Unified API across HTTP, WebSocket, gRPC, GraphQL, and more
- **First-class typing support** - Complete typing with Protocol interfaces and runtime checking
- **Elegant composability** - Mix and match capabilities through Protocol composition
- **Agent-ready interfaces** - Designed for LLM function calling and tool integration
- **Modern Python** - Built for Python 3.12+ with zero backward compatibility concerns
- **Schema discovery** - Dynamically map API structures, even for services without formal schemas
- **Function calling interfaces** - Clean abstractions for LLM agents to interact with networked services

## Installation

```bash
# Install the core package
uv pip install polyflux'[core]'

# Install specific protocol implementations
uv pip install polyflux'[http]'      # HTTP client with authentication and retry support
uv pip install polyflux'[websocket]' # WebSocket client with streaming and pub/sub
uv pip install polyflux'[all]'       # Install all available protocols
```

## Quick Start

### HTTP Example

```python
from polyflux.http import HTTPClient, HTTPRequest

# Create a client with typed configurations
client = HTTPClient(
    base_url="https://api.example.com",
    headers={"Authorization": "Bearer token"}
)

# Send a request with strongly typed PDUs
request = HTTPRequest(
    method="GET",
    params={"limit": 10}
)

response = await client.aexchange("/users", request)

# Process the response
if response:
    users = response.parse()  # Automatically parses JSON
    print(f"Status: {response.status_code}")
    print(f"Users: {users}")
```

### WebSocket Example

```python
from polyflux.websocket import WebSocketClient, WebSocketMessage

# Create a WebSocket client
client = WebSocketClient(uri="wss://api.example.com/ws")

# Connect and send messages
await client.aconnect()

# Send a message
message = WebSocketMessage(
    data={"action": "subscribe", "channel": "updates"},
    message_type="text"
)
await client.asend("control", message)

# Exchange pattern with correlation
request = WebSocketMessage(data={"command": "get_status"})
response = await client.aexchange("status", request)
print(f"Correlated response: {response.data}")

# Stream data
async for chunk in client.astream("data", WebSocketMessage(data={"start": True})):
    print(f"Stream chunk: {chunk.data}")
```

### Logging Example

```python
from polyflux.logging import PolyfluxLogger

# Zero-overhead structured logging
logger = PolyfluxLogger(lazy_init=True, async_emit=True)

# Integrate with any client
client = HTTPClient(base_url="https://api.example.com")
client.with_logger(logger)  # Now all operations are logged

# Direct logging with context
logger.log("INFO", "Processing request", user_id=123, action="fetch")
await logger.alog("ERROR", "Operation failed", error=str(e), retry_count=3)

# Graceful shutdown
logger.shutdown()
```

## Agent Interface Example (Coming Soon)

```python
from polyflux.tools.discovery import explore_arbitrary_url, build_api_map
from polyflux.tools.execution import execute_operation
from polyflux.tools.conversion import convert_data_format

# Agent autonomously discovers and maps an unknown API
api_map = build_api_map("https://api.example.com")

# Agent uses discovered operations
user_data = execute_operation(
    service_url="https://api.example.com",
    operation="get_users",
    parameters={"limit": 10},
)

# Agent converts between formats automatically
xml_data = convert_data_format(
    data=user_data["data"],
    source_format="json",
    target_format="xml"
)
```

## Project Structure

Polyflux is organized as a collection of packages:

- `polyflux-core`: Core interfaces and protocols
- `polyflux-http`: HTTP client implementation with authentication and retry support
- `polyflux-websocket`: WebSocket client implementation with streaming, pub/sub, and portal patterns
- `polyflux-logging`: Zero-overhead structured logging with async emission
- `polyflux-grpc`: gRPC client implementation (coming soon)
- `polyflux-graphql`: GraphQL client implementation (coming soon)
- `polyflux-sse`: Server-Sent Events client implementation (coming soon)
- `polyflux-tools`: LLM function calling and agent tools (coming soon)
- `polyflux-server`: Server implementations (coming soon)

## Examples

### Running the Examples

```bash
# Run main examples showing both HTTP and WebSocket clients
uv run python src/polyflux/main.py

# Run comprehensive HTTP examples
uv run python src/polyflux/examples_http.py

# Run WebSocket examples (requires a WebSocket server)
uv run python src/polyflux/examples_websocket.py
```

All examples demonstrate:

- Protocol-agnostic interfaces
- Request/response patterns
- Streaming and async operations
- Authentication and configuration
- Error handling and retry logic

## Architecture Documentation

The `architecture_outlines` directory contains detailed documentation on the architecture and design of Polyflux:

- `core/`: Core Protocol interfaces and umbrella protocols
- `server/`: Server implementation approaches and network exposure capabilities
- `tools/`: Function calling, agent communication, and server management tools

## Development

Polyflux uses `uv` EXCLUSIVELY for ALL Python operations and `hatch` for build/environment management.

```bash
# Clone the repository
git clone https://github.com/polyflux/polyflux.git
cd polyflux

# Create a virtual environment
uv venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install in development mode
uv pip install -e .
uv pip install .[dev]

# Or use dependency management commands
uv add --dev ruff mypy pytest
uv lock  # Create/update lockfile
uv sync  # Sync environment with lockfile

# Run quality checks
uv run ruff check --fix .
uv run ruff format .
uv run mypy --no-incremental --no-error-summary .
uv run pytest .

# Build packages
uv build

# Working with workspaces
uv add --package polyflux-core dependency-name
uv sync --package polyflux-core
uv run --package polyflux-core pytest

# Run tools without installing
uvx ruff check .  # Equivalent to: uv tool run ruff check .
```