Skip to main content

Async agent orchestration for Python

Project description

pygents

Async agent orchestration for Python. Define tools, queue turns, stream results.

Install

pip install pygents

Requires Python 3.12+.

Example

import asyncio
from pygents import Agent, Turn, tool

@tool()
async def greet(name: str) -> str:
    return f"Hello, {name}!"

async def main():
    agent = Agent("greeter", "Greets people", [greet])
    # Use kwargs:
    await agent.put(Turn("greet", kwargs={"name": "World"}))
    # Or positional args:
    await agent.put(Turn("greet", args=["World"]))

    async for turn, value in agent.run():
        print(value)  # "Hello, World!"

asyncio.run(main())

Tools are async functions. Turns say which tool to run and with what args. Agents process a queue of turns and stream results. The loop exits when the queue is empty.

Features

  • Streaming — agents yield (turn, value) as results are produced
  • Inter-agent messaging — agents can send turns to each other
  • Dynamic arguments — callable positional args and kwargs evaluated at runtime
  • Timeouts — per-turn, default 60s
  • Per-tool locking — opt-in serialization for shared state (lock is acquired inside the tool wrapper, so turn-level hooks run outside the tool lock)
  • Fixed kwargs — decorator kwargs (e.g. @tool(permission="admin")) are merged into every invocation; call-time kwargs override
  • Hooks@hook(hook_type, lock=..., **fixed_kwargs) decorator; hooks stored as a list and selected by type; turn, agent, tool, and memory hooks; same fixed_kwargs and lock options as tools
  • Serializationto_dict() / from_dict() for turns and agents

Design decisions

  • Turn identity: Turn instances no longer have a built-in uuid. If you need identifiers, store them yourself in metadata or wrap Turn in a higher-level domain object.

  • Turn arguments: Turn.__init__ takes args before kwargs, and metadata is the final parameter:

    Turn(
        "tool_name",
        args=[...],
        kwargs={...},
        timeout=...,
        start_time=...,
        end_time=...,
        stop_reason=...,
        metadata={...},
    )
    

    This keeps positional arguments explicit while reserving metadata purely for user-level annotations.

  • Agent serialization and current turn: Agent.to_dict() includes a current_turn key when the agent is in the middle of run() (the turn being executed). That turn is already off the queue, so without it a snapshot would lose the in-flight work. from_dict() restores it; the next run() consumes the restored current turn first, then the queue. So you can save agent state at any time and get a faithful snapshot (config, queue, and current turn if any).

  • Tool and hook metadata timing: ToolMetadata and HookMetadata include start_time and end_time (datetime | None). They are set on the metadata instance when the tool or hook runs (start at entry, end in a finally). So the same metadata object is updated each run; dict() includes ISO strings for serialization.

  • Hook protocol: Registered hooks conform to a Hook protocol (like Tool), with metadata (HookMetadata: name, description, and run timing), hook_type, fn, and lock. The decorator sets metadata (from __name__ and __doc__), fn, and lock; HookRegistry.register() sets hook_type. Raw async callables are typed as Callable[..., Awaitable[None]].

  • Hook decorator: @hook(hook_type, lock=False, **fixed_kwargs) mirrors the tool decorator: keyword arguments are merged into every invocation (call-time overrides), and lock=True uses an asyncio lock to serialize hook invocations.

  • Tool lock in tool layer: The tool lock is acquired inside the @tool wrapper, not in the turn. So the lock covers only the tool’s own execution (including its BEFORE_INVOKE / ON_YIELD / AFTER_INVOKE hooks). Turn-level hooks (BEFORE_RUN, AFTER_RUN, ON_TIMEOUT, ON_ERROR) run outside the tool lock; hooks that need serialization use their own lock=True.

  • Memory hooks: Memory has no compact callback. It supports MemoryHook.BEFORE_APPEND and MemoryHook.AFTER_APPEND only. Hooks are stored as list[Hook] (like Agent/Turn), filtered by hook_type when running. BEFORE_APPEND hooks receive (items, result) and can fill result to replace the window before new items are appended. Serialization uses the same by-type-by-name shape as Agent/Turn; from_dict() resolves names from HookRegistry.

Docs

Full documentation: uv run mkdocs serve. MkDocs is an optional dependency—install with pip install -e ".[docs]" (or use uv run as above) so the library itself does not depend on it.

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

pygents-0.3.1.tar.gz (14.5 kB view details)

Uploaded Source

Built Distribution

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

pygents-0.3.1-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file pygents-0.3.1.tar.gz.

File metadata

  • Download URL: pygents-0.3.1.tar.gz
  • Upload date:
  • Size: 14.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for pygents-0.3.1.tar.gz
Algorithm Hash digest
SHA256 2111ea7cb30354a3fb711828acb0e5f667e695ed04dec5a0fbd068ee887a9fb4
MD5 6447746dc8eb43a60cde7525e2e3562f
BLAKE2b-256 f87bf0ba6dde1dd1899595aa5aecc03da6a47ea146db5a9e426686d6f9ba1a1f

See more details on using hashes here.

File details

Details for the file pygents-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: pygents-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for pygents-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5c7736d12a5e07273f20795352593f273090ee461b4dfb190cead58ef96dc908
MD5 42a50be1fe6b502efc579faacb1041cf
BLAKE2b-256 9154a1663aa9d5450d2bfa0bd8dc07d6a9a04a197ef9c0ed217e0fdecfcde654

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