Making all tests good

This commit is contained in:
João Moura
2024-09-13 04:30:11 -05:00
parent 7120a9860b
commit 91ddab207f
88 changed files with 28070 additions and 26873 deletions

View File

@@ -20,6 +20,7 @@ from crewai.tasks.output_format import OutputFormat
from crewai.tasks.task_output import TaskOutput
from crewai.types.usage_metrics import UsageMetrics
from crewai.utilities import Logger
from crewai.utilities.rpm_controller import RPMController
from crewai.utilities.task_output_storage_handler import TaskOutputStorageHandler
ceo = Agent(
@@ -225,7 +226,7 @@ def test_crew_creation():
result = crew.kickoff()
expected_string_output = "**The Emergence of Ethical AI: Balancing Innovation with Responsibility**\n\nThe growing deployment of artificial intelligence (AI) in various sectors has highlighted the critical need for ethical AI. As organizations leverage AI to enhance efficiency, the potential for misuse and unintentional bias has surged. This segment delves into the importance of developing transparent, fair, and accountable AI systems. It underscores the responsibility of tech companies and developers to balance innovation with ethical standards, ensuring that AI advancements benefit society without compromising moral principles. By incorporating ethical guidelines and audits into AI development, stakeholders can mitigate risks and promote trust in AI technologies.\n\n**AI in Healthcare: Revolutionizing Diagnosis and Treatment**\n\nArtificial intelligence is transforming the healthcare sector with unprecedented precision and efficiency. By enhancing diagnostic accuracy, personalizing treatment plans, and streamlining administrative processes, AI is revolutionizing how healthcare providers deliver care. This section of the article explores real-world examples and case studies that demonstrate the life-saving potential and cost-reduction benefits of AI-driven healthcare solutions. It highlights how machine learning algorithms can analyze vast amounts of medical data to detect diseases earlier and predict patient outcomes more accurately, ultimately leading to better patient care and resource management.\n\n**AI-Powered Personal Assistants: The Future of Human-Technology Interaction**\n\nThe evolution of AI-powered personal assistants, such as Siri, Alexa, and Google Assistant, is significantly changing the dynamics of human-technology interaction. These assistants have progressed from simple voice command tools to sophisticated systems that can manage tasks, provide personalized recommendations, and even handle complex queries. This paragraph focuses on the expanding capabilities of AI personal assistants and their growing impact on daily life and work productivity. As they become more intuitive and integrated into various devices and platforms, these AI assistants are poised to become indispensable partners in our digital lives, transforming how we access and use technology.\n\n**AI in Content Creation: From Art to News**\n\nArtificial intelligence is making waves in the realm of content creation, generating art, writing, and news with increasing sophistication. This topic investigates how AI is challenging traditional notions of creativity and originality, raising questions about the role of human artists and journalists. By analyzing the implications for content creators and consumers, this section illuminates the possibilities and limitations of AI-generated content. It discusses how AI can democratize media production, making it accessible to a broader audience, while also considering the ethical and philosophical debates surrounding the authenticity of AI-driven creativity."
expected_string_output = "**AI in Healthcare: Revolutionizing Diagnosis and Treatment**\n\nThe integration of AI into healthcare systems heralds a transformative era in the medical field, with the potential to save lives and significantly enhance the quality of patient care. Advanced AI algorithms excel at diagnosing complex diseases such as cancer by analyzing medical images with precision that rivals human expertise. Additionally, the implementation of AI-powered personalized treatment plans can optimize individual patient care, while predictive analytics anticipates complications before they occur, shifting the healthcare paradigm from reactive to proactive. This revolution not only promises to improve diagnostic accuracy but also aims to enhance overall patient outcomes by making healthcare delivery more efficient and anticipatory.\n\n**Ethical Considerations in AI Development: Balancing Innovation and Responsibility**\n\nAs AI technologies become increasingly embedded in daily life, the ethical implications of their development and deployment come to the forefront. This topic delves into the crucial need for ethical frameworks to manage AI's growth responsibly. Issues such as biases within machine learning models, privacy concerns, and the socio-economic impact on employment highlight the importance of creating AI systems that are fair and just. Ensuring these technologies support human values and dignity requires careful navigation of moral dilemmas and the establishment of stringent ethical standards. Therefore, balancing innovation with responsibility is essential to harness the full potential of AI in a way that benefits society as a whole.\n\n**AI Agents in Customer Service: Enhancing User Experience While Reducing Costs**\n\nAI agents, including chatbots and virtual assistants, are revolutionizing customer service by offering round-the-clock support and addressing routine inquiries with an efficiency unmatched by human representatives. The advancements in Natural Language Processing (NLP) enable these AI agents to understand and respond to customer queries in a more natural and conversational manner, significantly boosting user satisfaction. This seamless interaction not only enhances the customer experience but also reduces operational costs for businesses, as AI agents can manage a high volume of interactions simultaneously. As a result, companies benefit from streamlined customer service operations while customers enjoy quicker, more effective resolutions to their problems.\n\n**The Role of AI in Climate Change: Predicting and Mitigating Environmental Impact**\n\nThe role of AI in combating climate change is becoming increasingly prominent, offering innovative solutions to one of the most pressing issues facing humanity today. AI's ability to process and analyze enormous datasets allows for the accurate prediction of climate trends and the identification of effective strategies to reduce carbon footprints. By optimizing energy consumption and other key factors, AI technologies contribute substantially to efforts aimed at mitigating environmental impact. This exploration into AI's contributions to environmental sustainability highlights the potential for these technologies to go beyond conventional approaches, providing new tools in the global fight against climate change and fostering a more sustainable future."
assert str(result) == expected_string_output
assert result.raw == expected_string_output
@@ -293,7 +294,7 @@ def test_hierarchical_process():
assert (
result.raw
== "1. **The Future of AI in Healthcare: Transformations and Innovations**\n - In the evolving landscape of healthcare, AI is poised to revolutionize patient care, diagnostics, and medical research. Imagine a world where AI-driven diagnostics can predict diseases before they manifest symptoms, personalized treatment plans are crafted using machine learning algorithms, and robotic surgeons operate with unparalleled precision. The infusion of AI into healthcare is not merely futuristic; it's happening now, with innovations such as predictive analytics in patient care, AI-powered telemedicine, and smart wearable devices tracking and analyzing health metrics in real-time. This article will delve into the groundbreaking advancements and forecast how AI will continue to transform the healthcare industry, improving outcomes and accessibility while addressing ethical and practical challenges.\n\n2. **AI Ethics and Bias: Navigating the Moral Landscape**\n - As AI systems become more integrated into society, the ethical implications of their deployment must be rigorously examined. AI's potential to replicate and even amplify human biases poses a significant challenge, necessitating robust frameworks for fairness, accountability, and transparency. This article will explore the pressing ethical dilemmas, from biased algorithms affecting hiring practices to facial recognition technologies intruding on privacy rights. It will highlight ongoing efforts to create ethical guidelines and equitable AI systems, the role of diverse datasets in mitigating bias, and the importance of interdisciplinary collaboration between technologists, ethicists, and policymakers in shaping an ethical AI future.\n\n3. **Autonomous Agents: From Virtual Assistants to Adaptive Learning Bots**\n - Autonomous agents are transforming how we interact with technology, moving beyond simple task automation to become sophisticated, adaptive entities capable of learning and evolving. This article will journey through the evolution of autonomous agents, showcasing virtual assistants like Siri and Alexa, and advancing to adaptive learning bots used in education and customer service. We'll examine their underlying technologies, such as natural language processing and reinforcement learning, and discuss real-world applications that demonstrate their potential to enhance productivity, learning experiences, and personalized user interactions. The promise of autonomous agents lies in their ability to continually adapt and improve, offering increasingly valuable assistance in our daily lives and work.\n\n4. **AI and the Future of Work: Opportunities and Challenges**\n - The integration of AI into the workplace promises a future teeming with opportunities and challenges. While AI can augment human capabilities, streamline operations, and drive innovation, it also raises concerns about job displacement and workforce adaptation. This article will present a balanced view of the AI-driven future of work, examining sectors likely to experience the most significant transformations and highlighting stories of AI complementing human skills. We'll also address the need for upskilling and reskilling initiatives to prepare the workforce for an AI-enhanced job market, illustrating how businesses can leverage AI to foster a collaborative human-machine environment that maximizes efficiency and creativity.\n\n5. **AI-Driven Startups: Innovators Pushing the Boundaries of Technology**\n - AI-driven startups are at the forefront of technological innovation, disrupting traditional industries and creating unprecedented solutions to complex problems. This article will spotlight some of the most dynamic AI startups, exploring their groundbreaking projects and the unique challenges they face. From AI in local agriculture optimizing crop yields to fintech startups using machine learning to revolutionize fraud detection, these companies are not just pushing the boundaries of what's possible but are also redefining how businesses operate. By decoding their success stories and the innovative minds behind them, we provide a glimpse into the future shaped by these AI pioneers and the limitless possibilities they unveil."
== "1. **The Future of AI Agents: From Healthcare to Education** \nArtificial Intelligence agents are not just a futuristic concept; they are rapidly becoming integral to diverse fields including healthcare and education. Imagine an AI agent capable of diagnosing diseases with pinpoint accuracy or predicting student burnout before it occurs. With continual advancements, AI agents can offer personalized treatments, manage chronic conditions, and optimize educational curriculums to cater to individual learning styles. This dynamic shift could lead to more efficient, effective, and personalized approaches in both sectors, making lives better and educational experiences richer. The future promises an exciting horizon where AI agents revolutionize how we live, learn, and heal.\n\n2. **Blockchain Beyond Bitcoin: How Decentralized Technology is Reshaping Industries** \nWhen most people hear \"blockchain,\" they think of Bitcoin and other cryptocurrencies. However, blockchain technology's potential reaches far beyond digital currencies. From supply chain transparency and secure voting systems to immutable medical records and decentralized finance, blockchain is infusing trust and transparency into multiple sectors. By eliminating intermediaries and ensuring data integrity, blockchain is poised to disrupt traditional business models, offering unprecedented efficiencies and new opportunities. This revolution underscores a foundational shift in how industries operate, emphasizing decentralization and direct peer-to-peer interaction.\n\n3. **The Rise of Remote Work: Transforming Corporate Culture and Collaboration** \nThe COVID-19 pandemic has accelerated a trend that was already catching on: remote work. As companies worldwide adapt to this new norm, it's not just about working from home; it's about transforming the very essence of corporate culture and collaboration. The rise of remote work is leading to a more flexible, inclusive, and diverse work environment. Organizations are leveraging advanced collaboration tools and redefining team dynamics to maintain productivity and innovation. This paradigm shift is reshaping leadership styles, employee engagement, and organizational structure, heralding a future where remote work could become a permanent fixture in the professional landscape.\n\n4. **Sustainable Tech Innovations: Green Solutions for a Planet in Peril** \nWith climate change and environmental degradation posing serious threats, sustainable tech innovations are more crucial than ever. From renewable energy solutions like solar and wind power to energy-efficient devices and sustainable manufacturing processes, technology is paving the way for a greener future. Companies are developing smart grids, eco-friendly gadgets, and recycling technologies that minimize waste and reduce the carbon footprint. These advancements are not just good for the planet; they represent significant business opportunities and regulatory advantages. As we face the urgency of environmental challenges, sustainable tech offers a beacon of hope and a clear path forward.\n\n5. **The Ethical Dilemma of AI: Balancing Innovation with Responsibility** \nAs artificial intelligence rapidly advances, it presents an intriguing ethical dilemma: how do we balance groundbreaking innovation with responsible use? The potential for AI to enhance efficiencies, discover new insights, and create unprecedented opportunities is immense. However, concerns around privacy, biased algorithms, and autonomous decision-making necessitate robust ethical frameworks. This conversation demands a nuanced approach that involves policymakers, technologists, and ethicists working together. Addressing these ethical dilemmas is not just about averting risks but also about ensuring that AI systems are designed, deployed, and regulated in ways that foster trust and societal well-being."
)
@@ -399,7 +400,7 @@ def test_crew_with_delegating_agents():
assert (
result.raw
== "**The Transformative Power of AI Agents Across Industries**\n\nAI Agents are revolutionizing the landscape of multiple industries by bringing unprecedented advancements in automation, decision-making, and operational efficiency. These sophisticated algorithms, capable of learning from vast datasets, are optimizing supply chains, enhancing customer service through intelligent chatbots, and even enabling precision medicine by analyzing complex medical data. Their ability to process and analyze information at hyper-human speeds allows businesses to make more informed, data-driven decisions, ultimately leading to increased productivity and innovative solutions. As AI Agents continue to evolve, they promise not only to transform existing processes but also to create entirely new paradigms in how industries operate, making them indispensable tools in the digital age.\n\nIn the healthcare industry, AI Agents are revolutionizing the diagnosis and treatment of diseases. IBM Watson for Oncology, for instance, assists oncologists in making informed treatment decisions by analyzing medical literature, patient records, and clinical trials. This enables doctors to offer more precise and personalized treatment plans for cancer patients, significantly enhancing patient outcomes. Additionally, AI-powered diagnostic tools like Google DeepMind's AI system are capable of detecting eye diseases from retinal scans with unprecedented accuracy, allowing for earlier and potentially life-saving interventions.\n\nThe financial sector is experiencing a redefinition through AI Agents as well, particularly in advanced fraud detection and personalized financial services. JPMorgan Chase's AI program, COiN, efficiently reviews legal documents and extracts critical data at rates far surpassing that of human capabilities, reducing error rates and operational costs. Furthermore, robo-advisors like Betterment and Wealthfront provide personalized investment advice, managing individual portfolios via sophisticated algorithms that analyze market trends, risk tolerance, and financial goals, thereby democratizing access to high-quality financial advice.\n\nSimilarly, the retail and logistics industries are significantly benefiting from AI implementations. E-commerce giants like Amazon use AI-driven recommendation engines to personalize shopping experiences, while AI-powered chatbots in customer service handle inquiries with efficient, consistent, and instantaneous responses. In logistics, companies like DHL and FedEx use AI for route optimization, predictive maintenance, and demand forecasting, resulting in faster delivery times and reduced fuel consumption. These varied applications highlight the transformative power of AI Agents in enhancing productivity, accuracy, and innovation across industries.\n\nThrough these multifaceted applications, it becomes clear that AI Agents are not only improving operational efficiency and service delivery but also driving significant innovation and fostering new standards of excellence across industries. Their integration and evolution represent a transformative movement, poised to redefine the future landscape of numerous sectors."
== "Artificial Intelligence (AI) Agents are transformative entities designed to automate processes, make decisions, and solve problems by mimicking human intelligence. These sophisticated systems leverage machine learning, natural language processing, and data analytics to perform tasks that traditionally required human intervention. From personal assistants like Siri and Alexa to complex decision-making systems in autonomous vehicles, AI Agents are increasingly becoming integral to our daily lives, promising enhanced efficiency and productivity across numerous domains.\n\nOne of the most prominent examples of AI Agents is their application in the healthcare industry. These intelligent systems can analyze vast amounts of medical data to assist in diagnostic processes, personalize treatment plans, and even predict outbreaks of diseases. For instance, IBM's Watson for Oncology utilizes AI to provide evidence-based treatment options by analyzing large datasets of medical literature and patient records. These capabilities not only improve the accuracy of diagnoses but also significantly reduce the time it takes to develop effective treatment plans, ultimately enhancing patient outcomes.\n\nBeyond healthcare, AI Agents are making strides in industries such as finance, retail, and manufacturing. In the financial sector, AI-driven chatbots and virtual assistants help manage customer inquiries, detect fraudulent activities, and offer personalized financial advice. Retailers use AI Agents to optimize supply chain operations, manage inventory, and enhance customer experiences through personalized recommendations. Meanwhile, in manufacturing, AI-powered agents are pivotal in predictive maintenance, quality control, and optimizing production lines. These applications underscore the versatility of AI Agents in transforming business operations and driving economic growth.\n\nDespite these notable benefits, the adoption of AI Agents also presents several challenges. Concerns about data privacy and security, ethical considerations regarding decision-making processes, and the potential for job displacement are significant hurdles that need to be addressed. As AI Agents become more autonomous, ensuring transparency and accountability in their operations is critical. Looking forward, the future of AI Agents holds immense potential. Continued advancements in AI technologies, coupled with robust regulatory frameworks, can further unlock the capabilities of AI Agents, making them indispensable assets in our quest for innovation and quality of life improvements. As we navigate this evolving landscape, fostering collaboration between AI developers, policymakers, and society at large will be crucial in harnessing the transformative potential of AI Agents."
)
@@ -502,30 +503,30 @@ def test_api_calls_throttling(capsys):
return 42
agent = Agent(
role="test role",
goal="test goal",
backstory="test backstory",
max_iter=5,
role="Very helpful assistant",
goal="Comply with necessary changes",
backstory="You obey orders",
max_iter=2,
allow_delegation=False,
verbose=True,
llm="gpt-4-0125-preview",
llm="gpt-4o",
)
task = Task(
description="Don't give a Final Answer, instead keep using the `get_final_answer` tool.",
description="Don't give a Final Answer unless explicitly told it's time to give the absolute best final answer.",
expected_output="The final answer.",
tools=[get_final_answer],
agent=agent,
)
crew = Crew(agents=[agent], tasks=[task], max_rpm=2, verbose=True)
crew = Crew(agents=[agent], tasks=[task], max_rpm=1, verbose=True)
with patch("time.sleep") as mock_sleep:
mock_sleep.return_value = None
with patch.object(RPMController, "_wait_for_next_minute") as moveon:
moveon.return_value = True
crew.kickoff()
captured = capsys.readouterr()
assert "Max RPM reached, waiting for next minute to start." in captured.out
mock_sleep.assert_called_with(60) # Assert that sleep was called with 1 second
moveon.assert_called()
@pytest.mark.vcr(filter_headers=["authorization"])
@@ -608,7 +609,7 @@ def test_sequential_async_task_execution_completion():
sequential_result = sequential_crew.kickoff()
assert sequential_result.raw.startswith(
"Artificial Intelligence (AI) has journeyed through pivotal milestones that have transformed the technology landscape as we know it."
"Artificial Intelligence (AI) has a rich history marked by significant milestones that have collectively shaped its evolution and applications."
)
@@ -636,7 +637,7 @@ def test_single_task_with_async_execution():
result = crew.kickoff()
assert result.raw.startswith(
"- AI agents in personalized healthcare diagnoses and treatment"
"- AI in healthcare: revolutionizing diagnostics and personalized treatments."
)
@@ -1273,9 +1274,9 @@ def test_agent_usage_metrics_are_captured_for_hierarchical_process():
assert result.raw == "Howdy!"
assert result.token_usage == UsageMetrics(
total_tokens=2565,
prompt_tokens=2424,
completion_tokens=141,
total_tokens=2695,
prompt_tokens=2548,
completion_tokens=147,
successful_requests=5,
)
@@ -2374,7 +2375,7 @@ def test_conditional_task_last_task_when_conditional_is_true():
)
result = crew.kickoff()
assert result.raw.startswith(
"1. **The Future of AI in Healthcare: Revolutionizing Diagnosis and Treatment**"
"1. **How AI Agents are Revolutionizing Customer Service**"
)