AGENTS.md
autogpt_platform/backend/AGENTS.mdAGENTS.md
Quality
81/100
Scores the file, not the repository.Length
1,314 words
38 headings · 4 code blocksRepository
186k
— · pushed 0 days agoLast changed
3 days ago
First indexed 3 days ago.1# Backend23This file provides guidance to coding agents when working with the backend.45## Essential Commands67To run something with Python package dependencies you MUST use `poetry run ...`.89```bash10# Install dependencies11poetry install1213# Run database migrations14poetry run prisma migrate dev1516# Start all services (database, redis, rabbitmq, clamav)17docker compose up -d1819# Run the backend as a whole20poetry run app2122# Run tests23poetry run test2425# Run specific test26poetry run pytest path/to/test_file.py::test_function_name2728# Run block tests (tests that validate all blocks work correctly)29poetry run pytest backend/blocks/test/test_block.py -xvs3031# Run tests for a specific block (e.g., GetCurrentTimeBlock)32poetry run pytest 'backend/blocks/test/test_block.py::test_available_blocks[GetCurrentTimeBlock]' -xvs3334# Lint and format35# prefer format if you want to just "fix" it and only get the errors that can't be autofixed36poetry run format # Black + isort37poetry run lint # ruff38```3940More details can be found in @TESTING.md4142### Creating/Updating Snapshots4344When you first write a test or when the expected output changes:4546```bash47poetry run pytest path/to/test.py --snapshot-update48```4950⚠️ **Important**: Always review snapshot changes before committing! Use `git diff` to verify the changes are expected.5152## Architecture5354- **API Layer**: FastAPI with REST and WebSocket endpoints55- **Database**: PostgreSQL with Prisma ORM, includes pgvector for embeddings56- **Queue System**: RabbitMQ for async task processing57- **Execution Engine**: Separate executor service processes agent workflows58- **Authentication**: JWT-based with Supabase integration59- **Security**: Cache protection middleware prevents sensitive data caching in browsers/proxies6061## Code Style6263- **Top-level imports only** — no local/inner imports (lazy imports only for heavy optional deps like `openpyxl`)64- **Absolute imports** — use `from backend.module import ...` for cross-package imports. Single-dot relative (`from .sibling import ...`) is acceptable for sibling modules within the same package (e.g., blocks). Avoid double-dot relative imports (`from ..parent import ...`) — use the absolute path instead65- **No duck typing** — no `hasattr`/`getattr`/`isinstance` for type dispatch; use typed interfaces/unions/protocols66- **Pydantic models** over dataclass/namedtuple/dict for structured data67- **No linter suppressors** — no `# type: ignore`, `# noqa`, `# pyright: ignore`; fix the type/code68- **List comprehensions** over manual loop-and-append69- **Early return** — guard clauses first, avoid deep nesting70- **f-strings vs printf syntax in log statements** — Use `%s` for deferred interpolation in `debug` statements, f-strings elsewhere for readability: `logger.debug("Processing %s items", count)`, `logger.info(f"Processing {count} items")`71- **Sanitize error paths** — `os.path.basename()` in error messages to avoid leaking directory structure72- **TOCTOU awareness** — avoid check-then-act patterns for file access and credit charging73- **`Security()` vs `Depends()`** — use `Security()` for auth deps to get proper OpenAPI security spec74- **Redis pipelines** — `transaction=True` for atomicity on multi-step operations75- **`max(0, value)` guards** — for computed values that should never be negative76- **SSE protocol** — `data:` lines for frontend-parsed events (must match Zod schema), `: comment` lines for heartbeats/status77- **File length** — keep files under ~300 lines; if a file grows beyond this, split by responsibility (e.g. extract helpers, models, or a sub-module into a new file). Never keep appending to a long file.78- **Function length** — keep functions under ~40 lines; extract named helpers when a function grows longer. Long functions are a sign of mixed concerns, not complexity.79- **Top-down ordering** — define the main/public function or class first, then the helpers it uses below. A reader should encounter high-level logic before implementation details.8081## Testing Approach8283- Uses pytest with snapshot testing for API responses84- Test files are colocated with source files (`*_test.py`)85- Mock at boundaries — mock where the symbol is **used**, not where it's **defined**86- After refactoring, update mock targets to match new module paths87- Use `AsyncMock` for async functions (`from unittest.mock import AsyncMock`)8889### Test-Driven Development (TDD)9091When fixing a bug or adding a feature, write the test **before** the implementation:9293```python94# 1. Write a failing test marked xfail95@pytest.mark.xfail(reason="Bug #1234: widget crashes on empty input")96def test_widget_handles_empty_input():97 result = widget.process("")98 assert result == Widget.EMPTY_RESULT99100# 2. Run it — confirm it fails (XFAIL)101# poetry run pytest path/to/test.py::test_widget_handles_empty_input -xvs102103# 3. Implement the fix104105# 4. Remove xfail, run again — confirm it passes106def test_widget_handles_empty_input():107 result = widget.process("")108 assert result == Widget.EMPTY_RESULT109```110111This catches regressions and proves the fix actually works. **Every bug fix should include a test that would have caught it.**112113## Database Schema114115Key models (defined in `schema.prisma`):116117- `User`: Authentication and profile data118- `AgentGraph`: Workflow definitions with version control119- `AgentGraphExecution`: Execution history and results120- `AgentNode`: Individual nodes in a workflow121- `StoreListing`: Marketplace listings for sharing agents122123## Environment Configuration124125- **Backend**: `.env.default` (defaults) → `.env` (user overrides)126127## Common Development Tasks128129### Adding a new block130131Follow the comprehensive [Block SDK Guide](@../../docs/platform/block-sdk-guide.md) which covers:132133- Provider configuration with `ProviderBuilder`134- Block schema definition135- Authentication (API keys, OAuth, webhooks)136- Testing and validation137- File organization138139Quick steps:1401411. Create new file in `backend/blocks/`1422. Configure provider using `ProviderBuilder` in `_config.py`1433. Inherit from `Block` base class1444. Define input/output schemas using `BlockSchema`1455. Implement async `run` method1466. Generate unique block ID using `uuid.uuid4()`1477. Test with `poetry run pytest backend/blocks/test/test_block.py`148149Note: when making many new blocks analyze the interfaces for each of these blocks and picture if they would go well together in a graph-based editor or would they struggle to connect productively?150ex: do the inputs and outputs tie well together?151152If you get any pushback or hit complex block conditions check the new_blocks guide in the docs.153154#### Handling files in blocks with `store_media_file()`155156When blocks need to work with files (images, videos, documents), use `store_media_file()` from `backend.util.file`. The `return_format` parameter determines what you get back:157158| Format | Use When | Returns |159|--------|----------|---------|160| `"for_local_processing"` | Processing with local tools (ffmpeg, MoviePy, PIL) | Local file path (e.g., `"image.png"`) |161| `"for_external_api"` | Sending content to external APIs (Replicate, OpenAI) | Data URI (e.g., `"data:image/png;base64,..."`) |162| `"for_block_output"` | Returning output from your block | Smart: `workspace://` in CoPilot, data URI in graphs |163164**Examples:**165166```python167# INPUT: Need to process file locally with ffmpeg168local_path = await store_media_file(169 file=input_data.video,170 execution_context=execution_context,171 return_format="for_local_processing",172)173# local_path = "video.mp4" - use with Path/ffmpeg/etc174175# INPUT: Need to send to external API like Replicate176image_b64 = await store_media_file(177 file=input_data.image,178 execution_context=execution_context,179 return_format="for_external_api",180)181# image_b64 = "data:image/png;base64,iVBORw0..." - send to API182183# OUTPUT: Returning result from block184result_url = await store_media_file(185 file=generated_image_url,186 execution_context=execution_context,187 return_format="for_block_output",188)189yield "image_url", result_url190# In CoPilot: result_url = "workspace://abc123"191# In graphs: result_url = "data:image/png;base64,..."192```193194**Key points:**195196- `for_block_output` is the ONLY format that auto-adapts to execution context197- Always use `for_block_output` for block outputs unless you have a specific reason not to198- Never hardcode workspace checks - let `for_block_output` handle it199200### Modifying the API2012021. Update route in `backend/api/features/`2032. Add/update Pydantic models in same directory2043. Write tests alongside the route file2054. Run `poetry run test` to verify206207## Workspace & Media Files208209**Read [Workspace & Media Architecture](../../docs/platform/workspace-media-architecture.md) when:**210- Working on CoPilot file upload/download features211- Building blocks that handle `MediaFileType` inputs/outputs212- Modifying `WorkspaceManager` or `store_media_file()`213- Debugging file persistence or virus scanning issues214215Covers: `WorkspaceManager` (persistent storage with session scoping), `store_media_file()` (media normalization pipeline), and responsibility boundaries for virus scanning and persistence.216217## Security Implementation218219### Cache Protection Middleware220221- Located in `backend/api/middleware/security.py`222- Default behavior: Disables caching for ALL endpoints with `Cache-Control: no-store, no-cache, must-revalidate, private`223- Uses an allow list approach - only explicitly permitted paths can be cached224- Cacheable paths include: static assets (`static/*`, `_next/static/*`), health checks, public store pages, documentation225- Prevents sensitive data (auth tokens, API keys, user data) from being cached by browsers/proxies226- To allow caching for a new endpoint, add it to `CACHEABLE_PATHS` in the middleware227- Applied to both main API server and external API applications228
Also in Significant-Gravitas/AutoGPT
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| Significant-Gravitas/AutoGPTautogpt_platform/frontend/src/tests/AGENTS.md · 186k | AGENTS.md | teststylearchtypes+2 | 81/100 | 3 days ago | |
| Significant-Gravitas/AutoGPT.github/copilot-instructions.md · 186k | Copilot instructions | setupbuildtestlint-format+10 | 88/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTAGENTS.md · 186k | AGENTS.md | teststylearchgit+1 | 87/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTautogpt_platform/AGENTS.md · 186k | AGENTS.md | setuptestarchtesting-strategy+3 | 77/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTautogpt_platform/backend/backend/copilot/graphiti/AGENTS.md · 186k | AGENTS.md | styleperformance | 66/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTautogpt_platform/frontend/AGENTS.md · 186k | AGENTS.md | setupbuildtestlint-format+7 | 96/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTclassic/CLAUDE.md · 186k | CLAUDE.md | setuptestlint-formatstyle+7 | 89/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTclassic/direct_benchmark/CLAUDE.md · 186k | CLAUDE.md | setuptestlint-formatarch+4 | 78/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTclassic/forge/CLAUDE.md · 186k | CLAUDE.md | teststylearchtypes+3 | 73/100 | 3 days ago | |
| Significant-Gravitas/AutoGPTclassic/original_autogpt/CLAUDE.md · 186k | CLAUDE.md | testarchuiperformance+2 | 90/100 | 3 days ago | |
| Significant-Gravitas/AutoGPT.claude/skills/vercel-react-best-practices/AGENTS.md · 186k | AGENTS.md | buildlint-formatstyledependencies+4 | 61/100 | 3 days ago |
Diff against autogpt_platform/frontend/src/tests/AGENTS.md Diff against .github/copilot-instructions.md Diff against AGENTS.md Diff against autogpt_platform/AGENTS.md Diff against autogpt_platform/backend/backend/copilot/graphiti/AGENTS.md Diff against autogpt_platform/frontend/AGENTS.md Diff against classic/CLAUDE.md Diff against classic/direct_benchmark/CLAUDE.md Diff against classic/forge/CLAUDE.md Diff against classic/original_autogpt/CLAUDE.md Diff against .claude/skills/vercel-react-best-practices/AGENTS.md
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| n8n-io/n8npackages/@n8n/agents/AGENTS.md · 199k | AGENTS.md | buildteststylearch+3 | 100/100 | 3 days ago | |
| vllm-project/vllmAGENTS.md · 88k | AGENTS.md | setuptestlint-formatstyle+5 | 100/100 | 3 days ago | |
| SkeneTechnologies/skene-cookbookAGENTS.md · 51 | AGENTS.md | setupbuildtestlint-format+7 | 100/100 | 2 days ago | |
| duckduckgo/content-scope-scriptsspecial-pages/AGENTS.md · 70 | AGENTS.md | buildteststylearch+3 | 100/100 | 3 days ago | |
| mui/material-uiAGENTS.md · 99k | AGENTS.md | setupbuildtestlint-format+9 | 100/100 | 3 days ago | |
| OnlyTerp/prompt-cache-skillsAGENTS.md · 112 | AGENTS.md | setupbuildtestlint-format+5 | 100/100 | 3 days ago | |
| trick77/agents-md-syncAGENTS.md · 2 | AGENTS.md | setupbuildteststyle+5 | 100/100 | 3 days ago | |
| TryGhost/Ghoste2e/AGENTS.md · 55k | AGENTS.md | setupteststylearch+2 | 100/100 | 3 days ago |
