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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import asyncio
|
| 3 |
+
import copy
|
| 4 |
+
import re
|
| 5 |
+
import ast
|
| 6 |
+
import tempfile
|
| 7 |
+
import subprocess
|
| 8 |
+
import os
|
| 9 |
+
from typing import Dict, Any, List, Optional, Union, Tuple, Set
|
| 10 |
+
|
| 11 |
+
from validators.base import BaseValidator, Validator
|
| 12 |
+
|
| 13 |
+
class CodeVerifier(BaseValidator, Validator):
|
| 14 |
+
"""コード検証を行うクラス"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, client):
|
| 17 |
+
"""検証クライアントを初期化"""
|
| 18 |
+
super().__init__(client)
|
| 19 |
+
# 検証用のモデル
|
| 20 |
+
self.verify_model = "qwen-2.5-coder-32b" # コード検証に特化したモデル
|
| 21 |
+
self.verification_results = {}
|
| 22 |
+
|
| 23 |
+
async def validate(self, content, context=None):
|
| 24 |
+
"""コード検証を実行する(インターフェース実装)"""
|
| 25 |
+
result = await self.verify_code_blocks(content, context)
|
| 26 |
+
self.verification_results = result["verification_result"]
|
| 27 |
+
return result["verified_content"]
|
| 28 |
+
|
| 29 |
+
def get_result_summary(self):
|
| 30 |
+
"""検証結果の要約を返す(インターフェース実装)"""
|
| 31 |
+
if not self.verification_results:
|
| 32 |
+
return "検証はまだ実行されていません。"
|
| 33 |
+
return self.verification_results.get("verification_summary", "要約は利用できません。")
|
| 34 |
+
|
| 35 |
+
def _extract_problem_description(self, user_input: str) -> Optional[str]:
|
| 36 |
+
"""ユーザー入力から問題記述を抽出する"""
|
| 37 |
+
# 問題文を示す一般的なパターン
|
| 38 |
+
problem_indicators = [
|
| 39 |
+
"問題:", "問題文:", "**問題:**", "# 問題", "課題:", "要件:",
|
| 40 |
+
"Problem:", "Task:", "Question:", "Exercise:",
|
| 41 |
+
"以下の問題", "次の問題", "この問題"
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
# 制約条件を示す一般的なパターン
|
| 45 |
+
constraint_indicators = [
|
| 46 |
+
"制約:", "条件:", "ただし", "ここで", "なお",
|
| 47 |
+
"Constraints:", "Note:", "Where:", "Given:",
|
| 48 |
+
"評価ポイント", "注意点", "考慮点", "エッジケース"
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
# 例を示す一般的なパターン
|
| 52 |
+
example_indicators = [
|
| 53 |
+
"例:", "入力例:", "出力例:", "サンプル:", "テストケース:",
|
| 54 |
+
"Example:", "Input:", "Output:", "Sample:", "Test case:"
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
problem_desc = None
|
| 58 |
+
|
| 59 |
+
# 問題文のパターンマッチング
|
| 60 |
+
for indicator in problem_indicators:
|
| 61 |
+
if indicator in user_input:
|
| 62 |
+
# 問題文の開始位置を見つける
|
| 63 |
+
start_pos = user_input.find(indicator) + len(indicator)
|
| 64 |
+
|
| 65 |
+
# 次のセクション(例や制約)の開始位置を見つける
|
| 66 |
+
end_pos = len(user_input)
|
| 67 |
+
for end_indicator in example_indicators + constraint_indicators:
|
| 68 |
+
pos = user_input.find(end_indicator, start_pos)
|
| 69 |
+
if pos != -1 and pos < end_pos:
|
| 70 |
+
end_pos = pos
|
| 71 |
+
|
| 72 |
+
# 問題文を抽出
|
| 73 |
+
problem_desc = user_input[start_pos:end_pos].strip()
|
| 74 |
+
break
|
| 75 |
+
|
| 76 |
+
# 問題文が見つからない場合、ユーザー入力全体を使用
|
| 77 |
+
if not problem_desc:
|
| 78 |
+
return user_input
|
| 79 |
+
|
| 80 |
+
# 制約条件の抽出と追加
|
| 81 |
+
constraints = []
|
| 82 |
+
for indicator in constraint_indicators:
|
| 83 |
+
if indicator in user_input:
|
| 84 |
+
# 制約の開始位置を見つける
|
| 85 |
+
start_pos = user_input.find(indicator) + len(indicator)
|
| 86 |
+
|
| 87 |
+
# 次のセクションの開始位置を見つける
|
| 88 |
+
end_pos = len(user_input)
|
| 89 |
+
for end_indicator in problem_indicators + example_indicators:
|
| 90 |
+
pos = user_input.find(end_indicator, start_pos)
|
| 91 |
+
if pos != -1 and pos < end_pos:
|
| 92 |
+
end_pos = pos
|
| 93 |
+
|
| 94 |
+
# 制約を抽出
|
| 95 |
+
constraint = user_input[start_pos:end_pos].strip()
|
| 96 |
+
if constraint:
|
| 97 |
+
constraints.append(constraint)
|
| 98 |
+
|
| 99 |
+
# 例の抽出と追加
|
| 100 |
+
examples = []
|
| 101 |
+
for indicator in example_indicators:
|
| 102 |
+
if indicator in user_input:
|
| 103 |
+
# 例の開始位置を見つける
|
| 104 |
+
start_pos = user_input.find(indicator) + len(indicator)
|
| 105 |
+
|
| 106 |
+
# 次のセクションの開始位置を見つける
|
| 107 |
+
end_pos = len(user_input)
|
| 108 |
+
for end_indicator in problem_indicators + constraint_indicators:
|
| 109 |
+
pos = user_input.find(end_indicator, start_pos)
|
| 110 |
+
if pos != -1 and pos < end_pos:
|
| 111 |
+
end_pos = pos
|
| 112 |
+
|
| 113 |
+
# 例を抽出
|
| 114 |
+
example = user_input[start_pos:end_pos].strip()
|
| 115 |
+
if example:
|
| 116 |
+
examples.append(example)
|
| 117 |
+
|
| 118 |
+
# 問題記述を構築
|
| 119 |
+
full_description = problem_desc
|
| 120 |
+
|
| 121 |
+
if constraints:
|
| 122 |
+
full_description += "\n\n制約条件:\n" + "\n".join(constraints)
|
| 123 |
+
|
| 124 |
+
if examples:
|
| 125 |
+
full_description += "\n\n例:\n" + "\n".join(examples)
|
| 126 |
+
|
| 127 |
+
return full_description
|
| 128 |
+
|
| 129 |
+
def _extract_problem_constraints(self, problem_description: str) -> List[str]:
|
| 130 |
+
"""問題記述から特定の制約を抽出する"""
|
| 131 |
+
constraints = []
|
| 132 |
+
|
| 133 |
+
# 一般的な制約パターン
|
| 134 |
+
constraint_patterns = [
|
| 135 |
+
(r'i\s*!=\s*j', "インデックスが異なる必要がある"),
|
| 136 |
+
(r'i\s*≠\s*j', "インデックスが異なる必要がある"),
|
| 137 |
+
(r'i\s*<>\s*j', "インデックスが異なる必要がある"),
|
| 138 |
+
(r'0\s*<=\s*\w+\s*<\s*n', "インデックスは配列の範囲内"),
|
| 139 |
+
(r'O\(n\)', "線形時間複雑度が要求される"),
|
| 140 |
+
(r'O\(n\s*log\s*n\)', "n log n の時間複雑度が要求される"),
|
| 141 |
+
(r'O\(1\)', "定数時間/空間が要求される"),
|
| 142 |
+
(r'空間複雑度.*O\(\w+\)', "特定の空間複雑度制約がある"),
|
| 143 |
+
(r'時間複雑度.*O\(\w+\)', "特定の時間複雑度制約がある"),
|
| 144 |
+
(r'メモリ使用量.*\d+[MG]B', "メモリ使用量制約がある"),
|
| 145 |
+
(r'実行時間.*\d+m?s', "実行時間制約がある"),
|
| 146 |
+
(r'入力.*\d+\s*<=\s*\w+\s*<=\s*\d+', "入力値の範囲制約がある")
|
| 147 |
+
]
|
| 148 |
+
|
| 149 |
+
# 特定のアルゴリズム/データ構造に関する制約
|
| 150 |
+
algorithm_patterns = [
|
| 151 |
+
(r'(?:使用|利用)(?:して|する)?.*(?:トライ|Trie)', "トライ木の使用が推奨/要求される"),
|
| 152 |
+
(r'(?:使用|利用)(?:して|する)?.*(?:動的計画法|DP)', "動的計画法の使用が推奨/要求される"),
|
| 153 |
+
(r'(?:使用|利用)(?:して|する)?.*(?:二分探索|バイナリサーチ)', "二分探索の使用が推奨/要求される"),
|
| 154 |
+
(r'(?:使用|利用)(?:して|する)?.*(?:BFS|幅優先探索)', "幅優先探索の使用が推奨/要求される"),
|
| 155 |
+
(r'(?:使用|利用)(?:して|する)?.*(?:DFS|深さ優先探索)', "深さ優先探索の使用が推奨/要求される"),
|
| 156 |
+
(r'(?:使用|利用)(?:して|する)?.*(?:ヒープ|優先度付きキュー)', "ヒープ/優先度付きキューの使用が推奨/要求される")
|
| 157 |
+
]
|
| 158 |
+
|
| 159 |
+
# 特定のトピックに関する制約(ビット操作、数学など)
|
| 160 |
+
topic_patterns = [
|
| 161 |
+
(r'ビット.*操作', "ビット操作の知識が必要"),
|
| 162 |
+
(r'XOR|ビット排他的論理和', "XOR操作の理解が必要"),
|
| 163 |
+
(r'mod(?:ulo)?.*10\^9\s*\+\s*7', "大きな数値に対するモジュロ演算が必要")
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
# 物理シミュレーション関連の制約パターン
|
| 167 |
+
physics_patterns = [
|
| 168 |
+
(r'(?:物理|力学).*シミュレーション', "物理シミュレーションの実装が必要"),
|
| 169 |
+
(r'(?:流体|流れ).*力学', "流体力学の知識と実装が必要"),
|
| 170 |
+
(r'(?:衝突|干渉).*検出', "衝突検出アルゴリズムが必要"),
|
| 171 |
+
(r'(?:剛体|弾性体).*運動', "剛体/弾性体運動の実装が必要"),
|
| 172 |
+
(r'(?:ニュートン|運動).*法則', "運動法則の正確な実装が必要"),
|
| 173 |
+
(r'(?:保存|エネルギー).*法則', "エネルギー保存法則の考慮が必要"),
|
| 174 |
+
(r'数値安定性', "数値計算の安定性への考慮が必要")
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
# 全てのパターンをチェック
|
| 178 |
+
all_patterns = constraint_patterns + algorithm_patterns + topic_patterns + physics_patterns
|
| 179 |
+
for pattern, description in all_patterns:
|
| 180 |
+
if re.search(pattern, problem_description, re.IGNORECASE):
|
| 181 |
+
constraints.append(description)
|
| 182 |
+
|
| 183 |
+
return constraints
|
| 184 |
+
|
| 185 |
+
def _build_verification_prompt(self, language: str, code: str, user_input: str = None, design_doc: str = None) -> str:
|
| 186 |
+
"""コード検証用のプロンプトを構築する(問題文も含める、OOP原則、ベクトル効率、無限ループ検出を強化)"""
|
| 187 |
+
# 問題記述の抽出
|
| 188 |
+
problem_description = None
|
| 189 |
+
problem_constraints = []
|
| 190 |
+
if user_input:
|
| 191 |
+
problem_description = self._extract_problem_description(user_input)
|
| 192 |
+
if problem_description:
|
| 193 |
+
problem_constraints = self._extract_problem_constraints(problem_description)
|
| 194 |
+
|
| 195 |
+
# 制約条件の文字列化
|
| 196 |
+
constraints_str = ""
|
| 197 |
+
if problem_constraints:
|
| 198 |
+
constraints_str = "特に注意すべき制約条件:\n" + "\n".join([f"- {c}" for c in problem_constraints])
|
| 199 |
+
|
| 200 |
+
# OOP設計原則項目の追加
|
| 201 |
+
oop_principles = """
|
| 202 |
+
オブジェクト指向設計原則:
|
| 203 |
+
- 単一責任の原則 (SRP): 各クラスは明確で単一の責任を持つべき
|
| 204 |
+
- 開放/閉鎖原則 (OCP): クラスは拡張に対しては開かれ、修正に対しては閉じられるべき
|
| 205 |
+
- リスコフの置換原則 (LSP): サブクラスはスーパークラスの代わりに使えるべき
|
| 206 |
+
- インターフェース分離の原則 (ISP): 具体的なクライアント向けに最小限のインターフェースを設計
|
| 207 |
+
- 依存関係逆転の原則 (DIP): 高レベルモジュールは低レベルモジュールに依存すべきでない
|
| 208 |
+
- 継承よりコンポジションを優先する
|
| 209 |
+
- 過剰な継承階層を避ける(3-4階層以内に抑える)
|
| 210 |
+
- 適切なカプセル化とアクセス修飾子の使用
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
# ベクトル計算効率項目の追加
|
| 214 |
+
vector_efficiency = """
|
| 215 |
+
ベクトル計算の効率:
|
| 216 |
+
- 大規模ベクトル操作はループの代わりにベクトル化された操作を使用
|
| 217 |
+
- 不必要なコピーを最小限に抑え、参照渡しや変更可能なベクトル操作を適切に使用
|
| 218 |
+
- キャッシュ効率を考慮した連続したメモリアクセスパターン
|
| 219 |
+
- 適切なBLAS/LAPACKなどの最適化ライブラリの使用(該当する場合)
|
| 220 |
+
- ゼロコピー操作とスライス操作の適切な使用
|
| 221 |
+
- 次元削減とブロードキャスト操作の効率的な利用
|
| 222 |
+
- 並列化可能なベクトル操作の特定と実装
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
# 無限ループ検出の強化
|
| 226 |
+
infinite_loop_detection = """
|
| 227 |
+
無限ループの詳細な検出項目:
|
| 228 |
+
1. 終了条件の欠如または到達不能な終了条件
|
| 229 |
+
2. ループカウンタの更新漏れまたは不適切な更新
|
| 230 |
+
3. 無効または変更されないループ条件変数
|
| 231 |
+
4. 再帰呼び出しの無限連鎖の可能性
|
| 232 |
+
5. イテレータ/インデックスの増減が条件に影響しない場合
|
| 233 |
+
6. 浮動小数点比較による終了条件の見落とし
|
| 234 |
+
7. コレクションを反復処理中にその構造を変更するケース
|
| 235 |
+
8. 複数の終了条件の論理的矛盾
|
| 236 |
+
9. 外部依存による終了条件(ファイル終端、ユーザー入力など)の信頼性
|
| 237 |
+
10. 入力値に依存した無限ループの可能性(入力範囲の検証)
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
# 物理シミュレーション固有の検証項目
|
| 241 |
+
physics_simulation_validation = """
|
| 242 |
+
物理シミュレーションの検証項目:
|
| 243 |
+
1. 物理法則の正確な適用(エネルギー保存、運動量保存など)
|
| 244 |
+
2. 単位の一貫性(SI単位系など)
|
| 245 |
+
3. 数値積分法の安定性(オイラー法、ルンゲクッタ法など)
|
| 246 |
+
4. 境界条件の適切な処理
|
| 247 |
+
5. 外力と拘束条件の正確な実装
|
| 248 |
+
6. エッジケースでの安定性(極端な初期条件、衝突など)
|
| 249 |
+
7. 計算効率と精度のバランス
|
| 250 |
+
8. 確率的要素の適切な実装(乱数生成など)
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
# エラーハンドリングの検証項目
|
| 254 |
+
error_handling_validation = """
|
| 255 |
+
エラーハンドリングの検証項目:
|
| 256 |
+
1. 例外の種類ごとの適切な捕捉と処理
|
| 257 |
+
2. エラーメッセージの具体性と有用性
|
| 258 |
+
3. リソースの適切な解放(ファイルハンドル、ネットワーク接続など)
|
| 259 |
+
4. エラー発生時のシステム状態の一貫性維持
|
| 260 |
+
5. 致命的でないエラーからの回復メカニズム
|
| 261 |
+
6. エラーログの詳細度と使いやすさ
|
| 262 |
+
7. ユーザーに表示するエラーメッセージの適切性
|
| 263 |
+
8. セキュリティに関連するエラー情報の適切な隠蔽
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
# コードの完全性検証項目
|
| 267 |
+
code_completeness_validation = """
|
| 268 |
+
コードの完全性検証項目:
|
| 269 |
+
1. 未実装メソッド(pass文や空の実装)の検出
|
| 270 |
+
2. インポートの漏れや未使用インポートの検出
|
| 271 |
+
3. 宣言されているが未使用の変数やメソッドの識別
|
| 272 |
+
4. 不完全なエラーハンドリング(try-exceptブロックなど)
|
| 273 |
+
5. 未完成のコメント(TODO、FIXME、XXXなど)の検出
|
| 274 |
+
6. テストコードの網羅性(全機能をカバーしているか)
|
| 275 |
+
7. ドキュメンテーションの完全性(すべての公開APIにドキュメントがあるか)
|
| 276 |
+
8. 設定ファイルや環境変数の完全性
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
# 設計書の情報を追加
|
| 280 |
+
design_spec_str = ""
|
| 281 |
+
if design_doc:
|
| 282 |
+
design_spec_str = f"""
|
| 283 |
+
このコードは以下の設計書に基づいています。コードが設計書の要件と一致しているか確認してください:
|
| 284 |
+
|
| 285 |
+
{design_doc}
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
prompt = {
|
| 289 |
+
"role": "Code_Verifier_And_Algorithm_Expert",
|
| 290 |
+
"instruction": f"""あなたは{language}の専門家で、アルゴリズムとデータ構造に精通しています。
|
| 291 |
+
提供されたコードを厳密に検証し、問題固有の制約条件を考慮して評価してください。
|
| 292 |
+
|
| 293 |
+
以下の観点でコードを検証し、JSON形式で結果を返してください:
|
| 294 |
+
|
| 295 |
+
1. 構文エラーやコンパイルエラー
|
| 296 |
+
2. 論理的な誤りやアルゴリズムの欠陥
|
| 297 |
+
3. 問題の制約条件との整合性
|
| 298 |
+
4. エッジケース(空の入力、最小/最大値、重複など)の処理
|
| 299 |
+
5. 時間/空間複雑度の要件への適合
|
| 300 |
+
6. データ構造の実装不備(例: トライ木の不完全な接続、グラフの誤った表現)
|
| 301 |
+
7. 指定されたアルゴリズムの正しい実装(該当する場合)
|
| 302 |
+
8. メモリリークやリソース管理の問題
|
| 303 |
+
|
| 304 |
+
特に重点的に検証すべき項目:
|
| 305 |
+
|
| 306 |
+
1. 無限ループの可能性
|
| 307 |
+
{infinite_loop_detection}
|
| 308 |
+
|
| 309 |
+
2. オブジェクト指向設計の原則(OOPコードの場合)
|
| 310 |
+
{oop_principles}
|
| 311 |
+
|
| 312 |
+
3. ベクトル計算の効率性(ベクトル/行列操作を含む場合)
|
| 313 |
+
{vector_efficiency}
|
| 314 |
+
|
| 315 |
+
4. 物理シミュレーションの正確性(物理シミュレーションの場合)
|
| 316 |
+
{physics_simulation_validation}
|
| 317 |
+
|
| 318 |
+
5. エラーハンドリングの完全性
|
| 319 |
+
{error_handling_validation}
|
| 320 |
+
|
| 321 |
+
6. コードの完全性と実行可能性
|
| 322 |
+
{code_completeness_validation}
|
| 323 |
+
|
| 324 |
+
{design_spec_str}
|
| 325 |
+
|
| 326 |
+
問題の説明:
|
| 327 |
+
{problem_description or "具体的な問題説明は提供されていません。一般的なコード品質を検証します。"}
|
| 328 |
+
|
| 329 |
+
{constraints_str}
|
| 330 |
+
|
| 331 |
+
応答は以下のJSON形式で返してください:
|
| 332 |
+
{{
|
| 333 |
+
"is_valid": boolean, // コードが有効かどうか
|
| 334 |
+
"issues": [string], // 検出された問題点のリスト(重要度順)
|
| 335 |
+
"design_compliance": boolean, // 設計書の要件に準拠しているか(設計書がある場合)
|
| 336 |
+
"missing_requirements": [string], // 設計書で定義されているが実装されていない要件(設計書がある場合)
|
| 337 |
+
"algorithm_analysis": string, // アルゴリズム分析(時間/空間複雑度など)
|
| 338 |
+
"edge_cases": [string], // テストすべきエッジケースのリスト
|
| 339 |
+
"oop_analysis": string, // OOP原則の遵守状況分析(該当する場合のみ)
|
| 340 |
+
"vector_efficiency_analysis": string, // ベクトル計算効率の分析(該当する場合のみ)
|
| 341 |
+
"physics_simulation_analysis": string, // 物理シミュレーションの分析(該当する場合のみ)
|
| 342 |
+
"error_handling_analysis": string, // エラーハンドリングの分析
|
| 343 |
+
"code_completeness_analysis": string, // コードの完全性分析
|
| 344 |
+
"infinite_loop_risk": {{
|
| 345 |
+
"risk_level": string, // "none", "low", "medium", "high"のいずれか
|
| 346 |
+
"potential_causes": [string], // 潜在的な無限ループの原因(リスクがある場合)
|
| 347 |
+
"recommended_safeguards": [string] // 推奨される安全対策(リスクがある場合)
|
| 348 |
+
}},
|
| 349 |
+
"fixed_code": string, // 修正されたコード(問題がある場合のみ)
|
| 350 |
+
"explanation": string // 修正の詳細な説明(問題がある場合のみ)
|
| 351 |
+
}}
|
| 352 |
+
""",
|
| 353 |
+
"code_to_verify": code,
|
| 354 |
+
"language": language
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
return json.dumps(prompt, ensure_ascii=False)
|
| 358 |
+
|
| 359 |
+
def _extract_design_doc(self, content: str) -> Optional[str]:
|
| 360 |
+
"""コンテンツから設計書部分を抽出する"""
|
| 361 |
+
# 設計書の開始と終了を示す一般的なパターン
|
| 362 |
+
design_doc_indicators = [
|
| 363 |
+
"設計書", "要件の整理と分析", "アーキテクチャ設計", "詳細設計",
|
| 364 |
+
"クラス/モジュール構造", "コンポーネント構成", "データモデル"
|
| 365 |
+
]
|
| 366 |
+
|
| 367 |
+
# コンテンツに設計書のパターンがあるか確認
|
| 368 |
+
for indicator in design_doc_indicators:
|
| 369 |
+
if indicator in content:
|
| 370 |
+
# 設計書全体を抽出
|
| 371 |
+
start_index = content.find(indicator)
|
| 372 |
+
design_doc = content[start_index:]
|
| 373 |
+
return design_doc
|
| 374 |
+
|
| 375 |
+
return None
|
| 376 |
+
|
| 377 |
+
def _extract_class_definitions_from_design(self, design_doc: str) -> Dict[str, Dict[str, Any]]:
|
| 378 |
+
"""設計書からクラス定義と要件を抽出する"""
|
| 379 |
+
class_definitions = {}
|
| 380 |
+
|
| 381 |
+
# クラス定義の抽出
|
| 382 |
+
class_pattern = r'class\s+(\w+):'
|
| 383 |
+
class_matches = re.finditer(class_pattern, design_doc)
|
| 384 |
+
|
| 385 |
+
for match in class_matches:
|
| 386 |
+
class_name = match.group(1)
|
| 387 |
+
# クラスの説明を抽出
|
| 388 |
+
start_pos = match.end()
|
| 389 |
+
next_class_match = re.search(r'class\s+\w+:', design_doc[start_pos:])
|
| 390 |
+
end_pos = start_pos + next_class_match.start() if next_class_match else len(design_doc)
|
| 391 |
+
class_body = design_doc[start_pos:end_pos].strip()
|
| 392 |
+
|
| 393 |
+
# メソッド定義の抽出
|
| 394 |
+
method_pattern = r'def\s+(\w+)\s*\((.*?)\)'
|
| 395 |
+
method_matches = re.finditer(method_pattern, class_body)
|
| 396 |
+
methods = {}
|
| 397 |
+
|
| 398 |
+
for method_match in method_matches:
|
| 399 |
+
method_name = method_match.group(1)
|
| 400 |
+
parameters = [p.strip() for p in method_match.group(2).split(',') if p.strip()]
|
| 401 |
+
methods[method_name] = parameters
|
| 402 |
+
|
| 403 |
+
class_definitions[class_name] = {
|
| 404 |
+
"methods": methods,
|
| 405 |
+
"description": class_body
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
return class_definitions
|
| 409 |
+
|
| 410 |
+
def _extract_requirements_from_design(self, design_doc: str) -> List[str]:
|
| 411 |
+
"""設計書から機能要件を抽出する"""
|
| 412 |
+
requirements = []
|
| 413 |
+
|
| 414 |
+
# 機能要件セクションの抽出
|
| 415 |
+
if "機能要件" in design_doc:
|
| 416 |
+
func_req_section = re.search(r'機能要件([\s\S]*?)(?=1\.2|非機能要件|$)', design_doc)
|
| 417 |
+
if func_req_section:
|
| 418 |
+
section_text = func_req_section.group(1)
|
| 419 |
+
# 箇条書きの抽出
|
| 420 |
+
bullet_pattern = r'[•*-]\s*(.*?)(?=$|\n)'
|
| 421 |
+
bullet_points = re.findall(bullet_pattern, section_text)
|
| 422 |
+
if bullet_points:
|
| 423 |
+
requirements.extend(bullet_points)
|
| 424 |
+
else:
|
| 425 |
+
# 番号付きリストの抽出
|
| 426 |
+
numbered_pattern = r'\d+\.\s*(.*?)(?=$|\n)'
|
| 427 |
+
numbered_points = re.findall(numbered_pattern, section_text)
|
| 428 |
+
if numbered_points:
|
| 429 |
+
requirements.extend(numbered_points)
|
| 430 |
+
|
| 431 |
+
return requirements
|
| 432 |
+
|
| 433 |
+
def _check_implementation_against_design(self, code: str, design_doc: str) -> Dict[str, Any]:
|
| 434 |
+
"""実装コードが設計書の要件に合致しているか確認する"""
|
| 435 |
+
result = {
|
| 436 |
+
"design_compliance": True,
|
| 437 |
+
"missing_requirements": [],
|
| 438 |
+
"missing_classes": [],
|
| 439 |
+
"missing_methods": []
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
# クラス定義の抽出
|
| 443 |
+
class_definitions = self._extract_class_definitions_from_design(design_doc)
|
| 444 |
+
|
| 445 |
+
# 要件の抽出
|
| 446 |
+
requirements = self._extract_requirements_from_design(design_doc)
|
| 447 |
+
|
| 448 |
+
# 実装されたクラスの抽出
|
| 449 |
+
implemented_classes = re.findall(r'class\s+(\w+)', code)
|
| 450 |
+
|
| 451 |
+
# クラスの確認
|
| 452 |
+
for class_name, class_info in class_definitions.items():
|
| 453 |
+
if class_name not in implemented_classes:
|
| 454 |
+
result["design_compliance"] = False
|
| 455 |
+
result["missing_classes"].append(class_name)
|
| 456 |
+
continue
|
| 457 |
+
|
| 458 |
+
# メソッドの確認
|
| 459 |
+
class_code_match = re.search(fr'class\s+{class_name}[\s\S]*?(?:class|\Z)', code)
|
| 460 |
+
if class_code_match:
|
| 461 |
+
class_code = class_code_match.group(0)
|
| 462 |
+
for method_name in class_info["methods"]:
|
| 463 |
+
method_pattern = fr'def\s+{method_name}\s*\('
|
| 464 |
+
if not re.search(method_pattern, class_code):
|
| 465 |
+
result["design_compliance"] = False
|
| 466 |
+
result["missing_methods"].append(f"{class_name}.{method_name}")
|
| 467 |
+
|
| 468 |
+
# 要件の確認
|
| 469 |
+
for req in requirements:
|
| 470 |
+
# キーワードベースの簡易チェック
|
| 471 |
+
keywords = self._extract_keywords(req)
|
| 472 |
+
if keywords and not all(re.search(fr'\b{re.escape(kw.lower())}\b', code.lower()) for kw in keywords if len(kw) > 3):
|
| 473 |
+
result["design_compliance"] = False
|
| 474 |
+
result["missing_requirements"].append(req)
|
| 475 |
+
|
| 476 |
+
return result
|
| 477 |
+
|
| 478 |
+
def _extract_keywords(self, text: str) -> List[str]:
|
| 479 |
+
"""テキストから重要なキーワードを抽出する"""
|
| 480 |
+
# ストップワードを定義
|
| 481 |
+
stop_words = {
|
| 482 |
+
"a", "an", "the", "this", "that", "these", "those", "and", "or", "but", "for", "nor", "so", "yet",
|
| 483 |
+
"を", "に", "は", "が", "で", "と", "から", "まで", "より", "して", "する", "ます", "です"
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
# 単語に分割
|
| 487 |
+
words = re.findall(r'\b\w+\b', text.lower())
|
| 488 |
+
|
| 489 |
+
# ストップワードと短す���る単語を除外
|
| 490 |
+
keywords = [w for w in words if w not in stop_words and len(w) > 1]
|
| 491 |
+
|
| 492 |
+
return keywords
|
| 493 |
+
|
| 494 |
+
async def _verify_single_code_block(self, index: int, code_block: Dict[str, Any], user_input: str = None, design_doc: str = None) -> Dict[str, Any]:
|
| 495 |
+
"""単一のコードブロックを検証する(ユーザー入力コンテキスト付き)"""
|
| 496 |
+
print(f"[Code Verification] Started verification of code block {index+1}")
|
| 497 |
+
|
| 498 |
+
language = code_block.get("language", "unknown")
|
| 499 |
+
code = code_block.get("code", "")
|
| 500 |
+
|
| 501 |
+
# 空のコードブロックや意味のない内容を検出
|
| 502 |
+
if not code.strip() or code.strip() in ["pass", "#", "# コード", "# Code"]:
|
| 503 |
+
return {
|
| 504 |
+
"block_info": {
|
| 505 |
+
"block_index": index,
|
| 506 |
+
"language": language,
|
| 507 |
+
"is_valid": False,
|
| 508 |
+
"issues": ["コードが提供されていないか、空です"],
|
| 509 |
+
"algorithm_analysis": "コードが不足しています",
|
| 510 |
+
"edge_cases": [],
|
| 511 |
+
"was_fixed": False
|
| 512 |
+
},
|
| 513 |
+
"needs_update": False,
|
| 514 |
+
"fixed_code": code,
|
| 515 |
+
"explanation": "コードが提供されていません。適切なコードを実装してください。"
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
# 検証プロンプトの構築(ユーザー入力と設計書を含める)
|
| 519 |
+
verification_prompt = self._build_verification_prompt(language, code, user_input, design_doc)
|
| 520 |
+
messages = [
|
| 521 |
+
{
|
| 522 |
+
"role": "system",
|
| 523 |
+
"content": verification_prompt
|
| 524 |
+
}
|
| 525 |
+
]
|
| 526 |
+
|
| 527 |
+
response = await self._make_async_api_call(
|
| 528 |
+
self.verify_model,
|
| 529 |
+
messages,
|
| 530 |
+
temperature=0.1,
|
| 531 |
+
response_format={"type": "json_object"}
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
# 検証結果の解析
|
| 535 |
+
verification_result = json.loads(response.choices[0].message.content)
|
| 536 |
+
|
| 537 |
+
# 結果をまとめる
|
| 538 |
+
needs_update = False
|
| 539 |
+
fixed_code = code
|
| 540 |
+
|
| 541 |
+
if not verification_result.get("is_valid", True):
|
| 542 |
+
print(f"[Code Verification] Issues found in code block {index+1}")
|
| 543 |
+
if "fixed_code" in verification_result and verification_result["fixed_code"].strip():
|
| 544 |
+
fixed_code = verification_result["fixed_code"]
|
| 545 |
+
needs_update = code != fixed_code
|
| 546 |
+
|
| 547 |
+
# 設計書の要件確認
|
| 548 |
+
design_compliance = verification_result.get("design_compliance", True)
|
| 549 |
+
missing_requirements = verification_result.get("missing_requirements", [])
|
| 550 |
+
|
| 551 |
+
return {
|
| 552 |
+
"block_info": {
|
| 553 |
+
"block_index": index,
|
| 554 |
+
"language": language,
|
| 555 |
+
"is_valid": verification_result.get("is_valid", True),
|
| 556 |
+
"issues": verification_result.get("issues", []),
|
| 557 |
+
"algorithm_analysis": verification_result.get("algorithm_analysis", ""),
|
| 558 |
+
"edge_cases": verification_result.get("edge_cases", []),
|
| 559 |
+
"was_fixed": needs_update,
|
| 560 |
+
"design_compliance": design_compliance,
|
| 561 |
+
"missing_requirements": missing_requirements,
|
| 562 |
+
"physics_simulation_analysis": verification_result.get("physics_simulation_analysis", ""),
|
| 563 |
+
"error_handling_analysis": verification_result.get("error_handling_analysis", ""),
|
| 564 |
+
"code_completeness_analysis": verification_result.get("code_completeness_analysis", "")
|
| 565 |
+
},
|
| 566 |
+
"needs_update": needs_update,
|
| 567 |
+
"fixed_code": fixed_code,
|
| 568 |
+
"explanation": verification_result.get("explanation", "")
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
async def verify_code_blocks(self, content: str, user_input: str = None) -> Dict[str, Any]:
|
| 572 |
+
"""コンテンツから抽出したコードブロックを並列検証する(設計書認識機能付き)"""
|
| 573 |
+
print("\n[Code Verification] Verifying code blocks in content...")
|
| 574 |
+
|
| 575 |
+
# 設計書の検出と抽出
|
| 576 |
+
design_doc = self._extract_design_doc(content)
|
| 577 |
+
if design_doc:
|
| 578 |
+
print("[Code Verification] Design document detected")
|
| 579 |
+
|
| 580 |
+
# コンテンツからコードブロックを抽出
|
| 581 |
+
code_blocks = self._extract_code_blocks(content)
|
| 582 |
+
|
| 583 |
+
if not code_blocks:
|
| 584 |
+
print("[Code Verification] No code blocks found to verify")
|
| 585 |
+
|
| 586 |
+
# 設計書があるが実装がない場合
|
| 587 |
+
if design_doc:
|
| 588 |
+
return {
|
| 589 |
+
"verified_content": content,
|
| 590 |
+
"verification_result": {
|
| 591 |
+
"verified_code_blocks": [],
|
| 592 |
+
"issues_found": True,
|
| 593 |
+
"verification_summary": "設計書は見つかりましたが、実装コードがありません。設計書に基づいた実装が必要です。",
|
| 594 |
+
"design_requirements": self._extract_requirements_from_design(design_doc)
|
| 595 |
+
}
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
return {
|
| 599 |
+
"verified_content": content,
|
| 600 |
+
"verification_result": {
|
| 601 |
+
"verified_code_blocks": [],
|
| 602 |
+
"issues_found": False,
|
| 603 |
+
"verification_summary": "コードブロックが見つかりませんでした。"
|
| 604 |
+
}
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
# 検証結果を格納する辞書
|
| 608 |
+
verification_results = {
|
| 609 |
+
"verified_code_blocks": [],
|
| 610 |
+
"issues_found": False,
|
| 611 |
+
"verification_summary": "",
|
| 612 |
+
"verification_time": 0,
|
| 613 |
+
"algorithm_issues": [],
|
| 614 |
+
"critical_edge_cases": [],
|
| 615 |
+
"design_compliance": True,
|
| 616 |
+
"missing_requirements": [],
|
| 617 |
+
"physics_simulation_issues": [],
|
| 618 |
+
"error_handling_issues": [],
|
| 619 |
+
"code_completeness_issues": []
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
# 並列検証の開始時間を記録
|
| 623 |
+
start_time = asyncio.get_event_loop().time()
|
| 624 |
+
|
| 625 |
+
# 各コードブロックの検証タスクを作成
|
| 626 |
+
verification_tasks = []
|
| 627 |
+
for i, code_block in enumerate(code_blocks):
|
| 628 |
+
task = self._verify_single_code_block(i, code_block, user_input, design_doc)
|
| 629 |
+
verification_tasks.append(task)
|
| 630 |
+
|
| 631 |
+
# すべての検証タスクを並列実行
|
| 632 |
+
print(f"[Code Verification] Parallel verification of {len(verification_tasks)} code blocks started")
|
| 633 |
+
block_results = await asyncio.gather(*verification_tasks, return_exceptions=True)
|
| 634 |
+
|
| 635 |
+
# 更新されたコンテンツ
|
| 636 |
+
verified_content = content
|
| 637 |
+
|
| 638 |
+
# 設計書関連の問題を収集
|
| 639 |
+
design_issues = set()
|
| 640 |
+
|
| 641 |
+
# 検証結果の処理
|
| 642 |
+
for i, result in enumerate(block_results):
|
| 643 |
+
if isinstance(result, Exception):
|
| 644 |
+
print(f"[Error] Verification of block {i} failed: {str(result)}")
|
| 645 |
+
verification_results["verified_code_blocks"].append({
|
| 646 |
+
"block_index": i,
|
| 647 |
+
"language": code_blocks[i].get("language", "unknown"),
|
| 648 |
+
"verification_error": str(result)
|
| 649 |
+
})
|
| 650 |
+
continue
|
| 651 |
+
|
| 652 |
+
# 結果を格納
|
| 653 |
+
verification_results["verified_code_blocks"].append(result["block_info"])
|
| 654 |
+
|
| 655 |
+
# 設計書の遵守状況を確認
|
| 656 |
+
if not result["block_info"].get("design_compliance", True):
|
| 657 |
+
verification_results["design_compliance"] = False
|
| 658 |
+
missing_reqs = result["block_info"].get("missing_requirements", [])
|
| 659 |
+
for req in missing_reqs:
|
| 660 |
+
design_issues.add(req)
|
| 661 |
+
|
| 662 |
+
# アルゴリズム分析とエッジケースの収集
|
| 663 |
+
if result["block_info"].get("algorithm_analysis"):
|
| 664 |
+
verification_results["algorithm_issues"].append({
|
| 665 |
+
"block_index": i,
|
| 666 |
+
"analysis": result["block_info"]["algorithm_analysis"]
|
| 667 |
+
})
|
| 668 |
+
|
| 669 |
+
if result["block_info"].get("edge_cases"):
|
| 670 |
+
verification_results["critical_edge_cases"].extend(result["block_info"]["edge_cases"])
|
| 671 |
+
|
| 672 |
+
# 物理シミュレーション分析の収集
|
| 673 |
+
if result["block_info"].get("physics_simulation_analysis"):
|
| 674 |
+
verification_results["physics_simulation_issues"].append({
|
| 675 |
+
"block_index": i,
|
| 676 |
+
"analysis": result["block_info"]["physics_simulation_analysis"]
|
| 677 |
+
})
|
| 678 |
+
|
| 679 |
+
# エラーハンドリング分析の収集
|
| 680 |
+
if result["block_info"].get("error_handling_analysis"):
|
| 681 |
+
verification_results["error_handling_issues"].append({
|
| 682 |
+
"block_index": i,
|
| 683 |
+
"analysis": result["block_info"]["error_handling_analysis"]
|
| 684 |
+
})
|
| 685 |
+
|
| 686 |
+
# コード完全性分析の収集
|
| 687 |
+
if result["block_info"].get("code_completeness_analysis"):
|
| 688 |
+
verification_results["code_completeness_issues"].append({
|
| 689 |
+
"block_index": i,
|
| 690 |
+
"analysis": result["block_info"]["code_completeness_analysis"]
|
| 691 |
+
})
|
| 692 |
+
|
| 693 |
+
# 問題が見つかった場合はコンテンツを更新
|
| 694 |
+
if result["needs_update"]:
|
| 695 |
+
verification_results["issues_found"] = True
|
| 696 |
+
verified_content = self._update_code_in_content(
|
| 697 |
+
verified_content,
|
| 698 |
+
i,
|
| 699 |
+
result["fixed_code"]
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
# 修正の説明も保存
|
| 703 |
+
if "explanation" in result and result["explanation"]:
|
| 704 |
+
if "code_fixes_explanations" not in verification_results:
|
| 705 |
+
verification_results["code_fixes_explanations"] = []
|
| 706 |
+
verification_results["code_fixes_explanations"].append({
|
| 707 |
+
"block_index": i,
|
| 708 |
+
"explanation": result["explanation"]
|
| 709 |
+
})
|
| 710 |
+
|
| 711 |
+
# 検証時間を計算
|
| 712 |
+
end_time = asyncio.get_event_loop().time()
|
| 713 |
+
verification_time = end_time - start_time
|
| 714 |
+
verification_results["verification_time"] = round(verification_time, 2)
|
| 715 |
+
|
| 716 |
+
# 重複するエッジケースを削除
|
| 717 |
+
verification_results["critical_edge_cases"] = list(set(verification_results["critical_edge_cases"]))
|
| 718 |
+
|
| 719 |
+
# 設計書の要件を追加
|
| 720 |
+
if design_issues:
|
| 721 |
+
verification_results["missing_requirements"] = list(design_issues)
|
| 722 |
+
|
| 723 |
+
# 検証サマリーの生成
|
| 724 |
+
if verification_results["issues_found"]:
|
| 725 |
+
verification_results["verification_summary"] = f"コードの問題が検出され修正されました(検証時間: {verification_results['verification_time']}秒)。\n\n"
|
| 726 |
+
|
| 727 |
+
# 問題と修正内容のサマリーを対比形式で表示
|
| 728 |
+
for block in verification_results["verified_code_blocks"]:
|
| 729 |
+
if block.get("was_fixed", False):
|
| 730 |
+
issues_list = block.get("issues", [])
|
| 731 |
+
if issues_list:
|
| 732 |
+
verification_results["verification_summary"] += f"ブロック{block['block_index']+1}({block['language']}):\n"
|
| 733 |
+
for issue in issues_list[:3]:
|
| 734 |
+
verification_results["verification_summary"] += f"❌ 問題: {issue}\n"
|
| 735 |
+
verification_results["verification_summary"] += f"✅ 修正完了: コードが自動修正されました\n\n"
|
| 736 |
+
|
| 737 |
+
# 設計書の要件未実装がある場合
|
| 738 |
+
if not verification_results["design_compliance"] and verification_results["missing_requirements"]:
|
| 739 |
+
verification_results["verification_summary"] += "\n設計書の要件に対する問題:\n"
|
| 740 |
+
for req in verification_results["missing_requirements"][:5]:
|
| 741 |
+
verification_results["verification_summary"] += f"❌ 未実装: {req}\n"
|
| 742 |
+
if len(verification_results["missing_requirements"]) > 5:
|
| 743 |
+
verification_results["verification_summary"] += "...他にも未実装の要件があります\n"
|
| 744 |
+
|
| 745 |
+
# 物理シミュレーション関連の問題がある場合
|
| 746 |
+
if verification_results["physics_simulation_issues"]:
|
| 747 |
+
verification_results["verification_summary"] += "\n物理シミュレーションの問題:\n"
|
| 748 |
+
for issue in verification_results["physics_simulation_issues"][:3]:
|
| 749 |
+
verification_results["verification_summary"] += f"⚠️ {issue['analysis']}\n"
|
| 750 |
+
|
| 751 |
+
# エラーハンドリング関連の問題がある場合
|
| 752 |
+
if verification_results["error_handling_issues"]:
|
| 753 |
+
verification_results["verification_summary"] += "\nエラーハンドリングの問題:\n"
|
| 754 |
+
for issue in verification_results["error_handling_issues"][:3]:
|
| 755 |
+
verification_results["verification_summary"] += f"⚠️ {issue['analysis']}\n"
|
| 756 |
+
|
| 757 |
+
# コード完全性関連の問題がある場合
|
| 758 |
+
if verification_results["code_completeness_issues"]:
|
| 759 |
+
verification_results["verification_summary"] += "\nコードの完全性に関する問題:\n"
|
| 760 |
+
for issue in verification_results["code_completeness_issues"][:3]:
|
| 761 |
+
verification_results["verification_summary"] += f"⚠️ {issue['analysis']}\n"
|
| 762 |
+
else:
|
| 763 |
+
verification_results["verification_summary"] = f"✅ すべてのコードが検証を通過しました(検証時間: {verification_results['verification_time']}秒)。\n"
|
| 764 |
+
|
| 765 |
+
# エッジケースの提案がある場合
|
| 766 |
+
if verification_results["critical_edge_cases"]:
|
| 767 |
+
verification_results["verification_summary"] += f"\n\nテスト推奨エッジケース: {', '.join(verification_results['critical_edge_cases'][:5])}"
|
| 768 |
+
|
| 769 |
+
return {
|
| 770 |
+
"verified_content": verified_content,
|
| 771 |
+
"verification_result": verification_results
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
async def verify_implementation(self, technical_analysis, user_input: str = None) -> Dict[str, Any]:
|
| 775 |
+
"""実装データを検証する(JSON形式または純粋なコンテンツ)"""
|
| 776 |
+
if isinstance(technical_analysis, dict):
|
| 777 |
+
# 辞書/JSON形式のデータが渡された場合
|
| 778 |
+
code_blocks = self._extract_nested_code_blocks(technical_analysis)
|
| 779 |
+
|
| 780 |
+
if not code_blocks:
|
| 781 |
+
print("[Code Verification] No code blocks found in analysis")
|
| 782 |
+
return technical_analysis
|
| 783 |
+
|
| 784 |
+
# 辞書の場合の検証コード��こちらに実装する
|
| 785 |
+
# 現在はコードの抽出のみ実装
|
| 786 |
+
return technical_analysis
|
| 787 |
+
|
| 788 |
+
elif isinstance(technical_analysis, str):
|
| 789 |
+
# 文字列(マークダウンなど)の場合
|
| 790 |
+
result = await self.verify_code_blocks(technical_analysis, user_input)
|
| 791 |
+
return result["verified_content"]
|
| 792 |
+
else:
|
| 793 |
+
# その他の型の場合
|
| 794 |
+
print(f"[Error] Unsupported data type for verification: {type(technical_analysis)}")
|
| 795 |
+
return technical_analysis
|
| 796 |
+
|
| 797 |
+
async def verify_implementation_completeness(self, code: str) -> Dict[str, Any]:
|
| 798 |
+
"""コードの完全性を検証し、不足している部分を特定する"""
|
| 799 |
+
# 結果を格納する辞書
|
| 800 |
+
result = {
|
| 801 |
+
"is_complete": True,
|
| 802 |
+
"issues": [],
|
| 803 |
+
"unimplemented_methods": [],
|
| 804 |
+
"missing_imports": [],
|
| 805 |
+
"missing_error_handling": [],
|
| 806 |
+
"todos": []
|
| 807 |
+
}
|
| 808 |
+
|
| 809 |
+
# 空のコード、空のメソッド、パスのみのメソッドを検出
|
| 810 |
+
if not code.strip():
|
| 811 |
+
result["is_complete"] = False
|
| 812 |
+
result["issues"].append("コードが空です")
|
| 813 |
+
return result
|
| 814 |
+
|
| 815 |
+
try:
|
| 816 |
+
# ASTを使用してコードを解析
|
| 817 |
+
tree = ast.parse(code)
|
| 818 |
+
|
| 819 |
+
# 未実装メソッドの検出
|
| 820 |
+
for node in ast.walk(tree):
|
| 821 |
+
if isinstance(node, ast.FunctionDef):
|
| 822 |
+
# 関数本体の確認
|
| 823 |
+
function_body = node.body
|
| 824 |
+
|
| 825 |
+
# 空の関数や単なる'pass'のみの関数を検出
|
| 826 |
+
if not function_body:
|
| 827 |
+
result["is_complete"] = False
|
| 828 |
+
result["unimplemented_methods"].append(node.name)
|
| 829 |
+
result["issues"].append(f"未実装のメソッド: {node.name}")
|
| 830 |
+
elif len(function_body) == 1 and isinstance(function_body[0], ast.Pass):
|
| 831 |
+
result["is_complete"] = False
|
| 832 |
+
result["unimplemented_methods"].append(node.name)
|
| 833 |
+
result["issues"].append(f"未実装のメソッド (pass文のみ): {node.name}")
|
| 834 |
+
|
| 835 |
+
# ToDo コメントの検出
|
| 836 |
+
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str):
|
| 837 |
+
comment = node.value.s
|
| 838 |
+
if any(marker in comment for marker in ["TODO", "FIXME", "XXX", "todo", "fixme"]):
|
| 839 |
+
result["todos"].append(comment)
|
| 840 |
+
result["issues"].append(f"TODOコメント: {comment}")
|
| 841 |
+
|
| 842 |
+
# インポートの確認
|
| 843 |
+
imported_modules = set()
|
| 844 |
+
for node in ast.walk(tree):
|
| 845 |
+
if isinstance(node, ast.Import):
|
| 846 |
+
for name in node.names:
|
| 847 |
+
imported_modules.add(name.name)
|
| 848 |
+
elif isinstance(node, ast.ImportFrom):
|
| 849 |
+
imported_modules.add(node.module)
|
| 850 |
+
|
| 851 |
+
# 使用されているが明示的にインポートされていないモジュールを検出
|
| 852 |
+
for node in ast.walk(tree):
|
| 853 |
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
|
| 854 |
+
module_name = node.id
|
| 855 |
+
# 標準ライブラリや組み込み関数は除外
|
| 856 |
+
if (module_name not in imported_modules and
|
| 857 |
+
module_name not in dir(__builtins__) and
|
| 858 |
+
not any(module_name.startswith(imp) for imp in imported_modules)):
|
| 859 |
+
result["missing_imports"].append(module_name)
|
| 860 |
+
result["issues"].append(f"使用されているが明示的にインポートされていないモジュール: {module_name}")
|
| 861 |
+
|
| 862 |
+
# エラーハンドリングの確認
|
| 863 |
+
try_blocks = sum(1 for node in ast.walk(tree) if isinstance(node, ast.Try))
|
| 864 |
+
if try_blocks == 0:
|
| 865 |
+
result["missing_error_handling"].append("try-exceptブロックが見つかりません")
|
| 866 |
+
result["issues"].append("エラーハンドリングが不足しています (try-exceptブロックなし)")
|
| 867 |
+
|
| 868 |
+
except SyntaxError as e:
|
| 869 |
+
result["is_complete"] = False
|
| 870 |
+
result["issues"].append(f"構文エラー: {str(e)}")
|
| 871 |
+
|
| 872 |
+
# 実行可能性のテスト
|
| 873 |
+
try:
|
| 874 |
+
# 一時ファイルにコードを書き込む
|
| 875 |
+
with tempfile.NamedTemporaryFile(suffix='.py', delete=False) as temp_file:
|
| 876 |
+
temp_file_path = temp_file.name
|
| 877 |
+
temp_file.write(code.encode('utf-8'))
|
| 878 |
+
|
| 879 |
+
# Pythonのコンパイルチェック(構文チェック)を実行
|
| 880 |
+
compile_result = subprocess.run(
|
| 881 |
+
['python', '-m', 'py_compile', temp_file_path],
|
| 882 |
+
capture_output=True,
|
| 883 |
+
text=True
|
| 884 |
+
)
|
| 885 |
+
|
| 886 |
+
# エラーがあれば記録
|
| 887 |
+
if compile_result.returncode != 0:
|
| 888 |
+
result["is_complete"] = False
|
| 889 |
+
result["issues"].append(f"コンパイルエラー: {compile_result.stderr}")
|
| 890 |
+
|
| 891 |
+
except Exception as e:
|
| 892 |
+
result["issues"].append(f"コードの実行可能性テスト中にエラー: {str(e)}")
|
| 893 |
+
finally:
|
| 894 |
+
# 一時ファイルの削除
|
| 895 |
+
if 'temp_file_path' in locals():
|
| 896 |
+
try:
|
| 897 |
+
os.remove(temp_file_path)
|
| 898 |
+
except:
|
| 899 |
+
pass
|
| 900 |
+
|
| 901 |
+
# 完全性の最終判定
|
| 902 |
+
result["is_complete"] = result["is_complete"] and not result["issues"]
|
| 903 |
+
|
| 904 |
+
return result
|
| 905 |
+
|
| 906 |
+
async def apply_verification_feedback(self, original_prompt: str, verification_result: Dict[str, Any]) -> str:
|
| 907 |
+
"""検証結果を基に改善されたプロンプトを生成する"""
|
| 908 |
+
# 検証結果から重要な問題点を抽出
|
| 909 |
+
issues = []
|
| 910 |
+
if "verified_code_blocks" in verification_result:
|
| 911 |
+
for block in verification_result["verified_code_blocks"]:
|
| 912 |
+
if not block.get("is_valid", True):
|
| 913 |
+
issues.extend(block.get("issues", []))
|
| 914 |
+
|
| 915 |
+
# 設計要件との不一致
|
| 916 |
+
if not verification_result.get("design_compliance", True):
|
| 917 |
+
missing_reqs = verification_result.get("missing_requirements", [])
|
| 918 |
+
for req in missing_reqs:
|
| 919 |
+
issues.append(f"設計要件未実装: {req}")
|
| 920 |
+
|
| 921 |
+
# エッジケース対応の不足
|
| 922 |
+
edge_cases = verification_result.get("critical_edge_cases", [])
|
| 923 |
+
if edge_cases:
|
| 924 |
+
issues.append(f"対応すべきエッジケース: {', '.join(edge_cases[:5])}")
|
| 925 |
+
|
| 926 |
+
# 物理シミュレーション関連の問題
|
| 927 |
+
if "physics_simulation_issues" in verification_result and verification_result["physics_simulation_issues"]:
|
| 928 |
+
for issue in verification_result["physics_simulation_issues"][:3]:
|
| 929 |
+
issues.append(f"物理シミュレーションの問題: {issue.get('analysis', '')}")
|
| 930 |
+
|
| 931 |
+
# エラーハンドリング関連の問題
|
| 932 |
+
if "error_handling_issues" in verification_result and verification_result["error_handling_issues"]:
|
| 933 |
+
for issue in verification_result["error_handling_issues"][:3]:
|
| 934 |
+
issues.append(f"エラーハンドリングの問題: {issue.get('analysis', '')}")
|
| 935 |
+
|
| 936 |
+
# コード完全性関連の問題
|
| 937 |
+
if "code_completeness_issues" in verification_result and verification_result["code_completeness_issues"]:
|
| 938 |
+
for issue in verification_result["code_completeness_issues"][:3]:
|
| 939 |
+
issues.append(f"コード完全性の問題: {issue.get('analysis', '')}")
|
| 940 |
+
|
| 941 |
+
# 問題点が見つからない場合は元のプロンプトを返す
|
| 942 |
+
if not issues:
|
| 943 |
+
return original_prompt
|
| 944 |
+
|
| 945 |
+
# 問題点を含めた改善プロンプトを生成
|
| 946 |
+
improved_prompt = f"{original_prompt}\n\n前回の実装では以下の問題点がありました。これらを解決した実装を提供してください:\n"
|
| 947 |
+
for i, issue in enumerate(issues[:10]): # 最大10個の問題を表示
|
| 948 |
+
improved_prompt += f"{i+1}. {issue}\n"
|
| 949 |
+
|
| 950 |
+
if len(issues) > 10:
|
| 951 |
+
improved_prompt += f"他にも{len(issues)-10}個の問題があります。\n"
|
| 952 |
+
|
| 953 |
+
improved_prompt += "\n特に以下の点に注意して実装してください:\n"
|
| 954 |
+
improved_prompt += "1. 全てのコードが実行可能であること\n"
|
| 955 |
+
improved_prompt += "2. エッジケース(極端な入力値、境界条件)に対応すること\n"
|
| 956 |
+
improved_prompt += "3. エラーハンドリングを徹底すること\n"
|
| 957 |
+
improved_prompt += "4. 設計書の全ての要件を実装すること\n"
|
| 958 |
+
|
| 959 |
+
return improved_prompt
|