Safe reflection pattern

Prevents subject confusion in responses

Problem

Eliza-style agents reflect user input back in their responses — if the user says “I feel sad,” the agent might respond “You feel sad.” This requires transforming first-person pronouns to second-person and vice versa. Naively substituting pronouns in captured regex groups produces grammatically wrong or semantically confusing output: reflecting “my dog” as “your dog” is correct, but reflecting “myself” as “yourself” may sound odd, and reflecting compound structures can introduce subject/object inversions that break the response entirely.

Solution

Apply a pronoun reflection map before inserting captured text into a response template. The map handles common first-person to second-person transformations. Wrap substitution in a sanitization step that strips or normalizes edge cases — possessives, reflexives, and contractions — before the reflected phrase is embedded in the output.

const reflectionMap: Record<string, string> = {
  "i am": "you are",
  "i'm": "you're",
  "i was": "you were",
  "i": "you",
  "me": "you",
  "my": "your",
  "myself": "yourself",
  "mine": "yours",
};
 
function reflect(text: string): string {
  return text
    .toLowerCase()
    .split(/\b/)
    .map((token) => reflectionMap[token] ?? token)
    .join("");
}

The agent applies reflect() to any captured group before substituting it into the response template, ensuring the reflected phrase is grammatically appropriate.

Usage

Essential for any agent that mirrors user language back in its responses. Apply when:

  • Response templates include $1, $2, or similar placeholders filled from user input
  • The agent is designed to appear empathetic or Rogerian (reflecting feelings back)
  • Pronoun confusion would undermine the conversational illusion

Not needed for purely generative responses where the agent composes its own sentences without incorporating user text directly.

Trade-offs

  • Pro: Prevents the most common and jarring reflection errors with a single lookup table that is easy to extend.
  • Pro: The reflection map is declarative — adding new transformation pairs requires no logic changes.
  • Con: Word-boundary tokenization fails on contractions and possessives in some locales. A production system needs more robust tokenization.
  • Con: The map covers English only. Multi-language agents require per-language reflection maps with substantially more complexity.

See Also

Source

Synced from ops-core learning data. Original source: Eliza