Skip to main content

petfishFramework

A runtime control framework for enterprise AI agents — enforcing policy, budget, credentials, audit, replay, and Tool/MCP governance at execution time.

Python 3.10+ License: MIT Tests: 484

Status: v1.0 Stable — Core runtime APIs are frozen. Selected integrations remain experimental; see API Stability.

Quick Start (Zero Cost — No API Key)

pip install petfishframework
from petfishframework import Agent, ReAct
from petfishframework.tools.calculator import Calculator
from petfishframework.models.fake import FakeModel

# FakeModel — runs without any API key, perfect for testing
model = FakeModel.script_tool_then_answer(
    tool_name="calculator",
    tool_args={"expression": "17 * 23"},
    final_answer="391",
)

agent = Agent(
    model=model,
    reasoning=ReAct(),
    tools=(Calculator(),),
)

result = agent.run("What is 17 * 23?")
print(result.answer)  # "391"
print(result.usage.total_tokens)
print(len(result.trajectory.steps), "steps")

Quick Start (Real LLM)

pip install "petfishframework[openai]"
from petfishframework import Agent, ReAct
from petfishframework.tools.calculator import Calculator
from petfishframework.models.openai import OpenAIModel

agent = Agent(
    model=OpenAIModel(model="gpt-4o-mini"),  # or model="openai:gpt-4o-mini"
    reasoning=ReAct(),
    tools=(Calculator(),),
)

result = agent.run("What is 17 * 23?")
print(result.answer)  # "391"

Set OPENAI_API_KEY in .env or environment. Works with OpenAI-compatible APIs (SiliconFlow, etc.) via OPENAI_BASE_URL.

Budget Control (Runtime Hard Limits)

from petfishframework import Budget

# Budget is execution-scoped — pass to run() or session(), not Agent()
result = agent.run(
    "Complex calculation task",
    budget=Budget(max_tokens=1000, max_tool_calls=5, max_steps=10),
)
# Exceeding any limit raises BudgetExceeded

Permission Gate (Runtime Access Control)

from petfishframework.permissions.model import (
    Decision, DecisionEffect, PermissionPolicy,
)

class DenyExpensiveTools:
    """Custom policy: deny tools tagged 'expensive'."""
    def evaluate(self, subject, action, resource, context):
        if "expensive" in resource.tags:
            return Decision(effect=DecisionEffect.DENY, reason="too expensive")
        return Decision(effect=DecisionEffect.ALLOW)

agent = Agent(
    model=model,
    reasoning=ReAct(),
    tools=(Calculator(),),
    permission_policy=DenyExpensiveTools(),
)
# Tool calls pass through the Environment chokepoint — denied calls never execute

Replay & Audit (Event-Sourced Sessions)

session = agent.session("What is 17 * 23?")
result = session.run()

# Every step is recorded — model calls, tool calls, permission decisions
for event in session.replay():
    print(f"{event.type}: {event.data}")

# Events come from session.replay(), not from Result
# Result has: answer, usage, trajectory
# Session has: events, replay(), checkpoint()

MCP Client (External Tool Servers)

pip install "petfishframework[mcp]"
from petfishframework.mcp import connect_stdio

# Connect to a real MCP server
client = connect_stdio("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"])
tools = client.discover_tools()  # 14 tools: read_file, write_file, list_directory...

agent = Agent(model=model, reasoning=ReAct(), tools=tuple(tools))
result = agent.run("List all files in /tmp")

Reliability Evaluation (Pass^k)

from petfishframework.reliability import pass_at_k_with_perturbations, exact_match
from petfishframework.core.types import Task

# Run same task 8 times — measure consistency
result = pass_at_k_with_perturbations(
    session_factory=lambda task: agent.session(task),
    task=Task(prompt="What is 17 * 23?"),
    k=8,
)
print(result.summary())
# Pass@8 — PASS (100%)
#   canonical:        8/8
#   order_shuffled:   8/8
#   paraphrase:       8/8

Core Concepts

Concept Role
Agent Immutable recipe (model + reasoning + tools)
Session Event-sourced execution (auditable, replayable)
Environment Single chokepoint (all calls audited, budget-metered, permission-gated)
Budget Hard execution limits (tokens, cost, steps, tool calls)
Permission SARC access control with 6 DecisionEffects
Replay AUDIT event log via session.replay(); RERUN + RESUME via reliability.replay wrappers
Pass^k Reliability metric (k repetitions + perturbation suite)

Features

  • 3 reasoning strategies: ReAct, LATS (MCTS search), LLM+P (symbolic planning)
  • 3 model adapters: OpenAI, Anthropic, FakeModel (deterministic testing)
  • 3 routing axes: ToolRegistry (auto tool selection), Adaptive-RAG (retrieval), ReasoningStrategy
  • MCP client: real stdio transport, tool discovery from external MCP servers
  • Multi-agent: AgentAsTool (supervisor delegates to specialist agents)
  • Structured output: JSON → dataclass (zero regex scoring)
  • Conversation memory: cross-session recall via ConversationStore
  • Async + streaming: dual sync/async interface

Documentation

Enterprise PoC

See examples/05_enterprise_expense.py and tests/test_enterprise_demo.py for a complete enterprise expense approval scenario demonstrating all 6 DecisionEffects.

Run (from a repository checkout): python examples/05_enterprise_expense.py

YAML Policy Engine

Configure permissions via YAML instead of Python:

from petfishframework.policies import YamlPolicy

policy = YamlPolicy.from_file("examples/policies/enterprise-expense.yaml")
policy.register_tools(tools)

agent = Agent(model=model, reasoning=ReAct(), tools=tools, permission_policy=policy)

Supported conditions: action.tool_name, subject.role_in, subject.role_not_in, action.args.amount_gt/lt, tool.side_effect, tool.external_egress.

CredentialBroker

Tools never hold raw API keys — they receive scoped, time-limited tokens:

from petfishframework.credentials import CredentialBroker

broker = CredentialBroker()
broker.register_credential("github_tool", os.environ["GITHUB_TOKEN"])

agent = Agent(model=model, reasoning=ReAct(), tools=tools, credential_broker=broker)
# Tools with requires_credentials=True receive a ScopedToken (repr-safe, auto-expiring)

Observability (OTel + SIEM)

from petfishframework.observability import OTelSink, SIEMSink

# OTel — creates spans for model/tool/session events (requires opentelemetry)
otel_sink = OTelSink()  # no-op if opentelemetry not installed

# SIEM — structured JSON-Lines export for downstream SIEM ingestion
siem_sink = SIEMSink(output_path="audit.jsonl")
# Credentials auto-redacted; configure additional secret fields:
# siem_sink = SIEMSink(output_path="audit.jsonl", redact_keys=("api_key", "password"))

agent = Agent(model=model, reasoning=ReAct(), tools=tools)

# Attach sinks to the session's EventEmitter
session = agent.session("your task")
session.events.subscribe(otel_sink)
session.events.subscribe(siem_sink)
result = session.run()

Tool Governance

from petfishframework.tools import ToolGovernance, ToolSchemaValidator
from petfishframework.tools.rate_limiter import RateLimiter, RateLimitPolicy

governance = ToolGovernance(
    schema_validator=ToolSchemaValidator(),  # validate tool args before execution
    rate_limiter=RateLimiter(),              # per-tool sliding-window rate limit
)

agent = Agent(model=model, reasoning=ReAct(), tools=tools, tool_governance=governance)

Roadmap

  • v0.2.x: Core runtime, permission semantics, enterprise PoC, Trusted Publishing ✅
  • v0.3.x: YAML Policy Engine, CredentialBroker ✅
  • v1.1.x (current): Enterprise mode — strict mode, ExecutionContext, tool visibility, approval state machine, cost tracking, streaming governance

Current Limitations

petfishFramework v1.0 has a stable core runtime with selected experimental integrations.

Capability Status
Zero-cost quickstart ✅ Available
ReAct / Budget / Pass^k ✅ Available
DENY permission gate ✅ Enforced (pre-execution block)
REQUIRE_APPROVAL ✅ Enforced (pre-execution block)
PARTIAL_ALLOW ✅ Enforced (pre-execution arg filtering)
MASK ✅ Enforced (input mask before + output mask after)
DEGRADE ✅ Enforced (fallback tool switching)
Session replay / deterministic rerun / resume ✅ Available
OpenTelemetry + SIEM observability ✅ Available
MCP client stdio ✅ Available
MCP server mode ✅ MVP (stdio JSON-RPC: initialize/tools.list/tools.call)
Structured output / conversation memory ✅ Available
YAML Policy Engine ✅ Available
Credential Broker ✅ Available
Tool governance (schema/rate/timeout/retry/idempotency) ✅ Available
Thread safety (EventEmitter/RateLimiter/IdempotencyStore) ✅ Available
LATS full MCTS / LLM+P 🔶 Experimental
CRAG / Adaptive-RAG 🔶 Lightweight reference implementations
Sandbox subprocess isolation 🔶 Phase 1 (not a security boundary)

API Stability

Area Status
Agent / Session / RuntimeEnvironment ✅ Stable
DecisionEffect semantics (all 6) ✅ Stable
Budget / CostAccountant ✅ Stable
CredentialBroker / ScopedToken ✅ Stable
YAML Policy Engine ✅ Stable
AuditReport / EventEmitter ✅ Stable
SIEMSink (key-based redaction) ✅ Stable
Tool schema validation / rate limiting ✅ Stable
MCP client governance (allowlist/pin/risk) ✅ Stable
Pass^k reliability metric ✅ Stable
FrameworkConfig ✅ Stable
MCP server mode 🔶 Experimental (stdio JSON-RPC MVP)
OTel sink 🔶 Experimental (optional dep)
Vault adapter 🔶 Experimental (optional dep)
Deterministic replay / resume 🔶 Experimental
LATS full MCTS / LLM+P 🔶 Experimental
CRAG / Adaptive-RAG 🔶 Lightweight reference
Sandbox executor 🔶 Phase 1 (process isolation)

See API Stability Policy for full classification and deprecation process.

Development

git clone https://github.com/kylecui/petfishFramework.git
cd petfishFramework
uv sync --all-extras
uv run pytest              # 484 tests
uv run ruff check src/ tests/

See CONTRIBUTING.md for details.

License

MIT — © 2026 Kyle Cui

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

petfishframework-1.1.0.tar.gz (522.3 kB view details)

Uploaded Source

Built Distribution

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

petfishframework-1.1.0-py3-none-any.whl (128.1 kB view details)

Uploaded Python 3

File details

Details for the file petfishframework-1.1.0.tar.gz.

File metadata

  • Download URL: petfishframework-1.1.0.tar.gz
  • Upload date:
  • Size: 522.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for petfishframework-1.1.0.tar.gz
Algorithm Hash digest
SHA256 c7fd907d2f4962d84254637e2d65f9190ac8642a69523c5dee5fac6563f14818
MD5 6c1b8f615040ecfbf9e0dd8d0f30a747
BLAKE2b-256 d7a0e3c808804f51a6c4840124e2b514f22b79446553df86e300038733c732ec

See more details on using hashes here.

Provenance

The following attestation bundles were made for petfishframework-1.1.0.tar.gz:

Publisher: publish.yml on kylecui/petfishFramework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file petfishframework-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for petfishframework-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 87ae64818fb8783ff73d89c494cfbbefda827c9a0b9a5792c5e9ea5bde91560c
MD5 65849c2c55107042f0e435a6f6c6f28b
BLAKE2b-256 52a66f9501ba5d0a7e2d312582f7903a899e14752358c2fc434e08627582a385

See more details on using hashes here.

Provenance

The following attestation bundles were made for petfishframework-1.1.0-py3-none-any.whl:

Publisher: publish.yml on kylecui/petfishFramework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

1.3.0

2 files

This release

1.1.0 This release

2 files

1.0.1

2 files

1.0.0

2 files

0.5.2

2 files

0.5.1

2 files

0.5.0

2 files

0.4.5

2 files

0.4.2

2 files

0.4.1

2 files

0.4.0

2 files

0.3.3

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.5

2 files

0.2.4

2 files

0.2.3

2 files

0.2.2

2 files

0.2.1

2 files

0.2.0

2 files

0.1.9

2 files

0.1.8

2 files

0.1.7

2 files

0.1.6

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

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