こんにちは。今回は話題のOSSエージェント「OpenManus」をFastAPIを使って簡単にAPI化した方法を紹介します。
🚀 この記事で達成すること
- OpenManusのエージェントをCLIだけでなく、REST API経由で利用可能にする
- 外部アプリケーションからプロンプトを送り、エージェントの回答をJSONで取得
🧐 OpenManusとは?
OpenManusはGPT-4などのLLMと連携し、多彩なツール(ブラウザ操作、Python実行など)を使って、複雑なタスクを自動で解決するエージェントフレームワークです。
📌 API化の完成形イメージ
最終的に以下のようなHTTPリクエストでプロンプトを投げると、OpenManusが実行して結果を返します。
curl -X POST http://localhost:8000/run/agent \
-H "Content-Type: application/json" \
-d '{"prompt": "PythonでFizzBuzzを書いて"}'
レスポンス:
{
"status": "ok",
"result": "FizzBuzzのPythonコードはこちらです:..."
}
📂 ディレクトリ構成
OpenManusAPI/
├── app/
│ ├── agent/
│ │ └── manus.py
│ └── service/
│ ├── agent_runner.py
│ └── __init__.py
├── main.py
├── requirements.txt
└── config/
└── config.toml
🔧 実装手順
1. FastAPIをインストール
pip install fastapi uvicorn httpx
2. main.py
にFastAPIのエンドポイントを作成
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from app.service.agent_runner import process_prompt
app = FastAPI()
class PromptInput(BaseModel):
prompt: str
@app.post("/run/agent")
async def run_agent(input: PromptInput):
prompt = input.prompt.strip()
if not prompt:
raise HTTPException(status_code=400, detail="Prompt is empty")
result = await process_prompt(prompt)
return {"status": "ok", "result": result}
3. agent_runner.py
を作成
app/service/agent_runner.py
に以下を追加します。
from app.agent.manus import Manus
from app.logger import logger
async def process_prompt(prompt: str) -> str:
agent = await Manus.create()
try:
logger.info(f"Running agent with prompt: {prompt}")
result = await agent.run(prompt)
return result
finally:
await agent.cleanup()
4. manus.py
(Manusクラス)にrun()
メソッドを追加
app/agent/manus.py
の Manus
クラスに以下を追加します。
async def run(self, prompt: str) -> str:
self.memory.add_user_message(prompt)
await self.run_loop()
for msg in reversed(self.memory.messages):
if msg.role == "assistant" and msg.content:
return msg.content
return "No response generated."
🎯 起動して動作確認
起動:
uvicorn main:app --reload
確認:
curl -X POST http://localhost:8000/run/agent \
-H "Content-Type: application/json" \
-d '{"prompt": "リストを逆順にするPythonコードは?"}'
正常な応答があれば成功です。
🐞 よくあるエラーと対処法
エラー例
ModuleNotFoundError: No module named 'app.service'
対策:
-
app/
やapp/service/
に__init__.py
を必ず置く - プロジェクトルートで実行する(
PYTHONPATH
を調整)
export PYTHONPATH=$(pwd)
uvicorn main:app --reload
🚩 まとめ
FastAPIでOpenManusをAPI化すると、
- 他サービスや外部UIとの連携が簡単
- ターミナル以外からも使える
これにより活用の幅が一気に広がります。