SwarmsによるマルチAIエージェントフレームワークを実行してみた際の備忘録

SwarmsによるマルチAIエージェントフレームワークを実行してみた際の備忘録です
[こちらの続きです](https://qiita.com/seigot/items/74db26e967704a37394a)

## Swarmsについて

マルチAIエージェントオーケストレーションフレームワークです。
これを使うことで、LLMを利用したAIエージェントを組み合わせ、複雑なタスクを自動化することが可能です。
[前回はシングルエージェント環境サンプルコードを実行しました。](https://qiita.com/seigot/items/74db26e967704a37394a)
今回はマルチAIエージェント環境でコードを実行してみます。

リンク: Swarms GitHubリポジトリ

https://github.com/kyegomez/swarms
https://docs.swarms.world/en/latest/

## 準備

- Python環境の構築

venv環境を使います、以下は例です。

```bash
# cd (working directry)
python3 -m venv venv
source venv/bin/activate
# (deactivate)
```

`venv`環境下で`swarms`と`openai`をインストールします
※ OpenAI以外を使う場合は追加で他パッケージのインストールが必要になると思います

```bash
pip install swarms
pip install openai
```

- OPEN AI APIトークンを取得
[こちら](https://qiita.com/yamii/items/914fcae6599a4ac9f9fd)や[こちら](https://qiita.com/seigot/items/f89ea1633783bc5fc1b5)を参考にOPEN AI APIトークンを取得します

その後、`export OPENAI_API_KEY=xxxxx`をコマンドラインから実行して環境変数からAPI_KEYを参照できるようにしておきます。

```bash
export OPENAI_API_KEY=xxxxx
```

## サンプルコード1: SwarmのAIエージェントはビジネスの成長にどのように寄与しますか？`に対するブログ生成と要約をしてもらうユースケース

まずは、[swarmsリポジトリ記載のサンプルコードを実行します。](https://github.com/kyegomez/swarms?tab=readme-ov-file#sequentialworkflow)
これは`SequentialWorkflow`という構造であり、複数のAIエージェントを順番に連携させるものです。

> Sequential Workflow enables you to sequentially execute tasks with Agent and then pass the output into the next agent and onwards until you have specified your max loops.

https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#sequential-swarm

- `SequentialWorkflow`のイメージ図

![スクリーンショット 2024-08-16 12.03.22.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/344880/5e0dfa75-17c7-345f-50ef-dd8943f568ce.png)

- コード

`"Blog generator"`と、`"summarizer"`を呼び出し、
`SwarmのAIエージェントはビジネスの成長にどのように寄与しますか？`に対するブログ生成と要約をしてもらいます。

> "Generate a blog post on how swarms of agents can help businesses grow."

```python:multi_agent.py
from swarms import Agent, SequentialWorkflow, OpenAIChat
import os

# Initialize the language model agent (e.g., GPT-3)
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
# export OPENAI_API_KEY=xxxxx

# Create an instance of the OpenAIChat class
model = OpenAIChat(
    api_key=api_key, model_name="gpt-4o", temperature=0.1
)

# Initialize agents for individual tasks
agent1 = Agent(
    agent_name="Blog generator",
    system_prompt="Generate a blog post like stephen king",
    llm=model,
    max_loops=1,
    dashboard=False,
    tools=[],
)
agent2 = Agent(
    agent_name="summarizer",
    system_prompt="Sumamrize the blog post",
    llm=model,
    max_loops=1,
    dashboard=False,
    tools=[],
)

# Create the Sequential workflow
workflow = SequentialWorkflow(
    agents=[agent1, agent2], max_loops=1, verbose=False
)

# Run the workflow
workflow.run(
    "Generate a blog post on how swarms of agents can help businesses grow."
)
```

- そのまま実行


<!-- open属性なし -->
<details><summary>実行結果とそのログ（長いので折りたたんでいます）</summary>

```python:
% python multi_agent.py 
/Users/seigo/Desktop/python/tools/openai/venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`.
  warn_deprecated(
Initializing Autonomous Agent Blog generator...
2024-08-16T12:06:24.225131-0700 Tools provided make sure the functions have documentation ++ type hints, otherwise tool execution won't be reliable.
2024-08-16T12:06:24.225429-0700 Tools provided: Accessing 0 tools
2024-08-16T12:06:24.225521-0700 Converting tools into OpenAI function calling schema
2024-08-16T12:06:24.232883-0700 Logger initialized and artifacts directory set up.
Initializing Autonomous Agent summarizer...
2024-08-16T12:06:24.234380-0700 Tools provided make sure the functions have documentation ++ type hints, otherwise tool execution won't be reliable.
2024-08-16T12:06:24.234519-0700 Tools provided: Accessing 0 tools
2024-08-16T12:06:24.234647-0700 Converting tools into OpenAI function calling schema
2024-08-16T12:06:24.241641-0700 Logger initialized and artifacts directory set up.
2024-08-16T12:06:24.242267-0700 AgentRearrange initialized with agents: ['Blog generator', 'summarizer']
2024-08-16T12:06:24.242531-0700 Running task with dynamic flow: Blog generator -> summarizer
Flow is valid.
2024-08-16T12:06:24.242716-0700 Running agents sequentially: ['Blog generator']
2024-08-16T12:06:24.242905-0700 Autonomous Agent Activated.
2024-08-16T12:06:24.243161-0700 All systems operational. Executing task...

Loop 1 of 1




Sure, let's dive into the eerie and fascinating world of swarms of agents and how they can help businesses grow, in a style reminiscent of Stephen King.

---

### The Swarm: How Agents Can Help Your Business Grow

In the dimly lit corridors of corporate America, where shadows stretch long and secrets whisper through the walls, a new force is emerging. It's not a ghost or a ghoul, but something far more powerful and enigmatic: swarms of agents. These digital phantoms, working in unison, have the potential to transform businesses in ways that are both thrilling and terrifying.

#### The Birth of the Swarm

Imagine a dark, stormy night. Lightning cracks the sky, illuminating a lone figure hunched over a computer. This isn't the beginning of a horror story, but rather the dawn of a new era in business. Swarms of agents, powered by artificial intelligence, are being unleashed into the world. These agents, like a colony of ants or a flock of birds, work together seamlessly, each one playing a crucial role in the larger system.

#### The Power of Many

In the natural world, swarms are a testament to the power of many. A single ant is insignificant, but a colony can move mountains. Similarly, a single AI agent might be limited, but a swarm can achieve remarkable feats. These agents can analyze vast amounts of data, predict market trends, optimize supply chains, and even interact with customers, all in real-time.

#### The Haunted Data

But with great power comes great responsibility. The data these agents feed on is vast and complex, often containing hidden patterns and secrets. It's as if the data itself is haunted, whispering secrets to those who know how to listen. Businesses that can harness this haunted data can gain insights that were previously unimaginable, giving them a competitive edge.

#### The Unseen Workforce

These swarms of agents operate in the shadows, unseen and often unnoticed. They don't require sleep or food, and they can work tirelessly around the clock. This unseen workforce can handle mundane tasks, freeing up human employees to focus on more creative and strategic endeavors. It's like having an army of tireless, invisible workers at your disposal.

#### The Ethical Dilemma

But as with any powerful tool, there are ethical considerations. The use of swarms of agents raises questions about privacy, security, and the potential for misuse. Businesses must tread carefully, ensuring that they use this technology responsibly and transparently. After all, the line between a helpful tool and a malevolent force can be thin.

#### The Future Beckons

As we stand on the precipice of this new era, the potential for growth is immense. Businesses that embrace swarms of agents can unlock new levels of efficiency, innovation, and customer satisfaction. But they must also be wary of the shadows, ensuring that they use this power for good.

In the end, the story of swarms of agents is one of both promise and peril. It's a tale that will continue to unfold, with twists and turns that are sure to keep us on the edge of our seats. So, as you navigate the dark corridors of the business world, remember: the swarm is out there, waiting to help you grow, if you dare to harness its power.

---

And there you have it, a blog post that delves into the mysterious and powerful world of swarms of agents, written in a style inspired by the master of suspense, Stephen King.
2024-08-16T12:07:04.244117-0700 Running agents sequentially: ['summarizer']
2024-08-16T12:07:04.245094-0700 Autonomous Agent Activated.
2024-08-16T12:07:04.245431-0700 All systems operational. Executing task...

Loop 1 of 1

To summarize the blog post, we need to extract the key points and present them in a concise manner. Here is the summary:

---

### Summary of "The Swarm: How Agents Can Help Your Business Grow"

1. **Introduction to Swarms of Agents**:
   - Swarms of AI agents are emerging as a powerful force in the business world.
   - These agents work together seamlessly, similar to a colony of ants or a flock of birds.

2. **Capabilities of Swarms**:
   - They can analyze vast amounts of data, predict market trends, optimize supply chains, and interact with customers in real-time.
   - The collective power of many agents can achieve remarkable feats.

3. **Data Insights**:
   - The data these agents analyze is vast and complex, often containing hidden patterns and secrets.
   - Businesses that harness this data can gain significant competitive advantages.

4. **Unseen Workforce**:
   - Swarms of agents operate tirelessly and unseen, handling mundane tasks and freeing up human employees for more strategic work.

5. **Ethical Considerations**:
   - The use of swarms raises questions about privacy, security, and potential misuse.
   - Businesses must use this technology responsibly and transparently.

6. **Future Potential**:
   - Embracing swarms of agents can unlock new levels of efficiency, innovation, and customer satisfaction.
   - The technology holds both promise and peril, requiring careful navigation.

---

This summary captures the essence of the blog post, highlighting the main points about the potential and ethical considerations of using swarms of AI agents in business.

No tool usage is required for this task as it involves summarizing the provided text. If you have any further requests or need additional assistance, feel free to ask!
To summarize the blog post, we need to extract the key points and present them in a concise manner. Here is the summary:

---

### Summary of "The Swarm: How Agents Can Help Your Business Grow"

1. **Introduction to Swarms of Agents**:
   - Swarms of AI agents are emerging as a powerful force in the business world.
   - These agents work together seamlessly, similar to a colony of ants or a flock of birds.

2. **Capabilities of Swarms**:
   - They can analyze vast amounts of data, predict market trends, optimize supply chains, and interact with customers in real-time.
   - The collective power of many agents can achieve remarkable feats.

3. **Data Insights**:
   - The data these agents analyze is vast and complex, often containing hidden patterns and secrets.
   - Businesses that harness this data can gain significant competitive advantages.

4. **Unseen Workforce**:
   - Swarms of agents operate tirelessly and unseen, handling mundane tasks and freeing up human employees for more strategic work.

5. **Ethical Considerations**:
   - The use of swarms raises questions about privacy, security, and potential misuse.
   - Businesses must use this technology responsibly and transparently.

6. **Future Potential**:
   - Embracing swarms of agents can unlock new levels of efficiency, innovation, and customer satisfaction.
   - The technology holds both promise and peril, requiring careful navigation.

---

This summary captures the essence of the blog post, highlighting the main points about the potential and ethical considerations of using swarms of AI agents in business.

No tool usage is required for this task as it involves summarizing the provided text. If you have any further requests or need additional assistance, feel free to ask!
```

</details>

ログを確認すると、`'Blog generator'`と`'summarizer'`が起動し、
`'Blog generator'`と`'summarizer'`が連携して最終的な結果を出力していることがわかります。

```bash
2024-08-16T12:06:24.242531-0700 Running task with dynamic flow: Blog generator -> summarizer
...
2024-08-16T12:06:24.242716-0700 Running agents sequentially: ['Blog generator']
...
2024-08-16T12:07:04.244117-0700 Running agents sequentially: ['summarizer']
2024-08-16T12:07:04.245094-0700 Autonomous Agent Activated.
2024-08-16T12:07:04.245431-0700 All systems operational. Executing task...
...
### Summary of "The Swarm: How Agents Can Help Your Business Grow"

1. **Introduction to Swarms of Agents**:
   - Swarms of AI agents are emerging as a powerful force in the business world.
   - These agents work together seamlessly, similar to a colony of ants or a flock of birds.

2. **Capabilities of Swarms**:
   - They can analyze vast amounts of data, predict market trends, optimize supply chains, and interact with customers in real-time.
   - The collective power of many agents can achieve remarkable feats.

3. **Data Insights**:
   - The data these agents analyze is vast and complex, often containing hidden patterns and secrets.
   - Businesses that harness this data can gain significant competitive advantages.

4. **Unseen Workforce**:
   - Swarms of agents operate tirelessly and unseen, handling mundane tasks and freeing up human employees for more strategic work.

5. **Ethical Considerations**:
   - The use of swarms raises questions about privacy, security, and potential misuse.
   - Businesses must use this technology responsibly and transparently.

6. **Future Potential**:
   - Embracing swarms of agents can unlock new levels of efficiency, innovation, and customer satisfaction.
   - The technology holds both promise and peril, requiring careful navigation.
---
```

## サンプルコード２：回覧板のチェックをエージェントが実施するユースケース

もうすこしマルチエージェント環境を感じたいと思い、住民の回覧板のチェックをエージェントが実施するユースケースを考えてみました。以下のような構成です。

以下の前提条件下で、以下のような3つのエージェントを定義します。

> 前提条件：
あなたは大阪のとある寮でお祭り開催に向けた自治会総会を計画しています。
寮のに住人にも参加してもらう必要があり、出欠確認のために回覧板を使おうと考えています。
エージェント1: 住人1用エージェント。回覧板を確認した後、住人1欄にチェックする。
エージェント2: 住人2用エージェント。回覧板を確認した後、住人2欄にチェックする。
エージェント3: 住人3用エージェント。回覧板を確認した後、住人3欄にチェックする。

回覧板は以下のような見た目です。回覧を通じて、出欠欄にチェックを依頼します。
[尚、フォーマットはマークダウンです。](https://github.com/seigot/tools/blob/master/openai/circular_board.md)

![スクリーンショット 2024-08-16 13.18.23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/344880/9b3c4ca2-cc6c-5204-6199-4ccb89c6c8b3.png)

- イメージ図

![スクリーンショット 2024-08-16 13.46.02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/344880/c460770d-61dd-b343-2826-01ff064a06a0.png)


## サンプルコード２ コード

<!-- open属性なし -->
<details><summary>コード（長いので折りたたんでいます）</summary>

```python:multi_agent2.py
from swarms import Agent, SequentialWorkflow, OpenAIChat
import os

# Initialize the language model agent (e.g., GPT-3)
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
# export OPENAI_API_KEY=xxxxx

# Create an instance of the OpenAIChat class
model = OpenAIChat(
    api_key=api_key, model_name="gpt-4o", temperature=0.1
)

# Initialize agents for individual tasks
agent1 = Agent(
    agent_name="resident1",
    system_prompt="Please answer by placing a check mark in the column for resident 1 in the table written in markdown.",
    llm=model,
    max_loops=1,
    dashboard=False,
    tools=[],
)
agent2 = Agent(
    agent_name="resident2",
    system_prompt="Please answer by placing a check mark in the column for resident 2 in the table written in markdown.",
    llm=model,
    max_loops=1,
    dashboard=False,
    tools=[],
)
agent3 = Agent(
    agent_name="resident3",
    system_prompt="Please answer by placing a check mark in the column for resident 3 in the table written in markdown.",
    llm=model,
    max_loops=1,
    dashboard=False,
    tools=[],
)

# Create the Sequential workflow
workflow = SequentialWorkflow(
    agents=[agent1, agent2, agent3], max_loops=1, verbose=False
)

# Run the workflow
out = workflow.run(
    "# 自治会総会の出欠連絡 \
    **概要**  \
    来月のお祭りに向けて、自治会総会を開催します。  \
    出欠欄の記入後、次の方へ回覧して下さい。  \
    **日時**: 2024年9月10日 18:00  \
    **場所**: 自治会館  \
    --- \
    ## 出欠欄 \
    - **住人1**: [ ] 出席  [ ] 欠席  \
    - **住人2**: [ ] 出席  [ ] 欠席  \
    - **住人3**: [ ] 出席  [ ] 欠席  \
    --- \
    **回覧板を次の方へお回しください。** "
)
print(out)
```

</details>

https://github.com/seigot/tools/blob/master/openai/multi_agent2.py

## サンプルコード２ 実行結果

<!-- open属性なし -->
<details><summary>実行結果とそのログ（長いので折りたたんでいます）</summary>

```bash
$ python multi_agent2.py
/Users/seigo/Desktop/python/tools/openai/venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`.
  warn_deprecated(
Initializing Autonomous Agent resident1...
2024-08-16T12:42:38.461086-0700 Tools provided make sure the functions have documentation ++ type hints, otherwise tool execution won't be reliable.
2024-08-16T12:42:38.461379-0700 Tools provided: Accessing 0 tools
2024-08-16T12:42:38.461449-0700 Converting tools into OpenAI function calling schema
2024-08-16T12:42:38.468503-0700 Logger initialized and artifacts directory set up.
Initializing Autonomous Agent resident2...
2024-08-16T12:42:38.469646-0700 Tools provided make sure the functions have documentation ++ type hints, otherwise tool execution won't be reliable.
2024-08-16T12:42:38.469787-0700 Tools provided: Accessing 0 tools
2024-08-16T12:42:38.469873-0700 Converting tools into OpenAI function calling schema
2024-08-16T12:42:38.477424-0700 Logger initialized and artifacts directory set up.
Initializing Autonomous Agent resident3...
2024-08-16T12:42:38.477951-0700 Tools provided make sure the functions have documentation ++ type hints, otherwise tool execution won't be reliable.
2024-08-16T12:42:38.478121-0700 Tools provided: Accessing 0 tools
2024-08-16T12:42:38.478225-0700 Converting tools into OpenAI function calling schema
2024-08-16T12:42:38.485624-0700 Logger initialized and artifacts directory set up.
2024-08-16T12:42:38.486142-0700 AgentRearrange initialized with agents: ['resident1', 'resident2', 'resident3']
2024-08-16T12:42:38.486343-0700 Running task with dynamic flow: resident1 -> resident2 -> resident3
Flow is valid.
2024-08-16T12:42:38.486479-0700 Running agents sequentially: ['resident1']
2024-08-16T12:42:38.486627-0700 Autonomous Agent Activated.
2024-08-16T12:42:38.486784-0700 All systems operational. Executing task...

Loop 1 of 1

Certainly! Here is the table with the check mark for resident 1 in markdown format:

markdown
## 出欠欄
- **住人1**: [x] 出席  [ ] 欠席
- **住人2**: [ ] 出席  [ ] 欠席
- **住人3**: [ ] 出席  [ ] 欠席

Please let me know if you need any further assistance!
2024-08-16T12:42:40.637626-0700 Running agents sequentially: ['resident2']
2024-08-16T12:42:40.638981-0700 Autonomous Agent Activated.
2024-08-16T12:42:40.639299-0700 All systems operational. Executing task...

Loop 1 of 1

Certainly! Here is the table with the check mark for resident 2 in markdown format:

markdown
## 出欠欄
- **住人1**: [x] 出席  [ ] 欠席
- **住人2**: [x] 出席  [ ] 欠席
- **住人3**: [ ] 出席  [ ] 欠席

If you need any further assistance, feel free to ask!
2024-08-16T12:42:42.692805-0700 Running agents sequentially: ['resident3']
2024-08-16T12:42:42.693719-0700 Autonomous Agent Activated.
2024-08-16T12:42:42.694269-0700 All systems operational. Executing task...

Loop 1 of 1

Certainly! Here is the table with the check mark for resident 3 in markdown format:

markdown
## 出欠欄
- **住人1**: [x] 出席  [ ] 欠席
- **住人2**: [x] 出席  [ ] 欠席
- **住人3**: [x] 出席  [ ] 欠席

If you need any further assistance, feel free to ask!
Certainly! Here is the table with the check mark for resident 3 in markdown format:

markdown
## 出欠欄
- **住人1**: [x] 出席  [ ] 欠席
- **住人2**: [x] 出席  [ ] 欠席
- **住人3**: [x] 出席  [ ] 欠席
```

</details>

ログを確認すると、`'resident1'`、`'resident2'`、`'resident3'`が起動し、
出欠確認を順番にチェックしていることがわかります。（今回は全員出席）

```bash
...
Certainly! Here is the table with the check mark for resident 1 in markdown format:
## 出欠欄
- **住人1**: [x] 出席  [ ] 欠席
- **住人2**: [ ] 出席  [ ] 欠席
- **住人3**: [ ] 出席  [ ] 欠席

...
Certainly! Here is the table with the check mark for resident 2 in markdown format:
markdown
## 出欠欄
- **住人1**: [x] 出席  [ ] 欠席
- **住人2**: [x] 出席  [ ] 欠席
- **住人3**: [ ] 出席  [ ] 欠席

...
Certainly! Here is the table with the check mark for resident 3 in markdown format:
markdown
## 出欠欄
- **住人1**: [x] 出席  [ ] 欠席
- **住人2**: [x] 出席  [ ] 欠席
- **住人3**: [x] 出席  [ ] 欠席
```

住人1にチェック[x]がついている様子
![スクリーンショット 2024-08-16 13.34.13.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/344880/1bf46351-49ab-0b01-647e-83005422cbe4.png)

住人2にチェック[x]がついている様子
![スクリーンショット 2024-08-16 13.34.07.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/344880/5b54e038-23ed-c42d-7e67-f0226a34f690.png)

住人3にチェック[x]がついている様子
![スクリーンショット 2024-08-16 13.34.01.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/344880/a736d689-639e-4b0a-9d73-3feb9dc28e7e.png)



## まとめ

- SwarmsによるマルチAIエージェントフレームワークを実行してみました
- 思ったよりサクッと動き、さらに拡張できる可能性をすごく感じた
- 「これ便利だよ、実はAIなんだ」の状態を目指してみたい

## 参考

https://github.com/kyegomez/swarms

https://docs.swarms.world/en/latest/

https://github.com/kyegomez/swarms?tab=readme-ov-file#sequentialworkflow

https://github.com/seigot/tools/blob/master/openai/multi_agent1.py

https://github.com/seigot/tools/blob/master/openai/multi_agent2.py