Skip to main content

Asyncio utilities for racing and hedged requests

Project description

Asynchedging: Async Racing And Hedging

This package provides tiny asyncio utilities for:

  • Race multiple calls, optionally with per-call start delays, and return the first acceptable result, cancelling the rest
  • Hedge a single call by starting backups immediately or after delays, returning the first winner

Install

pip install asynchedging

Demo

Run the included demo (sleep-based simulations, no network required):

uv run python main.py

Example of using asynchedging with OpenAI

import asyncio
from typing import Any, Awaitable, Callable

from openai import AsyncOpenAI
from asynchedging import WinnerInfo, hedge, race


client = AsyncOpenAI()

async def call_openai(prompt: str, model: str) -> Awaitable[Any]:
    return await client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
    )


async def main() -> None:
    # Race two OpenAI models. race(...) can accept a list of (awaitable, delay) pairs
    result, winner_info = await race([
        (call_openai("Why is the sky blue?", model="gpt-4o"), 0.0),  # starts immediately but takes ~0.80s to finish
        (call_openai("Why is the sky blue?", model="gpt-4o-mini"), 0.25),  # starts at 0.25s but takes ~0.65s to finish (likely winner)
    ])
    print(result)  # OpenAI response object
    print(
        f"meta: index={winner_info.index} started={winner_info.started_count} elapsed={winner_info.elapsed_s:.3f}s"
    )

    # Race two OpenAI models without delays, first to finish wins and the rest are cancelled
    result, winner_info = await race([
        call_openai("Why is the sky blue?", model="gpt-4o"),
        call_openai("Why is the sky blue?", model="gpt-4o-mini"),
    ])

    # Hedge one OpenAI call (start backups if slow) — delays are required (can be zero)
    # Each delay will become the start time for the corresponding backup call
    factory = call_openai("Another question", model="gpt-4o-mini")
    result, winner_info = await hedge(factory, delays_s=(0.25, 0.75))


asyncio.run(main())

Notes:

  • Use accept= to validate answers (e.g., non-empty content) and keep waiting if unacceptable
  • Use total_timeout_s= to set a hard cap for the entire race/hedge
  • Pending tasks are cancelled when a winner is chosen
  • race(...) accepts either awaitables or (awaitable, delay) pairs, hedge(...) requires delays_s for replicas (delays can be zero)

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

asynchedging-1.1.1.tar.gz (12.3 kB view details)

Uploaded Source

Built Distribution

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

asynchedging-1.1.1-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file asynchedging-1.1.1.tar.gz.

File metadata

  • Download URL: asynchedging-1.1.1.tar.gz
  • Upload date:
  • Size: 12.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.15 {"installer":{"name":"uv","version":"0.9.15","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for asynchedging-1.1.1.tar.gz
Algorithm Hash digest
SHA256 beb452a77b15aae00f81aef8b231b7d008d692f1f103b24e3f98269f82079642
MD5 ef509f4de3d2bc7a43eac1e965cac9a1
BLAKE2b-256 acc67906a06fbc87df7f82987fcd8a48377c8d5d2257119397afaf967df2d236

See more details on using hashes here.

File details

Details for the file asynchedging-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: asynchedging-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 6.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.15 {"installer":{"name":"uv","version":"0.9.15","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for asynchedging-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 fa0ccac3a8e4693c0547d4bc8fefa8a6f7232686e0fde71692b8aa596b8540ac
MD5 6e6dd711645d4ac77fffd880731c204a
BLAKE2b-256 545bd27cabe3a90659552487cf04b3a38972e1823956611f78243ed99b14378c

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