尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

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

用户画像记忆,让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_iddefault):self.llmllm self.user_iduser_id self.profile{basic_info:{},tech_preferences:{},interaction_preferences:{},knowledge_level:{},history_summary:[],}defupdate_from_conversation(self,conversation_text):从对话中更新用户画像promptChatPromptTemplate.from_template(请分析以下对话提取用户的相关信息更新用户画像。 当前用户画像 {current_profile} 最新对话 {conversation} 请分析对话提取以下信息 1. basic_info: 姓名、职业、技能水平、行业等基本信息 2. tech_preferences: 编程语言、框架、工具偏好 3. interaction_preferences: 回答风格偏好简洁/详细、代码量、语言 4. knowledge_level: 各领域知识水平评估 5. history_summary: 本次对话的关键主题一句话 请输出更新后的完整用户画像JSON格式。只输出JSON不要其他内容。)chainprompt|self.llm resultchain.invoke({current_profile:json.dumps(self.profile,ensure_asciiFalse,indent2),conversation:conversation_text,})try:new_profilejson.loads(result.content)self.profilenew_profile self.profile[last_updated]datetime.now().isoformat()returnTrueexceptjson.JSONDecodeError:print(画像更新失败解析JSON失败)returnFalsedefget_profile_summary(self):获取画像摘要用于注入Promptparts[]basicself.profile.get(basic_info,{})ifbasic:parts.append(f用户信息{json.dumps(basic,ensure_asciiFalse)})techself.profile.get(tech_preferences,{})iftech:parts.append(f技术偏好{json.dumps(tech,ensure_asciiFalse)})interactionself.profile.get(interaction_preferences,{})ifinteraction:parts.append(f交互偏好{json.dumps(interaction,ensure_asciiFalse)})knowledgeself.profile.get(knowledge_level,{})ifknowledge:parts.append(f知识水平{json.dumps(knowledge,ensure_asciiFalse)})return\n.join(parts)ifpartselse暂无用户画像信息defsave_to_file(self,filepath):保存画像到文件withopen(filepath,w,encodingutf-8)asf:json.dump(self.profile,f,ensure_asciiFalse,indent2)defload_from_file(self,filepath):从文件加载画像withopen(filepath,r,encodingutf-8)asf:self.profilejson.load(f)把画像注入对话用户画像构建好了怎么在对话中使用。在每次对话开始的时候把用户画像注入到System Prompt里。Agent就知道了用户是谁、喜欢什么、什么水平。classPersonalizedAgent:带用户画像的个性化Agentdef__init__(self,llm,user_profile):self.llmllm self.profileuser_profile self.conversation_history[]self.base_prompt你是一个智能助手。请根据用户画像提供个性化服务。 用户画像 {user_profile} 个性化要求 1. 根据用户的技术偏好选择合适的语言和框架 2. 根据用户的知识水平调整解释深度 3. 根据用户的交互偏好调整回答风格 4. 如果画像信息不足按默认方式回答defchat(self,user_input):# 获取画像摘要profile_textself.profile.get_profile_summary()# 构建系统提示system_promptself.base_prompt.format(user_profileprofile_text)# 构建消息列表messages[SystemMessage(contentsystem_prompt)]messages.extend(self.conversation_history)messages.append(HumanMessage(contentuser_input))# 调用大模型responseself.llm.invoke(messages)# 更新对话历史self.conversation_history.append(HumanMessage(contentuser_input))self.conversation_history.append(response)# 控制历史长度iflen(self.conversation_history)10:self.conversation_historyself.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[]# 使用示例llmChatOpenAI(modelgpt-3.5-turbo,temperature0)# 加载或创建用户画像profileUserProfile(llm,user_iduser_001)# profile.load_from_file(user_001_profile.json) # 如果已有画像# 创建个性化AgentagentPersonalizedAgent(llm,profile)# 对话print(agent.chat(我想做一个AI客服系统))# Agent会根据画像调整回答比如用PythonLangChain来回答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.llmllm self.storage_dirPath(storage_dir)self.storage_dir.mkdir(exist_okTrue)self.profiles{}# 缓存defget_profile(self,user_id):获取用户画像ifuser_idinself.profiles:returnself.profiles[user_id]# 从文件加载filepathself.storage_dir/f{user_id}.jsonprofileUserProfile(self.llm,user_iduser_id)iffilepath.exists():profile.load_from_file(str(filepath))self.profiles[user_id]profilereturnprofiledefsave_profile(self,user_id):保存用户画像ifuser_idinself.profiles:filepathself.storage_dir/f{user_id}.jsonself.profiles[user_id].save_to_file(str(filepath))下一篇讲记忆的检索与更新。什么时候该回忆、什么时候该遗忘怎么管理记忆的生命周期。
返回列表