Spaces:
Runtime error
Runtime error
Download app.py from datapartage/fmcg_bot: direct link, hf CLI and curl.
- Browser
- Download file 8.38 kB
-
https://huggingface.co/spaces/datapartage/fmcg_bot/resolve/main/app.py
- Command line
-
hf download hf://spaces/datapartage/fmcg_bot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/datapartage/fmcg_bot/resolve/main/app.py
8.38 kB
| # app.py | |
| import os | |
| import json | |
| from pathlib import Path | |
| from typing import List, Optional | |
| import faiss | |
| import numpy as np | |
| import pandas as pd | |
| from fastapi import FastAPI, Query | |
| from pydantic import BaseModel | |
| from openai import OpenAI | |
| import gradio as gr | |
| # ================== 配置区域 ================== | |
| CSV_PATH = "merged_total_knowledge_with_consulting.csv" | |
| INDEX_PATH = "kb_faiss.index" | |
| META_PATH = "kb_metadata.jsonl" | |
| EMBEDDING_MODEL = "text-embedding-3-large" | |
| CHAT_MODEL = "gpt-4.1-mini" # 按你账号情况改 | |
| client = OpenAI() # 从环境变量 OPENAI_API_KEY 读取 | |
| # ================================================= | |
| def l2_normalize(x: np.ndarray) -> np.ndarray: | |
| norm = np.linalg.norm(x, axis=1, keepdims=True) + 1e-10 | |
| return x / norm | |
| def load_knowledge(csv_path: str) -> pd.DataFrame: | |
| df = pd.read_csv(csv_path) | |
| df = df[df["chunk"].notna()].reset_index(drop=True) | |
| return df | |
| def embed_texts(texts: List[str]) -> np.ndarray: | |
| resp = client.embeddings.create( | |
| model=EMBEDDING_MODEL, | |
| input=texts, | |
| ) | |
| vecs = [d.embedding for d in resp.data] | |
| return np.array(vecs, dtype="float32") | |
| def build_faiss_index(df: pd.DataFrame, | |
| index_path: str, | |
| meta_path: str) -> faiss.Index: | |
| print(f"[INFO] Building FAISS index from CSV: {CSV_PATH}") | |
| texts = df["chunk"].tolist() | |
| embeddings = embed_texts(texts) | |
| embeddings = l2_normalize(embeddings) | |
| dim = embeddings.shape[1] | |
| index = faiss.IndexFlatIP(dim) | |
| index.add(embeddings) | |
| faiss.write_index(index, index_path) | |
| print(f"[INFO] FAISS index saved to {index_path}") | |
| with open(meta_path, "w", encoding="utf-8") as f: | |
| for i, row in df.iterrows(): | |
| meta = { | |
| "id": int(i), | |
| "Title": row.get("Title", ""), | |
| "chunk": row.get("chunk", ""), | |
| "category": row.get("category", ""), | |
| "tags": row.get("tags", ""), | |
| "persona": row.get("persona", ""), | |
| "source": row.get("source", ""), | |
| "reference": row.get("reference", ""), | |
| } | |
| f.write(json.dumps(meta, ensure_ascii=False) + "\n") | |
| print(f"[INFO] metadata saved to {meta_path}") | |
| return index | |
| def load_faiss_index(index_path: str) -> faiss.Index: | |
| return faiss.read_index(index_path) | |
| def load_metadata(meta_path: str) -> List[dict]: | |
| metas = [] | |
| with open(meta_path, "r", encoding="utf-8") as f: | |
| for line in f: | |
| metas.append(json.loads(line)) | |
| return metas | |
| def ensure_index(csv_path=CSV_PATH, | |
| index_path=INDEX_PATH, | |
| meta_path=META_PATH): | |
| idx_exists = Path(index_path).exists() | |
| meta_exists = Path(meta_path).exists() | |
| if idx_exists and meta_exists: | |
| print("[INFO] Loading existing FAISS index & metadata...") | |
| index = load_faiss_index(index_path) | |
| metas = load_metadata(meta_path) | |
| else: | |
| print("[INFO] Index or metadata not found, rebuilding...") | |
| df = load_knowledge(csv_path) | |
| index = build_faiss_index(df, index_path, meta_path) | |
| metas = load_metadata(meta_path) | |
| print(f"[INFO] Loaded {len(metas)} knowledge items.") | |
| return index, metas | |
| index, metas = ensure_index() | |
| def search_knowledge( | |
| query: str, | |
| index: faiss.Index, | |
| metas: List[dict], | |
| top_k: int = 6, | |
| category_filter: Optional[str] = None, | |
| persona_filter: Optional[str] = None, | |
| ) -> List[dict]: | |
| q_vec = embed_texts([query]) | |
| q_vec = l2_normalize(q_vec) | |
| scores, idxs = index.search(q_vec, top_k * 3) | |
| idxs = idxs[0] | |
| scores = scores[0] | |
| candidates = [] | |
| for i, score in zip(idxs, scores): | |
| if i == -1: | |
| continue | |
| meta = metas[int(i)] | |
| meta["_score"] = float(score) | |
| candidates.append(meta) | |
| if category_filter: | |
| candidates = [ | |
| m for m in candidates | |
| if category_filter in (m.get("category") or "") | |
| ] | |
| if persona_filter: | |
| candidates = [ | |
| m for m in candidates | |
| if persona_filter in (m.get("persona") or "") | |
| ] | |
| candidates = sorted(candidates, key=lambda x: x["_score"], reverse=True)[:top_k] | |
| return candidates | |
| def build_messages(user_query: str, contexts: List[dict]) -> List[dict]: | |
| ctx_blocks = [] | |
| for c in contexts: | |
| block = f"""【标题】{c.get('Title', '')} | |
| 【来源】{c.get('source', '')} | {c.get('reference', '')} | |
| 【类别】{c.get('category', '')} | |
| 【标签】{c.get('tags', '')} | |
| 【内容】{c.get('chunk', '')} | |
| """ | |
| ctx_blocks.append(block) | |
| context_str = "\n\n------\n\n".join(ctx_blocks) | |
| system_prompt = """ | |
| 你是一名专注于【快消品行业线下渠道数字化】的行业顾问, | |
| 擅长从门店数据治理、RTM、经销商数字化、品牌-经销商数据协同、 | |
| SFA 执行数字化、费用管理与渠道中台等维度,为品牌方和经销商提供结构化的轻咨询建议。 | |
| 回答要求: | |
| - 优先基于我提供的“知识库内容(context)”进行回答; | |
| - 如知识库未直接覆盖,可以补充行业通用经验,但要明确注明“以下为通用经验,非来自知识库”; | |
| - 回答时请分点说明:背景/判断、建议路径(步骤)、每步要点与业务价值; | |
| - 用中文回答。 | |
| """.strip() | |
| context_prompt = f""" | |
| 下面是与你的问题相关的一组“内部知识库内容”(请先理解这些内容,再用自己的话进行总结与回答): | |
| {context_str} | |
| 请基于这些内容,回答用户的问题。 | |
| """.strip() | |
| messages = [ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "system", "content": context_prompt}, | |
| {"role": "user", "content": user_query}, | |
| ] | |
| return messages | |
| # ========= 核心 RAG 调用 ========= | |
| def rag_core( | |
| query: str, | |
| category: Optional[str] = None, | |
| persona: Optional[str] = None, | |
| top_k: int = 6, | |
| ): | |
| contexts = search_knowledge( | |
| query=query, | |
| index=index, | |
| metas=metas, | |
| top_k=top_k, | |
| category_filter=category, | |
| persona_filter=persona, | |
| ) | |
| messages = build_messages(query, contexts) | |
| resp = client.chat.completions.create( | |
| model=CHAT_MODEL, | |
| messages=messages, | |
| temperature=0.2, | |
| ) | |
| answer = resp.choices[0].message.content | |
| return answer, contexts | |
| # ========= FastAPI 部分 ========= | |
| app = FastAPI( | |
| title="FMCG Channel RAG API", | |
| description="快消渠道数字化 RAG 行业顾问(FastAPI + FAISS + OpenAI + Gradio)", | |
| version="0.2.0", | |
| ) | |
| class RagRequest(BaseModel): | |
| query: str | |
| category: Optional[str] = None | |
| persona: Optional[str] = None | |
| top_k: int = 6 | |
| class RagResponse(BaseModel): | |
| answer: str | |
| contexts: List[dict] | |
| def health_check(): | |
| return {"status": "ok", "items": len(metas)} | |
| def rag_endpoint(body: RagRequest): | |
| answer, contexts = rag_core( | |
| query=body.query, | |
| category=body.category, | |
| persona=body.persona, | |
| top_k=body.top_k, | |
| ) | |
| return RagResponse(answer=answer, contexts=contexts) | |
| def rag_get( | |
| query: str = Query(..., description="用户问题"), | |
| category: Optional[str] = Query(None, description="可选:按类别过滤,如 '门店数据治理'"), | |
| persona: Optional[str] = Query(None, description="可选:按角色过滤,如 '数字化负责人'"), | |
| top_k: int = Query(6, ge=1, le=20, description="召回的知识条目数"), | |
| ): | |
| answer, contexts = rag_core( | |
| query=query, | |
| category=category, | |
| persona=persona, | |
| top_k=top_k, | |
| ) | |
| return RagResponse(answer=answer, contexts=contexts) | |
| # ========= Gradio 聊天前端 ========= | |
| def gradio_chat_fn(message, history): | |
| answer, _ = rag_core(query=message, category=None, persona=None, top_k=6) | |
| return answer | |
| demo = gr.ChatInterface( | |
| fn=gradio_chat_fn, | |
| title="快消渠道数字化智能顾问", | |
| description="基于快消线下渠道数字化知识库的 RAG 顾问,你可以问:门店数据治理、RTM、经销商协同、SFA 执行等问题。", | |
| ) | |
| # 把 Gradio 挂到 FastAPI 根路径 "/" | |
| app = gr.mount_gradio_app(app, demo, path="/") | |