Corin1998 commited on
Commit
3255054
·
verified ·
1 Parent(s): c699f80

Upload 8 files

Browse files
Files changed (8) hide show
  1. IR:ESG_RAGBot +28 -0
  2. README.md +24 -5
  3. app.py +250 -0
  4. config.yaml +36 -0
  5. guardrails.py +32 -0
  6. ingest.py +86 -0
  7. openai_client.py +27 -0
  8. requirements.txt +14 -0
IR:ESG_RAGBot ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile — Hugging Face Spaces (SDK: docker)
2
+ FROM python:3.10-slim
3
+
4
+ ENV PYTHONDONTWRITEBYTECODE=1 \
5
+ PYTHONUNBUFFERED=1 \
6
+ PIP_NO_CACHE_DIR=1 \
7
+ PORT=7860 \
8
+ UVICORN_WORKERS=1
9
+
10
+ WORKDIR /app
11
+
12
+ # OS依存(必要に応じて追加)
13
+ RUN apt-get update && apt-get install -y --no-install-recommends \
14
+ build-essential \
15
+ && rm -rf /var/lib/apt/lists/*
16
+
17
+ # 依存インストール
18
+ COPY requirements.txt /app/requirements.txt
19
+ RUN pip install --upgrade pip && pip install -r requirements.txt
20
+
21
+ # アプリケーション
22
+ COPY . /app
23
+
24
+ # データディレクトリ
25
+ RUN mkdir -p /app/data/pdf /app/data/index
26
+
27
+ # Spaces は $PORT を渡す; それにバインドして起動
28
+ CMD ["sh", "-c", "uvicorn app:app --host 0.0.0.0 --port ${PORT}"]
README.md CHANGED
@@ -1,10 +1,29 @@
1
  ---
2
- title: ESG IR RAGbot
3
- emoji: 🚀
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: IR・ESG RAG Bot (OpenAI, 8 languages) — Docker
3
+ emoji: 📊
4
+ colorFrom: yellow
5
+ colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # IR・ESG RAG Bot(Docker / FastAPI + Gradio)
12
+
13
+ - UI: `/`(Gradio)
14
+ - API: `POST /api/answer`(JSON: `{ "question":"...", "lang":"ja" }`)
15
+ - Rebuild Index: `POST /api/rebuild`(ingest.py 実行)
16
+ - Health: `GET /health`
17
+
18
+ ## 使い方(Spaces)
19
+ 1. このリポジトリをアップロード(このREADMEを含む)
20
+ 2. **Settings → Secrets** に `OPENAI_API_KEY` を登録
21
+ 3. `data/pdf/` にPDFを追加(UIからはアップロードしません)
22
+ 4. Space を再ビルド
23
+ 5. UIで「インデックス再構築」 or `POST /api/rebuild` を叩く → 質問
24
+
25
+ ## ローカル起動(任意)
26
+ ```bash
27
+ docker build -t ir-esg-rag .
28
+ docker run -e OPENAI_API_KEY=sk-... -p 7860:7860 -v $(pwd)/data:/app/data ir-esg-rag
29
+ # ブラウザ: http://localhost:7860
app.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py — FastAPI + Gradio (mounted at "/") for Hugging Face Spaces (Docker SDK)
2
+ from __future__ import annotations
3
+ import os, json, yaml, subprocess, sys, pathlib, traceback
4
+ from typing import List, Dict, Tuple
5
+
6
+ from fastapi import FastAPI, Body
7
+ from fastapi.responses import JSONResponse
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+
10
+ import gradio as gr
11
+
12
+ # =========================
13
+ # Config (failsafe loading)
14
+ # =========================
15
+ DEFAULT_CFG = {
16
+ "app_name": "IR/ESG RAG Bot (OpenAI, 8 languages)",
17
+ "embedding_model": "text-embedding-3-large",
18
+ "normalize_embeddings": True,
19
+ "chunk": {"target_chars": 1400, "overlap_chars": 180},
20
+ "retrieval": {"top_k": 6, "score_threshold": 0.15, "mmr_lambda": 0.3},
21
+ "llm": {
22
+ "model": "gpt-4o-mini",
23
+ "max_output_tokens": 700,
24
+ "temperature": 0.2,
25
+ "system_prompt": (
26
+ "あなたは上場企業のIR・ESG開示に特化したRAGアシスタントです。"
27
+ "回答は常に根拠(文書名・ページ)を箇条書きで示し、文書外の推測や断定は避けます。"
28
+ "数値は年度と単位を明記し、最新年度を優先してください。"
29
+ ),
30
+ },
31
+ "languages": {
32
+ "preferred": ["ja", "en", "zh", "ko", "fr", "de", "es", "it"],
33
+ "labels": {
34
+ "ja": "日本語", "en": "English", "zh": "中文", "ko": "한국어",
35
+ "fr": "Français", "de": "Deutsch", "es": "Español", "it": "Italiano"
36
+ },
37
+ },
38
+ }
39
+ CFG_ERR = None
40
+ CFG_PATH = "config.yaml"
41
+ try:
42
+ if os.path.exists(CFG_PATH):
43
+ with open(CFG_PATH, encoding="utf-8") as f:
44
+ CFG = yaml.safe_load(f) or {}
45
+ def _merge(dst, src):
46
+ for k, v in src.items():
47
+ if k not in dst:
48
+ dst[k] = v
49
+ _merge(CFG, DEFAULT_CFG)
50
+ for sec in ("chunk", "retrieval", "llm", "languages"):
51
+ if sec in DEFAULT_CFG:
52
+ if sec not in CFG or not isinstance(CFG[sec], dict):
53
+ CFG[sec] = DEFAULT_CFG[sec]
54
+ else:
55
+ _merge(CFG[sec], DEFAULT_CFG[sec])
56
+ else:
57
+ CFG = DEFAULT_CFG
58
+ CFG_ERR = "config.yaml が見つかりません。デフォルト設定で起動しました。"
59
+ except Exception as e:
60
+ CFG = DEFAULT_CFG
61
+ CFG_ERR = "config.yaml 読み込みエラー: " + str(e)
62
+
63
+ # =========================
64
+ # Paths / Lazy imports
65
+ # =========================
66
+ INDEX_PATH = pathlib.Path("data/index/faiss.index")
67
+ META_PATH = pathlib.Path("data/index/meta.jsonl")
68
+
69
+ def _lazy_imports():
70
+ """遅延インポート(初期化安定化)"""
71
+ global faiss, np, embed_texts, chat, detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT
72
+ import faiss
73
+ import numpy as np
74
+ from openai_client import embed_texts, chat
75
+ from guardrails import detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT
76
+ return faiss, np, embed_texts, chat, detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT
77
+
78
+ def _index_exists() -> bool:
79
+ return INDEX_PATH.exists() and META_PATH.exists()
80
+
81
+ def _check_api_key() -> bool:
82
+ return bool(os.getenv("OPENAI_API_KEY"))
83
+
84
+ # =========================
85
+ # Retrieval helpers
86
+ # =========================
87
+ _INDEX = None
88
+ _METAS = None
89
+
90
+ def _ensure_index_loaded():
91
+ global _INDEX, _METAS
92
+ if _INDEX is not None and _METAS is not None:
93
+ return
94
+ if not _index_exists():
95
+ raise RuntimeError("index_not_ready")
96
+ faiss, *_ = _lazy_imports()
97
+ _INDEX = faiss.read_index(str(INDEX_PATH))
98
+ _METAS = [json.loads(l) for l in open(META_PATH, encoding="utf-8")]
99
+
100
+ def _embed_query(q: str):
101
+ _, np, embed_texts, *_ = _lazy_imports()
102
+ v = np.array(embed_texts([q], CFG["embedding_model"])[0], dtype="float32")
103
+ v = v / (np.linalg.norm(v) + 1e-12)
104
+ return v[None, :]
105
+
106
+ def _search(q: str):
107
+ faiss, np, *_ = _lazy_imports()
108
+ _ensure_index_loaded()
109
+ TOP_K = CFG["retrieval"]["top_k"]
110
+ SCORETH = CFG["retrieval"]["score_threshold"]
111
+ qv = _embed_query(q)
112
+ sims, idxs = _INDEX.search(qv, TOP_K * 4)
113
+ sims, idxs = sims[0], idxs[0]
114
+ picked, seen = [], set()
115
+ for score, idx in zip(sims, idxs):
116
+ if score < SCORETH:
117
+ continue
118
+ c = _METAS[idx]
119
+ key = (c["source"], c["page"])
120
+ if key in seen:
121
+ continue
122
+ seen.add(key)
123
+ picked.append({**c, "score": float(score)})
124
+ if len(picked) >= TOP_K:
125
+ break
126
+ return picked
127
+
128
+ def _format_context(chunks: List[Dict]) -> str:
129
+ lines = []
130
+ for c in chunks:
131
+ snippet = c["text"][:180].replace("\n", " ")
132
+ lines.append(f"- 出典: {c['source']} p.{c['page']} | 抜粋: {snippet}…")
133
+ return "\n".join(lines)
134
+
135
+ _LANG_INSTRUCTIONS = {
136
+ "ja": "回答は日本語で出力してください。",
137
+ "en": "Answer in English.",
138
+ "zh": "请用中文回答。",
139
+ "ko": "한국어로 답변하세요.",
140
+ "fr": "Répondez en français.",
141
+ "de": "Bitte auf Deutsch antworten.",
142
+ "es": "Responde en español.",
143
+ "it": "Rispondi in italiano.",
144
+ }
145
+
146
+ def generate_answer(q: str, lang: str = "ja") -> Tuple[str, Dict]:
147
+ q = (q or "").strip()
148
+ if not q:
149
+ return "質問を入力してください。", {}
150
+ try:
151
+ _, _, _, chat, detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT = _lazy_imports()
152
+ if detect_out_of_scope(q):
153
+ return f"{SCOPE_HINT}\nIR/ESG関連の事項についてお尋ねください。", {}
154
+ chunks = _search(q)
155
+ context = _format_context(chunks)
156
+ lang_note = _LANG_INSTRUCTIONS.get(lang, "Answer in the user's language.")
157
+ user_prompt = (
158
+ "以下のコンテキストのみを根拠に、簡潔かつ正確に回答してください。\n"
159
+ "必ず箇条書きで根拠(文書名とページ)を列挙してください。\n"
160
+ f"{lang_note}\n\n[コンテキスト]\n{context}\n\n[質問]\n{q}"
161
+ )
162
+ messages = [
163
+ {"role": "system", "content": CFG["llm"]["system_prompt"]},
164
+ {"role": "user", "content": user_prompt},
165
+ ]
166
+ text = chat(
167
+ messages,
168
+ model=CFG["llm"]["model"],
169
+ max_output_tokens=CFG["llm"]["max_output_tokens"],
170
+ temperature=CFG["llm"]["temperature"],
171
+ )
172
+ text = sanitize(text) + "\n\n" + compliance_block()
173
+ meta = {"citations": [{"source": c["source"], "page": c["page"], "score": round(c["score"], 3)} for c in chunks]}
174
+ return text, meta
175
+ except RuntimeError as e:
176
+ if str(e) == "index_not_ready":
177
+ return ("⚠️ インデックスがまだありません。\n"
178
+ "1) data/pdf/ にPDFを置く\n"
179
+ "2) 『インデックス再構築』ボタンまたは /api/rebuild を実行(OpenAI APIキー必須)\n"), {}
180
+ raise
181
+ except Exception as e:
182
+ return "❌ 実行時エラー: " + str(e) + "\n" + traceback.format_exc()[-1200:], {}
183
+
184
+ def rebuild_index() -> str:
185
+ if not _check_api_key():
186
+ return "OPENAI_API_KEY が未設定です。コンソール / Secrets に登録してください。"
187
+ pdf_dir = pathlib.Path("data/pdf")
188
+ pdf_dir.mkdir(parents=True, exist_ok=True)
189
+ if not list(pdf_dir.glob("*.pdf")):
190
+ return "data/pdf/ にPDFがありません。PDFを置いて再実行してください。"
191
+ try:
192
+ out = subprocess.run([sys.executable, "ingest.py"], capture_output=True, text=True, check=True)
193
+ # キャッシュ破棄
194
+ global _INDEX, _METAS
195
+ _INDEX = None
196
+ _METAS = None
197
+ return "✅ インデックス生成完了\n```\n" + (out.stdout[-1200:] or "") + "\n```"
198
+ except subprocess.CalledProcessError as e:
199
+ return f"❌ インデックス生成に失敗\nstdout:\n{e.stdout}\n\nstderr:\n{e.stderr}"
200
+ except Exception as e:
201
+ return "❌ 予期せぬエラー: " + str(e) + "\n" + traceback.format_exc()[-1200:]
202
+
203
+ # =========================
204
+ # FastAPI (ASGI)
205
+ # =========================
206
+ app = FastAPI(title=CFG.get("app_name", "RAG Bot"))
207
+ app.add_middleware(
208
+ CORSMiddleware,
209
+ allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"],
210
+ )
211
+
212
+ @app.get("/health")
213
+ def health():
214
+ return {"status": "ok"}
215
+
216
+ @app.post("/api/answer")
217
+ def api_answer(payload: Dict = Body(...)):
218
+ text, meta = generate_answer(payload.get("question", ""), payload.get("lang", "ja"))
219
+ return JSONResponse({"text": text, **meta})
220
+
221
+ @app.post("/api/rebuild")
222
+ def api_rebuild():
223
+ msg = rebuild_index()
224
+ return JSONResponse({"message": msg})
225
+
226
+ # =========================
227
+ # Gradio UI (mounted at "/")
228
+ # =========================
229
+ LANGS = CFG["languages"]["preferred"]
230
+ LABELS = CFG["languages"].get("labels", {l: l for l in LANGS})
231
+
232
+ with gr.Blocks(fill_height=True, title=CFG.get("app_name", "RAG Bot")) as demo:
233
+ gr.Markdown("# IR・ESG開示RAG(OpenAI API)— 8言語対応")
234
+ if CFG_ERR:
235
+ gr.Markdown(f"**構成警告**: {CFG_ERR}")
236
+ with gr.Row():
237
+ q = gr.Textbox(label="質問 / Question", lines=3, placeholder="例: 2024年度のGHG排出量(スコープ1-3)は?")
238
+ with gr.Row():
239
+ lang = gr.Dropdown(choices=LANGS, value=LANGS[0], label="回答言語 / Output language")
240
+ with gr.Row():
241
+ ask = gr.Button("回答する / Answer", variant="primary")
242
+ rebuild = gr.Button("インデックス再構築(ingest.py 実行)")
243
+ ans = gr.Markdown()
244
+ cites = gr.JSON(label="根拠メタデータ / Citations")
245
+ log = gr.Markdown()
246
+ ask.click(fn=generate_answer, inputs=[q, lang], outputs=[ans, cites])
247
+ rebuild.click(fn=rebuild_index, outputs=[log])
248
+
249
+ from gradio.routes import mount_gradio_app
250
+ mount_gradio_app(app, demo, path="/")
config.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ app_name: "IR/ESG RAG Bot (OpenAI, 8 languages)"
2
+ embedding_model: "text-embedding-3-large"
3
+ normalize_embeddings: true
4
+
5
+ chunk:
6
+ target_chars: 1400
7
+ overlap_chars: 180
8
+
9
+ retrieval:
10
+ top_k: 6
11
+ score_threshold: 0.15
12
+ mmr_lambda: 0.3
13
+
14
+ llm:
15
+ model: "gpt-4o-mini"
16
+ max_output_tokens: 700
17
+ temperature: 0.2
18
+ system_prompt: |-
19
+ あなたは上場企業のIR・ESG開示に特化したRAGアシスタントです。回答は常に根拠(文書名・ページ)を箇条書きで示し、
20
+ 文書外の推測や断定は避けます。数値は年度と単位を明記し、最新年度を優先してください。
21
+
22
+ languages:
23
+ preferred: [ja, en, zh, ko, fr, de, es, it]
24
+ labels:
25
+ ja: "日本語"
26
+ en: "English"
27
+ zh: "中文"
28
+ ko: "한국어"
29
+ fr: "Français"
30
+ de: "Deutsch"
31
+ es: "Español"
32
+ it: "Italiano"
33
+
34
+ logging:
35
+ save_qa: true
36
+ path: "logs/qa_log.jsonl"
guardrails.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import re
3
+
4
+ ALLOWED_TOPICS = [
5
+ r"IR", r"投資家", r"決算", r"財務", r"ガバナンス", r"統合報告", r"サステナビリティ",
6
+ r"人的資本", r"リスク", r"セグメント", r"株主", r"資本政策", r"ESG", r"GHG",
7
+ ]
8
+ OUT_OF_SCOPE_PATTERNS = [r"採用の可否", r"未公開情報", r"株価予想", r"インサイダー", r"個人情報"]
9
+
10
+ # 簡易PIIマスク(郵便・電話・メール)
11
+ PII = re.compile(
12
+ r"(\d{3}-\d{4})" # 郵便番号
13
+ r"|(\d{2,4}-\d{2,4}-\d{3,4})" # 電話番号
14
+ r"|([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+)" # メール
15
+ )
16
+
17
+ SCOPE_HINT = (
18
+ "このボットはIR/ESG開示文書(統合報告書、サステナ、決算短信、コーポガバ報告)を根拠とするQ&A専用です。"
19
+ )
20
+
21
+ def detect_out_of_scope(q: str) -> bool:
22
+ if any(re.search(p, q) for p in OUT_OF_SCOPE_PATTERNS):
23
+ return True
24
+ if not any(re.search(p, q) for p in ALLOWED_TOPICS):
25
+ return True
26
+ return False
27
+
28
+ def sanitize(text: str) -> str:
29
+ return PII.sub("[REDACTED]", text)
30
+
31
+ def compliance_block() -> str:
32
+ return "※免責:本回答は公開済みIR/ESG資料に基づく情報提供であり、投資判断を目的としません。"
ingest.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json, pathlib
3
+ from typing import List, Dict, Tuple
4
+
5
+ import numpy as np
6
+ import faiss
7
+ from pypdf import PdfReader
8
+ import yaml
9
+
10
+ from openai_client import embed_texts
11
+ from guardrails import sanitize
12
+
13
+ CFG = yaml.safe_load(open("config.yaml", encoding="utf-8"))
14
+ EMB_MODEL = CFG["embedding_model"]
15
+ NORMALIZE = CFG.get("normalize_embeddings", True)
16
+
17
+ DATA_DIR = pathlib.Path("data")
18
+ PDF_DIR = DATA_DIR / "pdf"
19
+ INDEX_DIR = DATA_DIR / "index"
20
+ META_PATH = INDEX_DIR / "meta.jsonl" # app.py と一致
21
+ INDEX_PATH = INDEX_DIR / "faiss.index"
22
+
23
+ def read_pdf_with_pages(path: str) -> List[Tuple[int, str]]:
24
+ pages: List[Tuple[int, str]] = []
25
+ reader = PdfReader(path)
26
+ for i, p in enumerate(reader.pages):
27
+ txt = p.extract_text() or ""
28
+ txt = "\n".join(line.strip() for line in txt.splitlines() if line.strip())
29
+ pages.append((i + 1, txt))
30
+ return pages
31
+
32
+ def split_chunks(pages: List[Tuple[int, str]], target_chars: int, overlap_chars: int) -> List[Dict]:
33
+ chunks: List[Dict] = []
34
+ for page, text in pages:
35
+ if not text:
36
+ continue
37
+ start = 0
38
+ while start < len(text):
39
+ end = min(len(text), start + target_chars)
40
+ chunk = text[start:end]
41
+ if len(chunk.strip()) >= 50:
42
+ chunks.append({"page": page, "text": chunk})
43
+ start = end - overlap_chars if end - overlap_chars > 0 else end
44
+ return chunks
45
+
46
+ def l2_normalize(m: np.ndarray) -> np.ndarray:
47
+ if not NORMALIZE:
48
+ return m
49
+ norms = np.linalg.norm(m, axis=1, keepdims=True) + 1e-12
50
+ return m / norms
51
+
52
+ def build_index():
53
+ INDEX_DIR.mkdir(parents=True, exist_ok=True)
54
+ meta_f = open(META_PATH, "w", encoding="utf-8")
55
+
56
+ target_chars = CFG["chunk"]["target_chars"]
57
+ overlap_chars = CFG["chunk"]["overlap_chars"]
58
+
59
+ texts: List[str] = []
60
+ for pdf in sorted(PDF_DIR.glob("*.pdf")):
61
+ print(f"Processing {pdf.name}...")
62
+ pages = read_pdf_with_pages(str(pdf))
63
+ chunks = split_chunks(pages, target_chars, overlap_chars)
64
+ for c in chunks:
65
+ t = c["text"][:1800]
66
+ texts.append(t)
67
+ meta = {"source": pdf.name, "page": c["page"], "text": sanitize(t)}
68
+ meta_f.write(json.dumps(meta, ensure_ascii=False) + "\n")
69
+
70
+ meta_f.close()
71
+
72
+ if not texts:
73
+ raise SystemExit("Put PDFs under data/pdf/")
74
+
75
+ vecs = embed_texts(texts, EMB_MODEL)
76
+ mat = np.array(vecs, dtype="float32")
77
+ mat = l2_normalize(mat)
78
+
79
+ # コサイン類似(正規化済みベクトル × 内積)
80
+ index = faiss.IndexFlatIP(mat.shape[1])
81
+ index.add(mat)
82
+ faiss.write_index(index, str(INDEX_PATH))
83
+ print(f"Index {len(texts)} chunks → {INDEX_PATH}")
84
+
85
+ if __name__ == "__main__":
86
+ build_index()
openai_client.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import List, Dict
3
+ from openai import OpenAI
4
+
5
+ _client = None
6
+
7
+ def client() -> OpenAI:
8
+ global _client
9
+ if _client is None:
10
+ # OPENAI_API_KEY / OPENAI_BASE_URL は環境変数から取得
11
+ _client = OpenAI()
12
+ return _client
13
+
14
+ # Embeddings
15
+ def embed_texts(texts: List[str], model: str) -> List[List[float]]:
16
+ resp = client().embeddings.create(model=model, input=texts)
17
+ return [d.embedding for d in resp.data]
18
+
19
+ # Responses API
20
+ def chat(messages: List[Dict], model: str, max_output_tokens: int = 700, temperature: float = 0.2) -> str:
21
+ resp = client().responses.create(
22
+ model=model,
23
+ input=messages,
24
+ max_output_tokens=max_output_tokens,
25
+ temperature=temperature,
26
+ )
27
+ return resp.output_text
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ---
3
+
4
+ ## 3) `requirements.txt`
5
+ ```txt
6
+ fastapi==0.112.0
7
+ uvicorn[standard]==0.30.5
8
+ gradio==4.44.1
9
+ openai>=1.40.0
10
+ faiss-cpu==1.8.0.post1
11
+ pypdf==4.2.0
12
+ PyYAML==6.0.2
13
+ httpx==0.27.0
14
+ pydantic==2.8.2