### README # Mintlify Starter Kit ### Development Install the [Mintlify CLI](https://www.npmjs.com/package/mintlify) to preview the documentation changes locally. To install, use the following command ``` npm i mintlify ``` Run the following command at the root of your documentation (where docs.json is) ``` mintlify dev ``` **Note:** The `docs.json` file is the core configuration that defines your docs' navigation and layout, making it essential for Mintlify to properly run and preview your site. ### Publishing Changes Our GitHub App is already installed and seamlessly propagates changes from the OASIS repo to https://docs.oasis.camel-ai.org/. Updates are automatically deployed to production whenever changes are pushed to the main branch. ### Troubleshooting - Mintlify dev isn't running - Run `mintlify install` it'll re-install dependencies. - Page loads as a 404 - Make sure you are running in a folder with `docs.json` --- ### Cookbooks/Custom Prompt Simulation --- title: 'Custom Prompt Simulation' description: '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. ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### Cookbooks/Misinformation Spreading --- title: 'Misinformation Spreading' description: 'Comprehensive guide to all available actions in the OASIS simulation environment' --- # Misinformation Spreading This cookbook provides a comprehensive guide to running a misinformation spreading simulation using OASIS. First, we need to download the user profile data. [Download the user profile data](https://drive.google.com/drive/folders/1hs5D8vBj_eMkxR4N7Y-qRnTjTTh3ENFY?usp=sharing) ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### Cookbooks/Reddit Simulation --- title: 'Reddit Simulation' description: '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. ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### Cookbooks/Search Tools Simulation --- title: 'Search Tools Simulation' description: '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. ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### Cookbooks/Sympy Tools Simulation --- title: 'Sympy Tools Simulation' description: '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. ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### Cookbooks/Twitter Interview --- title: 'Interview' description: '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 ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ## 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 # 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 # 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 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 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 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 # 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 ``` --- ### Cookbooks/Twitter Report Post --- title: 'Report Post' description: 'Comprehensive guide to all available actions in the OASIS simulation environment' --- # Report Post This cookbook provides a comprehensive guide to running a Twitter simulation using OASIS, including the post reporting feature. ## Overview The REPORT_POST action type enables you to: - Report inappropriate or harmful content - Track reporting history - Analyze reporting patterns - Maintain platform content quality ## Key Features - **Manual Report Actions**: Use `ManualAction` with `ActionType.REPORT_POST` to report posts - **Automatic Report Tracking**: The system automatically collects and stores report information - **Database Storage**: All report data is stored in the report table for later analysis - **Concurrent Execution**: Reports can be submitted alongside other social media actions - **Warning Message Display**: Warning messages are shown when the number of reports exceeds the threshold ## Important Note The `ActionType.REPORT_POST` should be included in the `available_actions` list when creating your agent graph, as it's a regular social media action that agents can perform. ## Complete Example ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ## How It Works ### 1. Setup and Configuration Include `ActionType.REPORT_POST` in your available actions list: ```python available_actions = [ ActionType.CREATE_POST, ActionType.LIKE_POST, ActionType.REPORT_POST, # Include reporting functionality ActionType.REPOST, ActionType.FOLLOW, ActionType.DO_NOTHING, ] ``` ### 2. Reporting Posts Use `ManualAction` with `ActionType.REPORT_POST` to report posts: ```python # Single report report_action = ManualAction( action_type=ActionType.REPORT_POST, action_args={ "post_id": 1, "report_reason": "This is inappropriate content" }) actions = {env.agent_graph.get_agent(0): report_action} await env.step(actions) ``` ### 3. Multiple Reports in One Step You can have multiple agents report the same post: ```python actions = {} actions[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.REPORT_POST, action_args={ "post_id": 1, "report_reason": "This is spam" }) actions[env.agent_graph.get_agent(2)] = ManualAction( action_type=ActionType.REPORT_POST, action_args={ "post_id": 1, "report_reason": "This is misinformation" }) await env.step(actions) ``` ### 4. Mixing Reports with Other Actions Reports can be submitted alongside regular social media actions: ```python actions = {} # Regular post creation actions[env.agent_graph.get_agent(1)] = ManualAction( action_type=ActionType.CREATE_POST, action_args={"content": "Earth is not flat."}) # Report action actions[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) ``` ## Data Storage and Retrieval ### Database Schema Report data is stored in the `report` table with the following structure: - `report_id`: Unique identifier for the report - `user_id`: The ID of the reporting agent - `post_id`: The ID of the reported post - `report_reason`: The reason for the report - `created_at`: Timestamp of the report ### Retrieving Report Results ```python import sqlite3 import json conn = sqlite3.connect(db_path) cursor = conn.cursor() # Query all report records cursor.execute(""" SELECT report_id, user_id, post_id, report_reason, created_at FROM report ORDER BY created_at DESC """) for report_id, user_id, post_id, reason, timestamp in cursor.fetchall(): print(f"Report {report_id}:") print(f" User: {user_id}") print(f" Post: {post_id}") print(f" Reason: {reason}") print(f" Time: {timestamp}") conn.close() ``` ## Best Practices ### 1. Strategic Reporting Consider these factors when implementing reporting: - Set appropriate reporting thresholds - Monitor reporting frequency - Analyze report reason distribution - Process reported content promptly ### 2. Integration with Other Features The reporting feature can be integrated with other features: - Combine with interview functionality to understand user reactions to reports - Integrate with content moderation systems - Work with user behavior analysis systems ## Common Use Cases 1. **Content Moderation**: - Monitor inappropriate content - Track violations - Maintain platform quality 2. **User Behavior Analysis**: - Analyze reporting patterns - Identify problematic users - Optimize content strategy 3. **Platform Management**: - Automate report processing - Generate report summaries - Develop management strategies --- ### Cookbooks/Twitter Simulation --- title: 'Twitter Simulation' description: '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. ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### Api Reference/Introduction --- title: 'Introduction' description: 'Example section for showcasing API endpoints' --- If you're not looking to build API reference documentation, you can delete this section by removing the api-reference folder. ## Welcome There are two ways to build API documentation: [OpenAPI](https://mintlify.com/docs/api-playground/openapi/setup) and [MDX components](https://mintlify.com/docs/api-playground/mdx/configuration). For the starter kit, we are using the following OpenAPI specification. View the OpenAPI specification file ## Authentication All API endpoints are authenticated using Bearer tokens and picked up from the specification file. ```json "security": [ { "bearerAuth": [] } ] ``` --- ### Essentials/Code --- title: 'Code Blocks' description: 'Display inline code and code blocks' icon: 'code' --- ## Basic ### Inline Code To denote a `word` or `phrase` as code, enclose it in backticks (`). ``` To denote a `word` or `phrase` as code, enclose it in backticks (`). ``` ### Code Block Use [fenced code blocks](https://www.markdownguide.org/extended-syntax/#fenced-code-blocks) by enclosing code in three backticks and follow the leading ticks with the programming language of your snippet to get syntax highlighting. Optionally, you can also write the name of your code after the programming language. ```java HelloWorld.java class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` ````md ```java HelloWorld.java class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` ```` --- ### Essentials/Images --- title: 'Images and Embeds' description: 'Add image, video, and other HTML elements' icon: 'image' --- ## Image ### Using Markdown The [markdown syntax](https://www.markdownguide.org/basic-syntax/#images) lets you add images using the following code ```md ``` Note that the image file size must be less than 5MB. Otherwise, we recommend hosting on a service like [Cloudinary](https://cloudinary.com/) or [S3](https://aws.amazon.com/s3/). You can then use that URL and embed. ### Using Embeds To get more customizability with images, you can also use [embeds](/writing-content/embed) to add images ```html ``` ## Embeds and HTML elements
Mintlify supports [HTML tags in Markdown](https://www.markdownguide.org/basic-syntax/#html). This is helpful if you prefer HTML tags to Markdown syntax, and lets you create documentation with infinite flexibility. ### iFrames Loads another HTML page within the document. Most commonly used for embedding videos. ```html ``` --- ### Essentials/Markdown --- title: 'Markdown Syntax' description: 'Text, title, and styling in standard markdown' icon: 'text-size' --- ## Titles Best used for section headers. ```md ## Titles ``` ### Subtitles Best use to subsection headers. ```md ### Subtitles ``` Each **title** and **subtitle** creates an anchor and also shows up on the table of contents on the right. ## Text Formatting We support most markdown formatting. Simply add `**`, `_`, or `~` around text to format it. | Style | How to write it | Result | | ------------- | ----------------- | --------------- | | Bold | `**bold**` | **bold** | | Italic | `_italic_` | _italic_ | | Strikethrough | `~strikethrough~` | ~strikethrough~ | You can combine these. For example, write `**_bold and italic_**` to get **_bold and italic_** text. You need to use HTML to write superscript and subscript text. That is, add `` or `` around your text. | Text Size | How to write it | Result | | ----------- | ------------------------ | ---------------------- | | Superscript | `superscript` | superscript | | Subscript | `subscript` | subscript | ## Linking to Pages You can add a link by wrapping text in `[]()`. You would write `[link to google](https://google.com)` to [link to google](https://google.com). Links to pages in your docs need to be root-relative. Basically, you should include the entire folder path. For example, `[link to text](/writing-content/text)` links to the page "Text" in our components section. Relative links like `[link to text](../text)` will open slower because we cannot optimize them as easily. ## Blockquotes ### Singleline To create a blockquote, add a `>` in front of a paragraph. > Dorothy followed her through many of the beautiful rooms in her castle. ```md > Dorothy followed her through many of the beautiful rooms in her castle. ``` ### Multiline > Dorothy followed her through many of the beautiful rooms in her castle. > > The Witch bade her clean the pots and kettles and sweep the floor and keep the fire fed with wood. ```md > Dorothy followed her through many of the beautiful rooms in her castle. > > The Witch bade her clean the pots and kettles and sweep the floor and keep the fire fed with wood. ``` ### LaTeX Mintlify supports [LaTeX](https://www.latex-project.org) through the Latex component. 8 x (vk x H1 - H2) = (0,1) ```md 8 x (vk x H1 - H2) = (0,1) ``` --- ### Essentials/Navigation --- title: 'Navigation' description: 'The navigation field in docs.json defines the pages that go in the navigation menu' icon: 'map' --- The navigation menu is the list of links on every website. You will likely update `docs.json` every time you add a new page. Pages do not show up automatically. ## Navigation syntax Our navigation syntax is recursive which means you can make nested navigation groups. You don't need to include `.mdx` in page names. ```json Regular Navigation "navigation": { "tabs": [ { "tab": "Docs", "groups": [ { "group": "Getting Started", "pages": ["quickstart"] } ] } ] } ``` ```json Nested Navigation "navigation": { "tabs": [ { "tab": "Docs", "groups": [ { "group": "Getting Started", "pages": [ "quickstart", { "group": "Nested Reference Pages", "pages": ["nested-reference-page"] } ] } ] } ] } ``` ## Folders Simply put your MDX files in folders and update the paths in `docs.json`. For example, to have a page at `https://yoursite.com/your-folder/your-page` you would make a folder called `your-folder` containing an MDX file called `your-page.mdx`. You cannot use `api` for the name of a folder unless you nest it inside another folder. Mintlify uses Next.js which reserves the top-level `api` folder for internal server calls. A folder name such as `api-reference` would be accepted. ```json Navigation With Folder "navigation": { "tabs": [ { "tab": "Docs", "groups": [ { "group": "Group Name", "pages": ["your-folder/your-page"] } ] } ] } ``` ## Hidden Pages MDX files not included in `docs.json` will not show up in the sidebar but are accessible through the search bar and by linking directly to them. --- ### Essentials/Reusable Snippets --- title: Reusable Snippets description: Reusable, custom snippets to keep content in sync icon: 'recycle' --- import SnippetIntro from '/snippets/snippet-intro.mdx'; ## Creating a custom snippet **Pre-condition**: You must create your snippet file in the `snippets` directory. Any page in the `snippets` directory will be treated as a snippet and will not be rendered into a standalone page. If you want to create a standalone page from the snippet, import the snippet into another file and call it as a component. ### Default export 1. Add content to your snippet file that you want to re-use across multiple locations. Optionally, you can add variables that can be filled in via props when you import the snippet. ```mdx snippets/my-snippet.mdx Hello world! This is my content I want to reuse across pages. My keyword of the day is {word}. ``` The content that you want to reuse must be inside the `snippets` directory in order for the import to work. 2. Import the snippet into your destination file. ```mdx destination-file.mdx --- title: My title description: My Description --- import MySnippet from '/snippets/path/to/my-snippet.mdx'; ## Header Lorem impsum dolor sit amet. ``` ### Reusable variables 1. Export a variable from your snippet file: ```mdx snippets/path/to/custom-variables.mdx export const myName = 'my name'; export const myObject = { fruit: 'strawberries' }; ``` 2. Import the snippet from your destination file and use the variable: ```mdx destination-file.mdx --- title: My title description: My Description --- import { myName, myObject } from '/snippets/path/to/custom-variables.mdx'; Hello, my name is {myName} and I like {myObject.fruit}. ``` ### Reusable components 1. Inside your snippet file, create a component that takes in props by exporting your component in the form of an arrow function. ```mdx snippets/custom-component.mdx export const MyComponent = ({ title }) => (

{title}

... snippet content ...

); ``` MDX does not compile inside the body of an arrow function. Stick to HTML syntax when you can or use a default export if you need to use MDX. 2. Import the snippet into your destination file and pass in the props ```mdx destination-file.mdx --- title: My title description: My Description --- import { MyComponent } from '/snippets/custom-component.mdx'; Lorem ipsum dolor sit amet. ``` --- ### Essentials/Settings --- title: 'Global Settings' description: 'Mintlify gives you complete control over the look and feel of your documentation using the docs.json file' icon: 'gear' --- Every Mintlify site needs a `docs.json` file with the core configuration settings. Learn more about the [properties](#properties) below. ## Properties Name of your project. Used for the global title. Example: `mintlify` An array of groups with all the pages within that group The name of the group. Example: `Settings` The relative paths to the markdown files that will serve as pages. Example: `["customization", "page"]` Path to logo image or object with path to "light" and "dark" mode logo images Path to the logo in light mode Path to the logo in dark mode Where clicking on the logo links you to Path to the favicon image Hex color codes for your global theme The primary color. Used for most often for highlighted content, section headers, accents, in light mode The primary color for dark mode. Used for most often for highlighted content, section headers, accents, in dark mode The primary color for important buttons The color of the background in both light and dark mode The hex color code of the background in light mode The hex color code of the background in dark mode Array of `name`s and `url`s of links you want to include in the topbar The name of the button. Example: `Contact us` The url once you click on the button. Example: `https://mintlify.com/docs` Link shows a button. GitHub shows the repo information at the url provided including the number of GitHub stars. If `link`: What the button links to. If `github`: Link to the repository to load GitHub information from. Text inside the button. Only required if `type` is a `link`. Array of version names. Only use this if you want to show different versions of docs with a dropdown in the navigation bar. An array of the anchors, includes the `icon`, `color`, and `url`. The [Font Awesome](https://fontawesome.com/search?q=heart) icon used to feature the anchor. Example: `comments` The name of the anchor label. Example: `Community` The start of the URL that marks what pages go in the anchor. Generally, this is the name of the folder you put your pages in. The hex color of the anchor icon background. Can also be a gradient if you pass an object with the properties `from` and `to` that are each a hex color. Used if you want to hide an anchor until the correct docs version is selected. Pass `true` if you want to hide the anchor until you directly link someone to docs inside it. One of: "brands", "duotone", "light", "sharp-solid", "solid", or "thin" Override the default configurations for the top-most anchor. The name of the top-most anchor Font Awesome icon. One of: "brands", "duotone", "light", "sharp-solid", "solid", or "thin" An array of navigational tabs. The name of the tab label. The start of the URL that marks what pages go in the tab. Generally, this is the name of the folder you put your pages in. Configuration for API settings. Learn more about API pages at [API Components](/api-playground/demo). The base url for all API endpoints. If `baseUrl` is an array, it will enable for multiple base url options that the user can toggle. The authentication strategy used for all API endpoints. The name of the authentication parameter used in the API playground. If method is `basic`, the format should be `[usernameName]:[passwordName]` The default value that's designed to be a prefix for the authentication input field. E.g. If an `inputPrefix` of `AuthKey` would inherit the default input result of the authentication field as `AuthKey`. Configurations for the API playground Whether the playground is showing, hidden, or only displaying the endpoint with no added user interactivity `simple` Learn more at the [playground guides](/api-playground/demo) Enabling this flag ensures that key ordering in OpenAPI pages matches the key ordering defined in the OpenAPI file. This behavior will soon be enabled by default, at which point this field will be deprecated. A string or an array of strings of URL(s) or relative path(s) pointing to your OpenAPI file. Examples: ```json Absolute "openapi": "https://example.com/openapi.json" ``` ```json Relative "openapi": "/openapi.json" ``` ```json Multiple "openapi": ["https://example.com/openapi1.json", "/openapi2.json", "/openapi3.json"] ``` An object of social media accounts where the key:property pair represents the social media platform and the account url. Example: ```json { "x": "https://x.com/mintlify", "website": "https://mintlify.com" } ``` One of the following values `website`, `facebook`, `x`, `discord`, `slack`, `github`, `linkedin`, `instagram`, `hacker-news` Example: `x` The URL to the social platform. Example: `https://x.com/mintlify` Configurations to enable feedback buttons Enables a button to allow users to suggest edits via pull requests Enables a button to allow users to raise an issue about the documentation Customize the dark mode toggle. Set if you always want to show light or dark mode for new users. When not set, we default to the same mode as the user's operating system. Set to true to hide the dark/light mode toggle. You can combine `isHidden` with `default` to force your docs to only use light or dark mode. For example: ```json Only Dark Mode "modeToggle": { "default": "dark", "isHidden": true } ``` ```json Only Light Mode "modeToggle": { "default": "light", "isHidden": true } ``` A background image to be displayed behind every page. See example with [Infisical](https://infisical.com/docs) and [FRPC](https://frpc.io). --- ### Key Modules/Actions --- title: 'Actions' description: '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 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 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 @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 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 # 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 # 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 action = ManualAction( action=ActionType.CREATE_POST, args={"content": "Hello, OASIS world!"} ) ``` #### LIKE_POST ```python action = ManualAction( action=ActionType.LIKE_POST, args={"post_id": 123} ) ``` #### UNLIKE_POST ```python action = ManualAction( action=ActionType.UNLIKE_POST, args={"post_id": 123} ) ``` #### DISLIKE_POST ```python action = ManualAction( action=ActionType.DISLIKE_POST, args={"post_id": 123} ) ``` #### UNDO_DISLIKE_POST ```python action = ManualAction( action=ActionType.UNDO_DISLIKE_POST, args={"post_id": 123} ) ``` #### REPORT_POST ```python action = ManualAction( action=ActionType.REPORT_POST, args={ "post_id": 123, "report_reason": "This post contains false information" } ) ``` #### REPOST ```python action = ManualAction( action=ActionType.REPOST, args={"post_id": 123} ) ``` #### QUOTE_POST ```python action = ManualAction( action=ActionType.QUOTE_POST, args={"post_id": 123, "quote_content": "This is amazing content!"} ) ``` #### CREATE_COMMENT ```python action = ManualAction( action=ActionType.CREATE_COMMENT, args={"post_id": 123, "content": "Great post! I completely agree."} ) ``` #### LIKE_COMMENT ```python action = ManualAction( action=ActionType.LIKE_COMMENT, args={"comment_id": 456} ) ``` #### UNLIKE_COMMENT ```python action = ManualAction( action=ActionType.UNLIKE_COMMENT, args={"comment_id": 456} ) ``` #### DISLIKE_COMMENT ```python action = ManualAction( action=ActionType.DISLIKE_COMMENT, args={"comment_id": 456} ) ``` #### UNDO_DISLIKE_COMMENT ```python action = ManualAction( action=ActionType.UNDO_DISLIKE_COMMENT, args={"comment_id": 456} ) ``` #### FOLLOW ```python action = ManualAction( action=ActionType.FOLLOW, args={"followee_id": 789} ) ``` #### UNFOLLOW ```python action = ManualAction( action=ActionType.UNFOLLOW, args={"followee_id": 789} ) ``` #### MUTE ```python action = ManualAction( action=ActionType.MUTE, args={"mutee_id": 789} ) ``` #### UNMUTE ```python action = ManualAction( action=ActionType.UNMUTE, args={"mutee_id": 789} ) ``` #### SEARCH_POSTS ```python action = ManualAction( action=ActionType.SEARCH_POSTS, args={"query": "artificial intelligence"} ) ``` #### SEARCH_USER ```python action = ManualAction( action=ActionType.SEARCH_USER, args={"query": "john"} ) ``` #### TREND ```python action = ManualAction( action=ActionType.TREND, args={} ) ``` #### REFRESH ```python action = ManualAction( action=ActionType.REFRESH, args={} ) ``` #### DO_NOTHING ```python action = ManualAction( action=ActionType.DO_NOTHING, args={} ) ``` #### PURCHASE_PRODUCT ```python action = ManualAction( action=ActionType.PURCHASE_PRODUCT, args={"product_name": "Premium Subscription", "purchase_num": 1} ) ``` #### INTERVIEW ```python action = ManualAction( action=ActionType.INTERVIEW, args={"prompt": "What is your name?"} ) ``` #### CREATE_GROUP ```python action = ManualAction( action=ActionType.CREATE_GROUP, args={"group_name": "OASIS Fans"} ) ``` #### JOIN_GROUP ```python action = ManualAction( action=ActionType.JOIN_GROUP, args={"group_id": 1} ) ``` #### LEAVE_GROUP ```python action = ManualAction( action=ActionType.LEAVE_GROUP, args={"group_id": 1} ) ``` #### SEND_TO_GROUP ```python action = ManualAction( action=ActionType.SEND_TO_GROUP, args={"group_id": 1, "message": "Hello, OASIS fans!"} ) ``` #### LISTEN_FROM_GROUP ```python action = ManualAction( action=ActionType.LISTEN_FROM_GROUP, args={} ) ``` --- ### Key Modules/Agent Graph --- title: 'Agent Graph' description: '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 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 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 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 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 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 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 num_agents = agent_graph.get_num_nodes() ``` --- ### Key Modules/Environments --- title: 'Environment' description: '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 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 # 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) --- ### Key Modules/Models --- title: 'Models' description: '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 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. ```python 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 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', ) ``` --- ### Key Modules/Platform --- title: 'Platform' description: '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 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 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 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) | --- ### Key Modules/Recommendation System --- title: 'Recommendation Systems' description: 'Configure the recommendation systems for OASIS simulations' --- # Recommendation Settings OASIS provides various recommendation systems that determine how content is presented to users in the simulation. This guide explains how to configure recommendation settings for your social media platform simulations. ## Recommendation System Types OASIS supports several recommendation system types through the `RecsysType` enum: ```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... ) ``` The available recommendation system types are: | RecsysType | Description | |------------|-------------| | `TWITTER` | Standard Twitter-like recommendation system | | `TWHIN` | TWHINBert-based recommendation system for Twitter-like platforms | | `REDDIT` | Reddit-style recommendation system | | `RANDOM` | Random content recommendation (for baseline testing) | ## Configuring Recommendation Parameters When initializing a `Platform` object, you can configure various recommendation-related parameters: ```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 ) ``` ### Key Recommendation Parameters | Parameter | Type | Description | Default | |-----------|------|-------------|---------| | `recsys_type` | `RecsysType` | The recommendation system algorithm | `"reddit"` | | `refresh_rec_post_count` | `int` | Number of posts returned per refresh | `1` for Twitter, `5` for Reddit | | `max_rec_post_len` | `int` | Maximum number of posts in the recommendation table (buffer) | `2` for Twitter, `100` for Reddit | | `following_post_count` | `int` | Number of posts from followed users to show | `3` | | `use_openai_embedding` | `bool` | Whether to use OpenAI embeddings for content matching | `False` | | `rec_prob` | `float` | Probability balance between random and personalized recommendations | `0.7` | ## Platform-Specific Recommendation Settings ### Twitter-like Platform For Twitter-like platforms, you can use the TwHIN-Bert recommendation system: ```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, ) ``` The TwHIN recommendation system uses embeddings to match content with user interests. ### Reddit-like Platform For Reddit-like platforms, the recommendation system focuses on 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, ) ``` Reddit-style recommendations prioritize posts with higher scores (upvotes minus downvotes). ## Content Visibility Settings ### Score Display The `show_score` parameter determines how content ratings are presented to agents: - `show_score=True`: Shows a single score (likes minus dislikes), Reddit-style - `show_score=False`: Shows likes and dislikes separately, Twitter-style ### Self-Rating The `allow_self_rating` parameter controls whether users can rate their own content: - `allow_self_rating=True`: Users can like/dislike their own posts and comments - `allow_self_rating=False`: Users cannot rate their own content ## Recommendation System Implementation The recommendation systems in OASIS are implemented in the platform's `update_rec_table` method, which uses different algorithms based on the configured `recsys_type`: ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ## Custom Recommendation Systems For advanced use cases, you can implement custom recommendation algorithms by creating a specialized Platform class and overriding the `update_rec_table` method. ## Related Topics - [Basic Environment Settings](/environment_settings/basic_settings) - [Simulation Settings](/environment_settings/simulation_settings) --- ### Key Modules/Social Agent --- title: 'Social Agent' description: '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. 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 @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 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 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 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 ``` --- ### Key Modules/Toolkits --- title: 'Toolkits' description: '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 # 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 # 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 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. --- ### Simulation/Simulation --- title: 'Simulation' description: 'Configure advanced settings for running OASIS simulations' --- # Simulation Settings OASIS provides powerful tools for running social media simulations with AI agents. This guide covers the advanced settings for configuring and running simulations. ## Time Settings OASIS supports flexible time handling for simulations through the `Clock` class. This allows you to control how time progresses in your simulation. ```python from oasis.clock.clock import Clock from datetime import datetime # Create a clock with time magnification factor sandbox_clock = Clock(magnification_factor=60) # 60x speed # Create a platform with the custom clock platform = Platform( db_path="./data/simulation.db", channel=channel, sandbox_clock=sandbox_clock, start_time=datetime.now(), # Set the simulation start time # Additional parameters... ) ``` ### Clock Parameters | Parameter | Type | Description | |-----------|------|-------------| | `magnification_factor` | `int` | How much faster simulation time passes compared to real-time | | `start_time` | `datetime` | The starting time for the simulation (default: current time) | ## Simulation Controls ### Environment Actions You can control the simulation by sending `EnvAction` objects to the environment during each step: ```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) ``` ### Activating Agents You can control which agents are active during each simulation step: - Activate specific agents: `activate_agents=[1, 3, 5, 7, 9]` - Activate all agents: `EnvAction()` (empty action with no parameters) ### Empty Action To simply advance the simulation with all agents active and no interventions: ```python empty_action = EnvAction() # Activate all agents with no intervention await env.step(empty_action) ``` ## Agent Models OASIS supports various LLM backends through the CAMEL framework. You can configure agents to use different models: ```python from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType # Create models for agents openai_model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, ) # Use with multiple models (load balancing) vllm_model_1 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://127.0.0.1:8001", ) vllm_model_2 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://127.0.0.1:8002", ) models = [vllm_model_1, vllm_model_2] # List of models for load balancing # Create environment with the models env = oasis.make( platform=platform, agent_profile_path="./data/profiles/users.csv", agent_models=models, # Pass a single model or list of models available_actions=available_actions, ) ``` ## Agent Profiles OASIS supports different agent profile formats depending on the platform type: ### Twitter Agent Profiles (CSV format) For Twitter-like platforms, agent profiles are typically stored in CSV files: ``` 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 ``` ### Reddit Agent Profiles (JSON format) For Reddit-like platforms, agent profiles are typically stored in JSON format: ```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" } ] ``` ## Limiting Concurrent LLM Requests To prevent overloading the LLM service, you can limit concurrent requests using the `semaphore` parameter: ```python env = oasis.make( platform=platform, agent_profile_path="./data/profiles/users.csv", agent_models=models, available_actions=available_actions, semaphore=32, # Limit to 32 concurrent LLM requests ) ``` ## Complete Simulation Example Here's a complete example of a simulation with all the advanced settings: ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ## Analyzing Simulation Results After running a simulation, the results are stored in the SQLite database specified by `db_path`. You can analyze these results using SQL queries or OASIS's built-in utilities: ```python from oasis.testing.show_db import print_db_contents # Print all database contents print_db_contents("./data/simulation.db") ``` ## Related Topics - [Basic Environment Settings](/environment_settings/basic_settings) - [Recommendation Settings](/environment_settings/recommendation_settings) --- ### Simulation/Simulation Settings --- title: 'Simulation Settings' description: 'Configure advanced settings for running OASIS simulations' --- # Simulation Settings OASIS provides powerful tools for running social media simulations with AI agents. This guide covers the advanced settings for configuring and running simulations. ## Time Settings OASIS supports flexible time handling for simulations through the `Clock` class. This allows you to control how time progresses in your simulation. ```python from oasis.clock.clock import Clock from datetime import datetime # Create a clock with time magnification factor sandbox_clock = Clock(magnification_factor=60) # 60x speed # Create a platform with the custom clock platform = Platform( db_path="./data/simulation.db", channel=channel, sandbox_clock=sandbox_clock, start_time=datetime.now(), # Set the simulation start time # Additional parameters... ) ``` ### Clock Parameters | Parameter | Type | Description | |-----------|------|-------------| | `magnification_factor` | `int` | How much faster simulation time passes compared to real-time | | `start_time` | `datetime` | The starting time for the simulation (default: current time) | ## Simulation Controls ### Environment Actions You can control the simulation by sending `EnvAction` objects to the environment during each step: ```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) ``` ### Activating Agents You can control which agents are active during each simulation step: - Activate specific agents: `activate_agents=[1, 3, 5, 7, 9]` - Activate all agents: `EnvAction()` (empty action with no parameters) ### Empty Action To simply advance the simulation with all agents active and no interventions: ```python empty_action = EnvAction() # Activate all agents with no intervention await env.step(empty_action) ``` ## Agent Models OASIS supports various LLM backends through the CAMEL framework. You can configure agents to use different models: ```python from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType # Create models for agents openai_model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI, model_type=ModelType.GPT_4O_MINI, ) # Use with multiple models (load balancing) vllm_model_1 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://127.0.0.1:8001", ) vllm_model_2 = ModelFactory.create( model_platform=ModelPlatformType.VLLM, model_type="qwen-2", url="http://127.0.0.1:8002", ) models = [vllm_model_1, vllm_model_2] # List of models for load balancing # Create environment with the models env = oasis.make( platform=platform, agent_profile_path="./data/profiles/users.csv", agent_models=models, # Pass a single model or list of models available_actions=available_actions, ) ``` ## Agent Profiles OASIS supports different agent profile formats depending on the platform type: ### Twitter Agent Profiles (CSV format) For Twitter-like platforms, agent profiles are typically stored in CSV files: ``` 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 ``` ### Reddit Agent Profiles (JSON format) For Reddit-like platforms, agent profiles are typically stored in JSON format: ```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" } ] ``` ## Limiting Concurrent LLM Requests To prevent overloading the LLM service, you can limit concurrent requests using the `semaphore` parameter: ```python env = oasis.make( platform=platform, agent_profile_path="./data/profiles/users.csv", agent_models=models, available_actions=available_actions, semaphore=32, # Limit to 32 concurrent LLM requests ) ``` ## Complete Simulation Example Here's a complete example of a simulation with all the advanced settings: ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ## Analyzing Simulation Results After running a simulation, the results are stored in the SQLite database specified by `db_path`. You can analyze these results using SQL queries or OASIS's built-in utilities: ```python from oasis.testing.show_db import print_db_contents # Print all database contents print_db_contents("./data/simulation.db") ``` ## Related Topics - [Basic Environment Settings](/environment_settings/basic_settings) - [Recommendation Settings](/environment_settings/recommendation_settings) --- ### Snippets/Snippet Intro One of the core principles of software development is DRY (Don't Repeat Yourself). This is a principle that apply to documentation as well. If you find yourself repeating the same content in multiple places, you should consider creating a custom snippet to keep your content in sync. --- ### User Generation/Generation --- title: 'Agent Profile' --- 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 | 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 | ### 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 [ { "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/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 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 pip install matplotlib ``` 3. **Run the analysis script** ```bash 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 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 db_files = [ 'couterfact_up_100.db', 'couterfact_cnotrol_100.db', 'couterfact_down_100.db' ] ``` 2. **Install dependencies** ```bash pip install aiohttp ``` 3. **Run the analysis script** ```bash 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. ## 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 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 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 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. --- ### Development --- title: 'Development' description: 'Preview changes locally to update your docs' --- **Prerequisite**: Please install Node.js (version 19 or higher) before proceeding.
Please upgrade to ```docs.json``` before proceeding and delete the legacy ```mint.json``` file.
Follow these steps to install and run Mintlify on your operating system: **Step 1**: Install Mintlify: ```bash npm npm i mintlify ``` ```bash yarn yarn global add mintlify ``` **Step 2**: Navigate to the docs directory (where the `docs.json` file is located) and execute the following command: ```bash mintlify dev ``` A local preview of your documentation will be available at `http://localhost:3000`. ### Custom Ports By default, Mintlify uses port 3000. You can customize the port Mintlify runs on by using the `--port` flag. To run Mintlify on port 3333, for instance, use this command: ```bash mintlify dev --port 3333 ``` If you attempt to run Mintlify on a port that's already in use, it will use the next available port: ```md Port 3000 is already in use. Trying 3001 instead. ``` ## Mintlify Versions Please note that each CLI release is associated with a specific version of Mintlify. If your local website doesn't align with the production version, please update the CLI: ```bash npm npm i mintlify@latest ``` ```bash yarn yarn global upgrade mintlify ``` ## Validating Links The CLI can assist with validating reference links made in your documentation. To identify any broken links, use the following command: ```bash mintlify broken-links ``` ## Deployment Unlimited editors available under the [Pro Plan](https://mintlify.com/pricing) and above. If the deployment is successful, you should see the following: ## Code Formatting We suggest using extensions on your IDE to recognize and format MDX. If you're a VSCode user, consider the [MDX VSCode extension](https://marketplace.visualstudio.com/items?itemName=unifiedjs.vscode-mdx) for syntax highlighting, and [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) for code formatting. ## Troubleshooting This may be due to an outdated version of node. Try the following: 1. Remove the currently-installed version of mintlify: `npm remove -g mintlify` 2. Upgrade to Node v19 or higher. 3. Reinstall mintlify: `npm install mintlify` Solution: Go to the root of your device and delete the \~/.mintlify folder. Afterwards, run `mintlify dev` again. Curious about what changed in the CLI version? [Check out the CLI changelog.](https://www.npmjs.com/package/mintlify?activeTab=versions) --- ### Introduction --- title: Introduction description: "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 --- ### Overview --- title: 'Overview' description: '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 --- title: 'Quickstart' description: '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 pip install camel-oasis ``` ```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 ``` ## 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 export OPENAI_API_KEY= export OPENAI_API_BASE_URL= # Optional: for proxy services ``` **For Windows Command Prompt:** ```bash set OPENAI_API_KEY= set OPENAI_API_BASE_URL= # Optional: for proxy services ``` **For Windows PowerShell:** ```bash $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: ``` /* Detailed source-code truncated for AI context efficiency. */ ``` 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 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 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 curl http://$ip:$port/v1/models ``` 1. Edit or write the `scripts/environment/twitter_simulation.py` file to use your VLLM deployment: ```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] ``` 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: ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### CONTRIBUTING 🏝️ **Welcome to OASIS!** 🏝️ Thank you for your interest in contributing to the OASIS project! 🎉 We're excited to have your support. As an open-source initiative in a rapidly evolving and open-ended field, we wholeheartedly welcome contributions of all kinds. Whether you want to introduce new features, enhance the infrastructure, improve documentation, asking issues, add more examples, implement state-of-the-art research ideas, or fix bugs, we appreciate your enthusiasm and efforts. 🙌 You are welcome to join our [discord](https://discord.com/channels/1115015097560076329/1315102455624892469) or [wechat group](assets/wechatgroup.png) for more efficient communication. 💬 ## Join Our Community 🌍 ### Developer Meeting Time & Link 💻 - English speakers: Coming soon. - Chinese Speakers: Thursday at 10 PM UTC+8. Join via TecentMeeting: [Meeting Link](https://meeting.tencent.com/dm/4D2TCb67tTyB) ### Our Communication Channels 💬 - **Discord:** [Join here](https://discord.com/channels/1115015097560076329/1315102455624892469) - **WeChat:** Scan the QR code [here](assets/wechatgroup.png) ## Guidelines 📝 ### Contributing to the Code 👨‍💻👩‍💻 If you're eager to contribute to this project, that's fantastic! We're thrilled to have your support. - If you are a contributor from the community: - Follow the [Fork-and-Pull-Request](https://docs.github.com/en/get-started/quickstart/contributing-to-projects) workflow when opening your pull requests. - If you are a member of [CAMEL-AI.org](https://github.com/camel-ai) or a collaborator of OASIS: - Follow the [Checkout-and-Pull-Request](https://dev.to/ceceliacreates/how-to-create-a-pull-request-on-github-16h1) workflow when opening your pull request; this will allow the PR to pass all tests that require [GitHub Secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets). Make sure to mention any related issues and tag the relevant maintainers too. 💪 Before your pull request can be merged, it must pass the formatting, linting, and testing checks. You can find instructions on running these checks locally under the **Common Actions** section below. 🔍 Ensuring excellent documentation and thorough testing is absolutely crucial. Here are some guidelines to follow based on the type of contribution you're making: - If you fix a bug: - Add a relevant unit test when possible. These can be found in the `test` directory. - If you make an improvement: - Update any affected example console scripts in the `examples` directory, and documentation in the `docs` directory. - Update unit tests when relevant. - If you add a feature: - Include unit tests in the `test` directory. - Add a demo script in the `examples` directory. We're a small team focused on building great things. If you have something in mind that you'd like to add or modify, opening a pull request is the ideal way to catch our attention. 🚀 ### Contributing to Code Reviews 🔍 This part outlines the guidelines and best practices for conducting code reviews in OASIS. The aim is to ensure that all contributions are of high quality, align with the project's goals, and are consistent with our coding standards. #### Purpose of Code Reviews - Maintain Code Quality: Ensure that the codebase remains clean, readable, and maintainable. - Knowledge Sharing: Facilitate knowledge sharing among contributors and help new contributors learn best practices. - Bug Prevention: Catch potential bugs and issues before they are merged into the main branch. - Consistency: Ensure consistency in style, design patterns, and architecture across the project. #### Review Process Overview - Reviewers should check the code for functionality, readability, consistency, and compliance with the project’s coding standards. - If changes are necessary, the reviewer should leave constructive feedback. - The contributor addresses feedback and updates the PR. - The reviewer re-reviews the updated code. - Once the code is approved by at least one reviewer, it can be merged into the main branch. - Merging should be done by a maintainer or an authorized contributor. #### Code Review Checklist - Functionality - Correctness: Does the code perform the intended task? Are edge cases handled? - Testing: Is there sufficient test coverage? Do all tests pass? - Security: Are there any security vulnerabilities introduced by the change? - Performance: Does the code introduce any performance regressions? - Code Quality - Readability: Is the code easy to read and understand? Is it well-commented where necessary? - Maintainability: Is the code structured in a way that makes future changes easy? - Style: Does the code follow the project’s style guidelines? Currently we use Ruff for format check and take [Google Python Style Guide](%22https://google.github.io/styleguide/pyguide.html%22) as reference. - Documentation: Are public methods, classes, and any complex logic well-documented? - Design - Consistency: Does the code follow established design patterns and project architecture? - Modularity: Are the changes modular and self-contained? Does the code avoid unnecessary duplication? - Dependencies: Are dependencies minimized and used appropriately? #### Reviewer Responsibilities - Timely Reviews: Reviewers should strive to review PRs promptly to keep the project moving. - Constructive Feedback: Provide feedback that is clear, constructive, and aimed at helping the contributor improve. - Collaboration: Work with the contributor to address any issues and ensure the final code meets the project’s standards. - Approvals: Only approve code that you are confident meets all the necessary criteria. #### Common Pitfalls - Large PRs: Avoid submitting PRs that are too large. Break down your changes into smaller, manageable PRs if possible. - Ignoring Feedback: Address all feedback provided by reviewers, even if you don’t agree with it—discuss it instead of ignoring it. - Rushed Reviews: Avoid rushing through reviews. Taking the time to thoroughly review code is critical to maintaining quality. Code reviews are an essential part of maintaining the quality and integrity of our open source project. By following these guidelines, we can ensure that OASIS remains robust, secure, and easy to maintain, while also fostering a collaborative and welcoming community. ### Guideline for Writing Docstrings This guideline will help you write clear, concise, and structured docstrings for contributing to `OASIS`. #### 1. Use the Triple-Quoted String with `r"""` (Raw String) Begin the docstring with `r"""` to indicate a raw docstring. This prevents any issues with special characters and ensures consistent formatting. #### 2. Provide a Brief Class or Method Description - Start with a concise summary of the purpose and functionality. - Keep each line under `79` characters. - The summary should start on the first line without a linebreak. Example: ```python r"""Class for managing conversations of OASIS Agents. """ ``` #### 3. Document Parameters in the Args Section - Use an `Args`: section for documenting constructor or function parameters. - Maintain the `79`-character limit for each line, and indent continuation lines by 4 spaces. - Follow this structure: - Parameter Name: Match the function signature. - Type: Include the type (e.g., `int`, `str`, custom types like `BaseModelBackend`). - Description: Provide a brief explanation of the parameter's role. - Default Value: Use (`default: :obj:`) to indicate default values. Example: ```markdown 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`) ``` ### Principles 🛡️ #### Naming Principle: Avoid Abbreviations in Naming - Abbreviations can lead to ambiguity, especially since variable names and code in OASIS are directly used by agents. - Use clear, descriptive names that convey meaning without requiring additional explanation. This improves both human readability and the agent's ability to interpret the code. Examples: - Bad: msg_win_sz - Good: message_window_size By adhering to this principle, we ensure that OASIS remains accessible and unambiguous for both developers and AI agents. #### Logging Principle: Use `logger` Instead of `print` Avoid using `print` for output. Use Python's `logging` module (`logger`) to ensure consistent, configurable, and professional logging. Examples: - Bad: ```python print("Process started") print(f"User input: {user_input}") ``` - Good: ```python Args: logger.info("Process started") logger.debug(f"User input: {user_input}") ``` ### Board Item Create Workflow 🛠️ At OASIS, we manage our project through a structured workflow that ensures efficiency and clarity in our development process. Our workflow includes stages for issue creation and pull requests (PRs), sprint planning, and reviews. #### Issue Item Stage: Our [issues](https://github.com/camel-ai/oasis/issues) page on GitHub is regularly updated with bugs, improvements, and feature requests. We have a handy set of labels to help you sort through and find issues that interest you. Feel free to use these labels to keep things organized. When you start working on an issue, please assign it to yourself so that others know it's being taken care of. If you're unable to assign it to yourself because you're not an OASIS collaborator, feel free to leave a comment on the issue instead. When creating a new issue, it's best to keep it focused on a specific bug, improvement, or feature. If two issues are related or blocking each other, it's better to link them instead of merging them into one. We do our best to keep these issues up to date, but considering the fast-paced nature of this field, some may become outdated. If you come across any such issues, please give us a heads-up so we can address them promptly. 👀 Here’s how to engage with our issues effectively: - Go to [GitHub Issues](https://github.com/camel-ai/oasis/issues), create a new issue, choose the category, and fill in the required information. - Ensure the issue has a proper title and update the Assignees, Labels, Projects (select Backlog status), Development, and Milestones. - Discuss the issue during team meetings, then move it to the Analysis Done column. - At the beginning of each sprint, share the analyzed issue and move it to the Sprint Planned column if you are going to work on this issue in the sprint. #### Pull Request Item Stage: - Go to [GitHub Pulls](https://github.com/camel-ai/oasis/pulls), create a new PR, choose the branch, and fill in the information, linking the related issue. - Ensure the PR has a proper title and update the Reviewers (convert to draft), Assignees, Labels, Projects (select Developing status), Development, and Milestones. - If the PR is related to a roadmap, link the roadmap to the PR. - Move the PR item through the stages: Developing, Stuck, Reviewing (click ready for review), Merged. The linked issue will close automatically when the PR is merged. **Labeling PRs:** - **feat**: For new features (e.g., `feat: Add new AI model`) - **fix**: For bug fixes (e.g., `fix: Resolve memory leak issue`) - **docs**: For documentation updates (e.g., `docs: Update contribution guidelines`) - **style**: For code style changes (e.g., `style: Refactor code formatting`) - **refactor**: For code refactoring (e.g., `refactor: Optimize data processing`) - **test**: For adding or updating tests (e.g., `test: Add unit tests for new feature`) - **chore**: For maintenance tasks (e.g., `chore: Update dependencies`) ### Sprint Planning & Review 🎯 #### Definition Sprint planning defines what can be delivered in the sprint and how it will be achieved. Sprint review allows stakeholders to review and provide feedback on recent work. #### Practice - **Sprint Duration**: Four weeks for development and review. - **Sprint Planning & Review**: Conducted biweekly during the dev meeting (around 30 minutes). - **Planning**: Founder highlights the sprint goal and key points; developers pick items for the sprint. - **Review**: Feedback on delivered features and identification of improvement areas. ### Getting Help 🆘 Our aim is to make the developer setup as straightforward as possible. If you encounter any challenges during the setup process, don't hesitate to reach out to a maintainer. We're here to assist you and ensure that the experience is smooth not just for you but also for future contributors. 😊 In line with this, we do have specific guidelines for code linting, formatting, and documentation in the codebase. If you find these requirements difficult or even just bothersome to work with, please feel free to get in touch with a maintainer — you can *@doudou_wu in Discord or @张再斌 in the WeChat group*. We don't want these guidelines to hinder the integration of good code into the codebase, so we're more than happy to provide support and find a solution that works for you. 🤝 ## Quick Start 🚀 To get started with OASIS, follow these steps: ```sh # Clone github repo git clone https://github.com/camel-ai/oasis.git # Change directory into project directory cd oasis # Install oasis from source (this will create the virtual environment if needed) poetry install # Activate oasis virtual environment eval $(poetry env activate) # The following command installs a pre-commit hook into the local git repo, # so every commit gets auto-formatted and linted. pre-commit install # Run oasis's pre-commit before push pre-commit run --all-files # Run oasis's unit tests pytest test # Exit the virtual environment deactivate # Alternative: You can also use 'poetry run' prefix without activating the environment # poetry run pytest test ``` These commands will install all the necessary dependencies for running the package, examples, linting, formatting, tests, and coverage. To verify that everything is set up correctly, run `pytest .` This will ensure that all tests pass successfully. ✅ > \[!TIP\] > You need to config OPENAI API Keys as environment variables to pass all tests. ## Common Actions 🔄 ### Update dependencies Whenever you add, update, or delete any dependencies in `pyproject.toml`, please run `poetry lock` to synchronize the dependencies with the lock file. ### Coverage 📊 Code coverage measures the extent to which unit tests cover the code, helping identify both robust and less robust areas of the codebase. To generate a report showing the current code coverage, execute one of the following commands. To include all source files into coverage: ```bash coverage erase coverage run --source=. -m pytest . coverage html # Open htmlcov/index.html ``` To include only tested files: ```bash pytest --cov --cov-report=html ``` The coverage report will be generated at `htmlcov/index.html`. ### Tests 🧪 Currently, the test setup requires an OpenAI API key to test the framework, making them resemble integration tests. - For Bash shell (Linux, macOS, Git Bash on Windows):\*\* ```bash # Export your OpenAI API key export OPENAI_API_KEY= ``` - For Windows Command Prompt:\*\* ```cmd REM export your OpenAI API key set OPENAI_API_KEY= ``` To run all tests including those that use OpenAI API, use the following command: ```bash pytest . ``` ## Documentation 📚 ### Contribute to Documentation 📝 We use [Mintlify](https://mintlify.com/) for documentation. We kindly request that you provide comprehensive documentation for all classes and methods to ensure high-quality documentation coverage. ### Build Documentation Locally 🛠️ To build the documentation locally, follow these steps: 1. Install the Mintlify CLI: ```sh npm install mintlify ``` 1. Navigate to `docs` Directory: ```sh cd docs ``` 1. Run the Mintlify development server: ```sh mintlify dev ``` This will start a local server where you can preview your changes. More guidelines about building and hosting documentations locally can be found [here](https://github.com/camel-ai/oasis/tree/main/docs/README.md). ## Versioning and Release 🚀 As of now, OASIS is actively under development and the latest version has been published to PyPI. OASIS follows the [semver](https://semver.org/) versioning standard. As pre-1.0 software, even patch releases may contain [non-backwards-compatible changes](https://semver.org/#spec-item-4). Currently, the major version is 0, and the minor version is incremented. Releases are made once the maintainers feel that a significant body of changes has accumulated. ## License 📜 The source code of the OASIS project is licensed under Apache 2.0. Your contributed code will be also licensed under Apache 2.0 by default. To add license to you code, you can manually copy-paste it from `license_template.txt` to the head of your files or run the `update_license.py` script to automate the process: ```bash python licenses/update_license.py . licenses/license_template.txt ``` This script will add licenses to all the `*.py` files or update the licenses if the existing licenses are not the same as `license_template.txt`. ## Giving Credit 🎉 If your contribution has been included in a release, we'd love to give you credit on Twitter, Reddit, or Rednote (小红书)—but only if you're comfortable with it! If you have accounts on any of these platforms that you would like us to mention, please let us know either in the pull request or through another communication method. We want to make sure you receive proper recognition for your valuable contributions. 😄 --- ### README

OASIS: Open Agent Social Interaction Simulations with One Million Agents

[![Documentation][docs-image]][docs-url] [![Discord][discord-image]][discord-url] [![X][x-image]][x-url] [![Reddit][reddit-image]][reddit-url] [![Wechat][wechat-image]][wechat-url] [![Wechat][oasis-image]][oasis-url] [![Hugging Face][huggingface-image]][huggingface-url] [![Star][star-image]][star-url] [![Package License][package-license-image]][package-license-url]

[Community](https://github.com/camel-ai/camel#community) | [Paper](https://arxiv.org/abs/2411.11581) | [Examples](https://github.com/camel-ai/oasis/tree/main/examples) | [Dataset](https://huggingface.co/datasets/echo-yiyiyi/oasis-dataset) | [Citation](https://github.com/camel-ai/oasis#-citation) | [Contributing](https://github.com/camel-ai/oasis#-contributing-to-oasis) | [CAMEL-AI](https://www.camel-ai.org/)


🏝️ OASIS is a scalable, open-source social media simulator that incorporates large language model 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.


🌟 Star OASIS on GitHub and be instantly notified of new releases.

Star

## ✨ Key Features ### 📈 Scalability OASIS supports simulations of up to ***one million agents***, enabling studies of social media dynamics at a scale comparable to real-world platforms. ### 📲 Dynamic Environments Adapts to real-time changes in social networks and content, mirroring the fluid dynamics of platforms like **Twitter** and **Reddit** for authentic simulation experiences. ### 👍🏼 Diverse Action Spaces Agents can perform **23 actions**, such as following, commenting, and reposting, allowing for rich, multi-faceted interactions. ### 🔥 Integrated Recommendation Systems Features **interest-based** and **hot-score-based recommendation algorithms**, simulating how users discover content and interact within social media platforms.
## 📺 Demo Video ### Introducing OASIS: Open Agent Social Interaction Simulations with One Million Agents https://github.com/user-attachments/assets/3bd2553c-d25d-4d8c-a739-1af51354b15a
For more showcaes: - Can 1,000,000 AI agents simulate social media? [→Watch demo](https://www.youtube.com/watch?v=lprGHqkApus&t=2s)
## 🎯 Usecase ## ⚙️ Quick Start 1. **Install the OASIS package:** Installing OASIS is a breeze thanks to its availability on PyPI. Simply open your terminal and run: ```bash pip install camel-oasis ``` 2. **Set up your OpenAI API key:** ```bash # For Bash shell (Linux, macOS, Git Bash on Windows): export OPENAI_API_KEY= # For Windows Command Prompt: set OPENAI_API_KEY= ``` 3. **Prepare the agent profile file:** Create the profile you want to assign to the agent. As an example, you can download [user_data_36.json](https://github.com/camel-ai/oasis/blob/main/data/reddit/user_data_36.json) and place it in your local `./data/reddit` folder. 4. **Run the following Python code:** ``` /* Detailed source-code truncated for AI context efficiency. */ ```
> \[!TIP\] > For more detailed instructions and additional configuration options, check out the [documentation](https://docs.oasis.camel-ai.org/). ### 💰 Token Consumption Reference To help you estimate costs before running a simulation, here is a measured reference for token consumption: | Parameter | Value | | ---------------------- | ---------- | | Number of Agents | 100 | | Activation Probability | 1 | | Time Steps | 1 | | Input Tokens | 335,600 | | Output Tokens | 16,750 | | Model | QWEN_TURBO | > \[!NOTE\] > Token usage scales with the number of agents, activation probability, and time steps. Use this reference as a baseline to estimate the cost of larger simulations. Estimated cost for 1 time step, activation probability 0.1 (Qwen pricing as of 2024-12-14): | Model | 100 Agents | 1,000 Agents | 10,000 Agents | | --------- | ---------- | ------------ | ------------- | | qwen-plus | ¥0.026848 | ¥0.26848 | ¥2.6848 | | qwen-max | ¥0.717 | ¥7.717 | ¥77.17 | ### More Tutorials To discover how to create profiles for large-scale users, as well as how to visualize and analyze social simulation data once your experiment concludes, please refer to [More Tutorials](examples/experiment/user_generation_visualization.md) for detailed guidance.
Tutorial Overview
## 📢 News ### Upcoming Features & Contributions > We welcome community contributions! Join us in building these exciting features. - [Support Multi Modal Platform](https://github.com/camel-ai/oasis/issues/47) ### Latest Updates 📢 Update the camel-ai version to 0.2.78 and update the dataset HuggingFace link. - 📆 December 4, 2025 - Add the report post action to mark inappropriate content. - 📆 June 8, 2025 - Add features for creating group chats, sending messages in group chats, and leaving group chats. - 📆 June 6, 2025 - Support Interview Action for asking agents specific questions and getting answers. - 📆 June 2, 2025 - Support customization of each agent's models, tools, and prompts; refactor the interface to follow the PettingZoo style. - 📆 May 22, 2025 - Refactor into the OASIS environment, publish camel-oasis on PyPI, and release the documentation. - 📆 April 24, 2025 - Support OPENAI Embedding model for Twhin-Bert Recommendation System. - 📆 March 25, 2025 ... - Slightly refactoring the database to add Quote Action and modify Repost Action - 📆 January 13, 2025 - Added the demo video and oasis's star history in the README - 📆 January 5, 2025 - Introduced an Electronic Mall on the Reddit platform - 📆 December 5, 2024 - OASIS initially released on arXiv - 📆 November 19, 2024 - OASIS GitHub repository initially launched - 📆 November 19, 2024 ## 🔎 Follow-up Research - [MultiAgent4Collusion](https://github.com/renqibing/MultiAgent4Collusion): multi-agent collusion simulation framework in social systems - [CUBE](https://github.com/echo-yiyiyi/cube): dynamic simulations in customized unity3D-based environments - [MultiAgent4Fraud](https://github.com/zheng977/MutiAgent4Fraud): financial fraud risks by collaborative LLM agents on social platforms - More to come... If your research is based on OASIS, we'd be happy to feature your work here—feel free to reach out or submit a pull request to add it to the [README](https://github.com/camel-ai/oasis/blob/main/README.md)! ## 🥂 Contributing to OASIS🏝️ > We greatly appreciate your interest in contributing to our open-source initiative. To ensure a smooth collaboration and the success of contributions, we adhere to a set of contributing guidelines similar to those established by CAMEL. For a comprehensive understanding of the steps involved in contributing to our project, please refer to the OASIS [contributing guidelines](https://github.com/camel-ai/oasis/blob/master/CONTRIBUTING.md). 🤝🚀 > > An essential part of contributing involves not only submitting new features with accompanying tests (and, ideally, examples) but also ensuring that these contributions pass our automated pytest suite. This approach helps us maintain the project's quality and reliability by verifying compatibility and functionality. ## 📬 Community & Contact If you're keen on exploring new research opportunities or discoveries with our platform and wish to dive deeper or suggest new features, we're here to talk. Feel free to get in touch for more details at camel.ai.team@gmail.com.
- Join us ([*Discord*](https://discord.camel-ai.org/) or [*WeChat*](https://ghli.org/camel/wechat.png)) in pushing the boundaries of finding the scaling laws of agents. - Join WechatGroup for further discussions!
WeChat Group QR Code
## 🌟 Star History [](https://star-history.com/#camel-ai/oasis&Date) ## 🔗 Citation ``` @misc{yang2024oasisopenagentsocial, title={OASIS: Open Agent Social Interaction Simulations with One Million Agents}, author={Ziyi Yang and Zaibin Zhang and Zirui Zheng and Yuxian Jiang and Ziyue Gan and Zhiyu Wang and Zijian Ling and Jinsong Chen and Martz Ma and Bowen Dong and Prateek Gupta and Shuyue Hu and Zhenfei Yin and Guohao Li and Xu Jia and Lijun Wang and Bernard Ghanem and Huchuan Lu and Chaochao Lu and Wanli Ouyang and Yu Qiao and Philip Torr and Jing Shao}, year={2024}, eprint={2411.11581}, archivePrefix={arXiv}, primaryClass={cs.CL}, url={https://arxiv.org/abs/2411.11581}, } ``` ## 🙌 Acknowledgment We would like to thank Douglas for designing the logo of our project. ## 🖺 License The source code is licensed under Apache 2.0. [discord-image]: https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb [discord-url]: https://discord.camel-ai.org/ [docs-image]: https://img.shields.io/badge/Documentation-EB3ECC [docs-url]: https://docs.oasis.camel-ai.org/ [huggingface-image]: https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-CAMEL--AI-ffc107?color=ffc107&logoColor=white [huggingface-url]: https://huggingface.co/camel-ai [oasis-image]: https://img.shields.io/badge/WeChat-OASISProject-brightgreen?logo=wechat&logoColor=white [oasis-url]: ./assets/wechatgroup.png [package-license-image]: https://img.shields.io/badge/License-Apache_2.0-blue.svg [package-license-url]: https://github.com/camel-ai/oasis/blob/main/licenses/LICENSE [reddit-image]: https://img.shields.io/reddit/subreddit-subscribers/CamelAI?style=plastic&logo=reddit&label=r%2FCAMEL&labelColor=white [reddit-url]: https://www.reddit.com/r/CamelAI/ [star-image]: https://img.shields.io/github/stars/camel-ai/oasis?label=stars&logo=github&color=brightgreen [star-url]: https://github.com/camel-ai/oasis/stargazers [wechat-image]: https://img.shields.io/badge/WeChat-CamelAIOrg-brightgreen?logo=wechat&logoColor=white [wechat-url]: ./assets/wechat.JPGwechat.jpg [x-image]: https://img.shields.io/twitter/follow/CamelAIOrg?style=social [x-url]: https://x.com/CamelAIOrg ---