AI駆動調査分析エージェントの作り方完全ガイド【2025年最新版】
はじめに
AI技術の急速な発展により、調査分析業務を自動化する調査分析エージェントの需要が急激に高まっています。本記事では、初心者から上級者まで対応できる実践的な調査分析エージェントの構築方法を、豊富なサンプルコードと共に詳しく解説します。
調査分析エージェントとは
調査分析エージェントは、大量のデータを自動で収集・解析し、ビジネスインサイトを提供するAIシステムです。主な機能には以下があります:
- 自動データ収集: Web上の情報や各種APIからのデータ取得
- 自然言語処理: テキストデータの意味理解と分類
- 統計分析: 数値データの傾向分析と予測
- レポート生成: 分析結果の自動レポート作成
基本アーキテクチャ
1. システム構成
# 基本的なエージェント構成
class SurveyAnalysisAgent:
def __init__(self):
self.data_collector = DataCollector()
self.analyzer = DataAnalyzer()
self.reporter = ReportGenerator()
def run_analysis(self, query):
data = self.data_collector.collect(query)
results = self.analyzer.analyze(data)
return self.reporter.generate(results)
2. 必要なライブラリとツール
# 基本ライブラリのインストール
pip install pandas numpy scikit-learn
pip install requests beautifulsoup4
pip install openai langchain
pip install streamlit plotly
実装手順
Step 1: データ収集モジュール
import requests
from bs4 import BeautifulSoup
import pandas as pd
class DataCollector:
def __init__(self):
self.session = requests.Session()
def collect_web_data(self, urls):
"""Web上からデータを収集"""
data = []
for url in urls:
response = self.session.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# テキストデータを抽出
text = soup.get_text().strip()
data.append({
'url': url,
'content': text,
'timestamp': pd.Timestamp.now()
})
return pd.DataFrame(data)
def collect_api_data(self, api_endpoint, params):
"""APIからデータを取得"""
response = requests.get(api_endpoint, params=params)
return response.json()
Step 2: AI分析エンジン
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
class DataAnalyzer:
def __init__(self, api_key):
self.llm = OpenAI(api_key=api_key, temperature=0.1)
def analyze_sentiment(self, text_data):
"""感情分析を実行"""
prompt = PromptTemplate(
input_variables=["text"],
template="次のテキストの感情を分析してください:{text}\n感情:"
)
chain = LLMChain(llm=self.llm, prompt=prompt)
results = []
for text in text_data:
sentiment = chain.run(text=text)
results.append(sentiment)
return results
def extract_keywords(self, text_data):
"""キーワード抽出"""
prompt = PromptTemplate(
input_variables=["text"],
template="以下のテキストから重要なキーワードを5つ抽出:{text}"
)
chain = LLMChain(llm=self.llm, prompt=prompt)
return [chain.run(text=text) for text in text_data]
Step 3: 統計分析モジュール
import numpy as np
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
class StatisticalAnalyzer:
def __init__(self):
self.vectorizer = TfidfVectorizer(max_features=100)
def cluster_analysis(self, text_data, n_clusters=3):
"""テキストデータのクラスター分析"""
# TF-IDFベクトル化
tfidf_matrix = self.vectorizer.fit_transform(text_data)
# K-meansクラスタリング
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
clusters = kmeans.fit_predict(tfidf_matrix)
return clusters
def trend_analysis(self, time_series_data):
"""時系列トレンド分析"""
# 移動平均計算
window = 7
rolling_mean = np.convolve(time_series_data,
np.ones(window)/window,
mode='valid')
return rolling_mean
Step 4: レポート生成システム
import plotly.graph_objects as go
import plotly.express as px
class ReportGenerator:
def __init__(self):
self.template = """
# 調査分析レポート
## 分析サマリー
{summary}
## 主要な発見
{findings}
## 推奨アクション
{recommendations}
"""
def create_visualization(self, data, chart_type='bar'):
"""データ可視化"""
if chart_type == 'bar':
fig = px.bar(data, x='category', y='value')
elif chart_type == 'line':
fig = px.line(data, x='date', y='value')
return fig.to_html()
def generate_report(self, analysis_results):
"""レポート生成"""
summary = self._create_summary(analysis_results)
findings = self._extract_findings(analysis_results)
recommendations = self._generate_recommendations(findings)
return self.template.format(
summary=summary,
findings=findings,
recommendations=recommendations
)
実践例:市場調査エージェント
class MarketResearchAgent(SurveyAnalysisAgent):
def __init__(self, openai_api_key):
super().__init__()
self.analyzer = DataAnalyzer(openai_api_key)
def research_competitor(self, company_name):
"""競合他社分析"""
# 1. データ収集
search_urls = [
f"https://example-news-site.com/search?q={company_name}",
f"https://example-review-site.com/{company_name}"
]
data = self.data_collector.collect_web_data(search_urls)
# 2. 分析実行
sentiments = self.analyzer.analyze_sentiment(data['content'])
keywords = self.analyzer.extract_keywords(data['content'])
# 3. レポート生成
results = {
'company': company_name,
'sentiment_analysis': sentiments,
'key_topics': keywords,
'data_sources': len(search_urls)
}
return self.reporter.generate_report(results)
# 使用例
agent = MarketResearchAgent("your-openai-api-key")
report = agent.research_competitor("競合会社名")
print(report)
Webインターフェースの構築
import streamlit as st
def create_web_interface():
st.title("調査分析エージェント")
# サイドバー設定
st.sidebar.header("分析設定")
analysis_type = st.sidebar.selectbox(
"分析タイプ",
["市場調査", "競合分析", "トレンド分析"]
)
# メイン入力エリア
query = st.text_input("調査したい内容を入力してください")
if st.button("分析開始"):
with st.spinner("分析中..."):
agent = MarketResearchAgent("your-api-key")
if analysis_type == "市場調査":
results = agent.market_research(query)
elif analysis_type == "競合分析":
results = agent.research_competitor(query)
st.success("分析完了!")
st.write(results)
if __name__ == "__main__":
create_web_interface()
高度な機能実装
1. リアルタイム分析
import asyncio
import websockets
class RealTimeAnalyzer:
def __init__(self):
self.is_running = False
async def start_monitoring(self, data_sources):
"""リアルタイムデータ監視"""
self.is_running = True
while self.is_running:
for source in data_sources:
new_data = await self.fetch_new_data(source)
if new_data:
analysis = await self.quick_analysis(new_data)
await self.send_alert(analysis)
await asyncio.sleep(60) # 1分間隔で監視
async def fetch_new_data(self, source):
# 新しいデータの取得ロジック
pass
async def quick_analysis(self, data):
# 高速分析処理
pass
2. 機械学習モデル統合
from sklearn.ensemble import RandomForestClassifier
import joblib
class MLAnalyzer:
def __init__(self, model_path=None):
if model_path:
self.model = joblib.load(model_path)
else:
self.model = RandomForestClassifier(n_estimators=100)
def train_model(self, X_train, y_train):
"""機械学習モデルの訓練"""
self.model.fit(X_train, y_train)
joblib.dump(self.model, 'analysis_model.pkl')
def predict_trend(self, features):
"""トレンド予測"""
prediction = self.model.predict(features)
probability = self.model.predict_proba(features)
return {
'prediction': prediction[0],
'confidence': max(probability[0])
}
パフォーマンス最適化
1. 並列処理
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
class OptimizedAgent(SurveyAnalysisAgent):
def __init__(self, max_workers=None):
super().__init__()
self.max_workers = max_workers or multiprocessing.cpu_count()
def parallel_analysis(self, data_chunks):
"""並列データ分析"""
with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
futures = [
executor.submit(self.analyzer.analyze, chunk)
for chunk in data_chunks
]
results = [future.result() for future in futures]
return results
2. キャッシング機能
from functools import lru_cache
import redis
class CachedAnalyzer:
def __init__(self):
self.redis_client = redis.Redis(host='localhost', port=6379)
@lru_cache(maxsize=128)
def cached_analysis(self, data_hash):
"""結果をキャッシュして高速化"""
cached_result = self.redis_client.get(data_hash)
if cached_result:
return json.loads(cached_result)
# 新規分析実行
result = self.perform_analysis(data_hash)
self.redis_client.setex(data_hash, 3600, json.dumps(result))
return result
セキュリティ対策
import hashlib
import hmac
from cryptography.fernet import Fernet
class SecureAgent:
def __init__(self, encryption_key):
self.cipher_suite = Fernet(encryption_key)
def encrypt_sensitive_data(self, data):
"""機密データの暗号化"""
encrypted_data = self.cipher_suite.encrypt(data.encode())
return encrypted_data
def verify_request(self, request_data, signature, secret_key):
"""リクエストの署名検証"""
expected_signature = hmac.new(
secret_key.encode(),
request_data.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected_signature)
デプロイメントとモニタリング
Docker化
# Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8501
CMD ["streamlit", "run", "app.py"]
監視設定
import logging
from prometheus_client import Counter, Histogram
# メトリクス定義
analysis_counter = Counter('analysis_total', 'Total analyses performed')
analysis_duration = Histogram('analysis_duration_seconds', 'Analysis duration')
class MonitoredAgent(SurveyAnalysisAgent):
def __init__(self):
super().__init__()
self.logger = self._setup_logging()
def _setup_logging(self):
logging.basicConfig(level=logging.INFO)
return logging.getLogger(__name__)
@analysis_duration.time()
def run_analysis(self, query):
self.logger.info(f"Starting analysis for: {query}")
analysis_counter.inc()
try:
result = super().run_analysis(query)
self.logger.info("Analysis completed successfully")
return result
except Exception as e:
self.logger.error(f"Analysis failed: {str(e)}")
raise
まとめ
調査分析エージェントの構築は、以下のステップで実現できます:
- 要件定義: 分析対象と目標の明確化
- アーキテクチャ設計: モジュール構成の決定
- データ収集: APIとWebスクレイピング
- AI分析: 自然言語処理と機械学習
- 可視化: 結果の分かりやすい表示
- 最適化: パフォーマンスとセキュリティ
本記事で紹介したサンプルコードを参考に、あなたのビジネスニーズに合わせたカスタム調査分析エージェントを構築してください。AI技術の進歩により、より高度で効率的な分析システムの構築が可能になっています。
継続的な改善とアップデートを通じて、競争優位性を持つ調査分析システムを構築しましょう。
■テックジム「AIエンジニア養成コース」
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<オンライン無料>ゼロから始めるPython爆速講座

