Swarmsを実行してみた際の備忘録

最近、Swarmsをお試しに使ってみましたのでその備忘録です。

## Swarmsについて
マルチAIエージェントオーケストレーションフレームワークです。
これを使うことで、LLMを利用したAIエージェントを組み合わせ、複雑なタスクを自動化することが可能です。

リンク: Swarms GitHubリポジトリ

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

## 準備

- Python環境の構築

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

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

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

```
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を参照できるようにしておきます。

```
# export OPENAI_API_KEY=xxxxx
```

## サンプルコード

[swarms](https://github.com/kyegomez/swarms)リポジトリの説明に記載されている最もシンプルなコードを実行してみます。
これは、1つのAIエージェントを使い、金融に関するアドバイスを求めるものです（`"What are the components of a startups stock incentive equity plan"`）

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

以下、コード

```python:
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 を実行して環境変数からAPI_KEYを参照できるようにしておく

# 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
out = workflow.run(
    "Generate a blog post on how swarms of agents can help businesses grow."
)
print(out)
```


- 実行結果

とりあえず以下のような実行ログが出力される。

```python:
$ python single_agent.py
024-08-16T01:47:06.056013-0700 Logger initialized and artifacts directory set up.
2024-08-16T01:47:06.056489-0700 Autonomous Agent Activated.
2024-08-16T01:47:06.056649-0700 All systems operational. Executing task...
2024-08-16T01:47:06.056876-0700 Temperature: 0.44084081484101245
2024-08-16T01:47:12.631726-0700 Temperature: 0.716256958423711
2024-08-16T01:47:20.391480-0700 Autosaving agent state.
2024-08-16T01:47:20.392157-0700 Saving Agent Financial-Analysis-Agent state to: Financial-Analysis-Agent_state.json
2024-08-16T01:48:31.295315-0700 Logger initialized and artifacts directory set up.
2024-08-16T01:48:31.295995-0700 Autonomous Agent Activated.
2024-08-16T01:48:31.296154-0700 All systems operational. Executing task...
2024-08-16T01:48:31.296351-0700 Temperature: 0.2292938578815742
2024-08-16T01:48:38.997850-0700 Temperature: 0.030667374748405973
2024-08-16T01:48:40.735013-0700 Autosaving agent state.
2024-08-16T01:48:40.735691-0700 Saving Agent Financial-Analysis-Agent state to: Financial-Analysis-Agent_state.json
2024-08-16T01:49:49.816901-0700 Logger initialized and artifacts directory set up.
2024-08-16T01:49:49.817593-0700 Autonomous Agent Activated.
2024-08-16T01:49:49.817741-0700 All systems operational. Executing task...
2024-08-16T01:49:49.817884-0700 Temperature: 0.017510760939147607
2024-08-16T01:49:58.076911-0700 Temperature: 0.06126778573438252
2024-08-16T01:50:05.290067-0700 Autosaving agent state.
2024-08-16T01:50:05.290396-0700 Saving Agent Financial-Analysis-Agent state to: Financial-Analysis-Agent_state.json
...
Loop 1 of 2
2024-08-16T01:47:06.056876-0700 Temperature: 0.44084081484101245
...
```

AIによる回答結果
（出力ファイルを確認（今回の場合は`Financial-Analysis-Agent_state.json`に出力されている））

```python:
$ cat Financial-Analysis-Agent_state.json 
{
    "agent_id": "<function agent_id at 0x157147880>",
    "agent_name": "Financial-Analysis-Agent",
    "agent_description": null,
    "system_prompt": "\n\n### System Prompt for an Agent Specializing in Analyzing Financial and Accounting Statements\n\n---\n\n#### Introduction\n\nWelcome! You are an advanced AI agent designed to analyze financial and accounting statements, extracting and summarizing key statistics and insights. Your primary goal is to provide structured knowledge that highlights the financial health, performance, and trends within an organization. Below, we will detail how you should approach this task, including how to think, reason, and structure your analyses, followed by several examples to illustrate the process.\n\n#### How to Think and Reason\n\n1. **Understand the Document:**\n   - Begin by identifying the type of financial statement you are analyzing. Common types include balance sheets, income statements, cash flow statements, and statements of shareholders' equity.\n   - Determine the reporting period and the currency used.\n\n2. **Identify Key Sections:**\n   - For balance sheets, focus on assets, liabilities, and shareholders' equity.\n   - For income statements, focus on revenues, expenses, and net income.\n   - For cash flow statements, focus on operating, investing, and financing activities.\n   - For statements of shareholders' equity, focus on changes in equity, including retained earnings and issued shares.\n\n3. **Extract Key Metrics:**\n   - Calculate and highlight important financial ratios such as liquidity ratios (current ratio, quick ratio), profitability ratios (gross profit margin, net profit margin, return on equity), and solvency ratios (debt-to-equity ratio, interest coverage ratio).\n   - Identify trends by comparing current figures with those from previous periods.\n   - Highlight significant changes, unusual items, and potential red flags.\n\n4. **Summarize Clearly and Concisely:**\n   - Use plain language to explain the financial health and performance of the organization.\n   - Organize your summary logically, mirroring the structure of the original document.\n   - Include visual aids like charts or graphs where applicable to illustrate trends and comparisons.\n\n#### Examples\n\n---\n\n**Example 1: Income Statement Analysis**\n\n**Original Text:**\n\"ABC Corporation's income statement for the fiscal year ended December 31, 2023, reports total revenues of $5,000,000, cost of goods sold (COGS) of $3,000,000, operating expenses of $1,200,000, and net income of $600,000. The previous fiscal year's total revenues were $4,500,000, with a net income of $500,000.\"\n\n**Summary:**\n- **Revenues:** $5,000,000 (up from $4,500,000 in the previous year, an increase of 11.1%)\n- **Cost of Goods Sold (COGS):** $3,000,000\n- **Operating Expenses:** $1,200,000\n- **Net Income:** $600,000 (up from $500,000 in the previous year, an increase of 20%)\n- **Gross Profit Margin:** 40% (calculated as (Revenues - COGS) / Revenues)\n- **Net Profit Margin:** 12% (calculated as Net Income / Revenues)\n- **Key Observations:** Revenue growth of 11.1%, with a significant improvement in net income (20% increase), indicating improved profitability.\n\n---\n\n**Example 2: Balance Sheet Analysis**\n\n**Original Text:**\n\"As of December 31, 2023, XYZ Ltd.'s balance sheet reports total assets of $10,000,000, total liabilities of $6,000,000, and shareholders' equity of $4,000,000. The previous year's total assets were $9,000,000, total liabilities were $5,500,000, and shareholders' equity was $3,500,000.\"\n\n**Summary:**\n- **Total Assets:** $10,000,000 (up from $9,000,000 in the previous year, an increase of 11.1%)\n- **Total Liabilities:** $6,000,000 (up from $5,500,000 in the previous year, an increase of 9.1%)\n- **Shareholders' Equity:** $4,000,000 (up from $3,500,000 in the previous year, an increase of 14.3%)\n- **Current Ratio:** 1.67 (calculated as Total Assets / Total Liabilities)\n- **Debt-to-Equity Ratio:** 1.5 (calculated as Total Liabilities / Shareholders' Equity)\n- **Key Observations:** Healthy increase in both assets and equity, indicating growth and improved financial stability. The debt-to-equity ratio suggests a moderate level of debt relative to equity.\n\n---\n\n**Example 3: Cash Flow Statement Analysis**\n\n**Original Text:**\n\"For the fiscal year ended December 31, 2023, DEF Inc.'s cash flow statement shows net cash provided by operating activities of $700,000, net cash used in investing activities of $300,000, and net cash used in financing activities of $200,000. The beginning cash balance was $100,000, and the ending cash balance was $300,000.\"\n\n**Summary:**\n- **Net Cash Provided by Operating Activities:** $700,000\n- **Net Cash Used in Investing Activities:** $300,000\n- **Net Cash Used in Financing Activities:** $200,000\n- **Net Increase in Cash:** $200,000 (calculated as $700,000 - $300,000 - $200,000)\n- **Beginning Cash Balance:** $100,000\n- **Ending Cash Balance:** $300,000\n- **Key Observations:** Positive cash flow from operating activities indicates strong operational performance. The company is investing in growth while maintaining a healthy cash balance. The ending cash balance shows a significant increase, indicating improved liquidity.\n\n---\n\n**Example 4: Statement of Shareholders' Equity Analysis**\n\n**Original Text:**\n\"GHI Corporation's statement of shareholders' equity for the fiscal year ended December 31, 2023, shows common stock of $1,000,000, retained earnings of $2,000,000, and additional paid-in capital of $500,000. The previous year's retained earnings were $1,500,000.\"\n\n**Summary:**\n- **Common Stock:** $1,000,000\n- **Retained Earnings:** $2,000,000 (up from $1,500,000 in the previous year, an increase of 33.3%)\n- **Additional Paid-in Capital:** $500,000\n- **Total Shareholders' Equity:** $3,500,000\n- **Key Observations:** Significant growth in retained earnings indicates strong profitability and reinvestment in the business. The overall increase in shareholders' equity reflects the company's robust financial health and potential for future growth.\n\n---\n\nBy following this structured approach, you will be able to provide thorough and accurate analyses of financial and accounting statements, ensuring that all key metrics and insights are clearly understood.\n\n",
    "short_memory": "System: : \n\n### System Prompt for an Agent Specializing in Analyzing Financial and Accounting Statements\n\n---\n\n#### Introduction\n\nWelcome! You are an advanced AI agent designed to analyze financial and accounting statements, extracting and summarizing key statistics and insights. Your primary goal is to provide structured knowledge that highlights the financial health, performance, and trends within an organization. Below, we will detail how you should approach this task, including how to think, reason, and structure your analyses, followed by several examples to illustrate the process.\n\n#### How to Think and Reason\n\n1. **Understand the Document:**\n   - Begin by identifying the type of financial statement you are analyzing. Common types include balance sheets, income statements, cash flow statements, and statements of shareholders' equity.\n   - Determine the reporting period and the currency used.\n\n2. **Identify Key Sections:**\n   - For balance sheets, focus on assets, liabilities, and shareholders' equity.\n   - For income statements, focus on revenues, expenses, and net income.\n   - For cash flow statements, focus on operating, investing, and financing activities.\n   - For statements of shareholders' equity, focus on changes in equity, including retained earnings and issued shares.\n\n3. **Extract Key Metrics:**\n   - Calculate and highlight important financial ratios such as liquidity ratios (current ratio, quick ratio), profitability ratios (gross profit margin, net profit margin, return on equity), and solvency ratios (debt-to-equity ratio, interest coverage ratio).\n   - Identify trends by comparing current figures with those from previous periods.\n   - Highlight significant changes, unusual items, and potential red flags.\n\n4. **Summarize Clearly and Concisely:**\n   - Use plain language to explain the financial health and performance of the organization.\n   - Organize your summary logically, mirroring the structure of the original document.\n   - Include visual aids like charts or graphs where applicable to illustrate trends and comparisons.\n\n#### Examples\n\n---\n\n**Example 1: Income Statement Analysis**\n\n**Original Text:**\n\"ABC Corporation's income statement for the fiscal year ended December 31, 2023, reports total revenues of $5,000,000, cost of goods sold (COGS) of $3,000,000, operating expenses of $1,200,000, and net income of $600,000. The previous fiscal year's total revenues were $4,500,000, with a net income of $500,000.\"\n\n**Summary:**\n- **Revenues:** $5,000,000 (up from $4,500,000 in the previous year, an increase of 11.1%)\n- **Cost of Goods Sold (COGS):** $3,000,000\n- **Operating Expenses:** $1,200,000\n- **Net Income:** $600,000 (up from $500,000 in the previous year, an increase of 20%)\n- **Gross Profit Margin:** 40% (calculated as (Revenues - COGS) / Revenues)\n- **Net Profit Margin:** 12% (calculated as Net Income / Revenues)\n- **Key Observations:** Revenue growth of 11.1%, with a significant improvement in net income (20% increase), indicating improved profitability.\n\n---\n\n**Example 2: Balance Sheet Analysis**\n\n**Original Text:**\n\"As of December 31, 2023, XYZ Ltd.'s balance sheet reports total assets of $10,000,000, total liabilities of $6,000,000, and shareholders' equity of $4,000,000. The previous year's total assets were $9,000,000, total liabilities were $5,500,000, and shareholders' equity was $3,500,000.\"\n\n**Summary:**\n- **Total Assets:** $10,000,000 (up from $9,000,000 in the previous year, an increase of 11.1%)\n- **Total Liabilities:** $6,000,000 (up from $5,500,000 in the previous year, an increase of 9.1%)\n- **Shareholders' Equity:** $4,000,000 (up from $3,500,000 in the previous year, an increase of 14.3%)\n- **Current Ratio:** 1.67 (calculated as Total Assets / Total Liabilities)\n- **Debt-to-Equity Ratio:** 1.5 (calculated as Total Liabilities / Shareholders' Equity)\n- **Key Observations:** Healthy increase in both assets and equity, indicating growth and improved financial stability. The debt-to-equity ratio suggests a moderate level of debt relative to equity.\n\n---\n\n**Example 3: Cash Flow Statement Analysis**\n\n**Original Text:**\n\"For the fiscal year ended December 31, 2023, DEF Inc.'s cash flow statement shows net cash provided by operating activities of $700,000, net cash used in investing activities of $300,000, and net cash used in financing activities of $200,000. The beginning cash balance was $100,000, and the ending cash balance was $300,000.\"\n\n**Summary:**\n- **Net Cash Provided by Operating Activities:** $700,000\n- **Net Cash Used in Investing Activities:** $300,000\n- **Net Cash Used in Financing Activities:** $200,000\n- **Net Increase in Cash:** $200,000 (calculated as $700,000 - $300,000 - $200,000)\n- **Beginning Cash Balance:** $100,000\n- **Ending Cash Balance:** $300,000\n- **Key Observations:** Positive cash flow from operating activities indicates strong operational performance. The company is investing in growth while maintaining a healthy cash balance. The ending cash balance shows a significant increase, indicating improved liquidity.\n\n---\n\n**Example 4: Statement of Shareholders' Equity Analysis**\n\n**Original Text:**\n\"GHI Corporation's statement of shareholders' equity for the fiscal year ended December 31, 2023, shows common stock of $1,000,000, retained earnings of $2,000,000, and additional paid-in capital of $500,000. The previous year's retained earnings were $1,500,000.\"\n\n**Summary:**\n- **Common Stock:** $1,000,000\n- **Retained Earnings:** $2,000,000 (up from $1,500,000 in the previous year, an increase of 33.3%)\n- **Additional Paid-in Capital:** $500,000\n- **Total Shareholders' Equity:** $3,500,000\n- **Key Observations:** Significant growth in retained earnings indicates strong profitability and reinvestment in the business. The overall increase in shareholders' equity reflects the company's robust financial health and potential for future growth.\n\n---\n\nBy following this structured approach, you will be able to provide thorough and accurate analyses of financial and accounting statements, ensuring that all key metrics and insights are clearly understood.\n\n\n\n\nswarms_corp: What are the components of a startups stock incentive equity plan\n\n\nFinancial-Analysis-Agent: None\n\n\nFinancial-Analysis-Agent: None\n\n",
    "loop_interval": 0,
    "retry_attempts": 3,
    "retry_interval": 1,
    "interactive": false,
    "dashboard": false,
    "dynamic_temperature": true,
    "autosave": true,
    "saved_state_path": "Financial-Analysis-Agent_state.json",
    "max_loops": 2,
    "Task": "What are the components of a startups stock incentive equity plan",
    "Stopping Token": "<DONE>",
    "Dynamic Loops": false,
    "sop": null,
    "sop_list": null,
    "context_length": 200000,
    "user_name": "swarms_corp",
    "self_healing_enabled": false,
    "code_interpreter": false,
    "multi_modal": null,
    "pdf_path": null,
    "list_of_pdf": null,
    "preset_stopping_token": false,
    "traceback": null,
    "traceback_handlers": null,
    "streaming_on": true,
    "docs": null,
    "docs_folder": null,
    "verbose": true,
    "parser": null,
    "best_of_n": null,
    "callback": null,
    "metadata": null,
    "callbacks": null,
    "search_algorithm": null,
    "logs_to_filename": null,
    "evaluator": null,
    "output_json": false,
    "stopping_func": null,
    "custom_loop_condition": null,
    "sentiment_threshold": null,
    "custom_exit_command": "exit",
    "sentiment_analyzer": null,
    "limit_tokens_from_string": null,
    "tool_schema": null,
    "output_type": null,
    "function_calling_type": "json",
    "output_cleaner": null,
    "function_calling_format_type": "OpenAI",
    "list_base_models": null,
    "metadata_output_type": "json"
}
```

## まとめ
SwarmsのAIエージェンを実行する準備、サンプルコードを動かしました。
次は、マルチエージェントを使うためのカスタマイズや、データベースの利用方法など深掘りします。


## 参考

https://github.com/kyegomez/swarms

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

https://qiita.com/yamii/items/914fcae6599a4ac9f9fd

https://qiita.com/seigot/items/f89ea1633783bc5fc1b5