Saturday, December 05, 2026

THE HIDDEN FOUNDATIONS: WHAT TRAINING DATA POWERS THE WORLD’S MOST ADVANCED AI MODELS?



INTRODUCTION

Every time you interact with ChatGPT, Claude, Gemini, or any other large language model, you are essentially conversing with a digital artifact trained on vast swaths of human knowledge. These models can write poetry, debug code, explain quantum physics, and engage in surprisingly human-like conversations. But there is a fundamental question that remains shrouded in mystery for most of these systems: What exactly did they learn from? The training data that powers foundation models represents one of the most significant yet least transparent aspects of modern artificial intelligence. While companies eagerly showcase their models’ capabilities through impressive benchmarks and demonstrations, they remain remarkably tight-lipped about the specific datasets that made those capabilities possible. This secrecy has sparked intense debate about transparency, copyright, and the very foundations upon which we are building our AI future.


THE SCALE OF THE CHALLENGE


To understand why training data matters so profoundly, we first need to grasp the sheer scale involved. Modern large language models are not trained on a few textbooks or even a few libraries worth of content. They consume information measured in trillions of tokens, where each token roughly corresponds to a word or word fragment. GPT-4, for instance, was reportedly trained on approximately 13 trillion tokens according to industry analyses. Meta’s Llama 3 used over 15 trillion tokens, representing seven times more data than its predecessor Llama 2. These numbers are almost incomprehensibly large. To put this in perspective, if you read one token per second without stopping, it would take you over 400,000 years to consume 13 trillion tokens. The entire English Wikipedia contains only about 4 billion tokens, meaning these models train on datasets thousands of times larger than Wikipedia. This massive scale creates both technical and ethical challenges. The technical challenge involves not just gathering this much data, but filtering it, cleaning it, deduplicating it, and ensuring it represents diverse perspectives and high-quality content. The ethical challenge revolves around where this data comes from, who owns it, and whether its use in AI training constitutes fair use or copyright infringement. These questions have moved from academic debate to courtrooms, with billions of dollars and the future of AI development hanging in the balance.


OPENAI AND GPT: FROM TRANSPARENCY TO OPACITY


OpenAI’s journey with training data transparency tells a fascinating story about the evolution of the AI industry. When the company released GPT-2 in 2019, it was relatively forthcoming about its training approach. However, by the time GPT-4 arrived in March 2023, OpenAI had adopted a dramatically different stance. The technical report for GPT-4 explicitly stated that the company would not be disclosing details about the model’s architecture, training methods, or dataset composition. This marked a stark departure from earlier practices and drew immediate criticism from researchers and transparency advocates. According to leaked reports and industry analysis, GPT-4 was trained on approximately 13 trillion tokens from a mixture of sources. The primary foundation appears to be CommonCrawl and RefinedWeb, massive web scraping datasets that we will explore in detail later. However, speculation suggests the training corpus also included content from Twitter, Reddit, YouTube transcripts, and substantial collections of textbooks and code repositories. OpenAI has confirmed that its training data includes both publicly available sources and data licensed from third-party providers, though the company refuses to specify which providers or what percentage of the training data comes from licensed versus scraped sources. The company’s president Greg Brockman confirmed that GPT-4 was trained on images as well as text, making it multimodal from the ground up, but again declined to discuss where those images came from. In an interview with The Verge, OpenAI co-founder Ilya Sutskever went so far as to call the company’s earlier transparency a mistake, arguing that making AI development open source was a bad idea due to competitive pressures and the potential power of artificial general intelligence. The training of GPT-4 reportedly cost over 100 million dollars and took months of computation on clusters of high-end GPUs. Sam Altman, OpenAI’s CEO, has acknowledged the enormous expense involved. This investment explains, in part, why the company treats its training methodology as a closely guarded trade secret. OpenAI argues that revealing training data details would give competitors an unfair advantage and potentially expose the company to legal challenges. However, critics counter that this opacity makes it impossible to properly audit the models for bias, verify their capabilities, or ensure they were trained ethically and legally.


ANTHROPIC’S CLAUDE: CONSTITUTIONAL AI WITH CURATED DATA


Anthropic, the company behind Claude, takes a somewhat different approach to both training methodology and transparency. While Anthropic also declines to reveal the complete details of its training datasets, the company has been more forthcoming about its general approach and philosophy. Claude models are trained using a technique called Constitutional AI, which incorporates ethical guidelines directly into the training process. The system includes 75 principles drawn from sources including the UN Universal Declaration of Human Rights. During training, Claude generates responses, critiques them according to these constitutional principles, and then revises them. This self-correction process is baked into the model’s development, theoretically reducing harmful outputs without requiring extensive human feedback on every potential harmful scenario. Regarding data sources, Anthropic states that Claude is trained on three main categories of information. First, publicly available data from the internet, which includes websites, books, and other publicly accessible text. Second, data licensed from third-party providers, though Anthropic does not specify who these providers are. Third, and importantly, Anthropic emphasizes what it does not use. The company’s privacy policy explicitly states that it does not use user conversations for training unless users explicitly opt in or unless content is flagged for safety review. This privacy-first approach contrasts with some competitors and has become a key selling point for enterprise customers concerned about data security. Anthropic updates its models regularly, with different Claude versions having different knowledge cutoff dates. As of late 2024, Claude Sonnet 3.7 was trained on data up until November 2024, making it one of the most current foundation models available. This frequent updating suggests Anthropic is continuously gathering and processing new training data, though again, the specific sources and methods remain undisclosed. In recent legal proceedings, Anthropic faced copyright lawsuits from authors and music publishers. The company’s defense included arguments that training AI models on copyrighted material constitutes fair use, and interestingly, that a practical market for AI training data did not exist. However, as we will see later, the emergence of licensing deals has complicated this argument considerably.


GOOGLE’S GEMINI: MULTIMODAL MASTERY WITH MYSTERIOUS SOURCES


Google’s Gemini represents one of the most ambitious approaches to foundation model development, designed from the ground up to be natively multimodal. Unlike models that add vision or audio capabilities as an afterthought, Gemini was pre-trained simultaneously on text, images, audio, and video data. This unified training approach allows the model to understand relationships between different types of content in ways that modular systems cannot. However, Google has been remarkably vague about the specific datasets used to train Gemini. The company’s documentation repeatedly references training on diverse data from publicly available sources and publicly accessible information, but these phrases are deliberately unspecific. Google’s Terms of Service and Privacy Policies mention that Gemini uses information from publicly accessible sources and Gemini Apps information to improve and develop Google’s products, services, and machine learning technologies, but again, this reveals little about the actual composition of the training data. What we do know is that Google has significant advantages in data collection that other companies lack. The company has been crawling and indexing the web for decades through Google Search. It has access to YouTube, which represents one of the largest repositories of video content and associated metadata in the world. Gmail, Google Drive, Google Photos, and other services generate enormous amounts of user data, though Google states it does not use personal user data from these services for Gemini training without consent. The company developed its own version of the CommonCrawl dataset called C4, which stands for Colossal Clean Crawled Corpus. C4 was constructed specifically for training Google’s T5 language model series in 2019. Research has shown that approximately 45 percent of content in C4 is now explicitly restricted by websites that do not want their content scraped for AI training purposes, highlighting the growing tension between AI companies and content creators. Google’s Gemini training process includes extensive quality filtering and safety evaluation. The company states that it applies quality filters to all datasets using both heuristic rules and model-based classifiers. Safety filtering removes content likely to produce policy-violating outputs, and Google performs deduplication to remove evaluation data from the training corpus. The final data mixtures and weights are determined through experimentation on smaller models before being scaled up to the full Gemini training runs. Despite these general descriptions, Google has not released comprehensive information about dataset composition, the percentage of different data types, or the specific sources beyond the vague references to publicly available content. This opacity has drawn criticism from privacy advocates and researchers who argue that such a powerful system built by a company with Google’s data access deserves greater scrutiny and transparency.


META’S LLAMA: OPEN WEIGHTS, CLOSED DATA DETAILS


Meta’s Llama series represents an interesting case study in the tension between openness and proprietary secrecy. Meta releases the model weights for Llama models under a relatively permissive license, allowing researchers and developers to download, study, and even commercialize these models. This openness has made Llama one of the most widely used foundation model families, with over 300 million downloads across all versions. However, while Meta shares the model itself, the company is far less forthcoming about the training data used to create it. Llama 3, released in April 2024, was pre-trained on over 15 trillion tokens of data from publicly available sources. This represents seven times more data than Llama 2, which used 2 trillion tokens. Meta’s blog post announcing Llama 3 emphasized that this vast training dataset was key to the model’s improved performance. The company states that it developed a series of data-filtering pipelines including heuristic filters, NSFW filters, semantic deduplication approaches, and text classifiers to predict data quality. Interestingly, Meta used Llama 2 itself to help generate training data for the text-quality classifiers that powered Llama 3’s data filtering. This bootstrapping approach, where older models help curate data for newer ones, is becoming increasingly common in the industry. Meta also states that the Llama 3 training dataset includes four times more code than Llama 2 and that over 5 percent of the pre-training dataset consists of high-quality non-English data covering more than 30 languages. However, Meta has not disclosed the specific sources of this data beyond the generic phrase publicly available sources. The fine-tuning data for Llama Chat, the instruction-following version of Llama, includes publicly available instruction datasets as well as over 10 million human-annotated examples. Again, the specific datasets are not named. Meta’s approach to openness has drawn both praise and criticism. Supporters argue that releasing model weights democratizes access to powerful AI capabilities and enables independent research. Critics, particularly those from the open source community, contend that Llama is not truly open source because it does not meet the Open Source Initiative’s definition. The OSI requires that open source AI systems disclose details about training data, which Meta does not do. This debate came to a head when the Open Source Initiative published The Open Source AI Definition in October 2024, explicitly requiring disclosure of training data details for any system claiming to be open source. Meta’s license also includes restrictions on commercial use in certain circumstances and prohibits use in specific fields, further muddying claims of true openness. Researchers have noted that Meta’s selective openness, where the company shares the model but not the data or the detailed training methodology, represents a strategic middle ground. It allows Meta to build goodwill and encourage ecosystem development while protecting what it considers its most valuable competitive advantages. The data cutoff dates for Llama models provide some clues about their training timeline. Llama 3’s 8B model has a cutoff of March 2023, while the 70B model extends to December 2023, suggesting these different sized models were trained at different times and potentially on slightly different datasets.


MISTRAL AI: THE WALL OF SILENCE


French AI startup Mistral AI has taken perhaps the most restrictive approach to training data transparency of any major foundation model provider. The company’s official stance is simple and unequivocal: they do not disclose the datasets used to train their models. Period. Mistral’s help center states clearly that some assets remain proprietary, including the training datasets, the training logic, and the resources required to produce both open-source and optimized models. The company argues that keeping these elements private helps protect intellectual property and maintain model quality. When users have requested information about training data composition, Mistral representatives have stated that they are unable to share details about training and datasets due to the highly competitive nature of the field. The only hint provided is that data was extracted from the open Web, which tells us almost nothing about specific sources, filtering methods, or data composition. This complete opacity is particularly notable because Mistral releases some of its models with permissive licenses that allow commercial use and modification. However, unlike Meta’s partial openness with Llama, Mistral provides no transparency whatsoever about how these models were created. Researchers who have analyzed Mistral’s models have attempted to infer properties of the training data through the models’ behaviors and capabilities. For instance, evaluations have shown that Mistral models perform significantly better on English text than on Spanish text, suggesting that the training data was heavily weighted toward English-language sources. However, Mistral has not confirmed these observations or provided aggregate statistics about language composition in their training data. The company’s approach reflects a broader industry trend toward treating training data as the crown jewel of AI development, perhaps even more valuable than the model architectures themselves. After all, architectural innovations can be reverse-engineered or independently discovered, but a well-curated, massive training dataset represents years of effort and substantial financial investment. Mistral’s stance may also reflect legal caution. By not disclosing training data sources, the company avoids explicitly acknowledging any potentially problematic inclusions, which could provide ammunition for copyright lawsuits. This strategy of opacity may become increasingly common as the legal landscape around AI training data becomes more treacherous.


COMMON CRAWL: THE UBIQUITOUS FOUNDATION


To understand the training data landscape, we must examine the single most important source that nearly every foundation model uses: Common Crawl. This nonprofit organization has been crawling the web since 2008, creating massive archives of web page data that it makes freely available to anyone. Common Crawl releases new datasets every one to two months, with each crawl typically containing several billion web pages. The accumulated archive contains petabytes of data from billions of URLs spanning trillions of links. The organization operates with a remarkably small team but has become essential to the AI industry’s infrastructure. Common Crawl’s importance cannot be overstated. GPT-3 was trained on a filtered version of Common Crawl. GPT-4 incorporates it. Llama models use it extensively. Google’s C4 dataset is derived from it. Essentially, if you have used a modern large language model, you have indirectly interacted with Common Crawl data. The data is provided in three formats, all of which are useful for different purposes. WARC files contain the complete HTTP responses including headers and HTML code. WAT files provide structured metadata in JSON format, including links and response codes. WET files contain plain text extracted from the HTML, which is the format most commonly used for training language models. Common Crawl uses a crawling strategy based on harmonic centrality scoring. Essentially, URLs that are frequently linked to by other websites are considered higher quality and are more likely to be crawled. This creates a bias toward well-established, popular websites and against newer or more obscure content. The crawling process itself is not comprehensive, despite the scale. Common Crawl cannot access content behind paywalls, login walls, or other access restrictions. Or at least, it is not supposed to. A November 2025 investigation by The Atlantic revealed a troubling discovery. Common Crawl had been misrepresenting its practices, claiming it respected paywalls and robots.txt exclusion requests when in fact it did not. The investigation found that Common Crawl continued to include content from websites that had explicitly requested removal, and that the public search function on Common Crawl’s website showed misleading results that hid these violations. This revelation sent shockwaves through the AI industry. Major AI companies, including OpenAI and Anthropic, are significant financial supporters of Common Crawl, each having donated $250,000 in 2023. The fact that this supposedly neutral nonprofit was not respecting content creators’ wishes while taking money from the AI companies that benefit from its data raises serious ethical questions. Common Crawl’s data also has quality problems. The archive contains massive amounts of spam, duplicate content, machine-generated text, and low-quality material. This is why every AI company that uses Common Crawl applies extensive filtering and quality scoring systems. However, these filtering processes are themselves sources of potential bias. If a company uses an AI model to judge content quality, and that model was trained primarily on English text or certain types of content, it may systematically filter out valuable content from other languages or cultural contexts. Another challenge with Common Crawl is freshness. While new crawls are released regularly, the data in any given crawl is already somewhat dated by the time it is processed and incorporated into training datasets. This is one reason why foundation models typically have knowledge cutoff dates several months in the past. The archive also creates a historical bias, as content that has been online longer and accumulated more links is more likely to be included in multiple crawls, giving it disproportionate representation in the training data. Despite these problems, Common Crawl remains essential because it represents the only practical way to access web-scale text data for free. Creating a comparable dataset would require massive infrastructure, legal expertise to navigate scraping regulations, and substantial ongoing maintenance. For all but the largest AI companies, Common Crawl is not just convenient but necessary. The reliance on Common Crawl also creates systemic risks. If Common Crawl were to shut down, change its policies, or face legal challenges that restricted its operations, it could significantly impact the ability to train new foundation models. The entire AI industry has effectively built itself on the foundation of a single small nonprofit organization’s web crawling efforts.


VISION-LANGUAGE MODELS: THE MULTIMODAL DATA CHALLENGE


While text-based language models dominate discussions about AI, vision-language models that can understand both images and text represent an increasingly important category with their own unique training data requirements. These multimodal models face challenges that pure language models do not, primarily the difficulty of acquiring high-quality, aligned image-text pairs at the scale needed for effective training. The story of modern vision-language models begins with CLIP, released by OpenAI in 2021. CLIP stands for Contrastive Language-Image Pretraining, and it introduced a powerful new approach to linking visual and textual understanding. CLIP was trained on 400 million image-caption pairs scraped from the internet. The model learned to determine how well a given text description matched an image by minimizing the distance between the embeddings of matching pairs and maximizing it for non-matching pairs. This contrastive learning approach created a shared embedding space where similar concepts in text and images are close together, regardless of modality. CLIP’s training data was collected from publicly available sources on the internet, but OpenAI has not disclosed the specific websites or methods used for collection. Given the scale of 400 million pairs, this almost certainly involved automated scraping and pairing of images with associated text such as alt tags, captions, or surrounding text from web pages. Following CLIP’s success, researchers recognized the need for even larger multimodal datasets. This led to the creation of LAION-5B, which stands for Large-scale Artificial Intelligence Open Network, containing over 5 billion image-text pairs. LAION is notable for being an open dataset, meaning researchers can access and study it, unlike CLIP’s training data which remains proprietary. However, LAION-5B was itself created using CLIP. The researchers behind LAION used CLIP to filter through Common Crawl data and identify image-text pairs with high alignment scores. This recursive relationship, where one model’s outputs become another model’s training data, is increasingly common in AI development but raises questions about potential biases and limitations being perpetuated across generations of models. The LAION dataset includes descriptions in multiple languages, supporting multilingual vision-language model training. However, like many web-scraped datasets, LAION has faced criticism for including copyrighted images, private information, and harmful content. Researchers have found everything from medical images to photographs of identifiable individuals to copyrighted artwork in the dataset. This has made LAION a target of copyright lawsuits and raised serious privacy concerns. Other important datasets for vision-language training include ImageNet, which contains millions of annotated images organized by category, and COCO, which stands for Common Objects in Context and provides detailed annotations including object locations, segmentation masks, and multiple captions per image. Unlike the massive but noisy web-scraped datasets, COCO was carefully curated by human annotators, making it higher quality but much smaller at around 330,000 images. Specialized datasets exist for particular capabilities. Visual Question Answering (VQA) datasets pair images with questions and answers to train models on reasoning about visual content. Video-text datasets like WebVid provide millions of video-text pairs for training models that can understand temporal dynamics. OCR-specific datasets help models learn to read text within images. The training of vision-language models typically involves multiple stages. Initial pre-training uses large-scale noisy datasets to learn basic image-text correspondences. Subsequent fine-tuning uses smaller, higher-quality datasets to improve performance on specific tasks. Some recent models use knowledge distillation, where a smaller model is trained to mimic a larger, more capable model, allowing the training of efficient models without requiring the original massive datasets. The multimodal data challenge is not just about quantity but about alignment quality. An image paired with an irrelevant or misleading caption can actually harm model performance by teaching incorrect associations. This is why models like CLIP have become valuable not just as end products but as tools for filtering and scoring multimodal datasets. Recent developments in vision-language models show a trend toward using synthetic data generation, where AI models create additional training examples by generating images from text descriptions or vice versa. This approach can help address data scarcity for specific capabilities or concepts, though it raises its own concerns about model collapse, where training on AI-generated content leads to degraded performance over generations.


THE COPYRIGHT BATTLEGROUND: LAWSUITS, LICENSING, AND FAIR USE


The question of whether training AI models on copyrighted content constitutes copyright infringement has moved from theoretical debate to active litigation with billions of dollars at stake. The past two years have seen an explosion of lawsuits targeting AI companies, and the outcomes of these cases will likely reshape how foundation models are trained in the future. The New York Times fired one of the most prominent shots in December 2023 when it sued OpenAI and Microsoft, claiming that GPT models were trained on millions of Times articles without permission. The lawsuit argues that this use directly competes with the Times’s own business and damages the newspaper’s commercial opportunities. The Times has demonstrated that ChatGPT can reproduce substantial portions of Times articles when prompted appropriately, suggesting that the original content is in some way embedded in the model. Authors have filed multiple class-action lawsuits against AI companies. Sarah Silverman, Christopher Golden, and other writers sued both Meta and OpenAI, arguing that training on their copyrighted books constitutes infringement and that AI-generated text based on their writing creates derivative works. The lawsuit against Anthropic by authors resulted in a preliminary settlement of 1.5 billion dollars in September 2024, though this settlement faced challenges and has not yet received final approval. Visual artists have also taken action. The lawsuit Andersen v. Stability AI involves artists who claim that Stable Diffusion, Midjourney, and other image generation models were trained on billions of copyrighted images scraped from the internet without permission or compensation. While some claims have been dismissed on procedural grounds, key copyright infringement claims have survived initial challenges and are proceeding through the courts. The music industry has joined the fray as well. In June 2024, major record labels including Sony Music, Warner Music Group, and Universal Music Group sued AI music generation companies Suno and Udio, claiming they trained their models on copyrighted music at an almost unimaginable scale. German collecting society GEMA has filed similar lawsuits in Germany, with courts beginning to rule that AI training can constitute copyright infringement under certain circumstances. AI companies primarily defend themselves using the fair use doctrine, which allows limited use of copyrighted material without permission for purposes such as criticism, commentary, news reporting, teaching, scholarship, or research. The fair use determination involves four factors: the purpose and character of the use, the nature of the copyrighted work, the amount of the work used, and the effect on the potential market for the work. In February 2024, a federal court in Delaware delivered a significant ruling in Thomson Reuters v. ROSS Intelligence that is being closely watched by the AI industry. The court found that training an AI system on copyrighted legal headnotes to create a competing product was not fair use. The ruling emphasized that the AI company’s use was commercial and not transformative, and that it created a market substitute for the original copyrighted work. However, the judge carefully noted that the case involved a non-generative AI system and that the analysis might differ for generative AI models. In contrast, Judge William Alsup ruled in Bartz v. Anthropic that training on lawfully purchased books could constitute fair use, at least for certain purposes. However, he distinguished between legally purchased books and pirated copies, suggesting that the source of training data matters for fair use analysis. These early rulings suggest that fair use determinations will be highly fact-specific, depending on whether the data was legally obtained, whether the AI system competes directly with the original creators, and whether the use is transformative or merely reproductive. The legal landscape is further complicated by the emergence of a licensing market. In 2024, OpenAI began signing deals with major media companies including Axel Springer, France’s Le Monde, and Spain’s Prisa Media to license their content for training data. Microsoft struck a deal with HarperCollins to use nonfiction titles for training, reportedly paying $5,000 per title for three-year licenses. These licensing agreements fundamentally undermine AI companies’ arguments that a market for training data does not exist or is impracticable. If companies are willing to pay for licenses, it becomes much harder to argue that using copyrighted content without permission is necessary or justified under fair use. The existence of licensing deals also establishes market values, which can be used to calculate damages in infringement cases. Some content creators and platforms have taken technical measures rather than legal ones. Major newspapers and websites have updated their robots.txt files to block known AI scraping bots. The New York Times now explicitly prohibits AI companies from using its content for training purposes in its terms of service. However, enforcement remains challenging, and as the Common Crawl investigation revealed, some actors do not respect these exclusion requests. The copyright battle is far from over, with major cases still working their way through the courts. The outcomes will likely determine whether AI companies need to fundamentally change how they acquire training data, potentially requiring expensive licensing agreements, limiting themselves to public domain content, or developing techniques that can learn from less data. For now, the strategy of many AI companies appears to be to move forward with questionable data practices while fighting legal battles, hoping that either courts will side with them on fair use grounds or that they will become too established and important to be significantly constrained by copyright enforcement.


THE TRANSPARENCY PROBLEM: WHY SECRECY REIGNS


Given the importance of training data to understanding how AI models work, their capabilities, their limitations, and their biases, the lack of transparency from major AI companies is striking. While a few years ago it was common for AI research papers to include detailed information about training datasets, today’s frontier models come with minimal disclosure. OpenAI’s shift from relative openness to explicit secrecy exemplifies this trend, but it is hardly alone. Companies offer several justifications for keeping training data details confidential. The competitive argument holds that revealing training data sources and curation methods would give rivals a roadmap to replicate their success. Given that assembling, cleaning, and filtering training datasets represents years of work and tens of millions of dollars in investment, companies view this information as a core competitive advantage. If OpenAI revealed exactly which data sources it used and how it filtered them, competitors could potentially create comparable datasets more quickly and cheaply. The legal liability argument suggests that detailed disclosure of training data could expose companies to additional copyright lawsuits. If a company admits to training on specific copyrighted works, it provides plaintiff attorneys with clear targets and evidence. Vague references to publicly available sources offer some legal protection through ambiguity. This was evident when OpenAI’s Mira Murati awkwardly avoided answering questions about whether Sora was trained on YouTube content, and when other executives have similarly dodged specific questions about data sources. Some companies argue that transparency about training data could enable adversaries to intentionally poison or manipulate future training runs. If attackers know which websites are heavily weighted in training datasets, they could potentially inject misleading or harmful content into those sources. However, this argument is less compelling given that the general sources like Common Crawl are already known, and the specific filtering methods are where the real value lies. There are also practical challenges to disclosure. Training datasets are often assembled from dozens or hundreds of different sources, each potentially requiring separate licensing agreements with confidentiality clauses. Even if a company wanted to disclose full details, contractual obligations might prevent it. Additionally, some data sources may involve personally identifiable information or content that was legally scraped but ethically questionable to highlight. The lack of transparency has serious consequences for AI safety, research, and public trust. Without knowing what data models trained on, researchers cannot fully understand model behaviors or predict failure modes. Bias assessments are incomplete if we do not know whether training data over-represents or under-represents certain populations or perspectives. Claims about model capabilities cannot be independently verified if we cannot examine whether benchmark datasets leaked into training data. Regulators in several jurisdictions are beginning to push back against this opacity. The European Union’s AI Act includes provisions requiring AI developers to maintain detailed records of training data. The proposed Generative AI Copyright Disclosure Act in the United States would require companies to disclose datasets used for training. These regulatory efforts face pushback from industry groups arguing that such requirements would stifle innovation and advantage foreign competitors not subject to the same rules. Some researchers argue that complete training data transparency may not be necessary or even desirable for all purposes. What may be more important is transparent documentation of data collection methodologies, filtering criteria, known limitations and biases, and clear policies about data sources rather than exhaustive lists of every included document. This middle ground could provide accountability without requiring companies to reveal every competitive detail. The transparency debate also intersects with broader questions about AI governance and corporate responsibility. If AI systems are going to make decisions that affect people’s lives, employment, and access to information, many argue that the public has a right to understand how these systems were built. The fact that major AI systems are being deployed into critical applications while their fundamental training data remains a black box concerns many ethicists and policymakers. Going forward, we may see a bifurcation in the AI industry. Academic and nonprofit efforts may continue to emphasize transparency and reproducibility, building models on fully disclosed datasets even if those models are less capable than commercial alternatives. Meanwhile, commercial providers may maintain secrecy, competing primarily on model performance while treating training data as proprietary information. This split could have significant implications for the democratization of AI and the concentration of power in a few large technology companies.


THE FUTURE LANDSCAPE: SYNTHETIC DATA, LICENSING, AND REGULATION


As we look toward the future of foundation model training, several trends are emerging that will reshape how these models are built and what data powers them. One of the most significant developments is the increasing use of synthetic data generated by AI models themselves to train new models. This approach offers several advantages. Synthetic data avoids copyright issues since the generated content does not directly copy existing works. It can be created on demand for specific capabilities or to fill gaps in existing datasets. It can be carefully controlled to avoid harmful content or bias. Models like Anthropic’s Claude and OpenAI’s GPT-4 are already being used to generate training data for smaller, more specialized models. However, synthetic data comes with risks. Research has shown that training models exclusively on AI-generated content can lead to model collapse, where each generation becomes progressively worse as errors and biases compound. The wisdom and knowledge captured in human-created content may be irreplaceable, at least for now. Most experts believe that synthetic data will augment rather than replace human-generated training data for the foreseeable future. The licensing market for training data is rapidly maturing. Following OpenAI’s deals with news publishers and Microsoft’s agreement with HarperCollins, we are seeing the emergence of intermediary companies that aggregate content from multiple creators and license it to AI companies. Publishers, news organizations, and content platforms are beginning to view AI training as a new revenue stream and are actively negotiating terms. This shift from the take first, ask permission later approach that characterized early AI development to a licensing model could have profound effects. It may increase costs for AI companies substantially, potentially creating barriers to entry for new competitors. It could concentrate power in the hands of large content owners who can negotiate favorable deals. It may also lead to training data that over-represents content from wealthier, better-organized creators while under-representing content from marginalized communities or individuals who lack bargaining power. Regulatory frameworks are being developed that will shape training data practices. The European Union’s AI Act requires transparency about training data sources and composition. California has proposed legislation that would mandate disclosure of training data for AI systems used in the state. International bodies are developing guidelines and standards for responsible AI development that include data governance requirements. These regulations face resistance from AI companies who argue they are too burdensome, but public pressure for accountability appears to be growing. Courts are also developing a body of case law that will clarify what uses of copyrighted content for AI training are permissible. As these legal precedents accumulate, companies will gain clearer guidance about what data they can use and under what circumstances. This clarity could actually accelerate development by reducing legal uncertainty, even if it narrows the range of permissible data sources. Technical innovations may reduce the amount of data needed for training. Techniques like few-shot learning, meta-learning, and more efficient training algorithms are making it possible to train capable models on smaller datasets. Transfer learning allows knowledge from one domain to be efficiently adapted to another, reducing the need to train from scratch on massive datasets for every new capability. Neurosymbolic AI approaches that combine neural networks with symbolic reasoning may require less training data by incorporating structural knowledge more efficiently. The rise of multimodal models is creating new data requirements and new collection challenges. As models incorporate video, audio, 3D environments, and other modalities beyond text and static images, the datasets needed become increasingly complex. Companies are beginning to explore partnerships with content platforms, simulation environments, and specialized data providers to address these needs. We may also see the emergence of data cooperatives or commons where individuals and organizations pool their data specifically for AI training in exchange for access to trained models or revenue sharing. These approaches could democratize access to training data and model capabilities while giving data creators more control and compensation. The relationship between AI models and the internet itself is evolving. As more content online becomes AI-generated, the distinction between human-created and machine-created content blurs. This creates challenges for training new models, as we will need ways to identify and potentially filter AI-generated content from training datasets to avoid model collapse. Some propose watermarking schemes or provenance tracking systems, but these remain largely theoretical. Another interesting development is the potential for specialized, domain-specific foundation models trained on curated datasets rather than web-scale scraped data. A medical AI trained exclusively on peer-reviewed medical literature, clinical notes, and validated medical knowledge might be more reliable than a general model trained on the entire internet. Similarly, legal, scientific, and engineering domains may benefit from models trained on carefully selected, high-quality domain data rather than generic web text. This specialization could lead to a ecosystem of foundation models, each trained on different data for different purposes, rather than a few general models that attempt to do everything.


CONCLUSION: THE PARADOX OF HIDDEN FOUNDATIONS


We stand at a remarkable moment in technological history. AI systems trained on vast collections of human knowledge have achieved capabilities that seemed like science fiction just a few years ago. These models can engage in complex reasoning, creative writing, code generation, and multimodal understanding. They are being integrated into products and services used by hundreds of millions of people. They are changing how we work, learn, create, and communicate. Yet the foundations upon which these remarkable systems are built remain largely hidden from public view. We know that they train on trillions of tokens of text, millions or billions of images, and vast quantities of code and specialized content. We know that sources like Common Crawl, scraped web data, digitized books, and licensed content all play roles. But the specific details of what data, in what proportions, filtered and processed in what ways, remain closely guarded secrets. This opacity creates a fundamental paradox. We are asked to trust AI systems that make increasingly important decisions without being able to fully audit or understand how they were built. We are told that these systems represent transformative technology that will reshape society, yet we cannot independently verify claims about their capabilities or limitations. We see biases and failures in deployed systems, but we cannot trace those problems back to their roots in training data. The secrecy is maintained through a combination of competitive pressure, legal caution, and practical challenges. Companies argue, with some justification, that revealing training data details would undermine their competitive position and expose them to liability. But this individual rationality for each company creates a collective problem for the AI ecosystem and society at large. Without transparency, we cannot have meaningful accountability. The emerging copyright battles may force greater disclosure, as courts demand evidence about training data sources to adjudicate infringement claims. Regulatory efforts may mandate transparency as a condition for deploying AI systems in regulated industries or for public-facing applications. Market pressures may drive differentiation, with some companies positioning themselves as the transparent, ethical alternative to secretive competitors. As we look to the future, the question of training data transparency will likely remain contentious. The tension between openness and proprietary advantage, between innovation and accountability, between moving fast and getting permission, these tensions are fundamental to how we develop AI. The resolution of these tensions will shape not just individual companies’ success but the trajectory of AI technology and its impact on society. What is clear is that training data is not just a technical detail or a footnote in the development of foundation models. It is the foundation itself, the bedrock upon which everything else is built. The quality, diversity, and provenance of training data determines what these models can do, how they behave, what biases they carry, and whose interests they serve. As AI systems become more powerful and more prevalent, the question of what data powers them becomes increasingly central to questions of fairness, safety, and accountability. The hidden foundations of today’s AI may need to become more visible if we are to build a future where these powerful technologies serve broad human interests rather than narrow commercial ones. Whether that visibility comes through voluntary transparency, regulatory mandate, legal discovery, or market pressure remains to be seen. But the days of accepting mysterious, opaque training datasets as simply how AI development works may be drawing to a close. The conversation about training data is really a conversation about what kind of AI we want and who gets to decide. It is about whether we build these technologies in ways that are auditable and accountable, or whether we accept black boxes. It is about who benefits from AI and who pays the costs. It is about the relationship between human creativity and machine intelligence, between public knowledge and private property, between innovation and consent. These are not just technical questions for researchers and engineers to resolve. They are social and political questions that will require input from diverse stakeholders including content creators, researchers, ethicists, policymakers, and the public. The more we understand about training data and demand transparency about it, the better equipped we will be to ensure that AI development serves broad interests rather than narrow ones. The foundation models of today were built on hidden foundations. The foundation models of tomorrow need not be.

Friday, December 04, 2026

BUILDING AN INTELLIGENT CONTENT CREATION AGENCY WITH CREWAI

 


Introduction

Imagine having a team of specialized AI agents working together to create professional blog posts, complete with research, writing, editing, and SEO optimization. This is not science fiction but the reality of Agentic AI systems. In this tutorial, we will build a sophisticated content creation agency powered by CrewAI, where multiple AI agents collaborate like a real editorial team to produce high-quality articles.

Traditional AI applications typically involve a single model responding to prompts. Agentic AI systems, however, orchestrate multiple specialized agents that work together, delegate tasks, share information, and collectively solve complex problems. Think of it as the difference between hiring a single freelancer versus assembling a complete editorial team with researchers, writers, editors, and SEO specialists.

Our running example will be a Content Creation Agency that takes a topic and produces a complete, publication-ready blog post. The system will feature four specialized agents: a Research Agent that gathers information, a Writer Agent that crafts the initial draft, an Editor Agent that refines the content, and an SEO Specialist Agent that optimizes for search engines. This mirrors how professional content teams actually work, making it both practical and educational.

Understanding Agentic AI Systems

Before diving into code, we need to understand what makes Agentic AI different from traditional AI applications. An agent is an autonomous entity that can perceive its environment, make decisions, and take actions to achieve specific goals. In the context of AI, agents are language models equipped with tools, memory, and the ability to reason about tasks.

The key characteristics of agentic systems include autonomy, where agents can operate independently without constant human intervention. They possess reactivity, allowing them to respond to changes in their environment. Proactivity enables them to take initiative to achieve goals rather than simply responding to requests. Finally, social ability lets them communicate and collaborate with other agents, sharing information and coordinating their efforts.

CrewAI is a framework specifically designed for orchestrating multiple AI agents. It provides abstractions for defining agents with specific roles, creating tasks for those agents, and managing the flow of information between them. Unlike single-agent systems, CrewAI enables agents to work together in crews, sharing context and building upon each other's work. This collaborative approach mirrors how human teams function, with each member contributing their specialized expertise to a common goal.

The framework handles the complexity of inter-agent communication, task sequencing, and context management. When you define a crew, you specify which agents are involved and what tasks they need to accomplish. CrewAI then orchestrates the execution, ensuring that each agent receives the information it needs from previous agents and that the overall workflow proceeds smoothly.

Setting Up Your Development Environment

The first step in building our content creation agency is setting up a proper development environment that supports various hardware configurations. Modern AI development requires flexibility in terms of GPU support, as developers work with different hardware from NVIDIA CUDA to AMD ROCm, Intel GPUs, and Apple's Metal Performance Shaders.

We will start by creating a new Python project and installing the necessary dependencies. The beauty of our approach is that it will work whether you are running on a high-end NVIDIA GPU, an AMD graphics card, an Intel Arc GPU, or Apple Silicon with MPS acceleration. We will also support running models remotely via APIs for those without local GPU resources.

Create a new directory for your project and set up a virtual environment. Open your terminal and execute the following commands:

mkdir content-creation-agency
cd content-creation-agency
python -m venv venv
source venv/bin/activate

On Windows systems, you would use a slightly different activation command. Instead of the source command, you would run venv\Scripts\activate. This creates an isolated Python environment where we can install our dependencies without affecting your system Python installation.

Now we need to install the core dependencies. CrewAI will be our orchestration framework, and we will use LangChain as the underlying framework for agent interactions. For local LLM support, we will use llama-cpp-python, which provides excellent cross-platform GPU acceleration:

pip install crewai crewai-tools langchain langchain-community
pip install llama-cpp-python
pip install openai anthropic
pip install python-dotenv pydantic requests beautifulsoup4

The llama-cpp-python library automatically detects and uses available GPU acceleration. For NVIDIA GPUs, it uses CUDA. For AMD graphics cards, it uses ROCm. For Intel GPUs, it uses oneAPI. For Apple Silicon, it uses Metal. This makes our system truly hardware-agnostic, adapting to whatever hardware you have available.

The other dependencies serve specific purposes. The openai and anthropic packages allow us to connect to remote API services when local execution is not desired or feasible. The python-dotenv package helps us manage environment variables and API keys securely. Pydantic provides data validation and settings management. The requests and beautifulsoup4 libraries will be used by our agents to gather information from the web.

Creating the Configuration System

Let us create a configuration system that allows users to choose between local and remote models. We will use environment variables and a configuration class to manage this flexibility. This approach separates configuration from code, making our system adaptable to different deployment scenarios without code changes.

Start by creating a file named config.py in your project directory. This file will contain all the configuration logic:

# config.py
import os
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
from dotenv import load_dotenv

load_dotenv()

class ModelProvider(str, Enum):
    """Enumeration of supported model providers"""
    LOCAL = "local"
    OPENAI = "openai"
    ANTHROPIC = "anthropic"
    OLLAMA = "ollama"

class GPUBackend(str, Enum):
    """Enumeration of supported GPU backends"""
    CUDA = "cuda"
    ROCM = "rocm"
    METAL = "metal"
    ONEAPI = "oneapi"
    CPU = "cpu"

These enumerations define the valid options for model providers and GPU backends. Using enumerations rather than plain strings provides type safety and prevents configuration errors. If someone tries to specify an invalid provider, Python will raise an error immediately rather than failing later during execution.

The ModelProvider enumeration includes four options. LOCAL means we will run a model directly on the machine using llama-cpp-python. OPENAI connects to OpenAI's API services. ANTHROPIC uses Claude models from Anthropic. OLLAMA connects to a local Ollama server, which is useful for developers who want local execution but prefer Ollama's model management.

The GPUBackend enumeration covers all major GPU acceleration frameworks. CUDA is for NVIDIA graphics cards. ROCM supports AMD GPUs. METAL is for Apple Silicon. ONEAPI works with Intel GPUs. CPU is the fallback when no GPU acceleration is available.

Now let us create the main configuration class:

class ModelConfig(BaseModel):
    """Configuration for language model selection and parameters"""
    provider: ModelProvider = Field(
        default=ModelProvider.LOCAL,
        description="The model provider to use"
    )
    model_name: str = Field(
        default="mistral-7b-instruct",
        description="Name of the model to use"
    )
    temperature: float = Field(
        default=0.7,
        ge=0.0,
        le=2.0,
        description="Sampling temperature for generation"
    )
    max_tokens: int = Field(
        default=2048,
        gt=0,
        description="Maximum tokens to generate"
    )
    gpu_backend: Optional[GPUBackend] = Field(
        default=None,
        description="GPU backend for local models"
    )
    api_key: Optional[str] = Field(
        default=None,
        description="API key for remote providers"
    )
    model_path: Optional[str] = Field(
        default=None,
        description="Path to local model file"
    )

This configuration class uses Pydantic for validation and type safety. Each field has a type annotation, a default value, and constraints. The temperature field, for example, must be between zero and two. The max_tokens field must be greater than zero. These constraints ensure that configuration values are always valid.

The Field function provides additional metadata for each configuration parameter. The description helps developers understand what each parameter does. The ge parameter means greater than or equal, while gt means greater than. These validation rules prevent common configuration mistakes.

Notice that some fields are Optional, meaning they can be None. The gpu_backend field is optional because we can auto-detect it. The api_key is optional because it might come from environment variables. The model_path is only needed for local models.

Now we add initialization logic that handles defaults and auto-detection:

    def __init__(self, **data):
        super().__init__(**data)
        if self.provider == ModelProvider.LOCAL and self.gpu_backend is None:
            self.gpu_backend = self._detect_gpu_backend()
        
        if self.provider == ModelProvider.OPENAI and self.api_key is None:
            self.api_key = os.getenv("OPENAI_API_KEY")
        elif self.provider == ModelProvider.ANTHROPIC and self.api_key is None:
            self.api_key = os.getenv("ANTHROPIC_API_KEY")
    
    @staticmethod
    def _detect_gpu_backend() -> GPUBackend:
        """Automatically detect available GPU backend"""
        try:
            import torch
            if torch.cuda.is_available():
                return GPUBackend.CUDA
            elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
                return GPUBackend.METAL
        except ImportError:
            pass
        
        if os.path.exists('/opt/rocm'):
            return GPUBackend.ROCM
        
        if os.getenv('ONEAPI_ROOT'):
            return GPUBackend.ONEAPI
        
        return GPUBackend.CPU

The initialization method performs smart defaults. If the user chooses a local provider but does not specify a GPU backend, we automatically detect what hardware is available. This makes the system user-friendly because developers do not need to know the technical details of their GPU setup.

The GPU detection logic tries multiple approaches. First, it attempts to import PyTorch and check for CUDA or MPS availability. PyTorch provides reliable GPU detection for these backends. If PyTorch is not installed, we fall back to checking for ROCm and oneAPI installations by looking for their characteristic directories and environment variables.

For API keys, we check environment variables if the user did not provide them directly. This follows security best practices by keeping sensitive credentials out of code. Developers can create a .env file in their project directory with their API keys, and the load_dotenv function will load them automatically.

Building the Model Factory

With our configuration system in place, we need a factory pattern to instantiate the appropriate language model based on the configuration. This factory will handle the complexity of initializing different model types while presenting a uniform interface to the rest of our application.

Create a new file named model_factory.py. This file will contain the logic for creating model instances:

# model_factory.py
from typing import Union
from langchain.llms.base import BaseLLM
from langchain_community.llms import LlamaCpp, Ollama
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from config import ModelConfig, ModelProvider, GPUBackend

class ModelFactory:
    """Factory for creating language model instances based on configuration"""
    
    @staticmethod
    def create_model(config: ModelConfig) -> BaseLLM:
        """Create and configure a language model instance"""
        if config.provider == ModelProvider.LOCAL:
            return ModelFactory._create_local_model(config)
        elif config.provider == ModelProvider.OPENAI:
            return ModelFactory._create_openai_model(config)
        elif config.provider == ModelProvider.ANTHROPIC:
            return ModelFactory._create_anthropic_model(config)
        elif config.provider == ModelProvider.OLLAMA:
            return ModelFactory._create_ollama_model(config)
        else:
            raise ValueError(f"Unsupported model provider: {config.provider}")

The factory pattern is particularly useful here because it encapsulates the logic for creating different types of models. The create_model method is the public interface. It examines the configuration and delegates to the appropriate private method. This separation of concerns makes the code easier to maintain and extend.

Each provider requires different initialization parameters and different LangChain classes. By hiding these details inside the factory, we keep the rest of our application clean. The agents and tasks do not need to know whether they are using a local model or a remote API. They just receive a BaseLLM instance that works the same way regardless of the underlying implementation.

Let us look at how we create local models with GPU acceleration:

    @staticmethod
    def _create_local_model(config: ModelConfig) -> LlamaCpp:
        """Create a local model using llama-cpp-python with GPU acceleration"""
        if config.model_path is None:
            raise ValueError("model_path must be specified for local models")
        
        n_gpu_layers = ModelFactory._get_gpu_layers(config.gpu_backend)
        
        model_params = {
            "model_path": config.model_path,
            "temperature": config.temperature,
            "max_tokens": config.max_tokens,
            "n_gpu_layers": n_gpu_layers,
            "n_ctx": 4096,
            "n_batch": 512,
            "verbose": False,
        }
        
        if config.gpu_backend == GPUBackend.METAL:
            model_params["n_gpu_layers"] = 1
            model_params["f16_kv"] = True
        elif config.gpu_backend == GPUBackend.CUDA:
            model_params["n_gpu_layers"] = -1
        elif config.gpu_backend == GPUBackend.ROCM:
            model_params["n_gpu_layers"] = -1
        
        return LlamaCpp(**model_params)

Creating a local model involves several important parameters. The model_path points to the GGUF format model file on disk. The n_gpu_layers parameter controls how many transformer layers are offloaded to the GPU. Setting this to negative one means all layers go to the GPU for maximum acceleration.

The n_ctx parameter sets the context window size, which determines how much text the model can process at once. We use 4096 tokens, which is a good balance between capability and memory usage. The n_batch parameter controls how many tokens are processed in parallel during prompt evaluation, affecting speed.

Different GPU backends require different configurations. Apple's Metal Performance Shaders handle layer offloading differently than CUDA, so we set n_gpu_layers to 1 for Metal. We also enable f16_kv, which uses 16-bit floating point precision for the key-value cache, reducing memory usage on Apple Silicon.

For NVIDIA CUDA and AMD ROCm, we set n_gpu_layers to negative one, which tells llama-cpp-python to offload all layers to the GPU. This provides maximum performance on these platforms.

Now let us look at creating remote API models:

    @staticmethod
    def _create_openai_model(config: ModelConfig) -> ChatOpenAI:
        """Create an OpenAI model instance"""
        if config.api_key is None:
            raise ValueError("API key must be provided for OpenAI models")
        
        return ChatOpenAI(
            model_name=config.model_name,
            temperature=config.temperature,
            max_tokens=config.max_tokens,
            openai_api_key=config.api_key
        )
    
    @staticmethod
    def _create_anthropic_model(config: ModelConfig) -> ChatAnthropic:
        """Create an Anthropic Claude model instance"""
        if config.api_key is None:
            raise ValueError("API key must be provided for Anthropic models")
        
        return ChatAnthropic(
            model=config.model_name,
            temperature=config.temperature,
            max_tokens=config.max_tokens,
            anthropic_api_key=config.api_key
        )

Creating remote API models is simpler because the complexity is handled by the API provider. We just need to pass the API key and generation parameters. The LangChain wrappers handle all the HTTP communication, error handling, and response parsing.

Notice that we validate the API key is present before attempting to create the model. This fail-fast approach catches configuration errors immediately rather than waiting until the first API call fails.

The helper method for determining GPU layers encapsulates the backend-specific logic:

    @staticmethod
    def _get_gpu_layers(backend: GPUBackend) -> int:
        """Determine optimal number of GPU layers based on backend"""
        if backend == GPUBackend.CPU:
            return 0
        elif backend == GPUBackend.METAL:
            return 1
        else:
            return -1

This method returns zero for CPU-only execution, one for Metal, and negative one for full GPU offloading on other backends. By centralizing this logic, we ensure consistency across the codebase.

Defining Specialized Agents

Now we arrive at the heart of our agentic system: defining the specialized agents that will work together to create content. Each agent in our crew has a specific role, expertise, and set of responsibilities. This specialization allows agents to focus on what they do best, just like members of a real content team.

Create a new file named agents.py. This file will contain our agent definitions:

# agents.py
from crewai import Agent
from langchain.llms.base import BaseLLM

class ContentCreationAgents:
    """Factory class for creating specialized content creation agents"""
    
    def __init__(self, llm: BaseLLM):
        """Initialize the agent factory with a language model"""
        self.llm = llm

We use a factory class pattern here as well. The ContentCreationAgents class holds a reference to the language model and provides methods for creating each type of agent. This keeps agent creation logic organized and makes it easy to create multiple agents with the same underlying model.

Let us start by creating the Research Agent. This agent is responsible for gathering information about the topic, finding relevant facts, statistics, and expert opinions:

    def create_research_agent(self) -> Agent:
        """Create a research agent specialized in gathering information"""
        return Agent(
            role="Senior Research Analyst",
            goal="Conduct comprehensive research on the given topic and gather "
                 "accurate, relevant, and up-to-date information from credible sources",
            backstory="You are an experienced research analyst with a background in "
                     "investigative journalism and academic research. You have spent "
                     "over a decade honing your skills in finding reliable information, "
                     "fact-checking, and synthesizing complex topics into clear insights. "
                     "Your expertise lies in identifying authoritative sources, extracting "
                     "key data points, and understanding the nuances of various subjects. "
                     "You take pride in the accuracy and depth of your research, never "
                     "settling for surface-level information.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm
        )

Each agent definition contains several critical components. The role describes what the agent is, creating an identity that influences how it approaches tasks. Think of the role as the agent's job title. It sets expectations for what kind of work this agent does.

The goal specifies what the agent is trying to achieve. This provides direction for the agent's decision-making process. When the agent is working on a task, it keeps this goal in mind, shaping how it interprets instructions and what outputs it produces.

The backstory is particularly powerful because it gives the agent context and expertise. This is essentially creating a persona that shapes how the agent responds. By giving the Research Agent a background in investigative journalism and academic research, we prime it to approach tasks with thoroughness and attention to credibility.

The verbose parameter controls whether the agent prints its thought process during execution. Setting this to True is helpful during development because you can see what the agent is thinking and doing. In production, you might set it to False for cleaner output.

The allow_delegation parameter determines whether the agent can delegate tasks to other agents. We set this to False because our workflow is sequential. Each agent has a specific job to do in order, so delegation is not necessary.

Now let us create the Writer Agent, which transforms research findings into compelling prose:

    def create_writer_agent(self) -> Agent:
        """Create a writer agent specialized in crafting engaging content"""
        return Agent(
            role="Expert Content Writer",
            goal="Transform research findings into compelling, well-structured "
                 "articles that engage readers and communicate ideas clearly",
            backstory="You are a seasoned content writer with fifteen years of "
                     "experience creating articles for major publications. Your "
                     "writing style is clear, engaging, and accessible. You excel "
                     "at taking complex information and making it understandable "
                     "without dumbing it down. You understand narrative structure, "
                     "pacing, and how to keep readers engaged from the first "
                     "sentence to the last. You have a talent for finding the "
                     "perfect examples and analogies to illustrate complex concepts.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm
        )

The Writer Agent has a different persona than the Research Agent. While the researcher focuses on accuracy and thoroughness, the writer focuses on clarity and engagement. This specialization is key to the agentic approach. Each agent brings different strengths to the table.

Notice how the backstory emphasizes communication skills and the ability to make complex topics accessible. This primes the agent to produce content that is not just accurate but also readable and engaging. The mention of narrative structure and pacing guides the agent toward well-organized writing.

The Editor Agent comes next in our pipeline. After the Writer Agent produces a draft, the Editor Agent reviews it with a critical eye:

    def create_editor_agent(self) -> Agent:
        """Create an editor agent specialized in refining content"""
        return Agent(
            role="Senior Content Editor",
            goal="Review and refine written content to ensure clarity, coherence, "
                 "grammatical correctness, and stylistic excellence",
            backstory="You are a meticulous editor with a sharp eye for detail and "
                     "a deep understanding of language. With twenty years of editorial "
                     "experience at top-tier publications, you have developed an "
                     "instinct for what makes writing great. You catch grammatical "
                     "errors, awkward phrasing, logical inconsistencies, and structural "
                     "problems. You improve clarity without changing the author's voice. "
                     "You ensure every sentence serves a purpose and every paragraph "
                     "flows naturally into the next.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm
        )

The Editor Agent's backstory emphasizes attention to detail and quality. This agent is the quality gatekeeper, ensuring that the content meets professional standards. The mention of preserving the author's voice is important because we want the editor to improve the writing without completely rewriting it.

Finally, we create the SEO Specialist Agent, which optimizes content for search engines:

    def create_seo_agent(self) -> Agent:
        """Create an SEO specialist agent for optimizing content"""
        return Agent(
            role="SEO Optimization Specialist",
            goal="Optimize content for search engines while maintaining readability "
                 "and user engagement, ensuring the article ranks well and attracts "
                 "organic traffic",
            backstory="You are an SEO expert with deep knowledge of search engine "
                     "algorithms, keyword research, and content optimization strategies. "
                     "You have helped hundreds of articles achieve top rankings in "
                     "search results. You understand how to naturally incorporate "
                     "keywords, optimize meta descriptions, create compelling titles, "
                     "and structure content for both search engines and human readers. "
                     "You know that the best SEO serves the user first and the algorithm "
                     "second.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm
        )

The SEO Specialist has expertise in search engine optimization. This agent knows how to make content discoverable without sacrificing quality. The backstory emphasizes the balance between optimization and readability, ensuring that SEO improvements do not make the content feel artificial or keyword-stuffed.

Together, these four agents form a complete content creation pipeline. Each agent has a clear role and expertise, and they work in sequence to produce high-quality, optimized articles.

Creating Tasks for the Agents

Agents need tasks to work on. While agents define who is doing the work, tasks define what work needs to be done. In CrewAI, tasks are explicit instructions given to agents, complete with descriptions, expected outputs, and context.

Create a new file named tasks.py for our task definitions:

# tasks.py
from crewai import Task
from agents import ContentCreationAgents

class ContentCreationTasks:
    """Factory class for creating content creation tasks"""
    
    def __init__(self, agents: ContentCreationAgents):
        """Initialize with agent factory"""
        self.research_agent = agents.create_research_agent()
        self.writer_agent = agents.create_writer_agent()
        self.editor_agent = agents.create_editor_agent()
        self.seo_agent = agents.create_seo_agent()

The ContentCreationTasks class creates all the agents it needs during initialization. This ensures that the same agent instances are used consistently across all tasks. We create one instance of each agent type and reuse them for all the tasks we define.

Now let us create the research task:

    def create_research_task(self, topic: str) -> Task:
        """Create a task for researching the given topic"""
        return Task(
            description=f"""Conduct comprehensive research on the topic: {topic}
            
            Your research should include:
            - Key facts and statistics about the topic
            - Current trends and recent developments
            - Expert opinions and authoritative perspectives
            - Common questions and misconceptions
            - Relevant examples and case studies
            
            Focus on finding credible, up-to-date information from authoritative sources.
            Organize your findings in a clear, structured format that will be useful
            for a writer creating an article on this topic.
            
            Your output should be a detailed research report covering all important
            aspects of the topic.""",
            agent=self.research_agent,
            expected_output="A comprehensive research report with facts, statistics, "
                          "trends, expert opinions, and relevant examples organized "
                          "in a clear structure"
        )

The Task object contains three main components. The description is the detailed instruction given to the agent. This is where we specify exactly what we want the agent to do. Notice how we provide specific bullet points about what the research should include. This level of detail helps guide the agent toward producing useful output.

The agent parameter assigns this task to a specific agent. In this case, we assign it to the research_agent. This creates the connection between the task and the agent who will execute it.

The expected_output parameter describes what the task should produce. This helps the agent understand what format and level of detail is required. It also helps CrewAI validate that the task was completed successfully.

The topic parameter is passed into the task description using an f-string. This makes our tasks reusable. We can create research tasks for any topic by passing different values to this method.

Now let us create the writing task:

    def create_writing_task(self, topic: str, research_task: Task) -> Task:
        """Create a task for writing an article based on research"""
        return Task(
            description=f"""Using the research findings, write a comprehensive,
            engaging article on the topic: {topic}
            
            Your article should:
            - Have a compelling introduction that hooks the reader
            - Present information in a logical, well-structured flow
            - Use clear, accessible language appropriate for a general audience
            - Include relevant examples and explanations
            - Maintain reader engagement throughout
            - Conclude with a strong summary or call to action
            
            Aim for an article length of 1500-2000 words. Write in a professional
            yet conversational tone. Make complex ideas accessible without
            oversimplifying them.
            
            Base your article on the research findings provided, but transform
            the information into engaging narrative prose rather than simply
            listing facts.""",
            agent=self.writer_agent,
            expected_output="A well-written, engaging article of 1500-2000 words "
                          "with clear structure, compelling narrative, and "
                          "accessible explanations",
            context=[research_task]
        )

The writing task introduces a new concept: context. The context parameter is a list of other tasks whose outputs this task depends on. By including research_task in the context, we tell CrewAI that the writing task needs the output from the research task.

This creates a dependency chain. CrewAI will ensure that the research task completes before the writing task begins. When the writer agent starts working, it will have access to the research findings produced by the research agent.

This context mechanism is how information flows between agents in CrewAI. Each agent builds upon the work of previous agents, creating a collaborative workflow.

The editing task follows a similar pattern:

    def create_editing_task(self, writing_task: Task) -> Task:
        """Create a task for editing the written article"""
        return Task(
            description="""Review and refine the written article to ensure
            the highest quality.
            
            Your editing should address:
            - Grammar, spelling, and punctuation errors
            - Sentence structure and clarity
            - Paragraph flow and transitions
            - Logical consistency and coherence
            - Tone and style consistency
            - Removal of redundancy and wordiness
            
            Improve the writing while preserving the author's voice and intent.
            Ensure every sentence is clear and every paragraph serves a purpose.
            The final article should read smoothly from beginning to end.
            
            Provide the edited version of the complete article.""",
            agent=self.editor_agent,
            expected_output="A polished, error-free article with improved clarity, "
                          "flow, and coherence",
            context=[writing_task]
        )

The editing task depends on the writing task through its context parameter. The editor agent receives the draft article from the writer agent and refines it. Notice how the description focuses on improvement rather than rewriting. We want the editor to enhance the existing work, not start from scratch.

Finally, the SEO optimization task:

    def create_seo_task(self, topic: str, editing_task: Task) -> Task:
        """Create a task for SEO optimization"""
        return Task(
            description=f"""Optimize the edited article for search engines while
            maintaining readability and user engagement.
            
            Your optimization should include:
            - A compelling, SEO-friendly title incorporating the main keyword: {topic}
            - A meta description that encourages clicks from search results
            - Natural incorporation of relevant keywords throughout the article
            - Proper heading structure (H1, H2, H3) for both readability and SEO
            - Suggestions for internal and external linking opportunities
            
            Ensure that all SEO improvements feel natural and do not compromise
            the quality or readability of the content. The article should serve
            human readers first while also being discoverable by search engines.
            
            Provide the final, SEO-optimized version of the article along with
            the title and meta description.""",
            agent=self.seo_agent,
            expected_output="A complete, SEO-optimized article with title, meta "
                          "description, proper heading structure, and natural "
                          "keyword integration",
            context=[editing_task]
        )

The SEO task is the final step in our pipeline. It depends on the editing task, ensuring that SEO optimization happens after the content has been refined. The SEO agent receives a polished article and adds the final touches that make it discoverable in search engines.

Notice how we pass the topic parameter to this task as well. The SEO agent needs to know the main keyword to optimize for, so we provide it explicitly.

Assembling the Crew

Now that we have defined our agents and tasks, we need to assemble them into a crew. The crew is the orchestration layer that manages the execution of tasks and the flow of information between agents.

Create a new file named crew.py:

# crew.py
from crewai import Crew, Process
from langchain.llms.base import BaseLLM
from agents import ContentCreationAgents
from tasks import ContentCreationTasks

class ContentCreationCrew:
    """Orchestrates the content creation process using multiple specialized agents"""
    
    def __init__(self, llm: BaseLLM):
        """Initialize the crew with a language model"""
        self.llm = llm
        self.agents = ContentCreationAgents(llm)
        self.task_factory = ContentCreationTasks(self.agents)

The ContentCreationCrew class brings everything together. It holds references to the language model, the agent factory, and the task factory. This organization keeps our code clean and modular.

Now let us create the method that runs the content creation process:

    def create_article(self, topic: str) -> str:
        """
        Create a complete article on the given topic using the agent crew.
        
        Args:
            topic: The topic to write about
            
        Returns:
            The final, SEO-optimized article
        """
        research_task = self.task_factory.create_research_task(topic)
        writing_task = self.task_factory.create_writing_task(topic, research_task)
        editing_task = self.task_factory.create_editing_task(writing_task)
        seo_task = self.task_factory.create_seo_task(topic, editing_task)
        
        crew = Crew(
            agents=[
                self.agents.create_research_agent(),
                self.agents.create_writer_agent(),
                self.agents.create_editor_agent(),
                self.agents.create_seo_agent()
            ],
            tasks=[research_task, writing_task, editing_task, seo_task],
            process=Process.sequential,
            verbose=True
        )
        
        result = crew.kickoff()
        return result

The create_article method orchestrates the entire content creation process. It starts by creating all four tasks, passing the topic and establishing the dependency chain through context parameters.

Then it creates a Crew object. The agents parameter lists all the agents involved in the crew. The tasks parameter lists all the tasks to be executed. The order of tasks in this list matters when using sequential processing.

The process parameter specifies how tasks should be executed. Process.sequential means tasks run one after another in order. CrewAI also supports hierarchical processes where agents can delegate to each other, but sequential is appropriate for our linear workflow.

The verbose parameter controls output verbosity. Setting it to True shows detailed information about what each agent is doing, which is helpful for understanding and debugging the system.

Finally, we call crew.kickoff() to start the execution. This method runs all the tasks in order, managing the flow of information between agents. It returns the output of the final task, which in our case is the SEO-optimized article.

Creating Tools for Web Research

Our agents would be more powerful if they could actually search the web for information rather than relying solely on their training data. CrewAI supports equipping agents with tools that extend their capabilities. Let us create a simple web search tool.

Create a new file named tools.py:

# tools.py
from crewai_tools import tool
import requests
from bs4 import BeautifulSoup
from typing import List

@tool("Web Search Tool")
def web_search(query: str) -> str:
    """
    Search the web for information on a given query.
    
    Args:
        query: The search query
        
    Returns:
        Relevant information found on the web
    """
    try:
        search_url = f"https://html.duckduckgo.com/html/?q={query}"
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        }
        response = requests.get(search_url, headers=headers, timeout=10)
        
        if response.status_code != 200:
            return f"Search failed with status code {response.status_code}"
        
        soup = BeautifulSoup(response.content, 'html.parser')
        results = []
        
        for result in soup.find_all('div', class_='result')[:5]:
            title_elem = result.find('a', class_='result__a')
            snippet_elem = result.find('a', class_='result__snippet')
            
            if title_elem and snippet_elem:
                title = title_elem.get_text(strip=True)
                snippet = snippet_elem.get_text(strip=True)
                results.append(f"{title}: {snippet}")
        
        if not results:
            return "No results found"
        
        return "\n\n".join(results)
        
    except Exception as e:
        return f"Error performing web search: {str(e)}"

The tool decorator from CrewAI marks this function as a tool that agents can use. The decorator takes a name parameter that identifies the tool to agents. When an agent needs to search the web, it can invoke this tool by name.

The function uses DuckDuckGo's HTML interface for searching because it does not require an API key. We send a request with a user agent header to avoid being blocked. The BeautifulSoup library parses the HTML response and extracts search results.

We limit the results to the top five to keep the output manageable. Each result includes a title and snippet, giving the agent enough context to understand what information is available.

Error handling is important for tools because network requests can fail. If something goes wrong, we return an error message rather than crashing. This allows the agent to handle failures gracefully.

Now let us update our research agent to use this tool:

# agents.py (updated)
from tools import web_search

class ContentCreationAgents:
    def __init__(self, llm: BaseLLM):
        self.llm = llm
    
    def create_research_agent(self) -> Agent:
        """Create a research agent with web search capability"""
        return Agent(
            role="Senior Research Analyst",
            goal="Conduct comprehensive research on the given topic and gather "
                 "accurate, relevant, and up-to-date information from credible sources",
            backstory="You are an experienced research analyst with a background in "
                     "investigative journalism and academic research. You have spent "
                     "over a decade honing your skills in finding reliable information, "
                     "fact-checking, and synthesizing complex topics into clear insights.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm,
            tools=[web_search]
        )

By adding the tools parameter with our web_search function, we give the research agent the ability to search the web. When the agent is working on a research task, it can decide to use this tool to find current information.

The agent does not automatically use the tool for every task. Instead, it reasons about whether the tool would be helpful for the current task. If the agent determines that web search would provide valuable information, it invokes the tool with an appropriate query.

This tool-using capability transforms our agents from being limited to their training data to being able to access current information from the internet. This is especially valuable for the research agent, which needs up-to-date facts and statistics.

Building the Main Application

Now we need to tie everything together into a main application that users can run. This application will handle configuration, model initialization, and crew execution.

Create a file named main.py:

# main.py
import sys
from config import ModelConfig, ModelProvider
from model_factory import ModelFactory
from crew import ContentCreationCrew

def main():
    """Main entry point for the content creation agency"""
    
    if len(sys.argv) < 2:
        print("Usage: python main.py <topic>")
        print("Example: python main.py 'The Future of Renewable Energy'")
        sys.exit(1)
    
    topic = " ".join(sys.argv[1:])
    
    print(f"Creating article on topic: {topic}")
    print("=" * 60)
    
    config = ModelConfig(
        provider=ModelProvider.LOCAL,
        model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
        temperature=0.7,
        max_tokens=2048
    )
    
    print(f"Initializing {config.provider} model...")
    llm = ModelFactory.create_model(config)
    
    print("Creating content creation crew...")
    crew = ContentCreationCrew(llm)
    
    print("Starting content creation process...")
    print("=" * 60)
    
    result = crew.create_article(topic)
    
    print("\n" + "=" * 60)
    print("FINAL ARTICLE")
    print("=" * 60)
    print(result)
    
    with open(f"article_{topic.replace(' ', '_')}.txt", 'w') as f:
        f.write(result)
    
    print(f"\nArticle saved to article_{topic.replace(' ', '_')}.txt")

if __name__ == "__main__":
    main()

The main function orchestrates the entire application. It starts by checking command-line arguments to get the topic. If no topic is provided, it prints usage instructions and exits.

The configuration is created with sensible defaults. In this example, we use a local model, but users can easily modify this to use OpenAI or Anthropic by changing the provider and adding an API key.

After creating the configuration, we use the ModelFactory to instantiate the appropriate language model. This abstracts away the complexity of model initialization.

Then we create the ContentCreationCrew and call its create_article method with the topic. The crew handles all the orchestration, running each agent in sequence and managing the flow of information.

Finally, we print the result and save it to a file. The filename is derived from the topic, making it easy to find the generated article.

This main application provides a clean command-line interface for our content creation system. Users can generate articles on any topic with a single command.

Running the System

To run the system, users need to download a model file if using local execution. GGUF format models are available from Hugging Face. For example, to download a Mistral model:

mkdir models
cd models
wget https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.2-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_K_M.gguf
cd ..

Then run the application with a topic:

python main.py "The Impact of Artificial Intelligence on Healthcare"

The system will initialize the model, create the crew, and execute each task in sequence. You will see output from each agent as they work through their tasks. The research agent will gather information, the writer will craft an article, the editor will refine it, and the SEO specialist will optimize it.

For users who prefer remote APIs, modify the configuration in main.py:

config = ModelConfig(
    provider=ModelProvider.OPENAI,
    model_name="gpt-4",
    api_key="your-api-key-here",
    temperature=0.7,
    max_tokens=2048
)

Or use environment variables by creating a .env file:

OPENAI_API_KEY=your-api-key-here

Then the configuration can omit the api_key parameter and it will be loaded automatically:

config = ModelConfig(
    provider=ModelProvider.OPENAI,
    model_name="gpt-4",
    temperature=0.7,
    max_tokens=2048
)

The system works identically regardless of which model provider you choose. This flexibility is one of the key benefits of our abstraction layers.

Understanding the Execution Flow

Let us trace through what happens when you run the system. When you execute the main.py script with a topic, the following sequence occurs.

First, the configuration is created and validated. Pydantic ensures all values are valid and performs auto-detection of GPU backends if needed. If you are using a remote API, it loads the API key from environment variables.

Second, the ModelFactory creates the appropriate language model instance. For local models, it configures GPU acceleration based on your hardware. For remote APIs, it sets up the HTTP client with authentication.

Third, the ContentCreationCrew is instantiated. It creates the agent factory and task factory, preparing everything needed for execution.

Fourth, when you call create_article, the task factory creates all four tasks with their dependencies. The research task has no dependencies. The writing task depends on research. The editing task depends on writing. The SEO task depends on editing.

Fifth, the Crew object is created with all agents and tasks. CrewAI analyzes the task dependencies to determine the execution order.

Sixth, crew.kickoff() starts the execution. CrewAI runs the research task first because it has no dependencies. The research agent receives the task description and begins working. If equipped with the web search tool, it may use it to find current information.

Seventh, once the research task completes, its output is stored. CrewAI then starts the writing task, providing the research output as context. The writer agent receives both the task description and the research findings.

Eighth, the writer agent crafts an article based on the research. It structures the information into a narrative, adds examples and explanations, and produces a complete draft.

Ninth, the editing task begins once writing completes. The editor agent receives the draft article and refines it, improving clarity, fixing errors, and enhancing flow.

Tenth, finally, the SEO task runs. The SEO agent receives the polished article and optimizes it for search engines, adding a title, meta description, and proper heading structure.

The final output from the SEO task is returned by crew.kickoff() and becomes the result of create_article. This result is then printed and saved to a file.

This sequential flow ensures that each agent builds upon the work of previous agents, creating a collaborative process that produces high-quality content.

Extending the System

The system we have built is extensible. You can add new agents and tasks to enhance functionality. For example, you might add a fact-checking agent that verifies claims in the article. Or a formatting agent that converts the article to HTML or Markdown.

To add a new agent, create a method in the ContentCreationAgents class:

def create_factchecker_agent(self) -> Agent:
    """Create a fact-checking agent"""
    return Agent(
        role="Fact Checker",
        goal="Verify the accuracy of claims and statistics in the article",
        backstory="You are a meticulous fact-checker with expertise in "
                 "verifying information and identifying misinformation.",
        verbose=True,
        allow_delegation=False,
        llm=self.llm,
        tools=[web_search]
    )

Then create a corresponding task:

def create_factchecking_task(self, editing_task: Task) -> Task:
    """Create a fact-checking task"""
    return Task(
        description="""Review the article and verify all factual claims,
        statistics, and assertions. Flag any information that cannot be
        verified or appears questionable. Provide corrections for any
        inaccuracies found.""",
        agent=self.factchecker_agent,
        expected_output="A verified article with corrections for any "
                      "inaccuracies and notes on unverifiable claims",
        context=[editing_task]
    )

Add this task to the crew between editing and SEO:

factcheck_task = self.task_factory.create_factchecking_task(editing_task)
seo_task = self.task_factory.create_seo_task(topic, factcheck_task)

The fact-checking agent will now verify the article before SEO optimization. This demonstrates how easy it is to extend the system with new capabilities.

You can also create tools for other purposes. For example, a tool that checks readability scores:

@tool("Readability Checker")
def check_readability(text: str) -> str:
    """Calculate readability metrics for the given text"""
    sentences = text.count('.') + text.count('!') + text.count('?')
    words = len(text.split())
    
    if sentences == 0:
        return "Unable to calculate readability: no sentences found"
    
    avg_words_per_sentence = words / sentences
    
    if avg_words_per_sentence < 15:
        level = "Easy"
    elif avg_words_per_sentence < 20:
        level = "Medium"
    else:
        level = "Difficult"
    
    return f"Readability: {level} (avg {avg_words_per_sentence:.1f} words/sentence)"

Equip the editor agent with this tool to help it assess and improve readability.

Advanced Configuration Options

Our configuration system supports many options beyond what we have shown. You can create different configurations for different use cases.

For maximum quality with remote APIs:

config = ModelConfig(
    provider=ModelProvider.ANTHROPIC,
    model_name="claude-3-opus-20240229",
    temperature=0.5,
    max_tokens=4096
)

For fast local execution on CPU:

config = ModelConfig(
    provider=ModelProvider.LOCAL,
    model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
    temperature=0.7,
    max_tokens=1024,
    gpu_backend=GPUBackend.CPU
)

For creative writing with higher temperature:

config = ModelConfig(
    provider=ModelProvider.OPENAI,
    model_name="gpt-4",
    temperature=1.2,
    max_tokens=3000
)

The temperature parameter controls randomness in generation. Lower values like 0.5 produce more focused, deterministic output. Higher values like 1.2 produce more creative, varied output. For factual content, use lower temperatures. For creative content, use higher temperatures.

The max_tokens parameter controls output length. Longer articles require higher values. However, higher values also mean slower generation and higher costs for API-based models.

Error Handling and Robustness

Production systems need robust error handling. Let us enhance our main application with better error handling:

def main():
    """Main entry point with error handling"""
    
    try:
        if len(sys.argv) < 2:
            print("Usage: python main.py <topic>")
            sys.exit(1)
        
        topic = " ".join(sys.argv[1:])
        
        print(f"Creating article on topic: {topic}")
        print("=" * 60)
        
        config = ModelConfig(
            provider=ModelProvider.LOCAL,
            model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
            temperature=0.7,
            max_tokens=2048
        )
        
        print(f"Initializing {config.provider} model...")
        llm = ModelFactory.create_model(config)
        
        print("Creating content creation crew...")
        crew = ContentCreationCrew(llm)
        
        print("Starting content creation process...")
        print("=" * 60)
        
        result = crew.create_article(topic)
        
        print("\n" + "=" * 60)
        print("FINAL ARTICLE")
        print("=" * 60)
        print(result)
        
        filename = f"article_{topic.replace(' ', '_')}.txt"
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(result)
        
        print(f"\nArticle saved to {filename}")
        
    except FileNotFoundError as e:
        print(f"Error: Model file not found. {e}")
        print("Please download a model file and update the model_path in the configuration.")
        sys.exit(1)
    except ValueError as e:
        print(f"Configuration error: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

This enhanced version catches specific exceptions and provides helpful error messages. If the model file is not found, it tells the user to download one. If there is a configuration error, it explains what went wrong. For unexpected errors, it prints the full traceback to aid debugging.

Performance Considerations

The performance of your agentic system depends on several factors. The choice between local and remote models has the biggest impact. Local models require powerful hardware but have no per-request costs and no latency from network calls. Remote APIs are convenient and powerful but incur costs and network latency.

For local execution, GPU acceleration is crucial. A model running entirely on CPU might take minutes to generate a response. The same model on a GPU might take only seconds. Our system automatically uses available GPU acceleration, but you need appropriate hardware.

The number of GPU layers offloaded affects both speed and memory usage. Offloading all layers to GPU is fastest but requires more VRAM. If you run out of GPU memory, reduce the number of layers or use a smaller model.

Model size also matters. Larger models like 13B or 70B parameter models produce better output but run slower and require more memory. Smaller models like 7B parameters are faster but may produce lower quality output. Choose based on your quality requirements and hardware capabilities.

For production deployments, consider caching. If you generate articles on similar topics frequently, you might cache research results to avoid redundant work. You could also cache model outputs for common queries.

Testing Your Agentic System

Testing agentic systems is challenging because outputs are non-deterministic. The same input can produce different outputs due to the randomness in language model generation. However, you can still write useful tests.

Create a file named test_system.py:

# test_system.py
import unittest
from config import ModelConfig, ModelProvider
from model_factory import ModelFactory
from crew import ContentCreationCrew

class TestContentCreationSystem(unittest.TestCase):
    """Tests for the content creation system"""
    
    def setUp(self):
        """Set up test fixtures"""
        self.config = ModelConfig(
            provider=ModelProvider.LOCAL,
            model_path="./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
            temperature=0.7,
            max_tokens=512
        )
        self.llm = ModelFactory.create_model(self.config)
        self.crew = ContentCreationCrew(self.llm)
    
    def test_article_generation(self):
        """Test that article generation completes without errors"""
        topic = "Test Topic"
        result = self.crew.create_article(topic)
        
        self.assertIsNotNone(result)
        self.assertIsInstance(result, str)
        self.assertGreater(len(result), 100)
    
    def test_article_contains_topic(self):
        """Test that generated article mentions the topic"""
        topic = "Quantum Computing"
        result = self.crew.create_article(topic)
        
        self.assertIn("quantum", result.lower())

if __name__ == "__main__":
    unittest.main()

These tests verify basic functionality. The first test ensures that article generation completes and produces a non-empty string. The second test checks that the generated article actually relates to the requested topic.

For more comprehensive testing, you might evaluate output quality using metrics like readability scores, keyword density, or structural completeness. You could also use human evaluation, having people rate the quality of generated articles.

Deployment Considerations

When deploying an agentic system to production, consider several factors. First, decide between local and remote model execution based on your requirements. Local execution gives you control and eliminates per-request costs but requires infrastructure. Remote APIs are easier to deploy but incur ongoing costs.

For local deployment, containerization helps ensure consistency. Create a Dockerfile:

FROM python:3.10-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "main.py"]

This creates a container with all dependencies installed. You can deploy this container to any server with Docker support.

For scaling, consider using a task queue. Instead of generating articles synchronously, accept requests and queue them for processing. This allows you to handle multiple requests concurrently and scale horizontally.

Monitor your system in production. Track metrics like generation time, error rates, and output quality. Set up alerts for failures or performance degradation.

Secure your API keys and sensitive configuration. Never commit API keys to version control. Use environment variables or secret management services.

Conclusion

We have built a complete agentic AI system using CrewAI. This system demonstrates the key concepts of agentic AI: specialized agents working together, task orchestration, tool usage, and collaborative workflows.

Our content creation agency mirrors how human teams work, with each agent bringing specific expertise. The research agent gathers information, the writer crafts prose, the editor refines quality, and the SEO specialist optimizes discoverability. By breaking down the complex task of content creation into specialized subtasks, we achieve better results than a single generalist agent could produce.

The system is flexible and extensible. It supports both local and remote model execution, works with various GPU backends, and can be easily extended with new agents and tools. The clean architecture with separated concerns makes the code maintainable and testable.

This tutorial has covered the fundamental concepts you need to build agentic AI systems. You can apply these patterns to many domains beyond content creation. Any complex task that can be broken down into specialized subtasks is a candidate for an agentic approach.

The future of AI applications lies in these collaborative, multi-agent systems. As you build more sophisticated agents and crews, you will discover new ways to combine AI capabilities to solve real-world problems.


COMPLETE RUNNING EXAMPLE

Below is the complete, production-ready code for the content creation agency. This code includes all functionality discussed in the tutorial and is ready to run. Note: the listing below contains multiple files.

# config.py
import os
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
from dotenv import load_dotenv

load_dotenv()

class ModelProvider(str, Enum):
    """Enumeration of supported model providers"""
    LOCAL = "local"
    OPENAI = "openai"
    ANTHROPIC = "anthropic"
    OLLAMA = "ollama"

class GPUBackend(str, Enum):
    """Enumeration of supported GPU backends"""
    CUDA = "cuda"
    ROCM = "rocm"
    METAL = "metal"
    ONEAPI = "oneapi"
    CPU = "cpu"

class ModelConfig(BaseModel):
    """Configuration for language model selection and parameters"""
    provider: ModelProvider = Field(
        default=ModelProvider.LOCAL,
        description="The model provider to use"
    )
    model_name: str = Field(
        default="mistral-7b-instruct",
        description="Name of the model to use"
    )
    temperature: float = Field(
        default=0.7,
        ge=0.0,
        le=2.0,
        description="Sampling temperature for generation"
    )
    max_tokens: int = Field(
        default=2048,
        gt=0,
        description="Maximum tokens to generate"
    )
    gpu_backend: Optional[GPUBackend] = Field(
        default=None,
        description="GPU backend for local models"
    )
    api_key: Optional[str] = Field(
        default=None,
        description="API key for remote providers"
    )
    model_path: Optional[str] = Field(
        default=None,
        description="Path to local model file"
    )
    
    class Config:
        use_enum_values = True

    def __init__(self, **data):
        super().__init__(**data)
        if self.provider == ModelProvider.LOCAL and self.gpu_backend is None:
            self.gpu_backend = self._detect_gpu_backend()
        
        if self.provider == ModelProvider.OPENAI and self.api_key is None:
            self.api_key = os.getenv("OPENAI_API_KEY")
        elif self.provider == ModelProvider.ANTHROPIC and self.api_key is None:
            self.api_key = os.getenv("ANTHROPIC_API_KEY")
    
    @staticmethod
    def _detect_gpu_backend() -> GPUBackend:
        """Automatically detect available GPU backend"""
        try:
            import torch
            if torch.cuda.is_available():
                return GPUBackend.CUDA
            elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
                return GPUBackend.METAL
        except ImportError:
            pass
        
        if os.path.exists('/opt/rocm'):
            return GPUBackend.ROCM
        
        if os.getenv('ONEAPI_ROOT'):
            return GPUBackend.ONEAPI
        
        return GPUBackend.CPU
# model_factory.py
from typing import Union
from langchain.llms.base import BaseLLM
from langchain_community.llms import LlamaCpp, Ollama
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from config import ModelConfig, ModelProvider, GPUBackend

class ModelFactory:
    """Factory for creating language model instances based on configuration"""
    
    @staticmethod
    def create_model(config: ModelConfig) -> BaseLLM:
        """
        Create and configure a language model instance.
        
        Args:
            config: Model configuration specifying provider and parameters
            
        Returns:
            Configured language model instance
            
        Raises:
            ValueError: If the provider is not supported or configuration is invalid
        """
        if config.provider == ModelProvider.LOCAL:
            return ModelFactory._create_local_model(config)
        elif config.provider == ModelProvider.OPENAI:
            return ModelFactory._create_openai_model(config)
        elif config.provider == ModelProvider.ANTHROPIC:
            return ModelFactory._create_anthropic_model(config)
        elif config.provider == ModelProvider.OLLAMA:
            return ModelFactory._create_ollama_model(config)
        else:
            raise ValueError(f"Unsupported model provider: {config.provider}")
    
    @staticmethod
    def _create_local_model(config: ModelConfig) -> LlamaCpp:
        """Create a local model using llama-cpp-python with GPU acceleration"""
        if config.model_path is None:
            raise ValueError("model_path must be specified for local models")
        
        n_gpu_layers = ModelFactory._get_gpu_layers(config.gpu_backend)
        
        model_params = {
            "model_path": config.model_path,
            "temperature": config.temperature,
            "max_tokens": config.max_tokens,
            "n_gpu_layers": n_gpu_layers,
            "n_ctx": 4096,
            "n_batch": 512,
            "verbose": False,
        }
        
        if config.gpu_backend == GPUBackend.METAL:
            model_params["n_gpu_layers"] = 1
            model_params["f16_kv"] = True
        elif config.gpu_backend == GPUBackend.CUDA:
            model_params["n_gpu_layers"] = -1
        elif config.gpu_backend == GPUBackend.ROCM:
            model_params["n_gpu_layers"] = -1
        
        return LlamaCpp(**model_params)
    
    @staticmethod
    def _create_openai_model(config: ModelConfig) -> ChatOpenAI:
        """Create an OpenAI model instance"""
        if config.api_key is None:
            raise ValueError("API key must be provided for OpenAI models")
        
        return ChatOpenAI(
            model_name=config.model_name,
            temperature=config.temperature,
            max_tokens=config.max_tokens,
            openai_api_key=config.api_key
        )
    
    @staticmethod
    def _create_anthropic_model(config: ModelConfig) -> ChatAnthropic:
        """Create an Anthropic Claude model instance"""
        if config.api_key is None:
            raise ValueError("API key must be provided for Anthropic models")
        
        return ChatAnthropic(
            model=config.model_name,
            temperature=config.temperature,
            max_tokens=config.max_tokens,
            anthropic_api_key=config.api_key
        )
    
    @staticmethod
    def _create_ollama_model(config: ModelConfig) -> Ollama:
        """Create an Ollama model instance for local API server"""
        return Ollama(
            model=config.model_name,
            temperature=config.temperature,
            num_predict=config.max_tokens
        )
    
    @staticmethod
    def _get_gpu_layers(backend: GPUBackend) -> int:
        """
        Determine optimal number of GPU layers based on backend.
        
        Returns -1 for full GPU offloading, 0 for CPU only, or specific
        layer count for backends with special requirements.
        """
        if backend == GPUBackend.CPU:
            return 0
        elif backend == GPUBackend.METAL:
            return 1
        else:
            return -1
# tools.py
from crewai_tools import tool
import requests
from bs4 import BeautifulSoup
from typing import List

@tool("Web Search Tool")
def web_search(query: str) -> str:
    """
    Search the web for information on a given query.
    
    Args:
        query: The search query
        
    Returns:
        Relevant information found on the web
    """
    try:
        search_url = f"https://html.duckduckgo.com/html/?q={query}"
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        }
        response = requests.get(search_url, headers=headers, timeout=10)
        
        if response.status_code != 200:
            return f"Search failed with status code {response.status_code}"
        
        soup = BeautifulSoup(response.content, 'html.parser')
        results = []
        
        for result in soup.find_all('div', class_='result')[:5]:
            title_elem = result.find('a', class_='result__a')
            snippet_elem = result.find('a', class_='result__snippet')
            
            if title_elem and snippet_elem:
                title = title_elem.get_text(strip=True)
                snippet = snippet_elem.get_text(strip=True)
                results.append(f"{title}: {snippet}")
        
        if not results:
            return "No results found"
        
        return "\n\n".join(results)
        
    except Exception as e:
        return f"Error performing web search: {str(e)}"

@tool("Readability Checker")
def check_readability(text: str) -> str:
    """
    Calculate readability metrics for the given text.
    
    Args:
        text: The text to analyze
        
    Returns:
        Readability assessment and metrics
    """
    sentences = text.count('.') + text.count('!') + text.count('?')
    words = len(text.split())
    
    if sentences == 0:
        return "Unable to calculate readability: no sentences found"
    
    avg_words_per_sentence = words / sentences
    
    if avg_words_per_sentence < 15:
        level = "Easy"
        recommendation = "Good for general audiences"
    elif avg_words_per_sentence < 20:
        level = "Medium"
        recommendation = "Appropriate for most readers"
    else:
        level = "Difficult"
        recommendation = "Consider simplifying for broader appeal"
    
    return f"Readability: {level}\nAverage words per sentence: {avg_words_per_sentence:.1f}\nRecommendation: {recommendation}"
# agents.py
from crewai import Agent
from langchain.llms.base import BaseLLM
from tools import web_search, check_readability

class ContentCreationAgents:
    """Factory class for creating specialized content creation agents"""
    
    def __init__(self, llm: BaseLLM):
        """
        Initialize the agent factory with a language model.
        
        Args:
            llm: The language model to be used by all agents
        """
        self.llm = llm
    
    def create_research_agent(self) -> Agent:
        """
        Create a research agent specialized in gathering information.
        
        This agent acts as an investigative researcher, gathering facts,
        statistics, expert opinions, and relevant information about the
        given topic. It excels at finding credible sources and extracting
        key insights that will form the foundation of the content.
        
        Returns:
            Configured research agent instance
        """
        return Agent(
            role="Senior Research Analyst",
            goal="Conduct comprehensive research on the given topic and gather "
                 "accurate, relevant, and up-to-date information from credible sources",
            backstory="You are an experienced research analyst with a background in "
                     "investigative journalism and academic research. You have spent "
                     "over a decade honing your skills in finding reliable information, "
                     "fact-checking, and synthesizing complex topics into clear insights. "
                     "Your expertise lies in identifying authoritative sources, extracting "
                     "key data points, and understanding the nuances of various subjects. "
                     "You take pride in the accuracy and depth of your research, never "
                     "settling for surface-level information.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm,
            tools=[web_search]
        )
    
    def create_writer_agent(self) -> Agent:
        """
        Create a writer agent specialized in crafting engaging content.
        
        This agent takes research findings and transforms them into compelling,
        well-structured prose. It understands narrative flow, audience engagement,
        and how to present information in an accessible way.
        
        Returns:
            Configured writer agent instance
        """
        return Agent(
            role="Expert Content Writer",
            goal="Transform research findings into compelling, well-structured "
                 "articles that engage readers and communicate ideas clearly",
            backstory="You are a seasoned content writer with fifteen years of "
                     "experience creating articles for major publications. Your "
                     "writing style is clear, engaging, and accessible. You excel "
                     "at taking complex information and making it understandable "
                     "without dumbing it down. You understand narrative structure, "
                     "pacing, and how to keep readers engaged from the first "
                     "sentence to the last. You have a talent for finding the "
                     "perfect examples and analogies to illustrate complex concepts.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm
        )
    
    def create_editor_agent(self) -> Agent:
        """
        Create an editor agent specialized in refining and polishing content.
        
        This agent reviews written content with a critical eye, checking for
        clarity, coherence, grammar, and style. It acts as a quality gatekeeper,
        ensuring that the content meets professional standards.
        
        Returns:
            Configured editor agent instance
        """
        return Agent(
            role="Senior Content Editor",
            goal="Review and refine written content to ensure clarity, coherence, "
                 "grammatical correctness, and stylistic excellence",
            backstory="You are a meticulous editor with a sharp eye for detail and "
                     "a deep understanding of language. With twenty years of editorial "
                     "experience at top-tier publications, you have developed an "
                     "instinct for what makes writing great. You catch grammatical "
                     "errors, awkward phrasing, logical inconsistencies, and structural "
                     "problems. You improve clarity without changing the author's voice. "
                     "You ensure every sentence serves a purpose and every paragraph "
                     "flows naturally into the next.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm,
            tools=[check_readability]
        )
    
    def create_seo_agent(self) -> Agent:
        """
        Create an SEO specialist agent for optimizing content.
        
        This agent optimizes content for search engines while maintaining
        readability and user engagement. It ensures the article ranks well
        and attracts organic traffic.
        
        Returns:
            Configured SEO agent instance
        """
        return Agent(
            role="SEO Optimization Specialist",
            goal="Optimize content for search engines while maintaining readability "
                 "and user engagement, ensuring the article ranks well and attracts "
                 "organic traffic",
            backstory="You are an SEO expert with deep knowledge of search engine "
                     "algorithms, keyword research, and content optimization strategies. "
                     "You have helped hundreds of articles achieve top rankings in "
                     "search results. You understand how to naturally incorporate "
                     "keywords, optimize meta descriptions, create compelling titles, "
                     "and structure content for both search engines and human readers. "
                     "You know that the best SEO serves the user first and the algorithm "
                     "second.",
            verbose=True,
            allow_delegation=False,
            llm=self.llm
        )
# tasks.py
from crewai import Task
from agents import ContentCreationAgents

class ContentCreationTasks:
    """Factory class for creating content creation tasks"""
    
    def __init__(self, agents: ContentCreationAgents):
        """
        Initialize with agent factory.
        
        Args:
            agents: Agent factory for creating specialized agents
        """
        self.research_agent = agents.create_research_agent()
        self.writer_agent = agents.create_writer_agent()
        self.editor_agent = agents.create_editor_agent()
        self.seo_agent = agents.create_seo_agent()
    
    def create_research_task(self, topic: str) -> Task:
        """
        Create a task for researching the given topic.
        
        Args:
            topic: The topic to research
            
        Returns:
            Configured research task
        """
        return Task(
            description=f"""Conduct comprehensive research on the topic: {topic}
            
            Your research should include:
            - Key facts and statistics about the topic
            - Current trends and recent developments
            - Expert opinions and authoritative perspectives
            - Common questions and misconceptions
            - Relevant examples and case studies
            - Historical context where applicable
            
            Focus on finding credible, up-to-date information from authoritative sources.
            Use the web search tool to find current information when needed.
            Organize your findings in a clear, structured format that will be useful
            for a writer creating an article on this topic.
            
            Your output should be a detailed research report covering all important
            aspects of the topic, with clear sections and well-organized information.""",
            agent=self.research_agent,
            expected_output="A comprehensive research report with facts, statistics, "
                          "trends, expert opinions, and relevant examples organized "
                          "in a clear structure with distinct sections"
        )
    
    def create_writing_task(self, topic: str, research_task: Task) -> Task:
        """
        Create a task for writing an article based on research.
        
        Args:
            topic: The topic to write about
            research_task: The research task providing context
            
        Returns:
            Configured writing task
        """
        return Task(
            description=f"""Using the research findings, write a comprehensive,
            engaging article on the topic: {topic}
            
            Your article should:
            - Have a compelling introduction that hooks the reader and clearly
              states what the article will cover
            - Present information in a logical, well-structured flow with clear
              sections and smooth transitions
            - Use clear, accessible language appropriate for a general audience
              while maintaining accuracy and depth
            - Include relevant examples, analogies, and explanations to illustrate
              complex concepts
            - Maintain reader engagement throughout with varied sentence structure
              and interesting presentation
            - Conclude with a strong summary that reinforces key points and
              provides actionable takeaways or thought-provoking insights
            
            Aim for an article length of 1500-2000 words. Write in a professional
            yet conversational tone. Make complex ideas accessible without
            oversimplifying them.
            
            Base your article on the research findings provided, but transform
            the information into engaging narrative prose rather than simply
            listing facts. Tell a story with the information.""",
            agent=self.writer_agent,
            expected_output="A well-written, engaging article of 1500-2000 words "
                          "with clear structure, compelling narrative, accessible "
                          "explanations, and strong introduction and conclusion",
            context=[research_task]
        )
    
    def create_editing_task(self, writing_task: Task) -> Task:
        """
        Create a task for editing the written article.
        
        Args:
            writing_task: The writing task providing context
            
        Returns:
            Configured editing task
        """
        return Task(
            description="""Review and refine the written article to ensure
            the highest quality.
            
            Your editing should address:
            - Grammar, spelling, and punctuation errors
            - Sentence structure and clarity
            - Paragraph flow and transitions between ideas
            - Logical consistency and coherence of arguments
            - Tone and style consistency throughout the article
            - Removal of redundancy and wordiness
            - Factual accuracy and precision of language
            - Overall readability and accessibility
            
            Use the readability checker tool to assess the article's readability
            and make improvements if needed.
            
            Improve the writing while preserving the author's voice and intent.
            Ensure every sentence is clear and every paragraph serves a purpose.
            The final article should read smoothly from beginning to end with
            natural flow and engaging presentation.
            
            Provide the edited version of the complete article with all
            improvements incorporated.""",
            agent=self.editor_agent,
            expected_output="A polished, error-free article with improved clarity, "
                          "flow, and coherence, maintaining the original voice while "
                          "enhancing overall quality",
            context=[writing_task]
        )
    
    def create_seo_task(self, topic: str, editing_task: Task) -> Task:
        """
        Create a task for SEO optimization.
        
        Args:
            topic: The main topic/keyword to optimize for
            editing_task: The editing task providing context
            
        Returns:
            Configured SEO task
        """
        return Task(
            description=f"""Optimize the edited article for search engines while
            maintaining readability and user engagement.
            
            Your optimization should include:
            - A compelling, SEO-friendly title (60 characters or less) that
              incorporates the main keyword: {topic}
            - A meta description (150-160 characters) that encourages clicks
              from search results and includes the main keyword
            - Natural incorporation of relevant keywords and semantic variations
              throughout the article without keyword stuffing
            - Proper heading structure (H1 for title, H2 for main sections,
              H3 for subsections) that improves both readability and SEO
            - Suggestions for internal linking opportunities (where this article
              could link to related content)
            - Suggestions for external linking to authoritative sources
            - Image alt text suggestions if images were to be included
            
            Ensure that all SEO improvements feel natural and do not compromise
            the quality or readability of the content. The article should serve
            human readers first while also being discoverable by search engines.
            
            Provide the final, SEO-optimized version of the article along with
            the title, meta description, and any additional SEO recommendations.""",
            agent=self.seo_agent,
            expected_output="A complete, SEO-optimized article with compelling title, "
                          "meta description, proper heading structure, natural keyword "
                          "integration, and linking suggestions",
            context=[editing_task]
        )
# crew.py
from crewai import Crew, Process
from langchain.llms.base import BaseLLM
from agents import ContentCreationAgents
from tasks import ContentCreationTasks

class ContentCreationCrew:
    """Orchestrates the content creation process using multiple specialized agents"""
    
    def __init__(self, llm: BaseLLM):
        """
        Initialize the crew with a language model.
        
        Args:
            llm: The language model to be used by all agents
        """
        self.llm = llm
        self.agents = ContentCreationAgents(llm)
        self.task_factory = ContentCreationTasks(self.agents)
    
    def create_article(self, topic: str) -> str:
        """
        Create a complete article on the given topic using the agent crew.
        
        This method orchestrates the entire content creation process, running
        each agent in sequence to produce a high-quality, SEO-optimized article.
        
        The process follows these steps:
        1. Research Agent gathers comprehensive information on the topic
        2. Writer Agent crafts an engaging article based on the research
        3. Editor Agent refines and polishes the written content
        4. SEO Agent optimizes the article for search engines
        
        Args:
            topic: The topic to write about
            
        Returns:
            The final, SEO-optimized article with title and meta description
        """
        research_task = self.task_factory.create_research_task(topic)
        writing_task = self.task_factory.create_writing_task(topic, research_task)
        editing_task = self.task_factory.create_editing_task(writing_task)
        seo_task = self.task_factory.create_seo_task(topic, editing_task)
        
        crew = Crew(
            agents=[
                self.agents.create_research_agent(),
                self.agents.create_writer_agent(),
                self.agents.create_editor_agent(),
                self.agents.create_seo_agent()
            ],
            tasks=[research_task, writing_task, editing_task, seo_task],
            process=Process.sequential,
            verbose=True
        )
        
        result = crew.kickoff()
        return result
# main.py
import sys
import os
from config import ModelConfig, ModelProvider, GPUBackend
from model_factory import ModelFactory
from crew import ContentCreationCrew

def print_banner():
    """Print application banner"""
    print("\n" + "=" * 70)
    print(" " * 15 + "CONTENT CREATION AGENCY")
    print(" " * 10 + "Powered by CrewAI and Agentic AI")
    print("=" * 70 + "\n")

def print_usage():
    """Print usage instructions"""
    print("Usage: python main.py <topic> [options]")
    print("\nOptions:")
    print("  --provider <provider>    Model provider (local, openai, anthropic, ollama)")
    print("  --model <model>          Model name")
    print("  --temperature <temp>     Sampling temperature (0.0-2.0)")
    print("  --max-tokens <tokens>    Maximum tokens to generate")
    print("  --model-path <path>      Path to local model file (for local provider)")
    print("\nExamples:")
    print("  python main.py 'The Future of Renewable Energy'")
    print("  python main.py 'AI in Healthcare' --provider openai --model gpt-4")
    print("  python main.py 'Quantum Computing' --provider local --model-path ./models/mistral.gguf")

def parse_arguments():
    """Parse command line arguments"""
    if len(sys.argv) < 2 or sys.argv[1] in ['-h', '--help']:
        print_usage()
        sys.exit(0 if len(sys.argv) >= 2 else 1)
    
    topic = sys.argv[1]
    
    config_params = {
        "provider": ModelProvider.LOCAL,
        "model_name": "mistral-7b-instruct",
        "temperature": 0.7,
        "max_tokens": 2048,
    }
    
    i = 2
    while i < len(sys.argv):
        arg = sys.argv[i]
        
        if arg == "--provider" and i + 1 < len(sys.argv):
            config_params["provider"] = ModelProvider(sys.argv[i + 1])
            i += 2
        elif arg == "--model" and i + 1 < len(sys.argv):
            config_params["model_name"] = sys.argv[i + 1]
            i += 2
        elif arg == "--temperature" and i + 1 < len(sys.argv):
            config_params["temperature"] = float(sys.argv[i + 1])
            i += 2
        elif arg == "--max-tokens" and i + 1 < len(sys.argv):
            config_params["max_tokens"] = int(sys.argv[i + 1])
            i += 2
        elif arg == "--model-path" and i + 1 < len(sys.argv):
            config_params["model_path"] = sys.argv[i + 1]
            i += 2
        else:
            print(f"Unknown argument: {arg}")
            print_usage()
            sys.exit(1)
    
    if config_params["provider"] == ModelProvider.LOCAL and "model_path" not in config_params:
        config_params["model_path"] = "./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf"
    
    return topic, ModelConfig(**config_params)

def main():
    """Main entry point for the content creation agency"""
    
    try:
        print_banner()
        
        topic, config = parse_arguments()
        
        print(f"Topic: {topic}")
        print(f"Provider: {config.provider}")
        print(f"Model: {config.model_name}")
        print(f"Temperature: {config.temperature}")
        print(f"Max Tokens: {config.max_tokens}")
        
        if config.provider == ModelProvider.LOCAL:
            print(f"GPU Backend: {config.gpu_backend}")
            print(f"Model Path: {config.model_path}")
        
        print("\n" + "-" * 70 + "\n")
        
        print("Initializing language model...")
        llm = ModelFactory.create_model(config)
        print("Model initialized successfully.\n")
        
        print("Creating content creation crew...")
        crew = ContentCreationCrew(llm)
        print("Crew created successfully.\n")
        
        print("Starting content creation process...")
        print("This may take several minutes depending on your hardware.\n")
        print("-" * 70 + "\n")
        
        result = crew.create_article(topic)
        
        print("\n" + "=" * 70)
        print(" " * 25 + "FINAL ARTICLE")
        print("=" * 70 + "\n")
        print(result)
        print("\n" + "=" * 70 + "\n")
        
        filename = f"article_{topic.replace(' ', '_').replace('/', '_')}.txt"
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(f"Topic: {topic}\n")
            f.write(f"Generated by: Content Creation Agency\n")
            f.write(f"Provider: {config.provider}\n")
            f.write(f"Model: {config.model_name}\n")
            f.write("\n" + "=" * 70 + "\n\n")
            f.write(result)
        
        print(f"Article saved to: {filename}\n")
        
    except FileNotFoundError as e:
        print(f"\nError: Model file not found.")
        print(f"Details: {e}")
        print("\nFor local models, please download a GGUF model file and specify")
        print("its path using --model-path or place it at the default location:")
        print("  ./models/mistral-7b-instruct-v0.2.Q4_K_M.gguf")
        print("\nYou can download models from Hugging Face:")
        print("  https://huggingface.co/TheBloke")
        sys.exit(1)
    except ValueError as e:
        print(f"\nConfiguration Error: {e}")
        print("\nPlease check your configuration and try again.")
        print_usage()
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n\nProcess interrupted by user.")
        sys.exit(0)
    except Exception as e:
        print(f"\nAn unexpected error occurred: {e}")
        print("\nStack trace:")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()
# requirements.txt
crewai>=0.1.0
crewai-tools>=0.1.0
langchain>=0.1.0
langchain-community>=0.0.1
langchain-openai>=0.0.1
langchain-anthropic>=0.0.1
llama-cpp-python>=0.2.0
openai>=1.0.0
anthropic>=0.7.0
python-dotenv>=1.0.0
pydantic>=2.0.0
requests>=2.31.0
beautifulsoup4>=4.12.0

This complete running example includes all the code discussed in the tutorial. It is production-ready and supports local and remote model execution across various GPU architectures. The system is modular, extensible, and follows clean architecture principles. You can run it immediately after installing dependencies and obtaining a model file.