首页 › AI Agent实战项目案例库 › 推荐系统实战项目 › Agent项目:0-1 搭建智能推荐系统

Agent项目:0-1 搭建智能推荐系统

​

面向小白的企业级 AI Agent 项目 — 从零理解 Multi-Agent 架构,配套三语言代码 + 八股文 + 简历模板 + STAR面试话术,找工作全流程覆盖。​

​

​

​

这个项目是什么?​

用一句话解释​

​

用 AI Agent 技术,让电商平台的推荐 + 文案 + 库存三个系统协同工作,像一个聪明的"AI 运营团队"一起为每位用户生成个性化推荐结果。​

​

​

飞书文档 - 图片

​

用户画像 Agent​

它做什么?​

把用户的历史行为数据(点击、购买、收藏)转化成结构化的"用户画像",供其他 Agent 使用。​

核心逻辑(简化):​

​

代码块​

Java

# Step 1:从 Redis Feature Store 获取实时行为特征​

behavior = await feature_store.get_user_features(user_id)​

# 返回: {"clicks_1h": 12, "purchases_7d": 3, "categories": ["手机", "耳机"]}​

​

# Step 2:调用 LLM 分析,输出结构化画像​

prompt = f"用户行为数据: {behavior}\n请分析用户分群和RFM得分,输出JSON"​

profile_json = await llm.invoke(prompt)​

# 输出: {"segments": ["active", "price_sensitive"], "rfm_score": {"recency": 0.8}}​

​

# Step 3:返回 UserProfile 对象​

return UserProfile(user_id=user_id, segments=["active"], rfm_score=...)​

​

关键技术:​

•

Redis Sorted Set:ZADD user:u001:clicks {时间戳} {商品ID},支持滑动窗口查询​

•

RFM 模型:Recency(最近购买时间)× Frequency(购买频率)× Monetary(消费金额)​

•

用户分群:新客 / VIP / 价格敏感 / 活跃 / 流失风险,共 5 类​

​

​

🏗 系统架构​

​

代码块​

Plain Text

┌─────────────────────────────────────────────────────────────────┐​

│ 用户发起推荐请求 │​

│ {"user_id": "u001", "num_items": 5} │​

└───────────────────────────────┬─────────────────────────────────┘​

│​

▼​

┌─────────────────────────────────────────────────────────────────┐​

│ Supervisor 协调Agent │​

│ (python/orchestrator/supervisor.py) │​

│ │​

│ ════════════════ Phase 1: 并行执行 ═══════════════════ │​

│ ┌──────────────────────┐ ┌──────────────────────┐ │​

│ │ 用户画像 Agent │ │ 商品召回 Agent │ │​

│ │ user_profile_agent │ │ product_rec_agent │ │​

​

​

​

为什么用 Supervisor 模式?​

Supervisor 模式是 Multi-Agent 系统中最主流的编排方式之一:​

​

代码块​

Plain Text

Supervisor 模式 Handoffs 模式​

────────────────────── ──────────────────────​

Supervisor(中枢) Agent A → Agent B​

┌────┬────┬────┐ ↓​

▼ ▼ ▼ ▼ Agent B → Agent C​

A B C D ↓​

└────┴────┴────┘ Agent C → ...​

结果聚合 → 响应​

​

✅ 集中控制,流程清晰 ✅ 去中心化,灵活​

✅ 并行执行,延迟低 ✅ 适合对话/开放式任务​

✅ 异常统一处理 ❌ 状态管理复杂​

本项目采用 Supervisor 模式​

​

四大核心 Agent 详解​

Agent 1:用户画像 Agent​

它做什么?​

把用户的历史行为数据(点击、购买、收藏)转化成结构化的"用户画像",供其他 Agent 使用。​

核心逻辑(简化):​

​

代码块​

Shell

# Step 1:从 Redis Feature Store 获取实时行为特征​

behavior = await feature_store.get_user_features(user_id)​

# 返回: {"clicks_1h": 12, "purchases_7d": 3, "categories": ["手机", "耳机"]}​

​

# Step 2:调用 LLM 分析,输出结构化画像​

prompt = f"用户行为数据: {behavior}\n请分析用户分群和RFM得分,输出JSON"​

profile_json = await llm.invoke(prompt)​

# 输出: {"segments": ["active", "price_sensitive"], "rfm_score": {"recency": 0.8}}​

​

# Step 3:返回 UserProfile 对象​

return UserProfile(user_id=user_id, segments=["active"], rfm_score=...)​

​

关键技术:​

•

Redis Sorted Set:ZADD user:u001:clicks {时间戳} {商品ID},支持滑动窗口查询​

•

RFM 模型:Recency(最近购买时间)× Frequency(购买频率)× Monetary(消费金额)​

•

用户分群:新客 / VIP / 价格敏感 / 活跃 / 流失风险,共 5 类​

​

​

​

​

​

Agent 2:商品推荐 Agent​

它做什么?​

两阶段推荐:先"召回"大量候选商品,再用 LLM 精排出最合适的 TopN。​

​

代码块​

Plain Text

多路召回策略​

​

​

​

Agent 3:营销文案 Agent​

它做什么?​

根据用户画像自动选择合适的文案风格模板,调用 LLM 生成个性化文案,并做广告法合规校验。​

​

代码块​

Python

​

​

​

​

​

Agent 4:库存决策 Agent​

它做什么?​

查询商品实时库存,过滤缺货商品,输出限购策略和补货预警。​

​

代码块​

Python

# 输入: 推荐商品列表 [P001, P002, P003, ...]​

# 查询 MySQL/WMS 实时库存​

# 输出:​

{​

"available_products": ["P001", "P003"], # 有货商品​

"inventory_alerts": [ # 库存预警​

{"product_id": "P001", "stock": 5, "warning": "库存紧张"}​

],​

"purchase_limits": { # 限购策略​

"P001": 2 # 每人最多买2件​

}​

}​

​

​

​

🌐 三语言实现对比​

​

#ZBnkfJtKbftG text{white-space:pre}.fb0{stroke:var(--N900-FG, 0.15)}.fx0{stroke-miterlimit:10}.fa1{fill:#bbbfc4}.fx1{font:normal 400 12px MonospacedNumber,LarkHackSafariFont,LarkEmojiFont,LarkChineseQuote,-apple-system,BlinkMacSystemFont,Helvetica Neue,Tahoma,PingFang SC,Microsoft Yahei,Arial,Hiragino Sans GB,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}.fx2{text-anchor:middle}.fx3{dominant-baseline:central}.fx4{stroke:none}.fc0{fill:var(--text-caption)}.fa2{fill:var(--text-link-disabled)}.fc1{stroke:var(--B500)}.fx5{font:400 normal 13px MonospacedNumber, LarkHackSafariFont, LarkEmojiFont, LarkChineseQuote, -apple-system, BlinkMacSystemFont, "Helvetica Neue", Tahoma, "PingFang SC", "Microsoft Yahei", Arial, "Hiragino Sans GB", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"}.fx6{text-anchor:start}.fx7{dominant-baseline:alphabetic}.fc2{fill:rgb(0, 0, 0)}.fc3{fill:var(--B500)}.fb1{fill:var(--N900-FG, 0.15)}.fa3{fill:var(--bg-body)}ABCD123456维度框架并行方式推荐语言代码位置启动命令Python + FastAPIasyncio.gather()✅ 入门首选,代码量最少python Java + Spring Boot 3CompletableFuture.allOf()✅ 企业级Java岗mvn spring-boot:runGoLangChainGo + Gingoroutine + sync.WaitGroup✅ 高并发/云原生岗go run cmd/main.goLangGraphpython/main.pySpring AI Alibabajava/go/

​

​

​

💻 关键代码展示​

Supervisor 并行编排(Python 核心代码)​

​

代码块​

Python

class SupervisorOrchestrator:​

"""Supervisor 编排器 — 并行分发 + 聚合模式"""​

​

​

​

💡 小白解读:asyncio.gather() 就像你同时开了两个网页,而不是等一个加载完再开另一个。两个 Agent 并行跑,总延迟约等于最慢那个 Agent 的耗时,而不是两者相加。​

​

​

​

​

​

A/B 测试引擎(Thompson Sampling)​

​

代码块​

Python

class ABTestEngine:​

"""​

流量分桶 + Thompson Sampling 多臂赌博机​

​

Agent 基类:重试 + 降级(可靠性保障)​

​

代码块​

Python

class BaseAgent(ABC):​

"""所有 Agent 的基类 — 模板方法模式"""​

​

MAX_RETRIES = 3​

RETRY_DELAY = 1.0 # 秒,指数退避​

​

async def run(self, **kwargs) -> AgentResult:​

​

​

​

Go 版:goroutine 并行(高并发)​

​

代码块​

Go

func (s *Supervisor) Recommend(ctx context.Context, req *model.RecommendRequest) (*model.RecommendResponse, error) {​

var wg sync.WaitGroup​

​

// goroutine 并行:用户画像 + 商品召回​

wg.Add(2)​

go func() {​

defer wg.Done()​

profile, _ = s.UserProfileAgent.Run(ctx, req.UserID)​

​

​

​

🚀 快速上手运行​

前置条件​

•

Python 3.11+ / Java 17+ / Go 1.22+(选一个语言即可)​

•

申请 LLM API Key(推荐 MiniMax 或 阿里通义,有免费额度)​

Python 版(推荐小白从这里开始)​

​

代码块​

Markdown

# 1. 克隆项目​

git clone https://github.com/bcefghj/multi-agent-ecommerce-system.git​

​

​

​

​

​

飞书文档 - 图片

​

44%

​

​

​

飞书文档 - 图片

​

56%

​

​

​

Java 版​

​

代码块​

Markdown

cd multi-agent-ecommerce-system/java​

​

# 1. 配置 API Key(编辑 src/main/resources/application.yml)​

# 找到 ecommerce.llm.api-key,填入你的 key​

​

# 2. 构建并启动(需要 Maven,可以用 IDEA 直接导入运行)​

mvn spring-boot:run​

​

# 3. 测试​

curl -X POST http://localhost:8080/api/v1/recommend \​

-H "Content-Type: application/json" \​

-d '{"userId": "user_001", "numItems": 5}'​

​

Docker 一键部署(含 Redis + MySQL 等依赖)​

​

代码块​

Markdown

# 在项目根目录运行​

docker-compose up -d​

​

# 等待所有服务启动(约30秒)​

docker-compose ps​

​

# 服务地址​

# Python API: http://localhost:8000​

# Java API: http://localhost:8080​

# Redis: localhost:6379​

# MySQL: localhost:3306​

​

📡 API 接口文档​

接口列表​

​

​

📁 项目文件结构​

​

​

代码块​

Java

multi-agent-ecommerce-system/​

│​

├── README.md # 📄 本文件(项目总览)​

├── plan.md # 📋 完整项目计划(从调研到上线)​

├── docker-compose.yml # 🐳 一键启动所有服务​

│​

​

📋 简历写法(直接复制)​

​

代码块​

Plain Text

多Agent电商推荐与营销系统 | 个人项目 | 2026.01 - 2026.04​

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━​

• 设计并实现基于 Supervisor 模式的多 Agent 协同架构,含用户画像、商品推荐、​

营销文案、库存决策 4 个专业 Agent,采用并行分发+聚合的编排模式​

​

• 基于 Redis Sorted Set 实现实时用户特征工程(RFM 模型+行为序列),​

特征更新延迟 < 100ms,支持 1h/24h/7d 多时间窗口滑动计算​

​

• 集成 LLM 实现个性化营销文案生成,基于用户画像动态切换 5 套 Prompt 模板,​

文案合规率 100%(广告法敏感词自动过滤)​

​

• 设计流量分桶 + Thompson Sampling A/B 测试引擎,支持 Agent/模型/Prompt​

三层实验,推荐 CTR 提升 15%,文案点击率提升 23%​

​

​

​

❓ 面试八股文精选(10题)​

Q1:为什么用 Multi-Agent 而不是单个大 Agent?​

​

推荐答法(30秒): 单 Agent 管理几十个工具时,上下文膨胀、推理准确率会明显下降。Multi-Agent 的核心优势有三点:​

上下文隔离:每个 Agent 只关注自己领域的工具和数据,Token 消耗少、推理准确​

并行加速:4 个 Agent 可以同时跑,端到端延迟约等于最慢 Agent 的耗时,而不是四者相加​

独立演进:各 Agent 可以独立升级、独立做 A/B 测试,互不影响​

​

​

​

​

​

Q2:asyncio.gather() 和串行调用的区别?​

​

​

代码块​

Plain Text

串行:总耗时 = 3s + 5s = 8sprofile = await user_profile_agent.run() # 耗时 3sproducts = await product_rec_agent.run() # 耗时 5s# 并行:总耗时 = max(3s, 5s) = 5sprofile, products = await asyncio.gather(user_profile_agent.run(), # 3sproduct_rec_agent.run(), # 5s(同时开始)​

)​

​

asyncio.gather() 适合 IO 密集型任务(调用 API、查数据库),两个任务同时"等待",CPU 不浪费。​

​

​

​

Q3:Redis Sorted Set 怎么做实时特征?​

​

​

代码块​

Plain Text

# 写入:用户行为事件​

ZADD user:u001:clicks {timestamp} {product_id}​

​

# 读取:最近1小时的点击​

ZRANGEBYSCORE user:u001:clicks {now-3600} {now}​

​

# 滑动窗口统计(1h / 24h / 7d)​

clicks_1h = ZCOUNT user:u001:clicks {now-3600} {now}​

clicks_24h = ZCOUNT user:u001:clicks {now-86400} {now}​

clicks_7d = ZCOUNT user:u001:clicks {now-604800} {now}​

​

用 score=时间戳 的 Sorted Set,天然支持按时间范围查询,时间复杂度 O(log N)。​

​

​

​

Q4:A/B 测试的流量分桶怎么保证一致性?​

​

​

代码块​

Plain Text

​

​

​

​

Q5:Thompson Sampling 怎么动态调流量?​

​

核心思想:哪个实验组赢得多,就自动给它更多流量(像"站在赢家那边")。​

​

代码块​

Plain Text

​

​

​

​

Q6:Agent 调用失败怎么处理?​

​

三层保障:​

超时控制:asyncio.wait_for(coro, timeout=5) — 每个 Agent 独立超时,不阻塞整体​

指数退避重试:失败后等 1s → 2s → 4s 重试,共 3 次​

降级(Fallback):全部重试失败后,返回"说得过去的默认结果"(如热门商品列表),保证整个系统不崩溃​

​

​

​

​

​

Q7:RFM 模型怎么计算?​

​

​

代码块​

Plain Text

R (Recency) = 距离上次购买的天数 → 越小越好(最近买过)​

F (Frequency)= 一定周期内购买次数 → 越大越好(买的勤)​

M (Monetary) = 累计消费金额 → 越大越好(花的多)​

​

# 归一化到 0-1,加权求和​

rfm_score = 0.3 * R_norm + 0.3 * F_norm + 0.4 * M_norm​

​

# 用于分群:​

VIP: rfm_score > 0.8​

活跃用户: 0.6 < rfm_score ≤ 0.8​

价格敏感: 高 F,低 M(买的勤但花得少)​

流失风险: rfm_score < 0.3​

​

​

​

​

Q8:系统延迟怎么优化到 P99 < 2s?​

​

四个优化手段:​

并行化:Phase1 和 Phase2 各两个 Agent 并行,节省约 50% 时间​

超时熔断:单 Agent 超时不等待,返回降级结果,避免长尾拖累​

Redis 缓存:用户画像热点数据缓存,命中率 > 80% 的情况下延迟从 200ms → 5ms​

LLM 精简:Prompt 控制在 500 Token 以内,减少 LLM 推理时间​

​

​