### ManualAction Example Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/actions.mdx An example demonstrating how to create and use `ManualAction` for a specific action, such as creating a post, and then passing it to `env.step`. ```python from oasis import ActionType actions = {} manual_action = ManualAction( action=ActionType.CREATE_POST, args={"content": "Hello, OASIS world!"} ) actions[env.agent_graph.get_agents(0)] = manual_action await env.step(actions) ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/camel-ai/oasis/blob/main/CONTRIBUTING.md Install the Mintlify CLI globally to build documentation locally. This is required for contributing to the project's documentation. ```bash npm install -g mintlify ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/camel-ai/oasis/blob/main/docs/development.mdx Install the Mintlify CLI globally using npm or yarn. Ensure Node.js version 19 or higher is installed. ```bash npm i -g mintlify ``` ```bash yarn global add mintlify ``` -------------------------------- ### Install OASIS from Source Source: https://github.com/camel-ai/oasis/blob/main/CONTRIBUTING.md Install the OASIS project from source using poetry. This command also creates a virtual environment if one does not exist. ```bash poetry install ``` -------------------------------- ### Run Mintlify Development Server Source: https://github.com/camel-ai/oasis/blob/main/docs/README.md Start the local development server for Mintlify. Ensure you are in the root directory of your documentation project, which contains the docs.json file. ```bash mintlify dev ``` -------------------------------- ### Clone and Install OASIS from Repository Source: https://github.com/camel-ai/oasis/blob/main/docs/quickstart.mdx Clone the OASIS repository and install it locally with its dependencies. This method is useful for development or when you need the latest code. ```bash git clone https://github.com/camel-ai/oasis.git cd oasis pip install --upgrade pip setuptools pip install -e . # This will install dependencies as specified in pyproject.toml ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/camel-ai/oasis/blob/main/docs/README.md Install the Mintlify CLI globally using npm. This tool is required for local development and previewing documentation changes. ```bash npm i -g mintlify ``` -------------------------------- ### Install OASIS Package Source: https://github.com/camel-ai/oasis/blob/main/README.md Install the OASIS package using pip. This command should be run in your terminal. ```bash pip install camel-oasis ``` -------------------------------- ### Example User Info Template and Profile Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/social_agent.mdx Illustrates how to define a TextPrompt for user information and a corresponding profile dictionary. The profile keys must match the placeholders in the TextPrompt. ```python from camel.prompts import TextPrompt seller_template = TextPrompt('Your aim is: {aim} Your task is: {task}') profile = { "aim": "Persuade people to buy `GlowPod` lamp.", "task": "Using roleplay to tell some story about the product.", } ``` -------------------------------- ### Install Neo4j Driver Source: https://github.com/camel-ai/oasis/blob/main/docs/visualization/visualization.mdx Install the neo4j Python driver, which is necessary for the Dynamic Follow Network Visualization. ```bash pip install neo4j ``` -------------------------------- ### Complete Twitter Simulation Example Source: https://github.com/camel-ai/oasis/blob/main/docs/cookbooks/twitter_report_post.mdx This comprehensive example simulates a Twitter environment where agents can create posts, report posts, and be interviewed. It requires setting up the agent graph, environment, and then stepping through various agent actions. The results, including interviews, are stored in a SQLite database. ```python import asyncio import os import json import sqlite3 from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType import oasis from oasis import ( ActionType, LLMAction, ManualAction, generate_twitter_agent_graph, ) async def main(): # Create model instance openai_model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, ) # Define available actions for agents available_actions = [ ActionType.CREATE_POST, ActionType.LIKE_POST, ActionType.REPORT_POST, # Add post reporting functionality ActionType.REPOST, ActionType.FOLLOW, ActionType.DO_NOTHING, ] # Create agent graph agent_graph = await generate_twitter_agent_graph( profile_path=("data/twitter_dataset/anonymous_topic_200_1h/" "False_Business_0.csv"), model=openai_model, available_actions=available_actions, ) # Define database path db_path = "./data/twitter_simulation.db" # Remove old database if os.path.exists(db_path): os.remove(db_path) # Create environment env = oasis.make( agent_graph=agent_graph, platform=oasis.DefaultPlatformType.TWITTER, database_path=db_path, ) # Run environment await env.reset() # Step 1: Agent 0 creates a post actions_1 = {} actions_1[env.agent_graph.get_agent(0)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is flat."}) await env.step(actions_1) # Step 2: Let some agents respond with LLM actions actions_2 = { agent: LLMAction() for _, agent in env.agent_graph.get_agents([1, 3, 5, 7, 9]) } await env.step(actions_2) # Step 3: Agent 1 creates another post, Agent 0 reports the first post actions_3 = {} actions_3[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is not flat."}) # Create report action actions_3[env.agent_graph.get_agent(0)] = ManualAction( action_type=ActionType.REPORT_POST, action_args={ "post_id": 1, "report_reason": "This is misinformation!" }) await env.step(actions_3) # Step 4: Let other agents respond actions_4 = { agent: LLMAction() for _, agent in env.agent_graph.get_agents([2, 4, 6, 8, 10]) } await env.step(actions_4) # Step 5: Interview multiple agents actions_5 = {} actions_5[env.agent_graph.get_agent(0)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={ "prompt": "Has your post 'Earth is flat' been reported? What are your thoughts on this?" }) actions_5[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={ "prompt": "Has the post 'Earth is flat' been reported? Please share your thoughts." }) actions_5[env.agent_graph.get_agent(2)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={ "prompt": "What are your thoughts on the debate about Earth's shape?" }) await env.step(actions_5) # Step 6: Final LLM actions for remaining agents actions_6 = { agent: LLMAction() for _, agent in env.agent_graph.get_agents([3, 5, 7, 9]) } await env.step(actions_6) # Close environment await env.close() # Visualize interview results print("\n=== Interview Results ===") conn = sqlite3.connect(db_path) cursor = conn.cursor() # Query all interview records cursor.execute( """ SELECT user_id, info, created_at FROM trace WHERE action = ? """, (ActionType.INTERVIEW.value, )) # Display interview results for user_id, info_json, timestamp in cursor.fetchall(): info = json.loads(info_json) print(f"\nAgent {user_id} (Timestep {timestamp}):") print(f"Prompt: {info.get('prompt', 'N/A')}") print(f"Interview ID: {info.get('interview_id', 'N/A')}") print(f"Response: {info.get('response', 'N/A')}") conn.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Run Mintlify Development Server Source: https://github.com/camel-ai/oasis/blob/main/CONTRIBUTING.md Navigate to the 'docs' directory and run the Mintlify development server to preview documentation changes locally. This command starts a local server for live previewing. ```bash cd docs mintlify dev ``` -------------------------------- ### Install aiohttp for Counterfactual Analysis Source: https://github.com/camel-ai/oasis/blob/main/docs/visualization/visualization.mdx Install the aiohttp library, a dependency for the Reddit Counterfactual Content Analysis script. ```bash pip install aiohttp ``` -------------------------------- ### Install Matplotlib for Visualization Source: https://github.com/camel-ai/oasis/blob/main/docs/visualization/visualization.mdx Install the matplotlib library, which is required for generating the Reddit Score Analysis visualization. ```bash pip install matplotlib ``` -------------------------------- ### Install Dependencies and Run Twitter User Generation Scripts Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/user_generation_visualization.md Install required packages and execute the generation and network scripts for Twitter user profiles. ```bash pip install -r generator/twitter/requirement.txt python generator/twitter/gen.py python generator/twitter/network.py ``` -------------------------------- ### Initialize Platform with RecsysType Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/recommendation_system.mdx When creating a custom platform, specify the recommendation system type using the RecsysType enum. This example shows initialization with the TWHIN system. ```python from oasis.social_platform.typing import RecsysType # When creating a custom platform platform = Platform( db_path="./data/simulation.db", channel=channel, recsys_type=RecsysType.TWHIN, # Choose your recommendation system # Additional parameters... ) ``` -------------------------------- ### Complete Example - Interview Action Type Source: https://github.com/camel-ai/oasis/blob/main/docs/cookbooks/twitter_interview.mdx This code block contains the copyright and license information for the project. It does not contain executable code for the interview action type itself. ```python # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` -------------------------------- ### Run Complete Simulation with Advanced Settings Source: https://github.com/camel-ai/oasis/blob/main/docs/simulation/simulation.mdx This Python script demonstrates a full simulation setup with custom time, database path, platform configurations, and agent actions. It initializes the environment, performs several steps with different agent activations and interventions, and then cleans up. ```python import asyncio import os from datetime import datetime import oasis from oasis import ActionType, EnvAction, Platform, SingleAction from oasis.social_platform.channel import Channel from oasis.social_platform.typing import RecsysType from oasis.clock.clock import Clock from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType async def run_simulation(): # Setup models models = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, ) # Define available actions available_actions = [ ActionType.CREATE_POST, ActionType.LIKE_POST, ActionType.REPOST, ActionType.FOLLOW, ActionType.DO_NOTHING, ] # Setup custom time start_time = datetime(2023, 1, 1, 12, 0, 0) # Jan 1, 2023, 12:00 PM sandbox_clock = Clock(magnification_factor=120) # 120x speed # Database path db_path = "./data/custom_simulation.db" if os.path.exists(db_path): os.remove(db_path) # Setup custom platform channel = Channel() platform = Platform( db_path=db_path, channel=channel, sandbox_clock=sandbox_clock, start_time=start_time, recsys_type=RecsysType.TWHIN, refresh_rec_post_count=3, max_rec_post_len=5, following_post_count=2, show_score=False, allow_self_rating=False, ) # Create environment env = oasis.make( platform=platform, agent_profile_path="./data/profiles/users.csv", agent_models=models, available_actions=available_actions, semaphore=64, ) # Initialize the environment await env.reset() # Create initial actions action1 = SingleAction( agent_id=0, action=ActionType.CREATE_POST, args={"content": "First post in our simulation!"} ) env_action1 = EnvAction( activate_agents=[0, 1, 2, 3, 4], intervention=[action1] ) # Step 1: Run with initial post await env.step(env_action1) # Step 2: Activate a different set of agents env_action2 = EnvAction(activate_agents=[5, 6, 7, 8, 9]) await env.step(env_action2) # Step 3: Run with all agents env_action3 = EnvAction() # Empty action = all agents, no intervention await env.step(env_action3) # Clean up await env.close() if __name__ == "__main__": asyncio.run(run_simulation()) ``` -------------------------------- ### Configure Platform Recommendation Parameters Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/recommendation_system.mdx Configure various recommendation-related parameters when initializing a Platform object. This example sets parameters for post refresh count, buffer length, followed user posts, and embedding usage. ```python from oasis import Platform from oasis.social_platform.channel import Channel from oasis.social_platform.typing import RecsysType channel = Channel() platform = Platform( db_path="./data/simulation.db", channel=channel, recsys_type=RecsysType.TWHIN, refresh_rec_post_count=2, # Number of posts per refresh max_rec_post_len=10, # Max posts in recommendation buffer following_post_count=3, # Posts from followed users use_openai_embedding=False, # Whether to use OpenAI embeddings ) ``` -------------------------------- ### Install Pre-commit Hook Source: https://github.com/camel-ai/oasis/blob/main/CONTRIBUTING.md Install the pre-commit hook to automatically format and lint code on every commit. This helps maintain code quality and consistency. ```bash pre-commit install ``` -------------------------------- ### Run vLLM Deployment Script Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/README.md Execute the deploy.py script using srun to start the vLLM service. The output will confirm the available ports for the API server. ```bash srun --ntasks=1 --time=11:00:00 --gres=gpu:a100:1 bash -c 'python deploy.py' ``` -------------------------------- ### Example Interview Questions Source: https://github.com/camel-ai/oasis/blob/main/docs/cookbooks/twitter_interview.mdx Examples of well-designed interview questions that are specific, clear, and open-ended to elicit richer responses from agents. ```text # Good examples "What are your thoughts on renewable energy?" "How do you feel about the recent policy changes?" "Can you explain your reasoning behind your last post?" # Avoid "Don't you think renewable energy is great?" # Leading "Yes or no: Do you like cats?" # Too restrictive ``` -------------------------------- ### Download Model with Hugging Face CLI Source: https://github.com/camel-ai/oasis/blob/main/docs/quickstart.mdx Use the Hugging Face CLI to download a model to your local machine. Ensure you have the `huggingface_hub` package installed and provide your Hugging Face token. ```bash pip install huggingface_hub huggingface-cli download --resume-download "Qwen/Qwen2.5-7B-Instruct" \ --local-dir "YOUR_LOCAL_MODEL_DIRECTORY" \ --local-dir-use-symlinks False \ --resume-download \ --token "YOUR_HUGGING_FACE_TOKEN" ``` -------------------------------- ### Twitter-like Platform Configuration Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/recommendation_system.mdx Configure a Twitter-like platform using the TwHIN-Bert recommendation system. This example sets specific parameters for refresh count, buffer length, and followed posts. ```python platform = Platform( db_path="./data/twitter_simulation.db", channel=channel, recsys_type=RecsysType.TWHIN, refresh_rec_post_count=2, max_rec_post_len=2, following_post_count=3, ) ``` -------------------------------- ### Deploy VLLM API Server Source: https://github.com/camel-ai/oasis/blob/main/docs/quickstart.mdx Start the VLLM API server to serve your downloaded model. This command configures the host, port, served model name, and enables auto tool choice with a specific tool call parser. ```bash vllm serve /path/to/Qwen2.5-7B-Instruct --host 0.0.0.0 --port 8000 \ --served-model-name 'qwen-2' \ --enable-auto-tool-choice \ --tool-call-parser hermes ``` -------------------------------- ### Run Simulation Experiments Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/README.md Execute the main simulation scripts for Reddit or Twitter(X) by providing the path to the configured YAML file. This initiates the experiment based on the setup. ```bash # For Reddit # Align with human python examples/experiment/reddit_simulation_align_with_human/reddit_simulation_align_with_human.py --config_path examples/experiment/reddit_simulation_align_with_human/business_3600.yaml # Agent's reaction to counterfactual content python examples/experiment/reddit_simulation_counterfactual/reddit_simulation_counterfactual.py --config_path examples/experiment/reddit_simulation_counterfactual/control_100.yaml # For Twitter(X) # Information spreading ``` -------------------------------- ### Reddit Agent Profiles JSON Example Source: https://github.com/camel-ai/oasis/blob/main/docs/simulation/simulation.mdx Example structure for agent profiles in JSON format, suitable for Reddit-like platforms. Includes user details and karma. ```json [ { "user_id": 0, "user_name": "user0", "name": "User Zero", "bio": "I am user zero with interests in technology.", "karma": 1000, "created_at": "2023-01-01" }, { "user_id": 1, "user_name": "user1", "name": "User One", "bio": "Tech enthusiast and coffee lover.", "karma": 2000, "created_at": "2023-01-02" } ] ``` -------------------------------- ### Run Mintlify on a Custom Port Source: https://github.com/camel-ai/oasis/blob/main/docs/development.mdx Customize the port Mintlify runs on by using the --port flag. This example runs Mintlify on port 3333. ```bash mintlify dev --port 3333 ``` -------------------------------- ### Python Docstring Args Section Example Source: https://github.com/camel-ai/oasis/blob/main/CONTRIBUTING.md Document constructor or function parameters using an 'Args:' section. Maintain a 79-character limit per line and indent continuation lines by 4 spaces. Specify parameter name, type, description, and default value. ```python Args: system_message (BaseMessage): The system message for initializing the agent's conversation context. model (BaseModelBackend, optional): The model backend to use for response generation. Defaults to :obj:`OpenAIModel` with `GPT_4O_MINI`. (default: :obj:`OpenAIModel` with `GPT_4O_MINI`) ``` -------------------------------- ### Re-install Mintlify Dependencies Source: https://github.com/camel-ai/oasis/blob/main/docs/README.md If the Mintlify dev command is not running correctly, try re-installing dependencies using this command. This can resolve issues related to missing or corrupted installations. ```bash mintlify install ``` -------------------------------- ### Configure Local VLLM Models in Python Source: https://github.com/camel-ai/oasis/blob/main/docs/quickstart.mdx Instantiate local VLLM models using the `ModelFactory`. This setup is used for agents in simulations that require local model inference. ```python vllm_model_1 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://$ip:$port", ) vllm_model_2 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://$ip:$port", ) models = [vllm_model_1, vllm_model_2] ``` -------------------------------- ### Simulate Agent Interaction with Custom Prompts Source: https://github.com/camel-ai/oasis/blob/main/docs/cookbooks/custom_prompt_simulation.mdx This Python script simulates agent interactions using custom prompts for product selling. It sets up agents, defines actions, and runs a simulation environment. Ensure you have the necessary libraries installed. ```python import asyncio import os from camel.models import ModelFactory from camel.prompts import TextPrompt from camel.types import ModelPlatformType, ModelType import oasis from oasis import ActionType, AgentGraph, LLMAction, SocialAgent, UserInfo async def main(): # Define the model for the agents openai_model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, ) # Define the available actions for the agents available_actions = [ ActionType.LIKE_POST, ActionType.DISLIKE_POST, ActionType.CREATE_POST, ActionType.CREATE_COMMENT, ActionType.LIKE_COMMENT, ActionType.DISLIKE_COMMENT, ActionType.FOLLOW, ActionType.MUTE, ActionType.PURCHASE_PRODUCT ] seller_template = TextPrompt('Your aim is: {aim} Your task is: {task}') profile = { "aim": "Persuade people to buy `GlowPod` lamp.", "task": "Using roleplay to tell some story about the product.", } agent_graph = AgentGraph() agent_1 = SocialAgent( agent_id=0, user_info=UserInfo( user_name="snackslut", name="Snack Slut", description="I taste so you don’t have to.", profile=profile, ), user_info_template=seller_template, agent_graph=agent_graph, model=openai_model, available_actions=available_actions, ) agent_graph.add_agent(agent_1) agent_2 = SocialAgent( agent_id=1, user_info=UserInfo( user_name="bubble", name="Bob", description="A boy", profile=None, recsys_type="reddit", ), agent_graph=agent_graph, model=openai_model, available_actions=available_actions, ) agent_graph.add_agent(agent_2) # Define the path to the database db_path = "./data/reddit_simulation.db" # Delete the old database if os.path.exists(db_path): os.remove(db_path) # Make the environment env = oasis.make( agent_graph=agent_graph, platform=oasis.DefaultPlatformType.REDDIT, database_path=db_path, ) # Run the environment await env.reset() # Sign up the profuct await env.platform.sign_up_product(product_id=1, product_name="GlowPod") for _ in range(5): actions = { agent: LLMAction() for _, agent in env.agent_graph.get_agents() } await env.step(actions) # Close the environment await env.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Obtain Node Information Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/README.md Use srun with ifconfig to get the IP address of the GPU server. Ensure network accessibility, especially within restricted networks. ```bash srun --ntasks=1 --mem=100G --time=11:00:00 --gres=gpu:a100:1 bash -c 'ifconfig -a' ``` -------------------------------- ### Reddit-like Platform Configuration Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/recommendation_system.mdx Configure a Reddit-like platform with specific parameters for self-rating, score display, buffer length, and post refresh count. This setup prioritizes post scores and engagement. ```python platform = Platform( db_path="./data/reddit_simulation.db", channel=channel, recsys_type=RecsysType.REDDIT, allow_self_rating=True, show_score=True, max_rec_post_len=100, refresh_rec_post_count=5, ) ``` -------------------------------- ### Analyze Simulation Results from Database Source: https://github.com/camel-ai/oasis/blob/main/docs/simulation/simulation.mdx This Python snippet shows how to print the contents of the SQLite database generated by a simulation. Ensure the `db_path` used during simulation setup is correctly provided to this function. ```python from oasis.testing.show_db import print_db_contents # Print all database contents print_db_contents("./data/simulation.db") ``` -------------------------------- ### Get Visible GPU Devices Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/README.md Use srun with echo to retrieve the CUDA_VISIBLE_DEVICES identifier for the available GPU. This is crucial for multi-GPU setups. ```bash srun --ntasks=1 --mem=100G --time=11:00:00 --gres=gpu:a100:1 bash -c 'echo $CUDA_VISIBLE_DEVICES' ``` -------------------------------- ### Initialize Customized Platform Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/platform.mdx Initialize a custom Platform instance with specific configurations for database path, clock, recommendation system type, and other social features. The `db_path` is required. ```python from oasis.social_platform.platform import Platform from oasis.clock.clock import Clock # Initialize with custom configuration platform = Platform( db_path="social_platform.db", sandbox_clock=Clock(k=60), show_score=True, allow_self_rating=False, recsys_type="twitter", refresh_rec_post_count=5, max_rec_post_len=10, following_post_count=3, use_openai_embedding=False ) ``` -------------------------------- ### Initialize OASIS Environment Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/environments.mdx Use the `make` function to create a simulation environment. Specify the agent graph, platform type (e.g., REDDIT), and database path. ```python import oasis from oasis import DefaultPlatformType # Make the environment env = oasis.make( agent_graph=agent_graph, platform=oasis.DefaultPlatformType.REDDIT, database_path="simulation.db", ) ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/camel-ai/oasis/blob/main/CONTRIBUTING.md Change your current directory to the cloned OASIS project folder. ```bash cd oasis ``` -------------------------------- ### Twitter Agent Profiles CSV Example Source: https://github.com/camel-ai/oasis/blob/main/docs/simulation/simulation.mdx Example structure for agent profiles in CSV format, suitable for Twitter-like platforms. Includes user details and activity counts. ```text user_id,user_name,name,bio,friend_count,follower_count,statuses_count,created_at 0,user0,User Zero,I am user zero with interests in technology.,100,150,500,2023-01-01 1,user1,User One,Tech enthusiast and coffee lover.,200,250,1000,2023-01-02 ``` -------------------------------- ### Initialize Twitter Agent Graph and Environment Source: https://github.com/camel-ai/oasis/blob/main/docs/cookbooks/twitter_interview.mdx Sets up the agent graph with specified available actions and initializes the Oasis environment for Twitter simulation. Ensure the profile path is correct and the database file is managed. ```python import asyncio import os import sqlite3 import json from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType import oasis from oasis import ( ActionType, LLMAction, ManualAction, generate_twitter_agent_graph ) async def main(): openai_model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, ) # Define the available actions for the agents # Note: INTERVIEW is NOT included here to prevent LLM from automatically selecting it # INTERVIEW can still be used manually via ManualAction available_actions = [ ActionType.CREATE_POST, ActionType.LIKE_POST, ActionType.REPOST, ActionType.FOLLOW, ActionType.DO_NOTHING, ActionType.QUOTE_POST, # ActionType.INTERVIEW, # DO NOT include this - interviews should be manual only ] agent_graph = await generate_twitter_agent_graph( profile_path=("data/twitter_dataset/anonymous_topic_200_1h/" "False_Business_0.csv"), model=openai_model, available_actions=available_actions, ) # Define the path to the database db_path = "./data/twitter_simulation.db" # Delete the old database if os.path.exists(db_path): os.remove(db_path) # Make the environment env = oasis.make( agent_graph=agent_graph, platform=oasis.DefaultPlatformType.TWITTER, database_path=db_path, ) # Run the environment await env.reset() # First timestep: Agent 0 creates a post actions_1 = {} actions_1[env.agent_graph.get_agent(0)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is flat."}) await env.step(actions_1) # Second timestep: Let some agents respond with LLM actions actions_2 = { agent: LLMAction() # Activate 5 agents with id 1, 3, 5, 7, 9 for _, agent in env.agent_graph.get_agents([1, 3, 5, 7, 9]) } await env.step(actions_2) # Third timestep: Agent 1 creates a post, and we interview Agent 0 actions_3 = {} actions_3[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is not flat."}) # Create an interview action to ask Agent 0 about their views actions_3[env.agent_graph.get_agent(0)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={"prompt": "What do you think about the shape of the Earth? Please explain your reasoning."}) await env.step(actions_3) # Fourth timestep: Let some other agents respond actions_4 = { agent: LLMAction() for _, agent in env.agent_graph.get_agents([2, 4, 6, 8, 10]) } await env.step(actions_4) # Fifth timestep: Interview multiple agents actions_5 = {} actions_5[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={"prompt": "Why do you believe the Earth is not flat?"}) actions_5[env.agent_graph.get_agent(2)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={"prompt": "What are your thoughts on the debate about Earth's shape?"}) await env.step(actions_5) # Sixth timestep: Final LLM actions for remaining agents actions_6 = { agent: LLMAction() for _, agent in env.agent_graph.get_agents([3, 5, 7, 9]) } await env.step(actions_6) # Close the environment await env.close() # visualize the interview results print("\n=== Interview Results ===") conn = sqlite3.connect(db_path) cursor = conn.cursor() # Here we query all interview records from the database # We use ActionType.INTERVIEW.value as the query condition to get all interview records # Each record contains user ID, interview information (in JSON format), and creation timestamp cursor.execute(""" SELECT user_id, info, created_at FROM trace WHERE action = ? """, (ActionType.INTERVIEW.value,)) # This query retrieves all interview records from the trace table # - user_id: the ID of the agent who was interviewed # - info: JSON string containing interview details (prompt, response, etc.) # - created_at: timestamp when the interview was conducted # We'll parse this data below to display the interview results for user_id, info_json, timestamp in cursor.fetchall(): info = json.loads(info_json) print(f"\nAgent {user_id} (Timestep {timestamp}):") print(f"Prompt: {info.get('prompt', 'N/A')}") print(f"Interview ID: {info.get('interview_id', 'N/A')}") print(f"Response: {info.get('response', 'N/A')}") conn.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Example Reddit JSON User Data Format Source: https://github.com/camel-ai/oasis/blob/main/docs/user_generation/generation.mdx Provides an example of a JSON array representing user data for Reddit simulations, including fields such as realname, username, bio, persona, age, gender, mbti, and country. ```json [ { "realname": "James Miller", "username": "millerhospitality", "bio": "Passionate about hospitality & tourism. Exploring the world one destination at a time.", "persona": "James is a seasoned professional in the Hospitality & Tourism industry. With a knack for business and a keen interest in economics, he enjoys analyzing market trends and staying updated on the latest developments in the field. When not working, he loves traveling to exotic locations, sampling local cuisines, and experiencing different cultures. Follow for industry insights and travel inspiration!", "age": 40, "gender": "male", "mbti": "ESTJ", "country": "UK" }, { "realname": "Emma Hayes", "username": "emma_logistics_guru", "bio": "Passionate about transportation and logistics | ENFJ | Always seeking new connections and opportunities", "persona": "Emma Hayes is a 19-year-old logistics enthusiast currently studying Transportation, Distribution & Logistics. With a bubbly and outgoing personality (ENFJ), she loves discussing culture, society, and business trends. Emma is always expanding her knowledge in the transportation industry and enjoys connecting with like-minded individuals to exchange ideas and insights.", "age": 19, "gender": "female", "mbti": "ENFJ", "country": "UK" } ] ``` -------------------------------- ### Set OpenAI API Key Source: https://github.com/camel-ai/oasis/blob/main/README.md Set your OpenAI API key as an environment variable. This is required for OASIS to function. The example provided is for a Bash shell. ```bash # For Bash shell (Linux, macOS, Git Bash on Windows): export OPENAI_API_KEY= ``` -------------------------------- ### ManualAction: PURCHASE_PRODUCT Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/actions.mdx Initiates a product purchase. Requires 'product_name' and 'purchase_num' arguments. ```python action = ManualAction( action=ActionType.PURCHASE_PRODUCT, args={"product_name": "Premium Subscription", "purchase_num": 1} ) ``` -------------------------------- ### Create Environment with Reddit-like Platform Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/platform.mdx Use DefaultPlatformType.REDDIT to simulate a Reddit-like platform. Specify the database path and agent profile path accordingly. ```python env = oasis.make( platform=DefaultPlatformType.REDDIT, database_path="./data/reddit_simulation.db", agent_profile_path="./data/profiles/reddit_users.json", agent_models=models, available_actions=available_actions, ) ``` -------------------------------- ### Get Agent by ID from AgentGraph Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/agent_graph.mdx Retrieve a specific `SocialAgent` from the `AgentGraph` using its unique `agent_id`. This is useful for direct interaction or inspection of individual agents. ```python agent = agent_graph.get_agent(agent_id) ``` -------------------------------- ### Import and Use a Basic MDX Snippet Source: https://github.com/camel-ai/oasis/blob/main/docs/essentials/reusable-snippets.mdx Import a snippet from the `snippets` directory into your destination file and render it as a component, passing values for any defined variables. ```mdx --- title: My title description: My Description --- import MySnippet from '/snippets/path/to/my-snippet.mdx'; ## Header Lorem impsum dolor sit amet. ``` -------------------------------- ### Get Default Reddit Actions Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/actions.mdx Retrieves a list of default actions available for Reddit. This includes actions like liking posts, creating comments, and searching. ```python available_actions = ActionType.get_default_reddit_actions() ``` -------------------------------- ### Create and Step Environment Action Source: https://github.com/camel-ai/oasis/blob/main/docs/simulation/simulation.mdx Define custom environment actions, including agent interventions, and step the simulation environment with these actions. Use `EnvAction` to specify which agents are active and any interventions. ```python from oasis import EnvAction, SingleAction, ActionType # Create a custom intervention action = SingleAction( agent_id=0, action=ActionType.CREATE_POST, args={"content": "Test post for the simulation"} ) # Create an environment action to activate specific agents env_action = EnvAction( activate_agents=[0, 1, 2, 3, 4], # Only these agents will be active intervention=[action] # Optional interventions ) # Step the environment with the action await env.step(env_action) ``` -------------------------------- ### Deploy vLLM API Server Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/README.md Configure and run the deploy.py script to launch the vLLM OpenAI-compatible API server. Modify host, ports, and GPU settings as per your environment. ```python if __name__ == "__main__": host = "10.109.1.8" # input your IP address ports = [ [8002, 8003, 8005], [8006, 8007, 8008], [8011, 8009, 8010], [8014, 8012, 8013], [8017, 8015, 8016], [8020, 8018, 8019], [8021, 8022, 8023], [8024, 8025, 8026], ] gpus = [0] # input your $CUDA_VISIBLE_DEVICES all_ports = [port for i in gpus for port in ports[i]] print("All ports: ", all_ports, '\n\n') t = None for i in range(3): for j, gpu in enumerate(gpus): cmd = ( f"CUDA_VISIBLE_DEVICES={gpu} python -m " f"vllm.entrypoints.openai.api_server --model " f"'YOUR_LOCAL_MODEL_DIRECTORY' " # input the path where you downloaded your model f"--served-model-name 'YOUR_LOCAL_MODEL_NAME' " # input the name of the model you downloaded f"--host {host} --port {ports[j][i]} --gpu-memory-utilization " f"0.3 --disable-log-stats") t = threading.Thread(target=subprocess.run, args=(cmd, ), kwargs={"shell": True}, daemon=True) t.start() check_port_open(host, ports[0][i]) t.join() ``` -------------------------------- ### Get Number of Nodes (Agents) in AgentGraph Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/agent_graph.mdx Obtain the total count of `SocialAgent` instances within the `AgentGraph`. This provides a quick way to check the size of the agent population. ```python num_agents = agent_graph.get_num_nodes() ``` -------------------------------- ### Get All Agents from AgentGraph Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/agent_graph.mdx Retrieve a list of all `SocialAgent` objects currently present in the `AgentGraph`. Each item in the list is a tuple containing the agent's ID and the agent object itself. ```python agent_list = agent_graph.get_all_agents() ``` -------------------------------- ### Simulate Social Agents with Search Tools Source: https://github.com/camel-ai/oasis/blob/main/docs/cookbooks/search_tools_simulation.mdx Sets up a simulated social environment with two agents. Agent 2 is equipped with a SearchToolkit for DuckDuckGo searches. The simulation involves creating posts, comments, and allowing agents to use LLM actions to interact and search. ```python import asyncio import os from camel.models import ModelFactory from camel.toolkits import SearchToolkit from camel.types import ModelPlatformType, ModelType import oasis from oasis import ( ActionType, AgentGraph, LLMAction, ManualAction, SocialAgent, UserInfo, ) async def main(): # Define the model for the agents openai_model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, ) # Define the available actions for the agents available_actions = [ ActionType.LIKE_POST, ActionType.CREATE_POST, ActionType.CREATE_COMMENT, ActionType.FOLLOW, ] agent_graph = AgentGraph() agent_1 = SocialAgent( agent_id=0, user_info=UserInfo( user_name="ali", name="Alice", description="A girl", profile=None, recsys_type="reddit", ), agent_graph=agent_graph, model=openai_model, available_actions=available_actions, ) agent_graph.add_agent(agent_1) agent_2 = SocialAgent(agent_id=1, user_info=UserInfo( user_name="bubble", name="Bob", description="A boy", profile=None, recsys_type="reddit", ), tools=[SearchToolkit().search_duckduckgo], agent_graph=agent_graph, model=openai_model, available_actions=[ActionType.CREATE_COMMENT], max_iteration=5) agent_graph.add_agent(agent_2) # Define the path to the database db_path = "./data/reddit_simulation.db" os.environ["OASIS_DB_PATH"] = os.path.abspath(db_path) # Delete the old database if os.path.exists(db_path): os.remove(db_path) # Make the environment env = oasis.make( agent_graph=agent_graph, platform=oasis.DefaultPlatformType.REDDIT, database_path=db_path, ) # Run the environment await env.reset() actions_1 = { env.agent_graph.get_agent(0): [ ManualAction( action_type=ActionType.CREATE_POST, action_args={ "content": "Can someone use duckduckgo tool now? I can not open it." "If so, can you help me with searching the oasis?" }) ] } await env.step(actions_1) for _ in range(3): action = { agent: LLMAction() for _, agent in env.agent_graph.get_agents() } await env.step(action) # Close the environment await env.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Default Twitter Actions Source: https://github.com/camel-ai/oasis/blob/main/docs/key_modules/actions.mdx Retrieves a list of default actions available for Twitter. This includes actions like creating posts, liking posts, and following users. ```python available_actions = ActionType.get_default_twitter_actions() ``` -------------------------------- ### Download Open Source Models (LLaMA-3) Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/README.md Download LLaMA-3 models from Hugging Face using the `huggingface-cli` tool. Ensure you replace placeholder directory and token values with your actual information. ```bash pip install huggingface_hub huggingface-cli download --resume-download "meta-llama/Meta-Llama-3-8B-Instruct" --local-dir "YOUR_LOCAL_MODEL_DIRECTORY" --local-dir-use-symlinks False --resume-download --token "YOUR_HUGGING_FACE_TOKEN" ``` -------------------------------- ### Python Raw Docstring Example Source: https://github.com/camel-ai/oasis/blob/main/CONTRIBUTING.md Use triple-quoted raw strings (r""") for docstrings to prevent issues with special characters and ensure consistent formatting. ```python r"""Class for managing conversations of OASIS Agents. """ ``` -------------------------------- ### Configure Reddit Simulation Analysis Paths Source: https://github.com/camel-ai/oasis/blob/main/examples/experiment/user_generation_visualization.md Set the experiment results folder path, experiment name, database path, and experiment info file path in analysis_all.py. ```python if __name__ == "__main__": folder_path = ("visualization/reddit_simulation_align_with_human" "/experiment_results") exp_name = "business_3600" db_path = folder_path + f"/{exp_name}.db" exp_info_file_path = folder_path + f"/{exp_name}.json" analysis_score.main(exp_info_file_path, db_path, exp_name, folder_path) ``` -------------------------------- ### Example Twitter CSV User Data Format Source: https://github.com/camel-ai/oasis/blob/main/docs/user_generation/generation.mdx Illustrates the structure of a CSV file for Twitter user data, including fields like user_id, name, username, user_char, and description. ```csv user_id,name,username,user_char,description 14529063,user_9,user9,Beach bum, web developer, nerd πŸ€“, crocheter, avid reader πŸ“š, a singer in the shower, a notorious heart breaker. I blog about books @ https://t.co/JjnKtEnq4R,Beach bum, web developer, nerd πŸ€“, crocheter, avid reader πŸ“š, a singer in the shower, a notorious heart breaker. I blog about books @ https://t.co/JjnKtEnq4R ``` -------------------------------- ### Add Image using Markdown Source: https://github.com/camel-ai/oasis/blob/main/docs/essentials/images.mdx Use Markdown syntax to include images. Ensure image file size is under 5MB, or host externally and link the URL. ```markdown ![title](/path/image.jpg) ```