📋 本文目录
-
-
[3.1 用户画像提取器](#3.1 用户画像提取器)
-
[3.2 风格识别器](#3.2 风格识别器)
-
[3.3 响应个性化器](#3.3 响应个性化器)
-
[3.4 画像管理器](#3.4 画像管理器)
-
一、前言
1.1 工具化的个性化
个性化的核心是"记住"用户,然后根据用户的偏好调整响应。我们把这个过程拆成4个工具,每个工具负责一个环节。
1.2 你将学到什么?
-
✅ 从对话中提取用户画像
-
✅ 识别用户的沟通风格
-
✅ 根据偏好个性化响应
-
✅ 管理用户画像数据
二、工具概览
2.1 4个工具
| 工具 | 功能 |
|---|---|
| 用户画像提取器 | 从对话中提取兴趣、风格等 |
| 风格识别器 | 识别用户喜欢的沟通方式 |
| 响应个性化器 | 根据画像调整回复内容 |
| 画像管理器 | 管理和导出用户画像 |
2.2 文件结构
09_personalization/
├── shared_profile_store.py # 共享存储
├── tool_1_profile_extractor.py
├── tool_2_style_recognizer.py
├── tool_3_response_personalizer.py
├── tool_4_profile_manager.py
├── personalization_demo.py # 工具链演示
├── personalization_agent.py # Agent演示
└── sample_conversations.json # 示例数据
三、工具详解
3.1 用户画像提取器
功能说明:从用户的对话文本中,提取兴趣爱好、沟通风格、专业领域等信息,用来构建用户画像。
3.2 完整代码
from langchain.tools import tool
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from shared_profile_store import update_preference, get_profile, add_comparison
@tool
def profile_extractor(conversation_text: str, auto_update: bool = True):
"""用户画像提取器 - 从对话中提取用户特征和偏好
参数:
conversation_text: 对话文本内容
auto_update: 是否自动更新用户画像
返回:
提取的用户画像摘要
"""
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
# 初始化LLM
try:
llm = ChatOpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama",
model="qwen2.5:3b-instruct",
temperature=0.3
)
except Exception as e:
return f"[ERROR] LLM初始化失败: {e}"
# 构建提示
prompt = ChatPromptTemplate.from_messages([
("system", """你是一个用户画像分析专家。从对话中提取以下信息:
请分析对话,提取用户的特征,按以下格式输出:
【兴趣偏好】
- 兴趣1: 描述
- 兴趣2: 描述
【沟通风格】
- 喜欢简洁回答/喜欢详细解释: 是/否
- 喜欢正式风格/喜欢随意风格: 是/否
【专业领域】
- 领域1: 描述
- 领域2: 描述
请只提取明确提到的信息,不要添加推测。"""),
("user", "对话内容:{conversation_text}")
])
chain = prompt | llm
result = chain.invoke({"conversation_text": conversation_text})
# 简单解析并更新(模拟)
extracted_info = {
"conversation_length": len(conversation_text),
"extraction_success": True
}
if auto_update:
# 简单关键词匹配更新偏好
if "编程" in conversation_text or "代码" in conversation_text:
update_preference("interest_tech", True)
if "简洁" in conversation_text or "简单" in conversation_text:
update_preference("style_concise", True)
if "详细" in conversation_text or "具体" in conversation_text:
update_preference("style_detailed", True)
output = []
output.append("=" * 80)
output.append("【用户画像提取器】")
output.append("=" * 80)
output.append(f"\n输入对话长度: {len(conversation_text)} 字符")
output.append("\n" + "=" * 80)
output.append("【提取结果】")
output.append("=" * 80)
output.append(result.content)
output.append("\n" + "=" * 80)
output.append("[TIP] 提取的信息可用于构建用户画像")
output.append("=" * 80)
return "\n".join(output)
3.3 使用示例
test_conversation = """
用户:你好,我是一个程序员,最近在学Python编程。
助手:你好!很高兴帮助你学习Python。
用户:我喜欢简洁明了的解释,不要太啰嗦。
助手:好的,我会尽量简洁地回答你的问题。
"""
result = profile_extractor.invoke({"conversation_text": test_conversation, "auto_update": True})
print(result)
3.2 风格识别器
功能说明:分析用户的消息,识别用户喜欢的沟通风格:是简洁还是详细?是正式还是随意?是友好还是严肃?
完整代码:
from langchain.tools import tool
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from shared_profile_store import update_style, get_profile
@tool
def style_recognizer(user_messages: str, auto_update: bool = True):
"""风格识别器 - 识别用户偏好的交互风格
参数:
user_messages: 用户的消息历史(多行)
auto_update: 是否自动更新用户风格
返回:
识别的风格摘要
"""
output = []
output.append("=" * 80)
output.append("【风格识别器】")
output.append("=" * 80)
# 简单的关键词匹配识别风格
messages_lower = user_messages.lower()
recognized_styles = {
"concise": False,
"detailed": False,
"formal": False,
"casual": False,
"technical": False,
"friendly": False
}
# 简洁风格关键词
if any(keyword in messages_lower for keyword in ["简洁", "简单", "短一点", "不要啰嗦", "别太长"]):
recognized_styles["concise"] = True
# 详细风格关键词
if any(keyword in messages_lower for keyword in ["详细", "具体", "多讲一点", "解释清楚"]):
recognized_styles["detailed"] = True
# 正式/随意风格
if any(keyword in messages_lower for keyword in ["您好", "请", "谢谢", "请问"]):
recognized_styles["formal"] = True
if any(keyword in messages_lower for keyword in ["嘿", "嗨", "嘛", "啦", "哦"]):
recognized_styles["casual"] = True
# 技术风格
if any(keyword in messages_lower for keyword in ["代码", "编程", "技术", "开发", "算法"]):
recognized_styles["technical"] = True
# 友好风格
if any(keyword in messages_lower for keyword in ["谢谢", "感谢", "好的", "很棒", "厉害"]):
recognized_styles["friendly"] = True
if auto_update:
# 更新风格到用户画像
for style_key, value in recognized_styles.items():
if value:
update_style(style_key, True)
output.append(f"\n分析消息长度: {len(user_messages)} 字符")
output.append("\n" + "=" * 80)
output.append("【识别的风格】")
output.append("=" * 80)
style_names = {
"concise": "偏好简洁回答",
"detailed": "偏好详细解释",
"formal": "沟通风格较正式",
"casual": "沟通风格较随意",
"technical": "关注技术内容",
"friendly": "语气友好"
}
any_recognized = False
for key, name in style_names.items():
if recognized_styles[key]:
output.append(f" - {name}")
any_recognized = True
if not any_recognized:
output.append(" 暂未识别到明显风格特征")
output.append("\n" + "=" * 80)
output.append("[TIP] 识别的风格可用于个性化响应")
output.append("=" * 80)
return "\n".join(output)
4.3 使用示例
test_messages = """
你好,请帮我解释一下Python的装饰器,希望能详细一点,谢谢!
"""
result = style_recognizer.invoke({"user_messages": test_messages, "auto_update": True})
print(result)
3.3 响应个性化器
功能说明:拿到标准响应后,根据用户画像进行个性化调整:如果用户喜欢简洁,就缩短回复;如果用户喜欢友好,就添加友好语气。
完整代码:
from langchain.tools import tool
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from shared_profile_store import get_profile, add_interaction
@tool
def response_personalizer(base_response: str, use_profile: bool = True):
"""响应个性化器 - 基于用户画像个性化响应
参数:
base_response: 原始的标准响应
use_profile: 是否使用用户画像进行个性化
返回:
个性化后的响应
"""
profile = get_profile() if use_profile else {}
output = []
output.append("=" * 80)
output.append("【响应个性化器】")
output.append("=" * 80)
output.append(f"\n是否使用画像: {'是' if use_profile else '否'}")
if not use_profile:
output.append("\n" + "=" * 80)
output.append("【标准响应(无个性化)】")
output.append("=" * 80)
output.append(base_response)
output.append("\n" + "=" * 80)
output.append("[TIP] 使用用户画像可以让响应更贴心")
output.append("=" * 80)
return "\n".join(output)
# 获取用户风格
style = profile.get("style", {})
preferences = profile.get("preferences", {})
personalized_response = base_response
# 应用风格调整
if style.get("concise"):
# 简洁化处理
sentences = base_response.split("。")
if len(sentences) > 2:
personalized_response = "。".join(sentences[:2]) + "。"
if style.get("friendly"):
# 添加友好语气
if not personalized_response.startswith("好的") and not personalized_response.startswith("当然"):
personalized_response = "好的!" + personalized_response
if style.get("technical"):
# 技术风格,可以添加更多技术细节
pass
output.append("\n" + "=" * 80)
output.append("【标准响应】")
output.append("=" * 80)
output.append(base_response)
output.append("\n" + "=" * 80)
output.append("【个性化响应】")
output.append("=" * 80)
output.append(personalized_response)
# 显示应用的调整
output.append("\n" + "=" * 80)
output.append("【应用的个性化调整】")
output.append("=" * 80)
applied = []
if style.get("concise"):
applied.append("- 简洁化处理")
if style.get("friendly"):
applied.append("- 增加友好语气")
if style.get("technical"):
applied.append("- 技术风格适配")
if applied:
for item in applied:
output.append(item)
else:
output.append("无特定调整")
output.append("\n" + "=" * 80)
output.append("[TIP] 个性化让AI更懂用户")
output.append("=" * 80)
# 记录交互
add_interaction({
"type": "personalization",
"base_response": base_response,
"personalized_response": personalized_response,
"profile_used": use_profile
})
return "\n".join(output)
5.3 使用示例
test_response = """
Python装饰器是一种设计模式,用于在不修改原函数代码的情况下,给函数添加额外功能。
装饰器的语法是使用@符号放在函数定义上方。
装饰器本质上是一个接受函数作为参数并返回新函数的高阶函数。
"""
result = response_personalizer.invoke({"base_response": test_response, "use_profile": True})
print(result)
3.4 画像管理器
功能说明:管理用户画像:查看详情、获取摘要、清空数据、导出数据、手动更新偏好。
完整代码:
from langchain.tools import tool
import sys
import os
import json
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from shared_profile_store import (
get_profile, get_all_comparisons, get_interaction_history,
clear_profile_store, format_profile_summary, update_preference, update_style
)
@tool
def profile_manager(command: str, data: dict = None):
"""画像管理器 - 管理和更新用户画像
参数:
command: 命令类型 (view/summary/clear/export/update)
data: 相关数据(用于update命令)
返回:
操作结果
"""
if command == "view":
# 查看完整画像
profile = get_profile()
output = ["=" * 80, "【用户画像详情】", "=" * 80]
output.append(f"\n用户ID: {profile['user_id']}")
output.append(f"创建时间: {profile['created_at']}")
output.append(f"更新时间: {profile['updated_at']}")
preferences = profile["preferences"]
output.append(f"\n偏好设置 ({len(preferences)} 项):")
if preferences:
for key, value in preferences.items():
output.append(f" - {key}: {value}")
else:
output.append(" (暂无偏好设置)")
style = profile["style"]
output.append(f"\n风格偏好 ({len(style)} 项):")
if style:
for key, value in style.items():
output.append(f" - {key}: {value}")
else:
output.append(" (暂无风格偏好)")
output.append("\n" + "=" * 80)
return "\n".join(output)
elif command == "summary":
# 获取摘要
return format_profile_summary()
elif command == "clear":
# 清空
clear_profile_store()
return "[OK] 已清空用户画像"
elif command == "export":
# 导出
data_to_export = {
"profile": get_profile(),
"comparisons": get_all_comparisons(),
"interactions": get_interaction_history()
}
output_file = "output_user_profiles.json"
with open(output_file, "w", encoding="utf-8") as f:
json.dump(data_to_export, f, ensure_ascii=False, indent=2)
return f"[OK] 已导出到 {output_file}"
elif command == "update" and data:
# 更新画像
if "preference" in data:
key = data["preference"]["key"]
value = data["preference"]["value"]
update_preference(key, value)
return f"[OK] 已更新偏好: {key} = {value}"
if "style" in data:
key = data["style"]["key"]
value = data["style"]["value"]
update_style(key, value)
return f"[OK] 已更新风格: {key} = {value}"
return "[ERROR] 无效的更新数据"
else:
return f"[ERROR] 未知命令: {command}\n可用命令: view/summary/clear/export/update"
6.3 使用示例
# 查看用户画像
result = profile_manager.invoke({"command": "view"})
print(result)
# 获取摘要
result = profile_manager.invoke({"command": "summary"})
print(result)
四、实战案例
4.1 工具链演示
运行完整的工具链演示:
cd 09_personalization
python personalization_demo.py
4.2 工具功能对比表
| 工具 | 核心功能 | 适用场景 | 优势 |
|---|---|---|---|
| 用户画像提取器 | 从对话提取用户特征 | 用户初次交互 | 自动构建画像 |
| 风格识别器 | 识别用户沟通风格 | 持续交互中 | 适应用户偏好 |
| 响应个性化器 | 根据画像调整响应 | 生成回复时 | 个性化体验 |
| 画像管理器 | 管理用户画像数据 | 运维管理 | 便于维护 |
4.3 实际应用案例
案例1:提取用户画像
对话文本:
用户:你好,我是一个程序员,最近在学Python编程。
助手:你好!很高兴帮助你学习Python。
用户:我喜欢简洁明了的解释,不要太啰嗦,谢谢!
提取结果:
【用户画像】
用户ID: user_default
偏好设置:
- 职业: 程序员
- 兴趣: Python编程
- 学习阶段: 初学者
风格偏好:
- concise: True (喜欢简洁)
代码调用:
from tool_1_profile_extractor import profile_extractor
conversation = """
用户:你好,我是一个程序员,最近在学Python编程。
助手:你好!很高兴帮助你学习Python。
用户:我喜欢简洁明了的解释,不要太啰嗦,谢谢!
"""
result = profile_extractor.invoke({
"conversation_text": conversation,
"auto_update": True
})
print(result)
案例2:识别用户风格
用户消息:请帮我解释一下Python的装饰器,希望能详细一点,谢谢!
识别结果:
【风格识别结果】
详细程度偏好: 详细 (detailed)
正式程度偏好: 正式 (formal)
技术程度偏好: 技术 (technical)
建议响应方式: 详细、正式、技术化
代码调用:
from tool_2_style_recognizer import style_recognizer
test_messages = """
你好,请帮我解释一下Python的装饰器,希望能详细一点,谢谢!
"""
result = style_recognizer.invoke({
"user_messages": test_messages,
"auto_update": True
})
print(result)
案例3:个性化响应
标准响应:Python装饰器是一种设计模式,用于在不修改原函数代码的情况下添加额外功能。
个性化后响应(简洁风格):装饰器:不修改代码给函数加功能。
代码调用:
from tool_3_response_personalizer import response_personalizer
test_response = """
Python装饰器是一种设计模式,用于在不修改原函数代码的情况下,给函数添加额外功能。
装饰器的语法是使用@符号放在函数定义上方。
"""
result = response_personalizer.invoke({
"base_response": test_response,
"use_profile": True
})
print(result)
4.4 完整工具链调用示例
我们将4个工具组合成完整的个性化流程:
from tool_1_profile_extractor import profile_extractor
from tool_2_style_recognizer import style_recognizer
from tool_3_response_personalizer import response_personalizer
from tool_4_profile_manager import profile_manager
# 步骤1:从对话提取用户画像
conversation = """
用户:你好,我是一个程序员,最近在学Python编程。
助手:你好!很高兴帮助你学习Python。
用户:我喜欢简洁明了的解释,不要太啰嗦,谢谢!
"""
extract_result = profile_extractor.invoke({"conversation_text": conversation, "auto_update": True})
print(extract_result)
# 步骤2:识别用户风格
style_result = style_recognizer.invoke({"user_messages": conversation, "auto_update": True})
print(style_result)
# 步骤3:查看用户画像
profile_summary = profile_manager.invoke({"command": "summary"})
print(profile_summary)
# 步骤4:测试个性化响应
standard_response = """
Python装饰器是一种设计模式,用于在不修改原函数代码的情况下,给函数添加额外功能。
装饰器的语法是使用@符号放在函数定义上方。
装饰器本质上是一个接受函数作为参数并返回新函数的高阶函数。
在实际开发中,装饰器常用于日志记录、性能计时、权限校验等场景。
"""
personalized_result = response_personalizer.invoke({
"base_response": standard_response,
"use_profile": True
})
print(personalized_result)
五、工具链整合
5.1 个性化工具链架构
用户消息
↓
[用户画像提取器] 提取用户特征和偏好
↓
[风格识别器] 识别用户沟通风格
↓
[响应个性化器] 根据画像调整响应
↓
[画像管理器] 存储和管理用户画像
5.2 工具协作流程
| 步骤 | 工具 | 作用 |
|---|---|---|
| 1 | 用户画像提取器 | 从对话提取用户特征 |
| 2 | 风格识别器 | 识别用户沟通风格 |
| 3 | 响应个性化器 | 个性化调整响应内容 |
| 4 | 画像管理器 | 存储和维护画像 |
六、总结
6.1 本文要点
| 工具 | 核心能力 | 价值 |
|---|---|---|
| ✅ 用户画像提取器 | 从对话提取用户特征 | 自动构建画像 |
| ✅ 风格识别器 | 识别用户沟通风格 | 适应用户偏好 |
| ✅ 响应个性化器 | 根据画像调整响应 | 个性化体验 |
| ✅ 画像管理器 | 管理用户画像数据 | 便于维护 |
点赞 + 关注,更新不迷路!🚀