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 4 |
+
import torch
|
| 5 |
+
import csv
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from huggingface_hub import HfApi
|
| 8 |
+
from openai import OpenAI
|
| 9 |
+
from langchain.vectorstores import FAISS
|
| 10 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 11 |
+
|
| 12 |
+
# === 1. 初始化 API 和模型 ===
|
| 13 |
+
|
| 14 |
+
client = OpenAI(
|
| 15 |
+
api_key=os.getenv("DEEPSEEK_KEY"),
|
| 16 |
+
base_url="https://api.deepseek.com/v1"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
+
embeddings = HuggingFaceEmbeddings(
|
| 21 |
+
model_name="shibing624/text2vec-base-chinese",
|
| 22 |
+
model_kwargs={"device": device}
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# 加载本地 FAISS 向量库
|
| 26 |
+
vectorstore = FAISS.load_local("promotion_faiss_index", embeddings)
|
| 27 |
+
|
| 28 |
+
# === 2. 构建 Prompt ===
|
| 29 |
+
|
| 30 |
+
def build_prompt(query, docs):
|
| 31 |
+
context_blocks = []
|
| 32 |
+
for i, doc in enumerate(docs, start=1):
|
| 33 |
+
meta = doc.metadata
|
| 34 |
+
context_blocks.append(
|
| 35 |
+
f"[文档 {i}]\n"
|
| 36 |
+
f"{doc.page_content}\n"
|
| 37 |
+
f"门店类型: {meta.get('store_type')}, 地点: {meta.get('location')}, "
|
| 38 |
+
f"活动类型: {meta.get('promotion_type')}, 销售增长: {meta.get('sales_growth')}%\n"
|
| 39 |
+
)
|
| 40 |
+
context_text = "\n".join(context_blocks)
|
| 41 |
+
return f"""你是一位擅长制定促销策略的 AI 顾问,请结合历史促销案例,为用户提出的问题提供可执行的促销建议。
|
| 42 |
+
|
| 43 |
+
用户问题:{query}
|
| 44 |
+
|
| 45 |
+
参考历史促销案例如下:
|
| 46 |
+
{context_text}
|
| 47 |
+
|
| 48 |
+
请根据这些信息,给出适合该用户的建议。建议应简洁、具体、策略性强。
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
# === 3. 调用 DeepSeek 模型 ===
|
| 52 |
+
|
| 53 |
+
def ask_promotion_ai(query):
|
| 54 |
+
results = vectorstore.similarity_search(query, k=4)
|
| 55 |
+
prompt = build_prompt(query, results)
|
| 56 |
+
messages = [
|
| 57 |
+
{"role": "system", "content": "你是一位餐饮营销专家"},
|
| 58 |
+
{"role": "user", "content": prompt}
|
| 59 |
+
]
|
| 60 |
+
try:
|
| 61 |
+
response = client.chat.completions.create(
|
| 62 |
+
model="deepseek-reasoner",
|
| 63 |
+
messages=messages,
|
| 64 |
+
stream=False
|
| 65 |
+
)
|
| 66 |
+
return response.choices[0].message.content
|
| 67 |
+
except Exception as e:
|
| 68 |
+
return f"❗ 调用 DeepSeek 失败:{str(e)}"
|
| 69 |
+
|
| 70 |
+
# === 4. 格式化输入 ===
|
| 71 |
+
|
| 72 |
+
def format_query(store_name, store_type, location, budget, problem):
|
| 73 |
+
parts = [
|
| 74 |
+
f"店家名称:{store_name}",
|
| 75 |
+
f"餐馆类型:{store_type}",
|
| 76 |
+
f"地理位置:{location}",
|
| 77 |
+
f"问题或目标:{problem}"
|
| 78 |
+
]
|
| 79 |
+
if budget.strip():
|
| 80 |
+
parts.insert(3, f"促销预算:{budget}")
|
| 81 |
+
return "\n".join(parts)
|
| 82 |
+
|
| 83 |
+
# === 5. 记录用户反馈 ===
|
| 84 |
+
|
| 85 |
+
def record_feedback(user_query, final_answer, feedback_choice, improved_answer):
|
| 86 |
+
with open("feedback.csv", "a", encoding="utf-8", newline="") as f:
|
| 87 |
+
writer = csv.writer(f)
|
| 88 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 89 |
+
answer_used = final_answer if feedback_choice == "好" else improved_answer
|
| 90 |
+
writer.writerow([current_time, user_query, feedback_choice, answer_used])
|
| 91 |
+
|
| 92 |
+
hf_token = os.getenv("HF_TOKEN", None)
|
| 93 |
+
if not hf_token:
|
| 94 |
+
return "⚠️ 未设置 HF_TOKEN,无法同步到 Hugging Face Datasets"
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
api = HfApi()
|
| 98 |
+
api.upload_file(
|
| 99 |
+
path_or_fileobj="feedback.csv",
|
| 100 |
+
path_in_repo="feedback.csv",
|
| 101 |
+
repo_id="YourUser/YourDataset", # TODO: 替换为你自己的 Dataset 仓库路径
|
| 102 |
+
repo_type="dataset",
|
| 103 |
+
token=hf_token,
|
| 104 |
+
commit_message="更新用户反馈"
|
| 105 |
+
)
|
| 106 |
+
return "✅ 反馈已保存,并同步到 Hugging Face Datasets"
|
| 107 |
+
except Exception as e:
|
| 108 |
+
return f"⚠️ 本地已保存,但上传失败:{str(e)}"
|
| 109 |
+
|
| 110 |
+
# === 6. 构建 Gradio 界面 ===
|
| 111 |
+
|
| 112 |
+
with gr.Blocks() as demo:
|
| 113 |
+
gr.Markdown("# 🧠 AI促销推荐助手")
|
| 114 |
+
gr.Markdown("请填写以下信息,我们将根据历史案例为你定制促销建议。")
|
| 115 |
+
|
| 116 |
+
with gr.Row():
|
| 117 |
+
store_name = gr.Textbox(label="店家名称", placeholder="例如:小王烧烤")
|
| 118 |
+
store_type = gr.Textbox(label="餐馆类型", placeholder="例如:中式快餐 / 咖啡馆")
|
| 119 |
+
|
| 120 |
+
with gr.Row():
|
| 121 |
+
location = gr.Textbox(label="地理位置", placeholder="例如:北京市朝阳区")
|
| 122 |
+
budget = gr.Textbox(label="促销预算(选填)", placeholder="例如:500元以内,可留空")
|
| 123 |
+
|
| 124 |
+
problem = gr.Textbox(label="目前遇到的问题或目标", placeholder="例如:下午人流少,希望提高堂食销量", lines=3)
|
| 125 |
+
ai_answer = gr.Textbox(label="AI 回答", lines=8)
|
| 126 |
+
|
| 127 |
+
submit_btn = gr.Button("提交问题")
|
| 128 |
+
|
| 129 |
+
submit_btn.click(
|
| 130 |
+
fn=lambda sn, st, loc, bud, prob: ask_promotion_ai(
|
| 131 |
+
format_query(sn, st, loc, bud, prob)
|
| 132 |
+
),
|
| 133 |
+
inputs=[store_name, store_type, location, budget, problem],
|
| 134 |
+
outputs=[ai_answer]
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
gr.Markdown("---")
|
| 138 |
+
gr.Markdown("### 🙏 请对 AI 的回答进行评价")
|
| 139 |
+
|
| 140 |
+
feedback_choice = gr.Radio(["好", "不好"], label="你觉得这个回答怎么样?")
|
| 141 |
+
improved_answer = gr.Textbox(label="如果选择“不好”,你觉得更好的回答是什么?", lines=3)
|
| 142 |
+
feedback_btn = gr.Button("提交反馈")
|
| 143 |
+
feedback_output = gr.Markdown()
|
| 144 |
+
|
| 145 |
+
feedback_btn.click(
|
| 146 |
+
fn=record_feedback,
|
| 147 |
+
inputs=[problem, ai_answer, feedback_choice, improved_answer],
|
| 148 |
+
outputs=[feedback_output]
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
# 启动 Gradio app
|
| 152 |
+
demo.launch()
|