Make Your Library AI-Friendly
Modern libraries should be designed with both human developers and AI assistants in mind. As LLMs become integral to development workflows, library creators can significantly improve adoption by following AI-friendly design principles.
Use a Shallow Namespace
Keep your library's functionality directly accessible from the root import. Instead of burying features in nested sub-modules like from my_library.core.utils.helpers import feature
, make them available directly: from my_library import feature
. This shallow structure reduces the cognitive load for both humans and LLMs, making it easier to discover and use your library's capabilities — especially important for newer libraries that AI models haven't been extensively trained on.
Provide Comprehensive Type Annotations
Every public function and method should have complete type hints. Type annotations serve as inline documentation that helps AI models understand expected inputs and outputs, reducing errors in generated code. For example:
def process_data(items: list[dict[str, Any]], threshold: float = 0.5) -> pd.DataFrame:
"""Process raw data items into a structured DataFrame."""
Write Excellent Inline Documentation
Include working code examples directly in your docstrings. Don't just describe what a function does — show how to use it. AI models can learn from these examples to generate accurate usage patterns:
def calculate_metrics(data: np.ndarray) -> dict[str, float]:
"""Calculate statistical metrics for the given data.
Examples:
>>> data = np.array([1, 2, 3, 4, 5])
>>> metrics = calculate_metrics(data)
>>> print(metrics['mean'])
3.0
"""
Create Clear, Unambiguous Documentation
Avoid jargon and explain domain-specific terms clearly. Your documentation should be immediately understandable without requiring deep domain knowledge. Define crucial terms explicitly and use consistent terminology throughout. This helps AI models build accurate mental models of your library's concepts and relationships.
By following these principles, you make your library more predictable and easier for AI assistants to comprehend, ultimately leading to better code generation and fewer errors when developers use AI tools to work with your library.
For a more in-depth discussion, see this talk with Danny Roy Greenfeld and Isaac.