ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

用户画像记忆,让Agent记住用户偏好越用越懂你

2026/8/7 12:58:50 拓冰建站 浏览量
用户画像记忆,让Agent记住用户偏好越用越懂你

用户画像记忆,让Agent记住用户偏好越用越懂你

你用过的最好用的App是什么。大概率是那种"越用越好用"的。它记住你的习惯,推荐你喜欢的,过滤你不感兴趣的。

Agent也可以做到这一点。通过构建用户画像,记住用户的偏好和习惯,让每次交互都比上次更精准。

这一篇我们讲怎么在Agent里实现用户画像记忆。


什么是用户画像

用户画像,简单说就是对用户的结构化描述。记录用户的基本信息、偏好、行为模式。

一个用户画像大概包含这些维度。

基本信息。姓名、职业、技能水平、所在行业。这些是静态的,基本不变。

技术偏好。使用的编程语言、框架、工具。比如用户偏好Python,用LangChain做Agent开发,用VS Code做编辑器。

交互偏好。喜欢什么样的回答风格。详细还是简洁,代码多还是解释多,中文还是英文。

知识水平。对不同话题的熟悉程度。AI基础好但RAG不熟,Python精通但前端不熟。这样Agent可以调整解释的深度。

历史行为。之前问过什么问题,做过什么项目,遇到过什么问题。

有了这些信息,Agent就能做到个性化服务。给Python开发者推荐Python代码,给新手多解释基础概念,给资深开发者直接给方案。


怎么构建用户画像

用户画像的构建分三步。收集、整理、更新。

收集。从用户和Agent的交互中收集信息。用户主动告知的,比如"我是Python开发者"。Agent推断的,比如用户经常问Python相关问题,大概率是Python开发者。

整理。把收集到的零散信息,整理成结构化的画像。用大模型来提取和归类。

更新。用户画像是动态的。用户学了新技能、换了工作、改了偏好,画像要跟着更新。

来看具体实现。

fromlangchain_openaiimportChatOpenAIfromlangchain_core.promptsimportChatPromptTemplateimportjsonfromdatetimeimportdatetimeclassUserProfile:"""用户画像管理"""def__init__(self,llm,user_id="default"):self.llm=llm self.user_id=user_id self.profile={"basic_info":{},"tech_preferences":{},"interaction_preferences":{},"knowledge_level":{},"history_summary":[],}defupdate_from_conversation(self,conversation_text):"""从对话中更新用户画像"""prompt=ChatPromptTemplate.from_template("""请分析以下对话,提取用户的相关信息,更新用户画像。 当前用户画像: {current_profile} 最新对话: {conversation} 请分析对话,提取以下信息: 1. basic_info: 姓名、职业、技能水平、行业等基本信息 2. tech_preferences: 编程语言、框架、工具偏好 3. interaction_preferences: 回答风格偏好(简洁/详细、代码量、语言) 4. knowledge_level: 各领域知识水平评估 5. history_summary: 本次对话的关键主题(一句话) 请输出更新后的完整用户画像,JSON格式。只输出JSON,不要其他内容。""")chain=prompt|self.llm result=chain.invoke({"current_profile":json.dumps(self.profile,ensure_ascii=False,indent=2),"conversation":conversation_text,})try:new_profile=json.loads(result.content)self.profile=new_profile self.profile["last_updated"]=datetime.now().isoformat()returnTrueexceptjson.JSONDecodeError:print("画像更新失败:解析JSON失败")returnFalsedefget_profile_summary(self):"""获取画像摘要,用于注入Prompt"""parts=[]basic=self.profile.get("basic_info",{})ifbasic:parts.append(f"用户信息:{json.dumps(basic,ensure_ascii=False)}")tech=self.profile.get("tech_preferences",{})iftech:parts.append(f"技术偏好:{json.dumps(tech,ensure_ascii=False)}")interaction=self.profile.get("interaction_preferences",{})ifinteraction:parts.append(f"交互偏好:{json.dumps(interaction,ensure_ascii=False)}")knowledge=self.profile.get("knowledge_level",{})ifknowledge:parts.append(f"知识水平:{json.dumps(knowledge,ensure_ascii=False)}")return"\n".join(parts)ifpartselse"暂无用户画像信息"defsave_to_file(self,filepath):"""保存画像到文件"""withopen(filepath,"w",encoding="utf-8")asf:json.dump(self.profile,f,ensure_ascii=False,indent=2)defload_from_file(self,filepath):"""从文件加载画像"""withopen(filepath,"r",encoding="utf-8")asf:self.profile=json.load(f)

把画像注入对话

用户画像构建好了,怎么在对话中使用。

在每次对话开始的时候,把用户画像注入到System Prompt里。Agent就知道了用户是谁、喜欢什么、什么水平。

classPersonalizedAgent:"""带用户画像的个性化Agent"""def__init__(self,llm,user_profile):self.llm=llm self.profile=user_profile self.conversation_history=[]self.base_prompt="""你是一个智能助手。请根据用户画像提供个性化服务。 用户画像: {user_profile} 个性化要求: 1. 根据用户的技术偏好选择合适的语言和框架 2. 根据用户的知识水平调整解释深度 3. 根据用户的交互偏好调整回答风格 4. 如果画像信息不足,按默认方式回答"""defchat(self,user_input):# 获取画像摘要profile_text=self.profile.get_profile_summary()# 构建系统提示system_prompt=self.base_prompt.format(user_profile=profile_text)# 构建消息列表messages=[SystemMessage(content=system_prompt)]messages.extend(self.conversation_history)messages.append(HumanMessage(content=user_input))# 调用大模型response=self.llm.invoke(messages)# 更新对话历史self.conversation_history.append(HumanMessage(content=user_input))self.conversation_history.append(response)# 控制历史长度iflen(self.conversation_history)>10:self.conversation_history=self.conversation_history[-10:]returnresponse.contentdefend_session(self):"""会话结束时更新画像"""conv_text="\n".join(f"{'用户'ifisinstance(m,HumanMessage)else'助手'}:{m.content}"forminself.conversation_history)self.profile.update_from_conversation(conv_text)self.conversation_history=[]# 使用示例llm=ChatOpenAI(model="gpt-3.5-turbo",temperature=0)# 加载或创建用户画像profile=UserProfile(llm,user_id="user_001")# profile.load_from_file("user_001_profile.json") # 如果已有画像# 创建个性化Agentagent=PersonalizedAgent(llm,profile)# 对话print(agent.chat("我想做一个AI客服系统"))# Agent会根据画像调整回答,比如用Python+LangChain来回答print(agent.chat("怎么实现记忆管理"))# Agent知道用户在做AI客服,会结合上下文回答# 会话结束时保存画像agent.end_session()profile.save_to_file("user_001_profile.json")

画像的渐进式构建

用户画像不是一次成型的,是渐进式构建的。

第一次对话,画像可能是空的。Agent按默认方式回答。

聊了几次以后,画像慢慢丰富起来。知道了用户的职业、偏好、水平。Agent开始个性化回答。

聊了几十次以后,画像已经很完善了。Agent对用户的了解很深,回答精准度很高。

这个过程不需要用户刻意做什么。Agent在正常对话的过程中,自动提取信息、更新画像。用户感觉到的就是"这个助手越来越懂我了"。


画像的隐私和透明度

用户画像涉及隐私,需要注意几点。

让用户知道你记了什么。最好提供一个"查看我的画像"的功能。用户能看到Agent记了哪些信息。

让用户能删除。用户不想让Agent记住某些信息,应该能删除。

不要记敏感信息。密码、身份证号、银行卡号这些,绝对不能存。

画像数据加密存储。用户画像数据应该加密存储,防止泄露。


多用户画像管理

如果Agent服务多个用户,每个用户应该有独立的画像。

classUserProfileManager:"""多用户画像管理"""def__init__(self,llm,storage_dir="./user_profiles"):self.llm=llm self.storage_dir=Path(storage_dir)self.storage_dir.mkdir(exist_ok=True)self.profiles={}# 缓存defget_profile(self,user_id):"""获取用户画像"""ifuser_idinself.profiles:returnself.profiles[user_id]# 从文件加载filepath=self.storage_dir/f"{user_id}.json"profile=UserProfile(self.llm,user_id=user_id)iffilepath.exists():profile.load_from_file(str(filepath))self.profiles[user_id]=profilereturnprofiledefsave_profile(self,user_id):"""保存用户画像"""ifuser_idinself.profiles:filepath=self.storage_dir/f"{user_id}.json"self.profiles[user_id].save_to_file(str(filepath))

下一篇讲记忆的检索与更新。什么时候该回忆、什么时候该遗忘,怎么管理记忆的生命周期。