mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-08 15:48:29 +00:00
Adding proper support to memory-less agents
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"""Generic agent."""
|
||||
|
||||
from typing import List, Any, Optional
|
||||
from pydantic.v1 import BaseModel, Field, root_validator
|
||||
from pydantic.v1 import BaseModel, PrivateAttr, Field, root_validator
|
||||
|
||||
from langchain.agents import AgentExecutor
|
||||
from langchain.chat_models import ChatOpenAI as OpenAI
|
||||
@@ -35,6 +35,7 @@ class Agent(BaseModel):
|
||||
description="Tools at agents disposal",
|
||||
default=[]
|
||||
)
|
||||
_task_calls: List[Any] = PrivateAttr()
|
||||
|
||||
@root_validator(pre=True)
|
||||
def check_llm(_cls, values):
|
||||
@@ -47,39 +48,42 @@ class Agent(BaseModel):
|
||||
|
||||
def __init__(self, **data):
|
||||
super().__init__(**data)
|
||||
execution_prompt = Prompts.TASK_EXECUTION_PROMPT.partial(
|
||||
goal=self.goal,
|
||||
role=self.role,
|
||||
backstory=self.backstory,
|
||||
)
|
||||
|
||||
llm_with_bind = self.llm.bind(stop=["\nObservation"])
|
||||
inner_agent = {
|
||||
agent_args = {
|
||||
"input": lambda x: x["input"],
|
||||
"tools": lambda x: x["tools"],
|
||||
"tool_names": lambda x: x["tool_names"],
|
||||
"chat_history": lambda x: x["chat_history"],
|
||||
"agent_scratchpad": lambda x: format_log_to_str(x['intermediate_steps']),
|
||||
} | execution_prompt | llm_with_bind | ReActSingleInputOutputParser()
|
||||
|
||||
summary_memory = ConversationSummaryMemory(
|
||||
llm=self.llm,
|
||||
memory_key='chat_history',
|
||||
input_key="input"
|
||||
)
|
||||
|
||||
args = {
|
||||
}
|
||||
executor_args = {
|
||||
"tools": self.tools,
|
||||
"verbose": self.verbose,
|
||||
"handle_parsing_errors": True,
|
||||
}
|
||||
|
||||
llm_with_bind = self.llm.bind(stop=["\nObservation"])
|
||||
|
||||
if self.memory:
|
||||
args['memory'] = summary_memory
|
||||
summary_memory = ConversationSummaryMemory(
|
||||
llm=self.llm,
|
||||
memory_key='chat_history',
|
||||
input_key="input"
|
||||
)
|
||||
executor_args['memory'] = summary_memory
|
||||
agent_args['chat_history'] = lambda x: x["chat_history"]
|
||||
prompt = Prompts.TASK_EXECUTION_WITH_MEMORY_PROMPT
|
||||
else:
|
||||
prompt = Prompts.TASK_EXECUTION_PROMPT
|
||||
|
||||
execution_prompt = prompt.partial(
|
||||
goal=self.goal,
|
||||
role=self.role,
|
||||
backstory=self.backstory,
|
||||
)
|
||||
inner_agent = agent_args | execution_prompt | llm_with_bind | ReActSingleInputOutputParser()
|
||||
|
||||
self.agent_executor = AgentExecutor(
|
||||
agent=inner_agent,
|
||||
**args
|
||||
**executor_args
|
||||
)
|
||||
|
||||
def execute_task(self, task: str, context: str = None, tools: List[Any] = None) -> str:
|
||||
|
||||
@@ -62,9 +62,13 @@ class Prompts(BaseModel):
|
||||
{coworkers}
|
||||
""")
|
||||
|
||||
TASK_EXECUTION_PROMPT: ClassVar[str] = PromptTemplate.from_template(
|
||||
TASK_EXECUTION_WITH_MEMORY_PROMPT: ClassVar[str] = PromptTemplate.from_template(
|
||||
ROLE_PLAYING_SLICE + TOOLS_SLICE + MEMORY_SLICE + TASK_SLICE
|
||||
)
|
||||
|
||||
TASK_EXECUTION_PROMPT: ClassVar[str] = PromptTemplate.from_template(
|
||||
ROLE_PLAYING_SLICE + TOOLS_SLICE + TASK_SLICE
|
||||
)
|
||||
|
||||
CONSENSUNS_VOTING_PROMPT: ClassVar[str] = PromptTemplate.from_template(
|
||||
ROLE_PLAYING_SLICE + VOTING_SLICE + TASK_SLICE
|
||||
|
||||
@@ -68,6 +68,10 @@ def test_agent_without_memory():
|
||||
model="gpt-4"
|
||||
)
|
||||
)
|
||||
|
||||
result = no_memory_agent.execute_task("How much is 1 + 1?")
|
||||
|
||||
assert result == "2"
|
||||
assert no_memory_agent.agent_executor.memory is None
|
||||
assert memory_agent.agent_executor.memory is not None
|
||||
|
||||
@@ -81,7 +85,7 @@ def test_agent_execution():
|
||||
)
|
||||
|
||||
output = agent.execute_task("How much is 1 + 1?")
|
||||
assert output == "1 + 1 = 2"
|
||||
assert output == "1 + 1 equals 2."
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_agent_execution_with_tools():
|
||||
@@ -105,7 +109,7 @@ def test_agent_execution_with_tools():
|
||||
)
|
||||
|
||||
output = agent.execute_task("What is 3 times 4")
|
||||
assert output == "3 times 4 is 12"
|
||||
assert output == "3 times 4 equals to 12."
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_agent_execution_with_specific_tools():
|
||||
@@ -131,4 +135,4 @@ def test_agent_execution_with_specific_tools():
|
||||
task="What is 3 times 4",
|
||||
tools=[multiplier]
|
||||
)
|
||||
assert output == "12"
|
||||
assert output == "3 times 4 is 12."
|
||||
@@ -19,7 +19,7 @@ def test_delegate_work():
|
||||
command="researcher|share your take on AI Agents|I heard you hate them"
|
||||
)
|
||||
|
||||
assert result == "As a technology researcher, it's important to maintain objectivity. AI agents have their own merits and demerits. On the positive side, they can automate routine tasks, improve efficiency, and enable new forms of communication and decision-making. However, there are potential downsides, like job displacement due to automation and concerns about privacy and security. It's not accurate to say that I hate them, but rather, I recognize the potential implications - both positive and negative - of their use."
|
||||
assert result == "It seems there is a misunderstanding. As a researcher, my stance on AI agents is not based on personal emotions like love or hate. I study and analyze them objectively based on their capabilities, how they function, their limitations, and their potential for future development. AI agents are powerful tools that, when developed and used properly, can greatly benefit society in numerous ways such as improving efficiency, optimizing processes, and opening up new possibilities for innovation. However, like any other technology, it's also important to consider ethical implications and possible risks."
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_ask_question():
|
||||
@@ -27,7 +27,7 @@ def test_ask_question():
|
||||
command="researcher|do you hate AI Agents?|I heard you LOVE them"
|
||||
)
|
||||
|
||||
assert result == "As a researcher, my feelings towards AI Agents are neutral. I neither love nor hate them. I study and analyze them objectively to understand their potential, capabilities, and limitations. While I appreciate the technological advancement they represent, my job is to approach them from an analytical and scientific perspective."
|
||||
assert result == "As an AI, I don't have personal emotions, so I don't hate or love anything. However, I can analyze and provide insights about AI agents based on the data and information available. AI agents are a fascinating area of study in the field of technology, offering potential for significant advancements in various sectors. It's important to note that while they can be highly beneficial, they should be developed and used responsibly, considering ethical implications and potential risks."
|
||||
|
||||
def test_delegate_work_with_wrong_input():
|
||||
result = tools.ask_question(
|
||||
|
||||
@@ -108,15 +108,20 @@ def test_crew_creation():
|
||||
tasks=tasks,
|
||||
)
|
||||
|
||||
assert crew.kickoff() == """1. AI and Ethics: In a world that is increasingly being dominated by Artificial Intelligence, the question of ethics is ever more important. This article will delve into the complex intersection of AI and ethics, exploring how the decisions made by AI can impact society. From privacy concerns to the accountability of AI decisions, this piece will provide readers with a comprehensive understanding of the ethical dilemmas posed by AI.
|
||||
assert crew.kickoff() == """1. AI and Ethical Dilemmas:
|
||||
Facing the future, we grapple with moral quandaries brought forth by AI. This article will delve into the ethical dilemmas posed by AI, such as data privacy, algorithmic bias, and the responsibility of AI’s decisions. It will provide a compelling narrative about the necessity of considering ethical aspects in AI development and how they might shape the future of humanity.
|
||||
|
||||
2. The Role of AI in Climate Change: Climate change is the defining issue of our time. This article will examine how AI is playing a pivotal role in combating this global challenge. From predicting climate patterns to optimizing renewable energy use, the piece will highlight how AI is not just a part of the problem, but also a crucial part of the solution.
|
||||
2. AI in Healthcare:
|
||||
Imagine a world where diagnosis and treatment are not limited by human errors or geographical boundaries. This article will explore the transformative role of AI in healthcare, from robotic surgeries to personalized medicine. It will offer fascinating insights into how AI can revolutionize healthcare, save countless lives, and bring about a new era of medical science.
|
||||
|
||||
3. AI in Healthcare: The fusion of AI and healthcare holds a transformative potential. This article will explore how AI is revolutionizing healthcare, from improving diagnosis and treatment to enhancing patient care and hospital management. It will show how AI is not just improving healthcare outcomes but also driving a more efficient and patient-centered healthcare system.
|
||||
3. The Role of AI in Climate Change:
|
||||
As our planet faces an unprecedented climate crisis, we turn to AI for solutions. This article will illuminate the role of AI in combating climate change by optimizing renewable energy, predicting weather patterns, and managing resources. It will underscore the pivotal role that AI plays in our fight against climate change, painting a hopeful picture of the future.
|
||||
|
||||
4. The Future of AI and Work: The rise of AI has sparked a lively debate on its impact on jobs and the future of work. This article will explore this topic in-depth, examining both the potential job losses and the new opportunities created by AI. It will provide a balanced and insightful analysis of how AI is reshaping the world of work.
|
||||
4. AI in Art and Creativity:
|
||||
Art and AI may seem like odd companions, but they are pushing the boundaries of creativity. This article will highlight the influence of AI in art and creativity, from creating original art pieces to enhancing human creativity. It will delve into the intriguing intersection of technology and art, showcasing the unexpected harmony between AI and human creativity.
|
||||
|
||||
5. AI in Space Exploration: The final frontier is not beyond the reach of AI. This article will spotlight the role of AI in space exploration, from analyzing vast amounts of astronomical data to autonomous spacecraft navigating the vast expanse of space. The piece will highlight how AI is not just aiding but also accelerating our quest to explore the universe."""
|
||||
5. The Future of Jobs with AI:
|
||||
With the advent of AI, the job market is poised for a seismic shift. This article will delve into the implications of AI on the future of jobs, discussing the jobs AI will create and those it may render obsolete. It will provide a thought-provoking examination of how AI could redefine our workplaces and our understanding of work itself."""
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_crew_with_delegating_agents():
|
||||
@@ -133,7 +138,7 @@ def test_crew_with_delegating_agents():
|
||||
tasks=tasks,
|
||||
)
|
||||
|
||||
assert crew.kickoff() == 'The Senior Writer produced an amazing paragraph about AI Agents: "Artificial Intelligence (AI) agents, the cutting-edge technology that is reshaping the digital landscape, are software entities that autonomously perform tasks to achieve specific goals. These agents, programmed to make decisions based on their environment, are the driving force behind a multitude of innovations, from self-driving cars to personalized recommendations in e-commerce. They are pushing boundaries in various sectors, mitigating human error, increasing efficiency, and revolutionizing customer experience. The importance of AI agents is underscored by their ability to adapt and learn, ushering in a new era of technology where machines can mimic, and often surpass, human intelligence. Understanding AI agents is akin to peering into the future, a future where technology is seamless, intuitive, and astoundingly smart."'
|
||||
assert crew.kickoff() == 'AI agents represent a significant stride in the evolution of artificial intelligence. These entities are designed to act autonomously, learn from their environment, and make decisions based on a set of predefined rules or through machine learning techniques. The potential of AI agents is tremendous and their versatility is unparalleled. They can be deployed in various sectors, from healthcare to finance, performing tasks with efficiency and accuracy that surpass human capabilities. In healthcare, AI agents can predict patient deterioration, offer personalized treatment suggestions, and manage patient flow. In finance, they can detect fraudulent transactions, manage investments, and provide personalized financial advice. Furthermore, the adaptability of AI agents allows them to learn and improve over time, becoming more proficient and effective in their tasks. This dynamic nature of AI agents is what sets them apart and posits them as a revolutionary force in the AI landscape. As we continue to explore and harness the capabilities of AI agents, we can expect them to play an increasingly integral role in shaping our world and the way we live.'
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_crew_verbose_output(capsys):
|
||||
|
||||
Reference in New Issue
Block a user