DB-GPT Agent 角色画像(Profiling)模块实战指南:从 ProfileConfig 到动态 Prompt 生成

发布时间:2026/9/13 11:05:30
DB-GPT Agent 角色画像(Profiling)模块实战指南:从 ProfileConfig 到动态 Prompt 生成 DB-GPT Agent 角色画像Profiling模块实战指南从 ProfileConfig 到动态 Prompt 生成【免费下载链接】DB-GPTopen-source agentic AI data assistant for the next generation of AI Data products.项目地址: https://gitcode.com/GitHub_Trending/db/DB-GPT在 DB-GPT 的 Agent 体系中角色画像Profile是决定 Agent 行为的基础设施它把你是谁、你的职责是什么、你被允许做什么编码成系统提示词直接影响 LLM 的表现。本指南以 DB-GPT 官方文档中 Profiling 模块为主体结合仓库源码完整讲解画像的核心概念、ProfileConfig全参数用法、ProfileFactory工厂模式、Jinja2 Prompt 模板机制与DynConfig动态画像配置帮助你从零到一掌握自定义 Agent 角色定义与 Prompt 调优的完整方法。一、什么是 Agent 角色画像ProfilingAgent 执行任务时通常需要扮演特定角色例如程序员coder、教师teacher或领域专家domain expert。Profiling 模块的职责就是描述 Agent 的角色画像并将这些描述写入 Prompt从而影响 LLM 的行为。一个典型的 Agent 画像通常包含三类信息基础信息Basic Information年龄、性别、职业等身份属性心理信息Psychology Information反映 Agent 的性格、思维偏好与行为倾向社会信息Social Information描述 Agent 与 Agent 之间的协作关系。选择哪些信息来刻画 Agent在很大程度上取决于具体的应用场景。例如如果应用旨在研究人类的认知过程那么心理信息就会成为画像的关键部分而对于一个以数据库查询为主的 Agent职业能力描述则更为重要。在 DB-GPT 中画像Profile对 Agent 至关重要因为它被用于影响 Agent 的行为——最终生成的系统提示词System Prompt与用户提示词User Prompt都直接来自画像。二、在自定义 Agent 中使用 ProfileConfig如果你已经阅读过 编写自定义 Agent 指南应该见过ProfileConfig的基本用法。它提供了一种最简单的方式来定义 Agent 画像只需提供name、role、goal和desc四个核心字段。from dbgpt.agent import ConversableAgent, ProfileConfig class MySummarizerAgent(ConversableAgent): profile: ProfileConfig ProfileConfig( # The name of the agent nameAristotle, # The role of the agent roleSummarizer, # The core functional goals of the agent tell LLM what it can do with it. goal( Summarize answer summaries based on user questions from provided resource information or from historical conversation memories. ), # Introduction and description of the agent, used for task assignment and display. # If it is empty, the goal content will be used. desc( You can summarize provided text content according to users questions and output the summarization. ), ) def __init__(self, **kwargs): super().__init__(**kwargs)从源码结构看ProfileConfig 是一个 PydanticBaseModel它定义了与DefaultProfile一一对应的字段并负责在create_profile()时完成校验与实例化。值得注意的是它的model_validator校验逻辑如果没有指定factory则name和role是必填项否则会抛出ValueError如果同时指定了factory与name/role则以factory生成的结果优先。三、Profile 如何生成最终 PromptProfileConfig本身只是配置真正的画像对象由create_profile()创建随后通过format_system_prompt()与format_user_prompt()两个方法渲染出最终传给 LLM 的提示词。下面我们先单独创建一个画像配置并打印它生成的 Prompt直观感受画像到 Prompt 的映射过程from dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( # The name of the agent nameAristotle, # The role of the agent roleSummarizer, # The core functional goals of the agent tell LLM what it can do with it. goal( Summarize answer summaries based on user questions from provided resource information or from historical conversation memories. ), # Introduction and description of the agent, used for task assignment and display. # If it is empty, the goal content will be used. desc( You can summarize provided text content according to users questions and output the summarization. ), ) # Create a profile from the configuration real_profile profile.create_profile() system_prompt real_profile.format_system_prompt(questionWhat can you do?) user_prompt real_profile.format_user_prompt(questionWhat can you do?) print(fSystem Prompt: \n{system_prompt}) print(# * 50) print(fUser Prompt: \n{user_prompt})运行上述代码会得到如下输出System Prompt: You are a Summarizer, named Aristotle, your goal is Summarize answer summaries based on user questions from provided resource information or from historical conversation memories.. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. *** IMPORTANT REMINDER *** Please answer in English. ################################################## User Prompt: Question: What can you do?可以看到Profile 最终被渲染进系统提示词身份声明 目标 约束引导与用户提示词携带用户问题这两段文本会被一起传给 LLM 生成响应。能够直接看到 Profile 生成的真实 Prompt在调试和理解 Agent 行为时非常有用——DB-GPT 并没有对读者隐藏这些细节。在源码中Profile 是一个抽象基类format_system_prompt()与format_user_prompt()内部统一调用_format_prompt()完成渲染。_format_prompt()会把画像中的role、name、goal、constraints、examples、expand_prompt等字段填充进模板并通过find_undeclared_variables解析模板中的变量只保留模板真正引用的字段进行渲染避免多余变量干扰。四、ProfileConfig 全参数详解与完整示例官方文档 Profile Creation 详细列出了ProfileConfig支持的完整参数参数作用nameAgent 的名字。roleAgent 扮演的角色。goalAgent 的核心功能目标告诉 LLM 它能做什么。descAgent 的介绍与描述用于任务分配和展示为空时自动使用goal内容。constraints约束列表可包含多条约束与推理限制逻辑。expand_prompt追加到 Prompt 中的扩展文本可传入自定义内容。examplesPrompt 中的示例少样本示例。下面是一个包含全部核心参数的完整示例from dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( # The name of the agent nameAristotle, # The role of the agent roleSummarizer, # The core functional goals of the agent tell LLM what it can do with it. goal( Summarize answer summaries based on user questions from provided resource information or from historical conversation memories. ), # Constraints of the agent constraints[ Prioritize the summary of answers to user questions from the improved resource text. If no relevant information is found, summarize it from the historical dialogue memory given. It is forbidden to make up your own., You need to first detect users question that you need to answer with your summarization., Extract the provided text content used for summarization., Then you need to summarize the extracted text content., Output the content of summarization ONLY related to users question. The output language must be the same to users question language., If you think the provided text content is not related to user questions at all, ONLY output Did not find the information you want.!!., ], # Introduction and description of the agent, used for task assignment and display. # If it is empty, the goal content will be used. desc( You can summarize provided text content according to users questions and output the summarization. ), expand_promptKeep your answer concise, # Some examples in your prompt examples )可以看到上面的示例在画像中加入了constraints约束与expand_prompt扩展提示。继续生成并打印 Promptreal_profile profile.create_profile() system_prompt real_profile.format_system_prompt(questionWhat can you do?) user_prompt real_profile.format_user_prompt(questionWhat can you do?) print(fSystem Prompt: \n{system_prompt}) print(# * 50) print(fUser Prompt: \n{user_prompt})输出如下System Prompt: You are a Summarizer, named Aristotle, your goal is Summarize answer summaries based on user questions from provided resource information or from historical conversation memories.. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. Keep your answer concise *** IMPORTANT REMINDER *** Please answer in English. 1. Prioritize the summary of answers to user questions from the improved resource text. If no relevant information is found, summarize it from the historical dialogue memory given. It is forbidden to make up your own. 2. You need to first detect users question that you need to answer with your summarization. 3. Extract the provided text content used for summarization. 4. Then you need to summarize the extracted text content. 5. Output the content of summarization ONLY related to users question. The output language must be the same to users question language. 6. If you think the provided text content is not related to user questions at all, ONLY output Did not find the information you want.!!. ################################################## User Prompt: Question: What can you do?对比上一节可以看出expand_prompt的内容Keep your answer concise被插入到 IMPORTANT REMINDER 之前constraints列表则被逐条编号渲染在 IMPORTANT REMINDER 之后形成一组明确的硬性行为规范。这种目标 约束 扩展说明 示例的组合正是用 Prompt 工程约束 LLM 行为的核心手段。此外在 编写自定义 Agent 指南 中还提到一个进阶用法constraints支持使用参数模板{{ param_name }}例如... ONLY output {{ not_related_message }}!!.并通过重写_init_reply_message()在对话上下文中注入reply_message.context {not_related_message: NOT_RELATED_MESSAGE}来填充动态参数——这为约束带来了运行时变量能力。五、使用 ProfileFactory 批量创建画像当需要为大量 Agent例如上千个角色场景定义画像时逐个手写ProfileConfig字段并不现实。ProfileFactory提供了更灵活的方式。5.1 自定义 ProfileFactoryfrom typing import Optional from dbgpt.agent import ProfileFactory, Profile, DefaultProfile class MyProfileFactory(ProfileFactory): def create_profile( self, profile_id: int, name: Optional[str] None, role: Optional[str] None, goal: Optional[str] None, prefer_prompt_language: Optional[str] None, prefer_model: Optional[str] None, ) - Optional[Profile]: return DefaultProfile( nameAristotle, roleSummarizer, goal( Summarize answer summaries based on user questions from provided resource information or from historical conversation memories. ), desc( You can summarize provided text content according to users questions and output the summarization. ), expand_promptKeep your answer concise, examples )5.2 使用 ProfileFactory使用工厂时只需将工厂实例传入ProfileConfig无需再提供name、role、goal和descfrom dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( factoryMyProfileFactory(), )同样生成并打印 Promptreal_profile profile.create_profile() system_prompt real_profile.format_system_prompt(questionWhat can you do?) user_prompt real_profile.format_user_prompt(questionWhat can you do?) print(fSystem Prompt: \n{system_prompt}) print(# * 50) print(fUser Prompt: \n{user_prompt})输出System Prompt: You are a Summarizer, named Aristotle, your goal is Summarize answer summaries based on user questions from provided resource information or from historical conversation memories.. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. Keep your answer concise *** IMPORTANT REMINDER *** Please answer in English. ################################################## User Prompt: Question: What can you do?从 ProfileFactory 的源码结构看它是定义画像创建接口的抽象基类create_profile()接收profile_id、name、role、goal、prefer_prompt_language、prefer_model等参数返回一个Profile实例。仓库中还预置了几种工厂扩展方向当前源码标注为 TODO尚未完整实现LLMProfileFactory基于 LLM 自动生成画像。思路是先明确生成规则与目标群体的 Agent 配置构成和属性再给出少量样本最后让 LLM 批量生成所有 Agent 的配置DatasetProfileFactory基于数据集生成画像。当数据集中包含大量关于真实人物的信息时先将其整理为自然语言提示再用于生成 Agent 配置CompositeProfileFactory组合多个ProfileFactory支持把多种画像生成策略串联使用。ProfileConfig.create_profile()的调用优先级为若传入了factory先尝试用工厂生成工厂返回非空则直接使用工厂结果否则回退到基于字段构造DefaultProfile。六、Profile 到 PromptJinja2 模板机制前面的示例都使用了内部默认模板。官方文档 Profile To Prompt 专门讲解了模板机制DB-GPT 的 Agent 使用 Jinja2 模板渲染提示词原因在于 Jinja2 简洁且灵活。6.1 查看默认模板from dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( # The name of the agent nameAristotle, # The role of the agent roleSummarizer, # The core functional goals of the agent tell LLM what it can do with it. goal( Summarize answer summaries based on user questions from provided resource information or from historical conversation memories. ), # Introduction and description of the agent, used for task assignment and display. # If it is empty, the goal content will be used. desc( You can summarize provided text content according to users questions and output the summarization. ), ) real_profile profile.create_profile() print(fSystem Prompt Template: \n{real_profile.get_system_prompt_template()}) print(# * 50) print(fUser Prompt Template: \n{real_profile.get_user_prompt_template()})输出System Prompt Template: You are a {{ role }}, {% if name %}named {{ name }}, {% endif %}your goal is {{ goal }}. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. {% if resource_prompt %}{{ resource_prompt }} {% endif %}{% if expand_prompt %}{{ expand_prompt }} {% endif %} *** IMPORTANT REMINDER *** {% if language zh %}Please answer in simplified Chinese. {% else %}Please answer in English. {% endif %} {% if constraints %}{% for constraint in constraints %}{{ loop.index }}. {{ constraint }} {% endfor %}{% endif %} {% if examples %}You can refer to the following examples: {{ examples }}{% endif %} {% if out_schema %} {{ out_schema }} {% endif %} ################################################## User Prompt Template: {% if most_recent_memories %}Most recent observations: {{ most_recent_memories }} {% endif %} {% if question %}Question: {{ question }} {% endif %}可以看到模板中使用了丰富的 Jinja2 条件与循环指令条件渲染{% if name %}、{% if resource_prompt %}、{% if expand_prompt %}等保证缺失字段不会产生空占位语言分支{% if language zh %}决定回复使用简体中文还是英文约束编号{% for constraint in constraints %}{{ loop.index }}. {{ constraint }}把约束列表自动编号记忆注入most_recent_memories用于把最近的记忆/观察注入用户提示词输出结构out_schema用于追加输出格式约束。在源码 base.py 中_DEFAULT_SYSTEM_TEMPLATE与_DEFAULT_USER_TEMPLATE分别定义了英文默认模板同时还有对应的中文版本_DEFAULT_SYSTEM_TEMPLATE_ZH与_DEFAULT_USER_TEMPLATE_ZH如你是一个 {{ role }}, 名字叫 {{ name }}...请用简体中文进行回答DefaultProfile与ProfileConfig都内置了这些默认值。当前仓库中的系统模板还进一步包含了重试目标retry_goal/retry_constraints、now_time时间注入以及工具调用约束等字段这些额外能力同样通过is_retry_chat等变量在模板中条件渲染。此外Profile 接口还暴露了get_write_memory_template()用于定义记忆写入模板将question、thought、action、observation组织成结构化记忆说明 Profile 系统不仅服务于对话 Prompt也深度参与了记忆模块的数据组织。6.2 使用自定义 Prompt 模板如果默认模板无法满足业务需求可以直接为ProfileConfig传入自定义的system_prompt_template与user_prompt_template。首先创建简单的系统提示词模板与用户提示词模板my_system_prompt_template \ You are a {{ role }}, {% if name %}named {{ name }}, {% endif %}your goal is {{ goal }}. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. *** IMPORTANT REMINDER *** {% if language zh %}\ Please answer in simplified Chinese. {% else %}\ Please answer in English. {% endif %}\ # noqa my_user_prompt_template User question: {{ question }}然后在创建 Profile 时传入自定义模板from dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( # The name of the agent nameAristotle, # The role of the agent roleSummarizer, # The core functional goals of the agent tell LLM what it can do with it. goal( Summarize answer summaries based on user questions from provided resource information or from historical conversation memories. ), # Introduction and description of the agent, used for task assignment and display. # If it is empty, the goal content will be used. desc( You can summarize provided text content according to users questions and output the summarization. ), system_prompt_templatemy_system_prompt_template, user_prompt_templatemy_user_prompt_template, ) real_profile profile.create_profile() system_prompt real_profile.format_system_prompt(questionWhat can you do?) user_prompt real_profile.format_user_prompt(questionWhat can you do?) print(fSystem Prompt: \n{system_prompt}) print(# * 50) print(fUser Prompt: \n{user_prompt})输出System Prompt: You are a Summarizer, named Aristotle, your goal is Summarize answer summaries based on user questions from provided resource information or from historical conversation memories.. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. *** IMPORTANT REMINDER *** Please answer in English. ################################################## User Prompt: User question: What can you do?用户提示词被替换成了自定义格式User question: ...系统提示词也被裁剪成了精简版。这种完全可控的模板替换能力使得开发者可以为不同 Agent 设计完全不同的提示词风格与结构。在实现层面ProfileConfig 的system_prompt_template、user_prompt_template、write_memory_template字段默认值分别对应上述三个内置模板渲染时使用SandboxedEnvironmentJinja2 沙箱环境以保证模板执行安全并通过find_undeclared_variables只填充模板中实际声明的变量。七、动态画像用 DynConfig 让字段随环境变化前几节创建的都是静态画像——字段值在代码中写死。但在某些场景下你可能希望只修改画像的一部分字段例如根据部署环境动态切换 Agent 名字。官方文档 Dynamic Profile 介绍了使用DynConfig创建动态画像的方法。7.1 基本用法创建一个名为profile_dynamic.py的文件写入以下代码from dbgpt.agent import ProfileConfig, DynConfig profile: ProfileConfig ProfileConfig( # The name of the agent nameDynConfig( Aristotle, keysummary_profile_name, providerenv ), # The role of the agent roleSummarizer, )在上面的示例中name字段使用DynConfig包装默认值是Aristotle配置键为summary_profile_nameproviderenv表示该字段的值将从环境变量中读取。7.2 未设置环境变量时python profile_dynamic.py输出System Prompt: You are a Summarizer, named Aristotle, your goal is None. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. *** IMPORTANT REMINDER *** Please answer in English. ################################################## User Prompt: Question: What can you do?由于没有设置环境变量DynConfig回退到默认值Aristotle。7.3 设置环境变量后summary_profile_namePlato python profile_dynamic.py输出System Prompt: You are a Summarizer, named Plato, your goal is None. Please think step by step to achieve the goal. You can use the resources given below. At the same time, please strictly abide by the constraints and specifications in IMPORTANT REMINDER. *** IMPORTANT REMINDER *** Please answer in English. ################################################## User Prompt: Question: What can you do?Agent 的名字从Aristotle动态切换为Plato——同一个 Agent 代码仅通过环境变量即可改变身份非常适合多租户、多环境部署或大规模角色批量配置的场景。7.4 底层原理DynConfig实现在 configure/base.py它是一个返回ConfigInfo的工厂函数核心参数包括default默认值key配置键provider配置来源支持ProviderType.ENV环境变量、ProviderType.PROMPT_MANAGER或自定义ConfigProvider实例当category ConfigCategory.AGENT且未指定 provider 时默认使用PROMPT_MANAGERis_list是否为列表值列表场景下使用separator默认[LIST_SEP]拆分字符串description配置说明。ConfigInfo.query() 的取值逻辑为若key为空则直接返回默认值否则根据 provider 类型分别从环境变量EnvironmentConfigProvider或 Prompt 管理器PromptManagerConfigProvider查询查询结果为空时回退默认值最后按需用separator拆分成列表。回到 Profile 层面ProfileConfig 的所有字段name、role、goal、constraints、desc、expand_prompt、examples乃至三个模板字段都声明为str | ConfigInfo | None类型在create_profile()中会统一检查若字段是ConfigInfo实例则调用query()解析出真实值再构造DefaultProfile。这也解释了为什么nameDynConfig(...)可以无缝嵌入ProfileConfig。八、进阶阅读与源码导航本模块的完整知识脉络如下画像核心文档Profiling Module 主文档画像创建方式Profile CreationProfileConfig全参数 ProfileFactory模板渲染机制Profile To Prompt默认/自定义 Jinja2 模板动态画像Dynamic ProfileDynConfig环境变量注入画像与自定义 Agent 的完整结合Write Your Custom Agent约束模板参数、Action 绑定、正确性校验对应的核心源码实现位于Profile 抽象接口与 DefaultProfile 实现Profile接口get_name/get_role/get_goal/get_constraints/get_examples等与DefaultProfile数据模型ProfileFactory 及三种扩展工厂ProfileFactory、LLMProfileFactory、DatasetProfileFactory、CompositeProfileFactoryProfileConfig 配置入口字段定义、校验逻辑与create_profile()实例化流程DynConfig/ConfigInfo 动态配置环境变量与 Prompt 管理器两种取值 provider 的底层实现。需要提醒的是Profile 生成的最终提示词在仓库不同版本中可能存在差异例如系统模板中的工具调用约束、重试目标、当前时间等字段以上默认模板展示以当前仓库源码为准若升级版本建议通过real_profile.get_system_prompt_template()打印实际模板避免依赖过时的输出格式假设。【免费下载链接】DB-GPTopen-source agentic AI data assistant for the next generation of AI Data products.项目地址: https://gitcode.com/GitHub_Trending/db/DB-GPT创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考