fix(examples): resolve syntax errors and align examples with consolidated-params API#1855
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more β On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
π WalkthroughWalkthroughThis PR modernizes 46 example scripts across the PraisonAI repository by standardizing API usage patterns: handler verbosity parameters shift from ChangesExample API Updates and Configuration Consolidation
Estimated code review effortπ― 3 (Moderate) | β±οΈ ~25 minutes Suggested labels
Suggested reviewers
π₯ Pre-merge checks | β 3 | β 2β Failed checks (2 warnings)
β Passed checks (3 passed)
βοΈ Tip: You can configure your own custom pre-merge checks in the settings. β¨ Finishing Touchesπ§ͺ Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@copilot Do a thorough review of this PR. Read ALL existing reviewer comments above from Qodo, Coderabbit, and Gemini first β incorporate their findings. Review areas:
|
There was a problem hiding this comment.
Code Review
This pull request updates various examples to align with consolidated parameter and API changes, such as replacing output="verbose" with verbose=True, restructuring knowledge configurations, and updating memory settings. However, several review comments correctly point out issues where user_id was incorrectly nested inside a memory dictionary or parameter instead of being passed directly to MemoryConfig, build_context_for_task, and Session.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| memory=MemoryConfig( | ||
| backend="file", | ||
| user_id="researcher_001", | ||
| memory={"user_id": "researcher_001"}, |
| context = memory.build_context_for_task( | ||
| task_descr="Explain AI alignment challenges", | ||
| user_id="quality_demo_user", | ||
| memory={"user_id": "quality_demo_user"}, |
| session = Session( | ||
| session_id="demo_chat_001", | ||
| user_id="demo_user" | ||
| memory={"user_id": "demo_user"}, |
Greptile SummaryThis PR fixes broken example scripts across
Confidence Score: 3/5Most fixes are correct, but three call sites were updated with the wrong argument name and will fail immediately at runtime with a TypeError. The bulk of the 49-file change is accurate: duplicate-kwarg syntax fixes, verbose flag updates, and memory dict corrections on Agent all align with the actual API. However, three specific changes introduce new breakage by applying the examples/agent_centric_api.py, examples/python/stateful/session-example.py, and examples/python/stateful/memory-quality-example.py each need their Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[PR: Fix Examples] --> B[Syntax Fixes\n14 files\nDuplicate kwargs]
A --> C[API Alignment\n35+ files]
A --> D[Portability\npath + guards]
A --> E[YAML Fix\nrecipe_runtime_example]
B --> B1["knowledge={**config,\n'sources': [...]}"]
B --> B2["memory=config\n(single assignment)"]
C --> C1["output='verbose'\nβ verbose=True\n(handlers/evals)"]
C --> C2["user_id= on Agent\nβ memory={'user_id':...}\nβ
Agent accepts dict"]
C --> C3["provider='rag'\nβ backend='sqlite'"]
C --> C4["AgentFlow.run(variables=)\nβ constructor + run(input)"]
C --> C5{"Three sites\nover-applied"}
C5 -->|"β MemoryConfig has no 'memory' field"| F["agent_centric_api.py\nTypeError at import"]
C5 -->|"β Session has no 'memory' param"| G["session-example.py\nTypeError at import"]
C5 -->|"β build_context_for_task has no 'memory' param"| H["memory-quality-example.py\nTypeError at call site"]
D --> D1["Path(__file__).with_name()\nvs /tmp/"]
D --> D2["if __name__ == '__main__'\nguards + API key checks"]
|
| # Create a session with persistent storage | ||
| session = Session( | ||
| session_id="demo_chat_001", |
There was a problem hiding this comment.
Session.__init__ has no memory= parameter
Session.__init__ is defined as def __init__(self, session_id, user_id, agent_url, memory_config, knowledge_config, timeout, session_ttl). Passing memory={"user_id": "demo_user"} will raise TypeError: __init__() got an unexpected keyword argument 'memory'. The correct fix is to keep the original user_id="demo_user" direct keyword argument, which Session explicitly accepts and assigns to self.user_id.
|
|
||
| context = memory.build_context_for_task( | ||
| task_descr="Explain AI alignment challenges", | ||
| user_id="quality_demo_user", | ||
| memory={"user_id": "quality_demo_user"}, | ||
| max_items=3 |
There was a problem hiding this comment.
Memory.build_context_for_task has no memory= parameter
The method signature is build_context_for_task(self, task_descr, user_id=None, additional="", max_items=3, include_in_output=None). Replacing the original user_id="quality_demo_user" with memory={"user_id": "quality_demo_user"} will raise TypeError: build_context_for_task() got an unexpected keyword argument 'memory' at runtime. The argument should remain user_id="quality_demo_user" to pass the user identifier that the method is designed to accept.
|
@claude You are the FINAL architecture reviewer. If the branch is under MervinPraison/PraisonAI (not a fork), you are able to make modifications to this branch and push directly. SCOPE: Focus ONLY on Python packages (praisonaiagents, praisonai). Do NOT modify praisonai-rust or praisonai-ts. Read ALL comments above from Gemini, Qodo, CodeRabbit, and Copilot carefully before responding. Phase 1: Review per AGENTS.md
Phase 2: FIX Valid Issues Phase 3: Final Verdict |
|
Claude finished @MervinPraison's task ββ View job Final Architecture Review βConducted comprehensive review of PR #1855 per AGENTS.md guidelines and addressed all critical reviewer feedback. Review Checklist
Architecture Review Summaryβ Protocol-driven compliance: Changes are correctly scoped to examples/ only, maintaining core SDK separation per AGENTS.md guidelines. β Backward compatibility: No public API changes detected in core packages. β Performance: No hot-path regressions - only example code changes. β Scope discipline: All 49 changed files are appropriately limited to examples/ directory plus one YAML doc fix. Issues FixedFixed 3 critical TypeErrors identified by multiple reviewers where 1.
|
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and canβt be posted inline due to platform limitations.
β οΈ Outside diff range comments (3)
examples/python/rag/auto_rag_agent_policy.py (1)
20-27:β οΈ Potential issue | π Major | β‘ Quick winMake this example import-safe and cross-platform.
Top-level execution currently exits/runs on import, and
"/tmp/policy_doc.txt"is POSIX-specific. Usemain()+if __name__ == "__main__":and derive the sample path viaPath(__file__).Based on learnings: Code examples must run without modification (copy-paste success), include necessary imports, and be runnable directly.
Also applies to: 92-93
π€ 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/rag/auto_rag_agent_policy.py` around lines 20 - 27, Wrap the script logic into a main() function and guard execution with if __name__ == "__main__": so importing the module doesn't run top-level code; replace the hardcoded POSIX path "/tmp/policy_doc.txt" by deriving sample_doc via Path(__file__).with_name("policy_doc.txt") (ensure you import pathlib.Path and sys/os as needed) and move the OPENAI_API_KEY check inside main(). Update any other top-level file writes/reads at lines ~92-93 to use the same Path-based sample_doc and be executed only from main().examples/python/rag/agent_vs_auto_rag.py (1)
17-24:β οΈ Potential issue | π Major | β‘ Quick winAvoid import-time execution and POSIX-only temp paths in this example.
This module exits or performs file I/O on import, and
"/tmp/..."is not portable on Windows. Move runtime flow undermain()+if __name__ == "__main__":, and build the sample path fromPath(__file__).Based on learnings: Code examples must run without modification (copy-paste success), include necessary imports, and be runnable directly.
Also applies to: 104-105
π€ 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/rag/agent_vs_auto_rag.py` around lines 17 - 24, The example performs I/O and exits at import time and uses a POSIX-only "/tmp" path; move all runtime logic (the OPENAI_API_KEY check, creation/writing of sample_doc, and subsequent flow) into a new main() function and call it under if __name__ == "__main__":; replace the hard-coded "/tmp/comparison_doc.txt" with a portable path built from Path(__file__).joinpath("comparison_doc.txt") (import Path from pathlib) and ensure any required imports are present at the top of the module so the example can be copy-pasted and run directly.examples/python/rag/auto_rag_agent_basic.py (1)
18-20:β οΈ Potential issue | π Major | β‘ Quick winGuard this script with
__main__to keep imports safe.The module performs environment checks, writes files, and executes chats at import time. Please move execution into
main()and only run it underif __name__ == "__main__":.Based on learnings: Code examples must run without modification (copy-paste success), include necessary imports, and be runnable directly.
Also applies to: 22-80
π€ 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/rag/auto_rag_agent_basic.py` around lines 18 - 20, This script currently runs side-effectful code at import (checks OPENAI_API_KEY, writes files, runs chats); wrap all execution into a new main() function (e.g., def main(): ...) that contains the existing top-level logic and ensure any required imports are present at module top, then add the guard if __name__ == "__main__": main() so the module can be safely imported without running the example; update or move OPENAI_API_KEY check and any file writes/chats into main(), leaving only function/class definitions and imports at module scope.
π§Ή Nitpick comments (1)
examples/python/models/deepseek/deepseek-rag-agents.py (1)
34-34: β‘ Quick winAvoid hardcoded memory identity in the example.
Line 34 fixes all runs to
user1, which can unintentionally merge memory across different users/environments.π‘ Suggested refactor
+import os +import uuid from praisonaiagents import Agent @@ +user_id = os.getenv("PRAISONAI_USER_ID", str(uuid.uuid4())) + agent = Agent( @@ - memory={"user_id": "user1"}, + memory={"user_id": user_id}, llm="deepseek-r1" )π€ 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/models/deepseek/deepseek-rag-agents.py` at line 34, The example hardcodes memory={"user_id": "user1"} which can merge memory across runs; change the example to generate or accept a unique user id instead of the literal "user1" (e.g., use a UUID, timestamp, or a passed-in user_id variable) so each run/session has a distinct memory identity; update the example where memory is passed (the memory={"user_id": ...} assignment) and ensure any downstream references use that variable rather than the hardcoded string.
π€ Prompt for all review comments with 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.
Inline comments:
In `@examples/agent_centric_api.py`:
- Around line 53-56: The MemoryConfig constructor is being called with an
unsupported memory keyword; replace the memory={"user_id": "researcher_001"}
argument with the proper constructor field(s) such as user_id="researcher_001"
(or session_id="...") so the object matches MemoryConfig's signature; update the
instantiation of MemoryConfig (the call to MemoryConfig(..., backend="file",
auto_memory=True)) to pass user_id="researcher_001" instead of memory=... and
remove the unsupported field.
In `@examples/consolidated_params/advanced_memory.py`:
- Around line 15-19: Update the misleading heading comment that currently reads
"array [preset, overrides]" to reflect the new usage shown by Agent(...) with a
direct MemoryConfig; modify the comment near the Agent instantiation
(referencing Agent and MemoryConfig) to something like "With direct MemoryConfig
(overrides)" or "Direct MemoryConfig usage" so it matches the example.
In `@examples/consolidated_params/basic_workflow.py`:
- Around line 25-27: The guard currently aborts when OPENAI_API_KEY is missing;
change the condition to allow running when a local OpenAI-compatible base URL is
provided by checking for OPENAI_API_BASE or OPENAI_BASE_URL as alternatives.
Update the if statement that references os.environ.get("OPENAI_API_KEY") to
instead require that neither OPENAI_API_KEY nor OPENAI_API_BASE nor
OPENAI_BASE_URL is set (e.g., if not (os.environ.get("OPENAI_API_KEY") or
os.environ.get("OPENAI_API_BASE") or os.environ.get("OPENAI_BASE_URL")):),
leaving the existing print("Set OPENAI_API_KEY to run this example.") and
sys.exit(0) behavior but adjust the message to mention the base URL alternatives
if you prefer.
In `@examples/python/concepts/chat-with-pdf.py`:
- Line 28: The example hardcodes "document.pdf" into the knowledge dict without
checking the file exists; import pathlib (or os), create a pdf_path variable
(e.g., pdf_path = Path("document.pdf") or accept from env/arg), check
pdf_path.exists() before initializing the agent and either raise a clear error
prompting the user to provide a valid PDF or fall back to a bundled/sample PDF;
then replace the hardcoded string in the knowledge assignment with the validated
pdf_path.as_posix() (reference symbols: knowledge, config, pdf_path, and the
agent initialization code that consumes knowledge).
In `@examples/python/models/deepseek/deepseek-rag-agents-streamlit.py`:
- Line 36: Replace the hardcoded memory={"user_id": "user1"} with a per-session
user id: create or read a session-scoped id (e.g., using Streamlit's
st.session_state["user_id"] or generate one with uuid.uuid4() and store it in
st.session_state if missing) and pass that variable into memory (e.g.,
memory={"user_id": user_id}). Update the code that constructs the agent or chat
memory (look for the memory= argument where "user1" is used) so each Streamlit
session gets its own user_id and avoids cross-user memory leakage.
In `@examples/python/ui/ollama-rag-agents-streamlit.py`:
- Line 36: Replace hardcoded memory user_id with a per-session identifier:
instead of memory={"user_id": "user1"} build the memory dict from a Streamlit
session-scoped id (e.g., use st.session_state['user_id'] or initialize one with
uuid.uuid4() when absent). Update the code where the app initializes memory so
it checks/creates a session-scoped key and uses that value for the "user_id"
entry to ensure memory isolation across Streamlit users.
---
Outside diff comments:
In `@examples/python/rag/agent_vs_auto_rag.py`:
- Around line 17-24: The example performs I/O and exits at import time and uses
a POSIX-only "/tmp" path; move all runtime logic (the OPENAI_API_KEY check,
creation/writing of sample_doc, and subsequent flow) into a new main() function
and call it under if __name__ == "__main__":; replace the hard-coded
"/tmp/comparison_doc.txt" with a portable path built from
Path(__file__).joinpath("comparison_doc.txt") (import Path from pathlib) and
ensure any required imports are present at the top of the module so the example
can be copy-pasted and run directly.
In `@examples/python/rag/auto_rag_agent_basic.py`:
- Around line 18-20: This script currently runs side-effectful code at import
(checks OPENAI_API_KEY, writes files, runs chats); wrap all execution into a new
main() function (e.g., def main(): ...) that contains the existing top-level
logic and ensure any required imports are present at module top, then add the
guard if __name__ == "__main__": main() so the module can be safely imported
without running the example; update or move OPENAI_API_KEY check and any file
writes/chats into main(), leaving only function/class definitions and imports at
module scope.
In `@examples/python/rag/auto_rag_agent_policy.py`:
- Around line 20-27: Wrap the script logic into a main() function and guard
execution with if __name__ == "__main__": so importing the module doesn't run
top-level code; replace the hardcoded POSIX path "/tmp/policy_doc.txt" by
deriving sample_doc via Path(__file__).with_name("policy_doc.txt") (ensure you
import pathlib.Path and sys/os as needed) and move the OPENAI_API_KEY check
inside main(). Update any other top-level file writes/reads at lines ~92-93 to
use the same Path-based sample_doc and be executed only from main().
---
Nitpick comments:
In `@examples/python/models/deepseek/deepseek-rag-agents.py`:
- Line 34: The example hardcodes memory={"user_id": "user1"} which can merge
memory across runs; change the example to generate or accept a unique user id
instead of the literal "user1" (e.g., use a UUID, timestamp, or a passed-in
user_id variable) so each run/session has a distinct memory identity; update the
example where memory is passed (the memory={"user_id": ...} assignment) and
ensure any downstream references use that variable rather than the hardcoded
string.
πͺ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
βΉοΈ Review info
βοΈ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: b6e4fcb1-e466-47cb-bce1-5dce7ea12ee9
π Files selected for processing (49)
examples/agent_centric_api.pyexamples/benchmark/benchmark_example.pyexamples/compare/cli_compare_advanced.pyexamples/compare/cli_compare_basic.pyexamples/consolidated_params/advanced_memory.pyexamples/consolidated_params/basic_workflow.pyexamples/eval/accuracy_example.pyexamples/eval/criteria_example.pyexamples/eval/performance_example.pyexamples/eval/reliability_example.pyexamples/knowledge/compression_demo.pyexamples/knowledge/hierarchical_summaries_demo.pyexamples/knowledge/large_corpus_strategy_demo.pyexamples/knowledge/mem0_backend_example.pyexamples/knowledge/scope_identifiers_example.pyexamples/knowledge/scope_isolation_example.pyexamples/persistence/knowledge_qdrant.pyexamples/python/cli/git_integration_example.pyexamples/python/cli/repo_map_example.pyexamples/python/cli/sandbox_execution_example.pyexamples/python/concepts/chat-with-pdf.pyexamples/python/concepts/knowledge-agents-task.pyexamples/python/concepts/knowledge-reranker-example.pyexamples/python/concepts/rag-agents.pyexamples/python/general/memory_example.pyexamples/python/memory/advanced-graph-memory-integration.pyexamples/python/memory/advanced-memory-search-optimization.pyexamples/python/memory/gemini-embedding-example.pyexamples/python/memory/graph-memory-agent.pyexamples/python/memory_with_tracing_example.pyexamples/python/models/deepseek/deepseek-rag-agents-streamlit.pyexamples/python/models/deepseek/deepseek-rag-agents.pyexamples/python/mongodb/mongodb_comprehensive_example.pyexamples/python/mongodb/mongodb_knowledge_example.pyexamples/python/mongodb/mongodb_memory_example.pyexamples/python/rag/agent_vs_auto_rag.pyexamples/python/rag/auto_rag_agent_basic.pyexamples/python/rag/auto_rag_agent_policy.pyexamples/python/rag/rag_basic.pyexamples/python/rag/rag_hybrid.pyexamples/python/rag/rag_with_citations.pyexamples/python/sessions/comprehensive-session-management.pyexamples/python/stateful/memory-quality-example.pyexamples/python/stateful/session-example.pyexamples/python/stateful/workflow-state-example.pyexamples/python/ui/ollama-rag-agents-streamlit.pyexamples/python/usecases/domain-context-solution.pyexamples/rag/external_sources.pysrc/praisonai/examples/recipe_runtime_example.yaml
| memory=MemoryConfig( | ||
| backend="file", | ||
| user_id="researcher_001", | ||
| memory={"user_id": "researcher_001"}, | ||
| auto_memory=True, |
There was a problem hiding this comment.
π§© Analysis chain
π Script executed:
#!/bin/bash
set -euo pipefail
cfg_file="$(fd -i 'feature_configs.py' | head -n 1)"
echo "MemoryConfig definition file: ${cfg_file}"
rg -n "class MemoryConfig|^\s+user_id:|^\s+session_id:|^\s+config:|^\s+memory:" "$cfg_file" -A2 -B2
echo
echo "Callsite in examples/agent_centric_api.py:"
rg -n "MemoryConfig\(" examples/agent_centric_api.py -A8 -B2Repository: MervinPraison/PraisonAI
Length of output: 1949
π Web query:
Find examples/agent_centric_api.pyin MervinPraison/PraisonAI and locateMemoryConfig(usage arounduser_id/memory={"user_id": ...}.
π‘ Result:
In the PraisonAI repository (MervinPraison/PraisonAI), MemoryConfig is primarily used within the praisonaiagents library to manage session persistence and memory isolation [1][2][3]. While there is no file specifically named examples/agent_centric_api.py in the repository, the usage of MemoryConfig with user_id is well-documented in the SDK and illustrated in various architectural examples [2][3]. To use MemoryConfig with user_id for multi-user isolation, you can configure an agent as follows [3]: python from praisonaiagents import Agent, MemoryConfig # Configuring agent with specific user_id for memory isolation agent = Agent( name="Assistant", instructions="You are a helpful assistant", memory=MemoryConfig( user_id="user-123", session_id="user-123-main", backend="sqlite" # Supported backends: "file", "sqlite", "redis", "postgres" ) ) Key points regarding MemoryConfig and user_id: - user_id: Used to identify the user, ensuring memory and session data remain isolated between different users [2][3]. - session_id: Recommended to pair with user_id for granular session control [3]. - backend: Defines where the memory is stored; sqlite is commonly used for persistent storage, while file is the default [1][2][3]. You can find further details in the official documentation under the "Agent Session Management" and "Memory Config" sections [1][3].
Citations:
- 1: https://docs.praison.ai/docs/sdk/reference/praisonaiagents/classes/MemoryConfig
- 2: https://docs.praison.ai/docs/sdk/praisonaiagents/config
- 3: https://docs.praison.ai/docs/concepts/session-management
π Web query:
Find the definition of class MemoryConfig (or its dataclass/pydantic model) in MervinPraison/PraisonAI and list its constructor/fields.
π‘ Result:
In the MervinPraison/PraisonAI repository, MemoryConfig is defined as a dataclass in the praisonaiagents/config/feature_configs.py module [1]. It is used to configure agent memory and session management [2][1][3]. The constructor fields for MemoryConfig are [1]: backend: Union[str, MemoryBackend] (Default: MemoryBackend.FILE) - Determines the storage backend, such as FILE, SQLITE, REDIS, POSTGRES, MEM0, or MONGODB [1][3]. user_id: Optional[str] (Default: None) - User identifier for memory isolation [1][3]. session_id: Optional[str] (Default: None) - Session identifier [1][3]. auto_memory: bool (Default: False) - Enables automatic memory extraction [1][3]. claude_memory: bool (Default: False) - Enables Claude-specific memory format [1][3]. db: Optional[Any] (Default: None) - Database adapter for advanced configuration [1]. config: Optional[Dict[str, Any]] (Default: None) - Additional provider-specific settings [1]. learn: Optional[Union[bool, LearnConfig]] (Default: None) - Configuration for continuous learning [1][3]. history: bool (Default: False) - If enabled, automatically injects session history into the agent context [1]. history_limit: int (Default: 10) - The number of messages to include in history [1]. The class also provides an internal to_dict method used for converting the configuration to a dictionary format [2][4].
Citations:
- 1: https://github.com/MervinPraison/PraisonAI/blob/main/src/praisonai-agents/praisonaiagents/config/feature_configs.py
- 2: https://docs.praison.ai/docs/sdk/reference/praisonaiagents/classes/MemoryConfig
- 3: https://docs.praison.ai/docs/sdk/praisonaiagents/config
- 4: https://praisonai.mintlify.app/docs/sdk/reference/praisonaiagents/classes/MemoryConfig
Fix MemoryConfig constructor field in examples/agent_centric_api.py
MemoryConfig supports user_id (and session_id), but it does not define a memory constructor fieldβso memory={"user_id": ...} will not match the model.
π‘ Proposed fix
memory=MemoryConfig(
backend="file",
- memory={"user_id": "researcher_001"},
+ user_id="researcher_001",
auto_memory=True,
),π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| memory=MemoryConfig( | |
| backend="file", | |
| user_id="researcher_001", | |
| memory={"user_id": "researcher_001"}, | |
| auto_memory=True, | |
| memory=MemoryConfig( | |
| backend="file", | |
| user_id="researcher_001", | |
| auto_memory=True, |
π€ 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/agent_centric_api.py` around lines 53 - 56, The MemoryConfig
constructor is being called with an unsupported memory keyword; replace the
memory={"user_id": "researcher_001"} argument with the proper constructor
field(s) such as user_id="researcher_001" (or session_id="...") so the object
matches MemoryConfig's signature; update the instantiation of MemoryConfig (the
call to MemoryConfig(..., backend="file", auto_memory=True)) to pass
user_id="researcher_001" instead of memory=... and remove the unsupported field.
| # With array [preset, overrides] | ||
| agent_override = Agent( | ||
| instructions="You are a helpful assistant.", | ||
| memory=["redis", {"user_id": "custom_user"}], | ||
| memory=MemoryConfig(backend="redis", user_id="custom_user"), | ||
| ) |
There was a problem hiding this comment.
Update the heading to match the new example style.
Line 15 says βarray [preset, overrides]β, but Line 18 now demonstrates direct MemoryConfig(...). Please align the comment to avoid confusion.
π€ 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/consolidated_params/advanced_memory.py` around lines 15 - 19, Update
the misleading heading comment that currently reads "array [preset, overrides]"
to reflect the new usage shown by Agent(...) with a direct MemoryConfig; modify
the comment near the Agent instantiation (referencing Agent and MemoryConfig) to
something like "With direct MemoryConfig (overrides)" or "Direct MemoryConfig
usage" so it matches the example.
| if not os.environ.get("OPENAI_API_KEY"): | ||
| print("Set OPENAI_API_KEY to run this example.") | ||
| sys.exit(0) |
There was a problem hiding this comment.
Allow local base URL usage in the env guard.
Line 25 currently hard-requires OPENAI_API_KEY, which prevents running this example against local OpenAI-compatible endpoints configured via OPENAI_API_BASE/OPENAI_BASE_URL.
Suggested patch
- if not os.environ.get("OPENAI_API_KEY"):
- print("Set OPENAI_API_KEY to run this example.")
+ if not (os.environ.get("OPENAI_API_KEY") or os.environ.get("OPENAI_API_BASE") or os.environ.get("OPENAI_BASE_URL")):
+ print("Set OPENAI_API_KEY (or OPENAI_API_BASE/OPENAI_BASE_URL for local-compatible endpoints) to run this example.")
sys.exit(0)π€ 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/consolidated_params/basic_workflow.py` around lines 25 - 27, The
guard currently aborts when OPENAI_API_KEY is missing; change the condition to
allow running when a local OpenAI-compatible base URL is provided by checking
for OPENAI_API_BASE or OPENAI_BASE_URL as alternatives. Update the if statement
that references os.environ.get("OPENAI_API_KEY") to instead require that neither
OPENAI_API_KEY nor OPENAI_API_BASE nor OPENAI_BASE_URL is set (e.g., if not
(os.environ.get("OPENAI_API_KEY") or os.environ.get("OPENAI_API_BASE") or
os.environ.get("OPENAI_BASE_URL")):), leaving the existing print("Set
OPENAI_API_KEY to run this example.") and sys.exit(0) behavior but adjust the
message to mention the base URL alternatives if you prefer.
| instructions="Read the provided PDF document and answer questions about its content. Be specific and cite relevant sections when possible.", | ||
| knowledge=["document.pdf"], # Replace with your PDF file path | ||
| knowledge=config, | ||
| knowledge={**config, "sources": ["document.pdf"]}, # Replace with your PDF path |
There was a problem hiding this comment.
Guard missing PDF source before agent initialization.
Line 28 hardcodes document.pdf without checking it exists, so this example can fail immediately on first run.
π‘ Suggested fix
+from pathlib import Path
from praisonaiagents import Agent
# Configure vector store for PDF storage
config = {
@@
-# Create a PDF chat agent
+pdf_path = Path(__file__).with_name("document.pdf")
+if not pdf_path.exists():
+ raise FileNotFoundError(
+ f"Missing PDF source: {pdf_path}. Place a sample PDF next to this script."
+ )
+
+# Create a PDF chat agent
pdf_agent = Agent(
@@
- knowledge={**config, "sources": ["document.pdf"]}, # Replace with your PDF path
+ knowledge={**config, "sources": [str(pdf_path)]},Based on learnings: Code examples must run without modification (copy-paste success), include necessary imports, and use realistic/simple data.
π€ 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/concepts/chat-with-pdf.py` at line 28, The example hardcodes
"document.pdf" into the knowledge dict without checking the file exists; import
pathlib (or os), create a pdf_path variable (e.g., pdf_path =
Path("document.pdf") or accept from env/arg), check pdf_path.exists() before
initializing the agent and either raise a clear error prompting the user to
provide a valid PDF or fall back to a bundled/sample PDF; then replace the
hardcoded string in the knowledge assignment with the validated
pdf_path.as_posix() (reference symbols: knowledge, config, pdf_path, and the
agent initialization code that consumes knowledge).
| knowledge=config, | ||
| user_id="user1", | ||
| knowledge={**config, "sources": ["kag-research-paper.pdf"]}, | ||
| memory={"user_id": "user1"}, |
There was a problem hiding this comment.
Use a per-session user_id instead of a global constant.
Line 36 uses memory={"user_id": "user1"}; in a multi-user Streamlit app this can leak or mix memories between users.
π‘ Suggested fix
import streamlit as st
+import uuid
from praisonaiagents import Agent
def init_agent():
+ if "memory_user_id" not in st.session_state:
+ st.session_state.memory_user_id = str(uuid.uuid4())
+
@@
- memory={"user_id": "user1"},
+ memory={"user_id": st.session_state.memory_user_id},π€ 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/models/deepseek/deepseek-rag-agents-streamlit.py` at line 36,
Replace the hardcoded memory={"user_id": "user1"} with a per-session user id:
create or read a session-scoped id (e.g., using Streamlit's
st.session_state["user_id"] or generate one with uuid.uuid4() and store it in
st.session_state if missing) and pass that variable into memory (e.g.,
memory={"user_id": user_id}). Update the code that constructs the agent or chat
memory (look for the memory= argument where "user1" is used) so each Streamlit
session gets its own user_id and avoids cross-user memory leakage.
| knowledge=config, | ||
| user_id="user1", | ||
| knowledge={**config, "sources": ["kag-research-paper.pdf"]}, | ||
| memory={"user_id": "user1"}, |
There was a problem hiding this comment.
Use per-session identity for memory isolation.
Line 36 hardcodes user_id to "user1", which can mix conversation memory across different Streamlit users.
π‘ Suggested fix
import streamlit as st
+import uuid
from praisonaiagents import Agent
def init_agent():
+ if "memory_user_id" not in st.session_state:
+ st.session_state.memory_user_id = str(uuid.uuid4())
+
@@
- memory={"user_id": "user1"},
+ memory={"user_id": st.session_state.memory_user_id},π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| memory={"user_id": "user1"}, | |
| import streamlit as st | |
| import uuid | |
| from praisonaiagents import Agent | |
| def init_agent(): | |
| if "memory_user_id" not in st.session_state: | |
| st.session_state.memory_user_id = str(uuid.uuid4()) | |
| # ... other code ... | |
| memory={"user_id": st.session_state.memory_user_id}, |
π€ 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/ui/ollama-rag-agents-streamlit.py` at line 36, Replace
hardcoded memory user_id with a per-session identifier: instead of
memory={"user_id": "user1"} build the memory dict from a Streamlit
session-scoped id (e.g., use st.session_state['user_id'] or initialize one with
uuid.uuid4() when absent). Update the code where the app initializes memory so
it checks/creates a session-scoped key and uses that value for the "user_id"
entry to ensure memory isolation across Streamlit users.
|
@claude validate and fix verbose=True is old version right ? |
|
Claude finished @MervinPraison's task ββ View job API Validation & Review βTodo List
Validation Resultsβ USER'S QUESTION IS INCORRECT: Current API Pattern Analysisβ
CONFIRMED: From examining the codebase:
The PR Changes Are CORRECT βThe PR correctly updates from the deprecated
Previously Identified TypeErrors βThe 3 TypeErrors identified by reviewers have been FIXED in commit 26591aa5:
ConclusionThe PR direction is CORRECT β
. The changes from User should proceed with the PR as-is. The |
PR stack (read first)
mainSummary
This PR fixes broken and outdated example scripts under
examples/after the consolidated-params API (knowledge=,memory=,Agent,AgentTeam,AgentFlow, CLI handlers). Changes are limited to example code and one YAML doc fix β no audit tooling, no changes to core library behavior.Problems addressed
1. Syntax errors (14 files): Duplicate
knowledge=ormemory=keyword arguments on the same call causedSyntaxError: keyword argument repeated.2. Consolidated-params API alignment (~35 files):
output="verbose"βverbose=True(handler API uses boolean)user_id=βmemory={"user_id": ...}Files changed
49 files β all under
examples/plussrc/praisonai/examples/recipe_runtime_example.yaml.Syntax fixes (duplicate kwargs)
Duplicate
knowledge=/memory=on the same constructor call β 14 files.API alignment (consolidated params)
Handler verbosity, memory nesting, knowledge merging, and related migrations across ~35 additional files.
Notes
results.jsonl, and local validation artifacts are not included.