ryoshimu
commited on
Commit
·
854e13d
1
Parent(s):
668c519
commit
Browse files- __pycache__/app.cpython-313.pyc +0 -0
- app.py +110 -229
__pycache__/app.cpython-313.pyc
CHANGED
|
Binary files a/__pycache__/app.cpython-313.pyc and b/__pycache__/app.cpython-313.pyc differ
|
|
|
app.py
CHANGED
|
@@ -1,261 +1,142 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
from dataclasses import dataclass
|
| 4 |
-
from typing import Dict, Iterable, List, Optional, Tuple
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
-
import
|
| 8 |
|
| 9 |
|
| 10 |
-
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
""
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
"""
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
""
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
payload["filters"] = filters
|
| 71 |
-
|
| 72 |
-
attempts = 0
|
| 73 |
-
while True:
|
| 74 |
-
try:
|
| 75 |
-
raw = self._post("/tools/storage_search", payload)
|
| 76 |
-
hits = []
|
| 77 |
-
for item in raw.get("hits", []):
|
| 78 |
-
hits.append(
|
| 79 |
-
StorageHit(
|
| 80 |
-
file_id=item.get("file_id"),
|
| 81 |
-
file_name=item.get("file_name"),
|
| 82 |
-
chunk_id=item.get("chunk_id"),
|
| 83 |
-
score=item.get("score"),
|
| 84 |
-
snippet=item.get("snippet"),
|
| 85 |
-
)
|
| 86 |
-
)
|
| 87 |
-
return hits
|
| 88 |
-
except ToolCallError:
|
| 89 |
-
attempts += 1
|
| 90 |
-
if attempts > retries:
|
| 91 |
-
raise
|
| 92 |
-
|
| 93 |
-
def storage_get(
|
| 94 |
-
self,
|
| 95 |
-
*,
|
| 96 |
-
chunk_id: Optional[str] = None,
|
| 97 |
-
file_id: Optional[str] = None,
|
| 98 |
-
retries: int = 1,
|
| 99 |
-
) -> Optional[str]:
|
| 100 |
-
"""storage_get エンドポイントからチャンクまたはファイルを取得する。"""
|
| 101 |
-
if not chunk_id and not file_id:
|
| 102 |
-
raise ValueError("Either chunk_id or file_id must be provided.")
|
| 103 |
-
|
| 104 |
-
payload: Dict[str, object] = {}
|
| 105 |
-
if chunk_id:
|
| 106 |
-
payload["chunk_id"] = chunk_id
|
| 107 |
-
if file_id:
|
| 108 |
-
payload["file_id"] = file_id
|
| 109 |
-
|
| 110 |
-
attempts = 0
|
| 111 |
-
while True:
|
| 112 |
-
try:
|
| 113 |
-
raw = self._post("/tools/storage_get", payload)
|
| 114 |
-
content = raw.get("content")
|
| 115 |
-
if isinstance(content, str):
|
| 116 |
-
return content
|
| 117 |
-
return None
|
| 118 |
-
except ToolCallError:
|
| 119 |
-
attempts += 1
|
| 120 |
-
if attempts > retries:
|
| 121 |
-
raise
|
| 122 |
-
def get_vector_store_ids_from_env() -> List[str]:
|
| 123 |
-
"""環境変数 VECTOR_STORE_ID からベクターストアIDのリストを抽出する。"""
|
| 124 |
-
raw = os.getenv("VECTOR_STORE_ID", "").strip()
|
| 125 |
-
if not raw:
|
| 126 |
-
return []
|
| 127 |
-
|
| 128 |
-
ids: List[str] = []
|
| 129 |
-
for token in re.split(r"[,\s]+", raw):
|
| 130 |
-
if not token:
|
| 131 |
-
continue
|
| 132 |
-
if VECTOR_STORE_ID_RE.fullmatch(token) and token not in ids:
|
| 133 |
-
ids.append(token)
|
| 134 |
-
return ids
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def generate_search_queries(question: str) -> List[str]:
|
| 138 |
-
"""自然言語の質問から最大3件の検索クエリを生成する。"""
|
| 139 |
-
normalized = question.strip()
|
| 140 |
-
if not normalized:
|
| 141 |
-
return []
|
| 142 |
-
|
| 143 |
-
queries: List[str] = [normalized]
|
| 144 |
-
|
| 145 |
-
ascii_tokens = re.findall(r"[A-Za-z0-9]+", normalized)
|
| 146 |
-
if ascii_tokens:
|
| 147 |
-
english_query = " ".join(ascii_tokens)
|
| 148 |
-
if english_query and english_query.lower() != normalized.lower():
|
| 149 |
-
queries.append(english_query)
|
| 150 |
-
|
| 151 |
-
japanese_clean = re.sub(r"[、。;;,]", " ", normalized)
|
| 152 |
-
japanese_clean = re.sub(r"\s+", " ", japanese_clean).strip()
|
| 153 |
-
if japanese_clean and japanese_clean not in queries:
|
| 154 |
-
queries.append(japanese_clean)
|
| 155 |
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
-
def deduplicate_hits(hits_by_query: Iterable[Tuple[str, List[StorageHit]]]) -> List[StorageHit]:
|
| 160 |
-
"""クエリごとのヒットを重複除去しながら結合する。"""
|
| 161 |
-
seen_keys = set()
|
| 162 |
-
merged: List[StorageHit] = []
|
| 163 |
-
for _, hits in hits_by_query:
|
| 164 |
-
for hit in hits:
|
| 165 |
-
key = (hit.chunk_id, hit.file_id)
|
| 166 |
-
if key in seen_keys:
|
| 167 |
-
continue
|
| 168 |
-
seen_keys.add(key)
|
| 169 |
-
merged.append(hit)
|
| 170 |
-
return merged
|
| 171 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
|
| 181 |
def produce_answer(question: str, top_k: int) -> str:
|
| 182 |
-
"""
|
| 183 |
question = (question or "").strip()
|
| 184 |
if not question:
|
| 185 |
return "質問が入力されていません。"
|
| 186 |
|
| 187 |
-
api_key = os.getenv("OPENAI_API_KEY")
|
| 188 |
-
if not api_key:
|
| 189 |
-
return "OPENAI_API_KEY が設定されていません。環境変数を確認してください。"
|
| 190 |
-
|
| 191 |
-
client = OpenAIStorageClient(api_key=api_key)
|
| 192 |
-
|
| 193 |
-
vector_store_ids = get_vector_store_ids_from_env()
|
| 194 |
-
if not vector_store_ids:
|
| 195 |
-
return "VECTOR_STORE_ID が設定されていません。環境変数を確認してください。"
|
| 196 |
-
|
| 197 |
-
queries = generate_search_queries(question)
|
| 198 |
-
if not queries:
|
| 199 |
-
return "該当データがありません。"
|
| 200 |
-
|
| 201 |
try:
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
if not hits_by_query:
|
| 210 |
-
return "該当データがありません。"
|
| 211 |
-
|
| 212 |
-
merged_hits = deduplicate_hits(hits_by_query)
|
| 213 |
-
evidence_lines: List[str] = []
|
| 214 |
-
|
| 215 |
-
for hit in merged_hits[:3]:
|
| 216 |
-
content: Optional[str] = None
|
| 217 |
-
try:
|
| 218 |
-
if hit.chunk_id:
|
| 219 |
-
content = client.storage_get(chunk_id=hit.chunk_id)
|
| 220 |
-
if not content and hit.file_id:
|
| 221 |
-
content = client.storage_get(file_id=hit.file_id)
|
| 222 |
-
except ToolCallError:
|
| 223 |
-
# Propagate after exceeding retry budget according to spec.
|
| 224 |
-
return "システムエラーが発生しました。時間をおいて再度お試しください。"
|
| 225 |
-
|
| 226 |
-
source_text = content or hit.snippet
|
| 227 |
-
if not source_text:
|
| 228 |
-
continue
|
| 229 |
-
|
| 230 |
-
excerpt = build_excerpt(source_text)
|
| 231 |
-
if not excerpt:
|
| 232 |
-
continue
|
| 233 |
-
|
| 234 |
-
file_ref = hit.file_name or (hit.file_id or "unknown")
|
| 235 |
-
chunk_ref = hit.chunk_id or "chunk"
|
| 236 |
-
evidence_lines.append(f"- {excerpt} [{file_ref}#{chunk_ref}]")
|
| 237 |
-
|
| 238 |
-
if not evidence_lines:
|
| 239 |
-
return "該当データがありません。"
|
| 240 |
-
|
| 241 |
-
return "\n".join(evidence_lines)
|
| 242 |
-
|
| 243 |
-
except ToolCallError:
|
| 244 |
return "システムエラーが発生しました。時間をおいて再度お試しください。"
|
| 245 |
|
| 246 |
|
| 247 |
def respond(question: str, top_k: int = 5) -> str:
|
| 248 |
-
"""Gradio UI
|
| 249 |
try:
|
| 250 |
-
return produce_answer(question,
|
| 251 |
-
except Exception:
|
| 252 |
return "システムエラーが発生しました。時間をおいて再度お試しください。"
|
| 253 |
|
| 254 |
|
| 255 |
with gr.Blocks() as demo:
|
| 256 |
gr.Markdown(
|
| 257 |
"""
|
| 258 |
-
## MCP Storage
|
|
|
|
|
|
|
| 259 |
"""
|
| 260 |
)
|
| 261 |
|
|
|
|
| 1 |
import os
|
| 2 |
+
from typing import Any, Dict, List, Tuple
|
|
|
|
|
|
|
| 3 |
|
| 4 |
import gradio as gr
|
| 5 |
+
from openai import OpenAI
|
| 6 |
|
| 7 |
|
| 8 |
+
def get_openai_client() -> OpenAI:
|
| 9 |
+
"""OpenAI API クライアントを環境変数から初期化して返す。"""
|
| 10 |
+
api_key = os.getenv("OPENAI_API_KEY", "").strip()
|
| 11 |
+
if not api_key:
|
| 12 |
+
raise RuntimeError("OPENAI_API_KEY が設定されていません。環境変数を確認してください。")
|
| 13 |
+
|
| 14 |
+
base_url = os.getenv("OPENAI_API_BASE", "").strip() or None
|
| 15 |
+
return OpenAI(api_key=api_key, base_url=base_url)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_vector_store_id() -> str:
|
| 19 |
+
"""環境変数 VECTOR_STORE_ID から単一のベクターストアIDを取得する。"""
|
| 20 |
+
value = os.getenv("VECTOR_STORE_ID", "").strip()
|
| 21 |
+
if not value:
|
| 22 |
+
raise RuntimeError("VECTOR_STORE_ID が設定されていません。環境変数を確認してください。")
|
| 23 |
+
return value.split(",")[0].strip()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def extract_citations(response_dict: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 27 |
+
"""Responses API レスポンスから file_search の引用情報を抽出する。"""
|
| 28 |
+
citations: List[Dict[str, Any]] = []
|
| 29 |
+
outputs = response_dict.get("output") or []
|
| 30 |
+
|
| 31 |
+
for output in outputs:
|
| 32 |
+
for content in output.get("content", []) or []:
|
| 33 |
+
annotations = content.get("annotations") or []
|
| 34 |
+
for annotation in annotations:
|
| 35 |
+
file_citation = annotation.get("file_citation")
|
| 36 |
+
if not file_citation:
|
| 37 |
+
continue
|
| 38 |
+
entry = {
|
| 39 |
+
"file_id": file_citation.get("file_id"),
|
| 40 |
+
"file_name": file_citation.get("file_name"),
|
| 41 |
+
"vector_store_id": file_citation.get("vector_store_id"),
|
| 42 |
+
"quote": file_citation.get("quote"),
|
| 43 |
+
}
|
| 44 |
+
if entry not in citations:
|
| 45 |
+
citations.append(entry)
|
| 46 |
+
return citations
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def answer_with_file_search(
|
| 50 |
+
vector_store_id: str,
|
| 51 |
+
query: str,
|
| 52 |
+
top_k: int = 5,
|
| 53 |
+
model: str = "gpt-4o-mini",
|
| 54 |
+
) -> Tuple[str, List[Dict[str, Any]]]:
|
| 55 |
+
"""
|
| 56 |
+
Responses API + file_search ツールを用いて検索と回答を同時に行い、回答と引用を返す。
|
| 57 |
+
|
| 58 |
+
Cookbook の "Integrating search results with LLM in a single API call" を参考に構成。
|
| 59 |
+
"""
|
| 60 |
+
if not query.strip():
|
| 61 |
+
return "", []
|
| 62 |
+
|
| 63 |
+
client = get_openai_client()
|
| 64 |
+
system_prompt = (
|
| 65 |
+
"あなたは取得したドキュメントから根拠が確認できる場合のみ回答するアシスタントです。"
|
| 66 |
+
"根拠が確認できない場合は「該当データがありません。」と答えてください。"
|
| 67 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
user_message = f"{query}\n\n検索結果は最大 {top_k} 件まで引用してください。"
|
| 70 |
+
|
| 71 |
+
response = client.responses.create(
|
| 72 |
+
model=model,
|
| 73 |
+
input=[
|
| 74 |
+
{"role": "system", "content": system_prompt},
|
| 75 |
+
{"role": "user", "content": user_message},
|
| 76 |
+
],
|
| 77 |
+
tools=[
|
| 78 |
+
{
|
| 79 |
+
"type": "file_search",
|
| 80 |
+
"vector_store_ids": [vector_store_id],
|
| 81 |
+
}
|
| 82 |
+
],
|
| 83 |
+
)
|
| 84 |
|
| 85 |
+
response_dict = response.to_dict_recursive() # type: ignore[attr-defined]
|
| 86 |
+
answer_text = response_dict.get("output_text") or ""
|
| 87 |
+
citations = extract_citations(response_dict)
|
| 88 |
+
return answer_text.strip(), citations
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
def format_answer(answer: str, citations: List[Dict[str, Any]]) -> str:
|
| 92 |
+
"""回答文と引用リストを UI 向けのテキストに整形する。"""
|
| 93 |
+
if not answer:
|
| 94 |
+
return "該当データがありません。"
|
| 95 |
|
| 96 |
+
lines = [answer]
|
| 97 |
+
if citations:
|
| 98 |
+
lines.append("")
|
| 99 |
+
lines.append("引用:")
|
| 100 |
+
for citation in citations:
|
| 101 |
+
file_name = citation.get("file_name") or citation.get("file_id") or "unknown"
|
| 102 |
+
quote = citation.get("quote")
|
| 103 |
+
if quote:
|
| 104 |
+
lines.append(f"- {quote} [{file_name}]")
|
| 105 |
+
else:
|
| 106 |
+
lines.append(f"- [{file_name}]")
|
| 107 |
+
return "\n".join(lines)
|
| 108 |
|
| 109 |
|
| 110 |
def produce_answer(question: str, top_k: int) -> str:
|
| 111 |
+
"""Gradio UI からの質問を処理し、Responses API の結果を返す。"""
|
| 112 |
question = (question or "").strip()
|
| 113 |
if not question:
|
| 114 |
return "質問が入力されていません。"
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
try:
|
| 117 |
+
vector_store_id = get_vector_store_id()
|
| 118 |
+
answer, citations = answer_with_file_search(vector_store_id, question, top_k=top_k)
|
| 119 |
+
return format_answer(answer, citations)
|
| 120 |
+
except RuntimeError as runtime_error:
|
| 121 |
+
return str(runtime_error)
|
| 122 |
+
except Exception:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
return "システムエラーが発生しました。時間をおいて再度お試しください。"
|
| 124 |
|
| 125 |
|
| 126 |
def respond(question: str, top_k: int = 5) -> str:
|
| 127 |
+
"""Gradio の UI から呼び出されるハンドラ。"""
|
| 128 |
try:
|
| 129 |
+
return produce_answer(question, int(top_k))
|
| 130 |
+
except Exception:
|
| 131 |
return "システムエラーが発生しました。時間をおいて再度お試しください。"
|
| 132 |
|
| 133 |
|
| 134 |
with gr.Blocks() as demo:
|
| 135 |
gr.Markdown(
|
| 136 |
"""
|
| 137 |
+
## MCP Storage レスポンダ
|
| 138 |
+
OpenAI Responses API の file_search ツールを利用し、指定した Vector Store から根拠付きで回答します。
|
| 139 |
+
OPENAI_API_KEY と VECTOR_STORE_ID を環境変数に設定してからご利用ください。
|
| 140 |
"""
|
| 141 |
)
|
| 142 |
|