đ« CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
Auto-update documentation after merge [skip ci]
camel-docs-bot5ad7603cbc23
diff --git a/docs/cookbooks/multi_agent_society/agents_society.md b/docs/cookbooks/multi_agent_society/agents_society.mdnew file mode 100644index 000000000..4908f6888--- /dev/null+++ b/docs/cookbooks/multi_agent_society/agents_society.md@@ -0,0 +1,200 @@+---+title: "Develop Trading Bot with Role Playing"+---++You can also check this cookbook in colab [here](https://drive.google.com/file/d/17_m8BPMSh4f9mmdYP2PLQCU639aGFSBj/view?usp=sharing)++â <i>Star us on [*Github*](https://github.com/camel-ai/camel), join our [*Discord*](https://discord.camel-ai.org) or follow our [*X*](https://x.com/camelaiorg)</i>++### 1. Concept++The society module is one of the core modules of CAMEL. By simulating the information exchange process, this module studies the social behaviors among agents.++Currently, the society module aims to enable agents to collaborate autonomously toward completing tasks while keeping consistent with human intentions and requiring minimal human intervention. It includes `RolePlaying`, which is used to run the interaction behaviors of agents to achieve objectives.++Taking `RolePlaying` as an example, this framework was designed in an instruction-following manner. These roles independently undertake the responsibilities of executing and planning tasks, respectively. The dialogue is continuously advanced through a turn-taking mechanism, thereby collaborating to complete tasks. The main concepts include:++- Task: a task can be as simple as an idea, initialized by an inception prompt.++- AI User: the agent who is expected to provide instructions.++- AI Assistant: the agent who is expected to respond with solutions that fulfill the instructions.++### 2. Types++#### 2.1 `RolePlaying`++`RolePlaying` is a unique cooperative agent framework of CAMEL. Through this framework, agents in CAMEL overcome numerous challenges, such as *role flipping*, *assistant repeats instructions*, *flake replies*, *infinite loop of messages*, and *conversation termination conditions.*++When using `RolePlaying` framework in CAMEL, predefined prompts are used to create unique initial settings for different agents. For example, if the user wants to initialize an assistant agent, the agent will be initialized with the following prompt.+++- Never forget you are a `ASSISTANT_ROLE` and I am a `USER_ROLE`.++ *This assigns the chosen role to the assistant agent and provides it with information about the userâs role.*+- Never flip roles! Never instruct me!++ *This prevents agents from flipping roles. In some cases, we have observed the assistant and the user switching roles, where the assistant suddenly takes control and instructs the user, and the user follows those instructions.*+- You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.++ *This prohibits the agent from producing harmful, false, illegal, and misleading information.*+- Unless I say the task is completed, you should always start with: Solution: `<YOUR_SOLUTION>`. `<YOUR_SOLUTION>` should be specific, and provide preferable implementations and examples for task-solving.++ *This encourages the assistant to always responds in a consistent format, avoiding any deviation from the structure of the conversation, and preventing vague or incomplete responses, which we refer to as flake responses, such as "I will do something".*+- Always end your solution with: Next request.++ *This ensures that the assistant keeps the conversation going by requesting a new instruction to solve.*++#### `RolePlaying` Attributes+++| Attribute | Type | Description |+| --- | --- | --- |+| assistant_role_name | str | The name of the role played by the assistant. |+| user_role_name | str | The name of the role played by the user. |+| critic_role_name | str | The name of the role played by the critic. |+| task_prompt | str | A prompt for the task to be performed. |+| with_task_specify | bool | Whether to use a task specify agent. |+| with_task_planner | bool | Whether to use a task planner agent. |+| with_critic_in_the_loop | bool | Whether to include a critic in the loop. |+| critic_criteria | str | Critic criteria for the critic agent. |+| model | BaseModelBackend | The model backend to use for generating responses. |+| task_type | TaskType | The type of task to perform. |+| assistant_agent_kwargs | Dict | Additional arguments to pass to the assistant agent. |+| user_agent_kwargs | Dict | Additional arguments to pass to the user agent. |+| task_specify_agent_kwargs | Dict | Additional arguments to pass to the task specify agent. |+| task_planner_agent_kwargs | Dict | Additional arguments to pass to the task planner agent. |+| critic_kwargs | Dict | Additional arguments to pass to the critic. |+| sys_msg_generator_kwargs | Dict | Additional arguments to pass to the system message generator. |+| extend_sys_msg_meta_dicts | List[Dict] | A list of dicts to extend the system message meta dicts with. |+| extend_task_specify_meta_dict | Dict | A dict to extend the task specify meta dict with. |+| output_language | str | The language to be output by the agents. |++## 3. Get Started++### Installation++Ensure you have CAMEL AI installed in your Python environment:+++```python+!pip install "camel-ai==0.2.16"+```++### Setting Up API Keys++You'll need to set up your API keys for OpenAI.+++```python+import os+from getpass import getpass++# Prompt for the API key securely+openai_api_key = getpass('Enter your API key: ')+os.environ["OPENAI_API_KEY"] = openai_api_key+```++Alternatively, if running on Colab, you could save your API keys and tokens as **Colab Secrets**, and use them across notebooks.++To do so, **comment out** the above **manual** API key prompt code block(s), and **uncomment** the following codeblock.++â ïž Don't forget granting access to the API key you would be using to the current notebook.+++```python+# import os+# from google.colab import userdata++# os.environ["OPENAI_API_KEY"] = userdata.get("OPENAI_API_KEY")+```++### 3.1. Using `RolePlaying`+++```python+from colorama import Fore++from camel.societies import RolePlaying+from camel.utils import print_text_animated+```+++```python+def main(model=None, chat_turn_limit=10) -> None:+# Initial the role-playing session on developing a trading bot task with default model (`GPT_4O_MINI`)+ task_prompt = "Develop a trading bot for the stock market"+ role_play_session = RolePlaying(+ assistant_role_name="Python Programmer",+ assistant_agent_kwargs=dict(model=model),+ user_role_name="Stock Trader",+ user_agent_kwargs=dict(model=model),+ task_prompt=task_prompt,+ with_task_specify=True,+ task_specify_agent_kwargs=dict(model=model),+ )++# Output initial message with different colors.+ print(+ Fore.GREEN+ + f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n"+ )+ print(+ Fore.BLUE + f"AI User sys message:\n{role_play_session.user_sys_msg}\n"+ )++ print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")+ print(+ Fore.CYAN+ + "Specified task prompt:"+ + f"\n{role_play_session.specified_task_prompt}\n"+ )+ print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")++ n = 0+ input_msg = role_play_session.init_chat()++# Output response step by step with different colors.+# Keep output until detect the terminate content or reach the loop limit.+ while n < chat_turn_limit:+ n += 1+ assistant_response, user_response = role_play_session.step(input_msg)++ if assistant_response.terminated:+ print(+ Fore.GREEN+ + (+ "AI Assistant terminated. Reason: "+ f"{assistant_response.info['termination_reasons']}."+ )+ )+ break+ if user_response.terminated:+ print(+ Fore.GREEN+ + (+ "AI User terminated. "+ f"Reason: {user_response.info['termination_reasons']}."+ )+ )+ break++ print_text_animated(+ Fore.BLUE + f"AI User:\n\n{user_response.msg.content}\n"+ )++ if "CAMEL_TASK_DONE" in user_response.msg.content:+ break++ print_text_animated(+ Fore.GREEN + "AI Assistant:\n\n"+ f"{assistant_response.msg.content}\n"+ )++++ input_msg = assistant_response.msg++if __name__ == "__main__":+ main()+```diff --git a/docs/mintlify/docs.json b/docs/mintlify/docs.jsonindex fc67e15b5..b83dd267b 100644--- a/docs/mintlify/docs.json+++ b/docs/mintlify/docs.json@@ -847,4 +847,4 @@"article:tag": "CAMEL, AI agents, multi-agent systems, LLM, open source, developers, MCP"}}-}+}\ No newline at end of filediff --git a/docs/mintlify/key_modules/society.mdx b/docs/mintlify/key_modules/society.mdxnew file mode 100644index 000000000..c48f0ca14--- /dev/null+++ b/docs/mintlify/key_modules/society.mdx@@ -0,0 +1,193 @@+---+title: "Society"+description: "Collaborative agent frameworks in CAMEL: autonomous social behaviors, role-based task solving, and turn-based agent societies."+icon: people-group+---++<Note type="info" title="What is the Society Module?">+ The <b>society module</b> simulates agent social behaviors and collaborative workflows.<br/>+ It powers <b>autonomous, multi-role agents</b> that can plan, debate, critique, and solve tasks together, minimizing human intervention while maximizing alignment with your goals.+</Note>++---++<Card icon="users" title="Society Concepts: How Do AI Agents Interact?" className="my-6">+ <b>Task:</b> An objective or idea, given as a simple prompt.<br/>+ <b>AI User:</b> The role responsible for providing instructions or challenges.<br/>+ <b>AI Assistant:</b> The role tasked with generating solutions, plans, or step-by-step responses.<br/>+ <b>Critic (optional):</b> An agent that reviews or critiques the assistant's responses for quality control.<br/><br/>+ <b>Frameworks:</b>+ <ul>+ <li><code>RolePlaying</code> â Advanced turn-taking, prompt-guarded collaboration (most common for LLM societies).</li>+ </ul>+</Card>++---++## đ€ Frameworks++<div style={{ display: "flex", gap: "1.5rem", flexWrap: "wrap" }}>+ <Card icon="repeat" title="RolePlaying" style={{ flex: "1 1 320px" }}>+ <b>Turn-based, prompt-engineered, zero-role-flip agent collaboration.</b>+ <ul>+ <li>Guards against role-flipping, infinite loops, vague responses</li>+ <li>Structured, strict turn-takingâuser and assistant never switch</li>+ <li>Supports optional task planners, critics, and meta-reasoning</li>+ <li>Every message follows a system-enforced structure</li>+ </ul>+ <div>+ <b>Built-in Prompt Rules:</b>+ <ul style={{ marginBottom: 0 }}>+ <li>Never forget you are <code><ASSISTANT_ROLE></code>, I am <code><USER_ROLE></code></li>+ <li>Never flip roles or instruct me</li>+ <li>Decline impossible or unsafe requests, explain why</li>+ <li>Always answer as: <code>Solution: <YOUR_SOLUTION></code></li>+ <li>Always end with: <code>Next request.</code></li>+ </ul>+ </div>+ </Card>+</div>++---++## đ§© RolePlaying Attributes++<AccordionGroup>+ <Accordion title="All RolePlaying Parameters">+ <table>+ <thead>+ <tr>+ <th>Attribute</th>+ <th>Type</th>+ <th>Description</th>+ </tr>+ </thead>+ <tbody>+ <tr><td>assistant_role_name</td><td>str</td><td>Name of assistant's role</td></tr>+ <tr><td>user_role_name</td><td>str</td><td>Name of user's role</td></tr>+ <tr><td>critic_role_name</td><td>str</td><td>Name of critic's role (optional)</td></tr>+ <tr><td>task_prompt</td><td>str</td><td>Prompt for the main task</td></tr>+ <tr><td>with_task_specify</td><td>bool</td><td>Enable task specification agent</td></tr>+ <tr><td>with_task_planner</td><td>bool</td><td>Enable task planner agent</td></tr>+ <tr><td>with_critic_in_the_loop</td><td>bool</td><td>Include critic in conversation loop</td></tr>+ <tr><td>critic_criteria</td><td>str</td><td>How the critic scores/evaluates outputs</td></tr>+ <tr><td>model</td><td>BaseModelBackend</td><td>Model backend for responses</td></tr>+ <tr><td>task_type</td><td>TaskType</td><td>Type/category of the task</td></tr>+ <tr><td>assistant_agent_kwargs</td><td>Dict</td><td>Extra options for assistant agent</td></tr>+ <tr><td>user_agent_kwargs</td><td>Dict</td><td>Extra options for user agent</td></tr>+ <tr><td>task_specify_agent_kwargs</td><td>Dict</td><td>Extra options for task specify agent</td></tr>+ <tr><td>task_planner_agent_kwargs</td><td>Dict</td><td>Extra options for task planner agent</td></tr>+ <tr><td>critic_kwargs</td><td>Dict</td><td>Extra options for critic agent</td></tr>+ <tr><td>sys_msg_generator_kwargs</td><td>Dict</td><td>Options for system message generator</td></tr>+ <tr><td>extend_sys_msg_meta_dicts</td><td>List[Dict]</td><td>Extra metadata for system messages</td></tr>+ <tr><td>extend_task_specify_meta_dict</td><td>Dict</td><td>Extra metadata for task specification</td></tr>+ <tr><td>output_language</td><td>str</td><td>Target output language</td></tr>+ </tbody>+ </table>+ </Accordion>+</AccordionGroup>++---++<Card icon="zap" title="Get Started: RolePlaying in Action" className="my-6">+ <b>Example: Turn-based multi-agent chat with custom roles and live output colors.</b>+ <br/><br/>+ ~~~python+from colorama import Fore+from camel.societies import RolePlaying+from camel.utils import print_text_animated++def main(model=None, chat_turn_limit=50) -> None:+ # Initialize a session for developing a trading bot+ task_prompt = "Develop a trading bot for the stock market"+ role_play_session = RolePlaying(+ assistant_role_name="Python Programmer",+ assistant_agent_kwargs=dict(model=model),+ user_role_name="Stock Trader",+ user_agent_kwargs=dict(model=model),+ task_prompt=task_prompt,+ with_task_specify=True,+ task_specify_agent_kwargs=dict(model=model),+ )++ # Print initial system messages+ print(+ Fore.GREEN+ + f"AI Assistant sys message:\\n{role_play_session.assistant_sys_msg}\\n"+ )+ print(+ Fore.BLUE + f"AI User sys message:\\n{role_play_session.user_sys_msg}\\n"+ )++ print(Fore.YELLOW + f"Original task prompt:\\n{task_prompt}\\n")+ print(+ Fore.CYAN+ + "Specified task prompt:"+ + f"\\n{role_play_session.specified_task_prompt}\\n"+ )+ print(Fore.RED + f"Final task prompt:\\n{role_play_session.task_prompt}\\n")++ n = 0+ input_msg = role_play_session.init_chat()++ # Turn-based simulation+ while n < chat_turn_limit:+ n += 1+ assistant_response, user_response = role_play_session.step(input_msg)++ if assistant_response.terminated:+ print(+ Fore.GREEN+ + (+ "AI Assistant terminated. Reason: "+ f"{assistant_response.info['termination_reasons']}."+ )+ )+ break+ if user_response.terminated:+ print(+ Fore.GREEN+ + (+ "AI User terminated. "+ f"Reason: {user_response.info['termination_reasons']}."+ )+ )+ break++ print_text_animated(+ Fore.BLUE + f"AI User:\\n\\n{user_response.msg.content}\\n"+ )+ print_text_animated(+ Fore.GREEN + "AI Assistant:\\n\\n"+ f"{assistant_response.msg.content}\\n"+ )++ if "CAMEL_TASK_DONE" in user_response.msg.content:+ break++ input_msg = assistant_response.msg++if __name__ == "__main__":+ main()+ ~~~+</Card>++---++<AccordionGroup>+ <Accordion title="Tips & Best Practices">+ <ul>+ <li>Use <b>RolePlaying</b> for most multi-agent conversations, with or without a critic.</li>+ <li>Define specific roles and prompt-guardrails for your agentsâstructure is everything!</li>+ <li>Leverage the <code>with_task_specify</code> and <code>with_task_planner</code> options for highly complex tasks.</li>+ <li>Monitor for infinite loopsâevery agent response should have a clear next step or end.</li>+ </ul>+ </Accordion>+ <Accordion title="More Examples & Advanced Use">+ <ul>+ <li>Check <code>[examples/society/](https://github.com/camel-ai/camel/tree/master/examples/runtimes)</code> in the CAMEL repo for advanced agent society demos.</li>+ <li>Explore <b>critic-in-the-loop</b> setups for higher accuracy and safety.</li>+ <li>Integrate toolkits or external APIs into agent society loops for real-world workflows.</li>+ </ul>+ </Accordion>+</AccordionGroup>