Po wyrenderowaniu, ten blok pojawia się jako standardowy przykład kodu. Podczas testowania jest jednak wykonywany jako normalny kod Pythona. Ta podwójna natura zapewnia, że dokumentacja pozostaje czysta dla czytelników, jednocześnie dostarczając solidne, testowalne przykłady dla deweloperów. To podejście jest szczególnie istotne w skomplikowanych dziedzinach, takich jak AI, gdzie przykłady często obejmują złożone ładowanie modeli i kroki wnioskowania.
## Bezproblemowa integracja z `pytest` i zaawansowane funkcje
Kluczowym wyróżnikiem podejścia Hugging Face jest jego bezproblemowa integracja z nowoczesnymi frameworkami testowymi, w szczególności `pytest`. Po zainstalowaniu `hf-doc-builder`, `pytest` może automatycznie wykrywać i wykonywać uruchamialne bloki w plikach Markdown, traktując każdy blok jako standardowy element testowy. Oznacza to, że przykłady w dokumentacji mogą w pełni uczestniczyć w istniejącej infrastrukturze testowej projektu, wykorzystując potężne funkcje `pytest`, takie jak asercje, fixture'y, narzędzia do debugowania i kompleksowe raportowanie.
### Ewolucja wykonywalnej dokumentacji: `doctest` vs. `doc-builder`
| Cecha | `doctest` (Tradycyjne) | `doc-builder` (Nowoczesny uruchamialny Markdown) |
| :--------------------------- | :---------------------------------------------------- | :----------------------------------------------------- |
| **Podejście do testowania** | Osadza testy jako sesje interpretera w dokumentacji | Traktuje fragmenty dokumentacji jako normalny kod Pythona do testowania |
| **Integracja** | Moduł biblioteki standardowej | Wtyczka `pytest` do bezproblemowej integracji |
| **Składnia testów** | Podpowiedzi `>>>`, dopasowywanie oczekiwanego wyniku | Standardowy kod Pythona, asercje `pytest` |
| **Elastyczność** | Ograniczone, kruche dopasowywanie wyników | Wysoka, obsługuje złożone testy, dekoratory, debugowanie |
| **Czystość dokumentacji** | Może zaśmiecać dokumentację mechaniką testową | Zachowuje czystość dokumentacji dzięki ukrytym dyrektywom |
| **Debugowanie** | Porównywanie ciągów, mniej bezpośrednia inspekcja | Standardowe debugowanie Pythona, pełne ślady stosu |
| **Setup/Teardown** | Może dodawać 'szum' do przykładów | Skutecznie zarządza kontekstem dzięki blokom kontynuacyjnym |
| **Źródło prawdy** | Format dokumentacji i osadzone testy | Źródło Markdown, testowane poprzez standardowe wykonanie Pythona |
`Doc-builder` wprowadza również **bloki kontynuacyjne**, kluczową funkcję dla wieloetapowych samouczków. Umożliwiają one autorom dzielenie przykładu na wiele widocznych fragmentów, takich jak `runnable:test_basic` a następnie `runnable:test_basic:2`. Co kluczowe, bloki te współdzielą ten sam kontekst wykonania podczas testów, umożliwiając naturalny przepływ instruktażowy bez zmuszania całego kodu do jednego długiego bloku. Ta elastyczność jest niezbędna do prowadzenia użytkowników przez złożone użycie modeli AI lub potoki przetwarzania danych.
Na przykład, przepływ pracy w rozwoju agentów AI może obejmować kilka kroków: definiowanie narzędzi agenta, inicjalizowanie agenta, a następnie uruchamianie zapytania. Bloki kontynuacyjne pozwalają na jasne przedstawienie każdego z tych kroków w oddzielnych sekcjach dokumentacji, jednocześnie będąc wykonywanymi jako jedna spójna sekwencja testowa, podobnie jak zaawansowane przepływy pracy agentowe są [Operationalizing Agentic AI: Part 1](/pl/operationalizing-agentic-ai-part-1-a-stakeholders-guide).
## Utrzymywanie czystej dokumentacji przy jednoczesnym zapewnieniu solidnego testowania
Jednym z najbardziej eleganckich rozwiązań `doc-builder` jest jego zdolność do utrzymywania czystej renderowanej dokumentacji, nawet gdy źródłowy Markdown zawiera dyrektywy specyficzne dla testów. Deweloperzy mogą osadzać komentarze takie jak `# doc-builder: hide` dla wykonywalnych linii, które nie powinny pojawiać się w dokumentacji, lub `# doc-builder: ignore-bare-assert` dla asercji, które są częścią testu, ale których komentarz nie powinien być renderowany. Podobnie, dekoratory `pytest` (`# pytest-decorator: ...`) są usuwane podczas renderowania.
Zapewnia to, że dokumentacja pozostaje skoncentrowana na nauczaniu i klarowności, nie będąc zaśmieconą przez szablon testowy. Użytkownik widzi tylko odpowiedni kod, podczas gdy podstawowy system gwarantuje jego funkcjonalność. Ta równowaga jest kluczowa dla dokumentacji narzędzi deweloperskich, gdzie zarówno estetyka, jak i absolutna poprawność są najważniejsze.
## Wpływ na duże projekty AI i nie tylko
Dla ogromnych repozytoriów, takich jak Transformers firmy Hugging Face, z setkami stron dokumentacji i tysiącami przykładów, ta funkcja jest transformacyjna. Automatyzuje zapobieganie dryfowi dokumentacji, problemowi, który w innym przypadku wymagałby ogromnego wysiłku ręcznego lub prowadziłby do stałego strumienia zepsutych przykładów. Uruchamialna dokumentacja pomaga utrzymać synchronizację dokumentacji i bazy kodu, zachowując wiarygodność w skali, w której ręczny przegląd jest po prostu niewykonalny. Jest to zgodne z szerszymi wysiłkami w społeczności AI w celu rygorystycznego [Evaluating AI Agents for Production](/pl/evaluating-ai-agents-for-production-a-practical-guide-to-strands-evals) i zapewnienia niezawodności.
Wprowadzając wykonywalną dokumentację do współczesnej ery `pytest` i wyrafinowanych potoków CI/CD, Hugging Face demonstruje silne zaangażowanie w doświadczenie deweloperów i jakość kodu. Cel pozostaje ten sam, co ponad dwie dekady temu: przykłady w dokumentacji powinny działać. Ale teraz, nie tylko ilustrują, jak kod *powinien* działać, ale ciągle *udowadniają*, że działa, tworząc bardziej niezawodny i godny zaufania ekosystem dla rozwoju AI.
Źródło oryginalne
https://huggingface.co/blog/huggingface/runnable-examplesCzęsto zadawane pytania
What is the core problem Hugging Face's runnable Markdown addresses?
Hugging Face's runnable Markdown addresses the pervasive problem of 'documentation drift,' where code examples in documentation become outdated and silently break as libraries and APIs evolve. This leads to user frustration and diminishes the credibility of the documentation. By making documentation examples runnable and testable, the doc-builder ensures that these snippets are continuously validated against the codebase, guaranteeing that they always work as advertised. This proactive approach prevents broken examples, enhances user trust, and improves the overall developer experience by providing reliable resources.
How does runnable Markdown differ from Python's traditional `doctest` module?
While both `doctest` and runnable Markdown aim for executable documentation, they differ significantly in their approach. `doctest` embeds tests directly into documentation syntax, requiring examples to mirror interactive interpreter sessions with expected output. This often leads to documentation being cluttered with test mechanics. Hugging Face's runnable Markdown, in contrast, treats documentation snippets as normal Python code living within Markdown files. It integrates seamlessly with modern testing frameworks like `pytest`, allowing for complex assertions, debugging, and standard test infrastructure. This separation of concerns ensures documentation remains clean and readable, while testing remains powerful and flexible, avoiding the limitations of `doctest`'s brittle output matching and verbose setup/teardown.
What are 'continuation blocks' in Hugging Face's `doc-builder`?
Continuation blocks are a powerful feature in Hugging Face's `doc-builder` that allow authors to split complex code examples or tutorials across multiple visible Markdown snippets while maintaining a shared execution context during testing. This means that a setup defined in one runnable block can be reused and built upon in a subsequent block, without forcing the documentation to present everything as one long, monolithic code fence. For example, `runnable:test_basic` can define initial variables, and `runnable:test_basic:2` can then use those variables. This enhances readability and instructional flow in documentation, making it easier to present multi-step processes without sacrificing the integrity of the underlying testable code.
How does `doc-builder` integrate with existing testing frameworks like `pytest`?
Hugging Face's `doc-builder` integrates natively with `pytest`, transforming runnable Markdown blocks into standard `pytest` test items. With `hf-doc-builder` installed, `pytest` automatically discovers and executes these blocks within Markdown files. This integration means that documentation examples can leverage the full power of `pytest`, including its assertion mechanisms, fixtures, decorators, and debugging tools. Failures appear as normal test failures with comprehensive tracebacks, allowing developers to debug effectively. This approach avoids the need for a special-purpose testing mini-language, embedding documentation tests directly into the project's existing, robust test infrastructure.
How does `doc-builder` ensure documentation remains clean despite embedded test logic?
A key design principle of `doc-builder` is to prevent test mechanics from polluting the user-facing documentation. Authors can embed test-only directives, such as `# pytest-decorator: transformers.testing_utils.slow` or `# doc-builder: hide` for lines that should be executable but not displayed, directly within the Markdown source. When the documentation is rendered, `doc-builder` intelligently strips these directives and comments, presenting a clean, readable code snippet to the user. This allows developers to write comprehensive tests alongside their examples without compromising the clarity and brevity expected of good documentation, maintaining a clear separation between the source code for testing and the rendered content for users.
What are the benefits of runnable documentation for large AI projects like Hugging Face Transformers?
For large AI projects such as Hugging Face Transformers, which involve extensive documentation and thousands of code examples, runnable documentation offers immense benefits. It drastically reduces 'documentation drift' by continuously validating examples against the evolving codebase, ensuring they remain accurate and functional. This prevents user frustration caused by broken examples and builds trust in the documentation's reliability. By integrating with `pytest`, it allows these projects to manage documentation tests within their existing CI/CD pipelines, making manual review of examples unnecessary at scale. This automated validation is crucial for maintaining the quality and usability of documentation in rapidly developing and complex software ecosystems.
Can runnable Markdown be adopted by other projects outside of Hugging Face?
Yes, the principles and mechanisms behind Hugging Face's runnable Markdown, particularly its integration with standard Python testing tools like `pytest` and its focus on separating testing logic from displayed documentation, are highly applicable and beneficial for any software project. While the `doc-builder` itself is specific to Hugging Face, the underlying ideas represent a best practice in developer tools. Other projects can implement similar systems using existing tools or adapt `doc-builder`'s concepts to ensure their documentation examples are continuously tested and reliable. This approach is a general solution to a common problem across the software development landscape, making documentation more robust and trustworthy.
Bądź na bieżąco
Otrzymuj najnowsze wiadomości o AI na swoją skrzynkę.
