kofdai commited on
Commit
ee76e96
·
verified ·
1 Parent(s): 00507a4

Upload src/judge_alpha_lobe.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/judge_alpha_lobe.py +184 -0
src/judge_alpha_lobe.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any, Optional
2
+ import logging
3
+
4
+ from ilm_athens_engine.deepseek_integration.deepseek_runner import DeepSeekR1Engine
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ # ドメイン別のプロンプトテンプレート
10
+ DOMAIN_PROMPT_TEMPLATES = {
11
+ "medical": """【医療知識ベース参考情報】
12
+ {db_context}
13
+
14
+ 【セッション履歴】
15
+ {session_summary}
16
+
17
+ 【ユーザーの医療質問】
18
+ {question}
19
+
20
+ 上記の参考情報を踏まえ、医学的に正確な回答を構造化フォーマットで提供してください。""",
21
+
22
+ "legal": """【法律知識ベース参考情報】
23
+ {db_context}
24
+
25
+ 【セッション履歴】
26
+ {session_summary}
27
+
28
+ 【ユーザーの法律質問】
29
+ {question}
30
+
31
+ 上記の参考情報を踏まえ、法的に正確な回答を構造化フォーマットで提供してください。
32
+ ※これは法的助言ではなく、情報提供です。""",
33
+
34
+ "economics": """【経済知識ベース参考情報】
35
+ {db_context}
36
+
37
+ 【セッション履歴】
38
+ {session_summary}
39
+
40
+ 【ユーザーの経済質問】
41
+ {question}
42
+
43
+ 上記の参考情報を踏まえ、客観的な経済分析を構造化フォーマットで提供してください。""",
44
+
45
+ "general": """【参考情報】
46
+ {db_context}
47
+
48
+ 【ユーザーの質問】
49
+ {question}"""
50
+ }
51
+
52
+
53
+ class AlpheLobe:
54
+ """
55
+ 生成院(α-Lobe):DeepSeek R1エンジンをラップし、
56
+ ドメイン対応の構造化されたプロンプトを渡して回答を生成する責務を持つ。
57
+ """
58
+ def __init__(self, engine: DeepSeekR1Engine):
59
+ self.engine = engine
60
+
61
+ def _format_db_context(self, db_context: Dict) -> str:
62
+ """DB知識コンテキストを読みやすい形式にフォーマット"""
63
+ if not db_context:
64
+ return "(参考情報なし)"
65
+
66
+ formatted_parts = []
67
+ for coord, tile in db_context.items():
68
+ if tile:
69
+ content = tile.get("content", tile.get("data", ""))
70
+ if isinstance(content, str) and content:
71
+ formatted_parts.append(f"[{coord}]\n{content[:500]}")
72
+
73
+ return "\n\n".join(formatted_parts) if formatted_parts else "(参考情報なし)"
74
+
75
+ def _format_session_context(self, session_context: Optional[Dict]) -> str:
76
+ """セッション履歴を要約"""
77
+ if not session_context:
78
+ return "(新規セッション)"
79
+
80
+ history = session_context.get("history", [])
81
+ if not history:
82
+ return "(履歴なし)"
83
+
84
+ # 直近3件の会話を要約
85
+ recent = history[-3:]
86
+ summary_parts = []
87
+ for item in recent:
88
+ q = item.get("question", "")[:50]
89
+ summary_parts.append(f"Q: {q}...")
90
+
91
+ return "\n".join(summary_parts)
92
+
93
+ async def generate_response(
94
+ self,
95
+ question: str,
96
+ db_context: Dict,
97
+ session_context: Optional[Dict] = None,
98
+ domain_id: str = "medical"
99
+ ) -> Dict[str, Any]:
100
+ """
101
+ ドメイン対応のプロンプトを構築し、DeepSeekエンジンで推論を実行する。
102
+ """
103
+ # 1. プロンプトテンプレートを選択
104
+ template = DOMAIN_PROMPT_TEMPLATES.get(domain_id, DOMAIN_PROMPT_TEMPLATES["general"])
105
+
106
+ # 2. コンテキストをフォーマット
107
+ formatted_db = self._format_db_context(db_context)
108
+ formatted_session = self._format_session_context(session_context)
109
+
110
+ # 3. プロンプトを構築
111
+ prompt = template.format(
112
+ db_context=formatted_db,
113
+ session_summary=formatted_session,
114
+ question=question
115
+ )
116
+
117
+ logger.debug(f"AlpheLobe生成プロンプト (domain={domain_id}): {prompt[:200]}...")
118
+
119
+ # 4. DeepSeekエンジンに推論を依頼
120
+ result = await self.engine.infer(
121
+ prompt,
122
+ domain_context={"domain_name": domain_id}
123
+ )
124
+
125
+ # 5. 不確実性を抽出
126
+ uncertainties = self._extract_uncertainties(result.get("response", ""))
127
+
128
+ # 6. Judge層が期待する形式に合わせる
129
+ return {
130
+ "main_response": result.get("response", ""),
131
+ "thinking_process": result.get("thinking", ""),
132
+ "structured": result.get("structured", {}),
133
+ "confidence": result.get("confidence", 0.0),
134
+ "domain": domain_id,
135
+ "sources_cited": self._extract_sources(result.get("response", "")),
136
+ "uncertainties": uncertainties,
137
+ "latency_ms": result.get("latency_ms", 0)
138
+ }
139
+
140
+ def _extract_uncertainties(self, response: str) -> list:
141
+ """回答から不確実性の言及を抽出"""
142
+ uncertainty_markers = [
143
+ "可能性があります",
144
+ "かもしれません",
145
+ "不確実",
146
+ "データが限定的",
147
+ "議論があります",
148
+ "見解が分かれ",
149
+ "要検���",
150
+ "専門家に相談"
151
+ ]
152
+
153
+ uncertainties = []
154
+ for marker in uncertainty_markers:
155
+ if marker in response:
156
+ # マーカー周辺のコンテキストを抽出
157
+ idx = response.find(marker)
158
+ start = max(0, idx - 30)
159
+ end = min(len(response), idx + len(marker) + 30)
160
+ context = response[start:end]
161
+ uncertainties.append({
162
+ "marker": marker,
163
+ "context": context.strip()
164
+ })
165
+
166
+ return uncertainties[:5] # 最大5件
167
+
168
+ def _extract_sources(self, response: str) -> list:
169
+ """回答から参考文献の言及を抽出"""
170
+ import re
171
+
172
+ sources = []
173
+
174
+ # 【参考】セクションを探す
175
+ ref_match = re.search(r'【参考[^】]*】(.+?)(?=【|$)', response, re.DOTALL)
176
+ if ref_match:
177
+ ref_text = ref_match.group(1).strip()
178
+ # 行ごとに分割して抽出
179
+ for line in ref_text.split('\n'):
180
+ line = line.strip()
181
+ if line and len(line) > 5:
182
+ sources.append(line[:100])
183
+
184
+ return sources[:5] # 最大5件