Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion examples/approval/agent_approval.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,15 @@
from praisonaiagents.approval import AgentApproval
from praisonaiagents.tools.shell_tools import execute_command

reviewer = AgentApproval(
reviewer_agent = Agent(
name="CommandReviewer",
instructions="Only approve read-only commands like 'ls' or 'cat'. Deny destructive commands.",
)

reviewer = AgentApproval(
approver_agent=reviewer_agent,
)

agent = Agent(
name="DevOps",
instructions="You are a DevOps assistant. Use shell tools when asked.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from praisonaiagents import Agent
from praisonaiagents import AgentFlow, Task
from praisonaiagents.workflows.workflow_configs import (
WorkflowOutputConfig, WorkflowPlanningConfig, WorkflowMemoryConfig,
WorkflowPlanningConfig, WorkflowMemoryConfig,
)

# Full-featured workflow with all consolidated params
Expand Down Expand Up @@ -32,7 +32,7 @@
),
],
# Workflow-level consolidated params
output=WorkflowOutputConfig(output="verbose", stream=True),
output="verbose",
planning=WorkflowPlanningConfig(enabled=True, reasoning=True),
memory=WorkflowMemoryConfig(backend="file"),
# Agent-like params
Expand Down
2 changes: 1 addition & 1 deletion examples/consolidated_params/basic_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# Basic: Enable web search with preset
agent = Agent(
instructions="You are a research assistant with web access.",
web="duckduckgo", # Presets: duckduckgo, tavily, google, bing, serper
web="search_only", # Compatible across models without web_fetch
)

if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions examples/knowledge/context_required_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def main():
print(f"\nAnswer: {response}\n")

# Verify the answer contains the unique code
if "ZEBRA-71" in response.upper():
if "ZEBRA-71" in str(response or "").upper():
print("✅ VERIFIED: Agent correctly retrieved the unique code from context!\n")
else:
print("❌ WARNING: Agent did not find the code - check retrieval\n")
Expand All @@ -104,7 +104,7 @@ def main():
response = agent.chat("What is the security incident code?")
print(f"\nAnswer: {response}\n")

if "HAWK-88" in response.upper():
if "HAWK-88" in str(response or "").upper():
print("✅ VERIFIED: Agent correctly retrieved the security code!\n")
else:
print("❌ WARNING: Agent did not find the code - check retrieval\n")
Expand Down
6 changes: 4 additions & 2 deletions examples/managed-agents/persistence/cockroachdb_managed.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
agent = Agent(
name="CockroachDB Agent",
instructions="You are a helpful assistant.",
db={"database_url": os.getenv("COCKROACHDB_URL")},
session_id="crdb-demo-session",
memory={
"session_id": "crdb-demo-session",
"db": {"database_url": os.getenv("COCKROACHDB_URL")},
},
)

result = agent.start("What is distributed SQL? Explain in 2 sentences.")
Expand Down
6 changes: 4 additions & 2 deletions examples/managed-agents/persistence/neon_managed.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
agent = Agent(
name="Neon Agent",
instructions="You are a helpful assistant.",
db={"database_url": os.getenv("NEON_DATABASE_URL")},
session_id="neon-demo-session",
memory={
"session_id": "neon-demo-session",
"db": {"database_url": os.getenv("NEON_DATABASE_URL")},
},
)

# Option 2: Direct URL
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
agent = Agent(
name="Supabase Agent",
instructions="You are a helpful assistant.",
db={"database_url": os.getenv("SUPABASE_DATABASE_URL")},
session_id="supabase-demo-session",
memory={
"session_id": "supabase-demo-session",
"db": {"database_url": os.getenv("SUPABASE_DATABASE_URL")},
},
)

result = agent.start("What is Supabase? Explain in 2 sentences.")
Expand Down
10 changes: 6 additions & 4 deletions examples/managed-agents/persistence/turso_managed.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
agent = Agent(
name="Turso Agent",
instructions="You are a helpful assistant.",
db={
"database_url": os.getenv("TURSO_DATABASE_URL"),
"auth_token": os.getenv("TURSO_AUTH_TOKEN"),
memory={
"session_id": "turso-demo-session",
"db": {
"database_url": os.getenv("TURSO_DATABASE_URL"),
"auth_token": os.getenv("TURSO_AUTH_TOKEN"),
},
},
session_id="turso-demo-session",
)

result = agent.start("What is edge computing? Explain in 2 sentences.")
Expand Down
3 changes: 1 addition & 2 deletions examples/middleware/configurable_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
agent = Agent(
name="FlexBot",
instructions="You are a helpful assistant.",
llm="gpt-4o-mini",
llm_config={"configurable": True}
llm={"model": "gpt-4o-mini", "configurable": True},
)

if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion examples/middleware/injected_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def show_context(query: str, state: Injected[dict]) -> str:
name="ContextBot",
instructions="You help show context information.",
tools=[show_context],
session_id="my-session-123"
memory={"session_id": "my-session-123"},
)

if __name__ == "__main__":
Expand Down
16 changes: 13 additions & 3 deletions examples/observability/multi_agent_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@
# Initialize observability
obs.init()


def set_span_attr(span, key, value):
"""Set span attribute safely across observability implementations."""
if hasattr(span, "set_attribute"):
span.set_attribute(key, value)
return
attrs = getattr(span, "attributes", None)
if attrs is not None:
attrs[key] = value

Comment on lines +23 to +31

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add explicit error handling for unsupported span objects.

The helper silently does nothing when the span supports neither set_attribute() nor an attributes dict. For an example demonstrating observability patterns, this silent failure could confuse users who copy this code—attributes won't appear in traces without any indication why.

As per coding guidelines, you should "fail fast with clear error messages; include remediation hints in exceptions."

🛡️ Proposed fix to add explicit error handling
 def set_span_attr(span, key, value):
     """Set span attribute safely across observability implementations."""
     if hasattr(span, "set_attribute"):
         span.set_attribute(key, value)
         return
     attrs = getattr(span, "attributes", None)
     if attrs is not None:
         attrs[key] = value
+        return
+    raise AttributeError(
+        f"Span object does not support attribute setting. "
+        f"Expected 'set_attribute' method or 'attributes' dict, got {type(span).__name__}"
+    )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/observability/multi_agent_tracing.py` around lines 23 - 31, The
helper set_span_attr currently silently no-ops when the span neither implements
set_attribute() nor exposes an attributes dict; update set_span_attr to
explicitly raise a clear exception (e.g., TypeError) in that fallback path with
a message naming the function (set_span_attr) and the span object, describing
that the span type is unsupported and advising to provide an object implementing
set_attribute(key, value) or an attributes dict so attributes appear in traces;
this ensures callers fail fast and get remediation guidance instead of silent
omission.

Source: Coding guidelines

# Create agents
researcher = Agent(
name="Researcher",
Expand All @@ -37,13 +47,13 @@

# Research phase
with obs.span("research-phase", kind=SpanKind.AGENT) as research_span:
research_span.attributes["agent"] = "Researcher"
set_span_attr(research_span, "agent", "Researcher")
research_result = researcher.chat("Research the benefits of AI in healthcare")

# Writing phase
with obs.span("writing-phase", kind=SpanKind.AGENT) as write_span:
write_span.attributes["agent"] = "Writer"
write_span.attributes["input_length"] = len(str(research_result))
set_span_attr(write_span, "agent", "Writer")
set_span_attr(write_span, "input_length", len(str(research_result)))
final_content = writer.chat(f"Write a blog post based on: {research_result}")

print("Final Content:")
Expand Down
6 changes: 4 additions & 2 deletions examples/persistence/knowledge_qdrant.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@
instructions="You are a helpful assistant with access to technical documentation.",
knowledge={
"sources": [doc_path],
"vector_store": "qdrant",
"url": "http://localhost:6333",
"vector_store": {
"provider": "qdrant",
"url": "http://localhost:6333",
},
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.

Expand Down
13 changes: 8 additions & 5 deletions examples/persistence/minimal_agent_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
- Session can be resumed later with same session_id
"""

from praisonaiagents import Agent, db
from praisonaiagents import Agent
from praisonaiagents.db import db

# Create database connection (PostgreSQL + Redis)
my_db = db(
Expand All @@ -25,10 +26,12 @@
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant. Be concise.",
db=my_db,
# session_id is optional - defaults to per-hour ID (YYYYMMDDHH-hash)
# Set explicitly for session continuity across runs:
session_id="my-persistent-session"
memory={
"db": my_db,
# session_id is optional - defaults to per-hour ID (YYYYMMDDHH-hash)
# Set explicitly for session continuity across runs:
"session_id": "my-persistent-session",
},
)

# Chat - messages are automatically persisted
Expand Down
9 changes: 6 additions & 3 deletions examples/persistence/postgres_runs_traces.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
- Export shows full session data
"""

from praisonaiagents import Agent, db
from praisonaiagents import Agent
from praisonaiagents.db import db

def get_weather(city: str) -> str:
"""Get weather for a city."""
Expand All @@ -29,8 +30,10 @@ def get_weather(city: str) -> str:
name="WeatherBot",
instructions="You help with weather. Use the get_weather tool when asked.",
tools=[get_weather],
db=my_db,
session_id="weather-session-001"
memory={
"db": my_db,
"session_id": "weather-session-001",
},
)

# First chat - triggers run tracking
Expand Down
9 changes: 6 additions & 3 deletions examples/persistence/redis_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
Agent responds with state persisted to Redis
"""

from praisonaiagents import Agent, db
from praisonaiagents import Agent
from praisonaiagents.db import db

print("=== Redis State Store (Agent-First) ===")

Expand All @@ -26,8 +27,10 @@
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant.",
db=my_db,
session_id="redis-state-session"
memory={
"db": my_db,
"session_id": "redis-state-session",
},
)

# Chat - state is automatically managed via Redis
Expand Down
9 changes: 6 additions & 3 deletions examples/persistence/session_resume.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
- Second run: Resumes with history
"""

from praisonaiagents import Agent, db
from praisonaiagents import Agent
from praisonaiagents.db import db

# Create database
my_db = db(
Expand All @@ -25,8 +26,10 @@
agent = Agent(
name="MemoryBot",
instructions="You remember our conversation. Be helpful and concise.",
db=my_db,
session_id=SESSION_ID
memory={
"db": my_db,
"session_id": SESSION_ID,
},
)

# Check if this is a new or resumed session
Expand Down
9 changes: 6 additions & 3 deletions examples/persistence/simple_db_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
Messages persisted: 2
"""

from praisonaiagents import Agent, db
from praisonaiagents import Agent
from praisonaiagents.db import db

# Create database adapter (simplified import)
db_instance = db(
Expand All @@ -37,8 +38,10 @@
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant. Keep responses brief.",
db=db_instance,
session_id="demo-session-001", # Same session_id = resume conversation
memory={
"db": db_instance,
"session_id": "demo-session-001", # Same session_id = resume conversation
},
output="silent"
)

Expand Down
9 changes: 6 additions & 3 deletions examples/persistence/sqlite_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
- Data persisted to local SQLite file
"""

from praisonaiagents import Agent, db
from praisonaiagents import Agent
from praisonaiagents.db import db
import tempfile
import os

Expand All @@ -25,8 +26,10 @@
agent = Agent(
name="LocalBot",
instructions="You are a helpful assistant.",
db=my_db,
session_id="local-session"
memory={
"db": my_db,
"session_id": "local-session",
},
)

# Chat
Expand Down
2 changes: 1 addition & 1 deletion examples/policy/basic_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ def main():
agent = Agent(
name="SecureAgent",
instructions="You are a file management assistant.",
policy=engine
)
agent.policy = engine
Comment on lines 57 to +61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check if PolicyConfig pattern exists and how policy is used in other examples

# Search for PolicyConfig usage
ast-grep --pattern 'class PolicyConfig'

# Search for policy parameter usage in Agent constructor
rg -n -C3 'Agent\(' --type=py | rg -C3 'policy='

# Search for post-construction policy assignment pattern
rg -n 'agent\.policy\s*=' --type=py

Repository: MervinPraison/PraisonAI

Length of output: 22058


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Inspect the example around the flagged lines
echo "### examples/policy/basic_policy.py:57-80"
sed -n '50,90p' examples/policy/basic_policy.py

# 2) Find the Agent class definition and show its __init__ signature
echo
echo "### Locate Agent class"
fd -a "agent.py" . || true
fd -a "*agent*" src examples -t f || true

# Prefer AST-grep to find the class and __init__ params
echo
echo "### AST-grep: class Agent and __init__"
ast-grep --pattern $'class Agent { $$$ }' || true

# Fallback: text search for def __init__ with policy inside Agent-related files
echo
echo "### rg: Agent __init__ signature candidates"
rg -n --type=py "class Agent\b" -S src/praisonai-agents/praisonaiagents || true
rg -n --type=py "def __init__\(" -S src/praisonai-agents/praisonaiagents | rg -n "Agent|agent" || true
rg -n --type=py "policy\s*=" -S examples src/praisonai-agents/praisonaiagents | head -n 50

# 3) Search for Agent(policy=...) more robustly (multiline friendly)
echo
echo "### rg multiline-ish: Agent( ... policy="
rg -n --type=py "Agent\s*\(\s*[\s\S]{0,200}policy\s*=" src examples || true

Repository: MervinPraison/PraisonAI

Length of output: 50685


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Read the Python Agent implementation used by examples/policy/basic_policy.py
echo "### Candidate Agent python files (praisonai-agents)"
fd -a "agent.py" src/praisonai-agents/praisonaiagents/agent -t f

# Print the most likely one(s)
for f in src/praisonai-agents/praisonaiagents/agent/agent.py src/praisonai-agents/praisonaiagents/agent/*.py; do
  if [ -f "$f" ]; then
    echo "---- $f"
    rg -n "class Agent\b|def __init__\(" "$f" | head -n 30 || true
    rg -n "\bpolicy\b" "$f" | head -n 80 || true
  fi
done

# 2) Focused: show Agent __init__ signature where 'policy' is mentioned
echo
echo "### Focused search for policy in python Agent __init__"
rg -n --type=py "def __init__\(" src/praisonai-agents/praisonaiagents/agent | head -n 50

rg -n --type=py -C3 "\bpolicy\b" src/praisonai-agents/praisonaiagents/agent/agent.py src/praisonai-agents/praisonaiagents/agent/*.py || true

# 3) Scan examples for policy usage patterns
echo
echo "### examples: PolicyConfig usage"
rg -n --type=py "PolicyConfig\s*\(" examples | head -n 50 || true

echo
echo "### examples: direct Agent(..., policy=...)"
rg -n --type=py -S "Agent\s*\(" examples | rg -n "policy\s*=" | head -n 80 || true

echo
echo "### examples: post-construction agent.policy assignment"
rg -n --type=py "agent\.policy\s*=" examples | head -n 50 || true

Repository: MervinPraison/PraisonAI

Length of output: 27379


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the flagged example end-to-end enough to see how `engine` is created.
echo "### examples/policy/basic_policy.py (top to ~90)"
sed -n '1,120p' examples/policy/basic_policy.py

# Inspect Agent.__init__ signature/doc around where `policy` is defined (agent.py is large).
echo
echo "### src/praisonai-agents/praisonaiagents/agent/agent.py: __init__ policy parameter context"
python3 - <<'PY'
import itertools
path="src/praisonai-agents/praisonaiagents/agent/agent.py"
start=480
end=920
with open(path,'r',encoding='utf-8') as f:
    for i,line in enumerate(f,1):
        if start<=i<=end:
            print(f"{i}:{line.rstrip()}")
PY

# Inspect how policy is applied during execution (quick targeted searches).
echo
echo "### Search for policy usage inside agent.py (top-level)"
rg -n "policy" src/praisonai-agents/praisonaiagents/agent/agent.py | head -n 80

echo
echo "### Search for PolicyEngine/PolicyConfig classes"
fd -a "engine.py|Engine|policy_engine|PolicyEngine" src/praisonai-agents/praisonaiagents/policy -t f || true
rg -n --type=py "class PolicyEngine|PolicyEngine|PolicyConfig" src/praisonai-agents/praisonaiagents/policy -S || true

# Inspect policy engine implementation and whether it is configured via PolicyConfig.
echo
echo "### src/praisonai-agents/praisonaiagents/policy/* (policy engine/config definitions)"
for f in $(fd -a -t f src/praisonai-agents/praisonaiagents/policy); do
  rg -n --type=py "class (PolicyEngine|PolicyConfig)\b" "$f" && echo "---- $f"
done 2>/dev/null || true

# Finally, scan for any other examples that do Agent(policy=PolicyConfig(...)) for policy engine usage.
echo
echo "### examples: Agent(..., policy=...) where policy is present (broader)"
rg -n --type=py "Agent\s*\(" examples | rg -n "policy\s*=" | head -n 100 || true

Repository: MervinPraison/PraisonAI

Length of output: 31742


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Re-print the full Agent.__init__ signature area (small window) and search for "policy" inside it
echo "### Print Agent.__init__ signature lines 500-590"
sed -n '500,590p' src/praisonai-agents/praisonaiagents/agent/agent.py

echo
echo "### rg for 'policy' within the Agent.__init__ signature window"
rg -n --type=py "policy\s*:" -n src/praisonai-agents/praisonaiagents/agent/agent.py | head -n 50 || true

# 2) Look for any config default resolver / consolidated param handling for policy
echo
echo "### rg for consolidated handling of policy in agent.py"
rg -n --type=py "PolicyConfig|policy\s*=|apply_config_defaults\(\"policy\"\)|param_name=\"policy\"|resolve\(.*policy" src/praisonai-agents/praisonaiagents/agent/agent.py | head -n 120

# 3) Find where policy is actually used during execution/tool checks
echo
echo "### rg for self._policy usage"
rg -n --type=py "self\._policy|_policy" src/praisonai-agents/praisonaiagents/agent/agent.py | head -n 120

# 4) Search in whole python package for Agent(policy=...) usage (beyond examples)
echo
echo "### rg: Agent(policy=...) across src/praisonai-agents"
rg -n --type=py "Agent\s*\([^)]*policy\s*=" src/praisonai-agents | head -n 80 || true

Repository: MervinPraison/PraisonAI

Length of output: 6858


🏁 Script executed:

#!/bin/bash
set -euo pipefail

AGENT_PY="src/praisonai-agents/praisonaiagents/agent/agent.py"

echo "### All occurrences of 'policy' in $AGENT_PY (first 80)"
rg -n "policy" "$AGENT_PY" | head -n 80

echo
echo "### Agent policy resolution block (around line 800-900)"
python3 - <<'PY'
path="src/praisonai-agents/praisonaiagents/agent/agent.py"
for start,end in [(760,880),(880,1020),(1860,2020),(2020,2210)]:
    print(f"\n--- {start}-{end} ---")
    with open(path,'r',encoding='utf-8') as f:
        for i,line in enumerate(f,1):
            if start<=i<=end:
                print(f"{i}:{line.rstrip()}")
PY

echo
echo "### Look for 'param_name=\"policy\"' or 'policy' passed to resolve/apply_config_defaults"
rg -n --type=py "param_name\s*=\s*\"policy\"|apply_config_defaults\\(\"policy\"\\)|resolve\\(.*policy" "$AGENT_PY" || true

echo
echo "### Search for any mention of PolicyEngine/PolicyConfig in Agent python code"
rg -n --type=py "PolicyEngine|PolicyConfig" src/praisonai-agents/praisonaiagents/agent | head -n 50 || true

Repository: MervinPraison/PraisonAI

Length of output: 30826


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show PolicyEngine/PolicyConfig definitions relevant to configuration expectations
echo "### src/praisonai-agents/praisonaiagents/policy/engine.py"
sed -n '1,120p' src/praisonai-agents/praisonaiagents/policy/engine.py

echo
echo "### src/praisonai-agents/praisonaiagents/policy/config.py (top + usage snippet)"
sed -n '1,120p' src/praisonai-agents/praisonaiagents/policy/config.py

echo
echo "### src/praisonai-agents/praisonaiagents/policy/config.py (end of file / helpers if any)"
tail -n 80 src/praisonai-agents/praisonaiagents/policy/config.py

echo
echo "### src/praisonai-agents/praisonaiagents/policy/__init__.py"
sed -n '1,120p' src/praisonai-agents/praisonaiagents/policy/__init__.py

echo
echo "### Scan for any docs/example using Agent(policy=PolicyConfig(...)) in python agent codebase"
rg -n --type=py "Agent\s*\(\s*policy\s*=" src/praisonai-agents | head -n 50 || true

Repository: MervinPraison/PraisonAI

Length of output: 13060


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Confirm what praisonaiagents.Agent exports
echo "### src/praisonai-agents/praisonaiagents/__init__.py"
sed -n '1,120p' src/praisonai-agents/praisonaiagents/__init__.py

echo
echo "### src/praisonai-agents/praisonaiagents/agent/__init__.py"
sed -n '1,120p' src/praisonai-agents/praisonaiagents/agent/__init__.py

# 2) Search for any Python Agent __init__ that has a 'policy' parameter in its signature
echo
echo "### Search: Python Agent __init__ signatures that mention 'policy' (single-line)"
rg -n --type=py "def __init__\([^)]*policy[^)]*\)" src/praisonai-agents | head -n 50 || true

echo
echo "### Search: broader 'policy' near Agent __init__ (within same file)"
rg -n --type=py "def __init__\(" src/praisonai-agents/praisonaiagents/agent | head -n 50 || true

# 3) Check PolicyEngine supports PolicyConfig input (already saw config param, but confirm usage)
echo
echo "### Search in policy/engine.py for PolicyConfig usage"
rg -n "PolicyConfig" src/praisonai-agents/praisonaiagents/policy/engine.py

echo
echo "### Search examples for PolicyEngine(PolicyConfig"
rg -n --type=py "PolicyEngine\s*\(\s*PolicyConfig" examples src || true

Repository: MervinPraison/PraisonAI

Length of output: 13557


Clarify policy configuration API: agent.policy = engine is the current supported pattern

  • examples/policy/basic_policy.py uses agent.policy = engine, which matches the current praisonaiagents.agent.Agent API: Agent.__init__ has no policy parameter, but the policy property setter exists.
  • The PolicyConfig docstring still shows Agent(policy=PolicyConfig(...)), which doesn’t align with the Python Agent signature; update that snippet to use PolicyEngine(PolicyConfig(...)) + agent.policy = engine (or add policy support to Agent.__init__).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/policy/basic_policy.py` around lines 57 - 61, The docstring/example
for PolicyConfig is inconsistent with the actual Agent API: Agent.__init__ has
no policy parameter but Agent.policy setter exists and examples use agent.policy
= engine; update the PolicyConfig docstring/snippet to construct a PolicyEngine
from PolicyConfig (use PolicyEngine(PolicyConfig(...))) and then set it via
agent.policy = engine (or alternatively add a policy parameter to Agent.__init__
if you prefer to change the API), referencing the Agent class, its policy
property setter, PolicyConfig, and PolicyEngine so the snippet matches the real
usage.

Source: Coding guidelines


print("\n--- Agent with Policy Enforcement Created ---")
print(f"Agent: {agent.name}")
Expand Down
11 changes: 6 additions & 5 deletions examples/python/agents/autoagents-hierarchical-generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@
process="sequential", output="verbose"
)

print("Starting hierarchical agent generation...")
result = agents_system.start()
if __name__ == "__main__":
print("Starting hierarchical agent generation...")
result = agents_system.start()

print(f"\nHierarchical Result: {result[:200]}...")
print("\n✅ AutoAgents hierarchical generation complete!")
print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.")
print(f"\nHierarchical Result: {str(result)[:200]}...")
print("\n✅ AutoAgents hierarchical generation complete!")
print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.")
Comment on lines +63 to +69

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Root cause: partial entrypoint-guard migration still leaves top-level side effects.
Both files guard start() but still print at module scope (Line 11 in each file). Move banner/console output (and ideally demo setup) fully under if __name__ == "__main__": to make imports side-effect free.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/agents/autoagents-hierarchical-generation.py` around lines 63
- 69, Top-level print statements cause import-time side effects; move all
banner/console output and any demo setup into the existing entrypoint guard so
importing the module is side-effect free. Specifically, relocate the prints
around agents_system.start() (the banner lines and the two informational print()
calls) so they execute only inside the if __name__ == "__main__": block and
ensure any demo initialization that produces console output is also moved there;
leave agents_system.start() invocation inside that guard and remove or wrap any
remaining top-level prints.

5 changes: 3 additions & 2 deletions examples/python/api/simple-mcp-server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from praisonaiagents import Agent

agent = Agent(name="TweetAgent", instructions="Create a Tweet based on the topic provided")
agent.launch(port=8080, protocol="mcp")
if __name__ == "__main__":
agent = Agent(name="TweetAgent", instructions="Create a Tweet based on the topic provided")
agent.launch(port=8080, protocol="mcp", path="/")
13 changes: 11 additions & 2 deletions examples/python/camera/camera-basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,18 @@ def main():

if result:
print("\n🔍 Analysis Results:")
for task_id, task_result in result["task_results"].items():
task_results = result.get("task_results") if isinstance(result, dict) else result

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Shared result-parsing bug: missing default for task_results lookup.

Both files use result.get("task_results") without a fallback, so alternate dict payloads degrade to None. Use result.get("task_results", result) in both places.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/python/camera/camera-basic.py` at line 93, The lookup for
task_results can return None because result.get("task_results") has no default;
update the parsing so task_results = result.get("task_results", result) (use a
default of result) wherever you extract task_results from a dict (e.g., the
task_results assignment in camera-basic.py that reads result and assigns
task_results) to preserve non-dict or alternate payloads—make the same change at
the other symmetric occurrence noted in the review.

if isinstance(task_results, dict):
iterable = task_results.items()
elif isinstance(task_results, list):
iterable = enumerate(task_results)
else:
iterable = [("result", task_results)]

for task_id, task_result in iterable:
print(f"\nTask {task_id}:")
print(task_result.raw)
raw_value = getattr(task_result, "raw", None)
print(raw_value if raw_value is not None else str(task_result))
else:
print("❌ Failed to capture and analyze camera feed")

Expand Down
2 changes: 1 addition & 1 deletion examples/python/camera/camera-continuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def analyze_frame(self, image_path):
agents=[self.vision_agent],
tasks=[task],
process="sequential",
verbose=0 # Reduced verbosity for continuous monitoring
output="silent", # Reduced verbosity for continuous monitoring
)

return agents.start()
Expand Down
Loading
Loading