6.5 KiB
6.5 KiB
API Design & Interfaces
Rules for designing public APIs, managing visibility, backward compatibility, and API patterns
When to check: When designing or modifying public APIs, parameters, or class interfaces
Rules
Compatibility impacts
- Treat previously valid user code that now needs modification as a compatibility impact.
- Preserve compatibility unless the bridge retains incorrect behavior, creates a permanent legacy-only API, or makes the contract contradictory.
- When no valid bridge exists, identify the exact exception in
docs/version-policy.md. - Without an applicable exception, deprecate the old behavior before removal or wait for a major release.
- Treat non-underscore symbols on public modules and classes as public by default. A missing docstring alone does not make a symbol internal.
- Treat additions to released public unions as compatibility-relevant changes. Inspect attributes common to prior arms and exhaustive consumers.
- Do not add semantically false fields only to preserve a union's previous structural shape.
- For every permitted compatibility impact, add the
compatibility impactlabel and a release note. - Add a
[!WARNING]PR section that names affected code, the policy exception, and the migration. - Add an exact API-check waiver when the deterministic compatibility gate reports the permitted change: a
.github/api-compatibility-waivers/<fingerprint>.jsonfile, named by the fingerprint the gate reports, holdingagainst(the release tag the gate compared with),reason, andpull_request(your PR's URL). If that file already exists for an older release, replace its contents with this PR's waiver. - Treat model-name
Literalaliases (listed undermodel_name_literalsin.github/api-compatibility-allowlist.json; add one there when the gate reports a change to it) as autocompletion aids. The gate passes changes to theirLiteralstring members, and any change whose new value is nothing but stringLiterals, such as an SDK type replaced by a curatedLiteral; any other change to them still needs a waiver. An arm the new value drops that isn't a stringLiteral, such asstr |or that SDK type, counts as removed names. Removing a name from an alias without astr |arm is a permitted compatibility impact: add thecompatibility impactlabel and a release note. Code that passes the removed name stops type-checking. - Treat registry constants (listed under
growing_collectionsin.github/api-compatibility-allowlist.json, such as CLAI'sSETTING_FIELDSandSTRING_SETTINGS, orCAPABILITY_TYPES) as growing: the gate passes a change that only adds entries to thedictorsetliteral, or, for a comprehension over a single tuple or list literal likeCAPABILITY_TYPES, only adds items to that sequence. Removing an entry or changing an entry's value still needs a waiver, as does changing a comprehension's key, value or filter, and removing a setting needs a deprecation first. List another registry there when adding entries to it is never a compatibility impact. - Change the
descriptionof aField(...)default without a waiver: the gate passes a value change whose two sides are calls to the bare nameFieldwith the same positional arguments and the same keywords, in the same order, apart fromdescription. Any other change still needs a waiver, including a switch topydantic.Field.
- Prefix implementation details with underscore (
_) and exclude them from__all__to avoid accidental public API commitments.
- Export commonly-used types and classes from top-level
pydantic_aipackage — hides internal structure and simplifies user imports — Makes the public API easier to use and allows internal refactoring without breaking user code that would otherwise depend on specific submodule paths
- Use
_: KW_ONLYmarker before optional fields in dataclasses/Pydantic models — Prevents breakage when adding parameters — callers can't accidentally pass defaults positionally, ensuring backward compatibility when fields are added or reordered
- Prefer instance methods when accessing
selfattributes or enabling polymorphism; use module-level functions when no instance state is needed — Reduces unnecessary coupling and parameter passing while enabling proper polymorphism; extract shared logic to private top-level helpers to avoid duplication across classes
- Keep old names as deprecated aliases when renaming public API elements — prevents breaking existing code — Maintains backward compatibility so users can migrate gradually rather than experiencing immediate breakage when upgrading
- Return new collections from transform functions instead of mutating inputs to prevent surprising side effects. Exceptions: performance-critical paths or functions named
update_*/*_inplace.
- Don't access or modify private attributes (
_prefixed) — use public APIs, properties, or constructor parameters — Prevents breakage when internal implementation changes and ensures compatibility with library updates
- Promote settings to base classes (
ModelSettings, embedding settings) when 2-3+ providers support them; maintain backward compatibility with automatic mapping from new common fields to legacy provider-prefixed fields — Prevents API duplication across provider-specific subclasses (e.g.,OpenAIEmbeddingSettings,CohereEmbeddingSettings) while preserving backward compatibility when refactoring provider-prefixed parameters (e.g.,cohere_,openai_) to shared fields - Never change a shared default, public signature, or abstraction to accommodate one new feature — if a new type only behaves correctly once an existing public default is rewritten, the new type's design is wrong — Fix the new code instead, or split the shared change into its own PR with maintainer sign-off, so one caller's needs don't silently change behavior for every existing user
- Keep
NativeToolReturnPart.contentflat and non-redundant — avoid duplicating part fields, repeatingreturn_valuedata, single-key wrappers, or unnecessary lists — Reduces API surface area, prevents inconsistencies between duplicate fields, and simplifies consumption for both users and AI assistants
- Use
'provider:model'format (e.g.,'openai:gpt-4','anthropic:claude-3') andinfer_model()for instantiation — Ensures consistent model reference syntax across code, docs, and CLI; provides unified instantiation interface that prevents fragmentation