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 开源仓库中的 Profiling 模块为核心系统讲解 Agent 角色画像的设计思路如何通过ProfileConfig与ProfileFactory定义 Agent 的身份、角色、目标与约束如何用DynConfig实现动态画像以及画像数据如何被 Jinja2 模板渲染为真正发给 LLM 的 System/User Prompt。读完本文你将掌握自定义 Agent 画像的三种创建方式、默认提示词模板的内部结构以及如何替换自定义模板能够独立为各类业务场景设计可复用的 Agent 角色。Profiling 模块是什么在 Multi-Agent 系统中Agent 通常需要扮演特定角色来完成任务例如程序员coder、教师teacher、领域专家domain expert等。Profiling 模块角色画像模块的职责就是刻画 Agent 的角色画像并将这些画像信息写入 Prompt从而影响 LLM 的行为表现。从仓库中 Profiling 模块的模块说明profile/init.py可以看到Agent 画像一般涵盖三类信息基本信息如年龄、性别、职业等心理信息反映 Agent 的人格特征personality社会信息描述 Agent 之间的关系。具体选取哪些信息来刻画 Agent主要取决于应用场景。例如若应用目标是研究人类认知过程那么心理信息就变得至关重要。这也是画像设计场景驱动原则的体现。DB-GPT Agents 中的 Profile在 DB-GPT 的 Agent 体系中Profile 是影响 Agent 行为的核心要素——它决定了 Agent 以什么身份、按什么目标、受什么约束去执行任务。在编写自定义 Agent一节中你已经见过一个最基本的 Profile 使用示例通过继承ConversableAgent并用类属性profile: ProfileConfig声明画像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)这里只提供了name名字、role角色、goal核心目标、desc描述四个字段ProfileConfig就会据此自动完成画像配置。这也是最推荐的自定义方式。画像如何变成 Prompt先看一份真实输出配置好画像后最终要落到 LLM 可读的 Prompt 上。DB-GPT 提供了两个关键方法让你看见画像生成的完整 Prompt这对于调试和理解 Agent 行为极其有用——仓库在设计上刻意不向你隐藏内部细节。先单独创建一个 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. ), ) # 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})运行上述代码将生成如下 PromptSystem 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?可以看到name、role、goal被渲染进了 System Prompt而传入的question被渲染进 User Prompt。这两个 Prompt 最终会被一起发给 LLM 用于生成回复。从源码看这条链路的核心实现在 profile/base.pyProfileConfig.create_profile()把配置解析为一个Profile对象默认返回DefaultProfileProfile.format_system_prompt(...)/format_user_prompt(...)基于默认或自定义模板把role、name、goal、constraints、question、language等变量填充进 Jinja2 模板渲染前还会对模板做变量解析find_undeclared_variables只保留模板中实际声明过的变量参与渲染同时支持对role、name、goal、expand_prompt、constraints等字段做子模板二次渲染即字段值本身也可以包含{{ param }}占位符。ProfileConfig 参数详解ProfileConfig是定义 Agent 画像的最简单方式。根据源码 base.py 中ProfileConfig的字段定义它支持以下参数参数类型说明profile_idint画像 ID默认 0用于标识与缓存画像namestr/ConfigInfoAgent 的名字必填除非指定factoryrolestr/ConfigInfoAgent 的角色必填除非指定factorygoalstr/ConfigInfoAgent 的核心功能目标告诉 LLM 它能做什么retry_goalstr/ConfigInfo重试场景下使用的目标配合is_retry_chatconstraintsList[str]/ConfigInfo约束与推理限制逻辑可包含多条retry_constraintsList[str]/ConfigInfo重试场景下使用的约束列表descstr/ConfigInfoAgent 的介绍与描述用于任务分配和展示注意desc 不会参与 Prompt 生成为空时使用 goal 内容expand_promptstr/ConfigInfo追加到 Prompt 中的自定义扩展文本examplesstr/ConfigInfo注入 Prompt 的示例few-shotsystem_prompt_templatestr/ConfigInfoSystem Prompt 模板默认内置模板user_prompt_templatestr/ConfigInfoUser Prompt 模板默认内置模板write_memory_templatestr/ConfigInfo写记忆时的模板factoryProfileFactory画像工厂用于更灵活的画像创建可选值得注意的是ProfileConfig在构造时会做一次前置校验check_before如果未指定factory则name与role必须提供否则抛出ValueError如果同时指定了factory和name/role则以factory的创建结果为准。带约束与扩展文本的完整示例以下是一个包含constraints与expand_prompt的完整ProfileConfig示例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 )这段配置生成的 System Prompt 会多出两部分expand_prompt追加在主体之后、IMPORTANT REMINDER之前constraints则以编号列表的形式渲染在IMPORTANT REMINDER之后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?约束中支持参数模板constraints里的每一条都支持使用{{ param_name }}参数模板见 custom_agents.md。例如把固定文案改成占位符constraints[ ... If you think the provided text content is not related to user questions at all, ONLY output {{ not_related_message }}!!., ],此时需要在 Agent 中重载_init_reply_message在对话开始时把动态参数写入上下文from dbgpt.agent import AgentMessage, ConversableAgent, ProfileConfig NOT_RELATED_MESSAGE Did not find the information you want. class MySummarizerAgent(ConversableAgent): profile: ProfileConfig ProfileConfig(...) def _init_reply_message(self, received_message: AgentMessage) - AgentMessage: reply_message super()._init_reply_message(received_message) # Fill in the dynamic parameters in the prompt template reply_message.context {not_related_message: NOT_RELATED_MESSAGE} return reply_message默认 Prompt 模板的内部结构在生成上述输出时DB-GPT 内部使用的是一套内置的 Jinja2 模板。你可以通过get_system_prompt_template()与get_user_prompt_template()把模板打印出来查看from dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( 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. ), ) 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 模板。仓库当前在 Agent 领域统一采用 Jinja2看重的是它的简洁与灵活。结合源码 base.py默认模板_DEFAULT_SYSTEM_TEMPLATE与_DEFAULT_USER_TEMPLATE中可用的变量在白名单VALID_TEMPLATE_KEYS中列出共 11 个role、name、goal、resource_prompt、expand_prompt、language、constraints、examples、out_schema、most_recent_memories、question。另有与重试机制相关的is_retry_chat、retry_goal、retry_constraints以及渲染时注入的当前时间now_time。同时仓库还内置了完整的中文模板_DEFAULT_SYSTEM_TEMPLATE_ZH与_DEFAULT_USER_TEMPLATE_ZH当prefer_prompt_language为中文时create_profile会自动把默认模板切换为中文版本见 base.py例如请用简体中文进行回答、当前时间是:{{now_time}}并附带 DB-GPT 特有的工具调用约束所有工具调用必须经由 ToolExpert Agent。这在构建中文 Agent 应用时非常实用。各模板变量的实际取值来自_format_prompt见 base.py拼接的上下文role/name/goal/constraints等来自Profile的 getter 方法most_recent_memories来自记忆系统question是用户问题resource_vars是资源如检索工具、知识库注入的额外变量。使用自定义 Prompt 模板内置模板不能满足需求时你可以完全替换 System/User Prompt 模板。首先定义自己的模板字符串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 }}然后通过system_prompt_template与user_prompt_template参数把它绑定到 Profilefrom dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( 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. ), 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})运行结果中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?方法二使用 ProfileFactory 创建画像当需要批量、按规则或按数据驱动的方式生成画像时例如要构建上千个不同角色 Agent 的场景可以使用ProfileFactory。这是比手写ProfileConfig更灵活的方案。创建自定义 Factory继承ProfileFactory并实现create_profile抽象方法from 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 )把 Factory 交给 ProfileConfig使用 Factory 时不再需要提供name、role、goal、descfrom dbgpt.agent import ProfileConfig profile: ProfileConfig ProfileConfig( factoryMyProfileFactory(), )生成 Prompt 的方式与前文一致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. Keep your answer concise *** IMPORTANT REMINDER *** Please answer in English. ################################################## User Prompt: Question: What can you do?仓库内置的 Factory 体系从源码 base.py 可以看到仓库为画像从哪来设计了一整套可扩展的工厂体系ProfileFactory抽象基类定义create_profile(profile_id, name, role, goal, prefer_prompt_language, prefer_model)接口LLMProfileFactory由 LLM 自动生成画像——先指定目标人群的生成规则与 Agent 配置构成再给少量样本最后由 LLM 批量产出所有 Agent 的配置DatasetProfileFactory基于现有数据集生成画像——把数据集中关于真实人物的信息整理成自然语言 Prompt再据此生成 Agent 配置CompositeProfileFactory组合多个 Factory 协同创建画像。需要说明的是目前LLMProfileFactory、DatasetProfileFactory、CompositeProfileFactory的create_profile在源码中仍标记为TODO未实现具体逻辑但接口与扩展点已经就绪开发者可以在MyProfileFactory中实现自己的生成规则。从模块文档profile/init.py看画像的创建方式明确包含三种手工创建Handcrafting、LLM 生成LLM-generation、数据集对齐Dataset alignment与上述工厂一一对应。动态画像用 DynConfig 按需覆盖字段有些场景下你只想局部修改画像的某个字段例如不同部署环境使用不同名字不必重新定义整个 Profile。此时可以使用DynConfig实现动态画像。创建文件profile_dynamic.pyfrom 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, )这里用DynConfig声明了一个动态字段name默认值是Aristotle配置键key是summary_profile_nameproviderenv表示该字段的值会从环境变量读取。然后照常生成 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})不设置环境变量时python profile_dynamic.py输出中name使用默认值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?设置环境变量后summary_profile_namePlato python profile_dynamic.py输出中name被环境变量覆盖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?DynConfig 的底层机制DynConfig的实现在 packages/dbgpt-core/src/dbgpt/util/configure/base.py它本质上是一个返回ConfigInfo对象的工厂函数。ConfigInfo.query()的逻辑如下未指定key时直接返回default指定了key时根据provider选择配置源ProviderType.ENVenv→ 读取环境变量os.environ.get(key)ProviderType.PROMPT_MANAGERprompt_manager→ 从 DB-GPT 的 Prompt Manager 服务查询仅 Web 服务运行时有效可用于按prefer_prompt_language、prefer_model等偏好查询多语言/多模型提示词查询结果为None时回退到default若is_listTrue且值为字符串则按separator默认[LIST_SEP]切分为列表。另外DynConfig在category为ConfigCategory.AGENT且未显式指定 provider 时会默认使用prompt_manager——这意味着 Agent 画像字段天然支持接入提示词管理平台进行版本化维护。目前DynConfig仅支持获取字符串或字符串列表值。ProfileConfig的所有字段name、role、goal、constraints、desc、expand_prompt、examples、三个模板等都通过DynConfig声明因此任意画像字段都可以被动态覆盖。仓库中大量内置扩展 Agent如 summary_assistant_agent.py、data_analysis_agent.py 等正是利用这一机制来复用画像配置。把画像接入真实对话一个完整的自定义 Agent画像最终服务于真实对话。下面把以上内容串起来定义一个带画像的自定义 Summarizer Agent绑定 LLM 后通过UserProxyAgent发起对话。完整可运行代码可参考 custom_agents.md其核心运行骨架如下import asyncio import os from dbgpt.agent import AgentContext, ConversableAgent, AgentMemory, LLMConfig, UserProxyAgent from dbgpt.model.proxy import OpenAILLMClient class MySummarizerAgent(ConversableAgent): ... async def main(): llm_client OpenAILLMClient( model_aliasgpt-3.5-turbo, # or other models, eg. gpt-4o api_baseos.getenv(OPENAI_API_BASE), api_keyos.getenv(OPENAI_API_KEY), ) context: AgentContext AgentContext(conv_idsummarize) agent_memory: AgentMemory AgentMemory() agent_memory.gpts_memory.init(conv_idsummarize) summarizer ( await MySummarizerAgent() .bind(context) .bind(LLMConfig(llm_clientllm_client)) .bind(agent_memory) .build() ) user_proxy await UserProxyAgent().bind(agent_memory).bind(context).build() await user_proxy.initiate_chat( recipientsummarizer, revieweruser_proxy, messageI want to summarize advantages of Nuclear Power according to the following content. ..., ) print(await agent_memory.gpts_memory.app_link_chat_message(summarize)) if __name__ __main__: asyncio.run(main())关键点Agent 通过.bind(context)、.bind(LLMConfig(...))、.bind(agent_memory)、.build()完成初始化装配UserProxyAgent代表用户发起对话initiate_chat的message会被送入对话流画像字段name/role/goal/constraints已由ProfileConfig在构建时写入 System Prompt最终随每次对话生效对话记录可经agent_memory.gpts_memory.app_link_chat_message(conv_id)取回查看。总结与下一步在 DB-GPT 的 Agent 体系中Profiling 模块承担着定义 Agent 是谁、要做什么、受什么约束的核心职责并把这份画像通过 Jinja2 模板渲染成真实 Prompt直接影响 LLM 的输出行为。你可以用ProfileConfig手写画像推荐入门支持name/role/goal/constraints/desc/expand_prompt/examples及自定义模板等字段用ProfileFactory含DefaultProfile与内置扩展体系按规则批量创建画像适合大规模多 Agent 场景用DynConfig把任意画像字段动态化从环境变量或 Prompt Manager 读取配置实现按环境、按语言的灵活覆盖通过get_system_prompt_template()/format_system_prompt()等接口完全掌握并自定义最终 Prompt 的形态。想要继续深入可以阅读同目录的系列文档画像创建的更多方式profile_creation.md画像如何转换为 LLM Promptprofile_to_prompt.md动态画像的完整实践profile_dynamic.md自定义 Agent 的完整流程custom_agents.md源码层面画像模块的全部实现集中在 packages/dbgpt-core/src/dbgpt/agent/core/profile/base.py动态配置机制在 packages/dbgpt-core/src/dbgpt/util/configure/base.py模块导出与设计说明见 profile/init.py可供进一步阅读与二次开发。【免费下载链接】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),仅供参考