Spaces:
Runtime error
Runtime error
Upload 4 files
Browse files- Dockerfile +15 -0
- app.py +290 -0
- merged_total_knowledge_with_consulting (1).csv +0 -0
- requirements.txt +7 -0
Dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONUNBUFFERED=1
|
| 4 |
+
|
| 5 |
+
# 安装基础编译环境(给 faiss/numpy 用),不再装 libatlas-base-dev
|
| 6 |
+
RUN apt-get update && apt-get install -y \
|
| 7 |
+
build-essential \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
WORKDIR /code
|
| 11 |
+
COPY . .
|
| 12 |
+
|
| 13 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
+
|
| 15 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
|
| 7 |
+
import faiss
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from fastapi import FastAPI, Query
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
import gradio as gr
|
| 14 |
+
|
| 15 |
+
# ================== 配置区域 ==================
|
| 16 |
+
|
| 17 |
+
CSV_PATH = "merged_total_knowledge_with_consulting.csv"
|
| 18 |
+
INDEX_PATH = "kb_faiss.index"
|
| 19 |
+
META_PATH = "kb_metadata.jsonl"
|
| 20 |
+
|
| 21 |
+
EMBEDDING_MODEL = "text-embedding-3-large"
|
| 22 |
+
CHAT_MODEL = "gpt-4.1-mini" # 按你账号情况改
|
| 23 |
+
|
| 24 |
+
client = OpenAI() # 从环境变量 OPENAI_API_KEY 读取
|
| 25 |
+
|
| 26 |
+
# =================================================
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def l2_normalize(x: np.ndarray) -> np.ndarray:
|
| 30 |
+
norm = np.linalg.norm(x, axis=1, keepdims=True) + 1e-10
|
| 31 |
+
return x / norm
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_knowledge(csv_path: str) -> pd.DataFrame:
|
| 35 |
+
df = pd.read_csv(csv_path)
|
| 36 |
+
df = df[df["chunk"].notna()].reset_index(drop=True)
|
| 37 |
+
return df
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def embed_texts(texts: List[str]) -> np.ndarray:
|
| 41 |
+
resp = client.embeddings.create(
|
| 42 |
+
model=EMBEDDING_MODEL,
|
| 43 |
+
input=texts,
|
| 44 |
+
)
|
| 45 |
+
vecs = [d.embedding for d in resp.data]
|
| 46 |
+
return np.array(vecs, dtype="float32")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def build_faiss_index(df: pd.DataFrame,
|
| 50 |
+
index_path: str,
|
| 51 |
+
meta_path: str) -> faiss.Index:
|
| 52 |
+
print(f"[INFO] Building FAISS index from CSV: {CSV_PATH}")
|
| 53 |
+
texts = df["chunk"].tolist()
|
| 54 |
+
|
| 55 |
+
embeddings = embed_texts(texts)
|
| 56 |
+
embeddings = l2_normalize(embeddings)
|
| 57 |
+
|
| 58 |
+
dim = embeddings.shape[1]
|
| 59 |
+
index = faiss.IndexFlatIP(dim)
|
| 60 |
+
index.add(embeddings)
|
| 61 |
+
|
| 62 |
+
faiss.write_index(index, index_path)
|
| 63 |
+
print(f"[INFO] FAISS index saved to {index_path}")
|
| 64 |
+
|
| 65 |
+
with open(meta_path, "w", encoding="utf-8") as f:
|
| 66 |
+
for i, row in df.iterrows():
|
| 67 |
+
meta = {
|
| 68 |
+
"id": int(i),
|
| 69 |
+
"Title": row.get("Title", ""),
|
| 70 |
+
"chunk": row.get("chunk", ""),
|
| 71 |
+
"category": row.get("category", ""),
|
| 72 |
+
"tags": row.get("tags", ""),
|
| 73 |
+
"persona": row.get("persona", ""),
|
| 74 |
+
"source": row.get("source", ""),
|
| 75 |
+
"reference": row.get("reference", ""),
|
| 76 |
+
}
|
| 77 |
+
f.write(json.dumps(meta, ensure_ascii=False) + "\n")
|
| 78 |
+
print(f"[INFO] metadata saved to {meta_path}")
|
| 79 |
+
return index
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def load_faiss_index(index_path: str) -> faiss.Index:
|
| 83 |
+
return faiss.read_index(index_path)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_metadata(meta_path: str) -> List[dict]:
|
| 87 |
+
metas = []
|
| 88 |
+
with open(meta_path, "r", encoding="utf-8") as f:
|
| 89 |
+
for line in f:
|
| 90 |
+
metas.append(json.loads(line))
|
| 91 |
+
return metas
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def ensure_index(csv_path=CSV_PATH,
|
| 95 |
+
index_path=INDEX_PATH,
|
| 96 |
+
meta_path=META_PATH):
|
| 97 |
+
idx_exists = Path(index_path).exists()
|
| 98 |
+
meta_exists = Path(meta_path).exists()
|
| 99 |
+
|
| 100 |
+
if idx_exists and meta_exists:
|
| 101 |
+
print("[INFO] Loading existing FAISS index & metadata...")
|
| 102 |
+
index = load_faiss_index(index_path)
|
| 103 |
+
metas = load_metadata(meta_path)
|
| 104 |
+
else:
|
| 105 |
+
print("[INFO] Index or metadata not found, rebuilding...")
|
| 106 |
+
df = load_knowledge(csv_path)
|
| 107 |
+
index = build_faiss_index(df, index_path, meta_path)
|
| 108 |
+
metas = load_metadata(meta_path)
|
| 109 |
+
print(f"[INFO] Loaded {len(metas)} knowledge items.")
|
| 110 |
+
return index, metas
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
index, metas = ensure_index()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def search_knowledge(
|
| 117 |
+
query: str,
|
| 118 |
+
index: faiss.Index,
|
| 119 |
+
metas: List[dict],
|
| 120 |
+
top_k: int = 6,
|
| 121 |
+
category_filter: Optional[str] = None,
|
| 122 |
+
persona_filter: Optional[str] = None,
|
| 123 |
+
) -> List[dict]:
|
| 124 |
+
q_vec = embed_texts([query])
|
| 125 |
+
q_vec = l2_normalize(q_vec)
|
| 126 |
+
scores, idxs = index.search(q_vec, top_k * 3)
|
| 127 |
+
|
| 128 |
+
idxs = idxs[0]
|
| 129 |
+
scores = scores[0]
|
| 130 |
+
|
| 131 |
+
candidates = []
|
| 132 |
+
for i, score in zip(idxs, scores):
|
| 133 |
+
if i == -1:
|
| 134 |
+
continue
|
| 135 |
+
meta = metas[int(i)]
|
| 136 |
+
meta["_score"] = float(score)
|
| 137 |
+
candidates.append(meta)
|
| 138 |
+
|
| 139 |
+
if category_filter:
|
| 140 |
+
candidates = [
|
| 141 |
+
m for m in candidates
|
| 142 |
+
if category_filter in (m.get("category") or "")
|
| 143 |
+
]
|
| 144 |
+
if persona_filter:
|
| 145 |
+
candidates = [
|
| 146 |
+
m for m in candidates
|
| 147 |
+
if persona_filter in (m.get("persona") or "")
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
candidates = sorted(candidates, key=lambda x: x["_score"], reverse=True)[:top_k]
|
| 151 |
+
return candidates
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def build_messages(user_query: str, contexts: List[dict]) -> List[dict]:
|
| 155 |
+
ctx_blocks = []
|
| 156 |
+
for c in contexts:
|
| 157 |
+
block = f"""【标题】{c.get('Title', '')}
|
| 158 |
+
【来源】{c.get('source', '')} | {c.get('reference', '')}
|
| 159 |
+
【类别】{c.get('category', '')}
|
| 160 |
+
【标签】{c.get('tags', '')}
|
| 161 |
+
【内容】{c.get('chunk', '')}
|
| 162 |
+
"""
|
| 163 |
+
ctx_blocks.append(block)
|
| 164 |
+
|
| 165 |
+
context_str = "\n\n------\n\n".join(ctx_blocks)
|
| 166 |
+
|
| 167 |
+
system_prompt = """
|
| 168 |
+
你是一名专注于【快消品行业线下渠道数字化】的行业顾问,
|
| 169 |
+
擅长从门店数据治理、RTM、经销商数字化、品牌-经销商数据协同、
|
| 170 |
+
SFA 执行数字化、费���管理与渠道中台等维度,为品牌方和经销商提供结构化的轻咨询建议。
|
| 171 |
+
|
| 172 |
+
回答要求:
|
| 173 |
+
- 优先基于我提供的“知识库内容(context)”进行回答;
|
| 174 |
+
- 如知识库未直接覆盖,可以补充行业通用经验,但要明确注明“以下为通用经验,非来自知识库”;
|
| 175 |
+
- 回答时请分点说明:背景/判断、建议路径(步骤)、每步要点与业务价值;
|
| 176 |
+
- 用中文回答。
|
| 177 |
+
""".strip()
|
| 178 |
+
|
| 179 |
+
context_prompt = f"""
|
| 180 |
+
下面是与你的问题相关的一组“内部知识库内容”(请先理解这些内容,再用自己的话进行总结与回答):
|
| 181 |
+
|
| 182 |
+
{context_str}
|
| 183 |
+
|
| 184 |
+
请基于这些内容,回答用户的问题。
|
| 185 |
+
""".strip()
|
| 186 |
+
|
| 187 |
+
messages = [
|
| 188 |
+
{"role": "system", "content": system_prompt},
|
| 189 |
+
{"role": "system", "content": context_prompt},
|
| 190 |
+
{"role": "user", "content": user_query},
|
| 191 |
+
]
|
| 192 |
+
return messages
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# ========= 核心 RAG 调用 =========
|
| 196 |
+
|
| 197 |
+
def rag_core(
|
| 198 |
+
query: str,
|
| 199 |
+
category: Optional[str] = None,
|
| 200 |
+
persona: Optional[str] = None,
|
| 201 |
+
top_k: int = 6,
|
| 202 |
+
):
|
| 203 |
+
contexts = search_knowledge(
|
| 204 |
+
query=query,
|
| 205 |
+
index=index,
|
| 206 |
+
metas=metas,
|
| 207 |
+
top_k=top_k,
|
| 208 |
+
category_filter=category,
|
| 209 |
+
persona_filter=persona,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
messages = build_messages(query, contexts)
|
| 213 |
+
|
| 214 |
+
resp = client.chat.completions.create(
|
| 215 |
+
model=CHAT_MODEL,
|
| 216 |
+
messages=messages,
|
| 217 |
+
temperature=0.2,
|
| 218 |
+
)
|
| 219 |
+
answer = resp.choices[0].message.content
|
| 220 |
+
return answer, contexts
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# ========= FastAPI 部分 =========
|
| 224 |
+
|
| 225 |
+
app = FastAPI(
|
| 226 |
+
title="FMCG Channel RAG API",
|
| 227 |
+
description="快消渠道数字化 RAG 行业顾问(FastAPI + FAISS + OpenAI + Gradio)",
|
| 228 |
+
version="0.2.0",
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class RagRequest(BaseModel):
|
| 233 |
+
query: str
|
| 234 |
+
category: Optional[str] = None
|
| 235 |
+
persona: Optional[str] = None
|
| 236 |
+
top_k: int = 6
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class RagResponse(BaseModel):
|
| 240 |
+
answer: str
|
| 241 |
+
contexts: List[dict]
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@app.get("/health")
|
| 245 |
+
def health_check():
|
| 246 |
+
return {"status": "ok", "items": len(metas)}
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@app.post("/rag", response_model=RagResponse)
|
| 250 |
+
def rag_endpoint(body: RagRequest):
|
| 251 |
+
answer, contexts = rag_core(
|
| 252 |
+
query=body.query,
|
| 253 |
+
category=body.category,
|
| 254 |
+
persona=body.persona,
|
| 255 |
+
top_k=body.top_k,
|
| 256 |
+
)
|
| 257 |
+
return RagResponse(answer=answer, contexts=contexts)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@app.get("/rag", response_model=RagResponse)
|
| 261 |
+
def rag_get(
|
| 262 |
+
query: str = Query(..., description="用户问题"),
|
| 263 |
+
category: Optional[str] = Query(None, description="可选:按类别过滤,如 '门店数据治理'"),
|
| 264 |
+
persona: Optional[str] = Query(None, description="可选:按角色过滤,如 '数字化负责人'"),
|
| 265 |
+
top_k: int = Query(6, ge=1, le=20, description="召回的知识条目数"),
|
| 266 |
+
):
|
| 267 |
+
answer, contexts = rag_core(
|
| 268 |
+
query=query,
|
| 269 |
+
category=category,
|
| 270 |
+
persona=persona,
|
| 271 |
+
top_k=top_k,
|
| 272 |
+
)
|
| 273 |
+
return RagResponse(answer=answer, contexts=contexts)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ========= Gradio 聊天前端 =========
|
| 277 |
+
|
| 278 |
+
def gradio_chat_fn(message, history):
|
| 279 |
+
answer, _ = rag_core(query=message, category=None, persona=None, top_k=6)
|
| 280 |
+
return answer
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
demo = gr.ChatInterface(
|
| 284 |
+
fn=gradio_chat_fn,
|
| 285 |
+
title="快消渠道数字化智能顾问",
|
| 286 |
+
description="基于快消线下渠道数字化知识库的 RAG 顾问,你可以问:门店数据治理、RTM、经销商协同、SFA 执行等问题。",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# 把 Gradio 挂到 FastAPI 根路径 "/"
|
| 290 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
merged_total_knowledge_with_consulting (1).csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
pandas
|
| 4 |
+
numpy
|
| 5 |
+
faiss-cpu
|
| 6 |
+
openai
|
| 7 |
+
gradio
|