我如何让 AI 根据对话上下文表现不同(Multi-Role Prompt Engineering)
发布: (2026年5月9日 GMT+8 16:35)
4 分钟阅读
原文: Dev.to
Source: Dev.to
简单角色提示的问题
如果你仅仅在不同的提示中告诉 AI “你是角色 A” 和 “你是角色 B”,它们最终都会听起来一样:通用、乐于助人且乏味。要实现不同的行为,仅靠形容词是不够的。
不佳示例
You are a friendly witness who is helpful.
更佳示例
You are a witness being questioned. Rules:
- Only answer what is directly asked.
- If the question is vague, ask for clarification.
- Never volunteer extra information.
- If pressed on a contradiction, become defensive.
约束条件比单纯的性格描述能产生更一致的行为。
使用模式参数切换行为
同一个角色可能需要根据与之交谈的人不同而表现不同。我通过在系统提示中传入 mode 参数来实现。
function buildPrompt(
character: Character,
mode: 'friendly' | 'hostile'
) {
const base = `You are ${character.name}. Background: ${character.bio}`;
if (mode === 'friendly') {
return `${base}\n\nBehavior: Be cooperative. Give detailed answers. Expand on your responses when appropriate.`;
} else {
return `${base}\n\nBehavior: Be defensive. Give minimal answers. Only confirm what you cannot deny. Redirect when possible.`;
}
}
这个小小的切换会让回复的自然度产生巨大的差异。
在多轮对话中保持上下文
最难的部分是让角色记住之前发生的事情并作出相应调整。我维护一个简化的状态对象,并在每次调用 AI 前注入一个摘要。
interface ConversationState {
currentSpeaker: string;
previousStatements: string[];
contradictions: string[];
mood: 'neutral' | 'defensive' | 'confident';
}
通过对当前对话进行摘要,回复能够保持上下文感知,同时不会导致 token 数量激增。
覆盖模型默认的“乐于助人助理”模式
大语言模型被训练成乐于助人。当你需要角色回避或不提供帮助时,需要与这种训练抗争。
有效做法
- 明确说明角色 不想帮助 提问者。
- 为角色设定一个难以合作的动机。
- 在提示中加入转移话题的示例。
You are being questioned about something you want to hide.
Your goal is to answer without revealing [specific fact].
Techniques you use: giving technically true but misleading answers,
answering a different question than what was asked, saying "I don't recall."
不同原型的温度设置
- 权威角色(法官、专家):使用较低温度(0.3–0.5),以确保一致性和果断性。
- 情感丰富或不可预测的角色:使用较高温度(0.7–0.9),增加随机性,使其更具人性化。
要点
多角色 AI 并非只在于写更好的角色描述,而是关于:
- 定义明确的行为规则。
- 在每轮对话中注入恰当的上下文。
- 主动抵消模型默认的乐于助人倾向。
一旦我弄清这些,所有东西都顺畅起来。
很想了解是否还有其他人在做多代理工作——你们使用了哪些模式?