oasis

GitHub

🏝️ OASIS: Open Agent Social Interaction Simulations with One Million Agents.

RAW Doc

README

Mintlify Starter Kit

Development

Install the Mintlify CLI to preview the documentation changes locally. To install, use the following command

text
npm i mintlify

Run the following command at the root of your documentation (where docs.json is)

text
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.

text
/ 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

text
/ 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.

text
/ 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.

text
/ 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.

text
/ 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

text
/ 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

text
/ 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.

text
/ Detailed source-code truncated for AI context efficiency. /

---

Api Reference/Introduction

---
title: 'Introduction'
description: 'Example section for showcasing API endpoints'
---

<Note>
If you're not looking to build API reference documentation, you can delete
this section by removing the api-reference folder.
</Note>

Welcome

There are two ways to build API documentation: OpenAPI and MDX components. For the starter kit, we are using the following OpenAPI specification.

<Card
title="Plant Store Endpoints"
icon="leaf"
href="https://github.com/mintlify/starter/blob/main/api-reference/openapi.json"

View the OpenAPI specification file

</Card>

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 ().

text
To denote a word or phrase as code, enclose it in backticks ().

Code Block

Use 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!");
}
}

text
md
``java HelloWorld.java
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
text

---

Essentials/Images

---
title: 'Images and Embeds'
description: 'Add image, video, and other HTML elements'
icon: 'image'
---

<img
style={{ borderRadius: '0.5rem' }}
src="https://mintlify-assets.b-cdn.net/bigbend.jpg"
/>

Image

Using Markdown

The markdown syntax 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 or S3. You can then use that URL and embed.

Using Embeds

To get more customizability with images, you can also use embeds to add images

html
<img height="200" src="/path/image.jpg" />

Embeds and HTML elements

<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/4KzFe50RQkQ"
title="YouTube video player"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
style={{ width: '100%', borderRadius: '0.5rem' }}
></iframe>

<br />

<Tip>

Mintlify supports HTML tags in Markdown. This is helpful if you prefer HTML tags to Markdown syntax, and lets you create documentation with infinite flexibility.

</Tip>

iFrames

Loads another HTML page within the document. Most commonly used for embedding videos.

html
<iframe src="https://www.youtube.com/embed/4KzFe50RQkQ"> </iframe>

---

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

<Tip>

Each title and subtitle creates an anchor and also shows up on the table of contents on the right.

</Tip>

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 <sup> or <sub> around your text.

| Text Size | How to write it | Result |
| ----------- | ------------------------ | ---------------------- |
| Superscript | <sup>superscript</sup> | <sup>superscript</sup> |
| Subscript | <sub>subscript</sub> | <sub>subscript</sub> |

Linking to Pages

You can add a link by wrapping text in [](). You would write link to google to link to google.

Links to pages in your docs need to be root-relative. Basically, you should include the entire folder path. For example, link to text links to the page "Text" in our components section.

Relative links like link to 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 through the Latex component.

<Latex>8 x (vk x H1 - H2) = (0,1)</Latex>

md
<Latex>8 x (vk x H1 - H2) = (0,1)</Latex>

---

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.

Our navigation syntax is recursive which means you can make nested navigation groups. You don't need to include .mdx in page names.

<CodeGroup>

``json Regular Navigation
"navigation": {
"tabs": [
{
"tab": "Docs",
"groups": [
{
"group": "Getting Started",
"pages": ["quickstart"]
}
]
}
]
}

text
json Nested Navigation
"navigation": {
"tabs": [
{
"tab": "Docs",
"groups": [
{
"group": "Getting Started",
"pages": [
"quickstart",
{
"group": "Nested Reference Pages",
"pages": ["nested-reference-page"]
}
]
}
]
}
]
}
text
</CodeGroup>

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.

<Warning>

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.

</Warning>

json Navigation With Folder
"navigation": {
"tabs": [
{
"tab": "Docs",
"groups": [
{
"group": "Group Name",
"pages": ["your-folder/your-page"]
}
]
}
]
}
text

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';

<SnippetIntro />

Creating a custom snippet

Pre-condition: You must create your snippet file in the snippets directory.

<Note>
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.
</Note>

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}.
text
<Warning>
The content that you want to reuse must be inside the
snippets directory in
order for the import to work.
</Warning>

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';

Lorem impsum dolor sit amet.

<MySnippet word="bananas" />

text

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' };

text
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}.

text

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 }) => (
<div>
<h1>{title}</h1>
<p>... snippet content ...</p>
</div>
);
text
<Warning>
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.
</Warning>

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.

<MyComponent title={'Custom title'} />

text
---

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 below.

Properties

<ResponseField name="name" type="string" required>
Name of your project. Used for the global title.

Example: mintlify

</ResponseField>

<ResponseField name="navigation" type="Navigation[]" required>
An array of groups with all the pages within that group
<Expandable title="Navigation">
<ResponseField name="group" type="string">
The name of the group.

Example: Settings

</ResponseField>
<ResponseField name="pages" type="string[]">
The relative paths to the markdown files that will serve as pages.

Example: ["customization", "page"]

</ResponseField>

</Expandable>
</ResponseField>

<ResponseField name="logo" type="string or object">
Path to logo image or object with path to "light" and "dark" mode logo images
<Expandable title="Logo">
<ResponseField name="light" type="string">
Path to the logo in light mode
</ResponseField>
<ResponseField name="dark" type="string">
Path to the logo in dark mode
</ResponseField>
<ResponseField name="href" type="string" default="/">
Where clicking on the logo links you to
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="favicon" type="string">
Path to the favicon image
</ResponseField>

<ResponseField name="colors" type="Colors">
Hex color codes for your global theme
<Expandable title="Colors">
<ResponseField name="primary" type="string" required>
The primary color. Used for most often for highlighted content, section
headers, accents, in light mode
</ResponseField>
<ResponseField name="light" type="string">
The primary color for dark mode. Used for most often for highlighted
content, section headers, accents, in dark mode
</ResponseField>
<ResponseField name="dark" type="string">
The primary color for important buttons
</ResponseField>
<ResponseField name="background" type="object">
The color of the background in both light and dark mode
<Expandable title="Object">
<ResponseField name="light" type="string" required>
The hex color code of the background in light mode
</ResponseField>
<ResponseField name="dark" type="string" required>
The hex color code of the background in dark mode
</ResponseField>
</Expandable>
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="topbarLinks" type="TopbarLink[]">
Array of
names and urls of links you want to include in the topbar
<Expandable title="TopbarLink">
<ResponseField name="name" type="string">
The name of the button.

Example: Contact us
</ResponseField>
<ResponseField name="url" type="string">
The url once you click on the button. Example:
https://mintlify.com/docs
</ResponseField>

</Expandable>
</ResponseField>

<ResponseField name="topbarCtaButton" type="Call to Action">
<Expandable title="Topbar Call to Action">
<ResponseField name="type" type={'"link" or "github"'} default="link">
Link shows a button. GitHub shows the repo information at the url provided including the number of GitHub stars.
</ResponseField>
<ResponseField name="url" type="string">
If
link: What the button links to.

If github: Link to the repository to load GitHub information from.
</ResponseField>
<ResponseField name="name" type="string">
Text inside the button. Only required if
type is a link.
</ResponseField>

</Expandable>
</ResponseField>

<ResponseField name="versions" type="string[]">
Array of version names. Only use this if you want to show different versions
of docs with a dropdown in the navigation bar.
</ResponseField>

<ResponseField name="anchors" type="Anchor[]">
An array of the anchors, includes the
icon, color, and url.
<Expandable title="Anchor">
<ResponseField name="icon" type="string">
The Font Awesome icon used to feature the anchor.

Example: comments
</ResponseField>
<ResponseField name="name" type="string">
The name of the anchor label.

Example: Community
</ResponseField>
<ResponseField name="url" type="string">
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.
</ResponseField>
<ResponseField name="color" type="string">
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.
</ResponseField>
<ResponseField name="version" type="string">
Used if you want to hide an anchor until the correct docs version is selected.
</ResponseField>
<ResponseField name="isDefaultHidden" type="boolean" default="false">
Pass
true if you want to hide the anchor until you directly link someone to docs inside it.
</ResponseField>
<ResponseField name="iconType" default="duotone" type="string">
One of: "brands", "duotone", "light", "sharp-solid", "solid", or "thin"
</ResponseField>

</Expandable>
</ResponseField>

<ResponseField name="topAnchor" type="Object">
Override the default configurations for the top-most anchor.
<Expandable title="Object">
<ResponseField name="name" default="Documentation" type="string">
The name of the top-most anchor
</ResponseField>
<ResponseField name="icon" default="book-open" type="string">
Font Awesome icon.
</ResponseField>
<ResponseField name="iconType" default="duotone" type="string">
One of: "brands", "duotone", "light", "sharp-solid", "solid", or "thin"
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="tabs" type="Tabs[]">
An array of navigational tabs.
<Expandable title="Tabs">
<ResponseField name="name" type="string">
The name of the tab label.
</ResponseField>
<ResponseField name="url" type="string">
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.
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="api" type="API">
Configuration for API settings. Learn more about API pages at API Components.
<Expandable title="API">
<ResponseField name="baseUrl" type="string">
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.
</ResponseField>

<ResponseField name="auth" type="Auth">
<Expandable title="Auth">
<ResponseField name="method" type='"bearer" | "basic" | "key"'>
The authentication strategy used for all API endpoints.
</ResponseField>
<ResponseField name="name" type="string">
The name of the authentication parameter used in the API playground.

If method is basic, the format should be [usernameName]:[passwordName]
</ResponseField>
<ResponseField name="inputPrefix" type="string">
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.
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="playground" type="Playground">
Configurations for the API playground

<Expandable title="Playground">
<ResponseField name="mode" default="show" type='"show" | "simple" | "hide"'>
Whether the playground is showing, hidden, or only displaying the endpoint with no added user interactivity
simple

Learn more at the playground guides
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="maintainOrder" type="boolean">
Enabling this flag ensures that key ordering in OpenAPI pages matches the key ordering defined in the OpenAPI file.

<Warning>This behavior will soon be enabled by default, at which point this field will be deprecated.</Warning>
</ResponseField>

</Expandable>
</ResponseField>

<ResponseField name="openapi" type="string | string[]">
A string or an array of strings of URL(s) or relative path(s) pointing to your
OpenAPI file.

Examples:
<CodeGroup>

json Absolute
"openapi": "https://example.com/openapi.json"
text
json Relative
"openapi": "/openapi.json"
text
json Multiple
"openapi": ["https://example.com/openapi1.json", "/openapi2.json", "/openapi3.json"]
text
</CodeGroup>

</ResponseField>

<ResponseField name="footerSocials" type="FooterSocials">
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"
}
text
<Expandable title="FooterSocials">
<ResponseField name="[key]" type="string">
One of the following values
website, facebook, x, discord, slack, github, linkedin, instagram, hacker-news

Example: x
</ResponseField>
<ResponseField name="property" type="string">
The URL to the social platform.

Example: https://x.com/mintlify
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="feedback" type="Feedback">
Configurations to enable feedback buttons

<Expandable title="Feedback">
<ResponseField name="suggestEdit" type="boolean" default="false">
Enables a button to allow users to suggest edits via pull requests
</ResponseField>
<ResponseField name="raiseIssue" type="boolean" default="false">
Enables a button to allow users to raise an issue about the documentation
</ResponseField>
</Expandable>
</ResponseField>

<ResponseField name="modeToggle" type="ModeToggle">
Customize the dark mode toggle.
<Expandable title="ModeToggle">
<ResponseField name="default" type={'"light" or "dark"'}>
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.
</ResponseField>
<ResponseField name="isHidden" type="boolean" default="false">
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:

<CodeGroup>

json Only Dark Mode
"modeToggle": {
"default": "dark",
"isHidden": true
}
text
json Only Light Mode
"modeToggle": {
"default": "light",
"isHidden": true
}
text
</CodeGroup>

</ResponseField>

</Expandable>
</ResponseField>

<ResponseField name="backgroundImage" type="string">
A background image to be displayed behind every page. See example with
Infisical and FRPC.
</ResponseField>

---

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]]]
text
- 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)

text

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

text
- 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)

text
For more details about the ActionType and corresponding arguments, please refer to the 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()
text
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()
text
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!"}
)
text
#### LIKE_POST
python
action = ManualAction(
action=ActionType.LIKE_POST,
args={"post_id": 123}
)
text
#### UNLIKE_POST
python
action = ManualAction(
action=ActionType.UNLIKE_POST,
args={"post_id": 123}
)
text
#### DISLIKE_POST
python
action = ManualAction(
action=ActionType.DISLIKE_POST,
args={"post_id": 123}
)
text
#### UNDO_DISLIKE_POST
python
action = ManualAction(
action=ActionType.UNDO_DISLIKE_POST,
args={"post_id": 123}
)
text
#### REPORT_POST
python
action = ManualAction(
action=ActionType.REPORT_POST,
args={
"post_id": 123,
"report_reason": "This post contains false information"
}
)
text
#### REPOST
python
action = ManualAction(
action=ActionType.REPOST,
args={"post_id": 123}
)
text
#### QUOTE_POST
python
action = ManualAction(
action=ActionType.QUOTE_POST,
args={"post_id": 123, "quote_content": "This is amazing content!"}
)
text
#### CREATE_COMMENT
python
action = ManualAction(
action=ActionType.CREATE_COMMENT,
args={"post_id": 123, "content": "Great post! I completely agree."}
)
text
#### LIKE_COMMENT
python
action = ManualAction(
action=ActionType.LIKE_COMMENT,
args={"comment_id": 456}
)
text
#### UNLIKE_COMMENT
python
action = ManualAction(
action=ActionType.UNLIKE_COMMENT,
args={"comment_id": 456}
)
text
#### DISLIKE_COMMENT
python
action = ManualAction(
action=ActionType.DISLIKE_COMMENT,
args={"comment_id": 456}
)
text
#### UNDO_DISLIKE_COMMENT
python
action = ManualAction(
action=ActionType.UNDO_DISLIKE_COMMENT,
args={"comment_id": 456}
)
text
#### FOLLOW
python
action = ManualAction(
action=ActionType.FOLLOW,
args={"followee_id": 789}
)
text
#### UNFOLLOW
python
action = ManualAction(
action=ActionType.UNFOLLOW,
args={"followee_id": 789}
)
text
#### MUTE
python
action = ManualAction(
action=ActionType.MUTE,
args={"mutee_id": 789}
)
text
#### UNMUTE
python
action = ManualAction(
action=ActionType.UNMUTE,
args={"mutee_id": 789}
)
text
#### SEARCH_POSTS
python
action = ManualAction(
action=ActionType.SEARCH_POSTS,
args={"query": "artificial intelligence"}
)
text
#### SEARCH_USER
python
action = ManualAction(
action=ActionType.SEARCH_USER,
args={"query": "john"}
)
text
#### TREND
python
action = ManualAction(
action=ActionType.TREND,
args={}
)
text
#### REFRESH
python
action = ManualAction(
action=ActionType.REFRESH,
args={}
)
text
#### DO_NOTHING
python
action = ManualAction(
action=ActionType.DO_NOTHING,
args={}
)
text
#### PURCHASE_PRODUCT
python
action = ManualAction(
action=ActionType.PURCHASE_PRODUCT,
args={"product_name": "Premium Subscription", "purchase_num": 1}
)
text
#### INTERVIEW
python
action = ManualAction(
action=ActionType.INTERVIEW,
args={"prompt": "What is your name?"}
)
text
#### CREATE_GROUP
python
action = ManualAction(
action=ActionType.CREATE_GROUP,
args={"group_name": "OASIS Fans"}
)
text
#### JOIN_GROUP
python
action = ManualAction(
action=ActionType.JOIN_GROUP,
args={"group_id": 1}
)
text
#### LEAVE_GROUP
python
action = ManualAction(
action=ActionType.LEAVE_GROUP,
args={"group_id": 1}
)
text
#### SEND_TO_GROUP
python
action = ManualAction(
action=ActionType.SEND_TO_GROUP,
args={"group_id": 1, "message": "Hello, OASIS fans!"}
)
text
#### LISTEN_FROM_GROUP
python
action = ManualAction(
action=ActionType.LISTEN_FROM_GROUP,
args={}
)
text
---

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 section. |
|
model | BaseModelBackend or List[BaseModelBackend] or ModelManager | βœ— | 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,
)

text
- 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,
)

text

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()
text

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.
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)
text

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)
text

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()
text

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()
text
---

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",
)
text

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|
|
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, Agent Profile, Model and Actions 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()
text
For more action details, see Actions Module

---

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.

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(),
)
text
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
)

text
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',
)

text
---

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,
)
text
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,
)
text

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
)
text

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...
)
text
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
)

text

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,
)
text
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,
)
text
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. /
text

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.

- Basic 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. |
|
user_info_template | TextPrompt | βœ— | None | A text template that describes the agent when deciding what action to take. If None, a default prompt template will be selected based on recsys_type in UserInfo. |
|
agent_graph | AgentGraph | βœ” | - | The AgentGraph instance that the SocialAgent belongs to. |
|
model | BaseModelBackend or List[BaseModelBackend] or ModelManager 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. 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 , 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" target="_blank" rel="noopener noreferrer">CAMEL and Toolkits Module.

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.
text
- 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.",
}

text

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
text

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
text
---

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.

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
)
text

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
)
text

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
)
text
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...
)
text

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)
text

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)
text

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,
)
text

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
text

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"
}
]
text

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
)
text

Complete Simulation Example

Here's a complete example of a simulation with all the advanced settings:


/ Detailed source-code truncated for AI context efficiency. /
text

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")
text

- Basic 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...
)
text

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)
text

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)
text

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,
)
text

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
text

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"
}
]
text

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
)
text

Complete Simulation Example

Here's a complete example of a simulation with all the advanced settings:


/ Detailed source-code truncated for AI context efficiency. /
text

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")
text

- Basic 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"
}
]
text

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 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 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)
text
2. Install dependencies
bash
pip install matplotlib
text
3. Run the analysis script
bash
python visualization/reddit_simulation_align_with_human/code/analysis_all.py
text
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'
]
text
2. Install dependencies
bash
pip install aiohttp
text
3. Run the analysis script
bash
python visualization/reddit_simulation_counterfactual/code/analysis_couterfact.py
text
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/
- Create a free instance
- Obtain and save credentials as environment variables
- Connect to the instance

2. Install dependencies

bash
pip install neo4j
text
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)
text
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
text
5. Explore the visualization

- Visit 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'
---

<Info>
Prerequisite: Please install Node.js (version 19 or higher) before proceeding. <br />
Please upgrade to

docs.json
` before proceeding and delete the legacy `mint.json` file.
</Info>

Follow these steps to install and run Mintlify on your operating system:

Step 1: Install Mintlify:

<CodeGroup>

`bash npm
npm i mintlify

text
bash yarn
yarn global add mintlify
text
</CodeGroup>

Step 2: Navigate to the docs directory (where the docs.json file is located) and execute the following command:

bash
mintlify dev
text
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
text
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.
text

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:

<CodeGroup>

bash npm
npm i mintlify@latest
text
bash yarn
yarn global upgrade mintlify
text
</CodeGroup>

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
text

Deployment

<Tip>
Unlimited editors available under the Pro
Plan
and above.
</Tip>

If the deployment is successful, you should see the following:

<Frame>
<img src="/images/checks-passed.png" style={{ borderRadius: '0.5rem' }} />
</Frame>

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 for syntax highlighting, and Prettier for code formatting.

Troubleshooting

<AccordionGroup>
<Accordion title='Error: Could not load the "sharp" module using the darwin-arm64 runtime'>

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
</Accordion>

<Accordion title="Issue: Encountering an unknown error">

Solution: Go to the root of your device and delete the \~/.mintlify folder. Afterwards, run mintlify dev again.
</Accordion>
</AccordionGroup>

Curious about what changed in the CLI version? Check out the CLI changelog.

---

Introduction

---
title: Introduction
description: "Welcome to OASIS: Open Agent Social Interaction Simulations with One Million Agents"
---

<img
className="block dark:hidden"
src="/images/oasis_intro.png"
alt="Hero Light"
/>
<img
className="hidden dark:block"
src="/images/oasis_intro.png"
alt="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.

<img
className="block"
src="/images/oasis_main.png"
alt="OASIS Main"
/>

Key Features

<CardGroup cols={2}>
<Card
title="Scalability"
icon="chart-line"
href="https://github.com/camel-ai/oasis/blob/main/oasis/social_agent/agent.py"
>
Supports simulations of up to <b>one million agents</b>, enabling studies of social media dynamics at a scale comparable to real-world platforms
</Card>
<Card
title="Dynamic Environments"
icon="mobile-screen"
href="https://github.com/camel-ai/oasis/blob/main/oasis/social_platform/platform.py"
>
Adapts to real-time changes in social networks and content, mirroring the fluid dynamics of platforms like <b>Twitter</b> and <b>Reddit</b> for authentic simulation experiences
</Card>
<Card
title="Diverse Action Spaces"
icon="thumbs-up"
href="https://github.com/camel-ai/oasis/blob/main/oasis/social_agent/agent_action.py"
>
Agents can perform <b>23 different actions</b>, such as following, commenting, reposting, and quoting for rich, multi-faceted interactions
</Card>
<Card
title="Recommendation Systems"
icon="fire"
href="https://github.com/camel-ai/oasis/blob/main/oasis/social_platform/recsys.py"
>
Features <b>interest-based</b> and <b>hot-score-based</b> recommendation algorithms, simulating how users discover content on real social media platforms
</Card>
</CardGroup>

Use Cases

<CardGroup cols={2}>
<Card
title="Research Simulations"
icon="flask"
href="https://arxiv.org/abs/2411.11581"
>
Study complex social phenomena like information spread, group polarization, and collective behavior at scale
</Card>
<Card
title="Interactive Environments"
icon="users"
href="https://arxiv.org/abs/2411.11581"
>
Create dynamic environments for testing human-agent interactions and social dynamics
</Card>
<Card
title="Content Creation"
icon="pen-to-square"
href="https://arxiv.org/abs/2411.11581"
>
Generate realistic social media content and interactions for creative or educational purposes
</Card>
<Card
title="Behavior Prediction"
icon="chart-simple"
href="https://arxiv.org/abs/2411.11581"
>
Model and predict how information and behaviors might spread through social networks
</Card>
</CardGroup>

Getting Started

Learn how to set up and use OASIS for your social simulation needs.

<CardGroup cols={2}>
<Card
title="Installation"
icon="download"
href="https://docs.oasis.camel-ai.org/quickstart"
>
Get OASIS set up on your local environment with our step-by-step guide
</Card>
<Card
title="Tutorials"
icon="book-open"
href="https://docs.oasis.camel-ai.org/user_generation/generation"
>
Learn how to create user profiles and run your first simulation
</Card>
<Card
title="Documentation"
icon="file-code"
href="https://docs.oasis.camel-ai.org"
>
Explore the full capabilities of OASIS through our comprehensive docs
</Card>
<Card
title="Community"
icon="users"
href="https://github.com/camel-ai/oasis"
>
Join our Discord, Reddit, X, and WeChat groups to connect with other OASIS users
</Card>
</CardGroup>

Resources

<CardGroup cols={2}>
<Card
title="Research Paper"
icon="file-lines"
href="https://arxiv.org/abs/2411.11581"
>
Read the foundational research paper detailing OASIS methodology and findings
</Card>
<Card
title="Example Scripts"
icon="code"
href="https://github.com/camel-ai/oasis/tree/main/examples"
>
Explore example scripts for running various types of simulations
</Card>
<Card
title="Dataset"
icon="database"
href="https://huggingface.co/datasets/oasis-agent/oasis-dataset"
>
Access our comprehensive dataset of agent interactions on Hugging Face
</Card>
<Card
title="Demo Videos"
icon="video"
href="https://www.youtube.com/watch?v=wjLHrdZ1Smk"
>
Watch demonstrations of OASIS capabilities and simulation examples
</Card>
</CardGroup>

---

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:

<img
className="block"
src="/images/oasis_architecture.jpg"
alt="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:

<AccordionGroup>
<Accordion icon="download" title="Option 1: Install via pip">

bash
pip install camel-oasis
text
</Accordion>
<Accordion icon="github" title="Option 2: Clone the repository">
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

text
</Accordion>
</AccordionGroup>

Running simulations

OASIS supports different types of LLM backends for running simulations. Choose the option that works best for your needs.

Using OpenAI API

<AccordionGroup>
<Accordion icon="key" title="Set up your API key">
Add your OpenAI API key to your environment variables:

For Bash (Linux, macOS, Git Bash on Windows):

bash
export OPENAI_API_KEY=<insert your OpenAI API key>
export OPENAI_API_BASE_URL=<insert your OpenAI API BASE URL> # Optional: for proxy services
text
For Windows Command Prompt:
bash
set OPENAI_API_KEY=<insert your OpenAI API key>
set OPENAI_API_BASE_URL=<insert your OpenAI API BASE URL> # Optional: for proxy services
text
For Windows PowerShell:
bash
$env:OPENAI_API_KEY="<insert your OpenAI API key>"
$env:OPENAI_API_BASE_URL="<insert your OpenAI API BASE URL>" # Optional: for proxy services
text
</Accordion>
<Accordion icon="face-smile" title="Prepare the user profiles">
If you install with
pip, download this file to your own ./data/reddit/user_data_36.json directory.
</Accordion>
<Accordion icon="play" title="Run a Reddit simulation">
Execute the Reddit simulation script:

/ Detailed source-code truncated for AI context efficiency. /
text
This will start a simulation of user interactions in a Reddit-like environment.
</Accordion>
</AccordionGroup>

Using local open-source models with VLLM

<AccordionGroup>
<Accordion icon="server" title="Set up VLLM">
1. Install VLLM by following the instructions in the VLLM repository

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"

text
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
text
4. Test if VLLM is correctly deployed:
bash
curl http://$ip:$port/v1/models
text
</Accordion>
<Accordion icon="play" title="Run a Twitter simulation with local 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]
text
2. Prepare the user profiles:
If you install with
pip, download this file 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. /
text
</Accordion>
</AccordionGroup>

---

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 or wechat group for more efficient communication. πŸ’¬

Join Our Community 🌍

- English speakers: Coming soon.
- Chinese Speakers: Thursday at 10 PM UTC+8. Join via TecentMeeting: Meeting Link

Our Communication Channels πŸ’¬

- Discord: Join here
- WeChat: Scan the QR code here

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 workflow when opening your pull requests.
- If you are a member of CAMEL-AI.org or a collaborator of OASIS:
- Follow the Checkout-and-Pull-Request workflow when opening your pull request; this will allow the PR to pass all tests that require GitHub 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 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.
"""
text
#### 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:<default_value>) 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)
text

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}")
text
- Good:
python
Args:
logger.info("Process started")
logger.debug(f"User input: {user_input}")
text

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 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, 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, 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


text
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


text
To include only tested files:
bash
pytest --cov --cov-report=html
text
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=<insert your OpenAI API key>
text
- For Windows Command Prompt:\\
cmd
REM export your OpenAI API key
set OPENAI_API_KEY=<insert your OpenAI API key>
text
To run all tests including those that use OpenAI API, use the following command:
bash
pytest .
text

Documentation πŸ“š

Contribute to Documentation πŸ“

We use Mintlify 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
text
1. Navigate to docs Directory:
sh
cd docs
text
1. Run the Mintlify development server:
sh
mintlify dev
text
This will start a local server where you can preview your changes.

More guidelines about building and hosting documentations locally can be found here.

Versioning and Release πŸš€

As of now, OASIS is actively under development and the latest version has been published to PyPI.

OASIS follows the semver versioning standard. As pre-1.0 software, even patch releases may contain non-backwards-compatible changes. 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
text
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

<div align="center">
<a href="https://www.camel-ai.org/">
<img src="assets/banner.png" alt=banner>
</a>
</div>

</br>

<div align="center">

<h1> OASIS: Open Agent Social Interaction Simulations with One Million Agents
</h1>

[![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]

<h4 align="center">

Community |
Paper |
Examples |
Dataset |
Citation |
Contributing |
CAMEL-AI

</h4>

</div>

<br>

<p align="left">
<img src='assets/intro.png'>

🏝️ 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.

</p>

<br>

<div align="center">
🌟 Star OASIS on GitHub and be instantly notified of new releases.
</div>

<br>

<div align="center">
<img src="assets/star.gif" alt="Star" width="196" height="52">
</a>
</div>

<br>

✨ 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.

<br>

πŸ“Ί Demo Video

Introducing OASIS: Open Agent Social Interaction Simulations with One Million Agents

https://github.com/user-attachments/assets/3bd2553c-d25d-4d8c-a739-1af51354b15a

<br>

For more showcaes:

- Can 1,000,000 AI agents simulate social media?
β†’Watch demo

<br>

🎯 Usecase

<div align="left">
<img src="assets/research_simulation.png" alt=usecase1>
<img src="assets/interaction.png" alt=usecase2>
<a href="http://www.matrix.eigent.ai">
<img src="assets/content_creation.png" alt=usecase3>
</a>
<img src="assets/prediction.png" alt=usecase4>
</div>

βš™οΈ 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
text
2. Set up your OpenAI API key:
bash

For Bash shell (Linux, macOS, Git Bash on Windows):


export OPENAI_API_KEY=<insert your OpenAI API key>

For Windows Command Prompt:


set OPENAI_API_KEY=<insert your OpenAI API key>
text
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 and place it in your local ./data/reddit folder.

4. Run the following Python code:


/ Detailed source-code truncated for AI context efficiency. /
text
<br>

\[!TIP\]

For more detailed instructions and additional configuration options, check out the documentation.

πŸ’° 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 for detailed guidance.

<div align="center">
<img src="assets/tutorial.png" alt="Tutorial Overview">
</div>

πŸ“’ News

Upcoming Features & Contributions

We welcome community contributions! Join us in building these exciting features.

- Support Multi Modal Platform

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: multi-agent collusion simulation framework in social systems
- CUBE: dynamic simulations in customized unity3D-based environments
- MultiAgent4Fraud: 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!

πŸ₯‚ 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. πŸ€πŸš€

> 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 [email protected].

<br>

- Join us (Discord or WeChat) in pushing the boundaries of finding the scaling laws of agents.

- Join WechatGroup for further discussions!

<div align="">
<img src="assets/wechatgroup.png" alt="WeChat Group QR Code" width="600">
</div>

🌟 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

---