Two files, one repository
originalankur/GenerateAgents.md ships 1 format across 5 indexed files. The question worth asking is whether the second one says anything the first does not.
| Dimension | Shared | Only in A | Only in B | Overlap |
|---|---|---|---|---|
| Sections | 16 | 4 | 6 | 62% |
| Commands | 1 | 5 | 13 | 5% |
| Section tags | 11 | 1 | 3 | 73% |
What each file covers
Sections
16 shared · 4 only in A · 6 only in B- − AGENTS.md — AutogenerateAgentsMD.md
- − 1. Type Hinting
- − 2. Import Ordering
- − 3. Error Handling
- + AGENTS.md — fastapi
- + Correct pattern for managing a database session
- + Bad: Blocking I/O in an `async` route
- + ANTI-PATTERN: This will block the entire application!
- + Good: Non-blocking I/O in an `async` route
- + CORRECT PATTERN: Non-blocking I/O
- Project Overview
- Tech Stack
- Architecture
- Code Style
- Anti-Patterns & Restrictions
- Database & State Management
- Error Handling & Logging
- Testing Commands
- Testing Guidelines
- Security & Compliance
- Dependencies & Environment
- PR & Git Rules
- Documentation Standards
- Common Patterns
- Agent Workflow / SOP
- Few-Shot Examples
Commands
1 shared · 5 only in A · 13 only in B- − uv sync --extra dev
- − pytest -m e2e
- − pytest tests/test_utils.py
- − python-dotenv
- − git
- + ruff format
- + ruff check . --fix
- + mypy
- + pdm-backend
- + ruff
- + black
- + ruff check
- + pytest-mock
- + pdm
- + pdm add <package>
- + pdm add -dG <group> <package>
- + pdm add -dG tests pytest-mock
- + git checkout -b feature/my-new-feature
- pytest
Section tags
11 shared · 1 only in A · 3 only in B- − types
- + lint-format
- + testing-strategy
- + api
- setup
- test
- code-style
- architecture
- git-pr
- security
- dependencies
- database
- do-not
- agent-behaviour
- docs
Line diff
originalankur/GenerateAgents.md · AGENTS.md
@@ −1 @@
1# AGENTS.md — AutogenerateAgentsMD.md
2
3## Project Overview
4
5`GenerateAgents.md` is a Python command-line tool that automates the creation of a comprehensive `AGENTS.md` file for any public GitHub or local code repository. It acts as an automated codebase analyst and technical writer, using the `dspy` framework to programmatically interface with LLMs. The tool clones and analyzes a target codebase to produce a standardized blueprint, enabling AI coding agents to rapidly understand a project's architecture, conventions, and data flow. The primary language is Python (>=3.12).
6
7## Tech Stack
8
9* **Primary Language:** Python (>=3.12)
10* **Core AI Framework:** `dspy`
11* **LLM Abstraction Layer:** `litellm`
12* **Dependency Management:** `uv`
13* **CLI Framework:** `argparse` (standard library)
14* **Configuration:** `python-dotenv`
15* **Version Control Interaction:** `git` (via `subprocess`)
16* **Testing:** `pytest`
17
18## Architecture
19
20The application follows a modular, stateless pipeline pattern orchestrated by the main CLI entry point.
21
22* `src/autogenerateagentsmd/cli.py`: The command-line interface entry point. It parses arguments and orchestrates the entire analysis and generation pipeline via the `run_agents_md_pipeline` function.
23* `src/autogenerateagentsmd/modules.py`: Contains the core `dspy.Module` classes (`CodebaseConventionExtractor`, `AgentsMdCreator`, `AntiPatternExtractor`). These modules encapsulate the primary LLM-driven logic for analyzing code and synthesizing the final document.
24* `src/autogenerateagentsmd/signatures.py`: Defines the contracts for LLM interactions using `dspy.Signature`. These signatures specify the expected inputs (e.g., source code) and outputs (e.g., extracted conventions) for each LLM-powered step.
25* `src/autogenerateagentsmd/model_config.py`: Centralizes the configuration for supported LLMs, making it easy to switch between models like Gemini, Claude, and OpenAI.
26* `src/autogenerateagentsmd/utils.py`: Contains helper functions for non-LLM tasks, such as cloning Git repositories, loading files into memory, and other file system operations.
27* `tests/`: The test suite, containing end-to-end and unit tests.
28* `pyproject.toml`: Defines project metadata, dependencies, and the `autogenerateagentsmd` console script entry point.
29
30## Code Style
31
32The project enforces a strict and consistent Python coding style.
33
34* **Type Hinting**: Type hints are strictly mandatory for all function parameters and return values.
35
36 ```python
37 # Good
38 def load_source_tree(repo_path: str) -> dict[str, str]:
39 # ...
40
41 # Bad
42 def load_source_tree(repo_path):
43 # ...
44 ```
45
46* **Naming Conventions**:
47 * `snake_case` for functions, methods, and variables (e.g., `run_agents_md_pipeline`).
48 * `PascalCase` for all classes (e.g., `CodebaseConventionExtractor`).
49 * `ALL_CAPS_WITH_UNDERSCORES` for module-level constants.
50
51* **Import Ordering**: Imports must be grouped at the top of each file in the following order: 1) Standard library, 2) Third-party libraries, 3) Local application imports.
52
53 ```python
54 # Good
55 import argparse
56 import logging
57 from pathlib import Path
58
59 import dspy
60 from dotenv import load_dotenv
61
62 from .modules import AgentsMdCreator, CodebaseConventionExtractor
63 from .utils import clone_repo, load_source_tree
64 ```
65
66* **Formatting**: Use 4-space indentation and maintain a line length between 80-100 characters.
67
68## Anti-Patterns & Restrictions
69
70* **NEVER use on private codebases**: The tool sends the full source code to third-party LLM APIs. Using it on private, proprietary, or sensitive codebases is a significant security risk. It is designed **exclusively** for public, open-source repositories.
71* **NEVER commit secrets**: Do not commit the `.env` file or any other file containing API keys or secrets to version control.
72* **DO NOT introduce new LLM frameworks**: The project architecture is tightly coupled to `dspy`. Avoid introducing other orchestration frameworks like LangChain or LlamaIndex.
73* **AVOID new end-to-end tests**: E2E tests are slow and costly due to live API calls. Prioritize mocked unit tests for new functionality unless there is a strong justification for an E2E test.
74
75## Database & State Management
76
77The application is entirely **stateless**. It does not use a database or any form of persistent storage between runs. All configuration is loaded at runtime from command-line arguments and the `.env` file. The application's state exists only for the duration of a single execution, primarily as an in-memory dictionary (`source_tree`) holding the target repository's code. The only output is the generated `AGENTS.md` file.
78
79## Error Handling & Logging
80
81* **Error Handling**: Application logic within modules and utilities should raise specific exceptions (e.g., `FileNotFoundError`, `subprocess.CalledProcessError`). Generic `except Exception` blocks should be avoided. A single global `try...except Exception` block exists in `src/autogenerateagentsmd/cli.py` to catch any unhandled exceptions at the top level and provide a clean exit with a user-friendly error message.
82* **Logging**: The standard `logging` module is used for progress reporting. It is configured in `cli.py` to print `INFO`-level messages to the console, informing the user about the current stage of the pipeline (e.g., "Cloning repository...", "Extracting conventions...").
83
84## Testing Commands
85
86* **Install dependencies for testing:**
87 ```bash
88 uv sync --extra dev
89 ```
90* **Run all tests (excluding slow E2E tests):**
91 ```bash
92 pytest
93 ```
94* **Run only the end-to-end (E2E) tests:**
95 ```bash
96 pytest -m e2e
97 ```
98* **Run tests for a specific file:**
99 ```bash
100 pytest tests/test_utils.py
101 ```
102
103## Testing Guidelines
104
105The project uses `pytest` for testing. The testing strategy is two-pronged:
106
107* **End-to-End (E2E) Tests**:
108 * Located in `tests/test_e2e_pipeline.py`.
109 * These tests validate the entire pipeline by cloning real public repositories and making live LLM API calls.
110 * They are marked with `@pytest.mark.e2e` and are run sparingly due to their cost and long execution time.
111 * They serve as the ultimate validation that the integrated system works as expected.
112
113* **Unit Tests**:
114 * This is the preferred method for testing new contributions.
115 * Focus on testing individual functions in `src/autogenerateagentsmd/utils.py`.
116 * For `dspy` modules in `src/autogenerateagentsmd/modules.py`, tests should use mocking to avoid actual LLM API calls. This ensures tests are fast, deterministic, and free of cost.
117
118## Security & Compliance
119
120* **API Key Management**: All API keys and other secrets **must** be stored in a `.env` file at the project root. This file is explicitly listed in `.gitignore` and must never be committed to version control.
121* **Data Handling and Privacy**: The tool's core function involves sending the entire source code of a target repository to external, third-party LLM APIs. This is a critical security consideration. **NEVER** run this tool on any repository containing proprietary code, sensitive data, secrets, or personally identifiable information (PII). It is intended for use only on publicly available, open-source software.
122
123## Dependencies & Environment
124
125* **Dependency Management**: Dependencies are managed with `uv` and are defined in `pyproject.toml`.
126 * Production dependencies are under `[project.dependencies]`.
127 * Development dependencies (like `pytest`) are under `[project.optional-dependencies]dev`.
128* **Installation**: To install all required dependencies for development and testing, run the following command from the project root:
129 ```bash
130 uv sync --extra dev
131 ```
132* **Environment Variables**: The application requires API keys for the desired LLM providers. Create a `.env` file in the project root and add the necessary keys.
133 ```bash
134 # Example .env file
135 OPENAI_API_KEY="sk-..."
136 ANTHROPIC_API_KEY="..."
137 GEMINI_API_KEY="..."
138 ```
139* **Runtime Version**: The project requires Python version 3.12 or newer.
140
141## PR & Git Rules
142
143The project uses Git for version control. The repository includes a standard Python `.gitignore` file to exclude common artifacts like `__pycache__`, virtual environments (`.venv`), build directories, and the `.env` file containing secrets. No specific branch naming conventions or commit message formats are formally documented.
144
145## Documentation Standards
146
147* **User Documentation**: The `README.md` file serves as the primary user-facing guide. It contains the project's purpose, installation instructions, and command-line usage examples.
148* **Agent/Developer Documentation**: The `AGENTS.md` file (which this tool generates for itself) is the definitive technical guide for developers and AI agents. It provides a deep, structured overview of the architecture, conventions, and patterns.
149* **In-Code Documentation**:
150 * **Type Hints**: Mandatory for all function signatures.
151 * **Docstrings**: Public modules and complex functions should have descriptive docstrings explaining their purpose, arguments, and return values.
152
153## Common Patterns
154
155* **Stateless Pipeline Pattern**: The entire application is orchestrated as a linear, stateless pipeline in `src/autogenerateagentsmd/cli.py`. Data flows from one stage to the next (e.g., `load_source_tree` -> `CodebaseConventionExtractor` -> `AgentsMdCreator`) without persisting state between executions.
156* **DSPy Modules for LLM Logic**: All direct interactions with large language models are encapsulated within `dspy.Module` classes (e.g., `AgentsMdCreator`). This separates the prompt engineering and LLM logic from the main application orchestration code.
157* **Strict Type Hinting**: ALWAYS add type hints to all function parameters and return values. This is a non-negotiable standard for code clarity and static analysis.
158 ```python
159 # ALWAYS do this
160 def clone_repo(github_url: str, target_dir: Path) -> None:
161 ...
162 ```
163* **Specific Exception Handling**: NEVER use a generic `except Exception:` in application modules. ALWAYS catch specific, anticipated exceptions to handle errors gracefully and avoid masking unknown bugs.
164 ```python
165 # Good
166 try:
167 # some file operation
168 except FileNotFoundError:
169 logger.error("Could not find the specified file.")
170
171 # Bad
172 try:
173 # some file operation
174 except Exception as e:
175 logger.error(f"An unknown error occurred: {e}")
176 ```
177
178## Agent Workflow / SOP
179
180When tasked with modifying or extending this codebase, follow this standard operating procedure:
181
1821. **Understand the Goal**: Clarify the specific change required. Is it adding a new analysis capability, supporting a new LLM, or fixing a bug in the file processing?
1832. **Locate Relevant Code**:
184 * For CLI changes (new arguments): `src/autogenerateagentsmd/cli.py`.
185 * For new LLM-driven analysis: Define a new `dspy.Signature` in `signatures.py` and a new `dspy.Module` in `modules.py`.
186 * For general helper functions (e.g., file handling): `src/autogenerateagentsmd/utils.py`.
187 * For model configuration: `src/autogenerateagentsmd/model_config.py`.
1883. **Implement the Change**: Adhere strictly to the coding conventions:
189 * Add mandatory type hints for all new functions.
190 * Use `snake_case` for functions/variables and `PascalCase` for classes.
191 * Isolate LLM logic within a `dspy.Module`.
1924. **Write Tests**:
193 * For changes in `utils.py`, add a new unit test to the appropriate file in the `tests/` directory.
194 * For a new `dspy.Module`, write a unit test that mocks the LLM call to verify the module's behavior without making a real API request.
1955. **Verify**: Run the local test suite using `pytest` to ensure your changes have not introduced any regressions.
1966. **Document**: If you've added a new user-facing feature (like a new CLI flag), update the `README.md`. The `AGENTS.md` is auto-generated and does not need manual updates.
197
198## Few-Shot Examples
199
200### 1. Type Hinting
201
202* **Good**: Mandatory type hints for parameters and return values.
203 ```python
204 from pathlib import Path
205
206 def save_markdown_file(content: str, output_path: Path) -> None:
207 """Saves the given content to a file."""
208 output_path.parent.mkdir(parents=True, exist_ok=True)
209 output_path.write_text(content, encoding="utf-8")
210 ```
211
212* **Bad**: Missing type hints.
213 ```python
214 def save_markdown_file(content, output_path):
215 """Saves the given content to a file."""
216 output_path.parent.mkdir(parents=True, exist_ok=True)
217 output_path.write_text(content, encoding="utf-8")
218 ```
219
220### 2. Import Ordering
221
222* **Good**: Imports are correctly grouped (standard library, third-party, local).
223 ```python
224 import logging
225 import subprocess
226 from pathlib import Path
227
228 from git.repo import Repo # Hypothetical third-party library
229
230 from .exceptions import GitCloneError
231 ```
232
233* **Bad**: Imports are mixed together without logical grouping.
234 ```python
235 from pathlib import Path
236 from .exceptions import GitCloneError
237 import logging
238 from git.repo import Repo
239 import subprocess
240 ```
241
242### 3. Error Handling
243
244* **Good**: Catching a specific, expected exception.
245 ```python
246 import subprocess
247
248 def run_git_command(command: list[str]) -> str:
249 try:
250 result = subprocess.run(
251 command,
252 check=True,
253 capture_output=True,
254 text=True
255 )
256 return result.stdout
257 except subprocess.CalledProcessError as e:
258 logging.error(f"Git command failed: {e.stderr}")
259 raise
260 ```
261
262* **Bad**: Using a generic `except Exception` which can hide other bugs.
263 ```python
264 import subprocess
265
266 def run_git_command(command: list[str]) -> str:
267 try:
268 result = subprocess.run(
269 command,
270 check=True,
271 capture_output=True,
272 text=True
273 )
274 return result.stdout
275 except Exception as e: # This is too broad
276 logging.error(f"An unexpected error occurred: {e}")
277 raise
278
originalankur/GenerateAgents.md · projects/fastapi/AGENTS.md
@@ +1 @@
1# AGENTS.md — fastapi
2
3## Project Overview
4
5FastAPI is a modern, high-performance Python web framework for building APIs, based on standard Python type hints. It is built on top of Starlette for web functionality and Pydantic for data validation and serialization. The project's core philosophy is to provide developers with a world-class experience through robust tools, predictable behavior, and frictionless workflows, enabling the creation of clear, performant, and automatically documented APIs.
6
7## Tech Stack
8
9* **Primary Language**: Python
10* **Core Frameworks**: Starlette (ASGI foundation), Pydantic (data validation/serialization)
11* **Typing**: `typing-extensions`, `typing-inspection`
12* **Ecosystem**: Uvicorn (ASGI server), HTTPX (async HTTP client for testing)
13* **Build System**: `pdm-backend`
14* **Testing**: `pytest`, `anyio` (for async tests), `coverage`
15* **Code Quality**: `ruff` (linter and formatter), `black` (formatter), `mypy` (static type checker)
16* **Documentation**: `mkdocs-material`, `mkdocstrings`
17
18## Architecture
19
20The project is organized with a clear separation of concerns, primarily distinguishing between the core framework logic, tests, and documentation.
21
22* `fastapi/`: The core source code of the framework.
23 * `applications.py`: Contains the main `FastAPI` application class.
24 * `routing.py`: Defines the `APIRouter` and handles all routing logic.
25 * `dependencies/`: Implements the dependency injection system.
26 * `openapi/`: Manages the OpenAPI schema generation.
27 * `security/`: Provides built-in security utilities like OAuth2 and API Keys.
28* `tests/`: Contains all unit, integration, and end-to-end tests. The directory structure mirrors the `fastapi/` source directory.
29* `docs_src/`: The raw Markdown source files for the official documentation.
30* `scripts/`: Holds utility scripts for development, maintenance, and CI/CD.
31* `pyproject.toml`: The central configuration file for project metadata, dependencies, and all development tooling.
32
33## Code Style
34
35The project enforces a strict, automated code style to ensure consistency and readability.
36
37* **Formatting**: All code is formatted using `black` and `ruff format`. Manual formatting adjustments are not permitted. The command `ruff format .` should be run before committing.
38* **Linting**: `ruff check` is used for linting. All code must be free of its errors and warnings, which includes rules for ordered imports, no unused variables, and other best practices.
39* **Static Typing**: This is a non-negotiable cornerstone of the codebase.
40 * All function signatures, method signatures, variables, and class attributes **must** have explicit type hints.
41 * The entire codebase must pass `mypy .` static analysis without any errors. This is critical for preventing bugs and ensuring a great developer experience via IDE autocompletion.
42
43An example of a correctly styled and typed function signature:
44
45```python
46from typing import Any, Dict
47
48def create_item(item_id: int, data: Dict[str, Any]) -> Dict[str, Any]:
49 # function implementation
50 return {"item_id": item_id, **data}
51```
52
53## Anti-Patterns & Restrictions
54
55To maintain performance, concurrency safety, and maintainability, the following patterns are strictly forbidden.
56
571. **NEVER perform blocking I/O in `async` routes.** A synchronous call like `requests.get()` or `time.sleep()` in an `async` function will freeze the entire server's event loop. Always use `async`-compatible libraries (e.g., `httpx`, `asyncpg`). For CPU-bound work, use `asyncio.to_thread()`.
582. **NEVER use global mutable variables for request state.** This leads to race conditions, data leaks between requests, and makes testing impossible. All per-request state must be managed via the Dependency Injection system (`Depends`).
593. **NEVER manually validate request data.** This bypasses Pydantic's validation, error reporting, and automatic OpenAPI schema generation. Always define a Pydantic `BaseModel` and use it as a type hint in your endpoint function to let FastAPI handle validation automatically.
604. **NEVER create monolithic routers.** A single file with hundreds of routes is unmaintainable. Group related endpoints into separate `APIRouter` instances in different modules and include them in the main application using `app.include_router()`.
61
62## Database & State Management
63
64State and data management conventions are designed to ensure concurrency safety, testability, and clear data contracts.
65
66* **Golden Rule of State**: **Never use global mutable state.** Global variables modified during requests are a source of race conditions and are forbidden. For application-wide, read-only configuration, use `pydantic-settings` to load settings at startup.
67* **Per-Request State**: The **Dependency Injection (`Depends`)** system is the **only** approved way to manage request-scoped state and resources, such as database sessions.
68* **Resource Management**: For resources that need setup and teardown (like database connections), use a `yield` statement within a dependency function. This pattern ensures resources are properly cleaned up, even in case of errors.
69
70```python
71# Correct pattern for managing a database session
72def get_db() -> Generator[Session, None, None]:
73 db = SessionLocal()
74 try:
75 yield db # Provide the session to the endpoint
76 finally:
77 db.close() # Guarantee the session is closed
78```
79
80* **Data Contracts**: Use Pydantic `BaseModel` classes for all data entering or leaving the API. Define separate models for request bodies and use the `response_model` parameter in decorators to control response bodies, preventing accidental data leakage.
81
82## Error Handling & Logging
83
84The framework uses a structured approach to error handling and logging.
85
86* **Client Errors**: For all expected client-side errors (e.g., resource not found, permission denied), you **must** raise `fastapi.HTTPException` with the appropriate status code.
87* **Validation Errors**: `RequestValidationError` is raised automatically by the framework when incoming request data fails Pydantic validation. The default handler returns a `422 Unprocessable Entity` response with detailed error information.
88* **Unhandled Exceptions**: Custom exception handlers can be added to the application to catch unhandled server errors and return a consistent, formatted error response instead of a generic 500 error.
89* **Logging**: **Do not use `print()` statements.** All logging within the framework must be done using the central logger obtained via `logging.getLogger("fastapi")`.
90
91## Testing Commands
92
93Before submitting code, run the full local quality suite using these commands from the project root.
94
95* **Run all tests**:
96 ```bash
97 pytest
98 ```
99* **Format code**:
100 ```bash
101 ruff format .
102 ```
103* **Lint and auto-fix code**:
104 ```bash
105 ruff check . --fix
106 ```
107* **Run static type checking**:
108 ```bash
109 mypy .
110 ```
111
112## Testing Guidelines
113
114A multi-layered testing strategy ensures the framework's stability and correctness.
115
116* **Framework**: All tests are written using `pytest`.
117* **Test Client**: Integration tests for API endpoints must use `fastapi.testclient.TestClient`, which wraps `httpx` to send requests to the application.
118* **File Placement**: Test files are located in the `tests/` directory. The structure of `tests/` mirrors the `fastapi/` source directory.
119* **Asynchronous Tests**: Tests for `async` code must be marked appropriately and are executed using the `anyio` pytest backend.
120* **Static Analysis as a Test**: Passing `mypy` checks is a mandatory part of the testing suite. Code that fails type checking is considered broken.
121* **Mocking**: Use standard mocking libraries compatible with `pytest` (e.g., `unittest.mock` or `pytest-mock`) to test components in isolation.
122* **Coverage**: New code should have high test coverage. Use `coverage` to identify and cover untested code paths.
123
124## Security & Compliance
125
126* **Vulnerability Reporting**: Security vulnerabilities **must not** be reported via public GitHub issues. Report them privately to `security@tiangolo.com`.
127* **Authentication & Authorization**: When implementing security features, leverage the framework's built-in security schemes from `fastapi.security` (e.g., `OAuth2PasswordBearer`, `APIKeyHeader`).
128* **Dependency Updates**: Keep all project dependencies up-to-date, especially FastAPI itself, to ensure you have the latest security patches.
129
130## Dependencies & Environment
131
132* **Dependency Manager**: The project uses `pdm` for dependency and environment management. The single source of truth for dependencies is `pyproject.toml`.
133* **Dependency Groups**:
134 * `[project.dependencies]`: Core runtime dependencies required for the framework to function.
135 * `[project.optional-dependencies]`: Optional features users can install (e.g., `[all]`, `[standard]`).
136 * `[tool.pdm.dev-dependencies]`: Development-only dependencies, organized into groups like `tests` and `docs`.
137* **Adding Dependencies**:
138 * To add a runtime dependency: `pdm add <package>`
139 * To add a development dependency to a group: `pdm add -dG <group> <package>` (e.g., `pdm add -dG tests pytest-mock`)
140
141## PR & Git Rules
142
143* **Branching Convention**: Create feature branches from an up-to-date `main` branch. Name branches with a prefix indicating the work type, e.g., `feature/my-new-feature` or `fix/bug-in-routing`.
144* **Commit Messages**: Follow conventional commit message standards for clarity.
145* **Pull Request Process**:
146 1. Open PRs against the `main` branch.
147 2. The PR description must clearly explain the "what" and "why" of the change and link to any relevant GitHub issues.
148 3. All CI checks (testing, linting, type checking) must pass before a PR can be merged.
149 4. Engage with reviewer feedback and push updates to your branch to update the PR.
150* **Contributing Guide**: Before starting any work, you must read the detailed guidelines at [Development - Contributing](https://fastapi.tiangolo.com/contributing/).
151
152## Documentation Standards
153
154* **Public Documentation**: The public-facing documentation is built with `MkDocs` and the `Material for MkDocs` theme from source files in `docs_src/`.
155* **Docstrings**: All public functions, classes, and methods **must** have clear, comprehensive docstrings. API reference documentation is generated automatically from these docstrings using `mkdocstrings`.
156* **Type Hints in Docs**: Type hints are a fundamental part of the documentation and are rendered automatically. Ensure they are correct and explicit.
157* **Examples**: All new features or significant changes must be accompanied by documentation updates, including clear, complete, and runnable examples.
158
159## Common Patterns
160
161These are recurring design patterns and strict rules that must be followed throughout the codebase.
162
163* **Declarative Routing with Decorators**: ALWAYS define API endpoints using decorators on path operation functions. This keeps routing logic clean and co-located with the implementation.
164 ```python
165 from fastapi import FastAPI
166
167 app = FastAPI()
168
169 @app.get("/items/{item_id}")
170 async def read_item(item_id: int):
171 return {"item_id": item_id}
172 ```
173* **Dependency Injection for Resources**: ALWAYS use the `Depends` system for managing per-request resources like database sessions. NEVER create global, shared resources for requests.
174 ```python
175 # The correct pattern for managing a database session
176 def get_db() -> Generator[Session, None, None]:
177 db = SessionLocal()
178 try:
179 yield db # The session is provided to the endpoint
180 finally:
181 db.close() # The session is guaranteed to be closed
182
183 @app.get("/items/")
184 async def read_items(db: Session = Depends(get_db)):
185 return db.query(Item).all()
186 ```
187* **Pydantic for Data Contracts**: ALWAYS define `pydantic.BaseModel` classes for all request and response data structures. This provides automatic validation, serialization, and documentation.
188* **Async for I/O**: ALWAYS use `async def` for path operation functions and use `await` with `async`-compatible libraries for any I/O-bound operations (e.g., database calls, external API requests) to avoid blocking the event loop.
189
190## Agent Workflow / SOP
191
192To contribute a new feature or fix, follow this standard operating procedure:
193
1941. **Sync `main`**: Ensure your local `main` branch is up-to-date with the upstream repository.
1952. **Create Branch**: Create a new feature branch from `main` (e.g., `git checkout -b feature/my-new-feature`).
1963. **Implement Changes**: Write the code for the new feature or fix, strictly adhering to the project's code style, typing, and architectural conventions.
1974. **Write Tests**: Add comprehensive `pytest` tests covering the new code. Include tests for success cases, edge cases, and error conditions.
1985. **Write Documentation**: Update the documentation in the `docs_src/` directory. Add a new page or update an existing one to explain the feature, providing clear, runnable examples.
1996. **Local Verification**: Before pushing, run the entire local quality suite to ensure everything passes:
200 * `pytest`
201 * `ruff format .`
202 * `ruff check . --fix`
203 * `mypy .`
2047. **Push and Open PR**: Push your branch to the remote and open a Pull Request against the `main` branch. Provide a detailed description of your changes.
2058. **Review and Iterate**: Respond to any feedback from code reviewers. Push subsequent commits to your branch to update the PR.
206
207## Few-Shot Examples
208
209This example demonstrates the critical rule of using non-blocking I/O in `async` functions.
210
211### Bad: Blocking I/O in an `async` route
212
213This code uses the synchronous `requests` library, which will block the entire server's event loop, preventing it from handling any other requests until this one is complete. This is a severe performance anti-pattern.
214
215```python
216# ANTI-PATTERN: This will block the entire application!
217@app.get("/bad")
218async def bad_request():
219 import requests
220 response = requests.get("http://example.com") # BLOCKING!
221 return response.json()
222```
223
224### Good: Non-blocking I/O in an `async` route
225
226This code uses the `httpx` library, which is `async`-compatible. The `await` keyword correctly pauses the function, allowing the event loop to handle other tasks while waiting for the network response, thus maintaining high concurrency.
227
228```python
229# CORRECT PATTERN: Non-blocking I/O
230@app.get("/good")
231async def good_request():
232 import httpx
233 async with httpx.AsyncClient() as client:
234 response = await client.get("http://example.com") # NON-BLOCKING!
235 return response.json()
236
@@ −1 +1 @@
1−# AGENTS.md — AutogenerateAgentsMD.md
1+# AGENTS.md — fastapi
22
33 ## Project Overview
44
5−`GenerateAgents.md` is a Python command-line tool that automates the creation of a comprehensive `AGENTS.md` file for any public GitHub or local code repository. It acts as an automated codebase analyst and technical writer, using the `dspy` framework to programmatically interface with LLMs. The tool clones and analyzes a target codebase to produce a standardized blueprint, enabling AI coding agents to rapidly understand a project's architecture, conventions, and data flow. The primary language is Python (>=3.12).
5+FastAPI is a modern, high-performance Python web framework for building APIs, based on standard Python type hints. It is built on top of Starlette for web functionality and Pydantic for data validation and serialization. The project's core philosophy is to provide developers with a world-class experience through robust tools, predictable behavior, and frictionless workflows, enabling the creation of clear, performant, and automatically documented APIs.
66
77 ## Tech Stack
88
9−* **Primary Language:** Python (>=3.12)
10−* **Core AI Framework:** `dspy`
11−* **LLM Abstraction Layer:** `litellm`
12−* **Dependency Management:** `uv`
13−* **CLI Framework:** `argparse` (standard library)
14−* **Configuration:** `python-dotenv`
15−* **Version Control Interaction:** `git` (via `subprocess`)
16−* **Testing:** `pytest`
9+* **Primary Language**: Python
10+* **Core Frameworks**: Starlette (ASGI foundation), Pydantic (data validation/serialization)
11+* **Typing**: `typing-extensions`, `typing-inspection`
12+* **Ecosystem**: Uvicorn (ASGI server), HTTPX (async HTTP client for testing)
13+* **Build System**: `pdm-backend`
14+* **Testing**: `pytest`, `anyio` (for async tests), `coverage`
15+* **Code Quality**: `ruff` (linter and formatter), `black` (formatter), `mypy` (static type checker)
16+* **Documentation**: `mkdocs-material`, `mkdocstrings`
1717
1818 ## Architecture
1919
20−The application follows a modular, stateless pipeline pattern orchestrated by the main CLI entry point.
20+The project is organized with a clear separation of concerns, primarily distinguishing between the core framework logic, tests, and documentation.
2121
22−* `src/autogenerateagentsmd/cli.py`: The command-line interface entry point. It parses arguments and orchestrates the entire analysis and generation pipeline via the `run_agents_md_pipeline` function.
23−* `src/autogenerateagentsmd/modules.py`: Contains the core `dspy.Module` classes (`CodebaseConventionExtractor`, `AgentsMdCreator`, `AntiPatternExtractor`). These modules encapsulate the primary LLM-driven logic for analyzing code and synthesizing the final document.
24−* `src/autogenerateagentsmd/signatures.py`: Defines the contracts for LLM interactions using `dspy.Signature`. These signatures specify the expected inputs (e.g., source code) and outputs (e.g., extracted conventions) for each LLM-powered step.
25−* `src/autogenerateagentsmd/model_config.py`: Centralizes the configuration for supported LLMs, making it easy to switch between models like Gemini, Claude, and OpenAI.
26−* `src/autogenerateagentsmd/utils.py`: Contains helper functions for non-LLM tasks, such as cloning Git repositories, loading files into memory, and other file system operations.
27−* `tests/`: The test suite, containing end-to-end and unit tests.
28−* `pyproject.toml`: Defines project metadata, dependencies, and the `autogenerateagentsmd` console script entry point.
22+* `fastapi/`: The core source code of the framework.
23+ * `applications.py`: Contains the main `FastAPI` application class.
24+ * `routing.py`: Defines the `APIRouter` and handles all routing logic.
25+ * `dependencies/`: Implements the dependency injection system.
26+ * `openapi/`: Manages the OpenAPI schema generation.
27+ * `security/`: Provides built-in security utilities like OAuth2 and API Keys.
28+* `tests/`: Contains all unit, integration, and end-to-end tests. The directory structure mirrors the `fastapi/` source directory.
29+* `docs_src/`: The raw Markdown source files for the official documentation.
30+* `scripts/`: Holds utility scripts for development, maintenance, and CI/CD.
31+* `pyproject.toml`: The central configuration file for project metadata, dependencies, and all development tooling.
2932
3033 ## Code Style
3134
32−The project enforces a strict and consistent Python coding style.
35+The project enforces a strict, automated code style to ensure consistency and readability.
3336
34−* **Type Hinting**: Type hints are strictly mandatory for all function parameters and return values.
37+* **Formatting**: All code is formatted using `black` and `ruff format`. Manual formatting adjustments are not permitted. The command `ruff format .` should be run before committing.
38+* **Linting**: `ruff check` is used for linting. All code must be free of its errors and warnings, which includes rules for ordered imports, no unused variables, and other best practices.
39+* **Static Typing**: This is a non-negotiable cornerstone of the codebase.
40+ * All function signatures, method signatures, variables, and class attributes **must** have explicit type hints.
41+ * The entire codebase must pass `mypy .` static analysis without any errors. This is critical for preventing bugs and ensuring a great developer experience via IDE autocompletion.
3542
36− ```python
37− # Good
38− def load_source_tree(repo_path: str) -> dict[str, str]:
39− # ...
43+An example of a correctly styled and typed function signature:
4044
41− # Bad
42− def load_source_tree(repo_path):
43− # ...
44− ```
45+```python
46+from typing import Any, Dict
4547
46−* **Naming Conventions**:
47− * `snake_case` for functions, methods, and variables (e.g., `run_agents_md_pipeline`).
48− * `PascalCase` for all classes (e.g., `CodebaseConventionExtractor`).
49− * `ALL_CAPS_WITH_UNDERSCORES` for module-level constants.
48+def create_item(item_id: int, data: Dict[str, Any]) -> Dict[str, Any]:
49+ # function implementation
50+ return {"item_id": item_id, **data}
51+```
5052
51−* **Import Ordering**: Imports must be grouped at the top of each file in the following order: 1) Standard library, 2) Third-party libraries, 3) Local application imports.
53+## Anti-Patterns & Restrictions
5254
53− ```python
54− # Good
55− import argparse
56− import logging
57− from pathlib import Path
55+To maintain performance, concurrency safety, and maintainability, the following patterns are strictly forbidden.
5856
59− import dspy
60− from dotenv import load_dotenv
57+1. **NEVER perform blocking I/O in `async` routes.** A synchronous call like `requests.get()` or `time.sleep()` in an `async` function will freeze the entire server's event loop. Always use `async`-compatible libraries (e.g., `httpx`, `asyncpg`). For CPU-bound work, use `asyncio.to_thread()`.
58+2. **NEVER use global mutable variables for request state.** This leads to race conditions, data leaks between requests, and makes testing impossible. All per-request state must be managed via the Dependency Injection system (`Depends`).
59+3. **NEVER manually validate request data.** This bypasses Pydantic's validation, error reporting, and automatic OpenAPI schema generation. Always define a Pydantic `BaseModel` and use it as a type hint in your endpoint function to let FastAPI handle validation automatically.
60+4. **NEVER create monolithic routers.** A single file with hundreds of routes is unmaintainable. Group related endpoints into separate `APIRouter` instances in different modules and include them in the main application using `app.include_router()`.
6161
62− from .modules import AgentsMdCreator, CodebaseConventionExtractor
63− from .utils import clone_repo, load_source_tree
64− ```
62+## Database & State Management
6563
66−* **Formatting**: Use 4-space indentation and maintain a line length between 80-100 characters.
64+State and data management conventions are designed to ensure concurrency safety, testability, and clear data contracts.
6765
68−## Anti-Patterns & Restrictions
66+* **Golden Rule of State**: **Never use global mutable state.** Global variables modified during requests are a source of race conditions and are forbidden. For application-wide, read-only configuration, use `pydantic-settings` to load settings at startup.
67+* **Per-Request State**: The **Dependency Injection (`Depends`)** system is the **only** approved way to manage request-scoped state and resources, such as database sessions.
68+* **Resource Management**: For resources that need setup and teardown (like database connections), use a `yield` statement within a dependency function. This pattern ensures resources are properly cleaned up, even in case of errors.
6969
70−* **NEVER use on private codebases**: The tool sends the full source code to third-party LLM APIs. Using it on private, proprietary, or sensitive codebases is a significant security risk. It is designed **exclusively** for public, open-source repositories.
71−* **NEVER commit secrets**: Do not commit the `.env` file or any other file containing API keys or secrets to version control.
72−* **DO NOT introduce new LLM frameworks**: The project architecture is tightly coupled to `dspy`. Avoid introducing other orchestration frameworks like LangChain or LlamaIndex.
73−* **AVOID new end-to-end tests**: E2E tests are slow and costly due to live API calls. Prioritize mocked unit tests for new functionality unless there is a strong justification for an E2E test.
70+```python
71+# Correct pattern for managing a database session
72+def get_db() -> Generator[Session, None, None]:
73+ db = SessionLocal()
74+ try:
75+ yield db # Provide the session to the endpoint
76+ finally:
77+ db.close() # Guarantee the session is closed
78+```
7479
75−## Database & State Management
80+* **Data Contracts**: Use Pydantic `BaseModel` classes for all data entering or leaving the API. Define separate models for request bodies and use the `response_model` parameter in decorators to control response bodies, preventing accidental data leakage.
7681
77−The application is entirely **stateless**. It does not use a database or any form of persistent storage between runs. All configuration is loaded at runtime from command-line arguments and the `.env` file. The application's state exists only for the duration of a single execution, primarily as an in-memory dictionary (`source_tree`) holding the target repository's code. The only output is the generated `AGENTS.md` file.
78−
7982 ## Error Handling & Logging
8083
81−* **Error Handling**: Application logic within modules and utilities should raise specific exceptions (e.g., `FileNotFoundError`, `subprocess.CalledProcessError`). Generic `except Exception` blocks should be avoided. A single global `try...except Exception` block exists in `src/autogenerateagentsmd/cli.py` to catch any unhandled exceptions at the top level and provide a clean exit with a user-friendly error message.
82−* **Logging**: The standard `logging` module is used for progress reporting. It is configured in `cli.py` to print `INFO`-level messages to the console, informing the user about the current stage of the pipeline (e.g., "Cloning repository...", "Extracting conventions...").
84+The framework uses a structured approach to error handling and logging.
8385
86+* **Client Errors**: For all expected client-side errors (e.g., resource not found, permission denied), you **must** raise `fastapi.HTTPException` with the appropriate status code.
87+* **Validation Errors**: `RequestValidationError` is raised automatically by the framework when incoming request data fails Pydantic validation. The default handler returns a `422 Unprocessable Entity` response with detailed error information.
88+* **Unhandled Exceptions**: Custom exception handlers can be added to the application to catch unhandled server errors and return a consistent, formatted error response instead of a generic 500 error.
89+* **Logging**: **Do not use `print()` statements.** All logging within the framework must be done using the central logger obtained via `logging.getLogger("fastapi")`.
90+
8491 ## Testing Commands
8592
86−* **Install dependencies for testing:**
93+Before submitting code, run the full local quality suite using these commands from the project root.
94+
95+* **Run all tests**:
8796 ```bash
88− uv sync --extra dev
97+ pytest
8998 ```
90−* **Run all tests (excluding slow E2E tests):**
99+* **Format code**:
91100 ```bash
92− pytest
101+ ruff format .
93102 ```
94−* **Run only the end-to-end (E2E) tests:**
103+* **Lint and auto-fix code**:
95104 ```bash
96− pytest -m e2e
105+ ruff check . --fix
97106 ```
98−* **Run tests for a specific file:**
107+* **Run static type checking**:
99108 ```bash
100− pytest tests/test_utils.py
109+ mypy .
101110 ```
102111
103112 ## Testing Guidelines
104113
105−The project uses `pytest` for testing. The testing strategy is two-pronged:
114+A multi-layered testing strategy ensures the framework's stability and correctness.
106115
107−* **End-to-End (E2E) Tests**:
108− * Located in `tests/test_e2e_pipeline.py`.
109− * These tests validate the entire pipeline by cloning real public repositories and making live LLM API calls.
110− * They are marked with `@pytest.mark.e2e` and are run sparingly due to their cost and long execution time.
111− * They serve as the ultimate validation that the integrated system works as expected.
116+* **Framework**: All tests are written using `pytest`.
117+* **Test Client**: Integration tests for API endpoints must use `fastapi.testclient.TestClient`, which wraps `httpx` to send requests to the application.
118+* **File Placement**: Test files are located in the `tests/` directory. The structure of `tests/` mirrors the `fastapi/` source directory.
119+* **Asynchronous Tests**: Tests for `async` code must be marked appropriately and are executed using the `anyio` pytest backend.
120+* **Static Analysis as a Test**: Passing `mypy` checks is a mandatory part of the testing suite. Code that fails type checking is considered broken.
121+* **Mocking**: Use standard mocking libraries compatible with `pytest` (e.g., `unittest.mock` or `pytest-mock`) to test components in isolation.
122+* **Coverage**: New code should have high test coverage. Use `coverage` to identify and cover untested code paths.
112123
113−* **Unit Tests**:
114− * This is the preferred method for testing new contributions.
115− * Focus on testing individual functions in `src/autogenerateagentsmd/utils.py`.
116− * For `dspy` modules in `src/autogenerateagentsmd/modules.py`, tests should use mocking to avoid actual LLM API calls. This ensures tests are fast, deterministic, and free of cost.
117−
118124 ## Security & Compliance
119125
120−* **API Key Management**: All API keys and other secrets **must** be stored in a `.env` file at the project root. This file is explicitly listed in `.gitignore` and must never be committed to version control.
121−* **Data Handling and Privacy**: The tool's core function involves sending the entire source code of a target repository to external, third-party LLM APIs. This is a critical security consideration. **NEVER** run this tool on any repository containing proprietary code, sensitive data, secrets, or personally identifiable information (PII). It is intended for use only on publicly available, open-source software.
126+* **Vulnerability Reporting**: Security vulnerabilities **must not** be reported via public GitHub issues. Report them privately to `security@tiangolo.com`.
127+* **Authentication & Authorization**: When implementing security features, leverage the framework's built-in security schemes from `fastapi.security` (e.g., `OAuth2PasswordBearer`, `APIKeyHeader`).
128+* **Dependency Updates**: Keep all project dependencies up-to-date, especially FastAPI itself, to ensure you have the latest security patches.
122129
123130 ## Dependencies & Environment
124131
125−* **Dependency Management**: Dependencies are managed with `uv` and are defined in `pyproject.toml`.
126− * Production dependencies are under `[project.dependencies]`.
127− * Development dependencies (like `pytest`) are under `[project.optional-dependencies]dev`.
128−* **Installation**: To install all required dependencies for development and testing, run the following command from the project root:
129− ```bash
130− uv sync --extra dev
131− ```
132−* **Environment Variables**: The application requires API keys for the desired LLM providers. Create a `.env` file in the project root and add the necessary keys.
133− ```bash
134− # Example .env file
135− OPENAI_API_KEY="sk-..."
136− ANTHROPIC_API_KEY="..."
137− GEMINI_API_KEY="..."
138− ```
139−* **Runtime Version**: The project requires Python version 3.12 or newer.
132+* **Dependency Manager**: The project uses `pdm` for dependency and environment management. The single source of truth for dependencies is `pyproject.toml`.
133+* **Dependency Groups**:
134+ * `[project.dependencies]`: Core runtime dependencies required for the framework to function.
135+ * `[project.optional-dependencies]`: Optional features users can install (e.g., `[all]`, `[standard]`).
136+ * `[tool.pdm.dev-dependencies]`: Development-only dependencies, organized into groups like `tests` and `docs`.
137+* **Adding Dependencies**:
138+ * To add a runtime dependency: `pdm add <package>`
139+ * To add a development dependency to a group: `pdm add -dG <group> <package>` (e.g., `pdm add -dG tests pytest-mock`)
140140
141141 ## PR & Git Rules
142142
143−The project uses Git for version control. The repository includes a standard Python `.gitignore` file to exclude common artifacts like `__pycache__`, virtual environments (`.venv`), build directories, and the `.env` file containing secrets. No specific branch naming conventions or commit message formats are formally documented.
143+* **Branching Convention**: Create feature branches from an up-to-date `main` branch. Name branches with a prefix indicating the work type, e.g., `feature/my-new-feature` or `fix/bug-in-routing`.
144+* **Commit Messages**: Follow conventional commit message standards for clarity.
145+* **Pull Request Process**:
146+ 1. Open PRs against the `main` branch.
147+ 2. The PR description must clearly explain the "what" and "why" of the change and link to any relevant GitHub issues.
148+ 3. All CI checks (testing, linting, type checking) must pass before a PR can be merged.
149+ 4. Engage with reviewer feedback and push updates to your branch to update the PR.
150+* **Contributing Guide**: Before starting any work, you must read the detailed guidelines at [Development - Contributing](https://fastapi.tiangolo.com/contributing/).
144151
145152 ## Documentation Standards
146153
147−* **User Documentation**: The `README.md` file serves as the primary user-facing guide. It contains the project's purpose, installation instructions, and command-line usage examples.
148−* **Agent/Developer Documentation**: The `AGENTS.md` file (which this tool generates for itself) is the definitive technical guide for developers and AI agents. It provides a deep, structured overview of the architecture, conventions, and patterns.
149−* **In-Code Documentation**:
150− * **Type Hints**: Mandatory for all function signatures.
151− * **Docstrings**: Public modules and complex functions should have descriptive docstrings explaining their purpose, arguments, and return values.
154+* **Public Documentation**: The public-facing documentation is built with `MkDocs` and the `Material for MkDocs` theme from source files in `docs_src/`.
155+* **Docstrings**: All public functions, classes, and methods **must** have clear, comprehensive docstrings. API reference documentation is generated automatically from these docstrings using `mkdocstrings`.
156+* **Type Hints in Docs**: Type hints are a fundamental part of the documentation and are rendered automatically. Ensure they are correct and explicit.
157+* **Examples**: All new features or significant changes must be accompanied by documentation updates, including clear, complete, and runnable examples.
152158
153159 ## Common Patterns
154160
155−* **Stateless Pipeline Pattern**: The entire application is orchestrated as a linear, stateless pipeline in `src/autogenerateagentsmd/cli.py`. Data flows from one stage to the next (e.g., `load_source_tree` -> `CodebaseConventionExtractor` -> `AgentsMdCreator`) without persisting state between executions.
156−* **DSPy Modules for LLM Logic**: All direct interactions with large language models are encapsulated within `dspy.Module` classes (e.g., `AgentsMdCreator`). This separates the prompt engineering and LLM logic from the main application orchestration code.
157−* **Strict Type Hinting**: ALWAYS add type hints to all function parameters and return values. This is a non-negotiable standard for code clarity and static analysis.
161+These are recurring design patterns and strict rules that must be followed throughout the codebase.
162+
163+* **Declarative Routing with Decorators**: ALWAYS define API endpoints using decorators on path operation functions. This keeps routing logic clean and co-located with the implementation.
158164 ```python
159− # ALWAYS do this
160− def clone_repo(github_url: str, target_dir: Path) -> None:
161− ...
165+ from fastapi import FastAPI
166+
167+ app = FastAPI()
168+
169+ @app.get("/items/{item_id}")
170+ async def read_item(item_id: int):
171+ return {"item_id": item_id}
162172 ```
163−* **Specific Exception Handling**: NEVER use a generic `except Exception:` in application modules. ALWAYS catch specific, anticipated exceptions to handle errors gracefully and avoid masking unknown bugs.
173+* **Dependency Injection for Resources**: ALWAYS use the `Depends` system for managing per-request resources like database sessions. NEVER create global, shared resources for requests.
164174 ```python
165− # Good
166− try:
167− # some file operation
168− except FileNotFoundError:
169− logger.error("Could not find the specified file.")
170−
171− # Bad
172− try:
173− # some file operation
174− except Exception as e:
175− logger.error(f"An unknown error occurred: {e}")
175+ # The correct pattern for managing a database session
176+ def get_db() -> Generator[Session, None, None]:
177+ db = SessionLocal()
178+ try:
179+ yield db # The session is provided to the endpoint
180+ finally:
181+ db.close() # The session is guaranteed to be closed
182+
183+ @app.get("/items/")
184+ async def read_items(db: Session = Depends(get_db)):
185+ return db.query(Item).all()
176186 ```
187+* **Pydantic for Data Contracts**: ALWAYS define `pydantic.BaseModel` classes for all request and response data structures. This provides automatic validation, serialization, and documentation.
188+* **Async for I/O**: ALWAYS use `async def` for path operation functions and use `await` with `async`-compatible libraries for any I/O-bound operations (e.g., database calls, external API requests) to avoid blocking the event loop.
177189
178190 ## Agent Workflow / SOP
179191
180−When tasked with modifying or extending this codebase, follow this standard operating procedure:
192+To contribute a new feature or fix, follow this standard operating procedure:
181193
182−1. **Understand the Goal**: Clarify the specific change required. Is it adding a new analysis capability, supporting a new LLM, or fixing a bug in the file processing?
183−2. **Locate Relevant Code**:
184− * For CLI changes (new arguments): `src/autogenerateagentsmd/cli.py`.
185− * For new LLM-driven analysis: Define a new `dspy.Signature` in `signatures.py` and a new `dspy.Module` in `modules.py`.
186− * For general helper functions (e.g., file handling): `src/autogenerateagentsmd/utils.py`.
187− * For model configuration: `src/autogenerateagentsmd/model_config.py`.
188−3. **Implement the Change**: Adhere strictly to the coding conventions:
189− * Add mandatory type hints for all new functions.
190− * Use `snake_case` for functions/variables and `PascalCase` for classes.
191− * Isolate LLM logic within a `dspy.Module`.
192−4. **Write Tests**:
193− * For changes in `utils.py`, add a new unit test to the appropriate file in the `tests/` directory.
194− * For a new `dspy.Module`, write a unit test that mocks the LLM call to verify the module's behavior without making a real API request.
195−5. **Verify**: Run the local test suite using `pytest` to ensure your changes have not introduced any regressions.
196−6. **Document**: If you've added a new user-facing feature (like a new CLI flag), update the `README.md`. The `AGENTS.md` is auto-generated and does not need manual updates.
194+1. **Sync `main`**: Ensure your local `main` branch is up-to-date with the upstream repository.
195+2. **Create Branch**: Create a new feature branch from `main` (e.g., `git checkout -b feature/my-new-feature`).
196+3. **Implement Changes**: Write the code for the new feature or fix, strictly adhering to the project's code style, typing, and architectural conventions.
197+4. **Write Tests**: Add comprehensive `pytest` tests covering the new code. Include tests for success cases, edge cases, and error conditions.
198+5. **Write Documentation**: Update the documentation in the `docs_src/` directory. Add a new page or update an existing one to explain the feature, providing clear, runnable examples.
199+6. **Local Verification**: Before pushing, run the entire local quality suite to ensure everything passes:
200+ * `pytest`
201+ * `ruff format .`
202+ * `ruff check . --fix`
203+ * `mypy .`
204+7. **Push and Open PR**: Push your branch to the remote and open a Pull Request against the `main` branch. Provide a detailed description of your changes.
205+8. **Review and Iterate**: Respond to any feedback from code reviewers. Push subsequent commits to your branch to update the PR.
197206
198207 ## Few-Shot Examples
199208
200−### 1. Type Hinting
209+This example demonstrates the critical rule of using non-blocking I/O in `async` functions.
201210
202−* **Good**: Mandatory type hints for parameters and return values.
203− ```python
204− from pathlib import Path
211+### Bad: Blocking I/O in an `async` route
205212
206− def save_markdown_file(content: str, output_path: Path) -> None:
207− """Saves the given content to a file."""
208− output_path.parent.mkdir(parents=True, exist_ok=True)
209− output_path.write_text(content, encoding="utf-8")
210− ```
213+This code uses the synchronous `requests` library, which will block the entire server's event loop, preventing it from handling any other requests until this one is complete. This is a severe performance anti-pattern.
211214
212−* **Bad**: Missing type hints.
213− ```python
214− def save_markdown_file(content, output_path):
215− """Saves the given content to a file."""
216− output_path.parent.mkdir(parents=True, exist_ok=True)
217− output_path.write_text(content, encoding="utf-8")
218− ```
215+```python
216+# ANTI-PATTERN: This will block the entire application!
217+@app.get("/bad")
218+async def bad_request():
219+ import requests
220+ response = requests.get("http://example.com") # BLOCKING!
221+ return response.json()
222+```
219223
220−### 2. Import Ordering
224+### Good: Non-blocking I/O in an `async` route
221225
222−* **Good**: Imports are correctly grouped (standard library, third-party, local).
223− ```python
224− import logging
225− import subprocess
226− from pathlib import Path
226+This code uses the `httpx` library, which is `async`-compatible. The `await` keyword correctly pauses the function, allowing the event loop to handle other tasks while waiting for the network response, thus maintaining high concurrency.
227227
228− from git.repo import Repo # Hypothetical third-party library
228+```python
229+# CORRECT PATTERN: Non-blocking I/O
230+@app.get("/good")
231+async def good_request():
232+ import httpx
233+ async with httpx.AsyncClient() as client:
234+ response = await client.get("http://example.com") # NON-BLOCKING!
235+ return response.json()
229236
230− from .exceptions import GitCloneError
231− ```
232−
233−* **Bad**: Imports are mixed together without logical grouping.
234− ```python
235− from pathlib import Path
236− from .exceptions import GitCloneError
237− import logging
238− from git.repo import Repo
239− import subprocess
240− ```
241−
242−### 3. Error Handling
243−
244−* **Good**: Catching a specific, expected exception.
245− ```python
246− import subprocess
247−
248− def run_git_command(command: list[str]) -> str:
249− try:
250− result = subprocess.run(
251− command,
252− check=True,
253− capture_output=True,
254− text=True
255− )
256− return result.stdout
257− except subprocess.CalledProcessError as e:
258− logging.error(f"Git command failed: {e.stderr}")
259− raise
260− ```
261−
262−* **Bad**: Using a generic `except Exception` which can hide other bugs.
263− ```python
264− import subprocess
265−
266− def run_git_command(command: list[str]) -> str:
267− try:
268− result = subprocess.run(
269− command,
270− check=True,
271− capture_output=True,
272− text=True
273− )
274− return result.stdout
275− except Exception as e: # This is too broad
276− logging.error(f"An unexpected error occurred: {e}")
277− raise
278−
