python-agent-core
A minimalist, event-driven agent loop with cooperative preemption and unified backends in Python.
⚡ The Core Value: Why Cooperative Preemption?
Traditional frameworks treat ChatCompletion calls as monolithic black boxes. If a user tries to cancel or override the agent mid-sentence, the runtime is blocked until the generation finishes or the task is crudely killed.
py-agent-core handles preemption at the transport layer. By checking an interrupt flag during token consumption, it severs the network socket instantly when triggered—saving latency, tokens, and allowing immediate cognitive redirection.
THE COOPERATIVE PREEMPTION LOOP
[User App] [PyAgent] [LLM API]
│ │ │
│ ─── agent.run_loop() ──────► │ │
│ │ ─── Stream Request ───────► │
│ │ │
│ ◄── event: text_delta ────── │ ◄── Token Stream ────────── │
│ ◄── event: text_delta ────── │ ◄── Token Stream ────────── │
│ │ │
│ ─── agent.interrupt() ─────► │ │
│ │ ─── stream.close() ────────►X (Socket Closed)
│ ◄── event: interrupted ───── │ │
🔍 How It Compares
| Architectural Dimension | py-agent-core |
Big-Box Frameworks |
|---|---|---|
| 🔄 Control Paradigm | ⚡ Stream of Events (Async Generator) Yields raw events ( text_delta, tool_start, etc.) |
📥 Callback Managers Hides execution behind custom routers |
| 🛑 Stream Preemption | ✅ Surgical Transport-Level Abort Closes socket connection mid-generation instantly |
❌ Thread Kill / No Cancel Must wait for the LLM to finish speaking |
| 🧩 Tool Specifications | ✅ Auto-parsed Typehints & Docstrings Decorate standard Python functions with @tool |
⚠️ Manual Declarations Requires complex Pydantic schemas or JSON |
| 🎯 Model Resilience | ✅ Dynamic Parameter Fallback Gracefully falls back when reasoning vs sampling parameters clash |
❌ SDK Schema Crash Crashes if a parameter is not supported by the model |
| 🌳 Agent Hierarchy | ✅ Nested Worker Trees Instantiate child agents directly inside parent tools |
❌ Complex Graph Configs Requires custom routers and state channels |
| 📦 Footprint & Bloat | ✅ Zero-Dependency Core Minimalist loop code you can read and fit in your head |
❌ Sprawling Class Hierarchy Hundreds of helper wrappers and utilities |
Quickstart (Run 100% Locally)
1. Install
pip install python-agent-core
(For full local development environment setup instructions, refer to the Installation Guide.)
2. Define a Tool
Write standard Python functions. Their signatures, type hints, and docstrings compile into tool schemas automatically.
from py_agent_core import tool
@tool
def calculate_factorial(n: int) -> int:
"""Compute the factorial of n.
Args:
n: The target integer.
"""
return 1 if n <= 1 else n * calculate_factorial(n - 1)
3. Run the Event Loop (Ollama)
Consume the stream as structured events in real time:
import asyncio
from py_agent_core import PyAgent, OllamaBackend
async def main():
# Runs completely offline using a local model (llama3)
backend = OllamaBackend(model="llama3")
agent = PyAgent(backend=backend, tools=[calculate_factorial])
async for event in agent.run_loop("Calculate the factorial of 5"):
if event.type == "text_delta":
print(event.content, end="", flush=True)
elif event.type == "tool_start":
print(f"\n[Tool Started: {event.content}]")
elif event.type == "tool_end":
print(f"\n[Tool Finished: {event.content['result']}]")
if __name__ == "__main__":
asyncio.run(main())
🛠️ Swapping LLM Backends
Switching between provider endpoints requires zero changes to your agent logic:
OpenAI / Azure OpenAI
Configure your target endpoints using the official SDK client objects:
from openai import AsyncOpenAI
from py_agent_core import OpenAIBackend
client = AsyncOpenAI(api_key="sk-...")
backend = OpenAIBackend(client=client, model="gpt-6.1-sol", api_mode="auto")
Modern /v1/responses API & Frontier Models
OpenAIBackend and AzureOpenAIBackend support OpenAI's official /v1/responses endpoint alongside legacy /v1/chat/completions:
- Active Reasoning with Function Tools: Native reasoning models (e.g.,
gpt-6.1-sol,o-series) execute function tools concurrently with active thinking traces via/v1/responses. - Zero Model-Name Guessing: Protocol selection never branches on arbitrary model strings. In
api_mode="auto", requests negotiate endpoint capabilities dynamically:- Optimistically connects to
/v1/responses; gracefully falls back to/v1/chat/completionsif the server returns 404/405 or unsupported endpoint status. - Dynamically promotes to
/v1/responsesif/v1/chat/completionsrejects function tools due to active reasoning conflicts.
- Optimistically connects to
- Explicit Protocol Control: Set
api_mode="responses"to enforce the responses endpoint orapi_mode="chat_completions"for legacy proxies/servers (e.g., vLLM, LiteLLM). - Thinking Trace Mapping: Configured
thinking_level("low","medium","high") maps directly toreasoning={"effort": ...}on/v1/responsesandreasoning_efforton/v1/chat/completions.
Offline / Mock Testing
Simulate streaming completion and tool execution completely offline with zero LLM API dependency:
from py_agent_core import DummyBackend
backend = DummyBackend(lorem_text="hello world", chunk_delay=0.01)
💡 Executable Examples & Demos
We provide a comprehensive set of executable scripts in the examples/ directory. Each example can run completely offline out-of-the-box using the local DummyBackend.
🟢 Core Concepts (Beginner)
- Hello Agent: Bare-minimum streaming and logging run.
- Structured Streaming: Buffering and parsing structured JSON from token streams.
- Search Watchdog: Cooperative preemption via an external watchdog timer/timeout.
- Rhetoric Speaker: Real-time user input preemption mid-monologue.
- Hierarchical Assistant: Running nested sub-agents within tools to construct coordinating agent trees.
🟡 Production Patterns (Advanced)
- Streaming Guardrails: Stream middleware redacting PII and preempting on toxic words.
- Interactive TUI Chat: Full terminal TUI splitting user typing from token streams.
- Self-Healing Coder: Subprocess code execution with iterative error-traceback correction.
- Parallel Agent Swarm: Running multiple independent agents concurrently.
- Advanced Agent Features: Complete showcase of subscriptions, before/after hooks, parallel tool execution, context pruning pipelines, and active steering queues.
Running Tests
Verify the entire test suite including backend formatting correctness, tool execution, and preemption flows:
PYTHONPATH=. pytest
Contributing
We practice AI-first, spec-driven development using the OpenSpec framework. For all non-trivial changes, please refer to our Contributing Guide to set up your environment and author change specifications.
License
py-agent-core is open-source software licensed under the MIT License.
Metadata
Release files for python-agent-core 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| python_agent_core-0.2.1.tar.gz | 46.2 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| python_agent_core-0.2.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 80.6 kB
Release files / python_agent_core-0.2.1.tar.gz
| Download URL | python_agent_core-0.2.1.tar.gz |
|---|---|
| Size | 46.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8fbb5d34bd1b69a6bf50c1f1e3f8686bccf6b17b87f09599f2a2f7e1b6895280
|
|
BLAKE2b-256 checksum How to use checksums |
436acfd634d844710495344c9af4b635c9110d0c1d23b00ede48420f0e0285d2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.
Transparency logRelease files / python_agent_core-0.2.1-py3-none-any.whl
| Download URL | python_agent_core-0.2.1-py3-none-any.whl |
|---|---|
| Size | 34.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
427a3fb51f880a44da35efc0f564e4c26e43269784368ffc5a69714d48d6fd3c
|
|
BLAKE2b-256 checksum How to use checksums |
b8ff11b0d645ee441986121ebc2ddc2079d14c299a969a416cdcf54193e02f8c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.
Transparency log