[wrapper] Import-time env capture in api/call.py, three parallel persistence surfaces, and a self-contradicting praisonai.db deprecation
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Idoneità per principianti
- 25/100
- Tipo di issue
- Refactoring
- Chiarezza
- Abbastanza chiara
- Stato di attività
- Attiva
- Stack tecnologico
- python
- Ambito
- backend, databases, developer-experience
Direzione di ricerca
Start with src/praisonai/praisonai/api/call.py, comparing its environment handling with api/agent_invoke.py; trace the dotenv call and the uses of _refresh_env_globals. Then map the storage, persistence, and db imports, beginning with storage/__init__.py and persistence/orchestrator.py. The issue proposes broad API and data layout changes across multiple subsystems; done means consolidating the public persistence surface, removing stale environment capture, and resolving the praisonai.db deprecation contradiction without breaking existing data or internal callers.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Scope
In-depth architectural review of src/praisonai/praisonai/ (the wrapper) against the project's core pillars — agent-centric, protocol-driven, minimal API, performance-first, production-ready, DRY, no heavy module-level work, no global singletons, multi-agent + async safe. Not docs, not tests, not coverage, not file sizes.
Three validated gaps below. Each is grounded in direct reads of the source; the sibling-pattern and internal-callsite comparisons are what rule out "this is intentional".
1. praisonai.api.call captures env at import and runs dotenv as an import side effect
Why it matters: breaks runtime env rotation in long-lived hosts (praisonai serve, gateways, managed agents), silently mutates os.environ from a bare import praisonai, and directly contradicts the file's own docstring. The sibling file in the same subpackage (api/agent_invoke.py) already does it the right way, so this is intra-package drift, not intent.
Evidence — src/praisonai/praisonai/api/call.py:
# L22–L36: docstring explicitly forbids this, then does it:
def _maybe_load_dotenv() -> None:
"""Load a ``.env`` file only when explicitly opted in.
Importing a library should never mutate ``os.environ``. ...
"""
if os.getenv("PRAISONAI_CALL_LOAD_DOTENV", "").lower() == "true":
from dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv(usecwd=True))
_maybe_load_dotenv() # L36 — runs at import time
# L39–L42, L91–L93: seven env values captured as module globals:
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
PORT = int(os.getenv('PORT', 8090))
NGROK_AUTH_TOKEN = os.getenv('NGROK_AUTH_TOKEN')
PUBLIC = os.getenv('PUBLIC', 'false').lower() == 'true'
CALL_SERVER_TOKEN = os.getenv('CALL_SERVER_TOKEN')
MAX_CONCURRENT_CONNECTIONS = int(os.getenv('MAX_CONCURRENT_CONNECTIONS', '5'))
MAX_REQUESTS_PER_WINDOW = int(os.getenv('MAX_REQUESTS_PER_WINDOW', '100'))
# L55–L56: downstream code reads the captured (stale) global:
def _resolve_realtime_endpoint():
explicit_url = os.getenv('PRAISONAI_REALTIME_URL')
api_key = os.getenv('PRAISONAI_REALTIME_API_KEY') or OPENAI_API_KEY # stale
A workaround exists but is called from exactly one site:
# L250
def _refresh_env_globals() -> None:
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
PORT = int(os.getenv('PORT', 8090))
... # 7 reads re-executed
# L738 — only call-site
_refresh_env_globals()
Sibling file does it correctly — src/praisonai/praisonai/api/agent_invoke.py L37–L55:
def _call_server_token() -> Optional[str]:
"""Live-read the shared server token from the environment.
The environment is the single source of truth; capturing it at import time
broke any host that mounts this router without going through
praisonai.api.call.main() ..."""
return os.getenv('CALL_SERVER_TOKEN')
def _call_auth_disabled() -> bool:
return os.getenv('PRAISONAI_CALL_AUTH', '').lower() == 'disabled'
Reproduction:
praisonai.api.callis imported transitively viapraisonai.cli.commands.call/praisonai.cli.features.serve.- Host rotates
OPENAI_API_KEYorCALL_SERVER_TOKEN(secret manager,.envreload). - Next WebSocket handshake binds using the stale import-time
CALL_SERVER_TOKEN(constant-time compare), or the realtime OpenAI connection uses the stale key. - Separately: if
PRAISONAI_CALL_LOAD_DOTENV=trueis set before any transitive import, a bareimport praisonaisilently mutatesos.environ, surprising callers that deliberately unset env vars for test isolation.
Philosophy violated: "Importing a library should never mutate os.environ" (file's own docstring), "no heavy module-level work", "no global singletons", "multi-agent + async safe by default" (module globals cannot be re-scoped per-tenant).
Fix — move every env read to a function call, like agent_invoke.py, and drop the import-time dotenv side effect into the CLI entrypoint where loading a user's .env is intentional:
# src/praisonai/praisonai/api/call.py
def _openai_api_key() -> Optional[str]:
return os.getenv('OPENAI_API_KEY')
def _port() -> int:
raw = os.getenv('PORT', '8090')
try:
return int(raw)
except ValueError:
return 8090
def _ngrok_auth_token() -> Optional[str]:
return os.getenv('NGROK_AUTH_TOKEN')
def _is_public() -> bool:
return os.getenv('PUBLIC', 'false').lower() == 'true'
def _call_server_token() -> Optional[str]:
return os.getenv('CALL_SERVER_TOKEN')
def _max_concurrent_connections() -> int:
try:
return int(os.getenv('MAX_CONCURRENT_CONNECTIONS', '5'))
except ValueError:
return 5
def _max_requests_per_window() -> int:
try:
return int(os.getenv('MAX_REQUESTS_PER_WINDOW', '100'))
except ValueError:
return 100
# DELETE the module-level `_maybe_load_dotenv()` call.
# Move the opt-in dotenv load into praisonai.cli.commands.call (or the Typer
# handler) where a .env load is a deliberate CLI step, not an import side effect.
Update _resolve_realtime_endpoint, main, and the FastAPI middleware/websocket handlers to call these functions, and delete _refresh_env_globals() entirely — live reads make it dead code.
2. Three parallel persistence surfaces in the wrapper (praisonai.storage, praisonai.persistence, praisonai.db)
Why it matters: direct violation of DRY and the "minimal API" / "simpler, more extensible" pillars. A user asking "where do I plug in Mongo for my agent?" currently has three top-level public namespaces answering the same question, and even the wrapper's own docstrings admit "remaining duplication". A non-developer cannot choose.
Evidence:
src/praisonai/praisonai/storage/ 5 KV adapter classes
__init__.py exposes RedisStorageAdapter, MongoDBStorageAdapter,
PostgreSQLStorageAdapter, DynamoDBStorageAdapter,
ValkeyStorageAdapter
{redis,mongodb,postgresql,dynamodb,valkey}_adapter.py
src/praisonai/praisonai/persistence/ conversation/, knowledge/, state/
conversation/{postgres,mysql,sqlite,singlestore,supabase,surrealdb,...}.py
knowledge/{qdrant,pinecone,chroma,weaviate,lancedb,milvus,pgvector,...}.py
state/{redis,dynamodb,firestore,mongodb,upstash,memory,valkey,...}.py
src/praisonai/praisonai/db/
adapter.py PraisonAIDB monolith (marked "removed in v3.0", still live)
src/praisonai/praisonai/integrations/
db_session_adapter.py bridges PraisonDB → SessionStoreProtocol
The storage package admits the overlap in its own docstring — src/praisonai/praisonai/storage/__init__.py L11–L23:
"""
NOTE: ``praisonai.storage`` holds the canonical, low-level storage adapters.
It is NOT dead code — ``praisonai.persistence`` builds on top of it. For
example ``praisonai.persistence.state.redis.RedisStateStore`` is a thin wrapper
around ``RedisStorageAdapter`` defined here ...
Note on remaining duplication: ``persistence.state.dynamodb`` keeps its own
boto3 setup because it uses a different partition-key schema (``pk``) than the
adapter (``key``); collapsing it would change stored-data layout.
"""
Four equally-valid public spellings exist for "give an agent a Mongo-backed state store":
# Spelling A — the "new canonical" API (praisonaiagents re-export)
from praisonaiagents import Agent, db, MemoryConfig
agent = Agent(memory=MemoryConfig(db=db(database_url="mongodb://localhost/mydb"),
session_id="s1"))
# Spelling B — praisonai.persistence factory
from praisonai.persistence import create_state_store
store = create_state_store("mongodb", url="mongodb://localhost")
# Spelling C — praisonai.storage adapter directly
from praisonai.storage import MongoDBStorageAdapter
adapter = MongoDBStorageAdapter(url="mongodb://localhost", database="praisonai")
# Spelling D — the "deprecated" but still wired-in PraisonAIDB
from praisonai.db import PraisonAIDB # emits DeprecationWarning
db = PraisonAIDB(database_url="mongodb://localhost")
The wrapper's own orchestrator acknowledges the layering is tangled — src/praisonai/praisonai/persistence/orchestrator.py L7–L13:
"""
This class is a thin façade: the store-write side of the lifecycle hooks
(persisting messages, updating session metadata at agent end) is delegated to
:class:`praisonai.db.adapter.PraisonAIDB` — the single owner of that logic and
the live path core routes to via ``MemoryConfig(db=...)``. ...
"""
Reproduction / impact: A new contributor lands in any of three directories for the same backend and wires it up. Six months later a connection-pool bug has to be fixed in three independent places (storage/mongodb_adapter.py, persistence/state/mongodb.py, db/adapter.py's Mongo branch) — the exact DRY tax the "simpler, more extensible" pillar exists to prevent.
Philosophy violated: "DRY: reuse abstractions, no duplication", "minimal API: fewer params, sensible defaults", "easy for non-developers: few lines to do the task".
Fix — collapse to a single public surface and keep the others as implementation:
# 1. Make praisonai.persistence THE public surface. One factory call:
#
# from praisonai.persistence import create_state_store, create_conversation_store
# store = create_state_store("mongodb", url="...")
#
# 2. Demote praisonai.storage.* to private:
# praisonai.persistence._adapters.*
# Remove the top-level re-exports from storage/__init__.py's __all__.
# Every internal consumer in persistence.state.* currently does:
# from ...storage import MongoDBStorageAdapter
# becomes:
# from .._adapters.mongodb import MongoDBStorageAdapter
# No public API change — the KV adapters were always a wrapper internal.
#
# 3. Keep praisonai.db as a 2-line shim that rewrites to the persistence
# factory (so the DeprecationWarning ladder stays honest):
#
# # src/praisonai/praisonai/db/__init__.py
# from praisonai.persistence.factory import (
# create_conversation_store, create_knowledge_store, create_state_store,
# )
#
# def __getattr__(name):
# warnings.warn(_DEPRECATION_MSG, DeprecationWarning, stacklevel=2)
# ... # thin delegator returning a composite that uses the factories above
#
# 4. Resolve the DynamoDB partition-key mismatch via a one-time migration in
# persistence.state.dynamodb instead of forking the adapter.
3. praisonai.db is marked deprecated to users but remains the wrapper's internal "single owner" — the deprecation signal is dishonest
Why it matters: the wrapper signals one API direction to users while its own internal code baseline depends on the "deprecated" module being alive. Users following the deprecation guidance migrate off a path the wrapper itself still requires. v3.0 ships that contradiction into user code.
Evidence — user-facing module says "removed in v3.0" — src/praisonai/praisonai/db/__init__.py L40–L62:
_DEPRECATION_MSG = (
"Importing from 'praisonai.db' is deprecated and will be removed in v3.0. "
"Use the simplified import instead:\n"
" from praisonaiagents import Agent, db\n"
"Then use: db=db(database_url='...')"
)
def __getattr__(name: str):
if name == "DB":
warnings.warn(_DEPRECATION_MSG, DeprecationWarning, stacklevel=2)
from .adapter import DB
return DB
if name == "PraisonAIDB":
warnings.warn(_DEPRECATION_MSG, DeprecationWarning, stacklevel=2)
from .adapter import PraisonAIDB
return PraisonAIDB
...
Internal code bypasses the warning by importing the submodule directly:
# src/praisonai/praisonai/persistence/orchestrator.py L140–L148
"""
The adapter (:class:`praisonai.db.adapter.PraisonAIDB`) is the single
owner ... (orchestrator.on_message / on_agent_end delegate to it).
"""
...
from ..db.adapter import PraisonAIDB # bypasses db/__init__.py __getattr__
self._db = PraisonAIDB._from_stores(...)
# src/praisonai/praisonai/cli/features/persistence.py L574
from praisonai.db.adapter import PraisonAIDB # bypasses deprecation
# src/praisonai/praisonai/integrations/db_session_adapter.py
# Docstring instructs users THROUGH the deprecated path:
"""
Usage::
from praisonai.db import PraisonDB # triggers DeprecationWarning
from praisonai.integrations.db_session_adapter import DbSessionAdapter
db = PraisonDB(database_url="postgresql://localhost/praisonai")
store = DbSessionAdapter(db)
"""
And praisonai/db/adapter.py L35 ships the same warned path as the canonical example:
"""
Example:
from praisonaiagents import Agent, MemoryConfig
from praisonai.db import PraisonAIDB # DeprecationWarning
db = PraisonAIDB(database_url="postgresql://localhost/mydb")
"""
Reproduction:
- User runs
python -W error::DeprecationWarning(common in CI). - Imports
from praisonai.db import PraisonAIDBper every public docstring. - Test fails:
DeprecationWarning: ... will be removed in v3.0. - User rewrites to
from praisonaiagents import dbper the message — butPersistenceOrchestratorstill importspraisonai.db.adapter.PraisonAIDB, so droppingpraisonai.dbin v3.0 silently breaks every persistence-enabled run even for users who migrated.
Philosophy violated: "Preserve old praisonai.* import paths via shims when moving code between packages" — the shim exists but the destination (from praisonaiagents import db) doesn't own the orchestration logic; the real owner is the file being deprecated. Also "execute + verify mode: no guessing — proof of done required" — the deprecation claims v3.0 removal without the internal callsites having been migrated, so the claim is unverifiable.
Fix — pick one and commit to it:
# Option A (preferred if removal is really the plan):
# Move the PraisonAIDB implementation out of praisonai.db.adapter and into
# praisonai.persistence.adapter, then make praisonai.db a pure shim.
# src/praisonai/praisonai/db/__init__.py
import warnings
from praisonai.persistence.adapter import ( # the real new home
PraisonAIDB, PraisonDB, DB, PostgresDB, SQLiteDB, RedisDB,
)
def __getattr__(name):
if name in __all__:
warnings.warn(_DEPRECATION_MSG, DeprecationWarning, stacklevel=2)
import praisonai.persistence.adapter as _impl
return getattr(_impl, name)
raise AttributeError(name)
# Then update:
# - persistence/orchestrator.py → from praisonai.persistence.adapter import PraisonAIDB
# - integrations/db_session_adapter.py → same
# - cli/features/persistence.py L574 → same
# These are canonical imports and emit no warnings.
# Option B (if removal is NOT the plan):
# Un-deprecate praisonai.db. Delete _DEPRECATION_MSG from db/__init__.py and
# stop warning. Fix public docstrings on PraisonAIDB / DbSessionAdapter to
# show the new `from praisonaiagents import db` pattern as PREFERRED but keep
# praisonai.db as a first-class supported alias.
The deprecation warning and the internal architecture must say the same thing. Right now they don't, and v3.0 will ship that contradiction.
Validation notes (ruled out)
The following were investigated and are not gaps worth flagging under this review's rules:
_bootstrap.py,_async_bridge.py,_lazy_cache.py,auto.py— careful, well-engineered, cover the lazy-loading / async-bridge concerns correctly.tool_registry.py,tool_resolver.py,_registry.py— clean shims topraisonai_code.AgentsGenerator.__init__callsregister_default_adapters()eagerly, but it is idempotent and pre-warmed by_entrypoint.arun().- Adapter/registry inheritance via
PluginRegistryis already deduplicated.
🤖 Generated with Claude Code
- Lingua principale
- Python
- Stelle
- 9.3k
- Fork
- 1.5k
- Merge medio
- 1g 5h
- PR unite (30g)
- 520
Preparare l'ambiente
Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di MervinPraison/PraisonAI
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
MervinPraison/PraisonAI#6710 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
claude
Difficoltà 2/5 1-3 ore Idoneità per principianti 74/100
MervinPraison/PraisonAI#6707 ·
I maintainer di solito rispondono entro 1 giorno
-
bug claude
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 90/100
MervinPraison/PraisonAI#6671 ·
I maintainer di solito rispondono entro 1 giorno
-
Compaction budget regression fixture remains below budget with accurate tokenizationForse di nuovo libera Una pull request per questa issue è stata chiusa senza essere unita. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 62/100
MervinPraison/PraisonAI#5418 · 3 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
bug claude documentation
Difficoltà 2/5 1-3 ore Idoneità per principianti 70/100
MervinPraison/PraisonAI#5341 · 3 commenti ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di MervinPraison/PraisonAI
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 2 giorni
-
[Bug]: LANGSMITH_SAMPLING_RATE ignores fractional values (isdigit check), traces 100% of requestsAperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 84/100
I maintainer di solito rispondono entro 1 giorno
-
platform/backend tests
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
Significant-Gravitas/AutoGPT#17100 ·
I maintainer di solito rispondono entro 1 giorno
-
bug good first issue
Difficoltà 2/5 1-3 ore Idoneità per principianti 64/100
-
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 61/100
scverse/infercnvpy#238 ·
I maintainer di solito rispondono entro 1 giorno