# Custom Prompt Simulation Source: https://docs.oasis.camel-ai.org/cookbooks/custom_prompt_simulation This cookbook provides a example of an agent uses custom prompt to set a task for selling products. # Custom Prompt Simulation This cookbook provides a example of an agent uses custom prompt to set a task for selling products. ```python theme={null} 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()) ``` # Reddit Simulation Source: https://docs.oasis.camel-ai.org/cookbooks/reddit_simulation Comprehensive guide to all available actions in the OASIS simulation environment # Reddit Simulation This cookbook provides a comprehensive guide to running a Reddit simulation using OASIS. ```python theme={null} import asyncio import os from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType import oasis from oasis import (ActionType, LLMAction, ManualAction, generate_reddit_agent_graph) 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.SEARCH_POSTS, ActionType.SEARCH_USER, ActionType.TREND, ActionType.REFRESH, ActionType.DO_NOTHING, ActionType.FOLLOW, ActionType.MUTE, ] agent_graph = await generate_reddit_agent_graph( profile_path="./data/reddit/user_data_36.json", model=openai_model, available_actions=available_actions, ) # 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() actions_1 = {} actions_1[env.agent_graph.get_agent(0)] = [ ManualAction(action_type=ActionType.CREATE_POST, action_args={"content": "Hello, world!"}), ManualAction(action_type=ActionType.CREATE_COMMENT, action_args={ "post_id": "1", "content": "Welcome to the OASIS World!" }) ] actions_1[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_COMMENT, action_args={ "post_id": "1", "content": "I like the OASIS world." }) await env.step(actions_1) actions_2 = { agent: LLMAction() for _, agent in env.agent_graph.get_agents() } # Perform the actions await env.step(actions_2) # Close the environment await env.close() if __name__ == "__main__": asyncio.run(main()) ``` # Search Tools Simulation Source: https://docs.oasis.camel-ai.org/cookbooks/search_tools_simulation This cookbook provides a example of an agent uses search tools to get information. # Search Tools Simulation This cookbook provides a example of an agent uses search tools to get information. ```python theme={null} 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()) ``` # Sympy Tools Simulation Source: https://docs.oasis.camel-ai.org/cookbooks/sympy_tools_simulation This cookbook provides a example of an agent asks question about math problem and another agent solve it with Sympy. # Simulation with Sympy Tools This cookbook provides a example of an agent asks question about math problem and another agent solve it with Sympy. ```python theme={null} import asyncio import os from camel.models import ModelFactory from camel.toolkits import SymPyToolkit 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=SymPyToolkit().get_tools(), agent_graph=agent_graph, model=openai_model, available_actions=available_actions, 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": "I am doing my homework. Can any kind soul help me " "simplify this expression using sympy: " "(x**4 - 16)/(x**2 - 4) + sin(x)**2 + cos(x)**2 + " "(x**3 + 6*x**2 + 12*x + 8)/(x + 2)" }), ManualAction(action_type=ActionType.CREATE_COMMENT, action_args={ "post_id": "1", "content": "I will give a big thumbs up to " "anyone who helps me solve this!" }) ] } 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()) ``` # Interview Source: https://docs.oasis.camel-ai.org/cookbooks/twitter_interview Learn how to conduct interviews with AI agents in Twitter simulations using the INTERVIEW action type # Interview This cookbook demonstrates how to use the INTERVIEW action type to conduct interviews with AI agents in a Twitter simulation. The interview functionality allows you to ask specific questions to agents and collect their responses, which is useful for research, opinion polling, and understanding agent behaviors. ## Overview The INTERVIEW action type enables you to: * Ask specific questions to individual agents * Collect structured responses from agents * Store interview data in the database for analysis * Conduct interviews alongside regular social media interactions ## Key Features * **Manual Interview Actions**: Use `ManualAction` with `ActionType.INTERVIEW` to conduct interviews * **Automatic Response Collection**: The system automatically collects and stores agent responses * **Database Storage**: All interview data is stored in the trace table for later analysis * **Concurrent Execution**: Interviews can be conducted alongside other social media actions ## Important Note **Do NOT include `ActionType.INTERVIEW` in the `available_actions` list** when creating your agent graph. The interview action is designed to be used only manually by researchers/developers, not automatically selected by LLM agents. Including it in `available_actions` would allow agents to interview each other automatically, which is typically not desired behavior. ## Complete Example ```python theme={null} # =========== 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. # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== 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()) ``` ## How It Works ### 1. Setup and Configuration **Important**: Do NOT include `ActionType.INTERVIEW` in your available actions list. Interviews should only be conducted manually: ```python theme={null} # Correct configuration - INTERVIEW is NOT included available_actions = [ ActionType.CREATE_POST, ActionType.LIKE_POST, ActionType.REPOST, ActionType.FOLLOW, ActionType.DO_NOTHING, ActionType.QUOTE_POST, # ActionType.INTERVIEW, # DO NOT include - interviews are manual only ] ``` This prevents LLM agents from automatically selecting the interview action during their decision-making process. Interviews can still be conducted using `ManualAction`. ### 2. Conducting Interviews Use `ManualAction` with `ActionType.INTERVIEW` to conduct interviews: ```python theme={null} # Single interview interview_action = ManualAction( action_type=ActionType.INTERVIEW, action_args={"prompt": "What are your thoughts on climate change?"}) actions = {env.agent_graph.get_agent(0): interview_action} await env.step(actions) ``` ### 3. Multiple Interviews in One Step You can interview multiple agents simultaneously: ```python theme={null} actions = {} actions[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={"prompt": "Why do you believe the Earth is not flat?"}) actions[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) ``` ### 4. Mixing Interviews with Other Actions Interviews can be conducted alongside regular social media actions: ```python theme={null} actions = {} # Regular post creation actions[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is not flat."}) # Interview action actions[env.agent_graph.get_agent(0)] = ManualAction( action_type=ActionType.INTERVIEW, action_args={"prompt": "What do you think about the shape of the Earth?"}) await env.step(actions) ``` ## Data Storage and Retrieval ### Database Schema Interview data is stored in the `trace` table with the following structure: * `user_id`: The ID of the interviewed agent * `action`: Set to `ActionType.INTERVIEW.value` * `info`: JSON string containing interview details * `created_at`: Timestamp of the interview ### Retrieving Interview Results ```python theme={null} import sqlite3 import json 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,)) for user_id, info_json, timestamp in cursor.fetchall(): info = json.loads(info_json) print(f"Agent {user_id}: {info.get('response', 'N/A')}") conn.close() ``` ### Interview Data Structure Each interview record contains: * `prompt`: The question asked to the agent * `interview_id`: Unique identifier for the interview * `response`: The agent's response to the question ## Best Practices ### 1. Strategic Interview Timing Conduct interviews at strategic points in your simulation: * After controversial posts to gauge reactions * Before and after significant events * At regular intervals to track opinion changes ### 2. Question Design Design effective interview questions: * Be specific and clear * Avoid leading questions * Ask open-ended questions for richer responses ```python theme={null} # 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 ``` # Twitter Simulation Source: https://docs.oasis.camel-ai.org/cookbooks/twitter_simulation Comprehensive guide to all available actions in the OASIS simulation environment # Twitter Simulation This cookbook provides a comprehensive guide to running a Twitter simulation using OASIS. ```python theme={null} import asyncio import os from camel.models import ModelFactory, ModelManager from camel.types import ModelPlatformType import oasis from oasis import (ActionType, LLMAction, ManualAction, generate_twitter_agent_graph) async def main(): # NOTE: You need to deploy the vllm server first vllm_model_1 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", # TODO: change to your own vllm server url url="http://10.109.28.7:8080/v1", ) vllm_model_2 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", # TODO: change to your own vllm server url url="http://10.109.27.103:8080/v1", ) # Define the models for agents. Agents will select models based on # round-robin strategy shared_model_manager = ModelManager( models=[vllm_model_1, vllm_model_2], scheduling_strategy='round_robin', ) # Define the available actions for the agents available_actions = ActionType.get_default_twitter_actions() agent_graph = await generate_twitter_agent_graph( profile_path=("data/twitter_dataset/anonymous_topic_200_1h/" "False_Business_0.csv"), model=shared_model_manager, available_actions=available_actions, ) # Define the path to the database db_path = "./data/twitter_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.TWITTER, database_path=db_path, ) # Run the environment await env.reset() 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) 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) actions_3 = {} actions_3[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is not flat."}) await env.step(actions_3) actions_4 = { agent: LLMAction() # get all agents for _, agent in env.agent_graph.get_agents() } await env.step(actions_4) # Close the environment await env.close() if __name__ == "__main__": asyncio.run(main()) ``` # Introduction Source: https://docs.oasis.camel-ai.org/introduction Welcome to OASIS: Open Agent Social Interaction Simulations with One Million Agents Hero Light Hero Dark ## What is OASIS? 🏝️ OASIS is a scalable, open-source social media simulator that integrates large language models with rule-based agents to realistically mimic the behavior of up to one million users on platforms like Twitter and Reddit. It's designed to facilitate the study of complex social phenomena such as information spread, group polarization, and herd behavior, offering a versatile tool for exploring diverse social dynamics and user interactions in digital environments. OASIS Main ## Key Features Supports simulations of up to one million agents, enabling studies of social media dynamics at a scale comparable to real-world platforms Adapts to real-time changes in social networks and content, mirroring the fluid dynamics of platforms like Twitter and Reddit for authentic simulation experiences Agents can perform 23 different actions, such as following, commenting, reposting, and quoting for rich, multi-faceted interactions Features interest-based and hot-score-based recommendation algorithms, simulating how users discover content on real social media platforms ## Use Cases Study complex social phenomena like information spread, group polarization, and collective behavior at scale Create dynamic environments for testing human-agent interactions and social dynamics Generate realistic social media content and interactions for creative or educational purposes Model and predict how information and behaviors might spread through social networks ## Getting Started Learn how to set up and use OASIS for your social simulation needs. Get OASIS set up on your local environment with our step-by-step guide Learn how to create user profiles and run your first simulation Explore the full capabilities of OASIS through our comprehensive docs Join our Discord, Reddit, X, and WeChat groups to connect with other OASIS users ## Resources Read the foundational research paper detailing OASIS methodology and findings Explore example scripts for running various types of simulations Access our comprehensive dataset of agent interactions on Hugging Face Watch demonstrations of OASIS capabilities and simulation examples # Actions Source: https://docs.oasis.camel-ai.org/key_modules/actions This section provides detailed information about all available actions and how to configure them in your simulation environment, including the available action types, the predefined `ManualAction` and llm-based `LLMAction`. ## Actions for `env.step` The `actions` parameter passed to the OASIS environment's `step` method should be a dictionary that specifies what each agent should do at a given timestep, as shown below: ```python theme={null} dict[SocialAgent, Union[List[Union[ManualAction, LLMAction]],Union[ManualAction, LLMAction]]] ``` * The **key** is a `SocialAgent`. * The **value** is either: * A single predefined `ManualAction` or an LLM-generated `LLMAction`, or * A list of `ManualAction` or `LLMAction` instances, allowing the same agent to perform multiple actions within one timestep. ## `LLMAction` You can use `LLMAction()` to indicate that an agent should perform actions based on the output of an LLM. These actions can include both social actions and external tools, as defined during initialization. An example where all agents use `LLMAction()` to perform actions: ```python theme={null} from oasis import LLMAction all_llm_actions = { agent: LLMAction() for _, agent in env.agent_graph.get_agents() } await env.step(all_llm_actions) ``` ## `ManualAction` You can use `ManualAction()` to indicate that an agent should perform actions based on the predefined `ActionType` and corresponding arguments. * The data structure of `ManualAction`: ```python theme={null} @dataclass class ManualAction: r"""Some manual predefined social platform actions that need to be executed by certain agents. Args: agent_id: The ID of the agent that will perform the action. action: The action to perform. args: The arguments to pass to the action. For details of each args in each action, please refer to `https://github.com/camel-ai/oasis/blob/main/oasis/social_agent/agent_action.py`. """ action_type: ActionType action_args: Dict[str, Any] def init(self, action_type, action_args): self.action_type = action_type self.action_args = action_args ``` * A example of using `ManualAction()`: ```python theme={null} 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) ``` For more details about the `ActionType` and corresponding arguments, please refer to the [ActionType](#actiontype) section. ## `ActionType` OASIS provides a comprehensive set of actions that simulate real social media behaviors: | Action Type | Description | | ---------------------- | ---------------------------------------------------------------- | | `SIGNUP` | Register a new user with username, name, and bio | | `CREATE_POST` | Create a new post with text content | | `LIKE_POST` | Like or upvote a post | | `UNLIKE_POST` | Remove a like from a previously liked post | | `DISLIKE_POST` | Dislike or downvote a post | | `UNDO_DISLIKE_POST` | Remove a dislike from a previously disliked post | | `REPORT_POST` | Report a post for inappropriate content | | `REPOST` | Repost content without modification (equivalent to retweet) | | `QUOTE_POST` | Repost with additional commentary | | `CREATE_COMMENT` | Create a comment on a post | | `LIKE_COMMENT` | Like a comment | | `UNLIKE_COMMENT` | Remove a like from a previously liked comment | | `DISLIKE_COMMENT` | Dislike a comment | | `UNDO_DISLIKE_COMMENT` | Remove a dislike from a previously disliked comment | | `FOLLOW` | Follow another user | | `UNFOLLOW` | Unfollow a previously followed user | | `MUTE` | Mute another user (hide their content without unfollowing) | | `UNMUTE` | Unmute a previously muted user | | `SEARCH_POSTS` | Search for posts by keywords, post ID, or user ID | | `SEARCH_USER` | Search for users by username, name, bio, or user ID | | `TREND` | Get trending content based on popularity metrics | | `REFRESH` | Refresh the timeline to get recommended posts | | `DO_NOTHING` | Perform no action (pass the turn) | | `PURCHASE_PRODUCT` | Purchase a product (for e-commerce simulations) | | `INTERVIEW` | Interview a user and record the interview result in the database | | `CREATE_GROUP` | Create a new group with a given name | | `JOIN_GROUP` | Join a group by group ID | | `LEAVE_GROUP` | Leave a group by group ID | | `SEND_TO_GROUP` | Send a message to a group | | `LISTEN_FROM_GROUP` | Listen for messages from groups | ### Platform-Specific Actions OASIS provides platform-specific action sets that can be accessed using class methods: #### Reddit Actions ```python theme={null} # Get all Reddit-specific actions, return a list of ActionType available_actions = ActionType.get_default_reddit_actions() ``` The Reddit action set includes: * `LIKE_POST` * `DISLIKE_POST` * `CREATE_POST` * `CREATE_COMMENT` * `LIKE_COMMENT` * `DISLIKE_COMMENT` * `SEARCH_POSTS` * `SEARCH_USER` * `TREND` * `REFRESH` * `DO_NOTHING` * `FOLLOW` * `MUTE` #### Twitter Actions ```python theme={null} # Get all Reddit-specific actions, return a list of ActionType available_actions = ActionType.get_default_twitter_actions() ``` The Twitter action set includes: * `CREATE_POST` * `LIKE_POST` * `REPOST` * `FOLLOW` * `DO_NOTHING` * `QUOTE_POST` ## Arguments for `ManualAction` #### CREATE\_POST ```python theme={null} action = ManualAction( action=ActionType.CREATE_POST, args={"content": "Hello, OASIS world!"} ) ``` #### LIKE\_POST ```python theme={null} action = ManualAction( action=ActionType.LIKE_POST, args={"post_id": 123} ) ``` #### UNLIKE\_POST ```python theme={null} action = ManualAction( action=ActionType.UNLIKE_POST, args={"post_id": 123} ) ``` #### DISLIKE\_POST ```python theme={null} action = ManualAction( action=ActionType.DISLIKE_POST, args={"post_id": 123} ) ``` #### UNDO\_DISLIKE\_POST ```python theme={null} action = ManualAction( action=ActionType.UNDO_DISLIKE_POST, args={"post_id": 123} ) ``` #### REPORT\_POST ```python theme={null} action = ManualAction( action=ActionType.REPORT_POST, args={ "post_id": 123, "report_reason": "This post contains false information" } ) ``` #### REPOST ```python theme={null} action = ManualAction( action=ActionType.REPOST, args={"post_id": 123} ) ``` #### QUOTE\_POST ```python theme={null} action = ManualAction( action=ActionType.QUOTE_POST, args={"post_id": 123, "quote_content": "This is amazing content!"} ) ``` #### CREATE\_COMMENT ```python theme={null} action = ManualAction( action=ActionType.CREATE_COMMENT, args={"post_id": 123, "content": "Great post! I completely agree."} ) ``` #### LIKE\_COMMENT ```python theme={null} action = ManualAction( action=ActionType.LIKE_COMMENT, args={"comment_id": 456} ) ``` #### UNLIKE\_COMMENT ```python theme={null} action = ManualAction( action=ActionType.UNLIKE_COMMENT, args={"comment_id": 456} ) ``` #### DISLIKE\_COMMENT ```python theme={null} action = ManualAction( action=ActionType.DISLIKE_COMMENT, args={"comment_id": 456} ) ``` #### UNDO\_DISLIKE\_COMMENT ```python theme={null} action = ManualAction( action=ActionType.UNDO_DISLIKE_COMMENT, args={"comment_id": 456} ) ``` #### FOLLOW ```python theme={null} action = ManualAction( action=ActionType.FOLLOW, args={"followee_id": 789} ) ``` #### UNFOLLOW ```python theme={null} action = ManualAction( action=ActionType.UNFOLLOW, args={"followee_id": 789} ) ``` #### MUTE ```python theme={null} action = ManualAction( action=ActionType.MUTE, args={"mutee_id": 789} ) ``` #### UNMUTE ```python theme={null} action = ManualAction( action=ActionType.UNMUTE, args={"mutee_id": 789} ) ``` #### SEARCH\_POSTS ```python theme={null} action = ManualAction( action=ActionType.SEARCH_POSTS, args={"query": "artificial intelligence"} ) ``` #### SEARCH\_USER ```python theme={null} action = ManualAction( action=ActionType.SEARCH_USER, args={"query": "john"} ) ``` #### TREND ```python theme={null} action = ManualAction( action=ActionType.TREND, args={} ) ``` #### REFRESH ```python theme={null} action = ManualAction( action=ActionType.REFRESH, args={} ) ``` #### DO\_NOTHING ```python theme={null} action = ManualAction( action=ActionType.DO_NOTHING, args={} ) ``` #### PURCHASE\_PRODUCT ```python theme={null} action = ManualAction( action=ActionType.PURCHASE_PRODUCT, args={"product_name": "Premium Subscription", "purchase_num": 1} ) ``` #### INTERVIEW ```python theme={null} action = ManualAction( action=ActionType.INTERVIEW, args={"prompt": "What is your name?"} ) ``` #### CREATE\_GROUP ```python theme={null} action = ManualAction( action=ActionType.CREATE_GROUP, args={"group_name": "OASIS Fans"} ) ``` #### JOIN\_GROUP ```python theme={null} action = ManualAction( action=ActionType.JOIN_GROUP, args={"group_id": 1} ) ``` #### LEAVE\_GROUP ```python theme={null} action = ManualAction( action=ActionType.LEAVE_GROUP, args={"group_id": 1} ) ``` #### SEND\_TO\_GROUP ```python theme={null} action = ManualAction( action=ActionType.SEND_TO_GROUP, args={"group_id": 1, "message": "Hello, OASIS fans!"} ) ``` #### LISTEN\_FROM\_GROUP ```python theme={null} action = ManualAction( action=ActionType.LISTEN_FROM_GROUP, args={} ) ``` # Agent Graph Source: https://docs.oasis.camel-ai.org/key_modules/agent_graph The Agent Graph saves all the social agents in the simulation. In this section, we will introduce how to create an `AgentGraph` and some useful methods within it. # Two ways to create an `AgentGraph`: * Option 1: Create an `AgentGraph` from a `csv` or `json` file, which contains the agent profiles. * Option 2: Create an empty `AgentGraph` and add each customized agent. ## Option 1: Create an `AgentGraph` from the agent profile files We support initializing the AgentGraph using a file that stores agent profiles. In addition, you need to specify the LLM model used by all agents and the set of available social actions. The parameters for these two functions are as follows: | Parameter | Type | Required | Default | Description | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `profile_path` | `str` | βœ” | - | Path to a CSV or JSON file storing agent profiles. For details on different profile formats, see [Agent Profile](https://docs.oasis.camel-ai.org/user_generation/user_generation) section. | | `model` | [`BaseModelBackend`](https://docs.camel-ai.org/key_modules/models) or `List[BaseModelBackend]` or [`ModelManager`](https://docs.camel-ai.org/key_modules/models) | βœ— | gpt-4o-mini | The large language model(s) used by the all agents. | | `available_actions` | [`list[ActionType]`](https://docs.oasis.camel-ai.org/key_modules/actions.mdx) | βœ— | `None` | List of allowed actions in the social platform for all agents. For more details, see **Actions - OASIS**. If set to `None`, all actions are enabled by default. | ### Example of initializing an `AgentGraph` from a profile file * Twitter user profile style ```python theme={null} from oasis import generate_twitter_agent_graph agent_graph = await generate_twitter_agent_graph( profile_path=("data/twitter_dataset.csv"), model=openai_model, available_actions=available_actions, ) ``` * Reddit user profile style ```python theme={null} from oasis import generate_reddit_agent_graph agent_graph = await generate_reddit_agent_graph( profile_path="./data/reddit/user_data_36.json", model=openai_model, available_actions=available_actions, ) ``` ## Option 2: Create an empty `AgentGraph` and customize each agent ### Step 1: Create an empty `AgentGraph` ```python theme={null} from oasis import AgentGraph # Create an empty `AgentGraph` agent_graph = AgentGraph() ``` ### Step 2: Add each customized agent to the `AgentGraph` You can initialize some social agents and add them to the `AgentGraph`. For more details on how to customize the `SocialAgent` class, see [Social Agent Module](https://docs.oasis.camel-ai.org/key_modules/social_agent.mdx). ```python theme={null} from oasis import SocialAgent # Initialize a customized agent agent_1 = SocialAgent( agent_id=0, user_info=user_info, user_info_template=template, agent_graph=agent_graph, # The `AgentGraph` created before model=openai_model, tools=tools, available_actions=available_actions, ) agent_graph.add_agent(agent_1) ``` # Other Methods of `AgentGraph` ## 1. `agent_graph.get_agent(agent_id)` * Description: Get an `SocialAgent` by `agent_id`. * Parameters: * `agent_id`: The `agent_id` of the `SocialAgent` to get. * Returns: * `SocialAgent`: The `SocialAgent` with the given `agent_id`. * Example: ```python theme={null} agent = agent_graph.get_agent(agent_id) ``` ## 2. `agent_graph.get_all_agents()` * Description: Get all `SocialAgent` in the `AgentGraph`. * Parameters: * None * Returns: * list\[tuple\[int, SocialAgent]]: A list of tuples, each containing an `agent_id` and the corresponding `SocialAgent`. * Example: ```python theme={null} agent_list = agent_graph.get_all_agents() ``` ## 3. `agent_graph.get_num_nodes()` * Description: Get the number of `SocialAgent` in the `AgentGraph`. * Parameters: * None * Returns: * int: The number of `SocialAgent` in the `AgentGraph`. * Example: ```python theme={null} num_agents = agent_graph.get_num_nodes() ``` # Environment Source: https://docs.oasis.camel-ai.org/key_modules/environments Configure the fundamental settings for your OASIS simulation environment # Basic Environment Settings OASIS provides a powerful simulation environment for social media platforms. This guide covers the basic configuration options for setting up your simulation environment. ## Environment Initialization To create a simulation environment, use the `make` function from OASIS: ```python theme={null} import oasis from oasis import DefaultPlatformType # Make the environment env = oasis.make( agent_graph=agent_graph, platform=oasis.DefaultPlatformType.REDDIT, database_path="simulation.db", ) ``` ### Core Environment Parameters When initializing the OASIS environment, you can configure the following core parameters: | Parameter | Type | Description | | --------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `agent_graph` | `AgentGraph` | An `AgentGraph` instance that stores all the social agents in the simulation. For more details, see [Agent Graph](https://docs.oasis.camel-ai.org/key_modules/agent_graph) | | `platform` | `DefaultPlatformType` or `Platform` | The platform type to use (`TWITTER` or `REDDIT`) or a custom `Platform` instance | | `database_path` | `str` | Path to create a SQLite database (must end with `.db`) | | `semaphore` | `int` | Limit on concurrent LLM requests (default: 128) | For more details, see the [Platform](https://docs.oasis.camel-ai.org/key_modules/platform), [Agent Profile](https://docs.oasis.camel-ai.org/user_generation/user_generation), [Model](https://docs.oasis.camel-ai.org/key_modules/models) and [Actions](https://docs.oasis.camel-ai.org/key_modules/agent_graph) Module. ## Environment Lifecycle The OASIS environment has a simple lifecycle you can manage with these methods: ```python theme={null} # Initialize the environment await env.reset() # Run simulation steps for _ in range(n): await env.step(actions) # Close the environment when done await env.close() ``` For more action details, see [Actions Module](https://docs.oasis.camel-ai.org/key_modules/actions) # Models Source: https://docs.oasis.camel-ai.org/key_modules/models This section introduces the LLM models of Social Agent in OASIS. # Models OASIS supports all models listed in `camel` here: [https://docs.camel-ai.org/key\_modules/models](https://docs.camel-ai.org/key_modules/models). Note that only models with tool-calling support can successfully perform actions in OASIS. You can pass a `ModelBackend`, `List[ModelBackend]` or `ModelManager` as needed. For example, the OPENAI model: ```python theme={null} from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType from camel.configs import ChatGPTConfig # Define the model, here in this case we use gpt-4o-mini model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, model_config_dict=ChatGPTConfig().as_dict(), ) ``` For the vLLM model, note that to deploy the model with tool-calling capabilities, you should refer to the documentation here: [https://docs.vllm.ai/en/latest/features/tool\_calling.html](https://docs.vllm.ai/en/latest/features/tool_calling.html). ```python theme={null} from camel.models import ModelFactory from camel.types import ModelPlatformType vllm_model = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="microsoft/Phi-3-mini-4k-instruct", url="http://localhost:8000/v1", # Optional model_config_dict={"temperature": 0.0}, # Optional ) ``` For the ModelManager, you can define the scheduling strategy as needed. `round_robin` is the recommended strategy for load balancing on multiple models among agents. ```python theme={null} from camel.models import ModelFactory, ModelManager from camel.types import ModelPlatformType vllm_model_1 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://localhost:8000/v1", # Optional ) vllm_model_2 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://localhost:8001/v1", # Optional ) model_manager = ModelManager( models=[vllm_model_1, vllm_model_2], scheduling_strategy='round_robin', ) ``` # Platform Source: https://docs.oasis.camel-ai.org/key_modules/platform This section introduces how to configure the social platform in OASIS. The Social Platform module is a core component of Oasis that simulates a social media environment for agent interactions. It provides a complete infrastructure for social network activities, including user management, content creation, engagement metrics, recommendation systems, and user interactions. We support passing in two types of platforms. One is the `DefaultPlatformType`, which includes Twitter and Reddit. Otherwise, you can customize the `Platform` settings and pass them in. # Default Platform Type (Recommend) OASIS supports two built-in platform types, which can be specified during environment creation: ## Twitter-like Platform ```python theme={null} env = oasis.make( platform=DefaultPlatformType.TWITTER, database_path="./data/twitter_simulation.db", agent_profile_path="./data/profiles/twitter_users.csv", agent_models=models, available_actions=available_actions, ) ``` The Twitter-like platform simulates a microblogging service with features like posts, likes, retweets, and following. ## Reddit-like Platform ```python theme={null} 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, ) ``` # Customized Platform The platform uses an asynchronous architecture to handle agent actions and maintain a consistent timeline within the simulation. ## Key Features ### Time Management * Configurable time acceleration using `sandbox_clock` * Support for simulated timeline progression ### Database Integration * SQLite-based storage for all social activities and relationships * Comprehensive logging of user actions and system events ### Recommendation Systems Several recommendation system types are supported: * **Random**: Simple randomized content recommendation * **Reddit**: Reddit-style recommendation based on engagement metrics * **Twitter**: Personalized recommendations based on user history * **TWHin**: Advanced recommendation using graph embedding (optional OpenAI embedding integration) ### Social Actions The platform supports a wide range of social media actions. ## Initialization ```python theme={null} 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 ) ``` ### Configuration Options | Parameter | Type | Default | Description | | ------------------------ | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | | `db_path` | str | Required | Path to SQLite database | | `channel` | Any | Channel() | Communication channel for agent interactions | | `sandbox_clock` | Clock | Clock(60) | Time management for the simulation(for reddit recommendation system) | | `start_time` | datetime | datetime.now() | Initial time for the simulation(for reddit recommendation system) | | `show_score` | bool | False | Show combined score (Reddit style) instead of separate likes/dislikes | | `allow_self_rating` | bool | True | Allow users to like/dislike their own content | | `recsys_type` | str/RecsysType | "reddit" | Recommendation system type ("random", "reddit", "twitter", "twhin") | | `refresh_rec_post_count` | int | 1 | Number of posts returned per refresh | | `max_rec_post_len` | int | 2 | Maximum posts per user in recommendation buffer | | `following_post_count` | int | 3 | Number of posts from followed users | | `use_openai_embedding` | bool | False | Use OpenAI embeddings for TWHin recommendation system. If false, use the local TWHIN-BERT model to get embeddings. | ## Recommendation System Different recommendation algorithms can be configured through the `recsys_type` parameter: The available recommendation system types are: | RecsysType | Description | | ------------------ | ---------------------------------------------------------------- | | `TWITTER` | Standard Twitter-like recommendation system | | `TWHIN`(Recommend) | TWHINBert-based recommendation system for Twitter-like platforms | | `REDDIT` | Reddit-style recommendation system | | `RANDOM` | Random content recommendation (for baseline testing) | # Social Agent Source: https://docs.oasis.camel-ai.org/key_modules/social_agent The Social Agent is the main class for creating social agents in the simulation. In this section, we will introduce how to create a `SocialAgent`. # `SocialAgent` class A Social Agent in OASIS is an LLM-based social media user, inherited from CAMEL's `ChatAgent`. It can perform actions on social media (e.g., posting), use external tools (such as Google Search), and has features like user information and a memory module. When initializing a `SocialAgent`, you can configure the following core parameters: | Parameter | Type | Required | Default | Description | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `agent_id` | `int` | βœ” | - | The unique ID of the agent, used as the primary key to distinguish different agents. Each `SocialAgent` must have a unique `agent_id`. | | `user_info` | `UserInfo` | βœ” | - | A dataclass containing the agent's user registration info. For more details, see [UserInfo](#UserInfo). | | `user_info_template` | [`TextPrompt` ](https://docs.camel-ai.org/key_modules/prompts) | βœ— | `None` | A text template that describes the agent when deciding what action to take. If `None`, a [default prompt template](#default-user-info-template) will be selected based on `recsys_type` in `UserInfo`. | | `agent_graph` | [`AgentGraph` ](https://docs.oasis.camel-ai.org//key_modules/agent_graph) | βœ” | - | The `AgentGraph` instance that the `SocialAgent` belongs to. | | `model` | [`BaseModelBackend`](https://docs.camel-ai.org/key_modules/models) or `List[BaseModelBackend]` or [`ModelManager`](https://docs.camel-ai.org/key_modules/models) or `None` | βœ— | `None` | The llm model(s) to be used for the agent's actions. If `None`, the gpt-4o-mini model will be used. | | `available_actions` | [`list[ActionType]`](https://docs.oasis.camel-ai.org/key_modules/actions) or `None` | βœ— | `None` | List of allowed actions in the social platform. For more details, see [Actions Module](https://docs.oasis.camel-ai.org/key_modules/actions). If `None`, all actions are enabled by default. | | `tools` | `List[Union[FunctionTool, Callable]]` or `None` | βœ— | `None` | External tools the agent can use, such as a `get_weather` function, a `Toolkit`, or an `MCPToolkit` from \[CAMEL]\([https://docs.camel-ai.org/key\_modules/tools](https://docs.camel-ai.org/key_modules/tools). If set to `None`, the agent will not be able to use any external tools. | | `single_iteration` | `bool` | βœ— | `True` | Whether the agent performs only a single round of reasoning when taking an LLM action. If `False`, the agent may continue acting based on the outcome of previous actions or tool calls. | | `interview_record` | `bool` | βœ— | `False` | Whether to record the interview prompt and result in the agent's memory. | For more details on the `model` and the `tools` parameter, see [Models Module](https://docs.oasis.camel-ai.org/key_modules/models) and [Toolkits Module](https://docs.oasis.camel-ai.org/key_modules/toolkits). ## `UserInfo` class A dataclass containing the agent's user registration info. Fields like `user_name`, `name`, and `description` must not be empty. The `profile` field is a dictionary whose keys must match those specified in `user_info_template`. ```python theme={null} @dataclass class UserInfo: user_name: str name: str description: str profile: dict[str, Any] # If user_info_template is provided, the keys must match those in the template. recsys_type: RecsysType # Ignored if user_info_template is provided. ``` * Example of a `user_info_template` and corresponding `UserInfo.profile` class: ```python theme={null} 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.", } ``` ## Default User Info Template ### Twitter Style Template ```python theme={null} def to_twitter_system_message(self) -> str: name_string = "" description_string = "" if self.name is not None: name_string = f"Your name is {self.name}." if self.profile is None: description = name_string elif "other_info" not in self.profile: description = name_string elif "user_profile" in self.profile["other_info"]: if self.profile["other_info"]["user_profile"] is not None: user_profile = self.profile["other_info"]["user_profile"] description_string = f"Your have profile: {user_profile}." description = f"{name_string}\n{description_string}" system_content = f""" # OBJECTIVE You're a Twitter user, and I'll present you with some tweets. After you see the tweets, choose some actions from the following functions. # SELF-DESCRIPTION Your actions should be consistent with your self-description and personality. {description} # RESPONSE METHOD Please perform actions by tool calling. """ return system_content ``` ### Reddit Style Template ```python theme={null} def to_reddit_system_message(self) -> str: name_string = "" description_string = "" if self.name is not None: name_string = f"Your name is {self.name}." if self.profile is None: description = name_string elif "other_info" not in self.profile: description = name_string elif "user_profile" in self.profile["other_info"]: if self.profile["other_info"]["user_profile"] is not None: user_profile = self.profile["other_info"]["user_profile"] description_string = f"Your have profile: {user_profile}." description = f"{name_string}\n{description_string}" print(self.profile['other_info']) description += ( f"You are a {self.profile['other_info']['gender']}, " f"{self.profile['other_info']['age']} years old, with an MBTI " f"personality type of {self.profile['other_info']['mbti']} from " f"{self.profile['other_info']['country']}.") system_content = f""" # OBJECTIVE You're a Reddit user, and I'll present you with some posts. After you see the posts, choose some actions from the following functions. # SELF-DESCRIPTION Your actions should be consistent with your self-description and personality. {description} # RESPONSE METHOD Please perform actions by tool calling. """ return system_content ``` # Toolkits Source: https://docs.oasis.camel-ai.org/key_modules/toolkits This section introduces the toolkits of Social Agent in OASIS. # Toolkits OASIS supports all toolkits, mcp toolkits, and customized function tools listed in `camel` here: [https://docs.camel-ai.org/key\_modules/tools](https://docs.camel-ai.org/key_modules/tools). You can pass a `List[Union[FunctionTool, Callable]]` as the set of external tools that the agent is allowed to use in addition to performing social media actions. ## Example ### 1. `SympyToolkit`: For example, you can add the `SympyToolkit` to the `SocialAgent` as follows: ```python theme={null} # Import the SympyToolkit class from camel.tools import SympyToolkit # Create a SocialAgent instance with the sympy tool sympy_agent = SocialAgent( agent_id=1, user_info=user_info, tools=SympyToolkit().get_tools(), # allow agent to use sympy toolkits agent_graph=agent_graph, model=openai_model, available_actions=available_actions, single_iteration=False ) ``` ### 2. `SearchToolkit().search_duckduckgo`: ```python theme={null} # Import the SearchToolkit class from camel.tools import SearchToolkit # Create a SocialAgent instance with the search tool search_agent = SocialAgent( agent_id=2, user_info=user_info, tools=[SearchToolkit().search_duckduckgo], # allow agent to use search toolkits agent_graph=agent_graph, model=openai_model, available_actions=available_actions, single_iteration=False ) ``` ### 3. Your own function tool: Or you can define a custom function for the agent to query specific information β€” for example, letting the agent check whether your cat is sleeping. ```python theme={null} import random from datetime import time, datetime # Define a custom function def is_my_cat_sleep(current_time: datetime) -> bool: r"""Simulate a random check to determine whether your cat is sleeping, based on the current time. Args: current_time (datetime): The current datetime to base the cat's behavior on. Returns: bool: True if the cat is likely sleeping, False otherwise. """ return random.choice([True, False]) # Import the FunctionTool class from camel.toolkits import FunctionTool # Create a SocialAgent instance agent_2 = SocialAgent( agent_id=1, user_info=user_info, tools=[FunctionTool(is_my_cat_sleep)], # allow agent to use custom function tool agent_graph=agent_graph, model=openai_model, available_actions=[ActionType.CREATE_COMMENT], single_iteration=False ) ``` If you want to define other custom functions, make sure your functions include complete docstrings and type annotations β€” just like the example provided. # Overview Source: https://docs.oasis.camel-ai.org/overview Understanding how OASIS works # How OASIS Works ## System Architecture OASIS (Open Agent Social Interaction Simulations) is a comprehensive framework for simulating social media environments with AI agents. At its core, OASIS consists of several integrated components that work together to create realistic social media simulations: OASIS Architecture ### Core Components 1. **Platform**: The central infrastructure that simulates the social media environment (Twitter-like or Reddit-like). It manages user accounts, content, social relationships, and engagement metrics. 2. **Agents**: LLM-powered users that interact within the platform. Each agent has a unique profile and decision-making process driven by large language models. 3. **Actions**: A diverse set of operations agents can perform, such as creating posts, commenting, liking, following, and more. 4. **Recommendation System**: Algorithms that determine what content appears in each agent's feed, similar to real social media platforms. 5. **Simulation Engine**: The orchestration layer that controls the progression of time, activates agents, and manages the overall simulation flow. ## Operational Flow Here's how OASIS operates in a typical simulation: 1. **Initialization**: * The platform is created with specific settings (Twitter-like or Reddit-like) * Agent profiles are loaded from files or variables * LLM models are configured for agent decision-making * Available actions and recommendation systems are defined * Toolkits are defined for agent to get more external information 2. **Simulation Cycle**: * For each simulation step: * Time advances according to the simulation clock * The recommendation system refreshes content feeds * Active agents observe their current state (posts with comments from the recommendation system) * Active agents decide what actions to take based on LLM reasoning or predefined action list * The platform processes these actions and updates the environment 3. **LLM Agent Decision-Making**: * Each agent receives an observation of their current state * The LLM model processes this observation along with the agent's profile * The model decides which action the agent should take * The agent executes the chosen action on the platform 4. **Platform Updates**: * The platform processes all agent actions * Social relationships are updated (following/followers) * Content engagement metrics are recalculated * Recommendation algorithms determine new content for user feeds 5. **Data Collection**: * All actions and interactions are logged in the database * Researchers can analyze this data to study social phenomena ## Scale and Performance OASIS is designed to scale up to one million agents, enabling large-scale studies of social interactions. To achieve this scale: * The system uses efficient database operations for storing and retrieving data * Multiple LLM instances can be deployed for load balancing * Concurrent request limiting prevents overloading LLM services * Time acceleration allows simulating longer periods in less real time ## Customization Options OASIS provides extensive customization options: * **Platform Types**: Choose between Twitter-like or Reddit-like environments * **Recommendation Algorithms**: Configure how content is distributed to agents * **Agent Profiles**: Define diverse user demographics and personalities * **Available Actions**: Control which social actions agents can perform * **Model Selection**: Use different LLM backends for agent decision-making * **Toolkits**: Define toolkits for agent to get more external information ## Integration with LLMs OASIS leverages large language models through the CAMEL framework to power agent decision-making: * Support for OpenAI models (GPT-4, GPT-3.5) * Integration with local open-source models via VLLM * Load balancing across multiple model instances * Customizable prompting for agent reasoning ## Data Analysis The simulation data is stored in a SQLite database, allowing for comprehensive analysis: * Track the spread of information across the network * Analyze group formation and polarization * Study the effects of recommendation algorithms on user behavior * Examine emergent social phenomena ## Use Cases OASIS can be applied to a wide range of research and development scenarios: * Social media platform design and testing * Content moderation policy evaluation * Information spread and misinformation studies * Consumer behavior and marketing research * Community formation and group dynamics analysis By simulating realistic social media environments at scale, OASIS provides a powerful tool for understanding complex social phenomena without the ethical concerns of experimenting on real users. # Quickstart Source: https://docs.oasis.camel-ai.org/quickstart Start using OASIS for social simulations in under 5 minutes ## Setup your environment Learn how to set up OASIS and run your first social simulation. ### Installation You can install OASIS in two ways: ```bash theme={null} pip install camel-oasis ``` ```bash theme={null} 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 ``` ## Running simulations OASIS supports different types of LLM backends for running simulations. Choose the option that works best for your needs. ### Using OpenAI API Add your OpenAI API key to your environment variables: **For Bash (Linux, macOS, Git Bash on Windows):** ```bash theme={null} export OPENAI_API_KEY= export OPENAI_API_BASE_URL= # Optional: for proxy services ``` **For Windows Command Prompt:** ```bash theme={null} set OPENAI_API_KEY= set OPENAI_API_BASE_URL= # Optional: for proxy services ``` **For Windows PowerShell:** ```bash theme={null} $env:OPENAI_API_KEY="" $env:OPENAI_API_BASE_URL="" # Optional: for proxy services ``` If you install with `pip`, download [this file](https://github.com/camel-ai/oasis/blob/main/data/reddit/user_data_36.json) to your own `./data/reddit/user_data_36.json` directory. Execute the Reddit simulation script: ```python theme={null} import asyncio import os from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType import oasis from oasis import (ActionType, LLMAction, ManualAction, generate_reddit_agent_graph) 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.SEARCH_POSTS, ActionType.SEARCH_USER, ActionType.TREND, ActionType.REFRESH, ActionType.DO_NOTHING, ActionType.FOLLOW, ActionType.MUTE, ] agent_graph = await generate_reddit_agent_graph( profile_path="./data/reddit/user_data_36.json", model=openai_model, available_actions=available_actions, ) # 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() actions_1 = {} actions_1[env.agent_graph.get_agent(0)] = [ ManualAction(action_type=ActionType.CREATE_POST, action_args={"content": "Hello, world!"}), ManualAction(action_type=ActionType.CREATE_COMMENT, action_args={ "post_id": "1", "content": "Welcome to the OASIS World!" }) ] actions_1[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_COMMENT, action_args={ "post_id": "1", "content": "I like the OASIS world." }) await env.step(actions_1) actions_2 = { agent: LLMAction() for _, agent in env.agent_graph.get_agents() } # Perform the actions await env.step(actions_2) # Close the environment await env.close() if __name__ == "__main__": asyncio.run(main()) ``` This will start a simulation of user interactions in a Reddit-like environment. ### Using local open-source models with VLLM 1. Install VLLM by following the instructions in the [VLLM repository](https://github.com/vllm-project/vllm) 2. Download a model (e.g., Qwen 2.5) to your local machine: ```bash theme={null} 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" ``` 3. Deploy the VLLM API server: ```bash theme={null} 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 ``` 4. Test if VLLM is correctly deployed: ```bash theme={null} curl http://$ip:$port/v1/models ``` 1. Edit or write the `scripts/environment/twitter_simulation.py` file to use your VLLM deployment: ```python theme={null} 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] ``` 2. Prepare the user profiles: If you install with `pip`, download [this file](https://github.com/camel-ai/oasis/blob/refactor/data/twitter_dataset/anonymous_topic_200_1h/False_Business_0.csv) to your own `data/twitter_dataset/anonymous_topic_200_1h/False_Business_0.csv` directory. 3. Run the Twitter simulation: ```python theme={null} import asyncio import os from camel.models import ModelFactory from camel.types import ModelPlatformType import oasis from oasis import (ActionType, LLMAction, ManualAction, generate_twitter_agent_graph) async def main(): # Define the models for agents. Agents will select models based on # pre-defined scheduling strategies 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] # Define the available actions for the agents available_actions = [ ActionType.CREATE_POST, ActionType.LIKE_POST, ActionType.REPOST, ActionType.FOLLOW, ActionType.DO_NOTHING, ActionType.QUOTE_POST, ] agent_graph = await generate_twitter_agent_graph( profile_path="./data/reddit/user_data_36.json", model=models, 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() 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) 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) actions_3 = {} actions_3[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is not flat."}) await env.step(actions_3) actions_4 = { agent: LLMAction() # get all agents for _, agent in env.agent_graph.get_agents() } await env.step(actions_4) # Close the environment await env.close() if __name__ == "__main__": asyncio.run(main()) ``` # Agent Profile Source: https://docs.oasis.camel-ai.org/user_generation/generation The first step in using OASIS is to generate user data. This section provides a detailed overview of how user data should be prepared for simulation. ## Data Formats OASIS supports multiple social media platforms, each with its own data format. Note that the **type** of data format must align with the **DefaultPlatformType** or **RecsysType** specified for the platform. ### Twitter Format (CSV) For Twitter simulations, OASIS stores user data in CSV files. Each user (agent) requires the following information: | Field | Description | | --------------- | -------------------------------------------------------------------------------------------------------------- | | **name** | The real name of the agent | | **username** | The username of the agent within the system | | **user\_char** | A brief self-description of the agent (included in the agent's system prompt to establish an initial identity) | | **description** | Similar to `user_char`, serving as the agent's self-description | And the `agent_id` will be generated based on the order of the CSV file, starting from 0. #### Example Twitter CSV Format | 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](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](https://t.co/JjnKtEnq4R) | ### Reddit Format (JSON) For Reddit simulations, OASIS uses JSON files to store user data. Each user object contains the following fields: | Field | Description | | ------------ | ----------------------------------------------------------------------------------------------------------------- | | **realname** | The real name of the agent | | **username** | The username of the agent within the Reddit platform | | **bio** | A brief bio displayed on the user's profile | | **persona** | A detailed description of the agent's personality, interests, and background (used for the agent's system prompt) | | **age** | The age of the agent | | **gender** | The gender of the agent | | **mbti** | Myers-Briggs Type Indicator of the agent | | **country** | The country where the agent is based | And the `agent_id` will be generated based on the order of the JSON file, starting from 0. #### Example Reddit JSON Format ```json theme={null} [ { "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" } ] ``` ## Preparing User Data When preparing user data for OASIS, consider the following regardless of platform: 1. **Diverse Personalities**: Create agents with varied interests, opinions, and communication styles to simulate realistic social dynamics. 2. **Realistic Social Connections**: If you want to create a social connection between agents, you can add some [`ManualAction`](https://docs.oasis.camel-ai.org/key_modules/actions.mdx) during the simulation to let agents follow each other. 3. **Initial Content**: If you want to add some initial content to the agents, you can add some [`ManualAction`](https://docs.oasis.camel-ai.org/key_modules/actions.mdx) during the simulation to let agents post some initial content. 4. **Consistent Identity**: Ensure that the personality descriptors (`user_char` and `description` for Twitter; `bio` and `persona` for Reddit) align with the agent's intended personality and behavior in the simulation. 5. **Platform-Specific Behaviors**: Consider how users interact differently on Twitter versus Reddit. Twitter interactions are more brief and public, while Reddit discussions are often topic-focused and community-based. In the next sections, we'll explore how to customize the `SocialAgent` class to create agents with different prompt templates, tools, and models. # Visualization Source: https://docs.oasis.camel-ai.org/visualization/visualization # Data Visualization in Oasis This documentation outlines various visualization techniques and procedures available in the Oasis platform. These visualizations help analyze and interpret simulation results effectively. ## Reddit Score Analysis The Reddit Score Analysis visualization allows you to compare scores between different treatment groups in your simulations. ### Prerequisites * Completed simulation using `scripts/reddit_simulation_align_with_human/reddit_simulation_align_with_human.py` * Generated database file and JSON file from the simulation ### Steps to Generate Visualization 1. **Set up file paths** After running your simulation, modify the file paths in `visualization/reddit_simulation_align_with_human/code/analysis_all.py`: ```python theme={null} if __name__ == "__main__": folder_path = ("visualization/reddit_simulation_align_with_human" "/experiment_results") exp_name = "business_3600" # Use your experiment name 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) ``` 2. **Install dependencies** ```bash theme={null} pip install matplotlib ``` 3. **Run the analysis script** ```bash theme={null} python visualization/reddit_simulation_align_with_human/code/analysis_all.py ``` 4. **Examine Results** The script will generate a visualization showing scores for three treatment groups (down-treated, control, up-treated) at the experiment's conclusion. Reddit Score Analysis Example ## Reddit Counterfactual Content Analysis This visualization helps analyze differences in content across various treatment conditions. ### Prerequisites * OpenAI API key added to environment variables * Completed simulation using `scripts/reddit_simulation_counterfactual/reddit_simulation_counterfactual.py` * Generated database files from the simulation ### Steps to Generate Visualization 1. **Configure database paths** After running your simulation, update the database file paths in `visualization/reddit_simulation_counterfactual/code/analysis_couterfact.py`: ```python theme={null} db_files = [ 'couterfact_up_100.db', 'couterfact_cnotrol_100.db', 'couterfact_down_100.db' ] ``` 2. **Install dependencies** ```bash theme={null} pip install aiohttp ``` 3. **Run the analysis script** ```bash theme={null} python visualization/reddit_simulation_counterfactual/code/analysis_couterfact.py ``` 4. **Examine Results** The script will generate a visualization showing disagree scores for three treatment groups (down-treated, control, up-treated) at each timestep of the experiment. Counterfactual Analysis Example ## Dynamic Follow Network Visualization This visualization provides an interactive way to explore user follow relationships over time using Neo4j. ### Prerequisites * Neo4j account and a free instance * Neo4j credentials (`NEO4J_URI`, `NEO4J_USERNAME`, and `NEO4J_PASSWORD`) saved as environment variables * Completed simulation generating a database file ### Steps to Create Visualization 1. **Set up Neo4j** * Register at [https://neo4j.com/](https://neo4j.com/) * Create a free instance * Obtain and save credentials as environment variables * Connect to the instance 2. **Install dependencies** ```bash theme={null} pip install neo4j ``` 3. **Configure database path** Modify the database path in either: * `visualization/dynamic_follow_network/code/vis_neo4j_reddit.py` (for Reddit data) * `visualization/dynamic_follow_network/code/vis_neo4j_twitter.py` (for Twitter data) ```python theme={null} if __name__ == "__main__": sqlite_db_path = "all_360_follow.db" # Replace with your SQLite database path main(sqlite_db_path) ``` 4. **Run the appropriate script** ```bash theme={null} python visualization/dynamic_follow_network/code/vis_neo4j_reddit.py # or python visualization/dynamic_follow_network/code/vis_neo4j_twitter.py ``` 5. **Explore the visualization** * Visit [https://console.neo4j.io/](https://console.neo4j.io/) dashboard * Use the explore page * In the search bar, select `user-follow-user` * For the slicer, choose `follow-timestamp` to visualize changes in follow relationships over time ## Additional Visualization Options Beyond the core visualization techniques described above, the Oasis platform supports customized visualizations based on specific simulation needs. Developers can extend existing visualization modules or create new ones for specialized analysis requirements. For further assistance with visualization tools or to request additional visualization features, please refer to the project documentation or contact the development team.