Skip to main content

agentu

Run AI agents in Python with subprocess tool isolation, self-correction, and zero-SDK provider routing.

pip install agentu

Quick start

from agentu import Agent, tool

@tool(readonly=True)
def search_products(query: str, max_price: int = 1500) -> list[dict]:
    """Search catalog for matching products."""
    return [
        {"name": "ThinkPad X1 Carbon", "price": 1399},
        {"name": "MacBook Air M4", "price": 1199},
    ]

agent = Agent("sales", model="gemini-2.5-flash").with_tools([search_products])

# Synchronous script one-liner
res = agent.run("Find me laptops under $1500")
print(res.text)

# Or async inside your app:
# res = await agent.infer("Find me laptops under $1500")
# raw = await agent.call("search_products", {"query": "laptop"})

run() executes synchronously. infer() runs the async multi-turn agent loop and returns an InferResult. call() invokes a tool directly.

Zero-config providers

# Picks up GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENAI_API_KEY, GROQ_API_KEY, DEEPSEEK_API_KEY
gemini = Agent("analyst", model="gemini-2.5-flash")
claude = Agent("reviewer", model="claude-sonnet-4-20250514")
openai = Agent("coder", model="openai/gpt-4o")
groq   = Agent("fast", model="groq/llama-3.3-70b-versatile")
local  = Agent("offline", model="ollama/qwen3:latest")

All four protocol drivers (GeminiDriver, ClaudeDriver, OpenAIDriver, OllamaDriver) speak native REST/SSE over pooled aiohttp sessions — zero vendor SDK bloat.

Sandboxed tool execution

agent = Agent("ops", model="gpt-4o").with_sandbox(
    read_tools=[search_products, read_logs],
    write_tools=[save_report, send_email],
    timeout=10,
    max_memory_mb=256,
    allow_network=False,
)
  • read_tools run as READONLY; write_tools run as WRITE; DANGEROUS tools stay blocked unless enabled via .with_permissions(allow_dangerous=True)
  • Every sandboxed tool runs in an isolated subprocess — hung tools are killed at timeout without crashing your process
  • Defer large tool catalogs with .with_tools([core_tool], defer=[...100_extra_tools]) so the agent discovers them on demand via search_tools

Code Mode

agent = Agent("bot", model="claude-sonnet-4-20250514", codemode=True).with_tools([
    search_products, check_inventory, save_report
])
res = await agent.infer("Find in-stock laptops and save a summary")

Instead of N sequential JSON tool round-trips, the LLM writes typed Python against tools.* in a restricted sandbox (math, json, re allowed; os, sys, subprocess, socket blocked) and self-corrects on runtime errors.

Structured outputs + tools

from pydantic import BaseModel, Field
from agentu import Agent, InferResult

class DealSummary(BaseModel):
    top_pick: str
    price: int = Field(le=1500)
    rationale: str

res: InferResult[DealSummary] = await agent.infer(
    "Pick the best laptop deal",
    output_type=DealSummary,
)
print(res.data.top_pick, res.data.price)

Works standalone or combined with tools — agentu executes any needed tools first, validates the final output against your Pydantic model, and retries automatically with field-level error feedback if validation fails.

Guardrails & hooks

from agentu import Agent, PII, ContentFilter, HookAction, HookResult

async def block_prod_deletes(tool_name, params, ctx):
    if tool_name == "drop_table":
        return HookResult(action=HookAction.DENY, reason="Production drops blocked")
    return HookResult(action=HookAction.ALLOW)

agent = (
    Agent("support", model="gpt-4o")
    .with_guardrails(output_guardrails=[PII(), ContentFilter()], max_corrections=2)
    .with_hooks(pre_tool=block_prod_deletes)
)

Guardrail violations feed back into the model for automatic self-correction up to max_corrections attempts. Hooks intercept pre_tool, post_tool, and on_stop with ALLOW, DENY, or MODIFY.

Multimodal & image generation

res = await agent.infer(
    "Cross-check the keynote demo against the architecture PDF:",
    media=[
        {"type": "video", "url": "https://youtu.be/7Z5Vy9JBANs", "processing": "agentic"},
        "./latency_chart.png",
        "./whitepaper.pdf",
    ],
)

image = await agent.generate_image(
    "Minimalist isometric server rack on warm paper",
    model="gpt-image-2",
    output_path="renders/rack.png",
)

When targeting text-only models (e.g. deepseek-chat or local Ollama), install pip install "agentu[media]" and agentu automatically degrades videos and documents into Markdown transcripts.

Skills, rules & MCP

agent = await (
    Agent("engineer", model="claude-sonnet-4-20250514", auto_discover_rules=True)
    .with_skills(["./skills/security-audit", "github:hemanth/skills/python-perf"])
    .with_mcp(["http://localhost:3000", {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}])
)

Auto-discovers AGENTS.md / CLAUDE.md from your repo root, loads SKILL.md progressive instructions only when relevant, and connects to HTTP, Streamable HTTP, or STDIO MCP servers.

Memory, context & caching

agent = (
    Agent("researcher", model="gemini-2.5-flash", cache=True)
    .with_context(max_tokens=100_000, compaction="auto", keep_recent=5)
)
agent.remember("Customer prefers EU regions and PostgreSQL 17", importance=0.9)

Short-term working memory + SQLite long-term recall come built in. Context compaction triggers at 80% token budget (truncate old tool outputs → summarize → keep recent turns).

Workflows, sub-agents & Ralph

from agentu import Agent, ralph, run_maker_checker

pipeline = (researcher("Gather benchmarks") & analyst("Check pricing")) >> writer("Draft memo")
out = await pipeline.run()

reviewed = await run_maker_checker(maker=coder, checker=reviewer, task="Write rate limiter", max_rounds=3)
loop_stats = await ralph(coder.with_worktree(), "PROMPT.md", max_iterations=25, timeout_minutes=20)

Compose steps with >> (sequential) and & (parallel), delegate across agents with .with_agents([...]), isolate git edits with .with_worktree(), or run autonomous ralph loops with checkpoint recovery.

Observability, evals & CLI

# One-shot prompt from terminal
agentu run "Summarize recent git commits" --model gemini-2.5-flash

# Interactive dev REPL (preserves live HTTP & MCP sessions across turns)
agentu dev my_agent.py

# Autonomous Ralph loop or FastAPI + SSE + Dashboard server (pip install "agentu[serve]")
agentu ralph PROMPT.md --max 30
agentu serve my_agent.py --port 8000

Attach OpenTelemetry GenAI spans via .with_otel() (agentu[otel]), score datasets and tool trajectories with await evaluate(agent, cases), or serve HTTP/SSE/WebSocket endpoints with serve(agent).

Extras

  • pip install "agentu[serve]" — FastAPI HTTP/SSE/WebSocket server & live dashboard
  • pip install "agentu[media]" — Automatic video/PDF-to-Markdown degradation
  • pip install "agentu[search]" — Built-in SearchAgent & DuckDuckGo search_tool
  • pip install "agentu[semantic]" / "agentu[redis]" / "agentu[vectors]" / "agentu[otel]" / "agentu[all]"

License

MIT © Hemanth.HM

Metadata

Release files for agentu 2.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agentu 2.10.0
File Size Uploaded Provenance Actions
agentu-2.10.0.tar.gz 289.0 kB Without provenance Details for agentu-2.10.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agentu 2.10.0
File Interpreter ABI Platform Actions
agentu-2.10.0-py3-none-any.whl Python 3 none any Details for agentu-2.10.0-py3-none-any.whl

Total release size: 500.0 kB

Release files / agentu-2.10.0.tar.gz

Download URL agentu-2.10.0.tar.gz
Size 289.0 kB
Tags Source
SHA-256 checksum
How to use checksums
02933d54043be0462bb7e8b55192238697afab88c25a9079a67b74c1452f684e
BLAKE2b-256 checksum
How to use checksums
08a63d9d9430ef479ce36ea0ec3186b86526e9c3c50ed33c919030c961d9da16
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / agentu-2.10.0-py3-none-any.whl

Download URL agentu-2.10.0-py3-none-any.whl
Size 211.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ac5c4faf652ca0c51b378b6519827add4772bedb7955b0d682a59db602203ebf
BLAKE2b-256 checksum
How to use checksums
fec6a04c7de30150aff005392f750c64070da81fed362f57a65e97c5c4bd2829
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for agentu 2.10.0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.10.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page