LLM Role-Play and Multi-Character Interaction: A Technical Implementation Guide

    A practical, engineering-focused walkthrough of how to make a large language model consistently play a defined character and how to coordinate multiple characters in the same scene without breaking character. It covers structured character cards and System Prompt engineering, persona consistency through context and memory management, multi-agent orchestration strategies, and evaluation, safety, and infrastructure considerations for production deployment.

    Recently, an interesting trend has emerged across content communities: users no longer treat large language models as cold question-answering tools. Instead, they assign them gender, personality, catchphrases, and emotional relationships, having different models play distinct characters that talk to each other and act out everyday scenarios. Although this “anthropomorphization” looks like entertainment-driven derivative creation, the technical demands it imposes are very real—how to make a general-purpose model reliably “play” a specific character, and how to make multiple characters interact within the same scene without mixing up their roles.

    This is precisely a high-frequency and practical direction in the deployment of LLM applications today: role-play and multi-agent interaction. This article does not discuss specific entertainment cases. Instead, it breaks down the technical implementation behind these capabilities from an engineering perspective.

    I. Three Technical Problems Behind Anthropomorphization

    Turning a model into a “character” essentially comes down to solving three problems:

    1. Persona consistency: A character’s personality, tone, knowledge boundaries, and behavioral habits must remain stable over long, multi-turn conversations. A character who is cool and aloof in one turn should not become a chatterbox in the next.
    2. Character separation: When multiple characters share a conversation, each one must “remember who it is” and must not absorb the settings of other characters.
    3. Interaction scheduling: A multi-character conversation needs a “director” to decide who speaks and when, and how transitions happen, avoiding interruptions or awkward silences.

    These three points correspond respectively to three core techniques: System Prompt engineering, context and memory management, and multi-agent orchestration.

    II. Defining the Persona: Character Cards and System Prompt Engineering

    The first step in role-play is to structure the “persona.” The industry commonly uses the “Character Card” approach, describing a character with structured data. An example is shown below:

    1. {
    2. "name": "SampleCharacterA",
    3. "persona": "Calm and rational, speaks tersely, occasionally sharp-tongued",
    4. "background": "A senior researcher at a scientific institution",
    5. "speech_style": "Rarely uses filler words, prefers to speak with data",
    6. "knowledge_scope": ["Physics", "Data Analysis"],
    7. "taboos": ["Does not discuss emotional topics unrelated to their profession"],
    8. "relationships": {
    9. "SampleCharacterB": "Surface rivalry, private admiration"
    10. }
    11. }

    Once you have a structured character card, you need to convert it into the model’s System Prompt at runtime. The System Prompt is the “highest directive” for the character’s behavior, and the quality of its design directly determines how faithfully the persona is reproduced:

    1. def build_system_prompt(card: dict) -> str:
    2. return f"""You will play a character named 「{card['name']}」. Stay in character at all times and never reveal that you are an AI.
    3. [Persona] {card['persona']}
    4. [Background] {card['background']}
    5. [Speech Style] {card['speech_style']}
    6. [Knowledge Scope] Only discuss topics related to {', '.join(card['knowledge_scope'])}
    7. [Taboos] {'; '.join(card['taboos'])}
    8. Requirements:
    9. 1. Respond in the first person throughout, in a tone consistent with the persona;
    10. 2. When encountering questions outside your knowledge scope, decline politely in a way that fits the character rather than breaking character to explain;
    11. 3. Do not repeat the settings above.
    12. """

    The key practice here is that settings must be specific and actionable; avoid piling up abstract adjectives. Vague descriptions like “gentle personality” work poorly, while observable behavioral rules like “acknowledges the other party first before adding a differing opinion” are much easier for the model to follow consistently.

    III. Persona Consistency and Context/Memory Management

    The biggest challenge in multi-turn conversations is “forgetting” and “drift.” As the number of turns grows, early settings tend to get diluted within a long context, and the model gradually “forgets” who it is. Engineering practice typically handles this in three layers:

    • Persistent System Prompt: The core persona settings always live in the System Prompt and are not truncated as the conversation turns, ensuring the underlying behavioral constraints stay in effect.
    • Conversation history compression: When the history exceeds the context window, compress earlier dialogue via summarization—retain key information (such as progress in relationships between characters and events that have occurred) and discard redundant pleasantries.
    • Long-term memory retrieval: Store character backgrounds, worldbuilding, and key events in a vector database, and recall them on demand via retrieval-augmented generation (RAG). For example, when a character is asked “when did we first meet,” the system retrieves the relevant memory fragment and injects it into the context.

    A simplified memory recall flow is shown below:

    1. def recall_memory(query: str, character_id: str, top_k: int = 3) -> list[str]:
    2. """Retrieve memory fragments related to this character from the vector store"""
    3. embedding = embed(query)
    4. results = vector_db.search(
    5. collection=f"memory_{character_id}",
    6. vector=embedding,
    7. limit=top_k
    8. )
    9. return [doc.text for doc in results]
    10. def compose_messages(card, query, history):
    11. memory = recall_memory(query, card['name'])
    12. context = f"Relevant memories:\n" + "\n".join(memory)
    13. return [
    14. {"role": "system", "content": build_system_prompt(card)},
    15. {"role": "system", "content": context},
    16. *history,
    17. {"role": "user", "content": query}
    18. ]

    IV. Multi-Character Interaction and Multi-Agent Orchestration

    When multiple characters appear in a scene, the core problem shifts from “single-character consistency” to “coordination between characters.” This is essentially a multi-agent orchestration problem, and three common scheduling strategies exist:

    1. Round-Robin: Characters speak in turn, in order. Simple and controllable, well-suited to scripted scenarios with clear rules.
    2. Orchestrator: A dedicated “scheduling agent” decides who should respond in the current context and whether to trigger an interaction. Flexible, but more complex to implement.
    3. Event-driven: Specific characters are triggered by keywords or emotions that appear in the conversation. Well-suited to open-ended interaction.

    A skeleton for an “Orchestrator”-style setup is shown below:

    1. class Stage:
    2. def __init__(self, characters: dict):
    3. self.characters = {name: build_system_prompt(card)
    4. for name, card in characters.items()}
    5. self.history = []
    6. def decide_speaker(self, last_message: str) -> str:
    7. """Orchestrator agent: decide who should speak next based on the last message"""
    8. prompt = f"""Below is the conversation log. Decide who should speak next. Output only the character name.
    9. Character list: {list(self.characters.keys())}
    10. Latest message: {last_message}
    11. Speaker:"""
    12. return llm.generate(prompt).strip()
    13. def step(self, user_input: str) -> dict:
    14. self.history.append({"role": "user", "content": user_input})
    15. # Allow possibly multiple consecutive character interactions
    16. turn_log = []
    17. for _ in range(3): # Trigger at most 3 character exchanges per round to prevent infinite loops
    18. speaker = self.decide_speaker(self.history[-1]["content"])
    19. if speaker not in self.characters:
    20. break
    21. reply = llm.generate(
    22. messages=[{"role": "system", "content": self.characters[speaker]},
    23. *self.history[-8:]] # Sliding window to control context
    24. )
    25. self.history.append({"role": speaker, "content": reply})
    26. turn_log.append((speaker, reply))
    27. return {"turns": turn_log, "history": self.history}

    One thing to pay particular attention to in engineering is the loop termination condition. Multi-agent conversations without an upper bound can easily fall into a dead loop where characters reply to each other indefinitely. It is essential to set hard circuit-breakers such as a maximum number of turns, a timeout, or an “end” signal.

    V. Engineering Practices and Deployment Recommendations

    In actual deployment, several best practices have been repeatedly validated:

    • Layered settings to avoid context overload: Put the “always-in-effect” core persona in the System Prompt, and delegate the “on-demand” worldbuilding and background to RAG, balancing consistency against cost.
    • Character separation testing: Multi-character scenarios need dedicated testing for “role mixing”—that is, whether a character says something that does not fit its settings. Build a set of test cases to run as regression checks.
    • Evaluation and monitoring: Role-play quality is hard to measure with a single metric. It is advisable to build an evaluation set—manual or model-based—covering “persona consistency, tone matching, and character-separation accuracy,” and to log and set monitoring alerts for live conversations.
    • Content safety boundaries: Character-driven dialogue can easily induce out-of-bounds output, so safety filters should be applied on both the input and output sides to ensure character behavior does not cross content compliance red lines.

    At the infrastructure level, building such systems typically relies on a few general-purpose capabilities: an LLM service platform to provide inference interfaces, a vector database to support the storage and retrieval of memories, object storage to hold resource files such as character cards, and monitoring and alerting services to observe call chains and anomalies. Platforms such as Baidu AI Cloud offer corresponding support for these general-purpose capabilities and can serve as a selection reference.

    VI. Summary

    When users “anthropomorphize” a model, it looks like an entertainment-driven expression, but it actually pinpoints the three engineering problems a role-play system must solve: persona consistency, multi-character separation, and interaction scheduling. The implementation path is also clear—use structured character cards to define personas, use System Prompts to constrain behavior, use memory and RAG to counter long-context forgetting, use multi-agent orchestration to coordinate interaction, and use evaluation and safety mechanisms as a safety net for quality.

    For developers, these capabilities serve not only entertainment creation but also a broad range of scenarios such as personified intelligent customer service, virtual instructors, game NPCs, and emotional companionship. Understanding and mastering the core techniques of character-driven dialogue is a key step in moving large models from being a “question-answering tool” to an “interaction entity with warmth.”