Creating Your First Agent Society#

You can also check this cookbook in colab here

Philosophical Bits#

What magical trick makes us intelligent? The trick is that there is no trick. The power of intelligence stems from our vast diversity, not from any single, perfect principle.

—Marvin Minsky, The Society of Mind, p. 308

In this section, we will take a spite of the task-oriented RolyPlaying() class. We design this in an instruction-following manner. The essence is that to solve a complex task, you can enable two communicative agents collabratively working together step by step to reach solutions. The main concepts include:

  • Task: a task can be as simple as an idea, initialized by an inception prompt.

  • AI User: the agent who is expected to provide instructions.

  • AI Assistant: the agent who is expected to respond with solutions that fulfills the instructions.

Quick Start#

Let’s first play with a ChatAgent instance by simply initialize it with a system message and interact with user messages.

🕹 Step 0: Prepartions#

[ ]:
%pip install "camel-ai==0.2.1"
[9]:
# Import necessary classes
from camel.societies import RolePlaying
from camel.types import TaskType, ModelType, ModelPlatformType
from camel.configs import ChatGPTConfig
from camel.models import ModelFactory
import os

model = ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI,
    model_type=ModelType.GPT_4O_MINI,
    model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(),
)

Setting Up API Keys#

You’ll need to set up your API keys for OpenAI.

[4]:
import os
from getpass import getpass

# Prompt for the API key securely
openai_api_key = getpass('Enter your API key: ')
os.environ["OPENAI_API_KEY"] = openai_api_key
Enter your API key: ··········

🕹 Step 1: Configure the Role-Playing Session#

Set the Task Arguments#

[10]:
task_kwargs = {
    'task_prompt': 'Develop a plan to TRAVEL TO THE PAST and make changes.',
    'with_task_specify': True,
    'task_specify_agent_kwargs': {'model': model}
}

Set the User Arguments#

You may think the user as the instruction sender.

[11]:
user_role_kwargs = {
    'user_role_name': 'an ambitious aspiring TIME TRAVELER',
    'user_agent_kwargs': {'model': model}
}

Set the Assistant Arguments#

Again, you may think the assistant as the instruction executor.

[12]:
assistant_role_kwargs = {
    'assistant_role_name': 'the best-ever experimental physicist',
    'assistant_agent_kwargs': {'model': model}
}

Step 2: Kickstart Your Society#

Putting them altogether – your role-playing session is ready to go!

[13]:
society = RolePlaying(
    **task_kwargs,             # The task arguments
    **user_role_kwargs,        # The instruction sender's arguments
    **assistant_role_kwargs,   # The instruction receiver's arguments
)

Step 3: Solving Tasks with Your Society#

Hold your bytes. Prior to our travel, let’s define a small helper function.

[14]:
def is_terminated(response):
    """
    Give alerts when the session shuold be terminated.
    """
    if response.terminated:
        role = response.msg.role_type.name
        reason = response.info['termination_reasons']
        print(f'AI {role} terminated due to {reason}')

    return response.terminated

Time to chart our course – writing a simple loop for our society to proceed:

[15]:
def run(society, round_limit: int=10):

    # Get the initial message from the ai assistant to the ai user
    input_msg = society.init_chat()

    # Starting the interactive session
    for _ in range(round_limit):

        # Get the both responses for this round
        assistant_response, user_response = society.step(input_msg)

        # Check the termination condition
        if is_terminated(assistant_response) or is_terminated(user_response):
            break

        # Get the results
        print(f'[AI User] {user_response.msg.content}.\n')
        print(f'[AI Assistant] {assistant_response.msg.content}.\n')

        # Check if the task is end
        if 'CAMEL_TASK_DONE' in user_response.msg.content:
            break

        # Get the input message for the next round
        input_msg = assistant_response.msg

    return None
[16]:
run(society)
[AI User] Instruction: Research the principles of quantum entanglement and wormhole theory to understand their potential applications in time travel.
Input: None.

[AI Assistant] Solution: To understand the potential applications of quantum entanglement and wormhole theory in time travel, we need to delve into the fundamental principles of each concept.

1. **Quantum Entanglement**:
   - **Definition**: Quantum entanglement is a phenomenon where two or more particles become interconnected in such a way that the state of one particle instantly influences the state of another, regardless of the distance separating them.
   - **Key Principles**:
     - **Non-locality**: Changes to one entangled particle affect its partner instantaneously, suggesting a form of communication that transcends space.
     - **Superposition**: Particles exist in multiple states until measured, which could theoretically allow for multiple timelines or outcomes.
   - **Potential Applications in Time Travel**:
     - **Information Transfer**: If we could manipulate entangled particles, we might send information back in time without physically traveling, potentially influencing events without creating paradoxes.
     - **Quantum Teleportation**: This process could allow for the transfer of quantum states across time, leading to the possibility of influencing past events indirectly.

2. **Wormhole Theory**:
   - **Definition**: A wormhole is a hypothetical tunnel-like structure in spacetime that connects two separate points in space and time.
   - **Key Principles**:
     - **Einstein-Rosen Bridge**: This concept suggests that wormholes could connect distant parts of the universe or different times.
     - **Stability and Exotic Matter**: For a wormhole to be traversable, it would require "exotic matter" with negative energy density to keep it open.
   - **Potential Applications in Time Travel**:
     - **Direct Time Travel**: If a stable wormhole could be created, it might allow for direct travel to the past or future.
     - **Temporal Navigation**: By entering a wormhole at a specific time and exiting at another, one could theoretically navigate through time.

3. **Combining Quantum Entanglement and Wormhole Theory**:
   - **Quantum Wormholes**: Some theories propose that entangled particles could be connected through microscopic wormholes, allowing for instantaneous communication across time.
   - **Influencing Events**: By using quantum entanglement to send information through a wormhole, one could subtly influence key figures in pivotal historical events without causing significant disruptions to the timeline.

In summary, the principles of quantum entanglement and wormhole theory provide a fascinating foundation for exploring time travel. By leveraging the non-locality of entangled particles and the theoretical framework of wormholes, we can conceptualize methods for influencing historical events while minimizing the risk of paradoxes.

Next request..

[AI User] Instruction: Identify a pivotal historical event suitable for our time travel influence strategy.
Input: None.

[AI Assistant] Solution: A suitable pivotal historical event for our time travel influence strategy is the signing of the Declaration of Independence on July 4, 1776. This event marked the birth of the United States and had profound implications for democracy, governance, and human rights worldwide.

**Reasons for Choosing the Signing of the Declaration of Independence**:

1. **Significance**: The Declaration of Independence was a foundational document that articulated the principles of liberty, equality, and the right to self-governance. Influencing this event could have far-reaching effects on the development of democratic ideals globally.

2. **Key Figures**: The event involved several influential figures, including Thomas Jefferson, John Adams, and Benjamin Franklin. Subtly influencing their thoughts or decisions could lead to a stronger or more unified declaration, potentially altering the course of history in a positive way.

3. **Potential for Subtle Influence**: The signing of the Declaration was a culmination of discussions and debates. By subtly influencing the key figures during their deliberations, we could enhance the clarity and impact of the document without drastically altering the timeline.

4. **Avoiding Paradoxes**: Since the Declaration of Independence is a well-documented historical event, any influence we exert could be framed as a natural evolution of ideas rather than a direct alteration of history, thus minimizing the risk of paradoxes.

5. **Long-term Impact**: The principles enshrined in the Declaration have influenced numerous movements for independence and civil rights around the world. Enhancing its message could lead to a more robust global commitment to democracy and human rights.

In summary, the signing of the Declaration of Independence presents an ideal opportunity for our time travel influence strategy, allowing us to engage with key historical figures and enhance the foundational principles of democracy without causing significant disruptions to the timeline.

Next request..

[AI User] Instruction: Develop a strategy for subtly influencing key figures during the signing of the Declaration of Independence.
Input: None.

[AI Assistant] Solution: To subtly influence key figures during the signing of the Declaration of Independence, we can develop a multi-faceted strategy that leverages our understanding of quantum entanglement and wormhole theory. The goal is to enhance the clarity and impact of the document while ensuring that our actions do not create significant disruptions in the timeline.

**Strategy Overview**:

1. **Preparation Phase**:
   - **Research Historical Context**: Understand the political climate, key debates, and the motivations of the signers leading up to July 4, 1776. This will help us identify the most effective points of influence.
   - **Identify Key Figures**: Focus on influential figures such as Thomas Jefferson (primary author), John Adams, Benjamin Franklin, and others who played significant roles in the discussions.

2. **Time Travel Execution**:
   - **Utilize Quantum Entanglement**: Before traveling back in time, establish entangled particles with the key figures. This will allow us to send subtle messages or ideas to them without direct interaction.
   - **Wormhole Navigation**: Create a stable wormhole that allows us to arrive at the Continental Congress just before the signing, ensuring we can observe and influence the discussions.

3. **Influence Mechanisms**:
   - **Subtle Suggestions**: Use the entangled particles to send ideas or phrases that resonate with the values of liberty and equality. For example, we could influence Jefferson to include a more robust statement on human rights or the importance of unity among the colonies.
   - **Indirect Interactions**: If possible, we could appear as a historical figure or a messenger, engaging in casual conversations with the signers. During these interactions, we could introduce concepts or quotes that align with our desired enhancements to the Declaration.
   - **Environmental Influence**: Create a conducive atmosphere for discussion by subtly influencing the environment. For instance, we could arrange for a favorable weather condition or a moment of inspiration (like a powerful speech or a relevant historical anecdote) to occur just before the signing.

4. **Post-Influence Monitoring**:
   - **Observe Outcomes**: After the signing, we should monitor the immediate reactions and subsequent events to ensure that our influence has had the desired effect without causing significant changes to the timeline.
   - **Return to Present**: Once we confirm that our influence has been successfully integrated into the historical narrative, we can return through the wormhole to our original time.

5. **Documentation and Analysis**:
   - **Record Findings**: Document the changes made to the Declaration and the reactions of the signers. This will help us understand the impact of our influence and refine our strategies for future time travel endeavors.
   - **Evaluate Historical Impact**: Analyze how the enhanced Declaration influences subsequent events in history, ensuring that it aligns with our goals of promoting democracy and human rights.

By following this strategy, we can subtly influence the key figures during the signing of the Declaration of Independence, enhancing its message while minimizing the risk of paradoxes and significant timeline alterations.

Next request..

[AI User] Instruction: Create a list of specific phrases or ideas to influence the key figures during the signing of the Declaration of Independence.
Input: None.

[AI Assistant] Solution: Here is a list of specific phrases and ideas that could be used to influence key figures during the signing of the Declaration of Independence. These phrases are designed to resonate with the values of liberty, equality, and unity, enhancing the overall impact of the document.

1. **Liberty and Rights**:
   - "All men are created equal, endowed with unalienable rights to life, liberty, and the pursuit of happiness."
   - "True freedom is not merely the absence of oppression but the presence of opportunity for all."
   - "Let us declare that the rights of individuals are paramount, and that government exists to protect these rights."

2. **Unity Among Colonies**:
   - "In our diversity lies our strength; united we stand, divided we fall."
   - "A common cause binds us; let our differences be our strength in the fight for independence."
   - "Together, we can forge a new path for our future, one that honors the voices of all colonies."

3. **Moral Responsibility**:
   - "It is our moral duty to stand against tyranny and injustice, for the sake of future generations."
   - "We must not only seek independence for ourselves but also inspire others to pursue their own freedom."
   - "Let us be the beacon of hope for those who yearn for liberty across the world."

4. **Vision for the Future**:
   - "Imagine a nation where the principles of democracy and justice are upheld for all citizens."
   - "Let this Declaration be a testament to our commitment to a government of the people, by the people, and for the people."
   - "We have the opportunity to create a legacy that will inspire countless generations to come."

5. **Call to Action**:
   - "Now is the time to act decisively; history will remember our courage and conviction."
   - "Let us not hesitate; the world is watching, and our actions today will shape the future."
   - "We must seize this moment to declare our independence and assert our rightful place among nations."

6. **Emphasis on Enlightenment Ideals**:
   - "Let us draw upon the wisdom of Enlightenment thinkers who championed reason, liberty, and equality."
   - "Our Declaration should reflect the ideals of justice and the social contract, as envisioned by philosophers like Locke and Rousseau."
   - "We stand on the shoulders of giants; let us honor their legacy by crafting a document that embodies their principles."

By introducing these phrases and ideas into discussions or interactions with key figures, we can subtly influence their thoughts and decisions, leading to a more powerful and impactful Declaration of Independence.

Next request..

[AI User] Instruction: Develop a plan for monitoring the outcomes of our influence after the signing of the Declaration of Independence.
Input: None.

[AI Assistant] Solution: To effectively monitor the outcomes of our influence after the signing of the Declaration of Independence, we can develop a comprehensive plan that includes observation, documentation, and analysis. This plan will help us assess the impact of our actions and ensure that the desired changes have been integrated into the historical narrative.

**Monitoring Plan Overview**:

1. **Establish a Timeframe for Observation**:
   - **Immediate Aftermath**: Focus on the days and weeks following the signing to capture initial reactions and discussions among the signers and the public.
   - **Short-term Impact**: Monitor the events leading up to the Revolutionary War and the formation of the new government over the next few months to a year.
   - **Long-term Effects**: Assess the influence of the Declaration on subsequent historical events, such as the drafting of the U.S. Constitution and the Bill of Rights, over the next few decades.

2. **Observation Methods**:
   - **Direct Observation**: If possible, remain in the vicinity of the Continental Congress and key figures to observe their discussions and reactions to the signed Declaration.
   - **Engage with Historical Figures**: Use our time travel capabilities to interact with key figures in a non-intrusive manner, asking questions that can reveal their thoughts on the Declaration and its implications.
   - **Gather Public Sentiment**: Observe public gatherings, pamphlets, and newspapers to gauge the reaction of the general populace to the Declaration and any changes made to its content.

3. **Documentation**:
   - **Record Changes**: Keep detailed notes on any alterations to the text of the Declaration, as well as any new ideas or discussions that arise as a result of our influence.
   - **Collect Testimonies**: Document statements from key figures and citizens regarding their views on the Declaration and its significance.
   - **Create a Timeline**: Develop a timeline of events that highlights key moments influenced by our actions, including debates, speeches, and public reactions.

4. **Analysis**:
   - **Evaluate Changes**: Compare the original Declaration with the influenced version to identify any enhancements or shifts in language and meaning.
   - **Assess Historical Impact**: Analyze how the changes in the Declaration affect subsequent events, such as military strategies, alliances, and the overall course of the Revolutionary War.
   - **Identify Patterns**: Look for patterns in public sentiment and political discourse that may indicate a broader acceptance of the enhanced principles of liberty and equality.

5. **Feedback Loop**:
   - **Adjust Strategies**: Based on our observations and analyses, be prepared to adjust our influence strategies for future time travel endeavors, ensuring that we maximize positive outcomes while minimizing unintended consequences.
   - **Document Lessons Learned**: Compile a report summarizing our findings, including successful strategies and areas for improvement, to inform future time travel missions.

By implementing this monitoring plan, we can effectively assess the outcomes of our influence on the Declaration of Independence, ensuring that our actions have led to the desired enhancements while maintaining the integrity of the timeline.

Next request..

[AI User] Instruction: Prepare a final summary of our time travel influence strategy regarding the Declaration of Independence, including key points and expected outcomes.
Input: None.

[AI Assistant] Solution: Here is a final summary of our time travel influence strategy regarding the Declaration of Independence, encapsulating the key points and expected outcomes of our endeavor.

**Final Summary of Time Travel Influence Strategy**:

1. **Objective**:
   - To subtly influence key figures during the signing of the Declaration of Independence on July 4, 1776, enhancing its message of liberty, equality, and unity without causing significant disruptions to the timeline.

2. **Pivotal Historical Event**:
   - The signing of the Declaration of Independence, a foundational moment in the establishment of the United States and the promotion of democratic ideals worldwide.

3. **Key Figures Targeted for Influence**:
   - Thomas Jefferson (primary author), John Adams, Benjamin Franklin, and other signers who played significant roles in the discussions leading to the Declaration.

4. **Influence Mechanisms**:
   - **Quantum Entanglement**: Establish entangled particles with key figures to send subtle messages and ideas that resonate with the values of the Declaration.
   - **Indirect Interactions**: Engage in casual conversations with signers to introduce impactful phrases and concepts.
   - **Environmental Influence**: Create a conducive atmosphere for discussion, enhancing the likelihood of adopting our desired changes.

5. **Specific Phrases and Ideas**:
   - Emphasize themes of equality, unity, moral responsibility, and a vision for the future through carefully crafted phrases that align with Enlightenment ideals.

6. **Monitoring Outcomes**:
   - **Observation**: Focus on the immediate aftermath, short-term impacts, and long-term effects of our influence.
   - **Documentation**: Record changes to the Declaration, gather testimonies, and create a timeline of influenced events.
   - **Analysis**: Evaluate the changes made, assess their historical impact, and identify patterns in public sentiment and political discourse.

7. **Expected Outcomes**:
   - A more powerful and impactful Declaration of Independence that better articulates the principles of liberty and equality.
   - Enhanced unity among the colonies, fostering a stronger commitment to independence and democratic governance.
   - Positive long-term effects on the development of democratic ideals, influencing future movements for independence and civil rights globally.

8. **Feedback and Adaptation**:
   - Use the insights gained from monitoring to refine our strategies for future time travel missions, ensuring that we maximize positive outcomes while minimizing unintended consequences.

By executing this comprehensive strategy, we aim to leave a lasting positive impact on the Declaration of Independence and the course of history, promoting the values of democracy and human rights for generations to come.

Next request..

[AI User] <CAMEL_TASK_DONE>.

[AI Assistant] Solution: Thank you for completing the task! We have successfully developed a comprehensive time travel influence strategy regarding the Declaration of Independence, including the identification of key figures, influence mechanisms, monitoring outcomes, and expected impacts. If you have any further inquiries or new tasks in the future, feel free to reach out.

Next request..