Pi Agent: Non-Interactive Mode
最終更新:2026-08-31
--- title: "非インタラクティブモード" description: "Pi Agentの非インタラクティブ(バッチ)モードをマスターし、自動化タスクパイプライン、パイプ操作、スクリプト統合を理解します。" order: 6 lang: ja
インタラクティブモードは探索用、非インタラクティブモードは本番用——無人、バッチ処理、パイプライン編成。
1. 非インタラクティブモードとは
非インタラクティブモードでは、Agentが入力を受け取って自動的に実行し、人の介入を必要としません。以下に適しています:
- CI/CDパイプラインでの自動化タスク
- スケジュールバッチジョブ
- パイプ操作(他のCLIツールとの組み合わせ)
- 無人スクリプト統合
2. CLI非インタラクティブ使用
(1) 単一実行
BASH
pi-agent run "Explain what this code does: def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)"
(2) ファイルから入力を読み込み
BASH
pi-agent run --input code.py "Review the code quality of this file"
(3) 標準入力からのパイプ
BASH
cat error.log | pi-agent run "Analyze these error logs and find the most common issues"
(4) ファイルへ出力
BASH
pi-agent run --input data.csv "Analyze data trends" --output report.md
3. Pythonバッチ処理
(1) 基本バッチ
PYTHON
from pi_agent import Agent
agent = Agent(name="reviewer", system_prompt="You are a code review expert")
files = ["main.py", "utils.py", "config.py"]
for f in files:
result = agent.run(f"Review code quality of {f}, give scores and improvement suggestions")
print(f"=== {f} ===")
print(result)
print()
(2) 並列バッチ
PYTHON
import asyncio
from pi_agent import AsyncAgent
async def review_file(filename):
agent = AsyncAgent(name="reviewer")
result = await agent.run(f"Review {filename}")
return filename, result
async def main():
files = ["main.py", "utils.py", "config.py", "tests.py"]
tasks = [review_file(f) for f in files]
results = await asyncio.gather(*tasks)
for filename, result in results:
print(f"=== {filename} ===")
print(result)
asyncio.run(main())
4. パイプとスクリプト統合
例1:Gitコミットメッセージジェネレーター(難易度:⭐⭐)
BASH
git diff --staged | pi-agent run "Generate a concise git commit message based on the code changes"
例2:ログ分析パイプライン(難易度:⭐⭐)
BASH
tail -100 /var/log/app.log | pi-agent run --skill log_analyzer "Extract errors and warnings, sort by frequency"
例3:自動テストレポート(難易度:⭐⭐⭐)
PYTHON
from pi_agent import Agent
import subprocess
agent = Agent(name="qa", system_prompt="You are a QA engineer, analyze test results and generate reports")
result = subprocess.run(["pytest", "--tb=short"], capture_output=True, text=True)
report = agent.run(f"Analyze the following test results and generate a report:\n{result.stdout}\n{result.stderr}")
with open("test_report.md", "w") as f:
f.write(report.text)
5. 終了コードとエラー処理
| 終了コード | 意味 |
|---|---|
| 0 | 成功 |
| 1 | 一般エラー |
| 2 | 設定エラー |
| 3 | API呼び出し失敗 |
| 4 | ツール実行エラー |
BASH
pi-agent run "Check deployment status" --skill devops
if [ $? -eq 0 ]; then
echo "Check passed"
else
echo "Check failed, exit code: $?"
fi
Python:
PYTHON
from pi_agent import Agent, AgentError
agent = Agent(name="checker")
try:
result = agent.run("Verify configuration file")
print("Verification passed:", result.text)
except AgentError as e:
print(f"Execution failed: {e}")
print(f"Error code: {e.code}")
6. スケジュールタスク統合
BASH
# crontab -e
0 9 * * * pi-agent run --skill daily_report "Generate today's project progress report" --output /reports/daily.md
0 0 * * 0 pi-agent run --skill code_review "Review this week's code changes" --output /reports/weekly.md
❓ よくある質問
Q 非インタラクティブモードはストリーミングをサポートする?
A デフォルトではありませんが、
--streamフラグを使用できます。ただし、パイプでは通常ストリーミングは不要です。Q パイプ入力に長さ制限はある?
A ハードリミットはありませんが、モデルのコンテキストウィンドウに制約されます。非常に長い入力は自動的に切り詰めまたはチャンク化されます。
Q バッチ処理中のAPIレート制限は?
A Pi Agentにはリトライ機能が組み込まれています。コード内に
asyncio.sleep()を追加してリクエスト頻度を制御することもできます。📖 まとめ
- 非インタラクティブモードはCI/CD、バッチ処理、パイプ操作に適する
- CLI:
pi-agent run;Python:agent.run() - 標準入力パイプ、ファイル入力、ファイル出力をサポート
- 終了コードでエラータイプを判別し、スクリプト統合に活用
- cronやCIシステムと統合してスケジュール自動化
📝 練習問題
- 基礎(難易度:⭐):
pi-agent runで単一タスクを実行し、結果をファイルに保存してください。 - 中級(難易度:⭐⭐): ディレクトリ内のすべてのPythonファイルをレビューするバッチスクリプトを書いてください。
- 上級(難易度:⭐⭐⭐): コミット前にPi Agentでコミットメッセージを自動生成するgitフックを設定してください。