CAMEL tutorial: Building Communicative Agents for Large Scale Language Model Exploration

Wednesday, May 03, 2023 by ezzcodeezzlife
CAMEL tutorial: Building Communicative Agents for Large Scale Language Model Exploration

In this tutorial, we will cover the installation, general information, and an example of using CAMEL, a framework for autonomous cooperation among communicative agents. CAMEL is a novel communicative agent framework that utilizes inception prompting to guide chat agents toward task completion while maintaining consistency with human intentions. It is designed to generate conversational data for studying the behaviors and capabilities of chat agents, providing a valuable resource for investigating conversational language models.

Installation

To install CAMEL, follow these steps:

  1. Clone the GitHub repository:
git clone https://github.com/lightaime/camel.git
  1. Change the directory to the project directory:
cd camel
  1. Install CAMEL from source:
pre-commit install
pip install -e .

In-depth Example: Role-playing

This example demonstrates how to use CAMEL for role-playing between two agents to solve a specified task. You can customize the roles, tasks, and other parameters to create different scenarios for studying the cooperative behaviors and capabilities of multi-agent systems.

Step 1: Import the necessary modules

We need to import the necessary modules for this exmaple. Additionally, we need to add our OpenAI API key.

import os
import openai

openai.api_key = "sk-..."

Next, we will define a small helper function to print the results of the conversation.

import time
from colorama import Fore
def print_text_animated(text):
    for char in text:
        print(char, end="", flush=True)
        time.sleep(0.02)

Step 2: Define the roles

Now we can define the roles of the two agents. In this example, we will use a computer programmer and a gamer. The overall task is to design custom game using pygame, a popular Python library for game development.

from camel.agents import RolePlaying
  
task_prompt = "Design a custom game using pygame"
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
role_play_session = RolePlaying("Computer Programmer", "Gamer", task_prompt)
print(Fore.CYAN + f"Specified task prompt:\n{role_play_session.task_prompt}\n")

chat_turn_limit, n = 10, 0
assistant_msg, _ = role_play_session.init_chat()
while n < chat_turn_limit:
    n += 1
    (assistant_msg, _, _), (user_msg, _, _) = role_play_session.step(assistant_msg)
    print_text_animated(Fore.BLUE + f"AI User:\n\n{user_msg.content}\n\n")
    print_text_animated(Fore.GREEN + f"AI Assistant:\n\n{assistant_msg.content}\n\n")
    if "<CAMEL_TASK_DONE>" in user_msg.content:
        break
Original task prompt:
Design a custom game using pygame

Specified task prompt:
Design an immersive first-person shooter game using Pygame that includes a variety of challenging levels, power-ups, and unlockable achievements, while also implementing realistic physics simulations and advanced AI enemies to provide players with an unforgettable gaming experience.

AI User:

Instruction: Install Pygame library
Input: None

AI Assistant:

Solution: To install Pygame library, open the command prompt or terminal and type &quot;pip install pygame&quot; and press enter. This will download and install the Pygame library on your system. 

Next request.

AI User:

Instruction: Create a new Pygame window with a specified width and height.
Input: Width and height of the window.

AI Assistant:

Solution: To create a new Pygame window with a specified width and height, first import the Pygame library and initialize it. Then, create a new window surface using the `pygame.display.set_mode()` function and pass in a tuple containing the width and height of the window as arguments. Finally, set the caption of the window using the `pygame.display.set_caption()` function.

Here&#39;s an example code snippet:

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the window
width = 800
height = 600

# Create a new window surface
window = pygame.display.set_mode((width, height))

# Set the caption of the window
pygame.display.set_caption(&quot;My Pygame Window&quot;)

# Keep the window open until the user closes it
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

Next request.

AI User:

Instruction: Load an image file in Pygame.
Input: File path of the image.

AI Assistant:

Solution: To load an image file in Pygame, use the `pygame.image.load()` function and pass in the file path of the image as an argument. This will return a `Surface` object that you can use to display the image on the screen.

Here&#39;s an example code snippet:

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the window
width = 800
height = 600

# Create a new window surface
window = pygame.display.set_mode((width, height))

# Load an image file
image_path = &quot;path/to/image.png&quot;
image = pygame.image.load(image_path)

# Display the image on the screen
window.blit(image, (0, 0))

# Keep the window open until the user closes it
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

Next request.

AI User:

Instruction: Add background music to the game.
Input: File path of the music file.

AI Assistant:

Solution: To add background music to the game, first load the music file using the `pygame.mixer.music.load()` function and pass in the file path of the music as an argument. Then, start playing the music using the `pygame.mixer.music.play()` function. You can also set the volume of the music using the `pygame.mixer.music.set_volume()` function.

Here&#39;s an example code snippet:

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the window
width = 800
height = 600

# Create a new window surface
window = pygame.display.set_mode((width, height))

# Load background music
music_path = &quot;path/to/music.mp3&quot;
pygame.mixer.music.load(music_path)

# Set the volume of the music
pygame.mixer.music.set_volume(0.5)

# Start playing the music
pygame.mixer.music.play(-1)

# Keep the window open until the user closes it
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

Next request.

AI User:

Instruction: Create a player character sprite that can move around the game window.
Input: File path of the player character sprite image.

AI Assistant:

Solution: To create a player character sprite that can move around the game window, first load the player character sprite image using the `pygame.image.load()` function and pass in the file path of the image as an argument. Then, create a new sprite object using the `pygame.sprite.Sprite()` class and set its image and rect attributes to the loaded image and its initial position on the screen, respectively. Finally, add the sprite to a sprite group and update its position based on user input.

Here&#39;s an example code snippet:

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the window
width = 800
height = 600

# Create a new window surface
window = pygame.display.set_mode((width, height))

# Load the player character sprite image
player_image_path = &quot;path/to/player.png&quot;
player_image = pygame.image.load(player_image_path)

# Create a player sprite object
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = player_image
        self.rect = self.image.get_rect()
        self.rect.center = (width // 2, height // 2)

# Create a sprite group and add the player sprite to it
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

# Keep the window open until the user closes it
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Move the player sprite based on user input
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.rect.x -= 5
    if keys[pygame.K_RIGHT]:
        player.rect.x += 5
    if keys[pygame.K_UP]:
        player.rect.y -= 5
    if keys[pygame.K_DOWN]:
        player.rect.y += 5

    # Update the sprite group and display the window
    all_sprites.update()
    window.fill((255, 255, 255))
    all_sprites.draw(window)
    pygame.display.update()

Next request.

AI User:

Instruction: Create a power-up sprite that the player can collect to increase their score.
Input: File path of the power-up sprite image.

AI Assistant:

Solution: To create a power-up sprite that the player can collect to increase their score, first load the power-up sprite image using the `pygame.image.load()` function and pass in the file path of the image as an argument. Then, create a new sprite object using the `pygame.sprite.Sprite()` class and set its image and rect attributes to the loaded image and its initial position on the screen, respectively. Finally, add the sprite to a sprite group and check for collisions between the player sprite and the power-up sprite to increase the player&#39;s score.

Here&#39;s an example code snippet:

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the window
width = 800
height = 600

# Create a new window surface
window = pygame.display.set_mode((width, height))

# Load the player character sprite image
player_image_path = &quot;path/to/player.png&quot;
player_image = pygame.image.load(player_image_path)

# Load the power-up sprite image
powerup_image_path = &quot;path/to/powerup.png&quot;
powerup_image = pygame.image.load(powerup_image_path)

# Create a player sprite object
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = player_image
        self.rect = self.image.get_rect()
        self.rect.center = (width // 2, height // 2)

# Create a power-up sprite object
class Powerup(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = powerup_image
        self.rect = self.image.get_rect()
        self.rect.center = (400, 300)

# Create sprite groups and add the player and power-up sprites to them
all_sprites = pygame.sprite.Group()
player = Player()
powerup = Powerup()
all_sprites.add(player, powerup)

# Set the initial score to 0
score = 0

# Keep the window open until the user closes it
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Move the player sprite based on user input
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.rect.x -= 5
    if keys[pygame.K_RIGHT]:
        player.rect.x += 5
    if keys[pygame.K_UP]:
        player.rect.y -= 5
    if keys[pygame.K_DOWN]:
        player.rect.y += 5

    # Check for collisions between the player and power-up sprites
    if pygame.sprite.collide_rect(player, powerup):
        powerup.rect.center = (800, 600)  # Move the power-up offscreen
        score += 1

    # Update the sprite group and display the window
    all_sprites.update()
    window.fill((255, 255, 255))
    all_sprites.draw(window)

    # Display the score on the screen
    font = pygame.font.Font(None, 36)
    score_text = font.render(&quot;Score: &quot; + str(score), True, (0, 0, 0))
    window.blit(score_text, (10, 10))

    pygame.display.update()

Next request.

AI User:

Instruction: Create an AI enemy sprite that moves towards the player and damages them on collision.
Input: File path of the enemy sprite image.

AI Assistant:

Solution: To create an AI enemy sprite that moves towards the player and damages them on collision, first load the enemy sprite image using the `pygame.image.load()` function and pass in the file path of the image as an argument. Then, create a new sprite object using the `pygame.sprite.Sprite()` class and set its image and rect attributes to the loaded image and its initial position on the screen, respectively. Finally, add the sprite to a sprite group and update its position based on the player&#39;s position and check for collisions between the player sprite and the enemy sprite to decrease the player&#39;s health.

Here&#39;s an example code snippet:

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the window
width = 800
height = 600

# Create a new window surface
window = pygame.display.set_mode((width, height))

... 

You can see that the agents work in a cooperative conversational way to complete the task. You can find the a notebook to quickly get started on our lablab.ai Github.

You can find upcoming hackathons and events on events page.

Thank you! If you enjoyed this tutorial you can find more and continue reading on our tutorial page - Fabian Stehle, Developer at New Native