## File: README.md

<h1 align="center">
	🦉 OWL: Optimized Workforce Learning for General Multi-Agent Assistance in Real-World Task Automation
</h1>



<hr>













# 📋 Table of Contents

- [📋 Table of Contents](#-table-of-contents)
- [🔥 News](#-news)
- [🎬 Demo Video](#-demo-video)
- [✨️ Core Features](#️-core-features)
- [🛠️ Installation](#️-installation)
  - [**Prerequisites**](#prerequisites)
    - [Install Python](#install-python)
  - [**Installation Options**](#installation-options)
    - [Option 1: Using uv (Recommended)](#option-1-using-uv-recommended)
    - [Option 2: Using venv and pip](#option-2-using-venv-and-pip)
    - [Option 3: Using conda](#option-3-using-conda)
    - [Option 4: Using Docker](#option-4-using-docker)
      - [**Using Pre-built Image (Recommended)**](#using-pre-built-image-recommended)
      - [**Building Image Locally**](#building-image-locally)
      - [**Using Convenience Scripts**](#using-convenience-scripts)
  - [**Setup Environment Variables**](#setup-environment-variables)
    - [Setting Environment Variables Directly](#setting-environment-variables-directly)
    - [Alternative: Using a `.env` File](#alternative-using-a-env-file)
    - [**MCP Desktop Commander Setup**](#mcp-desktop-commander-setup)
- [🚀 Quick Start](#-quick-start)
  - [Basic Usage](#basic-usage)
  - [Running with Different Models](#running-with-different-models)
    - [Model Requirements](#model-requirements)
      - [Supported Models](#supported-models)
    - [Example Tasks](#example-tasks)
- [🧰 Toolkits and Capabilities](#-toolkits-and-capabilities)
  - [Model Context Protocol (MCP)](#model-context-protocol-mcp)
    - [**Install Node.js**](#install-nodejs)
    - [Windows](#windows)
    - [Linux](#linux)
    - [Mac](#mac)
    - [**Install Playwright MCP Service**](#install-playwright-mcp-service)
  - [Available Toolkits](#available-toolkits)
  - [Available Toolkits](#available-toolkits-1)
    - [Multimodal Toolkits (Require multimodal model capabilities)](#multimodal-toolkits-require-multimodal-model-capabilities)
    - [Text-Based Toolkits](#text-based-toolkits)
  - [Customizing Your Configuration](#customizing-your-configuration)
- [🌐 Web Interface](#-web-interface)
  - [Starting the Web UI](#starting-the-web-ui)
  - [Features](#features)
- [🧪 Experiments](#-experiments)
- [📄 License](#-license)
- [🤝 Contributing](#-contributing)
- [🔥 Community](#-community)
- [❓ FAQ](#-faq)
  - [General Questions](#general-questions)
  - [Experiment Questions](#experiment-questions)
- [📚 Exploring CAMEL Dependency](#-exploring-camel-dependency)
  - [Accessing CAMEL Source Code](#accessing-camel-source-code)
- [🖊️ Cite](#️-cite)
- [⭐ Star History](#-star-history)

# 🔥 News





- **[2025.09.22]**: Exicited to announce that OWL has been accepted by NeurIPS 2025!🚀 Check the latest paper [here](https://arxiv.org/abs/2505.23885).
- **[2025.07.21]**: We open-sourced the training dataset and model checkpoints of OWL project. Training code coming soon. [huggingface link](https://huggingface.co/collections/camel-ai/optimized-workforce-learning-682ef4ab498befb9426e6e27).
- **[2025.05.27]**: We released the technical report of OWL, including more details on the workforce (framework) and optimized workforce learning (training methodology). [paper](https://arxiv.org/abs/2505.23885).
- **[2025.05.18]**: We open-sourced an initial version for replicating workforce experiment on GAIA [here](https://github.com/camel-ai/owl/tree/gaia69).
- **[2025.04.18]**: We uploaded OWL's new GAIA benchmark score of **69.09%**, ranking #1 among open-source frameworks. Check the technical report [here](https://hypnotic-mind-6bd.notion.site/OWL-Optimized-Workforce-Learning-for-General-Multi-Agent-Assistance-in-Real-World-Task-Automation-1d4004aeb21380158749c7f84b20643f).
- **[2025.03.27]**: Integrate SearxNGToolkit performing web searches using SearxNG search engine.
- **[2025.03.26]**: Enhanced Browser Toolkit with multi-browser support for "chrome", "msedge", and "chromium" channels.
- **[2025.03.25]**: Supported Gemini 2.5 Pro, added example run code
- **[2025.03.21]**: Integrated OpenRouter model platform, fix bug with Gemini tool calling.
- **[2025.03.20]**: Accept header in MCP Toolkit, support automatic playwright installation.
- **[2025.03.16]**: Support Bing search, Baidu search.
- **[2025.03.12]**: Added Bocha search in SearchToolkit, integrated Volcano Engine model platform, and enhanced Azure and OpenAI Compatible models with structured output and tool calling.
- **[2025.03.11]**: We added MCPToolkit, FileWriteToolkit, and TerminalToolkit to enhance OWL agents with MCP tool calling, file writing capabilities, and terminal command execution.
- **[2025.03.09]**: We added a web-based user interface that makes it easier to interact with the system.
- **[2025.03.07]**: We open-sourced the codebase of the 🦉 OWL project.
- **[2025.03.03]**: OWL achieved the #1 position among open-source frameworks on the GAIA benchmark with a score of 58.18.

# 🎬 Demo Video

https://github.com/user-attachments/assets/2a2a825d-39ea-45c5-9ba1-f9d58efbc372

https://private-user-images.githubusercontent.com/55657767/420212194-e813fc05-136a-485f-8df3-f10d9b4e63ec.mp4

This video demonstrates how to install OWL locally and showcases its capabilities as a cutting-edge framework for multi-agent collaboration: https://www.youtube.com/watch?v=8XlqVyAZOr8

# ✨️ Core Features

- **Online Search**: Support for multiple search engines (including Wikipedia, Google, DuckDuckGo, Baidu, Bocha, etc.) for real-time information retrieval and knowledge acquisition.
- **Multimodal Processing**: Support for handling internet or local videos, images, and audio data.
- **Browser Automation**: Utilize the Playwright framework for simulating browser interactions, including scrolling, clicking, input handling, downloading, navigation, and more.
- **Document Parsing**: Extract content from Word, Excel, PDF, and PowerPoint files, converting them into text or Markdown format.
- **Code Execution**: Write and execute Python code using interpreter.
- **Built-in Toolkits**: Access to a comprehensive set of built-in toolkits including:
  - **Model Context Protocol (MCP)**: A universal protocol layer that standardizes AI model interactions with various tools and data sources
  - **Core Toolkits**: ArxivToolkit, AudioAnalysisToolkit, CodeExecutionToolkit, DalleToolkit, DataCommonsToolkit, ExcelToolkit, GitHubToolkit, GoogleMapsToolkit, GoogleScholarToolkit, ImageAnalysisToolkit, MathToolkit, NetworkXToolkit, NotionToolkit, OpenAPIToolkit, RedditToolkit, SearchToolkit, SemanticScholarToolkit, SymPyToolkit, VideoAnalysisToolkit, WeatherToolkit, BrowserToolkit, and many more for specialized tasks

# 🛠️ Installation

## **Prerequisites**

### Install Python

Before installing OWL, ensure you have Python installed (version 3.10, 3.11, or 3.12 is supported):

> **Note for GAIA Benchmark Users**: When running the GAIA benchmark evaluation, please use the `gaia58.18` branch which includes a customized version of the CAMEL framework in the `owl/camel` directory. This version contains enhanced toolkits with improved stability specifically optimized for the GAIA benchmark compared to the standard CAMEL installation.

```bash
# Check if Python is installed
python --version

# If not installed, download and install from https://www.python.org/downloads/
# For macOS users with Homebrew:
brew install python@3.10

# For Ubuntu/Debian:
sudo apt update
sudo apt install python3.10 python3.10-venv python3-pip
```

## **Installation Options**

OWL supports multiple installation methods to fit your workflow preferences.

### Option 1: Using uv (Recommended)

```bash
# Clone github repo
git clone https://github.com/camel-ai/owl.git

# Change directory into project directory
cd owl

# Install uv if you don't have it already
pip install uv

# Create a virtual environment and install dependencies
uv venv .venv --python=3.10

# Activate the virtual environment
# For macOS/Linux
source .venv/bin/activate
# For Windows
.venv\Scripts\activate

# Install CAMEL with all dependencies
uv pip install -e .
```

### Option 2: Using venv and pip

```bash
# Clone github repo
git clone https://github.com/camel-ai/owl.git

# Change directory into project directory
cd owl

# Create a virtual environment
# For Python 3.10 (also works with 3.11, 3.12)
python3.10 -m venv .venv

# Activate the virtual environment
# For macOS/Linux
source .venv/bin/activate
# For Windows
.venv\Scripts\activate

# Install from requirements.txt
pip install -r requirements.txt --use-pep517
```

### Option 3: Using conda

```bash
# Clone github repo
git clone https://github.com/camel-ai/owl.git

# Change directory into project directory
cd owl

# Create a conda environment
conda create -n owl python=3.10

# Activate the conda environment
conda activate owl

# Option 1: Install as a package (recommended)
pip install -e .

# Option 2: Install from requirements.txt
pip install -r requirements.txt --use-pep517
```

### Option 4: Using Docker

#### **Using Pre-built Image (Recommended)**

```bash
# This option downloads a ready-to-use image from Docker Hub
# Fastest and recommended for most users
docker compose up -d

# Run OWL inside the container
docker compose exec owl bash
cd .. && source .venv/bin/activate
playwright install-deps
xvfb-python examples/run.py
```

#### **Building Image Locally**

```bash
# For users who need to customize the Docker image or cannot access Docker Hub:
# 1. Open docker-compose.yml
# 2. Comment out the "image: mugglejinx/owl:latest" line
# 3. Uncomment the "build:" section and its nested properties
# 4. Then run:
docker compose up -d --build

# Run OWL inside the container
docker compose exec owl bash
cd .. && source .venv/bin/activate
playwright install-deps
xvfb-python examples/run.py
```

#### **Using Convenience Scripts**

```bash
# Navigate to container directory
cd .container

# Make the script executable and build the Docker image
chmod +x build_docker.sh
./build_docker.sh

# Run OWL with your question
./run_in_docker.sh "your question"
```

## **Setup Environment Variables**

OWL requires various API keys to interact with different services.

### Setting Environment Variables Directly

You can set environment variables directly in your terminal:

- **macOS/Linux (Bash/Zsh)**:

  ```bash
  export OPENAI_API_KEY="your-openai-api-key-here"
  # Add other required API keys as needed
  ```

- **Windows (Command Prompt)**:

  ```batch
  set OPENAI_API_KEY=your-openai-api-key-here
  ```

- **Windows (PowerShell)**:
  ```powershell
  $env:OPENAI_API_KEY = "your-openai-api-key-here"
  ```

> **Note**: Environment variables set directly in the terminal will only persist for the current session.

### Alternative: Using a `.env` File

If you prefer using a `.env` file instead, you can:

1. **Copy and Rename the Template**:

   ```bash
   # For macOS/Linux
   cd owl
   cp .env_template .env

   # For Windows
   cd owl
   copy .env_template .env
   ```

   Alternatively, you can manually create a new file named `.env` in the owl directory and copy the contents from `.env_template`.

2. **Configure Your API Keys**:
   Open the `.env` file in your preferred text editor and insert your API keys in the corresponding fields.

> **Note**: For the minimal example (`examples/run_mini.py`), you only need to configure the LLM API key (e.g., `OPENAI_API_KEY`).

### **MCP Desktop Commander Setup**

If using MCP Desktop Commander within Docker, run:

```bash
npx -y @wonderwhy-er/desktop-commander setup --force-file-protocol
```

For more detailed Docker usage instructions, including cross-platform support, optimized configurations, and troubleshooting, please refer to [DOCKER_README.md](.container/DOCKER_README_en.md).

# 🚀 Quick Start

## Basic Usage

After installation and setting up your environment variables, you can start using OWL right away:

```bash
python examples/run.py
```

## Running with Different Models

### Model Requirements

- **Tool Calling**: OWL requires models with robust tool calling capabilities to interact with various toolkits. Models must be able to understand tool descriptions, generate appropriate tool calls, and process tool outputs.

- **Multimodal Understanding**: For tasks involving web interaction, image analysis, or video processing, models with multimodal capabilities are required to interpret visual content and context.

#### Supported Models

For information on configuring AI models, please refer to our [CAMEL models documentation](https://docs.camel-ai.org/key_modules/models.html#supported-model-platforms-in-camel).

> **Note**: For optimal performance, we strongly recommend using OpenAI models (GPT-4 or later versions). Our experiments show that other models may result in significantly lower performance on complex tasks and benchmarks, especially those requiring advanced multi-modal understanding and tool use.

OWL supports various LLM backends, though capabilities may vary depending on the model's tool calling and multimodal abilities. You can use the following scripts to run with different models:

```bash
# Run with Claude model
python examples/run_claude.py

# Run with Qwen model
python examples/run_qwen_zh.py

# Run with Deepseek model
python examples/run_deepseek_zh.py

# Run with other OpenAI-compatible models
python examples/run_openai_compatible_model.py

# Run with Gemini model
python examples/run_gemini.py

# Run with Azure OpenAI
python examples/run_azure_openai.py

# Run with Ollama
python examples/run_ollama.py
```

For a simpler version that only requires an LLM API key, you can try our minimal example:

```bash
python examples/run_mini.py
```

You can run OWL agent with your own task by modifying the `examples/run.py` script:

```python
# Define your own task
task = "Task description here."

society = construct_society(question)
answer, chat_history, token_count = run_society(society)

print(f"\033[94mAnswer: {answer}\033[0m")
```

For uploading files, simply provide the file path along with your question:

```python
# Task with a local file (e.g., file path: `tmp/example.docx`)
task = "What is in the given DOCX file? Here is the file path: tmp/example.docx"

society = construct_society(question)
answer, chat_history, token_count = run_society(society)
print(f"\033[94mAnswer: {answer}\033[0m")
```

OWL will then automatically invoke document-related tools to process the file and extract the answer.

### Example Tasks

Here are some tasks you can try with OWL:

- "Find the latest stock price for Apple Inc."
- "Analyze the sentiment of recent tweets about climate change"
- "Help me debug this Python code: [your code here]"
- "Summarize the main points from this research paper: [paper URL]"
- "Create a data visualization for this dataset: [dataset path]"

# 🧰 Toolkits and Capabilities

## Model Context Protocol (MCP)

OWL's MCP integration provides a standardized way for AI models to interact with various tools and data sources:

Before using MCP, you need to install Node.js first.

### **Install Node.js**

### Windows

Download the official installer: [Node.js](https://nodejs.org/en).

Check "Add to PATH" option during installation.

### Linux

```bash
sudo apt update
sudo apt install nodejs npm -y
```

### Mac

```bash
brew install node
```

### **Install Playwright MCP Service**

```bash
npm install @executeautomation/playwright-mcp-server
npx playwright install-deps
```

Try our comprehensive MCP examples:

- `examples/run_mcp.py` - Basic MCP functionality demonstration (local call, requires dependencies)
- `examples/run_mcp_sse.py` - Example using the SSE protocol (Use remote services, no dependencies)

## Available Toolkits

> **Important**: Effective use of toolkits requires models with strong tool calling capabilities. For multimodal toolkits (Web, Image, Video), models must also have multimodal understanding abilities.

OWL supports various toolkits that can be customized by modifying the `tools` list in your script:

```python
# Configure toolkits
tools = [
    *BrowserToolkit(headless=False).get_tools(),  # Browser automation
    *VideoAnalysisToolkit(model=models["video"]).get_tools(),
    *AudioAnalysisToolkit().get_tools(),  # Requires OpenAI Key
    *CodeExecutionToolkit(sandbox="subprocess").get_tools(),
    *ImageAnalysisToolkit(model=models["image"]).get_tools(),
    SearchToolkit().search_duckduckgo,
    SearchToolkit().search_google,  # Comment out if unavailable
    SearchToolkit().search_wiki,
    SearchToolkit().search_bocha,
    SearchToolkit().search_baidu,
    *ExcelToolkit().get_tools(),
    *DocumentProcessingToolkit(model=models["document"]).get_tools(),
    *FileWriteToolkit(output_dir="./").get_tools(),
]
```

## Available Toolkits

Key toolkits include:

### Multimodal Toolkits (Require multimodal model capabilities)

- **BrowserToolkit**: Browser automation for web interaction and navigation
- **VideoAnalysisToolkit**: Video processing and content analysis
- **ImageAnalysisToolkit**: Image analysis and interpretation

### Text-Based Toolkits

- **AudioAnalysisToolkit**: Audio processing (requires OpenAI API)
- **CodeExecutionToolkit**: Python code execution and evaluation
- **SearchToolkit**: Web searches (Google, DuckDuckGo, Wikipedia)
- **DocumentProcessingToolkit**: Document parsing (PDF, DOCX, etc.)

Additional specialized toolkits: ArxivToolkit, GitHubToolkit, GoogleMapsToolkit, MathToolkit, NetworkXToolkit, NotionToolkit, RedditToolkit, WeatherToolkit, and more. For a complete list, see the [CAMEL toolkits documentation](https://docs.camel-ai.org/key_modules/tools).

## Customizing Your Configuration

To customize available tools:

```python
# 1. Import toolkits
from camel.toolkits import BrowserToolkit, SearchToolkit, CodeExecutionToolkit

# 2. Configure tools list
tools = [
    *BrowserToolkit(headless=True).get_tools(),
    SearchToolkit().search_wiki,
    *CodeExecutionToolkit(sandbox="subprocess").get_tools(),
]

# 3. Pass to assistant agent
assistant_agent_kwargs = {"model": models["assistant"], "tools": tools}
```

Selecting only necessary toolkits optimizes performance and reduces resource usage.

# 🌐 Web Interface



## Starting the Web UI

```bash
# Start the Chinese version
python owl/webapp_zh.py

# Start the English version
python owl/webapp.py

# Start the Japanese version
python owl/webapp_jp.py
```

## Features

- **Easy Model Selection**: Choose between different models (OpenAI, Qwen, DeepSeek, etc.)
- **Environment Variable Management**: Configure your API keys and other settings directly from the UI
- **Interactive Chat Interface**: Communicate with OWL agents through a user-friendly interface
- **Task History**: View the history and results of your interactions

The web interface is built using Gradio and runs locally on your machine. No data is sent to external servers beyond what's required for the model API calls you configure.

# 🧪 Experiments

To reproduce OWL's GAIA benchmark score:

We also provide an enhanced OWL in the `main` branch, so you can directly benefit from upgraded toolkits and increased stability even without switching branches. 
For the original GAIA-specific performance, we recommend our `gaia69` branch.

When running the benchmark evaluation:

1. Switch to the `gaia69` branch:

   ```bash
   git checkout gaia69
   ```

2. Run the evaluation script:
   ```bash
   python run_gaia_workforce_claude.py
   ```

This will execute the same configuration that achieved our top-ranking performance on the GAIA benchmark.

# 📄 License

The source code is licensed under Apache 2.0.

# 🤝 Contributing

We welcome contributions from the community! Here's how you can help:

1. Read our [Contribution Guidelines](https://github.com/camel-ai/camel/blob/master/CONTRIBUTING.md)
2. Check [open issues](https://github.com/camel-ai/camel/issues) or create new ones
3. Submit pull requests with your improvements

**Current Issues Open for Contribution:**

- [#1915](https://github.com/camel-ai/camel/issues/1915)
- [#2190](https://github.com/camel-ai/camel/issues/2190)
- [#2165](https://github.com/camel-ai/camel/issues/2165)
- [#2121](https://github.com/camel-ai/camel/issues/2121)
- [#1908](https://github.com/camel-ai/camel/issues/1908)
- [#1538](https://github.com/camel-ai/camel/issues/1538)
- [#1481](https://github.com/camel-ai/camel/issues/1481)

To take on an issue, simply leave a comment stating your interest.

# 🔥 Community

Join us ([_Discord_](https://discord.camel-ai.org/) or [_WeChat_](https://ghli.org/camel/wechat.png)) in pushing the boundaries of finding the scaling laws of agents.

Join us for further discussions!




# ❓ FAQ

## General Questions

**Q: Why don't I see Chrome running locally after starting the example script?**

A: If OWL determines that a task can be completed using non-browser tools (such as search or code execution), the browser will not be launched. The browser window will only appear when OWL determines that browser-based interaction is necessary.

**Q: Which Python version should I use?**

A: OWL supports Python 3.10, 3.11, and 3.12.

**Q: How can I contribute to the project?**

A: See our [Contributing](#-contributing) section for details on how to get involved. We welcome contributions of all kinds, from code improvements to documentation updates.

## Experiment Questions

**Q: Which CAMEL version should I use for replicate the role playing result?**

A: We provide a modified version of CAMEL (owl/camel) in the gaia58.18 branch. Please make sure you use this CAMEL version for your experiments.

**Q: Why are my experiment results lower than the reported numbers?**

A: Since the GAIA benchmark evaluates LLM agents in a realistic world, it introduces a significant amount of randomness. Based on user feedback, one of the most common issues for replication is, for example, agents being blocked on certain webpages due to network reasons.
We have uploaded a keywords matching script to help quickly filter out these errors [here](https://github.com/camel-ai/owl/blob/gaia58.18/owl/filter_failed_cases.py).
You can also check this [technical report](https://hypnotic-mind-6bd.notion.site/OWL-Optimized-Workforce-Learning-for-General-Multi-Agent-Assistance-in-Real-World-Task-Automation-1d4004aeb21380158749c7f84b20643f?pvs=74) for more details when evaluating LLM agents in realistic open-world environments.

# 📚 Exploring CAMEL Dependency

OWL is built on top of the [CAMEL](https://github.com/camel-ai/camel) Framework, here's how you can explore the CAMEL source code and understand how it works with OWL:

## Accessing CAMEL Source Code

```bash
# Clone the CAMEL repository
git clone https://github.com/camel-ai/camel.git
cd camel
```

# 🖊️ Cite

If you find this repo useful, please cite:

```
@misc{hu2025owl,
      title={OWL: Optimized Workforce Learning for General Multi-Agent Assistance in Real-World Task Automation},
      author={Mengkang Hu and Yuhang Zhou and Wendong Fan and Yuzhou Nie and Bowei Xia and Tao Sun and Ziyu Ye and Zhaoxuan Jin and Yingru Li and Qiguang Chen and Zeyu Zhang and Yifeng Wang and Qianshuo Ye and Bernard Ghanem and Ping Luo and Guohao Li},
      year={2025},
      eprint={2505.23885},
      archivePrefix={arXiv},
      primaryClass={cs.AI},
      url={https://arxiv.org/abs/2505.23885},
}
```

# ⭐ Star History

[](https://star-history.com/#camel-ai/owl&Date)

[docs-image]: https://img.shields.io/badge/Documentation-EB3ECC
[docs-url]: https://camel-ai.github.io/camel/index.html
[star-image]: https://img.shields.io/github/stars/camel-ai/owl?label=stars&logo=github&color=brightgreen
[star-url]: https://github.com/camel-ai/owl/stargazers
[package-license-image]: https://img.shields.io/badge/License-Apache_2.0-blue.svg
[package-license-url]: https://github.com/camel-ai/owl/blob/main/licenses/LICENSE
[colab-url]: https://colab.research.google.com/drive/1AzP33O8rnMW__7ocWJhVBXjKziJXPtim?usp=sharing
[colab-image]: https://colab.research.google.com/assets/colab-badge.svg
[huggingface-url]: https://huggingface.co/camel-ai
[huggingface-image]: https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-CAMEL--AI-ffc107?color=ffc107&logoColor=white
[discord-url]: https://discord.camel-ai.org/
[discord-image]: https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb
[wechat-url]: https://ghli.org/camel/wechat.png
[wechat-image]: https://img.shields.io/badge/WeChat-CamelAIOrg-brightgreen?logo=wechat&logoColor=white
[x-url]: https://x.com/CamelAIOrg
[x-image]: https://img.shields.io/twitter/follow/CamelAIOrg?style=social
[twitter-image]: https://img.shields.io/twitter/follow/CamelAIOrg?style=social&color=brightgreen&logo=twitter
[reddit-url]: https://www.reddit.com/r/CamelAI/
[reddit-image]: https://img.shields.io/reddit/subreddit-subscribers/CamelAI?style=plastic&logo=reddit&label=r%2FCAMEL&labelColor=white
[ambassador-url]: https://www.camel-ai.org/community
[owl-url]: ./assets/qr_code.jpg
[owl-image]: https://img.shields.io/badge/WeChat-OWLProject-brightgreen?logo=wechat&logoColor=white

---

## File: community_usecase/Airbnb-MCP/README.md

# 🏡 CAMEL-AI + MCP: Airbnb Use Case

This example demonstrates how to use the [CAMEL-AI OWL framework](https://github.com/camel-ai/owl) and **MCP (Model Context Protocol)** to search for Airbnb listings using a custom MCP server (`@openbnb/mcp-server-airbnb`). Agents in the OWL framework coordinate to perform tool-augmented travel research in a structured, automated way.

---

## ✨ Use Case

> _“Find me the best Airbnb in Gurugram with a check-in date of 2025-06-01 and a check-out date of 2025-06-07 for 2 adults. Return the top 5 listings with their names, prices, and locations.”_

Agents leverage an MCP server to execute real-time Airbnb queries and return formatted results.

---

## 📦 Setup

### 1. Clone and install dependencies

```bash
git clone https://github.com/camel-ai/owl
cd owl
pip install -r requirements.txt
```

---

### 2. Configure MCP Server

In your `mcp_servers_config.json`, add the following:

```json
{
  "mcpServers": {
    "airbnb": {
      "command": "npx",
      "args": [
        "-y",
        "@openbnb/mcp-server-airbnb",
        "--ignore-robots-txt"
      ]
    }
  }
}
```

> 🛠️ You will need **Node.js and NPM** installed. Run `npx` will automatically fetch the Airbnb MCP server.

---

### 3. Run the Example Script

```bash
python community_usecase/Airbnb_MCP
```

You can also customize the prompt inside the script itself. Edit the `default_task` section of `Airbnb_MCP.py` like this:

```python
# Replace this line:
default_task = (
    "here you need to add the task"
)

# Example:
default_task = (
    "Find me the best Airbnb in Gurugram with a check-in date of 2025-06-01 "
    "and a check-out date of 2025-06-07 for 2 adults. Return the top 5 listings with their names, "
    "prices, and locations."
)
```

This allows agents to work from your hardcoded task without passing anything via command line.

---

## 🧠 How It Works

- **MCPToolkit** reads the config and connects to the `@openbnb/mcp-server-airbnb`.
- **OWL RolePlaying Agents** simulate a conversation between a `content_curator` and a `research_assistant`.
- The **assistant agent** calls the MCP Airbnb server to fetch listings.
- The results are processed, formatted, and printed.

---

---

## 🚧 Notes

- This script uses **GPT-4o** via OpenAI for both user and assistant roles.
- Supports async execution and graceful cleanup of agents and MCP sessions.
- Add retries and fallback logic for production use.

---

## 📌 References

- [MCP Overview (Anthropic)](https://docs.anthropic.com/en/docs/agents-and-tools/mcp)
- [CAMEL-AI GitHub](https://github.com/camel-ai/camel)
- [OWL Framework](https://github.com/camel-ai/owl)
- [MCP Airbnb Plugin](https://www.npmjs.com/package/@openbnb/mcp-server-airbnb)
~~~

---

## File: community_usecase/a_share_investment_agent_camel/README.md

<h1 align="center">
	🦉A股投资代理系统
</h1>





[English](README_EN.md) |
[中文](README.md) |
[致谢](#-致谢) |
[示例运行结果](#-示例运行结果)

</h4>




## 📋 项目简介

本项目是一个基于OWL框架和Camel框架(v0.2.36)的多代理A股投资分析系统，通过多个专业角色代理协作完成投资分析，为用户提供投资决策建议。系统采用多模型支持，可灵活使用不同的大语言模型（如Gemini、OpenAI、Qwen）进行分析。

本项目参与了OWL社区用例挑战赛，是对开源项目[A_Share_investment_Agent](https://github.com/24mlight/A_Share_investment_Agent)的改进版本，使用OWL和Camel框架重构实现。

### 🌟 核心特点

- **多代理协作体系**: 通过10个专业角色代理协作进行分析，实现更全面、专业的投资决策
- **多模型支持**: 支持Gemini、OpenAI、Qwen等多种大语言模型，灵活切换
- **A股市场特化**: 专为A股市场设计，关注中国股市特性和数据
- **辩论与决策机制**: 创新的多空观点辩论机制，平衡分析观点
- **完整的数据处理流水线**: 从数据收集到分析再到决策的全流程支持

## 🏗️ 系统架构

系统架构包含以下几个核心代理：

### 📊 数据与分析层
1. **市场数据代理** (Market Data Agent) - 负责收集和预处理市场数据
2. **技术分析代理** (Technical Analyst) - 分析技术指标并生成交易信号
3. **基本面分析代理** (Fundamentals Analyst) - 分析基本面数据并生成交易信号
4. **情绪分析代理** (Sentiment Analyst) - 分析市场情绪并生成交易信号
5. **价值评估代理** (Valuation Analyst) - 计算股票内在价值并生成交易信号

### 🔍 研究与辩论层
6. **多头研究员** (Researcher Bull) - 提供看多角度分析
7. **空头研究员** (Researcher Bear) - 提供看空角度分析
8. **辩论室** (Debate Room) - 整合多空观点形成最终观点

### 🧮 决策层
9. **风险管理代理** (Risk Manager) - 计算风险指标并设置仓位限制
10. **投资组合管理代理** (Portfolio Manager) - 制定最终交易决策并生成订单

## 💻 安装指南

### 前提条件

- Python 3.9+
- 相关API密钥（Gemini/OpenAI/Qwen）

### 安装步骤

1. 克隆OWL仓库并进入项目目录
```bash
git clone https://github.com/camel-ai/owl.git
cd owl/community_usecase/a_share_investment_agent_camel
```

2. 安装依赖
```bash
pip install -r requirements.txt
```

3. 配置环境变量（创建.env文件）
```
# Gemini配置
GEMINI_API_KEY=your_gemini_api_key
GEMINI_MODEL=gemini-1.5-flash

# OpenAI配置
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-4o

# Qwen配置
QWEN_API_KEY=your_qwen_api_key
QWEN_MODEL=qwen-max
QWEN_API_URL=https://your-qwen-api-endpoint
```

### Docker 使用方法

为了简化安装流程，我们提供了Docker支持。

1. 构建Docker镜像
```bash
docker build -t a-share-investment-agent .
```

2. 创建包含API密钥的.env文件
```bash
# 创建与上述相同格式的.env文件
touch .env
# 编辑.env文件添加您的API密钥
```

## 🚀 使用方法

### 基本用法

```bash
python src/main.py --ticker 000001 --model qwen
```

### 测试模式

```bash
# 使用默认参数（Qwen模型和000001股票）进行测试
python src/main.py --test

# 指定股票进行测试
python src/main.py --test --ticker 600036
```

### 参数说明

- `--ticker`: 股票代码
- `--start-date`: 开始日期 (YYYY-MM-DD)
- `--end-date`: 结束日期 (YYYY-MM-DD)
- `--show-reasoning`: 显示分析推理过程
- `--num-of-news`: 情绪分析使用的新闻数量
- `--initial-capital`: 初始现金金额
- `--initial-position`: 初始股票持仓
- `--model`: 使用的模型 (gemini, openai, qwen)
- `--test`: 使用预设参数运行测试功能

### 示例运行结果

以下是针对寒武纪-U(688256)股票在2025/01/04-2025/03/24期间的分析结果示例：

```bash
python src/main.py --ticker 688256 --start-date 2025-01-04 --end-date 2025-03-24 --model qwen --show-reasoning
```

#### 各代理分析日志

**市场数据代理**:
```json
{
"trend": "短期趋势向下，但长期趋势仍需观察",
"judgment": "当前价格处于布林带中轨下方，RSI接近中性水平，MACD线在信号线下方，表明短期可能继续调整。但考虑到之前的大幅上涨，长期趋势仍需进一步观察。建议关注支撑位670.66和阻力位747.57。"
}
```

**技术分析代理**:
```json
{
  "signal": "bearish",
  "confidence": 0.8,
  "reasoning": "从技术指标来看，该股票目前处于一个相对弱势的状态。首先，5日均线（718.856）已经下穿10日均线（743.927）和20日均线（747.574），这表明短期趋势正在走弱。MACD指标也显示了类似的趋势，MACD线（8.994）低于信号线（20.004），并且MACD柱状图（-11.009）为负值，表明市场动能正在减弱。RSI指标（48.676）处于中性区域，但接近超卖区域，这可能预示着短期内可能会有反弹，但整体趋势仍然偏弱。布林带方面，当前价格（685.05）接近布林带下轨（670.657），这可能提供一定的支撑，但考虑到其他指标的弱势表现，支撑力度可能有限。综合来看，当前的市场环境和技术指标均指向一个偏空的趋势。"
}
```

**基本面分析代理**:
```json
{
  "signal": "bearish",
  "confidence": 0.8,
  "reasoning": "寒武纪-U的财务状况和业务表现显示出明显的负面趋势。首先，公司的净利润持续为负，且亏损额在最近几个季度有所增加，这表明公司在盈利能力方面存在严重问题。其次，公司的营业收入虽然在2023年第四季度有所增长，但随后几个季度出现了显著下降，这可能意味着市场需求或公司市场份额的减少。此外，公司的市盈率为负，市净率高达52.58，表明市场对其估值过高，存在较大的泡沫风险。从财务健康状况来看，尽管公司的资产负债率较低，但其经营现金流持续为负，表明公司在运营过程中面临较大的资金压力。综合以上因素，我们认为寒武纪-U的股票目前处于看跌状态。"
}
```

**情绪分析代理**:
```json
{
  "signal": "bullish",
  "confidence": 0.8,
  "reasoning": "从新闻数据来看，整体市场情绪偏向积极，积极新闻数量远多于消极新闻。尽管有一条新闻提到芯片ETF和寒武纪-U的下跌，但大多数新闻都强调了寒武纪-U及其所在板块的积极表现，包括股价上涨和技术突破等。此外，寒武纪-U被纳入富时中国A50指数的消息也表明市场对其长期前景持乐观态度。社交媒体讨论也主要集中在公司的积极发展上，进一步支持了看涨的观点。",
  "key_events": [
    "寒武纪-U被纳入富时中国A50指数",
    "寒武纪-U股价多次上涨",
    "人工智能AIETF持仓股寒武纪-U大涨",
    "智元启元大模型发布"
  ]
}
```

**估值分析代理**:
```json
{
  "signal": "bearish",
  "confidence": 0.85,
  "reasoning": "寒武纪-U的财务状况和业务表现显示出明显的负面趋势。首先，公司的净利润持续为负，且亏损额在最近几个季度有所增加，这表明公司在盈利能力方面存在严重问题。其次，公司的营业收入虽然在2023年第四季度有所增长，但随后几个季度出现了显著下降，这可能意味着市场需求或公司市场份额的减少。此外，公司的市盈率为负，市净率高达52.58，表明市场对其估值过高，存在较大的泡沫风险。从财务健康状况来看，尽管公司的资产负债率较低，但其经营现金流持续为负，表明公司在运营过程中面临较大的资金压力。综合以上因素，我们认为寒武纪-U的股票目前处于看跌状态。此外，通过DCF模型和相对估值法计算，公司的内在价值显著低于当前市场价格，进一步支持了看跌的观点。",
  "fair_value": 200.0,
  "key_metrics": [
    "市盈率",
    "市净率",
    "营业收入",
    "净利润",
    "经营现金流"
  ]
}
```

**多头研究员**:
```json
{
  "key_points": [
    "市场情绪积极，新闻和社交媒体讨论偏向乐观",
    "寒武纪-U被纳入富时中国A50指数，表明市场对其长期前景持乐观态度",
    "技术突破和股价上涨的积极新闻",
    "尽管技术面和基本面显示弱势，但市场情绪和潜在催化剂可能推动股价反弹"
  ],
  "confidence": 0.6,
  "reasoning": "尽管技术面和基本面分析显示寒武纪-U目前处于弱势状态，但市场情绪和潜在催化剂可能推动股价反弹。寒武纪-U被纳入富时中国A50指数，表明市场对其长期前景持乐观态度。此外，公司近期的技术突破和股价上涨的积极新闻也支持了看涨的观点。虽然当前的财务状况和估值较高，但市场情绪和潜在的积极因素可能为股价提供支撑。因此，我们建议在短期内保持谨慎，但长期来看，寒武纪-U仍具有投资潜力。"
}
```

**空头研究员**:
```json
{
  "key_points": [
    "技术指标显示短期趋势走弱",
    "净利润持续为负且亏损增加",
    "营业收入下降表明市场需求减少",
    "市净率高达52.58，估值过高",
    "经营现金流持续为负，资金压力大",
    "DCF模型和相对估值法显示内在价值低于市场价格"
  ],
  "confidence": 0.8,
  "reasoning": "综合技术分析、基本面分析、市场情绪分析和估值分析，寒武纪-U的股票目前处于看跌状态。技术指标显示短期趋势走弱，基本面分析显示公司盈利能力差、市场需求减少、估值过高且资金压力大。尽管市场情绪偏向积极，但这些积极情绪主要集中在短期事件上，无法掩盖长期基本面问题。估值分析进一步支持了看跌的观点，内在价值显著低于当前市场价格。因此，建议卖出寒武纪-U的股票。"
}
```

**辩论室**:
```json
{
  "signal": "neutral",
  "confidence": 0.7,
  "reasoning": "多头和空头研究员的观点都有其合理性和依据。多头研究员强调市场情绪积极、寒武纪-U被纳入富时中国A50指数以及技术突破和股价上涨的积极新闻，这些因素可能在短期内为股价提供支撑。然而，空头研究员指出技术指标显示短期趋势走弱，基本面分析显示公司盈利能力差、市场需求减少、估值过高且资金压力大。尽管市场情绪偏向积极，但这些积极情绪主要集中在短期事件上，无法掩盖长期基本面问题。综合来看，短期内市场情绪和技术突破可能推动股价反弹，但长期基本面问题仍然存在，因此建议保持中立态度，等待更多明确信号。",
  "final_verdict": "建议投资者在短期内保持谨慎，关注市场情绪和技术突破的持续性。长期来看，需要密切关注公司的基本面改善情况，特别是盈利能力、市场需求和资金压力等方面。在没有更多明确信号之前，建议保持中立态度，避免过度乐观或悲观。"
}
```

**风险管理代理**:
```json
{
  "max_position_size": 0.2,
  "volatility": 0.15,
  "risk_score": 0.7,
  "max_drawdown": 0.25,
  "suggested_position_size": 0.15,
  "reasoning": "鉴于股票688256较高的波动性和基本面风险，建议采取谨慎态度。虽然短期内存在技术突破的可能性，但长期来看公司面临盈利能力差等问题。因此，建议控制持仓比例不超过20%，并设置适当的止损点以保护资本。同时，通过多样化投资来分散风险。"
}
```

**投资组合管理代理（最终决策）**:
```json
{
  "action": "hold",
  "quantity": 0,
  "confidence": 0.8,
  "reasoning": "综合考虑各类分析师的交易信号、辩论结果、风险分析、当前投资组合状况以及最新市场价格，我们决定对股票688256采取持有策略。技术分析和基本面分析均显示该股票处于弱势状态，技术指标显示短期趋势走弱，基本面显示公司盈利能力差、市场需求减少、估值过高且资金压力大。尽管情绪分析显示市场情绪偏向积极，但这些积极情绪主要集中在短期事件上，无法掩盖长期基本面问题。辩论结果也建议在短期内保持谨慎，关注市场情绪和技术突破的持续性。长期来看，需要密切关注公司的基本面改善情况。风险分析建议控制持仓比例不超过20%，并设置适当的止损点以保护资本。因此，我们决定暂时持有该股票，等待更多明确信号。"
}
```

#### 综合结论

**最终投资决策**: 持有 (置信度: 0.8)

多个专业代理的分析结果表明，寒武纪-U(688256)股票目前处于技术和基本面的弱势状态，但市场情绪和短期事件可能为股价提供支撑。综合考虑各方面因素，系统建议对该股票采取持有策略，密切关注后续基本面变化和市场情绪变化。同时，风险管理建议将该股票的最大持仓比例控制在投资组合的20%以内，并设置适当的止损点以控制风险。

## 🔄 数据流程说明

系统的数据流程遵循以下步骤：

1. **数据采集**: 市场数据代理通过akshare API收集A股市场数据和新闻
2. **多维分析**: 由4个专业分析代理（技术、基本面、情绪、估值）独立进行分析
3. **正反研究**: 多头和空头研究员分别从看多和看空角度提供分析报告
4. **辩论整合**: 辩论室整合多空观点形成最终分析意见
5. **风险评估**: 风险管理代理评估投资风险并设置交易限制
6. **最终决策**: 投资组合管理代理制定最终交易决策并生成订单



## 📋 项目结构

```
community_usecase/a_share_investment_agent_camel/
├── src/                       # 源代码目录
│   ├── agents/                # 代理实现
│   │   ├── base_agent.py      # 代理基类
│   │   ├── market_data_agent.py  # 市场数据代理
│   │   ├── technical_analyst.py  # 技术分析代理
│   │   └── ...
│   ├── tools/                 # 工具模块
│   │   └── data_helper.py     # 数据辅助工具
│   ├── utils/                 # 实用工具
│   │   └── logging_utils.py   # 日志工具
│   ├── models.py              # 数据模型定义
│   ├── roles.py               # 角色定义
│   └── main.py                # 主程序
├── tests/                     # 测试目录
├── logs/                      # 日志文件
├── .env                       # 环境变量
├── pyproject.toml             # Poetry配置
├── requirements.txt           # 依赖项
└── README.md                  # 说明文档
```

## 🔍 代码实现亮点

### 1. 多代理协作架构

本项目实现了10个专业角色的代理，每个代理负责投资分析流程中的特定任务。代理之间通过消息传递进行协作，形成完整的分析决策链条。

```python
# 创建代理
market_data_agent = MarketDataAgent(show_reasoning=show_reasoning, model_name=model_name)
technical_analyst = TechnicalAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
fundamentals_analyst = FundamentalsAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
sentiment_analyst = SentimentAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
valuation_analyst = ValuationAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
researcher_bull = ResearcherBullAgent(show_reasoning=show_reasoning, model_name=model_name)
researcher_bear = ResearcherBearAgent(show_reasoning=show_reasoning, model_name=model_name)
debate_room = DebateRoomAgent(show_reasoning=show_reasoning, model_name=model_name)
risk_manager = RiskManagerAgent(show_reasoning=show_reasoning, model_name=model_name)
portfolio_manager = PortfolioManagerAgent(show_reasoning=show_reasoning, model_name=model_name)
```

### 2. 灵活的多模型支持

系统支持包括Gemini、OpenAI和Qwen在内的多种大语言模型，通过统一的接口实现灵活切换。

```python
def get_llm_client(model_name: str):
    """获取指定的LLM客户端"""
    if model_name.lower() == 'gemini':
        return GeminiClient()
    elif model_name.lower() == 'openai':
        return OpenAIClient()
    elif model_name.lower() == 'qwen':
        return QwenClient()
    else:
        raise ValueError(f"不支持的模型: {model_name}")
```



## 📝 改进与创新

相较于原始版本，基于Camel框架重构的系统具有以下创新和改进：

1. **模块化设计**: 更清晰的代理定义和系统结构，便于扩展和维护
2. **多模型支持**: 灵活支持多种LLM模型，提高系统适应性
3. **完善的日志系统**: 详细记录各代理的工作过程，便于调试和分析


## ⚠️ 免责声明

本项目仅用于**教育和研究目的**。

- 不适用于实际交易或投资
- 不提供任何保证
- 过往业绩不代表未来表现
- 创建者不承担任何财务损失责任
- 投资决策请咨询专业理财顾问

使用本软件即表示您同意仅将其用于学习目的。

## 📚 相关资源

- [OWL框架官方文档](https://github.com/camel-ai/owl)
- [Camel框架官方文档](https://github.com/camel-ai/camel)
- [A_Share_investment_Agent](https://github.com/24mlight/A_Share_investment_Agent)

## 🙏 致谢

本项目基于以下开源项目进行改进：

1. [A_Share_investment_Agent](https://github.com/24mlight/A_Share_investment_Agent) - 原始A股投资代理项目，为本项目提供了基础架构和投资分析思路，特别感谢其在A股数据处理和分析策略方面的创新设计。
2. [ai-hedge-fund](https://github.com/virattt/ai-hedge-fund.git) - 原始美股投资代理项目
3. [Camel框架](https://github.com/camel-ai/camel) - 多代理对话框架
4. [OWL框架](https://github.com/camel-ai/owl) - 开源多智能体协作框架

感谢所有原作者的贡献和启发，为本项目提供了坚实的基础。

---

## File: community_usecase/a_share_investment_agent_camel/README_EN.md

<h1 align="center">
	🦉A-Share Investment Agent System
</h1>





[English](README_EN.md) |
[中文](README.md) |
[Acknowledgements](#-acknowledgements) |
[Example Results](#-example-results)

</h4>




## 📋 Project Introduction

This project is a multi-agent A-share investment analysis system based on the OWL framework and Camel framework (v0.2.36), which completes investment analysis through multiple professional role agents working together to provide investment decision recommendations for users. The system adopts multi-model support and can flexibly use different large language models (such as Gemini, OpenAI, Qwen) for analysis.

This project participated in the OWL community use case challenge and is an improved version of the open-source project [A_Share_investment_Agent](https://github.com/24mlight/A_Share_investment_Agent), restructured using the OWL and Camel frameworks.

### 🌟 Core Features

- **Multi-agent Collaboration System**: Analysis through 10 professional role agents working together to achieve more comprehensive and professional investment decisions
- **Multi-model Support**: Support for multiple large language models such as Gemini, OpenAI, Qwen, with flexible switching
- **A-share Market Specialization**: Designed specifically for the A-share market, focusing on Chinese stock market characteristics and data
- **Debate and Decision Mechanism**: Innovative bull and bear perspective debate mechanism to balance analytical viewpoints
- **Complete Data Processing Pipeline**: Full process support from data collection to analysis to decision-making

## 🏗️ System Architecture

The system architecture includes the following core agents:

### 📊 Data and Analysis Layer
1. **Market Data Agent** - Responsible for collecting and preprocessing market data
2. **Technical Analyst** - Analyzes technical indicators and generates trading signals
3. **Fundamentals Analyst** - Analyzes fundamental data and generates trading signals
4. **Sentiment Analyst** - Analyzes market sentiment and generates trading signals
5. **Valuation Analyst** - Calculates the intrinsic value of stocks and generates trading signals

### 🔍 Research and Debate Layer
6. **Researcher Bull** - Provides bullish perspective analysis
7. **Researcher Bear** - Provides bearish perspective analysis
8. **Debate Room** - Integrates bull and bear perspectives to form a final viewpoint

### 🧮 Decision Layer
9. **Risk Manager** - Calculates risk indicators and sets position limits
10. **Portfolio Manager** - Formulates the final trading decision and generates orders

## 💻 Installation Guide

### Prerequisites

- Python 3.9+
- Related API keys (Gemini/OpenAI/Qwen)

### Installation Steps

1. Clone the OWL repository and enter the project directory
```bash
git clone https://github.com/camel-ai/owl.git
cd owl/community_usecase/a_share_investment_agent_camel
```

2. Install dependencies
```bash
pip install -r requirements.txt
```

3. Configure environment variables (create .env file)
```
# Gemini Configuration
GEMINI_API_KEY=your_gemini_api_key
GEMINI_MODEL=gemini-1.5-flash

# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-4o

# Qwen Configuration
QWEN_API_KEY=your_qwen_api_key
QWEN_MODEL=qwen-max
QWEN_API_URL=https://your-qwen-api-endpoint
```

### Docker Usage Method

To simplify the installation process, we provide Docker support.

1. Build Docker image
```bash
docker build -t a-share-investment-agent .
```

2. Create a .env file containing API keys
```bash
# Create a .env file with the same format as above
touch .env
# Edit the .env file to add your API keys
```

## 🚀 Usage

### Basic Usage

```bash
python src/main.py --ticker 000001 --model qwen
```

### Test Mode

```bash
# Use default parameters (Qwen model and 000001 stock) for testing
python src/main.py --test

# Specify stock for testing
python src/main.py --test --ticker 600036
```

### Parameter Description

- `--ticker`: Stock code
- `--start-date`: Start date (YYYY-MM-DD)
- `--end-date`: End date (YYYY-MM-DD)
- `--show-reasoning`: Display analysis reasoning process
- `--num-of-news`: Number of news used for sentiment analysis
- `--initial-capital`: Initial cash amount
- `--initial-position`: Initial stock position
- `--model`: Model to use (gemini, openai, qwen)
- `--test`: Run test function with preset parameters

## 🚀 Example Results

### Analysis Results

Below is an example of the analysis results for Cambricon-U (688256) stock during the period 2025/01/04-2025/03/24:

```bash
python src/main.py --ticker 688256 --start-date 2025-01-04 --end-date 2025-03-24 --model qwen --show-reasoning
```

#### Agent Analysis Logs

**Market Data Agent**:
```json
{
"trend": "Short-term trend is downward, but long-term trend still needs observation",
"judgment": "Current price is below the middle Bollinger band, RSI is close to neutral level, MACD line is below the signal line, indicating short-term adjustment may continue. However, considering the previous significant rise, the long-term trend still needs further observation. Recommend paying attention to support level 670.66 and resistance level 747.57."
}
```

**Technical Analyst**:
```json
{
  "signal": "bearish",
  "confidence": 0.8,
  "reasoning": "From technical indicators, the stock is currently in a relatively weak state. First, the 5-day moving average (718.856) has crossed below the 10-day (743.927) and 20-day (747.574) moving averages, indicating the short-term trend is weakening. The MACD indicator also shows a similar trend, with the MACD line (8.994) below the signal line (20.004), and the MACD histogram (-11.009) negative, indicating market momentum is weakening. The RSI indicator (48.676) is in neutral territory but approaching oversold territory, which may indicate a short-term rebound, but the overall trend remains weak. On the Bollinger Bands, the current price (685.05) is close to the lower band (670.657), which may provide some support, but considering the weakness shown by other indicators, the support may be limited. Overall, the current market environment and technical indicators point toward a bearish trend."
}
```

**Fundamentals Analyst**:
```json
{
  "signal": "bearish",
  "confidence": 0.8,
  "reasoning": "Cambricon-U's financial condition and business performance show clear negative trends. First, the company's net profit continues to be negative, and the loss amount has increased in recent quarters, indicating serious problems with profitability. Second, although the company's operating revenue increased in the fourth quarter of 2023, it experienced a significant decline in subsequent quarters, which may indicate a decrease in market demand or company market share. Additionally, the company's P/E ratio is negative, and its P/B ratio is as high as 52.58, indicating overvaluation in the market with significant bubble risk. From a financial health perspective, although the company has a low debt-to-asset ratio, its operating cash flow continues to be negative, indicating the company faces significant financial pressure in operations. Considering these factors, we believe Cambricon-U's stock is currently bearish."
}
```

**Sentiment Analyst**:
```json
{
  "signal": "bullish",
  "confidence": 0.8,
  "reasoning": "From the news data, the overall market sentiment is positive, with positive news far outnumbering negative news. Although one news item mentions the decline of chip ETFs and Cambricon-U, most news emphasizes the positive performance of Cambricon-U and its sector, including stock price increases and technological breakthroughs. Additionally, the news of Cambricon-U being included in the FTSE China A50 Index indicates the market's optimistic outlook for its long-term prospects. Social media discussions also mainly focus on the company's positive developments, further supporting the bullish view.",
  "key_events": [
    "Cambricon-U included in FTSE China A50 Index",
    "Cambricon-U stock price rises multiple times",
    "AI AIETF holding stock Cambricon-U surges",
    "ZhiYuan QiYuan large model released"
  ]
}
```

**Valuation Analyst**:
```json
{
  "signal": "bearish",
  "confidence": 0.85,
  "reasoning": "Cambricon-U's financial condition and business performance show clear negative trends. First, the company's net profit continues to be negative, and the loss amount has increased in recent quarters, indicating serious problems with profitability. Second, although the company's operating revenue increased in the fourth quarter of 2023, it experienced a significant decline in subsequent quarters, which may indicate a decrease in market demand or company market share. Additionally, the company's P/E ratio is negative, and its P/B ratio is as high as 52.58, indicating overvaluation in the market with significant bubble risk. From a financial health perspective, although the company has a low debt-to-asset ratio, its operating cash flow continues to be negative, indicating the company faces significant financial pressure in operations. Considering these factors, we believe Cambricon-U's stock is currently bearish. Furthermore, calculated through DCF model and relative valuation methods, the company's intrinsic value is significantly lower than the current market price, further supporting the bearish view.",
  "fair_value": 200.0,
  "key_metrics": [
    "P/E Ratio",
    "P/B Ratio",
    "Operating Revenue",
    "Net Profit",
    "Operating Cash Flow"
  ]
}
```

**Researcher Bull**:
```json
{
  "key_points": [
    "Market sentiment is positive, news and social media discussions lean optimistic",
    "Cambricon-U included in FTSE China A50 Index, indicating market's optimistic outlook for its long-term prospects",
    "Positive news of technological breakthroughs and stock price increases",
    "Despite weakness in technical and fundamental aspects, market sentiment and potential catalysts may drive stock price rebound"
  ],
  "confidence": 0.6,
  "reasoning": "Despite technical and fundamental analysis showing Cambricon-U is currently in a weak state, market sentiment and potential catalysts may drive stock price rebound. Cambricon-U being included in the FTSE China A50 Index indicates the market's optimistic outlook for its long-term prospects. Additionally, recent positive news about technological breakthroughs and stock price increases also support the bullish view. Although current financial conditions and valuations are high, market sentiment and potential positive factors may provide support for the stock price. Therefore, we recommend maintaining caution in the short term, but in the long term, Cambricon-U still has investment potential."
}
```

**Researcher Bear**:
```json
{
  "key_points": [
    "Technical indicators show short-term trend weakening",
    "Net profit continues to be negative and losses increase",
    "Declining operating revenue indicates decreased market demand",
    "P/B ratio as high as 52.58, overvalued",
    "Operating cash flow continues to be negative, significant financial pressure",
    "DCF model and relative valuation methods show intrinsic value lower than market price"
  ],
  "confidence": 0.8,
  "reasoning": "Combining technical analysis, fundamental analysis, market sentiment analysis, and valuation analysis, Cambricon-U's stock is currently bearish. Technical indicators show short-term trend weakening, fundamental analysis shows poor profitability, decreased market demand, overvaluation, and significant financial pressure. Although market sentiment leans positive, these positive sentiments mainly focus on short-term events and cannot mask long-term fundamental issues. Valuation analysis further supports the bearish view, with intrinsic value significantly lower than current market price. Therefore, selling Cambricon-U stock is recommended."
}
```

**Debate Room**:
```json
{
  "signal": "neutral",
  "confidence": 0.7,
  "reasoning": "Both bull and bear researchers' views have rationality and basis. The bull researcher emphasizes positive market sentiment, Cambricon-U's inclusion in the FTSE China A50 Index, and positive news about technological breakthroughs and stock price increases, which may provide support for the stock price in the short term. However, the bear researcher points out technical indicators show short-term trend weakening, fundamental analysis shows poor profitability, decreased market demand, overvaluation, and significant financial pressure. Although market sentiment leans positive, these positive sentiments mainly focus on short-term events and cannot mask long-term fundamental issues. Overall, in the short term, market sentiment and technological breakthroughs may drive stock price rebound, but long-term fundamental issues still exist, so maintaining a neutral attitude and waiting for more clear signals is recommended.",
  "final_verdict": "Investors are advised to remain cautious in the short term and pay attention to the continuity of market sentiment and technological breakthroughs. In the long term, close attention should be paid to the company's fundamental improvements, especially in areas such as profitability, market demand, and financial pressure. Before more clear signals emerge, maintaining a neutral attitude and avoiding excessive optimism or pessimism is recommended."
}
```

**Risk Manager**:
```json
{
  "max_position_size": 0.2,
  "volatility": 0.15,
  "risk_score": 0.7,
  "max_drawdown": 0.25,
  "suggested_position_size": 0.15,
  "reasoning": "Given stock 688256's high volatility and fundamental risks, a cautious approach is recommended. Although there is potential for technical breakthrough in the short term, the company faces issues such as poor profitability in the long term. Therefore, it is recommended to control position ratio not exceeding 20% and set appropriate stop-loss points to protect capital. At the same time, diversify investments to spread risk."
}
```

**Portfolio Manager (Final Decision)**:
```json
{
  "action": "hold",
  "quantity": 0,
  "confidence": 0.8,
  "reasoning": "Considering various analysts' trading signals, debate results, risk analysis, current portfolio status, and latest market price, we decide to adopt a holding strategy for stock 688256. Technical analysis and fundamental analysis both show the stock is in a weak state, with technical indicators showing short-term trend weakening, and fundamentals showing poor profitability, decreased market demand, overvaluation, and significant financial pressure. Although sentiment analysis shows positive market sentiment, these positive sentiments mainly focus on short-term events and cannot mask long-term fundamental issues. The debate result also recommends caution in the short term, paying attention to the continuity of market sentiment and technological breakthroughs. In the long term, close attention should be paid to the company's fundamental improvements. Risk analysis recommends controlling position ratio not exceeding 20% and setting appropriate stop-loss points to protect capital. Therefore, we decide to temporarily hold the stock and wait for more clear signals."
}
```

#### Comprehensive Conclusion

**Final Investment Decision**: Hold (Confidence: 0.8)

The analysis results from multiple professional agents indicate that Cambricon-U (688256) stock is currently in a weak state in terms of technicals and fundamentals, but market sentiment and short-term events may provide support for the stock price. Considering all factors, the system recommends adopting a holding strategy for this stock and closely monitoring subsequent changes in fundamentals and market sentiment. At the same time, risk management recommends controlling the maximum position ratio of this stock to within 20% of the portfolio and setting appropriate stop-loss points to control risk.

## 🔄 Data Process Description

The system's data process follows these steps:

1. **Data Collection**: Market data agent collects A-share market data and news through akshare API
2. **Multi-dimensional Analysis**: Four professional analysis agents (technical, fundamental, sentiment, valuation) conduct analysis independently
3. **Bull/Bear Research**: Bull and bear researchers provide analysis reports from bullish and bearish perspectives respectively
4. **Debate Integration**: Debate room integrates bull and bear perspectives to form a final analytical opinion
5. **Risk Assessment**: Risk manager assesses investment risk and sets trading restrictions
6. **Final Decision**: Portfolio manager formulates the final trading decision and generates orders


## 📋 Project Structure

```
community_usecase/a_share_investment_agent_camel/
├── src/                       # Source code directory
│   ├── agents/                # Agent implementations
│   │   ├── base_agent.py      # Base agent class
│   │   ├── market_data_agent.py  # Market data agent
│   │   ├── technical_analyst.py  # Technical analyst agent
│   │   └── ...
│   ├── tools/                 # Tool modules
│   │   └── data_helper.py     # Data helper tools
│   ├── utils/                 # Utility tools
│   │   └── logging_utils.py   # Logging tools
│   ├── models.py              # Data model definitions
│   ├── roles.py               # Role definitions
│   └── main.py                # Main program
├── tests/                     # Test directory
├── logs/                      # Log files
├── .env                       # Environment variables
├── pyproject.toml             # Poetry configuration
├── requirements.txt           # Dependencies
└── README.md                  # Documentation
```

## 🔍 Code Implementation Highlights

### 1. Multi-agent Collaboration Architecture

This project implements 10 professional role agents, with each agent responsible for specific tasks in the investment analysis process. Agents collaborate through message passing, forming a complete analysis decision chain.

```python
# Create agents
market_data_agent = MarketDataAgent(show_reasoning=show_reasoning, model_name=model_name)
technical_analyst = TechnicalAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
fundamentals_analyst = FundamentalsAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
sentiment_analyst = SentimentAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
valuation_analyst = ValuationAnalystAgent(show_reasoning=show_reasoning, model_name=model_name)
researcher_bull = ResearcherBullAgent(show_reasoning=show_reasoning, model_name=model_name)
researcher_bear = ResearcherBearAgent(show_reasoning=show_reasoning, model_name=model_name)
debate_room = DebateRoomAgent(show_reasoning=show_reasoning, model_name=model_name)
risk_manager = RiskManagerAgent(show_reasoning=show_reasoning, model_name=model_name)
portfolio_manager = PortfolioManagerAgent(show_reasoning=show_reasoning, model_name=model_name)
```

### 2. Flexible Multi-model Support

The system supports multiple large language models including Gemini, OpenAI, and Qwen, implementing flexible switching through a unified interface.

```python
def get_llm_client(model_name: str):
    """Get the specified LLM client"""
    if model_name.lower() == 'gemini':
        return GeminiClient()
    elif model_name.lower() == 'openai':
        return OpenAIClient()
    elif model_name.lower() == 'qwen':
        return QwenClient()
    else:
        raise ValueError(f"Unsupported model: {model_name}")
```



## 📝 Improvements and Innovations

Compared to the original version, the system restructured based on the Camel framework has the following innovations and improvements:

1. **Modular Design**: Clearer agent definitions and system structure, facilitating extension and maintenance
2. **Multi-model Support**: Flexible support for multiple LLM models, improving system adaptability
3. **Comprehensive Logging System**: Detailed recording of each agent's work process, facilitating debugging and analysis


## ⚠️ Disclaimer

This project is for **educational and research purposes only**.

- Not suitable for actual trading or investment
- No guarantees provided
- Past performance does not represent future performance
- Creators bear no responsibility for any financial losses
- Consult professional financial advisors for investment decisions

By using this software, you agree to use it for learning purposes only.

## 📚 Related Resources

- [OWL Framework Official Documentation](https://github.com/camel-ai/owl)
- [Camel Framework Official Documentation](https://github.com/camel-ai/camel)
- [A_Share_investment_Agent](https://github.com/24mlight/A_Share_investment_Agent)

## 🙏 Acknowledgements

This project is improved based on the following open-source projects:

1. [A_Share_investment_Agent](https://github.com/24mlight/A_Share_investment_Agent) - Original A-share investment agent project, providing the foundation architecture and investment analysis ideas for this project. Special thanks for its innovative design in A-share data processing and analysis strategies.
2. [ai-hedge-fund](https://github.com/virattt/ai-hedge-fund.git) - Original US stock investment agent project
3. [Camel Framework](https://github.com/camel-ai/camel) - Multi-agent dialogue framework
4. [OWL Framework](https://github.com/camel-ai/owl) - Open-source multi-agent collaboration framework

Thanks to all the original authors for their contributions and inspiration, providing a solid foundation for this project.

---

## File: community_usecase/cooking-assistant/README.md

# Personal Dietician

This code example searches for recipes on the internet based on the ingredients you have, refines the content based on a dieterary restriction and generates shopping lists.

## How to use

1. Set up the OPENAI api key in the .env file

```bash
OPENAI_API_KEY = 'xxx'
```

2. Copy the python script to the owl/examples folder.

3. Run the script

```bash
python run_gpt4o.py
```

4. You can find the entire thought process of the agent within the log file.

5. Demo Link - https://drive.google.com/drive/folders/10LnMEMf_xQGojHyTAS57vI7oOmjvuKPE?usp=sharing

---

## File: community_usecase/excel_analyzer/README.md

# Excel Analyzer  
[中文](README_zh.md)

This project uses **Owl** for data analysis and visualization.

## Features

- Provides both English and Chinese versions of the raw data and prompts
- Utilizes **CodeExecutionToolkit**, **ExcelToolkit**, and **FileWriteToolkit** to complete related tasks  
- Implements **ExcelRolePlaying** based on **OwlRolePlaying**, which overrides the `system_prompt` with a cleaner, more focused version tailored for data analysis scenarios  
- tested using `gpt-4o` and `deepseek-v3`
- The analysis and visualization of this Excel file involve:
    - Complex headers (merged rows)
    - Nan value handling
    - Complex group calculations
    - Visualization

## How to Use  
1. Set up the environment according to Owl's official instructions
2. Run the following commands:  
    ```bash
    cd community_usecase/excel_analyzer

    # Chinese version, using deepseek-v3
    python excel_analyzer_zh.py

    # English version, using gpt-4o
    python excel_analyzer_zh.py
    ```
3. The analysis results will be saved in the current directory

---

## File: community_usecase/excel_analyzer/README_zh.md

# Excel Analyzer
这个项目使用owl来做数据分析和可视化


## Features
- 提供了英文，中文两个版本的原始数据和prompt，方便理解
- 使用**CodeExecutionToolkit**，**ExcelToolkit**，**FileWriteToolkit**来完成相关工作
- 在**OwlRolePlaying**基础之上实现了**ExcelRolePalying**，它重写了system_prompt，更简洁，聚焦在数据分析场景
- 经过测试，在`gpt-4o`和`deepseek-v3`下均可以达到预期效果
- 对该excel进行分析和可视化时涉及到的内容有：
    - 复杂表头（合并行）
    - 缺失值处理
    - 复杂的分组计算
    - 可视化

## How to use 
1. 按照owl的官方流程搭建好环境
2. 运行
    ```
    cd community_usecase/excel_analyzer

    # Chinese version, using deepseek-v3
    python excel_analyzer_zh.py

    # English version, using gpt-4o
    python excel_analyzer_zh.py
    ```
3. 数据集分析的结果将会在出存在当前目录下

---

## File: community_usecase/learning-assistant/README.md

# Learning Assistant

This code example searches the internet for relevant learning materials depending on the user's knowledge level and devises a concrete learning roadmap all tailored to the user.

## How to use

1. Set up the OPENAI api key in the .env file

```bash
OPENAI_API_KEY = 'xxx'
```

2. Copy the python script to the owl/examples folder.

3. Run the script

```bash
python run_gpt4o.py
```

4. You can find the entire thought process of the agent within the log file.

5. Video demo - https://drive.google.com/drive/folders/1msrNNwjeZ0DKhSXCi2w1ljz_hULSusa_?usp=sharing

---

## File: community_usecase/Mcp_use_case/Readme.md

# Autonomous Website Scraping with OWL + FireCrawl MCP
 
This project leverages OWL (Optimized Workforce Learning) and FireCrawl MCP (Model Context Protocol) to automate content curation. The system scrapes top tech news websites, extracts relevant information, and compiles a summary report.

## Features

- Uses **FireCrawl MCP Server** for performing web scraping.
- Implements **OwlRolePlaying** for enhanced multi-agent task execution.
- Scrapes **TechCrunch, The Verge, and Wired** using **FireCrawl**.
- Extracts and summarizes **headlines, article summaries, and publication dates**.
- Generates a digest report **(Latest_tech_digest.md)** based on trends from these sources.
- Runs a default scraping task which can be updated before running the Script.

## Installation

1. Clone this repository:
   ```sh
   git clone https://github.com/camel-ai/owl.git
   cd owl
   ```
2. Install dependencies:
   ```sh
   pip install -r requirements.txt
   ```
3. Set up environment variables:
   - Create a `.env` file and add your API keys/configuration as needed.

## Usage

Navigate to the community use case directory before running the script:

```sh
cd community_usecase/Mcp_use_Case
```

Run the script using:

```sh
python Content_curator.py 
```
The script automatically executes the default task without taking additional input from the terminal.

## Configuration

- The script reads from `mcp_servers_config.json`, which is located in the same folder as Mcp_use_case.
- Modify the `default_task` section in `Content_curator.py` to adjust scraping and summarization behavior.

## Improvements & Customization

- The current implementation runs a **default task** and does not take task input from the terminal.
- To modify the scraping target or change the extracted details, update the `default_task` in `Content_curator.py`.
- The project is stored in the `Mcp_use_Case` folder inside `community_usecase` in the OWL directory.

## Error Handling

- Ensures **graceful cleanup** in case of failures.
- Implements **try-except** blocks to handle tool execution errors.
- Cancels running async tasks to **prevent memory leaks**.
- Supports **KeyboardInterrupt** for a safe shutdown.

## Cleanup & Shutdown

- The script **automatically disconnects MCP** after execution.
- Cancels remaining async tasks to **prevent memory leaks**.
- Special handling for **Windows platforms** is included to ensure smooth termination.

## Repository

For more details, visit the OWL repository: [OWL GitHub Repo](https://github.com/camel-ai/owl)

---

## File: community_usecase/Notion-MCP/README.md

# Notion Integration with OWL

This project demonstrates the integration of Notion with OWL (Optimized Workforce Learning) using the official Notion MCP server. It provides automated interaction with Notion workspaces through AI agents.

## Prerequisites

- Python >=3.10,<3.13
- Node.js and npm
- CAMEL framework installed
- A Notion account and integration

## Installation

#### 1. Clone this repository:
   ```sh
   git clone https://github.com/camel-ai/owl.git
   cd owl
   ```
#### 2. Install dependencies:
   ```sh
   pip install -r requirements.txt
   ```
#### 3. Set up environment variables:
   - Create a `.env` file and add your API keys/configuration as needed.

## Setup

#### 1. Install the required Node.js package:
   ```bash
   npm install @notionhq/notion-mcp-server@latest
   ```

#### 2. Set up your Notion integration:
   - Go to https://www.notion.so/profile/integrations
   - Create a new integration
   - Copy the integration token
   - Update `mcp_servers_config.json` with your token

#### 3. Connect your Notion pages:
   - Open each Notion page you want to work with
   - Click "..." (three dots) in the top right
   - Select "Add connections"
   - Choose your integration

#### 4. Visit official Notion MCP GitHub Repository
Visit the [Notion_MCP GitHub Repo](https://github.com/makenotion/notion-mcp-server) for detailed setup instructions.

## Usage

Navigate to the community use case directory before running the script:

```sh
cd community_usecase/Notion_MCP
```

#### Run the script using:
   ```bash
   python notion_manager.py
   ```
   This will run the default task which:
   - Searches for a specific page
   - Updates its properties
   - Adds a comment


## Supported Operations

The integration supports these Notion API operations:
- Searching for pages
- Reading page content
- Updating page properties
- Adding comments
- Creating new pages
- Retrieving database content

## Troubleshooting

If you encounter errors:

    1. Verify your Notion token is correct
    2. Check that pages are connected to your integration
    3. Ensure you have the required permissions
    4. Check the Notion API version in config matches the current version

## Error Handling

The script includes:
- Graceful connection handling
- Task execution error catching
- Proper cleanup on exit
- Windows-specific asyncio handling

## Repository

For more details, visit the OWL repository: [OWL GitHub Repo](https://github.com/camel-ai/owl)