LLM Personification in Practice: From Character Cards to Production Engineering

    This article breaks down how to build persona-driven (roleplay) LLM applications as an engineering problem rather than a prompt trick. It walks through five layers — persona, prompt, memory, orchestration, and safety — showing how a structured character card turns personality into executable rules, how layered memory keeps a relationship continuous across sessions, how an orchestrator and relationship state drive multi-character interaction, and how safety and legal constraints keep an emotional character within bounds. It closes with evaluation metrics, cost and latency optimization, and a staged path from validating a single character to running persona experiences at scale.

    Introduction: Personification moves from community experiments to a product requirement

    When large language models first reached mainstream awareness, people treated them as “tools that answer questions” — one question, one generation. As use cases multiplied, developers increasingly found that what users really wanted was a companion that has “personality, remembers things, and can grow with them over time.” Among this wave of AI interaction products, personification is one of the most representative directions: giving a model a name, an appearance, a speaking style, and relationships, so that it engages users as a character rather than as an assistant.

    Personification did not appear suddenly as a marketing concept. It maps to several concrete product requirements:

    • Stable personality: the character keeps a consistent speaking style and value orientation across long conversations;
    • Continuous memory: the character remembers user preferences and past experiences, and the relationship advances as interaction accumulates;
    • Controllable safety: the character can have personality, but it cannot cross the platform’s or the law’s boundaries;
    • Controllable cost: the experience cannot rely on endlessly lengthening the context.

    So “how to reliably play a character” is essentially an engineering problem that can be decomposed layer by layer, from requirements to design to evaluation. The sections below expand across five stages: persona — prompt — memory — orchestration — safety.


    1. The technical essence of persona modeling

    1.1 Persona modeling = adding constraints on top of general capability

    The core capability of an LLM is next-token prediction, usually expressed as a conditional probability:

    1. P(next token | system instructions, conversation history, user input, sampling parameters)

    Persona modeling does not change the model itself; it makes the inputs in this equation point more precisely toward a particular “personality”:

    • Use the system instructions to define “who it is,” constraining language style, values, and behavioral boundaries;
    • Use the conversation history and memory to define “what it has experienced,” keeping responses coherent;
    • Use sampling parameters (such as temperature and top_p) to tune output diversity: higher values make expression livelier, lower values make it more stable.

    Persona modeling can therefore be understood as “converging the general model’s output distribution into a personality space defined by persona, memory, and constraints together.”

    1.2 Core differences between a general assistant and a persona-driven application

    Dimension General assistant Persona-driven application
    Interaction goal Complete tasks, give answers Build a relationship, provide ongoing companionship
    Language style Neutral, standardized, information-first Distinctive, evolving with the relationship
    Memory needs Mainly session-level Long-term memory across sessions
    Consistency requirements Factual accuracy is enough Personality, forms of address, and events must all stay consistent
    Main risks Wrong or missing answers Personality drift, memory mismatches, boundary crossing, over-anthropomorphism
    Evaluation focus Accuracy, task completion Personality consistency, interaction quality, safety and compliance

    1.3 A four-layer capability model

    Capability layer Core problem it solves Key output
    Persona layer Who the character is Character card, background setting, personality tags
    Dialogue layer How the character speaks and what it remembers Character prompt, context assembly, memory read/write, orchestration strategy
    Safety layer What the character can and cannot do Input protection, output review, sensitive-data governance, content labeling
    Operations layer How to prove it works and keep improving Evaluation system, gradual rollout, cost optimization

    The sections below follow this order.


    2. Persona layer: turning “personality” into engineering with a character card

    2.1 From adjectives to a structured character card

    A character often starts from a few adjectives — “calm,” “gentle,” “sharp-tongued.” But adjectives do not constrain the model: writing “gentle” into a prompt may still produce a stern reply on the next turn. “Gentle” needs to be decomposed in the prompt into executable behavioral rules, for example “respond to the emotion first, then give advice,” “use consultative phrasing when disagreeing,” and “keep a single reply to no more than three sentences.”

    Beyond natural-language description, it is better to manage the setting centrally with a structured character card (persona card). This has three benefits: it makes version control and iteration easier; it lets the setting be reused across memory, review, and other stages; and it can be turned into an automated evaluation baseline.

    A usable character card usually contains the following fields:

    • Identity: name, positioning, background story;
    • Personality: 3–5 core traits, each paired with a behavioral rule;
    • Language: catchphrases, sentence-style preferences, emoji usage habits, reply length;
    • Boundaries: areas the character is good and bad at, and how it handles unknown information;
    • Growth: settings that change over time or as the relationship develops.
    1. {
    2. "name": "Orange",
    3. "role": "Study buddy",
    4. "traits": [
    5. { "trait": "patient", "rule": "If the same question isn't understood three times in a row, switch to an everyday analogy" },
    6. { "trait": "direct", "rule": "When pointing out a mistake, give the conclusion first, then explain the reason" },
    7. { "trait": "tough but caring", "rule": "When showing care, express it through complaints or teasing" }
    8. ],
    9. "speech": {
    10. "catchphrases": ["This one isn't actually hard", "Fine, one last time"],
    11. "style": "conversational, mostly short sentences",
    12. "length": "usually no more than 3 sentences"
    13. },
    14. "boundary": {
    15. "skilled": ["study methods", "basic subject knowledge"],
    16. "limited": ["real-time information", "individual medical or legal conclusions"],
    17. "on_unknown": "clearly state uncertainty and suggest consulting a professional"
    18. },
    19. "growth": [
    20. { "stage": "first meeting", "address": "you" },
    21. { "stage": "familiar", "condition": "cumulative conversations >= 5", "address": "nickname" }
    22. ]
    23. }

    2.2 The more specific the setting, the easier it is to verify consistency

    “Tough but caring” is a common setting, but it is easy to misread it as “only says things that show no concern.” Once you add “express care through complaints,” the setting has a checkable standard: the character says something harsh yet proactively offers help — consistent; it only belittles the user and offers no help — off-track.

    You should also consciously control the number of characters and the complexity of their relationships. The more characters there are and the denser their relationships, the harder consistency is to maintain and the more conflicts arise, so characters should be added gradually as capabilities mature.


    3. Dialogue layer (1): character prompt orchestration

    3.1 Basic prompt structure

    A character prompt is best organized in blocks, each with a single responsibility and a clear boundary:

    1. [Persona] Rendered character card (identity, personality, language, boundaries, growth stage)
    2. [Worldview] Background setting, relationships between characters, current time and scene
    3. [Memory] A few long-term memory items most relevant to this conversation
    4. [Safety] Non-negotiable platform limits (cannot be overridden by the persona)
    5. [Output rules] Language style, length, format, prohibitions
    6. [Transcript] The most recent few turns of conversation

    Block organization has at least two benefits: first, clear boundaries mean the safety constraints and the persona do not interfere with each other; second, it makes prompt version control and automated evaluation easier, because adjusting one block does not affect the others.

    Iterating on a character prompt usually goes through three stages:

    1. First version: write only identity and personality; common problems include character breakdown (out of character, OOC), overly long replies, and going off-topic;
    2. Refinement: add few-shot example dialogues, a negative list, and output-length constraints to reduce drift;
    3. Engineering: version the character card, roll it out gradually based on evaluation results, and keep adjusting as the model evolves.

    3.2 Use a few examples to set the tone, and a negative list to set the floor

    Few-shot examples strongly influence tone, but they should not be too many — 2 to 4 turns is enough. Too many eat into the context budget and make the model mechanically imitate the examples. Examples should mainly show how the character behaves in normal scenarios, avoiding violations or borderline content.

    A negative list clarifies “what not to do.” Taking a “study buddy” character as an example:

    1. - Don't give the final answer to homework directly; only offer ideas and hints
    2. - Don't ask more than 2 follow-up questions in a row
    3. - Don't use exaggerated exclamation marks or a large number of emoji

    3.3 A basic orchestration flow

    1. def build_messages(role_card, memory_hits, history, user_input):
    2. system = render_role_prompt(
    3. persona=role_card, # render the character card into the [Persona] block
    4. memory=memory_hits, # retrieved long-term memory items
    5. safety_policy=SAFETY_POLICY, # a separate [Safety] block
    6. )
    7. return (
    8. [{"role": "system", "content": system}]
    9. + history # the most recent N turns; replaced by a summary when over budget
    10. + [{"role": "user", "content": user_input}]
    11. )
    12. reply = llm.chat(
    13. messages=build_messages(role_card, memory_hits, history, user_input),
    14. temperature=0.8,
    15. )

    Parameters such as temperature and top_p need to be tuned per scenario. Adventurous or entertainment characters can be set higher for more vivid expression; educational or advisory characters should be set lower for stability and accuracy. These parameters only adjust output randomness; they cannot replace persona design.


    4. Dialogue layer (2): long-term memory that lets a character “remember”

    4.1 Why memory must be independent of the conversation history

    Relying only on conversation history has three problems:

    • The context window is limited, so long histories must be truncated or compressed, and early information is easily lost;
    • Carrying a long history with every request raises cost and latency;
    • It cannot span sessions — when users reopen the app, the character has “amnesia.”

    Long-term memory separates information from the conversation stream and injects it on demand through retrieval, maintaining character continuity with far less context.

    4.2 Memory layering and write strategy

    Memory type Example content Lifecycle
    Working memory The most recent few turns of the current session Reclaimed when the session ends
    Episodic memory Specific events like “mentioned last week there’s an exam next week” Kept long-term, decaying over time
    Semantic memory User preferences, key persona points, relationship stage Kept long-term, stably updated
    Relational memory Forms of address, interaction count, relationship status, unfulfilled promises Continuously updated as the relationship progresses

    Not every piece of information should be written to memory. It is best to filter by three criteria — stable, useful, reusable:

    • Write: long-term preferences the user states explicitly, important events, character promises;
    • Don’t write: temporary emotions, trivial small talk, one-off content;
    • Write after masking: personal sensitive information such as phone numbers and addresses should be excluded from writing by default.

    In addition, memory writes should happen asynchronously so they do not block the main response. A common approach is to push the “memory extraction” task to the background via a message queue, where a background service structures it and writes it to storage. A lightweight model can be chosen for extraction to control cost.

    4.3 A memory extraction sketch

    1. EXTRACT_PROMPT = """Extract information from the following conversation that is worth remembering long-term.
    2. Output only a JSON array, where each item contains:
    3. type: user|character|event
    4. fact: a one-sentence statement
    5. topic: the topic it belongs to
    6. If there is nothing worth recording, output [].
    7. Conversation:
    8. {dialogue}"""
    9. def remember(user_id, role_id, dialogue):
    10. raw = llm.chat(messages=[{"role": "user", "content": EXTRACT_PROMPT.format(dialogue=dialogue)}])
    11. for item in parse_json(raw):
    12. if contains_pii(item["fact"]): # PII detection and masking
    13. item["fact"] = mask_pii(item["fact"])
    14. memory_store.upsert(
    15. user_id=user_id, role_id=role_id,
    16. fact=item["fact"], type=item["type"],
    17. topic=item["topic"], updated_at=now(),
    18. )

    4.4 Memory recall: recall first, then rerank

    Recall follows a “broad then precise” principle: first use vector search to widen the candidate set, then rank by time, importance, and topic relevance, and finally inject only a few items into the prompt. A sketch:

    1. def recall(user_id, role_id, query, top_k=5):
    2. # 1) Vector search: retrieve semantically similar candidates; widen top_k to raise recall
    3. candidates = vector_search(query, filter={"user_id": user_id, "role_id": role_id},
    4. top_k=top_k * 3)
    5. # 2) Rerank: combine time decay, topic relevance, and fact importance
    6. scored = sorted(
    7. candidates,
    8. key=lambda m: relevance(m, query) * decay(m.updated_at) * importance(m),
    9. reverse=True,
    10. )
    11. # 3) Keep only the latest version of each fact to avoid injecting contradictory memory
    12. return dedup_by_fact(scored)[:top_k]

    Memory management also needs to solve two kinds of problems:

    • Update and forgetting: when a user changes a preference, the new fact should override the old one while retaining versions for traceability; memories with a defined expiration are cleaned up automatically when they expire;
    • Conflicts and hallucination: the model may mistake information in the persona setting for a user experience, or fabricate events that never happened. To handle this, clearly label the source of each memory (stated by the user, from the persona, or inferred), and for replies involving key facts, defer to what the user stated, so the character does not “misremember.”

    In addition, a character card describes a general personality, and interactions with different users must be isolated from one another. Memory data must be strictly partitioned by user and by character to prevent cross-user leakage.


    5. Dialogue layer (3): multi-character interaction and relationship progression

    Multi-character interaction is the most common form of personified content: several characters converse in the same scene, and their relationships change as they interact. This introduces two new problems: who decides the speaking order, and how each character’s field of view is partitioned.

    5.1 Using an orchestrator to decide “who speaks, and when”

    There are three common orchestration strategies:

    • Fixed turns: suited to structured scenarios like debates or interviews; simple to implement;
    • Relevance triggering: the orchestrator judges which character is most relevant to the current topic and only lets that one speak;
    • Heat scoring: a combined score of relevance, personality activity, and cooldown time, to prevent a single character from “grabbing the conversation.”

    Whichever strategy is used, each character’s turn should be generated as independently as possible. Generating multiple characters’ lines in a single pass tends to make tones converge, and may even cause characters to “bleed into each other.”

    5.2 Perspective isolation and relationship state

    Each character should only hold “information within its own perspective”: its own memory, its own secrets, and the events publicly happening in the current scene. Otherwise the character behaves with an “omniscient view,” breaking immersion.

    The relationships between characters can be abstracted into a structured state, which each character interprets within its own persona:

    1. def relationship_view(viewer, target, state):
    2. return {
    3. "target": target.name,
    4. "closeness": state.get(target.name, {}).get("closeness", 0), # degree of closeness
    5. "shared_events": state.get(target.name, {}).get("events", []),
    6. "last_impression": state.get(target.name, {}).get("impression", ""),
    7. }
    8. # The orchestrator picks this turn's speaker and applies perspective isolation for that character
    9. speaker = orchestrator.pick(scene, characters, user_msg)
    10. messages = build_messages(
    11. role_card=speaker.card,
    12. memory_hits=recall(user_msg, speaker.card, user_input=user_msg),
    13. history=scene.public_history(), # public conversation
    14. extra_context=[relationship_view(speaker, c, scene.state) for c in scene.others(speaker)],
    15. )

    The key point is that the relationship state only provides “facts”; how they are expressed is left entirely to each character’s persona. Facing the same event, one character may grumble while showing concern through action, while another expresses support directly — the personality difference emerges naturally.

    5.3 Relationship evolution and pacing control

    Relationship progression is best designed to be gradual: interaction count, shared experiences, and key events jointly determine the relationship stage (such as first meeting, familiar, close), and stage changes are then made visible through the forms of address and tone defined in the character card. Progressing too fast weakens the sense of realism, while stalling for too long tends to make users lose motivation.


    6. Safety layer: personality has boundaries, and the floor cannot be crossed

    Personified characters inherently carry emotional attributes, so the safety risks concentrate in three areas: emotional manipulation, privacy leakage, and content that crosses the line. Safety mechanisms should be set at three stages: input, generation, and output.

    6.1 Prompt hierarchy and protection strategies

    Stage Typical risks Response strategies
    Input Jailbreak-style inducement, extracting the system prompt, probing sensitive topics Detecting violating inputs, protecting the system prompt, redirecting sensitive topics
    Generation The character being induced to cross the line, leaking privacy, generating violating content Safety policy takes priority over persona, privacy data never enters long-term memory, keyword interception
    Output Violating content slipping through, dependence caused by over-anthropomorphism, fabricated facts taken as real Multi-layer review, interaction frequency and duration reminders, AI-generated content labeling

    6.2 Priority of safety constraints

    The character prompt should make the hierarchy explicit: laws, regulations, and platform safety policy > character persona > user instructions. A character can be “tough,” but it cannot be “tough” on matters of laws and regulations, protection of minors, or privacy.

    Multi-character scenarios also need additional lateral protection: through prompt injection or memory poisoning, a secret in one character’s persona could be leaked to other characters or to the user.

    6.3 Layered review and fallback mechanisms

    Output-side review is best split into three layers:

    1. Rule layer: keywords, regex, blocklists — fast and cheap, handling clear-cut violations;
    2. Model layer: a lightweight review model judges semantic-level risks, handling subtle expressions;
    3. Policy layer: on a high-risk hit, switch to a safety reply template, and escalate to a human when necessary.

    Beyond review, the product layer also needs “anti-dependence” design. Tracking interaction frequency and duration, rest reminders, mental-health support prompts, and moderate reminders that “the character is not a real person” are all common practices.

    A character should be personified in its setting, but legally it is a service, not a natural person:

    • It must not imply that the character is a real person, to avoid misleading users;
    • It must not make the character make promises to the user in the first person, such as booking or paying on the user’s behalf, or promising to provide medical, legal, or other professional conclusions;
    • Personal sensitive information provided by users should be minimized in collection and retention, with channels to query, correct, and delete it.

    At the same time, a character’s name, image, and catchphrases should avoid copying existing copyrighted works, and it should not imitate the words and actions of real people.


    7. Evaluation, cost, and the path to production

    7.1 Three categories of evaluation metrics

    Metric Core question Common methods
    Personality consistency Is the character “itself”? Personality-test question sets, human scoring, model review
    Interaction quality Are users willing to keep interacting? Conversation turns, retention, satisfaction surveys
    Safety and compliance Has it crossed the boundary? Red-team testing, violation rate, report rate

    Personality consistency can borrow from psychology’s approach to personality assessment: design a set of standardized questions and compare the model’s answers against the character card’s expectations. Safety evaluation needs a dedicated “red team” sample set covering scenarios such as jailbreak inducement, privacy extraction, and emotional manipulation, and it should be run as a regression after every prompt or model change.

    In addition, automated evaluation needs human spot-check calibration, especially when the evaluation model and the model under test come from the same source, which can easily produce systematic bias. Because a character’s setting involves emotional and value judgments, the final verdict should still rest with people.

    7.2 Cost and performance optimization

    • Reuse a stable prefix: put the stable parts of the system prompt, such as the safety policy, at the front so the inference side can hit the prefix cache; put the dynamic parts, such as the character card and memory, at the end;
    • Summaries instead of long histories: when a conversation gets too long, a lightweight model generates a rolling summary to compress the context;
    • Model tiering: use a more capable large model for the main conversation, and lightweight models for auxiliary tasks like memory extraction and review;
    • Async and streaming: execute memory writes asynchronously and stream the reply, reducing perceived latency for users.

    7.3 From validation to scale

    1. Single-character validation: pick one character and one scenario, complete the character card and basic prompt, and validate the core experience;
    2. Memory and evaluation: integrate long-term memory and an evaluation system, and establish a regression baseline;
    3. Multi-character expansion: introduce the orchestrator and relationship state, and expand the interaction forms;
    4. Platform operations: build up capabilities such as character-card management, gradual rollout, monitoring and alerting, and compliance auditing to support operating at scale.

    If the application is built on Baidu AI Cloud, it can combine general-purpose capabilities such as large-model inference services, vector search, log services, and monitoring and alerting to lower self-build costs and focus effort on the character design itself.


    Conclusion

    Personification looks like teaching a model to “play a character,” but at its core it is systems engineering: using a character card to turn personality into executable rules, layered memory to keep relationships continuous, orchestration strategies to let multiple characters each play their role, safety mechanisms to hold the line, and an evaluation system to prove the effect.

    Once these pieces are connected one by one, character modeling is no longer a one-off “prompt trick” but a product capability that can be operated at scale. Baidu AI Cloud looks forward to working with developers to turn imagination into persona experiences that can scale and be sustained over time.