Skip to main content

pygentic-ai

A meta-framework for building agentic workflows with Pydantic AI.

โš ๏ธ Early Alpha: This library is in active development. The API is subject to change as we refine the framework based on feedback and real-world usage.

Installation

pip install pygentic-ai

Or with uv:

uv add pygentic-ai

Quick Start

Build your first agentic workflow in 4 steps:

Step 1: Create Configuration

from dataclasses import dataclass

@dataclass
class AppConfig:
    api_key: str
    model: str = "gpt-4o-mini"
    language: str = "english"

Step 2: Build Agent Factory

Create a factory to configure your agents:

from pydantic_ai import UsageLimits
from pygentic_ai import AgentManager
from pygentic_ai.engines import ReasoningAgent, GuardrailsAgent, SimpleTranslatorWorker

class AgentFactory:
    @staticmethod
    async def create_manager(config: AppConfig) -> AgentManager:
        manager = AgentManager()

        # Configure usage limits
        usage_limits = UsageLimits(output_tokens_limit=2000)

        # Register agents
        manager.register(
            "agent",
            ReasoningAgent,
            api_key=config.api_key,
            llm_model=config.model,
            language=config.language,
            usage_limits=usage_limits,
        )

        manager.register(
            "guardrails",
            GuardrailsAgent,
            api_key=config.api_key,
            llm_model=config.model,
        )

        manager.register(
            "translator",
            SimpleTranslatorWorker,
            api_key=config.api_key,
            target_language=config.language,
        )

        # Initialize all agents
        await manager.initialize()
        return manager

Step 3: Set Up Workflow

Use the pre-built workflow:

from pygentic_ai import user_assistant_graph

# Run workflow - manager.to_deps() automatically includes all registered agents
result = await user_assistant_graph.run(
    {"message": "Hello!"},
    manager.to_deps(chat_history=[])
)
print(result)

Step 4: Put It All Together

Complete application:

import asyncio
from dataclasses import dataclass
from pydantic_ai import UsageLimits
from pygentic_ai import AgentManager, user_assistant_graph
from pygentic_ai.engines import ReasoningAgent, GuardrailsAgent, SimpleTranslatorWorker

@dataclass
class AppConfig:
    api_key: str
    model: str = "gpt-4o-mini"
    language: str = "english"

class AgentFactory:
    @staticmethod
    async def create_manager(config: AppConfig) -> AgentManager:
        manager = AgentManager()
        usage_limits = UsageLimits(output_tokens_limit=2000)

        manager.register("agent", ReasoningAgent, api_key=config.api_key,
                        llm_model=config.model, usage_limits=usage_limits)
        manager.register("guardrails", GuardrailsAgent, api_key=config.api_key)
        manager.register("translator", SimpleTranslatorWorker, api_key=config.api_key)

        await manager.initialize()
        return manager

async def main():
    config = AppConfig(api_key="sk-...")
    manager = await AgentFactory.create_manager(config)

    # Use workflow
    result = await user_assistant_graph.run(
        {"message": "Hello!"},
        manager.to_deps(chat_history=[])
    )
    print(result)

    # Or use agent directly
    agent = manager.get("agent")
    result = await agent.generate_response("What's the weather?", [])
    print(result.output)

if __name__ == "__main__":
    asyncio.run(main())

Complete working example: examples/simple-chat

Advanced Usage

Custom Agents

from pygentic_ai import BaseAgent

class MyCustomAgent(BaseAgent):
    def __init__(self, **kwargs):
        super().__init__(
            llm_vendor="openai",
            llm_model="gpt-4o",
            instructions="You are a helpful assistant.",
            **kwargs
        )

Custom Workflow with Pydantic Graph

Build your own workflow by composing nodes:

from pydantic_graph import Graph
from pygentic_ai.workflows.nodes import StartNode, GenerateNode, GuardrailsNode

# Define custom workflow
my_workflow = Graph(
    nodes=(StartNode, GenerateNode, GuardrailsNode),
    name="MyWorkflow"
)

# Execute with manager.to_deps()
result = await my_workflow.run(
    {"message": "Hello"},
    manager.to_deps(chat_history=[])
)

Adding Custom Tools

from pygentic_ai.tools import tool_manager, Toolpacks

# Get tools for your agent
tools = tool_manager.get_toolpack(AgentMode.GENERAL)

# Register agent with tools
manager.register(
    "agent",
    ReasoningAgent,
    api_key=config.api_key,
    tool_list=tools,
)

API Reference

Engines

  • BaseAgent: Foundation for custom agents
  • ReasoningAgent: General-purpose agent with reasoning capabilities
  • GuardrailsAgent: Agent with content safety checks
  • GenericRouter: Routes messages to appropriate handlers
  • SimpleTranslatorWorker: Translates responses to different languages

Manager

  • AgentManager: Registry for managing multiple agents

Workflows

  • user_assistant_graph: Pre-built workflow with routing, generation, guardrails, and translation

Workflow Nodes

  • StartNode: Entry point for workflows
  • GenerateNode: Generates responses using an agent
  • GuardrailsNode: Applies safety checks
  • ClassifyNode: Routes based on message classification
  • TranslateNode: Translates output
  • RefuseNode: Handles refused/blocked content

State Management

  • WorkflowState: Maintains conversation state and metadata
  • RefusalInfo: Tracks content refusal details

Tools

  • dateutils: Date utility functions (get_today_date, get_current_week, get_weekday_from_date)
  • tool_registry: ToolManager for organizing tools by agent mode

Features

  • ๐Ÿš€ Built on Pydantic AI for type safety
  • ๐Ÿ”ง Extensible agent system
  • ๐Ÿ”„ Workflow composition with pydantic-graph
  • ๐Ÿ›ก๏ธ Built-in guardrails
  • ๐ŸŒ Multi-language support
  • ๐Ÿ”Œ MCP (Model Context Protocol) support
  • ๐Ÿ“Š Token usage tracking

Examples

  • Simple Chat: Basic chat application showing complete workflow setup

See examples/ for more.

Project Structure

Recommended structure for your application:

your-app/
โ”œโ”€โ”€ config.py                 # Configuration (API keys, models)
โ”œโ”€โ”€ factories/
โ”‚   โ””โ”€โ”€ agent_factory.py      # Agent initialization
โ”œโ”€โ”€ engines/                  # Custom agents (optional)
โ”‚   โ””โ”€โ”€ my_custom_agent.py
โ”œโ”€โ”€ workflows/                # Custom workflows (optional)
โ”‚   โ””โ”€โ”€ my_workflow.py
โ”œโ”€โ”€ nodes/                    # Custom workflow nodes (optional)
โ”‚   โ””โ”€โ”€ my_custom_node.py
โ”œโ”€โ”€ tools/                    # Custom tools (optional)
โ”‚   โ””โ”€โ”€ my_tools.py
โ”œโ”€โ”€ main.py                  # Application entry point
โ””โ”€โ”€ .env                     # Environment variables

Example Custom Engine

# engines/my_custom_agent.py
from pygentic_ai import BaseAgent

class MyCustomAgent(BaseAgent):
    def __init__(self, **kwargs):
        super().__init__(
            llm_vendor="openai",
            llm_model="gpt-4o",
            instructions="You are a specialized assistant.",
            **kwargs
        )

Example Custom Node

# nodes/my_custom_node.py
from dataclasses import dataclass
from pydantic_graph import BaseNode, GraphRunContext
from pygentic_ai.workflows.state import WorkflowState

@dataclass
class MyCustomNode(BaseNode[WorkflowState, dict, str]):
    async def run(self, ctx: GraphRunContext[WorkflowState, dict]):
        # Your custom logic
        return NextNode()

Example Custom Tools

# tools/my_tools.py
def my_custom_tool(query: str) -> str:
    """Custom tool for your agent."""
    return f"Processed: {query}"

MY_TOOLS = [my_custom_tool]

# In factory:
manager.register(
    "agent",
    ReasoningAgent,
    tool_list=MY_TOOLS,
)

Features

  • ๐Ÿš€ Built on Pydantic AI for type safety
  • ๐Ÿ”ง Extensible agent system
  • ๐Ÿ”„ Workflow composition with pydantic-graph
  • ๐Ÿ›ก๏ธ Built-in guardrails
  • ๐ŸŒ Multi-language support
  • ๐Ÿ”Œ MCP (Model Context Protocol) support
  • ๐Ÿ“Š Token usage tracking

Download files

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

Source Distribution

pygentic_ai-0.1.0.post1.tar.gz (15.5 kB view details)

Uploaded Source

Built Distribution

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

pygentic_ai-0.1.0.post1-py3-none-any.whl (27.1 kB view details)

Uploaded Python 3

File details

Details for the file pygentic_ai-0.1.0.post1.tar.gz.

File metadata

  • Download URL: pygentic_ai-0.1.0.post1.tar.gz
  • Upload date:
  • Size: 15.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.28 {"installer":{"name":"uv","version":"0.9.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for pygentic_ai-0.1.0.post1.tar.gz
Algorithm Hash digest
SHA256 493d2f97e8005cca640d4c46a8662e20a8df6e095a09cc8dfeb8dd281fe2135b
MD5 096503dabe119833467d11f168bd0f1d
BLAKE2b-256 64c20d5fc2a628576abcd676ab216464bd4b6543da77e16815e30e212830c951

See more details on using hashes here.

File details

Details for the file pygentic_ai-0.1.0.post1-py3-none-any.whl.

File metadata

  • Download URL: pygentic_ai-0.1.0.post1-py3-none-any.whl
  • Upload date:
  • Size: 27.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.28 {"installer":{"name":"uv","version":"0.9.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for pygentic_ai-0.1.0.post1-py3-none-any.whl
Algorithm Hash digest
SHA256 51a451d322b7b90da63ea80c7c5d09a2832766f503f2f03b8757305c3ce9c114
MD5 99937e876be426196fbeec29c1b3ad2e
BLAKE2b-256 35f8c58b079df27963a123056d2ac5e95f75d0b15e132c7844193018a0301496

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.0.post1 This release

2 files

0.1.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page