API Reference๏ƒ

Complete API documentation for the Praval framework, auto-generated from source code docstrings.

Overview๏ƒ

The Praval API is organized into logical modules:

Core API๏ƒ

The fundamental building blocks of the Praval framework.

praval.core.agent

Core Agent class for the Praval framework.

praval.core.reef

Reef Communication System for Praval Framework.

praval.core.registry

Agent and Tool Registry for Praval Framework.

praval.core.exceptions

Custom exceptions for the Praval framework.

Decorators๏ƒ

High-level decorator API for creating agents and tools.

praval.decorators

Decorator-based Agent API for Praval Framework.

praval.composition

Composition utilities for decorator-based agents.

Memory System๏ƒ

Multi-layered memory capabilities for persistent agents.

praval.memory.memory_manager

MemoryManager - Unified interface for all Praval agent memory systems

praval.memory.short_term_memory

Short-term working memory for Praval agents

praval.memory.long_term_memory

Long-term vector memory using Qdrant for Praval agents

praval.memory.episodic_memory

Episodic memory for Praval agents - conversation history and experiences

praval.memory.semantic_memory

Semantic memory for Praval agents - knowledge, facts, and concepts

praval.memory.memory_types

Memory types and data structures for Praval agents

Storage System๏ƒ

Unified data storage and retrieval across multiple providers.

praval.storage.data_manager

Data Manager - Unified interface for storage operations

praval.storage.base_provider

Base Storage Provider Framework

praval.storage.storage_registry

Storage Registry System

praval.storage.decorators

Storage decorators for Praval agents

praval.storage.providers

Built-in storage providers for Praval framework

Tool System๏ƒ

Tool integration and management for agent capabilities.

praval.tools

Tool decorator and utilities for Praval Framework.

praval.core.tool_registry

Tool Registry for Praval Framework.

LLM Providers๏ƒ

Integration with multiple Large Language Model providers.

praval.providers.factory

Factory for creating LLM provider instances.

praval.providers.openai

OpenAI provider implementation for Praval framework.

praval.providers.anthropic

Anthropic provider implementation for Praval framework.

praval.providers.cohere

Cohere provider implementation for Praval framework.

Detailed Documentation๏ƒ

Core Module๏ƒ

Core Agent class for the Praval framework.

The Agent class provides a simple, composable interface for LLM-based conversations with support for multiple providers, tools, and state persistence.

class praval.core.agent.AgentConfig(provider=None, temperature=0.7, max_tokens=1000, system_message=None)[source]๏ƒ

Bases: object

Configuration for Agent behavior and LLM parameters.

Parameters:
  • provider (str | None)

  • temperature (float)

  • max_tokens (int)

  • system_message (str | None)

provider: Optional[str] = None๏ƒ
temperature: float = 0.7๏ƒ
max_tokens: int = 1000๏ƒ
system_message: Optional[str] = None๏ƒ
__post_init__()[source]๏ƒ

Validate configuration parameters.

__init__(provider=None, temperature=0.7, max_tokens=1000, system_message=None)๏ƒ
Parameters:
  • provider (str | None)

  • temperature (float)

  • max_tokens (int)

  • system_message (str | None)

Return type:

None

class praval.core.agent.Agent(name, provider=None, persist_state=False, system_message=None, config=None, memory_enabled=False, memory_config=None, knowledge_base=None)[source]๏ƒ

Bases: object

A simple, composable LLM agent.

The Agent class provides the core functionality for LLM-based conversations with support for multiple providers, conversation history, tools, and state persistence.

Examples

Basic usage: >>> agent = Agent(โ€œassistantโ€) >>> response = agent.chat(โ€œHello!โ€)

With persistence: >>> agent = Agent(โ€œmy_agentโ€, persist_state=True) >>> agent.chat(โ€œRemember this conversationโ€)

With tools: >>> agent = Agent(โ€œcalculatorโ€) >>> @agent.tool >>> def add(x: int, y: int) -> int: โ€ฆ return x + y

Parameters:
  • name (str)

  • provider (str | None)

  • persist_state (bool)

  • system_message (str | None)

  • config (Dict[str, Any] | None)

  • memory_enabled (bool)

  • memory_config (Dict[str, Any] | None)

  • knowledge_base (str | None)

__init__(name, provider=None, persist_state=False, system_message=None, config=None, memory_enabled=False, memory_config=None, knowledge_base=None)[source]๏ƒ

Initialize a new Agent.

Parameters:
  • name (str) โ€“ Unique identifier for this agent

  • provider (Optional[str]) โ€“ LLM provider to use (openai, anthropic, cohere)

  • persist_state (bool) โ€“ Whether to persist conversation state

  • system_message (Optional[str]) โ€“ System message to set agent behavior

  • config (Optional[Dict[str, Any]]) โ€“ Additional configuration parameters

  • memory_enabled (bool) โ€“ Whether to enable vector memory capabilities

  • memory_config (Optional[Dict[str, Any]]) โ€“ Configuration for memory system

  • knowledge_base (Optional[str]) โ€“ Path to knowledge base files to auto-index

Raises:
chat(message)[source]๏ƒ

Send a message to the agent and get a response.

Parameters:

message (Optional[str]) โ€“ User message to send to the agent

Return type:

str

Returns:

Agentโ€™s response as a string

Raises:
tool(func)[source]๏ƒ

Decorator to register a function as a tool for the agent.

Parameters:

func (Callable) โ€“ Function to register as a tool

Return type:

Callable

Returns:

The original function (unchanged)

Raises:

ValueError โ€“ If function lacks proper type hints

send_knowledge(to_agent, knowledge, channel='main')[source]๏ƒ

Send knowledge to another agent through the reef.

Parameters:
  • to_agent (str) โ€“ Name of the target agent

  • knowledge (Dict[str, Any]) โ€“ Knowledge data to send

  • channel (str) โ€“ Reef channel to use (default: โ€œmainโ€)

Return type:

str

Returns:

Spore ID of the sent message

broadcast_knowledge(knowledge, channel='main')[source]๏ƒ

Broadcast knowledge to all agents in the reef.

Parameters:
  • knowledge (Dict[str, Any]) โ€“ Knowledge data to broadcast

  • channel (str) โ€“ Reef channel to use (default: โ€œmainโ€)

Return type:

str

Returns:

Spore ID of the broadcast message

request_knowledge(from_agent, request, timeout=30)[source]๏ƒ

Request knowledge from another agent with timeout.

Parameters:
  • from_agent (str) โ€“ Name of the agent to request from

  • request (Dict[str, Any]) โ€“ Request data

  • timeout (int) โ€“ Timeout in seconds

Return type:

Optional[Dict[str, Any]]

Returns:

Response data or None if timeout

on_spore_received(spore)[source]๏ƒ

Handle received spores from the reef.

This is a default implementation that can be overridden by subclasses for custom spore handling.

Parameters:

spore โ€“ The received Spore object

Return type:

None

subscribe_to_channel(channel_name)[source]๏ƒ

Subscribe this agent to a reef channel.

Parameters:

channel_name (str) โ€“ Name of the channel to subscribe to

Return type:

None

unsubscribe_from_channel(channel_name)[source]๏ƒ

Unsubscribe this agent from a reef channel.

Parameters:

channel_name (str) โ€“ Name of the channel to unsubscribe from

Return type:

None

set_spore_handler(handler)[source]๏ƒ

Set a custom spore handler for this agent.

Parameters:

handler (Callable) โ€“ Function that takes a Spore object and handles it

Return type:

None

remember(content, importance=0.5, memory_type='short_term')[source]๏ƒ

Store a memory

Parameters:
  • content (str) โ€“ The content to remember

  • importance (float) โ€“ Importance score (0.0 to 1.0)

  • memory_type (str) โ€“ Type of memory (โ€œshort_termโ€, โ€œsemanticโ€, โ€œepisodicโ€)

Return type:

Optional[str]

Returns:

Memory ID if successful, None otherwise

recall(query, limit=5, similarity_threshold=0.1)[source]๏ƒ

Recall memories based on a query

Parameters:
  • query (str) โ€“ Search query

  • limit (int) โ€“ Maximum number of results

  • similarity_threshold (float) โ€“ Minimum similarity score

Return type:

List

Returns:

List of MemoryEntry objects

recall_by_id(memory_id)[source]๏ƒ

Recall a specific memory by ID (for resolving spore references)

Return type:

List

Parameters:

memory_id (str)

get_conversation_context(turns=10)[source]๏ƒ

Get recent conversation context

Return type:

List

Parameters:

turns (int)

create_knowledge_reference(content, importance=0.8)[source]๏ƒ

Create knowledge references for lightweight spores

Parameters:
  • content (str) โ€“ Knowledge content to store and reference

  • importance (float) โ€“ Importance threshold

Return type:

List[str]

Returns:

List of knowledge reference IDs

resolve_spore_knowledge(spore)[source]๏ƒ

Resolve knowledge references in a spore

Parameters:

spore โ€“ Spore object with potential knowledge references

Return type:

Dict[str, Any]

Returns:

Complete knowledge including resolved references

send_lightweight_knowledge(to_agent, large_content, summary, channel='main')[source]๏ƒ

Send large knowledge as lightweight spore with references

Parameters:
  • to_agent (str) โ€“ Target agent

  • large_content (str) โ€“ Large content to reference

  • summary (str) โ€“ Brief summary for the spore

  • channel (str) โ€“ Communication channel

Return type:

str

Returns:

Spore ID

Reef Communication System for Praval Framework.

Like coral reefs facilitate communication between polyps through chemical and biological signals, this system enables knowledge-first communication between agents through structured JSON message queues.

Components: - Spores: JSON messages containing knowledge, data, or requests - ReefChannel: Named message channels within the reef - Reef: The message queue network connecting all agents

class praval.core.reef.SporeType(*values)[source]๏ƒ

Bases: Enum

Types of spores that can flow through the reef.

KNOWLEDGE = 'knowledge'๏ƒ
REQUEST = 'request'๏ƒ
RESPONSE = 'response'๏ƒ
BROADCAST = 'broadcast'๏ƒ
NOTIFICATION = 'notification'๏ƒ
class praval.core.reef.Spore(id, spore_type, from_agent, to_agent, knowledge, created_at, expires_at=None, priority=5, reply_to=None, metadata=None, knowledge_references=None, data_references=None)[source]๏ƒ

Bases: object

A spore is a knowledge-carrying message that flows through the reef.

Like biological spores, each carries: - Genetic material (knowledge/data) - Identification markers (metadata) - Survival instructions (processing hints)

Spores can carry either direct knowledge or lightweight references to knowledge stored in vector memory, following the principle that โ€œlight spores travel far.โ€

Parameters:
id: str๏ƒ
spore_type: SporeType๏ƒ
from_agent: str๏ƒ
to_agent: Optional[str]๏ƒ
knowledge: Dict[str, Any]๏ƒ
created_at: datetime๏ƒ
expires_at: Optional[datetime] = None๏ƒ
priority: int = 5๏ƒ
reply_to: Optional[str] = None๏ƒ
metadata: Dict[str, Any] = None๏ƒ
knowledge_references: List[str] = None๏ƒ
data_references: List[str] = None๏ƒ
to_json()[source]๏ƒ

Serialize spore to JSON for transmission.

Return type:

str

classmethod from_json(json_str)[source]๏ƒ

Deserialize spore from JSON.

Return type:

Spore

Parameters:

json_str (str)

is_expired()[source]๏ƒ

Check if spore has expired.

Return type:

bool

add_knowledge_reference(reference_id)[source]๏ƒ

Add a reference to stored knowledge

Parameters:

reference_id (str)

add_data_reference(reference_uri)[source]๏ƒ

Add a reference to storage system data

Parameters:

reference_uri (str)

has_knowledge_references()[source]๏ƒ

Check if spore has knowledge references

Return type:

bool

has_data_references()[source]๏ƒ

Check if spore has data references

Return type:

bool

has_any_references()[source]๏ƒ

Check if spore has any kind of references

Return type:

bool

get_spore_size_estimate()[source]๏ƒ

Estimate spore size for lightweight transmission

Return type:

int

__init__(id, spore_type, from_agent, to_agent, knowledge, created_at, expires_at=None, priority=5, reply_to=None, metadata=None, knowledge_references=None, data_references=None)๏ƒ
Parameters:
Return type:

None

class praval.core.reef.ReefChannel(name, max_capacity=1000, max_workers=4)[source]๏ƒ

Bases: object

A message channel within the reef.

Like channels in a coral reef, they: - Have directional flow patterns - Can carry multiple spores simultaneously - Have capacity limits (to prevent overwhelming) - Can experience turbulence (message loss/delays)

Parameters:
  • name (str)

  • max_capacity (int)

  • max_workers (int)

__init__(name, max_capacity=1000, max_workers=4)[source]๏ƒ
Parameters:
  • name (str)

  • max_capacity (int)

  • max_workers (int)

send_spore(spore)[source]๏ƒ

Send a spore through this channel.

Return type:

bool

Parameters:

spore (Spore)

subscribe(agent_name, handler)[source]๏ƒ

Subscribe an agent to receive spores from this channel.

Return type:

None

Parameters:
unsubscribe(agent_name)[source]๏ƒ

Unsubscribe an agent from this channel.

Return type:

None

Parameters:

agent_name (str)

get_spores_for_agent(agent_name, limit=10)[source]๏ƒ

Get recent spores for a specific agent (polling interface).

Return type:

List[Spore]

Parameters:
  • agent_name (str)

  • limit (int)

cleanup_expired()[source]๏ƒ

Remove expired spores from the channel.

Return type:

int

get_stats()[source]๏ƒ

Get channel statistics.

Return type:

Dict[str, Any]

shutdown(wait=True)[source]๏ƒ

Shutdown the channelโ€™s thread pool.

Return type:

None

Parameters:

wait (bool)

class praval.core.reef.Reef(default_max_workers=4)[source]๏ƒ

Bases: object

The Reef manages all communication channels and facilitates agent communication.

Like a coral reef ecosystem, it: - Maintains multiple communication channels - Enables knowledge flow between polyps (agents) - Supports both direct and broadcast communication - Provides network health monitoring

Parameters:

default_max_workers (int)

__init__(default_max_workers=4)[source]๏ƒ
Parameters:

default_max_workers (int)

create_channel(name, max_capacity=1000, max_workers=None)[source]๏ƒ

Create a new reef channel.

Return type:

ReefChannel

Parameters:
  • name (str)

  • max_capacity (int)

  • max_workers (int | None)

get_channel(name)[source]๏ƒ

Get a reef channel by name.

Return type:

Optional[ReefChannel]

Parameters:

name (str)

send(from_agent, to_agent, knowledge, spore_type=SporeType.KNOWLEDGE, channel=None, priority=5, expires_in_seconds=None, reply_to=None, knowledge_references=None, auto_reference_large_knowledge=True)[source]๏ƒ

Send a spore through the reef.

Return type:

str

Parameters:
  • from_agent (str)

  • to_agent (str | None)

  • knowledge (Dict[str, Any])

  • spore_type (SporeType)

  • channel (str)

  • priority (int)

  • expires_in_seconds (int | None)

  • reply_to (str | None)

  • knowledge_references (List[str] | None)

  • auto_reference_large_knowledge (bool)

broadcast(from_agent, knowledge, channel=None)[source]๏ƒ

Broadcast knowledge to all agents in the reef.

Return type:

str

Parameters:
system_broadcast(knowledge, channel=None)[source]๏ƒ

Broadcast system-level messages to all agents in a channel.

Return type:

str

Parameters:
request(from_agent, to_agent, request, channel=None, expires_in_seconds=300)[source]๏ƒ

Send a knowledge request to another agent.

Return type:

str

Parameters:
reply(from_agent, to_agent, response, reply_to_spore_id, channel=None)[source]๏ƒ

Reply to a knowledge request.

Return type:

str

Parameters:
subscribe(agent_name, handler, channel=None)[source]๏ƒ

Subscribe an agent to receive spores from a channel.

Return type:

None

Parameters:
get_network_stats()[source]๏ƒ

Get statistics about the reef network.

Return type:

Dict[str, Any]

shutdown(wait=True)[source]๏ƒ

Shutdown the reef and all its channels.

Return type:

None

Parameters:

wait (bool)

create_knowledge_reference_spore(from_agent, to_agent, knowledge_summary, knowledge_references, spore_type=SporeType.KNOWLEDGE, channel=None)[source]๏ƒ

Create a lightweight spore with knowledge references

This follows the reef principle: โ€œlight spores travel farโ€

Return type:

str

Parameters:
resolve_knowledge_references(spore, memory_manager)[source]๏ƒ

Resolve knowledge references in a spore to actual knowledge

Parameters:
  • spore (Spore) โ€“ The spore with knowledge references

  • memory_manager โ€“ Agentโ€™s memory manager to resolve references

Return type:

Dict[str, Any]

Returns:

Combined knowledge from references

praval.core.reef.get_reef()[source]๏ƒ

Get the global reef instance.

Return type:

Reef

Agent and Tool Registry for Praval Framework.

Provides a global registry for tracking agents and tools across the system, enabling better coordination and discovery in multi-agent applications.

class praval.core.registry.PravalRegistry[source]๏ƒ

Bases: object

Global registry for agents and tools in Praval applications.

__init__()[source]๏ƒ
register_agent(agent)[source]๏ƒ

Register an agent in the global registry.

Parameters:

agent (Agent) โ€“ Agent instance to register

Return type:

Agent

Returns:

The registered agent

get_agent(name)[source]๏ƒ

Get an agent by name from the registry.

Return type:

Optional[Agent]

Parameters:

name (str)

get_all_agents()[source]๏ƒ

Get all registered agents.

Return type:

Dict[str, Agent]

get_tool(tool_name)[source]๏ƒ

Get a tool by name from the registry.

Return type:

Optional[Dict[str, Any]]

Parameters:

tool_name (str)

get_tools_by_agent(agent_name)[source]๏ƒ

Get all tools for a specific agent.

Return type:

Dict[str, Dict[str, Any]]

Parameters:

agent_name (str)

list_agents()[source]๏ƒ

List names of all registered agents.

Return type:

List[str]

list_tools()[source]๏ƒ

List names of all registered tools.

Return type:

List[str]

clear()[source]๏ƒ

Clear all registered agents and tools.

praval.core.registry.register_agent(agent)[source]๏ƒ

Register an agent in the global registry.

Return type:

Agent

Parameters:

agent (Agent)

praval.core.registry.get_registry()[source]๏ƒ

Get the global registry instance.

Return type:

PravalRegistry

Custom exceptions for the Praval framework.

These exceptions provide clear error handling and debugging information for common issues in LLM agent operations.

exception praval.core.exceptions.PravalError[source]๏ƒ

Bases: Exception

Base exception for all Praval-related errors.

exception praval.core.exceptions.ProviderError[source]๏ƒ

Bases: PravalError

Raised when there are issues with LLM provider operations.

exception praval.core.exceptions.ConfigurationError[source]๏ƒ

Bases: PravalError

Raised when there are configuration validation issues.

exception praval.core.exceptions.ToolError[source]๏ƒ

Bases: PravalError

Raised when there are issues with tool registration or execution.

exception praval.core.exceptions.StateError[source]๏ƒ

Bases: PravalError

Raised when there are issues with state persistence operations.

Decorators Module๏ƒ

Decorator-based Agent API for Praval Framework.

This module provides a Pythonic decorator interface for creating agents that automatically handle reef communication and coordination.

Example

@agent(โ€œexplorerโ€, channel=โ€knowledgeโ€) def explore_concepts(spore):

concepts = chat(โ€œFind concepts related to: โ€œ + spore.knowledge.get(โ€œconceptโ€, โ€œโ€)) return {โ€œdiscoveredโ€: concepts.split(โ€œ,โ€)}

praval.decorators.agent(name=None, channel=None, system_message=None, auto_broadcast=True, responds_to=None, memory=False, knowledge_base=None)[source]๏ƒ

Decorator that turns a function into an autonomous agent.

Parameters:
  • name (Optional[str]) โ€“ Agent name (defaults to function name)

  • channel (Optional[str]) โ€“ Channel to subscribe to (defaults to name + โ€œ_channelโ€)

  • system_message (Optional[str]) โ€“ System message (defaults to function docstring)

  • auto_broadcast (bool) โ€“ Whether to auto-broadcast return values

  • responds_to (Optional[List[str]]) โ€“ List of message types this agent responds to (None = all messages)

  • memory (Union[bool, Dict[str, Any]]) โ€“ Memory configuration - True for defaults, dict for custom config, False to disable

  • knowledge_base (Optional[str]) โ€“ Path to knowledge base files for auto-indexing

Examples

Basic agent: @agent(โ€œexplorerโ€, channel=โ€knowledgeโ€, responds_to=[โ€œconcept_requestโ€]) def explore_concepts(spore):

โ€˜โ€™โ€™Find related concepts and broadcast discoveries.โ€™โ€™โ€™ concepts = chat(โ€œRelated to: โ€œ + spore.knowledge.get(โ€œconceptโ€, โ€œโ€)) return {โ€œtypeโ€: โ€œdiscoveryโ€, โ€œdiscoveredโ€: concepts.split(โ€œ,โ€)}

Agent with memory: @agent(โ€œresearcherโ€, memory=True) def research_agent(spore):

โ€˜โ€™โ€™Research agent with memory capabilities.โ€™โ€™โ€™ query = spore.knowledge.get(โ€œqueryโ€) # Remember the research research_agent.remember(fโ€Researched: {query}โ€) # Recall similar past research past_research = research_agent.recall(query) return {โ€œresearchโ€: โ€œcompletedโ€, โ€œpast_similarโ€: len(past_research)}

Agent with knowledge base: @agent(โ€œexpertโ€, memory=True, knowledge_base=โ€./knowledge/โ€) def expert_agent(spore):

โ€˜โ€™โ€™Expert with pre-loaded knowledge base.โ€™โ€™โ€™ question = spore.knowledge.get(โ€œquestionโ€) relevant = expert_agent.recall(question, limit=3) return {โ€œanswerโ€: [r.content for r in relevant]}

praval.decorators.chat(message, timeout=10.0)[source]๏ƒ

Quick chat function that uses the current agentโ€™s LLM with timeout support. Can only be used within @agent decorated functions.

Parameters:
  • message (str) โ€“ Message to send to the LLM

  • timeout (float) โ€“ Maximum time to wait for response in seconds

Return type:

str

Returns:

LLM response as string

Raises:
async praval.decorators.achat(message, timeout=10.0)[source]๏ƒ

Async version of chat function for use within async agent handlers.

Parameters:
  • message (str) โ€“ Message to send to the LLM

  • timeout (float) โ€“ Maximum time to wait for response in seconds

Return type:

str

Returns:

LLM response as string

Raises:
praval.decorators.broadcast(data, channel=None, message_type=None)[source]๏ƒ

Quick broadcast function that uses the current agentโ€™s communication. Can only be used within @agent decorated functions.

Parameters:
  • data (Dict[str, Any]) โ€“ Data to broadcast

  • channel (Optional[str]) โ€“ Channel to broadcast to (defaults to agentโ€™s channel)

  • message_type (Optional[str]) โ€“ Message type to set (automatically added to data)

Return type:

str

Returns:

Spore ID of the broadcast message

Raises:

RuntimeError โ€“ If called outside of an @agent function

praval.decorators.get_agent_info(agent_func)[source]๏ƒ

Get information about an @agent decorated function.

Parameters:

agent_func (Callable) โ€“ Function decorated with @agent

Return type:

Dict[str, Any]

Returns:

Dictionary with agent metadata

Composition utilities for decorator-based agents.

This module provides utilities for composing and orchestrating agents decorated with the @agent decorator.

praval.composition.agent_pipeline(*agents, channel='pipeline')[source]๏ƒ

Compose agents into a pipeline that processes data sequentially.

Parameters:
  • *agents (Callable) โ€“ Functions decorated with @agent

  • channel (str) โ€“ Channel name for pipeline communication

Return type:

Callable

Returns:

Function that triggers the pipeline with initial data

Example

pipeline = agent_pipeline(explorer, analyzer, reporter) pipeline({โ€œtaskโ€: โ€œanalyze sentimentโ€})

praval.composition.conditional_agent(condition_func)[source]๏ƒ

Decorator for conditional agent execution.

Parameters:

condition_func (Callable[[Any], bool]) โ€“ Function that takes a spore and returns bool

Example

@conditional_agent(lambda spore: spore.knowledge.get(โ€œpriorityโ€) == โ€œhighโ€) @agent(โ€œurgent_processorโ€) def process_urgent(spore):

return {โ€œprocessedโ€: True}

praval.composition.throttled_agent(delay_seconds)[source]๏ƒ

Decorator to throttle agent execution.

Parameters:

delay_seconds (float) โ€“ Minimum seconds between executions

Example

@throttled_agent(2.0) # Max once every 2 seconds @agent(โ€œslow_processorโ€) def process_slowly(spore):

return {โ€œprocessedโ€: True}

class praval.composition.AgentSession(session_name)[source]๏ƒ

Bases: object

Context manager for coordinated agent sessions.

Example

with AgentSession(โ€œknowledge_miningโ€) as session:

session.add_agents(explorer, analyzer, curator) session.broadcast({โ€œtaskโ€: โ€œmine concepts about AIโ€})

Parameters:

session_name (str)

__init__(session_name)[source]๏ƒ
Parameters:

session_name (str)

add_agent(agent_func)[source]๏ƒ

Add an agent to this session.

Return type:

AgentSession

Parameters:

agent_func (Callable)

add_agents(*agent_funcs)[source]๏ƒ

Add multiple agents to this session.

Return type:

AgentSession

Parameters:

agent_funcs (Callable)

broadcast(data)[source]๏ƒ

Broadcast data to all agents in this session.

Return type:

str

Parameters:

data (Dict[str, Any])

get_stats()[source]๏ƒ

Get session statistics.

Return type:

Dict[str, Any]

praval.composition.start_agents(*agent_funcs, initial_data=None, channel='startup')[source]๏ƒ

Convenience function to start multiple agents with initial data.

Parameters:
  • *agent_funcs (Callable) โ€“ Functions decorated with @agent

  • initial_data (Optional[Dict[str, Any]]) โ€“ Initial data to broadcast (optional)

  • channel (str) โ€“ Channel to use for startup communication

Return type:

str

Returns:

Spore ID of startup broadcast

Example

start_agents(explorer, analyzer, curator,

initial_data={โ€œtaskโ€: โ€œanalyze market trendsโ€})

Memory Module๏ƒ

MemoryManager - Unified interface for all Praval agent memory systems

This coordinates: - Short-term working memory - Long-term vector memory - Episodic conversation memory - Semantic knowledge memory

class praval.memory.memory_manager.MemoryManager(agent_id, backend='auto', qdrant_url='http://localhost:6333', storage_path=None, collection_name='praval_memories', short_term_max_entries=1000, short_term_retention_hours=24, knowledge_base_path=None)[source]๏ƒ

Bases: object

Unified memory management system for Praval agents

Provides a single interface to: - Store and retrieve memories across all systems - Coordinate between short-term and long-term storage - Manage different types of memory (episodic, semantic, etc.) - Optimize memory access patterns

Parameters:
  • agent_id (str)

  • backend (str)

  • qdrant_url (str)

  • storage_path (str | None)

  • collection_name (str)

  • short_term_max_entries (int)

  • short_term_retention_hours (int)

  • knowledge_base_path (str | None)

__init__(agent_id, backend='auto', qdrant_url='http://localhost:6333', storage_path=None, collection_name='praval_memories', short_term_max_entries=1000, short_term_retention_hours=24, knowledge_base_path=None)[source]๏ƒ

Initialize the unified memory manager

Parameters:
  • agent_id (str) โ€“ ID of the agent using this memory

  • backend (str) โ€“ Memory backend (โ€œautoโ€, โ€œchromadbโ€, โ€œqdrantโ€, โ€œmemoryโ€)

  • qdrant_url (str) โ€“ URL for Qdrant vector database

  • storage_path (Optional[str]) โ€“ Path for persistent storage

  • collection_name (str) โ€“ Collection name for vector storage

  • short_term_max_entries (int) โ€“ Max entries in short-term memory

  • short_term_retention_hours (int) โ€“ Short-term memory retention time

  • knowledge_base_path (Optional[str]) โ€“ Path to knowledge base files to auto-index

store_memory(agent_id, content, memory_type=MemoryType.SHORT_TERM, metadata=None, importance=0.5, store_long_term=None)[source]๏ƒ

Store a memory entry

Parameters:
  • agent_id (str) โ€“ The agent storing the memory

  • content (str) โ€“ The memory content

  • memory_type (MemoryType) โ€“ Type of memory

  • metadata (Optional[Dict[str, Any]]) โ€“ Additional metadata

  • importance (float) โ€“ Importance score (0.0 to 1.0)

  • store_long_term (bool) โ€“ Whether to store in long-term memory (auto-decided if None)

Return type:

str

Returns:

Memory ID

retrieve_memory(memory_id)[source]๏ƒ

Retrieve a specific memory by ID

Parameters:

memory_id (str) โ€“ The memory ID

Return type:

Optional[MemoryEntry]

Returns:

The memory entry if found

search_memories(query)[source]๏ƒ

Search memories across all systems

Parameters:

query (MemoryQuery) โ€“ The search query

Return type:

MemorySearchResult

Returns:

Combined search results

get_conversation_context(agent_id, turns=10)[source]๏ƒ

Get recent conversation context for an agent

Parameters:
  • agent_id (str) โ€“ The agent ID

  • turns (int) โ€“ Number of conversation turns

Return type:

List[MemoryEntry]

Returns:

List of conversation memories

store_conversation_turn(agent_id, user_message, agent_response, context=None)[source]๏ƒ

Store a conversation turn

Parameters:
  • agent_id (str) โ€“ The agent ID

  • user_message (str) โ€“ Userโ€™s message

  • agent_response (str) โ€“ Agentโ€™s response

  • context (Optional[Dict[str, Any]]) โ€“ Additional context

Return type:

str

Returns:

Memory ID

store_knowledge(agent_id, knowledge, domain='general', confidence=1.0, knowledge_type='fact')[source]๏ƒ

Store knowledge or facts

Parameters:
  • agent_id (str) โ€“ The agent ID

  • knowledge (str) โ€“ The knowledge content

  • domain (str) โ€“ Domain of knowledge

  • confidence (float) โ€“ Confidence in the knowledge

  • knowledge_type (str) โ€“ Type of knowledge (fact, concept, rule)

Return type:

str

Returns:

Memory ID

get_domain_knowledge(agent_id, domain, limit=20)[source]๏ƒ

Get knowledge in a specific domain

Parameters:
  • agent_id (str) โ€“ The agent ID

  • domain (str) โ€“ The domain

  • limit (int) โ€“ Maximum results

Return type:

List[MemoryEntry]

Returns:

List of knowledge entries

clear_agent_memories(agent_id, memory_types=None)[source]๏ƒ

Clear memories for a specific agent

Parameters:
  • agent_id (str) โ€“ The agent ID

  • memory_types (Optional[List[MemoryType]]) โ€“ Types of memory to clear (all if None)

get_memory_stats()[source]๏ƒ

Get comprehensive memory statistics

Return type:

Dict[str, Any]

health_check()[source]๏ƒ

Check health of all memory systems

Return type:

Dict[str, bool]

recall_by_id(memory_id)[source]๏ƒ

Recall a specific memory by ID (for spore references)

Return type:

List[MemoryEntry]

Parameters:

memory_id (str)

get_knowledge_references(content, importance_threshold=0.7)[source]๏ƒ

Get knowledge references for lightweight spores

Return type:

List[str]

Parameters:
  • content (str)

  • importance_threshold (float)

shutdown()[source]๏ƒ

Shutdown all memory systems

Short-term working memory for Praval agents

This provides fast, in-memory storage for: - Current conversation context - Recent agent interactions - Active tasks and goals - Temporary state information

class praval.memory.short_term_memory.ShortTermMemory(max_entries=1000, retention_hours=24, cleanup_interval=3600)[source]๏ƒ

Bases: object

Fast, in-memory storage for short-term agent memory

Features: - Thread-safe operations - Automatic cleanup of old memories - Context-aware retrieval - Working memory capacity limits

Parameters:
  • max_entries (int)

  • retention_hours (int)

  • cleanup_interval (int)

__init__(max_entries=1000, retention_hours=24, cleanup_interval=3600)[source]๏ƒ

Initialize short-term memory

Parameters:
  • max_entries (int) โ€“ Maximum number of entries to keep

  • retention_hours (int) โ€“ How long to keep memories (hours)

  • cleanup_interval (int) โ€“ How often to cleanup old memories (seconds)

store(memory)[source]๏ƒ

Store a memory entry

Parameters:

memory (MemoryEntry) โ€“ The memory entry to store

Return type:

str

Returns:

The ID of the stored memory

retrieve(memory_id)[source]๏ƒ

Retrieve a specific memory by ID

Parameters:

memory_id (str) โ€“ The ID of the memory to retrieve

Return type:

Optional[MemoryEntry]

Returns:

The memory entry if found, None otherwise

search(query)[source]๏ƒ

Search memories using text similarity

Parameters:

query (MemoryQuery) โ€“ The search query

Return type:

MemorySearchResult

Returns:

Search results with matching memories

get_recent(agent_id=None, limit=10)[source]๏ƒ

Get recent memories

Parameters:
  • agent_id (Optional[str]) โ€“ Filter by specific agent

  • limit (int) โ€“ Maximum number of memories to return

Return type:

List[MemoryEntry]

Returns:

List of recent memory entries

get_context(agent_id, context_size=5)[source]๏ƒ

Get contextual memories for an agent

Parameters:
  • agent_id (str) โ€“ The agent to get context for

  • context_size (int) โ€“ Number of contextual memories

Return type:

List[MemoryEntry]

Returns:

List of contextual memory entries

clear_agent_memories(agent_id)[source]๏ƒ

Clear all memories for a specific agent

Parameters:

agent_id (str)

get_stats()[source]๏ƒ

Get memory statistics

Return type:

Dict[str, Any]

shutdown()[source]๏ƒ

Shutdown the memory system

Long-term vector memory using Qdrant for Praval agents

This provides persistent, vector-based storage for: - Semantic knowledge and concepts - Long-term conversation history - Learned patterns and insights - Cross-session memory persistence

class praval.memory.long_term_memory.LongTermMemory(qdrant_url='http://localhost:6333', collection_name='praval_memories', vector_size=1536, distance_metric='cosine')[source]๏ƒ

Bases: object

Qdrant-based long-term memory for persistent vector storage

Features: - Vector similarity search - Persistent storage across sessions - Scalable to millions of memories - Semantic search capabilities - Memory importance scoring

Parameters:
  • qdrant_url (str)

  • collection_name (str)

  • vector_size (int)

  • distance_metric (str)

__init__(qdrant_url='http://localhost:6333', collection_name='praval_memories', vector_size=1536, distance_metric='cosine')[source]๏ƒ

Initialize long-term memory

Parameters:
  • qdrant_url (str) โ€“ URL to Qdrant instance

  • collection_name (str) โ€“ Name of the collection to use

  • vector_size (int) โ€“ Size of embedding vectors

  • distance_metric (str) โ€“ Distance metric for similarity search

store(memory)[source]๏ƒ

Store a memory entry with vector embedding

Parameters:

memory (MemoryEntry) โ€“ The memory entry to store

Return type:

str

Returns:

The ID of the stored memory

retrieve(memory_id)[source]๏ƒ

Retrieve a specific memory by ID

Parameters:

memory_id (str) โ€“ The ID of the memory to retrieve

Return type:

Optional[MemoryEntry]

Returns:

The memory entry if found, None otherwise

search(query)[source]๏ƒ

Search memories using vector similarity

Parameters:

query (MemoryQuery) โ€“ The search query

Return type:

MemorySearchResult

Returns:

Search results with matching memories

delete(memory_id)[source]๏ƒ

Delete a memory entry

Parameters:

memory_id (str) โ€“ The ID of the memory to delete

Return type:

bool

Returns:

True if deleted successfully, False otherwise

clear_agent_memories(agent_id)[source]๏ƒ

Clear all memories for a specific agent

Parameters:

agent_id (str)

get_stats()[source]๏ƒ

Get memory statistics

Return type:

Dict[str, Any]

health_check()[source]๏ƒ

Check if Qdrant connection is healthy

Return type:

bool

Episodic memory for Praval agents - conversation history and experiences

This manages: - Conversation turns and dialogue history - Agent interaction sequences - Temporal event chains - Experience-based learning patterns

class praval.memory.episodic_memory.EpisodicMemory(long_term_memory, short_term_memory, conversation_window=50, episode_lifetime_days=30)[source]๏ƒ

Bases: object

Manages episodic memories - experiences and conversations over time

Features: - Conversation turn tracking - Experience sequencing - Temporal relationship modeling - Context window management

Parameters:
__init__(long_term_memory, short_term_memory, conversation_window=50, episode_lifetime_days=30)[source]๏ƒ

Initialize episodic memory

Parameters:
  • long_term_memory (LongTermMemory) โ€“ Long-term memory backend

  • short_term_memory (ShortTermMemory) โ€“ Short-term memory backend

  • conversation_window (int) โ€“ Number of conversation turns to keep in context

  • episode_lifetime_days (int) โ€“ How long to keep episodes before archiving

store_conversation_turn(agent_id, user_message, agent_response, context=None)[source]๏ƒ

Store a conversation turn as an episodic memory

Parameters:
  • agent_id (str) โ€“ The agent involved in the conversation

  • user_message (str) โ€“ The userโ€™s message

  • agent_response (str) โ€“ The agentโ€™s response

  • context (Optional[Dict[str, Any]]) โ€“ Additional context information

Return type:

str

Returns:

The memory ID

store_experience(agent_id, experience_type, experience_data, outcome, success=True)[source]๏ƒ

Store an experience or learning episode

Parameters:
  • agent_id (str) โ€“ The agent that had the experience

  • experience_type (str) โ€“ Type of experience (e.g., โ€œtask_completionโ€, โ€œproblem_solvingโ€)

  • experience_data (Dict[str, Any]) โ€“ Data about the experience

  • outcome (str) โ€“ The result or outcome

  • success (bool) โ€“ Whether the experience was successful

Return type:

str

Returns:

The memory ID

get_conversation_context(agent_id, turns=None)[source]๏ƒ

Get recent conversation context for an agent

Parameters:
  • agent_id (str) โ€“ The agent to get context for

  • turns (Optional[int]) โ€“ Number of conversation turns (default: conversation_window)

Return type:

List[MemoryEntry]

Returns:

List of recent conversation memories

get_similar_experiences(agent_id, experience_description, limit=5)[source]๏ƒ

Find similar past experiences for an agent

Parameters:
  • agent_id (str) โ€“ The agent to search experiences for

  • experience_description (str) โ€“ Description of the current experience

  • limit (int) โ€“ Maximum number of similar experiences to return

Return type:

MemorySearchResult

Returns:

Search results with similar experiences

get_episode_timeline(agent_id, start_time, end_time)[source]๏ƒ

Get episodic memories within a time range

Parameters:
  • agent_id (str) โ€“ The agent to get timeline for

  • start_time (datetime) โ€“ Start of the time range

  • end_time (datetime) โ€“ End of the time range

Return type:

List[MemoryEntry]

Returns:

List of episodic memories in chronological order

archive_old_episodes(cutoff_days=None)[source]๏ƒ

Archive old episodic memories (implementation depends on requirements)

Parameters:

cutoff_days (Optional[int]) โ€“ Days after which to archive (default: episode_lifetime_days)

get_stats()[source]๏ƒ

Get episodic memory statistics

Return type:

Dict[str, Any]

Semantic memory for Praval agents - knowledge, facts, and concepts

This manages: - Factual knowledge storage - Concept relationships - Domain expertise - Learned information persistence

class praval.memory.semantic_memory.SemanticMemory(long_term_memory)[source]๏ƒ

Bases: object

Manages semantic memories - facts, concepts, and knowledge

Features: - Factual knowledge storage - Concept relationship tracking - Knowledge validation and updating - Domain expertise building

Parameters:

long_term_memory (LongTermMemory)

__init__(long_term_memory)[source]๏ƒ

Initialize semantic memory

Parameters:

long_term_memory (LongTermMemory) โ€“ Long-term memory backend for persistence

store_fact(agent_id, fact, domain, confidence=1.0, source=None, related_concepts=None)[source]๏ƒ

Store a factual piece of knowledge

Parameters:
  • agent_id (str) โ€“ The agent learning this fact

  • fact (str) โ€“ The factual statement

  • domain (str) โ€“ Domain or category of knowledge

  • confidence (float) โ€“ Confidence in this fact (0.0 to 1.0)

  • source (Optional[str]) โ€“ Source of this information

  • related_concepts (Optional[List[str]]) โ€“ Related concepts or topics

Return type:

str

Returns:

The memory ID

store_concept(agent_id, concept, definition, domain, properties=None, relationships=None)[source]๏ƒ

Store a concept with its definition and relationships

Parameters:
  • agent_id (str) โ€“ The agent learning this concept

  • concept (str) โ€“ The concept name

  • definition (str) โ€“ Definition of the concept

  • domain (str) โ€“ Domain or field of the concept

  • properties (Optional[Dict[str, Any]]) โ€“ Properties or attributes of the concept

  • relationships (Optional[Dict[str, List[str]]]) โ€“ Relationships to other concepts (e.g., {โ€œis_aโ€: [โ€œcategoryโ€], โ€œrelates_toโ€: [โ€œother_conceptsโ€]})

Return type:

str

Returns:

The memory ID

store_rule(agent_id, rule_name, rule_description, conditions, actions, domain, confidence=1.0)[source]๏ƒ

Store a procedural rule or pattern

Parameters:
  • agent_id (str) โ€“ The agent learning this rule

  • rule_name (str) โ€“ Name of the rule

  • rule_description (str) โ€“ Description of what the rule does

  • conditions (List[str]) โ€“ Conditions when the rule applies

  • actions (List[str]) โ€“ Actions to take when conditions are met

  • domain (str) โ€“ Domain of application

  • confidence (float) โ€“ Confidence in this rule

Return type:

str

Returns:

The memory ID

get_knowledge_in_domain(agent_id, domain, limit=50)[source]๏ƒ

Get all knowledge in a specific domain

Parameters:
  • agent_id (str) โ€“ The agent to get knowledge for

  • domain (str) โ€“ The domain to search in

  • limit (int) โ€“ Maximum number of entries to return

Return type:

List[MemoryEntry]

Returns:

List of semantic memories in the domain

Find concepts related to a given concept

Parameters:
  • agent_id (str) โ€“ The agent to search for

  • concept (str) โ€“ The concept to find relations for

  • limit (int) โ€“ Maximum number of related concepts

Return type:

MemorySearchResult

Returns:

Search results with related concepts

validate_knowledge(agent_id, statement, threshold=0.8)[source]๏ƒ

Check if a statement is consistent with stored knowledge

Parameters:
  • agent_id (str) โ€“ The agent to check knowledge for

  • statement (str) โ€“ The statement to validate

  • threshold (float) โ€“ Similarity threshold for matching

Return type:

Dict[str, Any]

Returns:

Validation result with confidence and supporting evidence

update_knowledge(agent_id, old_knowledge, new_knowledge, reason='Updated information')[source]๏ƒ

Update existing knowledge with new information

Parameters:
  • agent_id (str) โ€“ The agent updating knowledge

  • old_knowledge (str) โ€“ The knowledge to update

  • new_knowledge (str) โ€“ The new knowledge

  • reason (str) โ€“ Reason for the update

Return type:

bool

Returns:

True if update was successful

get_domain_expertise_level(agent_id, domain)[source]๏ƒ

Assess the agentโ€™s expertise level in a domain

Parameters:
  • agent_id (str) โ€“ The agent to assess

  • domain (str) โ€“ The domain to assess expertise in

Return type:

Dict[str, Any]

Returns:

Expertise assessment with metrics

get_stats()[source]๏ƒ

Get semantic memory statistics

Return type:

Dict[str, Any]

Memory types and data structures for Praval agents

class praval.memory.memory_types.MemoryType(*values)[source]๏ƒ

Bases: Enum

Types of memory entries

SHORT_TERM = 'short_term'๏ƒ
EPISODIC = 'episodic'๏ƒ
SEMANTIC = 'semantic'๏ƒ
PROCEDURAL = 'procedural'๏ƒ
EMOTIONAL = 'emotional'๏ƒ
class praval.memory.memory_types.MemoryEntry(id, agent_id, memory_type, content, metadata, embedding=None, created_at=None, accessed_at=None, access_count=0, importance=0.5)[source]๏ƒ

Bases: object

A single memory entry

Parameters:
id: str๏ƒ
agent_id: str๏ƒ
memory_type: MemoryType๏ƒ
content: str๏ƒ
metadata: Dict[str, Any]๏ƒ
embedding: Optional[List[float]] = None๏ƒ
created_at: datetime = None๏ƒ
accessed_at: datetime = None๏ƒ
access_count: int = 0๏ƒ
importance: float = 0.5๏ƒ
mark_accessed()[source]๏ƒ

Mark this memory as accessed

to_dict()[source]๏ƒ

Convert to dictionary for storage

Return type:

Dict[str, Any]

classmethod from_dict(data)[source]๏ƒ

Create from dictionary

Return type:

MemoryEntry

Parameters:

data (Dict[str, Any])

__init__(id, agent_id, memory_type, content, metadata, embedding=None, created_at=None, accessed_at=None, access_count=0, importance=0.5)๏ƒ
Parameters:
Return type:

None

class praval.memory.memory_types.MemoryQuery(query_text, memory_types=None, agent_id=None, limit=10, similarity_threshold=0.7, include_metadata=True, temporal_filter=None)[source]๏ƒ

Bases: object

A memory search query

Parameters:
query_text: str๏ƒ
memory_types: List[MemoryType] = None๏ƒ
agent_id: Optional[str] = None๏ƒ
limit: int = 10๏ƒ
similarity_threshold: float = 0.7๏ƒ
include_metadata: bool = True๏ƒ
temporal_filter: Optional[Dict[str, datetime]] = None๏ƒ
__init__(query_text, memory_types=None, agent_id=None, limit=10, similarity_threshold=0.7, include_metadata=True, temporal_filter=None)๏ƒ
Parameters:
Return type:

None

class praval.memory.memory_types.MemorySearchResult(entries, scores, query, total_found)[source]๏ƒ

Bases: object

Result of a memory search

Parameters:
entries: List[MemoryEntry]๏ƒ
scores: List[float]๏ƒ
query: MemoryQuery๏ƒ
total_found: int๏ƒ
get_best_match()[source]๏ƒ

Get the best matching memory entry

Return type:

Optional[MemoryEntry]

get_above_threshold(threshold=0.8)[source]๏ƒ

Get entries above similarity threshold

Return type:

List[MemoryEntry]

Parameters:

threshold (float)

__init__(entries, scores, query, total_found)๏ƒ
Parameters:
Return type:

None

Storage Module๏ƒ

Data Manager - Unified interface for storage operations

Provides a high-level interface for agents to interact with multiple storage providers through a single, consistent API.

class praval.storage.data_manager.DataManager(registry=None)[source]๏ƒ

Bases: object

Unified data management interface for agents.

Provides high-level methods for storing, retrieving, and querying data across multiple storage backends through a single interface.

Features: - Automatic provider selection based on data type - Cross-provider queries and operations - Data reference management for spore communication - Storage optimization and caching - Transaction-like operations across providers

Parameters:

registry (StorageRegistry | None)

__init__(registry=None)[source]๏ƒ

Initialize data manager.

Parameters:

registry (Optional[StorageRegistry]) โ€“ Storage registry to use (defaults to global registry)

set_agent_context(agent_name)[source]๏ƒ

Set the current agent context for permission checking.

Parameters:

agent_name (str)

get_agent_context()[source]๏ƒ

Get the current agent context.

Return type:

Optional[str]

async store(provider, resource, data, **kwargs)[source]๏ƒ

Store data in a specific provider.

Parameters:
  • provider (str) โ€“ Storage provider name

  • resource (str) โ€“ Resource identifier (table, key, path, etc.)

  • data (Any) โ€“ Data to store

  • **kwargs โ€“ Provider-specific parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async get(provider, resource, **kwargs)[source]๏ƒ

Retrieve data from a specific provider.

Parameters:
  • provider (str) โ€“ Storage provider name

  • resource (str) โ€“ Resource identifier

  • **kwargs โ€“ Provider-specific parameters

Return type:

StorageResult

Returns:

StorageResult with retrieved data

async query(provider, resource, query, **kwargs)[source]๏ƒ

Execute a query on a specific provider.

Parameters:
  • provider (str) โ€“ Storage provider name

  • resource (str) โ€“ Resource to query

  • query (Union[str, Dict]) โ€“ Query string or structured query

  • **kwargs โ€“ Query parameters

Return type:

StorageResult

Returns:

StorageResult with query results

async delete(provider, resource, **kwargs)[source]๏ƒ

Delete data from a specific provider.

Parameters:
  • provider (str) โ€“ Storage provider name

  • resource (str) โ€“ Resource to delete

  • **kwargs โ€“ Delete parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async smart_store(data, resource=None, preferred_provider=None, **kwargs)[source]๏ƒ

Intelligently store data by selecting the best provider.

Parameters:
  • data (Any) โ€“ Data to store

  • resource (Optional[str]) โ€“ Optional resource identifier

  • preferred_provider (Optional[str]) โ€“ Preferred storage provider

  • **kwargs โ€“ Storage parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

Search across multiple providers intelligently.

Parameters:
  • query (Union[str, List[float], Dict]) โ€“ Search query (text, vector, or structured)

  • providers (Optional[List[str]]) โ€“ Providers to search (defaults to all suitable)

  • **kwargs โ€“ Search parameters

Return type:

List[StorageResult]

Returns:

List of StorageResult from different providers

create_data_reference(provider, resource, **metadata)[source]๏ƒ

Create a data reference for spore communication.

Parameters:
  • provider (str) โ€“ Storage provider name

  • resource (str) โ€“ Resource identifier

  • **metadata โ€“ Additional metadata

Return type:

DataReference

Returns:

DataReference object

async resolve_data_reference(data_ref, **kwargs)[source]๏ƒ

Resolve a data reference to actual data.

Parameters:
  • data_ref (Union[DataReference, str]) โ€“ DataReference object or URI string

  • **kwargs โ€“ Retrieval parameters

Return type:

StorageResult

Returns:

StorageResult with resolved data

async batch_store(operations)[source]๏ƒ

Execute multiple store operations in batch.

Parameters:

operations (List[Dict[str, Any]]) โ€“ List of operation dictionaries with keys: - provider: Storage provider name - resource: Resource identifier - data: Data to store - kwargs: Additional parameters

Return type:

List[StorageResult]

Returns:

List of StorageResult objects

async batch_get(operations)[source]๏ƒ

Execute multiple get operations in batch.

Parameters:

operations (List[Dict[str, Any]]) โ€“ List of operation dictionaries with keys: - provider: Storage provider name - resource: Resource identifier - kwargs: Additional parameters

Return type:

List[StorageResult]

Returns:

List of StorageResult objects

list_providers(storage_type=None)[source]๏ƒ

List available storage providers.

Parameters:

storage_type (Optional[str]) โ€“ Filter by storage type

Return type:

List[str]

Returns:

List of provider names

get_provider_info(provider)[source]๏ƒ

Get information about a storage provider.

Parameters:

provider (str) โ€“ Storage provider name

Return type:

Dict[str, Any]

Returns:

Provider information dictionary

async health_check(provider=None)[source]๏ƒ

Perform health check on providers.

Parameters:

provider (Optional[str]) โ€“ Specific provider to check (None for all)

Return type:

Dict[str, Any]

Returns:

Health check results

praval.storage.data_manager.get_data_manager()[source]๏ƒ

Get the global data manager instance.

Return type:

DataManager

async praval.storage.data_manager.store_data(provider, resource, data, **kwargs)[source]๏ƒ

Store data using the global data manager.

Return type:

StorageResult

Parameters:
async praval.storage.data_manager.get_data(provider, resource, **kwargs)[source]๏ƒ

Retrieve data using the global data manager.

Return type:

StorageResult

Parameters:
  • provider (str)

  • resource (str)

async praval.storage.data_manager.query_data(provider, resource, query, **kwargs)[source]๏ƒ

Query data using the global data manager.

Return type:

StorageResult

Parameters:
async praval.storage.data_manager.delete_data(provider, resource, **kwargs)[source]๏ƒ

Delete data using the global data manager.

Return type:

StorageResult

Parameters:
  • provider (str)

  • resource (str)

Base Storage Provider Framework

Defines the core interfaces and base classes for all Praval storage providers. This provides a standardized way to create, register, and use storage backends that agents can access uniformly.

class praval.storage.base_provider.StorageType(*values)[source]๏ƒ

Bases: Enum

Types of storage backends

RELATIONAL = 'relational'๏ƒ
DOCUMENT = 'document'๏ƒ
KEY_VALUE = 'key_value'๏ƒ
OBJECT = 'object'๏ƒ
VECTOR = 'vector'๏ƒ
SEARCH = 'search'๏ƒ
GRAPH = 'graph'๏ƒ
FILE_SYSTEM = 'file_system'๏ƒ
CACHE = 'cache'๏ƒ
QUEUE = 'queue'๏ƒ
class praval.storage.base_provider.DataReference(provider, storage_type, resource_id, metadata=<factory>, created_at=<factory>, expires_at=None)[source]๏ƒ

Bases: object

Reference to data stored in a backend

Parameters:
provider: str๏ƒ
storage_type: StorageType๏ƒ
resource_id: str๏ƒ
metadata: Dict[str, Any]๏ƒ
created_at: datetime๏ƒ
expires_at: Optional[datetime] = None๏ƒ
to_uri()[source]๏ƒ

Convert to URI format for spore communication

Return type:

str

classmethod from_uri(uri)[source]๏ƒ

Create DataReference from URI

Return type:

DataReference

Parameters:

uri (str)

is_expired()[source]๏ƒ

Check if reference has expired

Return type:

bool

__init__(provider, storage_type, resource_id, metadata=<factory>, created_at=<factory>, expires_at=None)๏ƒ
Parameters:
Return type:

None

class praval.storage.base_provider.StorageQuery(operation, resource, parameters=<factory>, filters=<factory>, limit=None, offset=None, timeout=None)[source]๏ƒ

Bases: object

Query parameters for storage operations

Parameters:
operation: str๏ƒ
resource: str๏ƒ
parameters: Dict[str, Any]๏ƒ
filters: Dict[str, Any]๏ƒ
limit: Optional[int] = None๏ƒ
offset: Optional[int] = None๏ƒ
timeout: Optional[float] = None๏ƒ
__init__(operation, resource, parameters=<factory>, filters=<factory>, limit=None, offset=None, timeout=None)๏ƒ
Parameters:
Return type:

None

class praval.storage.base_provider.StorageResult(success, data=None, error=None, execution_time=0.0, metadata=<factory>, data_reference=None, timestamp=<factory>)[source]๏ƒ

Bases: object

Result from storage operation

Parameters:
success: bool๏ƒ
data: Any = None๏ƒ
error: Optional[str] = None๏ƒ
execution_time: float = 0.0๏ƒ
metadata: Dict[str, Any]๏ƒ
data_reference: Optional[DataReference] = None๏ƒ
timestamp: datetime๏ƒ
__init__(success, data=None, error=None, execution_time=0.0, metadata=<factory>, data_reference=None, timestamp=<factory>)๏ƒ
Parameters:
Return type:

None

class praval.storage.base_provider.StorageMetadata(name, description, storage_type, version='1.0.0', supports_async=True, supports_transactions=False, supports_schemas=False, supports_indexing=False, supports_search=False, supports_streaming=False, max_connection_pool=10, default_timeout=30.0, required_config=<factory>, optional_config=<factory>, connection_string_template=None)[source]๏ƒ

Bases: object

Metadata describing a storage providerโ€™s capabilities

Parameters:
  • name (str)

  • description (str)

  • storage_type (StorageType)

  • version (str)

  • supports_async (bool)

  • supports_transactions (bool)

  • supports_schemas (bool)

  • supports_indexing (bool)

  • supports_search (bool)

  • supports_streaming (bool)

  • max_connection_pool (int)

  • default_timeout (float)

  • required_config (List[str])

  • optional_config (List[str])

  • connection_string_template (str | None)

name: str๏ƒ
description: str๏ƒ
storage_type: StorageType๏ƒ
version: str = '1.0.0'๏ƒ
supports_async: bool = True๏ƒ
supports_transactions: bool = False๏ƒ
supports_schemas: bool = False๏ƒ
supports_indexing: bool = False๏ƒ
supports_streaming: bool = False๏ƒ
max_connection_pool: int = 10๏ƒ
default_timeout: float = 30.0๏ƒ
required_config: List[str]๏ƒ
optional_config: List[str]๏ƒ
connection_string_template: Optional[str] = None๏ƒ
__init__(name, description, storage_type, version='1.0.0', supports_async=True, supports_transactions=False, supports_schemas=False, supports_indexing=False, supports_search=False, supports_streaming=False, max_connection_pool=10, default_timeout=30.0, required_config=<factory>, optional_config=<factory>, connection_string_template=None)๏ƒ
Parameters:
  • name (str)

  • description (str)

  • storage_type (StorageType)

  • version (str)

  • supports_async (bool)

  • supports_transactions (bool)

  • supports_schemas (bool)

  • supports_indexing (bool)

  • supports_search (bool)

  • supports_streaming (bool)

  • max_connection_pool (int)

  • default_timeout (float)

  • required_config (List[str])

  • optional_config (List[str])

  • connection_string_template (str | None)

Return type:

None

class praval.storage.base_provider.BaseStorageProvider(name, config)[source]๏ƒ

Bases: ABC

Abstract base class for all storage providers.

All storage backends must inherit from this class and implement the required methods. This ensures a consistent interface across all storage types while allowing for provider-specific optimizations.

Parameters:
__init__(name, config)[source]๏ƒ

Initialize the storage provider.

Parameters:
  • name (str) โ€“ Unique name for this provider instance

  • config (Dict[str, Any]) โ€“ Provider-specific configuration

abstractmethod async connect()[source]๏ƒ

Establish connection to the storage backend.

Return type:

bool

Returns:

True if connection successful, False otherwise

abstractmethod async disconnect()[source]๏ƒ

Close connection to the storage backend.

abstractmethod async store(resource, data, **kwargs)[source]๏ƒ

Store data in the backend.

Parameters:
  • resource (str) โ€“ Resource identifier (table, bucket, key, etc.)

  • data (Any) โ€“ Data to store

  • **kwargs โ€“ Provider-specific parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

abstractmethod async retrieve(resource, **kwargs)[source]๏ƒ

Retrieve data from the backend.

Parameters:
  • resource (str) โ€“ Resource identifier

  • **kwargs โ€“ Provider-specific parameters

Return type:

StorageResult

Returns:

StorageResult with retrieved data

abstractmethod async query(resource, query, **kwargs)[source]๏ƒ

Execute a query against the backend.

Parameters:
  • resource (str) โ€“ Resource to query

  • query (Union[str, Dict]) โ€“ Query string or structured query

  • **kwargs โ€“ Provider-specific parameters

Return type:

StorageResult

Returns:

StorageResult with query results

abstractmethod async delete(resource, **kwargs)[source]๏ƒ

Delete data from the backend.

Parameters:
  • resource (str) โ€“ Resource to delete

  • **kwargs โ€“ Provider-specific parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async exists(resource, **kwargs)[source]๏ƒ

Check if a resource exists.

Parameters:
  • resource (str) โ€“ Resource to check

  • **kwargs โ€“ Provider-specific parameters

Return type:

bool

Returns:

True if resource exists, False otherwise

async list_resources(prefix='', **kwargs)[source]๏ƒ

List available resources.

Parameters:
  • prefix (str) โ€“ Resource prefix to filter by

  • **kwargs โ€“ Provider-specific parameters

Return type:

StorageResult

Returns:

StorageResult with list of resources

async safe_execute(operation, *args, **kwargs)[source]๏ƒ

Execute operation with error handling and timing.

Parameters:
  • operation (str) โ€“ Operation name

  • *args โ€“ Operation parameters

  • **kwargs โ€“

    Operation parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

get_schema()[source]๏ƒ

Get provider schema/capabilities.

Return type:

Dict[str, Any]

async health_check()[source]๏ƒ

Perform health check on the storage backend.

Return type:

Dict[str, Any]

praval.storage.base_provider.create_storage_provider(provider_class, name, config)[source]๏ƒ

Create a storage provider instance.

Parameters:
Return type:

BaseStorageProvider

Returns:

Configured provider instance

Storage Registry System

Provides centralized registration, discovery, and management of storage providers available to Praval agents. This follows the same pattern as the tool registry for consistent framework design.

class praval.storage.storage_registry.StorageRegistry[source]๏ƒ

Bases: object

Central registry for managing storage providers available to agents.

Features: - Provider registration and discovery - Type-based organization (relational, object, vector, etc.) - Access control and permissions - Connection pooling and lifecycle management - Usage statistics and health monitoring - Multi-provider query routing

__init__()[source]๏ƒ
async register_provider(provider, replace_existing=False, permissions=None, auto_connect=None)[source]๏ƒ

Register a storage provider in the registry.

Parameters:
  • provider (BaseStorageProvider) โ€“ Provider instance to register

  • replace_existing (bool) โ€“ Whether to replace existing provider with same name

  • permissions (Optional[List[str]]) โ€“ List of agent names allowed to use this provider

  • auto_connect (bool) โ€“ Whether to auto-connect the provider

Return type:

bool

Returns:

True if registration successful, False otherwise

async unregister_provider(provider_name)[source]๏ƒ

Unregister a provider from the registry.

Parameters:

provider_name (str) โ€“ Name of provider to unregister

Return type:

bool

Returns:

True if unregistration successful, False if provider not found

get_provider(provider_name, agent_name=None)[source]๏ƒ

Get a provider by name with permission checking.

Parameters:
  • provider_name (str) โ€“ Name of the provider to retrieve

  • agent_name (str) โ€“ Name of the agent requesting the provider

Return type:

BaseStorageProvider

Returns:

BaseStorageProvider instance

Raises:
  • StorageNotFoundError โ€“ If provider not found

  • StoragePermissionError โ€“ If agent lacks permission

list_providers(storage_type=None, agent_name=None, connected_only=False)[source]๏ƒ

List available providers with optional filtering.

Parameters:
  • storage_type (Optional[StorageType]) โ€“ Filter by storage type

  • agent_name (Optional[str]) โ€“ Filter by agent permissions

  • connected_only (bool) โ€“ Only return connected providers

Return type:

List[str]

Returns:

List of provider names

get_providers_by_type(storage_type)[source]๏ƒ

Get all providers of a specific storage type.

Return type:

List[str]

Parameters:

storage_type (StorageType)

get_storage_types()[source]๏ƒ

Get list of all available storage types.

Return type:

List[StorageType]

async execute_query(provider_name, query, agent_name=None)[source]๏ƒ

Execute a query on a specific provider.

Parameters:
  • provider_name (str) โ€“ Name of provider to query

  • query (StorageQuery) โ€“ Query to execute

  • agent_name (Optional[str]) โ€“ Name of requesting agent

Return type:

StorageResult

Returns:

StorageResult with query outcome

async health_check_all()[source]๏ƒ

Perform health checks on all registered providers.

Return type:

Dict[str, Dict[str, Any]]

get_usage_stats(provider_name=None)[source]๏ƒ

Get usage statistics for providers.

Return type:

Union[Dict[str, Any], Dict[str, Dict[str, Any]]]

Parameters:

provider_name (str | None)

get_registry_info()[source]๏ƒ

Get comprehensive information about the registry.

Return type:

Dict[str, Any]

set_permissions(provider_name, agent_names)[source]๏ƒ

Set permissions for a provider.

Parameters:
add_permission(provider_name, agent_name)[source]๏ƒ

Add permission for an agent to use a provider.

Parameters:
  • provider_name (str)

  • agent_name (str)

remove_permission(provider_name, agent_name)[source]๏ƒ

Remove permission for an agent to use a provider.

Parameters:
  • provider_name (str)

  • agent_name (str)

block_provider(provider_name)[source]๏ƒ

Block a provider from being used.

Parameters:

provider_name (str)

unblock_provider(provider_name)[source]๏ƒ

Unblock a previously blocked provider.

Parameters:

provider_name (str)

async cleanup_registry()[source]๏ƒ

Clean up disconnected providers and expired data.

praval.storage.storage_registry.get_storage_registry()[source]๏ƒ

Get the global storage registry instance.

Return type:

StorageRegistry

async praval.storage.storage_registry.register_storage_provider(provider, **kwargs)[source]๏ƒ

Register a storage provider in the global registry.

Return type:

bool

Parameters:

provider (BaseStorageProvider)

praval.storage.storage_registry.get_storage_provider(provider_name, agent_name=None)[source]๏ƒ

Get a storage provider from the global registry.

Return type:

BaseStorageProvider

Parameters:
  • provider_name (str)

  • agent_name (str)

praval.storage.storage_registry.list_storage_providers(**kwargs)[source]๏ƒ

List available storage providers from the global registry.

Return type:

List[str]

Storage decorators for Praval agents

Provides decorator-based integration between agents and storage providers, following the same patterns as the agent and tool decorators.

praval.storage.decorators.storage_enabled(providers=None, auto_register=True, permissions=None, **default_configs)[source]๏ƒ

Decorator to enable storage access for agent functions.

Parameters:
  • providers (Union[str, List[str], Dict[str, Dict[str, Any]], None]) โ€“ Storage providers to enable. Can be: - String: Single provider name - List: Multiple provider names - Dict: Provider name -> configuration mapping

  • auto_register (bool) โ€“ Whether to auto-register providers from environment

  • permissions (Optional[List[str]]) โ€“ Default permissions for storage access

  • **default_configs โ€“ Default configurations for providers

Examples

@storage_enabled(โ€œpostgresโ€) @agent(โ€œdata_analystโ€) def analyze_data(spore):

data = storage.query(โ€œpostgresโ€, โ€œSELECT * FROM customersโ€)

@storage_enabled([โ€œpostgresโ€, โ€œs3โ€, โ€œredisโ€]) @agent(โ€œbusiness_intelligenceโ€) def generate_report(spore):

# Access multiple storage backends pass

@storage_enabled({

โ€œpostgresโ€: {โ€œhostโ€: โ€œlocalhostโ€, โ€œdatabaseโ€: โ€œbusinessโ€}, โ€œs3โ€: {โ€œbucket_nameโ€: โ€œreportsโ€}

}) @agent(โ€œreport_generatorโ€) def create_analysis(spore):

pass

praval.storage.decorators.requires_storage(*provider_names, permissions=None)[source]๏ƒ

Decorator to require specific storage providers for a function.

Parameters:
  • *provider_names (str) โ€“ Names of required storage providers

  • permissions (Optional[List[str]]) โ€“ Required permissions for storage access

Example

@requires_storage(โ€œpostgresโ€, โ€œs3โ€) @agent(โ€œdata_processorโ€) def process_customer_data(spore):

# Function requires both postgres and s3 to be available pass

Storage Providers๏ƒ

File system storage provider for Praval framework

Provides local file system storage capabilities with path management, directory operations, and file metadata support.

class praval.storage.providers.filesystem.FileSystemProvider(name, config)[source]๏ƒ

Bases: BaseStorageProvider

Local file system storage provider.

Features: - File and directory operations - Path management and validation - File metadata and permissions - Recursive operations - Pattern-based file listing - Atomic file operations

Parameters:
async connect()[source]๏ƒ

Verify file system access.

Return type:

bool

async disconnect()[source]๏ƒ

No explicit disconnection needed for file system.

async store(resource, data, **kwargs)[source]๏ƒ

Store data to file system.

Parameters:
  • resource (str) โ€“ File path relative to base_path

  • data (Any) โ€“ Data to store (string, bytes, dict/list for JSON, or file-like object)

  • **kwargs โ€“ File parameters (encoding, mode, etc.)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async retrieve(resource, **kwargs)[source]๏ƒ

Retrieve data from file system.

Parameters:
  • resource (str) โ€“ File path relative to base_path

  • **kwargs โ€“ Read parameters (encoding, decode_json, etc.)

Return type:

StorageResult

Returns:

StorageResult with retrieved data

async query(resource, query, **kwargs)[source]๏ƒ

Execute file system operations.

Parameters:
  • resource (str) โ€“ Path or pattern

  • query (Union[str, Dict]) โ€“ Query type (โ€œlistโ€, โ€œfindโ€, โ€œmetadataโ€, etc.)

  • **kwargs โ€“ Query parameters

Return type:

StorageResult

Returns:

StorageResult with query results

async delete(resource, **kwargs)[source]๏ƒ

Delete file or directory from file system.

Parameters:
  • resource (str) โ€“ Path to delete

  • **kwargs โ€“ Delete parameters (recursive, etc.)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async list_resources(prefix='', **kwargs)[source]๏ƒ

List files and directories.

Return type:

StorageResult

Parameters:

prefix (str)

PostgreSQL storage provider for Praval framework

Provides relational database capabilities with SQL query support, transactions, and schema management.

class praval.storage.providers.postgresql.PostgreSQLProvider(name, config)[source]๏ƒ

Bases: BaseStorageProvider

PostgreSQL storage provider with async connection pooling.

Features: - Async connection pooling - SQL query execution - Transaction support - Schema management - JSON column support - Full-text search capabilities

Parameters:
async connect()[source]๏ƒ

Establish connection pool to PostgreSQL.

Return type:

bool

async disconnect()[source]๏ƒ

Close connection pool.

async store(resource, data, **kwargs)[source]๏ƒ

Store data in PostgreSQL table.

Parameters:
  • resource (str) โ€“ Table name

  • data (Any) โ€“ Data to store (dict or list of dicts)

  • **kwargs โ€“ Additional parameters (upsert, returning, etc.)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async retrieve(resource, **kwargs)[source]๏ƒ

Retrieve data from PostgreSQL table.

Parameters:
  • resource (str) โ€“ Table name

  • **kwargs โ€“ Query parameters (where, limit, offset, order_by, etc.)

Return type:

StorageResult

Returns:

StorageResult with retrieved data

async query(resource, query, **kwargs)[source]๏ƒ

Execute SQL query against PostgreSQL.

Parameters:
  • resource (str) โ€“ Table name (ignored for raw SQL)

  • query (Union[str, Dict]) โ€“ SQL query string or structured query dict

  • **kwargs โ€“ Query parameters

Return type:

StorageResult

Returns:

StorageResult with query results

async delete(resource, **kwargs)[source]๏ƒ

Delete data from PostgreSQL table.

Parameters:
  • resource (str) โ€“ Table name

  • **kwargs โ€“ Delete parameters (where clause required)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async list_resources(prefix='', **kwargs)[source]๏ƒ

List tables in the database.

Return type:

StorageResult

Parameters:

prefix (str)

Redis storage provider for Praval framework

Provides key-value storage, caching, and pub/sub capabilities with Redis backend.

class praval.storage.providers.redis_provider.RedisProvider(name, config)[source]๏ƒ

Bases: BaseStorageProvider

Redis key-value storage provider with async support.

Features: - Key-value operations (GET, SET, DEL) - Hash operations (HGET, HSET, HGETALL) - List operations (LPUSH, RPUSH, LRANGE) - Set operations (SADD, SMEMBERS) - Expiration and TTL management - Pub/Sub messaging - Lua script execution

Parameters:
async connect()[source]๏ƒ

Establish connection to Redis.

Return type:

bool

async disconnect()[source]๏ƒ

Close Redis connection.

async store(resource, data, **kwargs)[source]๏ƒ

Store data in Redis.

Parameters:
  • resource (str) โ€“ Redis key

  • data (Any) โ€“ Data to store (will be JSON serialized if not string)

  • **kwargs โ€“ Redis parameters (ex, px, nx, xx, etc.)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async retrieve(resource, **kwargs)[source]๏ƒ

Retrieve data from Redis.

Parameters:
  • resource (str) โ€“ Redis key

  • **kwargs โ€“ Additional parameters (decode_json, etc.)

Return type:

StorageResult

Returns:

StorageResult with retrieved data

async query(resource, query, **kwargs)[source]๏ƒ

Execute Redis operations or search queries.

Parameters:
  • resource (str) โ€“ Pattern or specific key

  • query (Union[str, Dict]) โ€“ Query type or Redis command

  • **kwargs โ€“ Query parameters

Return type:

StorageResult

Returns:

StorageResult with query results

async delete(resource, **kwargs)[source]๏ƒ

Delete keys from Redis.

Parameters:
  • resource (str) โ€“ Key or pattern to delete

  • **kwargs โ€“ Delete parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async list_resources(prefix='', **kwargs)[source]๏ƒ

List keys in Redis.

Return type:

StorageResult

Parameters:

prefix (str)

S3 object storage provider for Praval framework

Provides object storage capabilities with S3-compatible backends including AWS S3, MinIO, and other S3-compatible services.

class praval.storage.providers.s3_provider.S3Provider(name, config)[source]๏ƒ

Bases: BaseStorageProvider

S3-compatible object storage provider.

Features: - Object upload, download, and deletion - Bucket management - Presigned URLs for secure access - Metadata and tagging support - Multipart uploads for large files - Lifecycle management - Cross-region replication support

Parameters:
async connect()[source]๏ƒ

Establish connection to S3.

Return type:

bool

async disconnect()[source]๏ƒ

Close S3 connection.

async store(resource, data, **kwargs)[source]๏ƒ

Store object in S3.

Parameters:
  • resource (str) โ€“ S3 object key

  • data (Any) โ€“ Data to store (bytes, string, file-like object, or dict/list for JSON)

  • **kwargs โ€“ S3 parameters (content_type, metadata, acl, etc.)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async retrieve(resource, **kwargs)[source]๏ƒ

Retrieve object from S3.

Parameters:
  • resource (str) โ€“ S3 object key

  • **kwargs โ€“ Retrieval parameters (range, decode_json, etc.)

Return type:

StorageResult

Returns:

StorageResult with retrieved data

async query(resource, query, **kwargs)[source]๏ƒ

Execute S3 operations or list objects.

Parameters:
  • resource (str) โ€“ Prefix or specific key

  • query (Union[str, Dict]) โ€“ Query type (โ€œlistโ€, โ€œsearchโ€, โ€œmetadataโ€, etc.)

  • **kwargs โ€“ Query parameters

Return type:

StorageResult

Returns:

StorageResult with query results

async delete(resource, **kwargs)[source]๏ƒ

Delete object(s) from S3.

Parameters:
  • resource (str) โ€“ Object key or prefix

  • **kwargs โ€“ Delete parameters (recursive, etc.)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async list_resources(prefix='', **kwargs)[source]๏ƒ

List objects in S3 bucket.

Return type:

StorageResult

Parameters:

prefix (str)

Qdrant vector storage provider for Praval framework

Integrates with existing Praval memory system to provide vector storage capabilities through the storage framework.

class praval.storage.providers.qdrant_provider.QdrantProvider(name, config)[source]๏ƒ

Bases: BaseStorageProvider

Qdrant vector database storage provider.

Features: - Vector similarity search - Collection management - Point insertion and retrieval - Filtering and metadata search - Batch operations - Integration with Praval memory system

Parameters:
async connect()[source]๏ƒ

Establish connection to Qdrant.

Return type:

bool

async disconnect()[source]๏ƒ

Close Qdrant connection.

async store(resource, data, **kwargs)[source]๏ƒ

Store vector data in Qdrant.

Parameters:
  • resource (str) โ€“ Collection name (optional, uses default if not specified)

  • data (Any) โ€“ Data to store - can be: - Single point: {โ€œidโ€: โ€œโ€ฆโ€, โ€œvectorโ€: [โ€ฆ], โ€œpayloadโ€: {โ€ฆ}} - Multiple points: [{โ€œidโ€: โ€œโ€ฆโ€, โ€œvectorโ€: [โ€ฆ], โ€œpayloadโ€: {โ€ฆ}}, โ€ฆ] - Just vector: [0.1, 0.2, โ€ฆ] (will generate ID)

  • **kwargs โ€“ Additional parameters

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async retrieve(resource, **kwargs)[source]๏ƒ

Retrieve vectors from Qdrant.

Parameters:
  • resource (str) โ€“ Collection name or โ€œcollection:point_idโ€

  • **kwargs โ€“ Retrieval parameters (point_ids, with_vectors, with_payload)

Return type:

StorageResult

Returns:

StorageResult with retrieved data

async query(resource, query, **kwargs)[source]๏ƒ

Execute vector search or other operations.

Parameters:
  • resource (str) โ€“ Collection name

  • query (Union[str, Dict]) โ€“ Query type or search vector

  • **kwargs โ€“ Query parameters

Return type:

StorageResult

Returns:

StorageResult with query results

async delete(resource, **kwargs)[source]๏ƒ

Delete points from Qdrant.

Parameters:
  • resource (str) โ€“ Collection name or โ€œcollection:point_idโ€

  • **kwargs โ€“ Delete parameters (point_ids, filter)

Return type:

StorageResult

Returns:

StorageResult with operation outcome

async list_resources(prefix='', **kwargs)[source]๏ƒ

List collections in Qdrant.

Return type:

StorageResult

Parameters:

prefix (str)

Tool Module๏ƒ

Tool decorator and utilities for Praval Framework.

This module provides the @tool decorator for creating tools that can be registered and used by agents. Tools are automatically registered in the global tool registry and can be associated with specific agents.

praval.tools.tool(tool_name=None, owned_by=None, description=None, category='general', shared=False, version='1.0.0', author='', tags=None)[source]๏ƒ

Decorator to register a function as a tool in the Praval framework.

The @tool decorator automatically registers functions as tools that can be used by agents. Tools can be owned by specific agents, shared across all agents, or organized by category.

Parameters:
  • tool_name (Optional[str]) โ€“ Name of the tool (defaults to function name)

  • owned_by (Optional[str]) โ€“ Agent that owns this tool

  • description (Optional[str]) โ€“ Description of what the tool does (defaults to docstring)

  • category (str) โ€“ Category for organizing tools

  • shared (bool) โ€“ Whether this tool is available to all agents

  • version (str) โ€“ Version of the tool

  • author (str) โ€“ Author of the tool

  • tags (Optional[List[str]]) โ€“ Tags for tool discovery

Return type:

Callable

Returns:

Decorated function with tool metadata attached

Raises:

ToolError โ€“ If tool registration fails or validation errors occur

Examples

Basic tool owned by specific agent: ```python @tool(โ€œadd_numbersโ€, owned_by=โ€calculatorโ€) def add(x: float, y: float) -> float:

โ€˜โ€™โ€™Add two numbers together.โ€™โ€™โ€™ return x + y

```

Shared tool available to all agents: ```python @tool(โ€œloggerโ€, shared=True, category=โ€utilityโ€) def log_message(level: str, message: str) -> str:

โ€˜โ€™โ€™Log a message at the specified level.โ€™โ€™โ€™ import logging logger = logging.getLogger(โ€œpraval.toolsโ€) getattr(logger, level.lower())(message) return fโ€Logged: {message}โ€

```

Tool with metadata: ```python @tool(

โ€œvalidate_emailโ€, owned_by=โ€data_processorโ€, category=โ€validationโ€, tags=[โ€œemailโ€, โ€œvalidationโ€, โ€œdataโ€], version=โ€2.0.0โ€, author=โ€Praval Teamโ€

) def validate_email(email: str) -> bool:

โ€˜โ€™โ€™Validate email address format.โ€™โ€™โ€™ import re pattern = rโ€™^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$โ€™ return bool(re.match(pattern, email))

```

praval.tools.get_tool_info(tool_func)[source]๏ƒ

Get information about a @tool decorated function.

Parameters:

tool_func (Callable) โ€“ Function decorated with @tool

Return type:

dict

Returns:

Dictionary with tool metadata

Raises:

ValueError โ€“ If function is not decorated with @tool

praval.tools.is_tool(func)[source]๏ƒ

Check if a function is decorated with @tool.

Parameters:

func (Callable) โ€“ Function to check

Return type:

bool

Returns:

True if function is a tool, False otherwise

praval.tools.discover_tools(module=None, pattern=None, category=None)[source]๏ƒ

Discover tools based on various criteria.

Parameters:
  • module (Optional[str]) โ€“ Module name to search for tools

  • pattern (Optional[str]) โ€“ File pattern to search (e.g., โ€œ*_tool.pyโ€)

  • category (Optional[str]) โ€“ Category to filter by

Return type:

List[Tool]

Returns:

List of discovered Tool instances

praval.tools.list_tools(agent_name=None, category=None, shared_only=False)[source]๏ƒ

List tools with optional filtering.

Parameters:
  • agent_name (Optional[str]) โ€“ Filter by agent owner

  • category (Optional[str]) โ€“ Filter by category

  • shared_only (bool) โ€“ Only show shared tools

Return type:

List[dict]

Returns:

List of tool information dictionaries

praval.tools.register_tool_with_agent(tool_name, agent_name)[source]๏ƒ

Register an existing tool with an agent at runtime.

Parameters:
  • tool_name (str) โ€“ Name of the tool to register

  • agent_name (str) โ€“ Name of the agent to register with

Return type:

bool

Returns:

True if registration successful, False otherwise

praval.tools.unregister_tool_from_agent(tool_name, agent_name)[source]๏ƒ

Unregister a tool from an agent at runtime.

Parameters:
  • tool_name (str) โ€“ Name of the tool to unregister

  • agent_name (str) โ€“ Name of the agent to unregister from

Return type:

bool

Returns:

True if unregistration successful, False otherwise

class praval.tools.ToolCollection(name, description='')[source]๏ƒ

Bases: object

A collection of related tools that can be managed as a group.

Useful for organizing tools by functionality or creating tool suites that can be easily assigned to agents.

Parameters:
  • name (str)

  • description (str)

__init__(name, description='')[source]๏ƒ

Initialize a tool collection.

Parameters:
  • name (str) โ€“ Name of the collection

  • description (str) โ€“ Description of the collection

add_tool(tool_name)[source]๏ƒ

Add a tool to the collection.

Parameters:

tool_name (str) โ€“ Name of the tool to add

Raises:

ToolError โ€“ If tool doesnโ€™t exist

Return type:

None

remove_tool(tool_name)[source]๏ƒ

Remove a tool from the collection.

Parameters:

tool_name (str) โ€“ Name of the tool to remove

Return type:

bool

Returns:

True if removal successful, False if tool wasnโ€™t in collection

assign_to_agent(agent_name)[source]๏ƒ

Assign all tools in the collection to an agent.

Parameters:

agent_name (str) โ€“ Name of the agent to assign tools to

Return type:

int

Returns:

Number of tools successfully assigned

get_tools()[source]๏ƒ

Get all tools in the collection.

Return type:

List[Tool]

Returns:

List of Tool instances in the collection

Tool Registry for Praval Framework.

This module provides a centralized registry for managing tools and their relationships to agents. Tools can be registered, discovered, and assigned to agents dynamically.

class praval.core.tool_registry.ToolMetadata(tool_name, owned_by=None, description='', category='general', shared=False, version='1.0.0', author='', tags=<factory>, parameters=<factory>, return_type='Any')[source]๏ƒ

Bases: object

Metadata for a registered tool.

Parameters:
tool_name: str๏ƒ
owned_by: Optional[str] = None๏ƒ
description: str = ''๏ƒ
category: str = 'general'๏ƒ
shared: bool = False๏ƒ
version: str = '1.0.0'๏ƒ
author: str = ''๏ƒ
tags: List[str]๏ƒ
parameters: Dict[str, Any]๏ƒ
return_type: str = 'Any'๏ƒ
__init__(tool_name, owned_by=None, description='', category='general', shared=False, version='1.0.0', author='', tags=<factory>, parameters=<factory>, return_type='Any')๏ƒ
Parameters:
Return type:

None

class praval.core.tool_registry.Tool(func, metadata)[source]๏ƒ

Bases: object

Wrapper class for a registered tool function.

Provides metadata, validation, and execution capabilities for functions registered as tools in the Praval framework.

Parameters:
__init__(func, metadata)[source]๏ƒ

Initialize a Tool instance.

Parameters:
  • func (Callable) โ€“ The function to wrap as a tool

  • metadata (ToolMetadata) โ€“ Metadata describing the tool

Raises:

ToolError โ€“ If function validation fails

execute(*args, **kwargs)[source]๏ƒ

Execute the tool function with given arguments.

Parameters:
  • *args โ€“ Positional arguments for the tool function

  • **kwargs โ€“ Keyword arguments for the tool function

Return type:

Any

Returns:

Result of tool function execution

Raises:

ToolError โ€“ If execution fails

to_dict()[source]๏ƒ

Convert tool to dictionary representation for serialization.

Return type:

Dict[str, Any]

class praval.core.tool_registry.ToolRegistry[source]๏ƒ

Bases: object

Centralized registry for managing tools and their relationships to agents.

The registry provides functionality to: - Register and retrieve tools - Associate tools with agents - Manage shared tools - Query tools by category - Handle tool lifecycle

__init__()[source]๏ƒ

Initialize the tool registry.

register_tool(tool)[source]๏ƒ

Register a tool in the registry.

Parameters:

tool (Tool) โ€“ Tool instance to register

Raises:

ToolError โ€“ If tool name already exists or registration fails

Return type:

None

get_tool(tool_name)[source]๏ƒ

Retrieve a tool by name.

Parameters:

tool_name (str) โ€“ Name of the tool to retrieve

Return type:

Optional[Tool]

Returns:

Tool instance if found, None otherwise

get_tools_for_agent(agent_name)[source]๏ƒ

Get all tools available to a specific agent.

This includes: - Tools owned by the agent - Shared tools - Tools explicitly assigned to the agent

Parameters:

agent_name (str) โ€“ Name of the agent

Return type:

List[Tool]

Returns:

List of Tool instances available to the agent

get_tools_by_category(category)[source]๏ƒ

Get all tools in a specific category.

Parameters:

category (str) โ€“ Category name

Return type:

List[Tool]

Returns:

List of Tool instances in the category

get_shared_tools()[source]๏ƒ

Get all shared tools.

Return type:

List[Tool]

Returns:

List of all shared Tool instances

list_all_tools()[source]๏ƒ

List all registered tools.

Return type:

List[Tool]

Returns:

List of all Tool instances

assign_tool_to_agent(tool_name, agent_name)[source]๏ƒ

Assign a tool to an agent at runtime.

Parameters:
  • tool_name (str) โ€“ Name of the tool to assign

  • agent_name (str) โ€“ Name of the agent to assign to

Return type:

bool

Returns:

True if assignment successful, False if tool doesnโ€™t exist

remove_tool_from_agent(tool_name, agent_name)[source]๏ƒ

Remove a tool assignment from an agent.

Parameters:
  • tool_name (str) โ€“ Name of the tool to remove

  • agent_name (str) โ€“ Name of the agent to remove from

Return type:

bool

Returns:

True if removal successful, False if assignment didnโ€™t exist

unregister_tool(tool_name)[source]๏ƒ

Unregister a tool from the registry.

Parameters:

tool_name (str) โ€“ Name of the tool to unregister

Return type:

bool

Returns:

True if unregistration successful, False if tool didnโ€™t exist

clear_registry()[source]๏ƒ

Clear all tools from the registry.

Return type:

None

get_registry_stats()[source]๏ƒ

Get statistics about the registry.

Return type:

Dict[str, Any]

Returns:

Dictionary with registry statistics

search_tools(name_pattern=None, category=None, owned_by=None, shared_only=False, tags=None)[source]๏ƒ

Search for tools based on multiple criteria.

Parameters:
  • name_pattern (Optional[str]) โ€“ Pattern to match in tool names (case-insensitive)

  • category (Optional[str]) โ€“ Specific category to filter by

  • owned_by (Optional[str]) โ€“ Specific owner to filter by

  • shared_only (bool) โ€“ Only return shared tools

  • tags (Optional[List[str]]) โ€“ Tags that tools must have (any match)

Return type:

List[Tool]

Returns:

List of Tool instances matching the criteria

praval.core.tool_registry.get_tool_registry()[source]๏ƒ

Get the global tool registry instance.

Return type:

ToolRegistry

Returns:

Global ToolRegistry instance

praval.core.tool_registry.reset_tool_registry()[source]๏ƒ

Reset the global tool registry (primarily for testing).

Warning: This will clear all registered tools.

Return type:

None

Providers Module๏ƒ

Factory for creating LLM provider instances.

Provides a unified interface for instantiating different LLM providers with consistent configuration handling.

class praval.providers.factory.ProviderFactory[source]๏ƒ

Bases: object

Factory class for creating LLM provider instances.

static create_provider(provider_name, config)[source]๏ƒ

Create an LLM provider instance.

Parameters:
  • provider_name (str) โ€“ Name of the provider (openai, anthropic, cohere)

  • config (Any) โ€“ Configuration object for the provider

Returns:

Provider instance

Raises:

ProviderError โ€“ If provider is not supported or creation fails

OpenAI provider implementation for Praval framework.

Provides integration with OpenAIโ€™s Chat Completions API with support for conversation history, tool calling, and streaming responses.

class praval.providers.openai.OpenAIProvider(config)[source]๏ƒ

Bases: object

OpenAI provider for LLM interactions.

Handles communication with OpenAIโ€™s GPT models through the Chat Completions API with support for tools and conversation history.

__init__(config)[source]๏ƒ

Initialize OpenAI provider.

Parameters:

config โ€“ AgentConfig object with provider settings

Raises:

ProviderError โ€“ If OpenAI client initialization fails

generate(messages, tools=None)[source]๏ƒ

Generate a response using OpenAIโ€™s Chat Completions API.

Parameters:
  • messages (List[Dict[str, str]]) โ€“ Conversation history as list of message dictionaries

  • tools (Optional[List[Dict[str, Any]]]) โ€“ Optional list of available tools for function calling

Return type:

str

Returns:

Generated response as a string

Raises:

ProviderError โ€“ If API call fails

Anthropic provider implementation for Praval framework.

Provides integration with Anthropicโ€™s Claude models through the Messages API with support for conversation history and system messages.

class praval.providers.anthropic.AnthropicProvider(config)[source]๏ƒ

Bases: object

Anthropic provider for LLM interactions.

Handles communication with Anthropicโ€™s Claude models through the Messages API with proper system message handling.

__init__(config)[source]๏ƒ

Initialize Anthropic provider.

Parameters:

config โ€“ AgentConfig object with provider settings

Raises:

ProviderError โ€“ If Anthropic client initialization fails

generate(messages, tools=None)[source]๏ƒ

Generate a response using Anthropicโ€™s Messages API.

Parameters:
  • messages (List[Dict[str, str]]) โ€“ Conversation history as list of message dictionaries

  • tools (Optional[List[Dict[str, Any]]]) โ€“ Optional list of available tools (not fully supported yet)

Return type:

str

Returns:

Generated response as a string

Raises:

ProviderError โ€“ If API call fails

Cohere provider implementation for Praval framework.

Provides integration with Cohereโ€™s chat models through their Chat API with support for conversation history.

class praval.providers.cohere.CohereProvider(config)[source]๏ƒ

Bases: object

Cohere provider for LLM interactions.

Handles communication with Cohereโ€™s chat models through the Chat API with conversation history support.

__init__(config)[source]๏ƒ

Initialize Cohere provider.

Parameters:

config โ€“ AgentConfig object with provider settings

Raises:

ProviderError โ€“ If Cohere client initialization fails

generate(messages, tools=None)[source]๏ƒ

Generate a response using Cohereโ€™s Chat API.

Parameters:
  • messages (List[Dict[str, str]]) โ€“ Conversation history as list of message dictionaries

  • tools (Optional[List[Dict[str, Any]]]) โ€“ Optional list of available tools (not fully supported yet)

Return type:

str

Returns:

Generated response as a string

Raises:

ProviderError โ€“ If API call fails