- Rewrite README.md, DEPLOY.md and RULES.md in English - Translate module docstring, license string and inline comments - Rename Portuguese state variables (is_agendamento, is_useragenda, is_configia) to English equivalents (is_schedule, is_dailyroutine, is_configai) - Replace Portuguese web-search and file-creation trigger phrases with English keywords
9.8 KiB
9.8 KiB
PsAgentAI - Development Rules
Official rules for AIs and developers to code the PsAgentAI system correctly, standardized and securely.
1. Project Overview
- Name: PsAgentAI
- Type: Telegram bot for conversational AI agent
- Language: Python 3.9+
- Framework: python-telegram-bot (v20+)
- Main file:
psagentai_agent.py - Purpose: Personal conversational companion with memory, profiles, file workspace, image analysis, web search and automations.
Basic rule
Every change must preserve existing behavior unless the user explicitly requests a change. Structural changes must be validated with python3 -m py_compile psagentai_agent.py.
2. Code Standards
2.1 Style
- Follow the style already established in
psagentai_agent.py. - Use double quotes for short strings and messages; single quotes only when there are double quotes inside.
- Indentation: 4 spaces.
- Function/file names:
snake_case. - Global constants in
UPPER_CASE. - Comments in Brazilian Portuguese when necessary; avoid obvious comments.
- Keep
print("[LABEL] ...")logs only where they already exist; do not add new logs without need.
2.2 Main file structure
Maintain the logical order:
- Imports
- Global variables and constants
- Utility functions
- Profile/context/workspace functions
- Command handlers
- Message/voice/photo/document handlers
process_text_message- File creation/editing functions
- Handler registration and
main()
New handlers should be added close to similar existing functionalities.
2.3 Imports
- Group standard, third-party and local imports.
- Do not add dependencies without checking if they already exist in
requirements.txt. - If you need a new dependency, update
requirements.txtand communicate.
3. Command and Handler Conventions
3.1 Naming
- Command functions:
<name>_command(ex:help_command,manual_command). - Handler registration:
CommandHandler("name", name_command). - Command names in lowercase, without spaces, in Portuguese when it's a command for the end user.
3.2 Handler registration
- Always add the
CommandHandlerin the appropriate section ofsetup_handlers(). - Maintain the existing order: first commands, then callbacks, then media messages, then
MessageHandler(filters.TEXT & ~filters.COMMAND, message_handler). - Never register duplicate handlers for the same command.
3.3 Command behavior
- All command handlers must call
await auto_detect_chat_id(update)at the beginning, except where there is already explicit handling. - Responses should use
await update.message.reply_text(...)orawait context.bot.send_message(...)when necessary. - Use
ParseMode.HTMLonly when formatting is really needed.
4. Profile Management
4.1 Files
user_profile.json— user profile.agent_profile.json— agent profile.- Never create new profile files without need.
4.2 Profile updates
- Use the existing functions:
load_user_profile(),save_user_profile(),load_agent_profile(),save_agent_profile(). - Partial updates must merge with existing content, not overwrite entire fields without prior reading.
- Natural update triggers must use
handle_profile_update_if_triggered()whenever possible.
4.3 Onboarding
- Maintain the existing onboarding flow.
- New onboarding questions must be added to the
ONBOARDING_QUESTIONSdictionary or to the existing logic, not creating parallel flows.
5. Conversation Context
5.1 Directory
- Contexts are saved in
contexts/YYYY-MM-DD.json. - Use
load_context()andadd_to_context()to manipulate context. - Never access the context file directly without using the helper functions.
5.2 Limits
- Respect the token limits configured in
.env. - Context cleanup functions must use
remove_old_messages()or equivalent, not manually rewrite the file.
6. Workspace and Files
6.1 Directories
workspace/— stores uploads, images and created/edited files.workspace/projects/— projects created by the user.- Never create additional folders inside
workspace/without explicit need.
6.2 Mandatory functions
Always use the existing helper functions:
ensure_workspace_dirs()— creates necessary directories.save_workspace_file(filename, content)— saves file in workspace.build_workspace_tree()— generates visual workspace tree._find_workspace_file(target)— locates file by partial name._looks_like_create_request()/_handle_create_request()— creates files via AI._looks_like_edit_request()/_handle_edit_request()— edits files via AI.
6.3 Metadata
- Update
uploads_metadata.jsonwhen necessary. - Metadata must contain:
original_name,filepath,chat_id,summary,full_text,type.
7. AI Integration
7.1 Supported providers
openrouterstepfunqwencloudllamacpp(local)
7.2 Usage
- Always use
AIProvider.chat(model, messages, ...)for AI calls. - Do not call APIs directly; use the existing abstraction layer.
- Default models come from
.env:DEFAULT_MODEL,VISION_MODEL, etc. - New models must be added to the lists in
psagentai_agent.pywhen there is explicit support.
7.3 Prompts
- System prompt is generated by
build_system_prompt(). - Do not change the system prompt without need; if changing, preserve the date/time, user profile and agent profile sections.
- For specific tasks (file editing, creation, analysis), create separate and clear prompts.
8. Web Search
8.1 Functions
_web_search()— executes search on DuckDuckGo HTML._looks_like_search_request()— detects search intent.- Triggers are in
_WEB_SEARCH_TRIGGERS.
8.2 Rules
- Do not activate web search automatically for every type of question.
- Respect the
IMPORTANTE SOBRE INFORMAÇÕES ATUALIZADASguideline in the system prompt. - Results limit comes from
.env(WEB_SEARCH_MAX_RESULTS).
9. Image Analysis and Vision
- Functions:
encode_image_to_base64(),analyze_image(),save_image_to_workspace(). - Commands:
/viewvision,/configvision. - Configuration via
.env:VISION_MODEL,VISION_PROVIDER. - Images sent as document preserve the original name.
10. Scheduling and Routine
10.1 Files
config.json— stores schedules.- Do not add obsolete fields (ex:
timezonewas removed; use server time).
10.2 Rules
- The Agent ALWAYS uses server time (
datetime.now().astimezone()). /timezoneis only informative, does not allow changes.get_timezone()always returns the server timezone;set_timezone()returnsFalse.
11. Security
- Never commit
.env, API keys, tokens or sensitive data. - Use environment variables for secrets.
- Preserve emails and phones in profiles and contexts without exposing them in logs.
- Validate file paths to avoid path traversal.
12. Tests and Validation
12.1 Mandatory
- After changes in
psagentai_agent.py:python3 -m py_compile psagentai_agent.py. - Test basic scenarios with inline Python scripts when possible.
- Do not break existing functionalities (ex: file creation/editing, profiles, commands).
12.2 Recommended manual tests
/start,/help,/manual,/about- File creation: "create a test.txt file with content X"
- File editing: "edit the file test.txt and add Y"
- Photo sending and analysis
- Voice sending and transcription
- Web search: "search about X"
- AI configuration:
/viewai,/configai
13. Documentation
13.1 Mandatory files
README.md— main documentation, commands, features.DEPLOY.md— server deployment guide.RULES.md— this file, development rules.LICENSE— proprietary license.
13.2 Update
- Always update
README.mdwhen adding commands or features. - Update
DEPLOY.mdif there are changes in environment variables or structure. - This file (
RULES.md) must be updated when new rules are defined.
14. Git and Workflow
14.1 Commits
- Short and descriptive messages in Portuguese or technical English.
- Commits must reflect one logical change at a time.
- Do not make automatic commits without review.
14.2 Branches
- Work on the main branch or create branches for specific features.
- Do not force push without authorization.
15. Language and Communication
- Bot interface: Brazilian Portuguese.
- Agent replies: Brazilian Portuguese.
- Logs and code: technical English for variable/function names; Portuguese for user-facing messages.
- Documentation: Brazilian Portuguese.
16. PsAgentAI Specific Rules
16.1 Never do
- Remove existing functionalities without explicit request.
- Change
.envwithout notice. - Modify folder structure (
workspace/,contexts/) without need. - Introduce heavy dependencies without justification.
- Use
input()or blocking interactions in the bot code.
16.2 Always do
- Preserve compatibility with previous versions of profiles and contexts.
- Handle errors gracefully (try/except with logs).
- Use
loggerfor serious errors; useprint()only for existing debug. - Validate user inputs before processing.
- Provide feedback to the user in case of error ("Error processing. Please try again.").
16.3 Integration of new functionalities
- Understand the existing flow before adding code.
- Create small and specific functions.
- Integrate at the correct point of
process_text_messageor handlers. - Register handlers in the correct order.
- Update documentation.
- Validate with
py_compileand manual tests.
17. Versioning
- Current version:
1.0.0 - Increment version in
__version__when there are relevant changes. - Update
CHANGELOGif it exists; otherwise, document in the commit.
18. Contact and Support
- System developed by: Syspanel.com.br
- Author: Marco A. S. Costa
- Email: contato@syspanel.com.br
- License: Proprietary for syspanel.com.br
Last update: October 2026