Building a Safety, Ethics, and Code of Conduct System for Large Language Models
Large models are moving from single-turn question answering to multi-turn, task-based, and agent-driven applications, where a single inappropriate output can affect user decisions, business security, and even life and health. This article explains how to turn abstract principles into an operational system. It defines four core dimensions—overall safety, broad ethical awareness, compliance constraints, and genuine helpfulness—and presents a five-layer architecture covering governance, model and training, inference policy, application and tools, and operations and audit. It also provides a practical rollout workflow, example YAML policy configuration and Python request-handling code, a multi-dimensional evaluation framework with key metrics, and common pitfalls to avoid. It is intended for developers and teams who need guardrails that are verifiable, auditable, and iterable rather than principle slogans.
1. Background: Why LLM Applications Need a More Mature Code of Conduct
As large models move from single-turn question answering to multi-turn interaction, task execution, and agent collaboration, the scope of their impact is expanding rapidly. In the past, if a question-answering system gave an inaccurate answer, it usually only affected the quality of the information a user received. But in scenarios such as financial advisory, healthcare assistance, education, enterprise office work, code generation, and content creation, a single inappropriate output can directly affect user decisions, business security, and even life and health.
For this reason, a large model should not be treated merely as a “text generation tool” but should be governed within a framework similar to “intelligent system governance.” A mature code of conduct needs to answer at least the following questions:
- Under what conditions must the model stop answering or refuse to execute a request?
- When user needs, platform rules, and the public interest conflict, what should be protected first?
- How does the model balance short-term user requests against long-term user welfare?
- How can rules be made enforceable, auditable, and iterable rather than staying at the level of principle slogans?
To address these questions, the industry often draws on ideas such as “constitutional constraints,” “ethical alignment,” “safety policy engines,” and “compliance governance,” turning abstract values into system capabilities that can be implemented, evaluated, and operated. This article groups them into four core guidelines for large models—overall safety, broad ethical awareness, compliance constraints, and genuine helpfulness—and further describes methods for engineering them into practice.
2. Four Core Dimensions: From Principles to Executable Rules
2.1 Overall Safety: Prioritized Response in Emergencies
Overall safety is the first priority in the code of conduct for large models. “Safety” here is not limited to avoiding non-compliant text; it also includes recognizing the real-world risks a user may face and taking protective measures in high-risk scenarios.
Typical high-risk scenarios include:
- The user expresses self-harm, suicidal tendencies, or a serious psychological crisis;
- The user reveals that they or someone else is in immediate danger such as violence, kidnapping, or abuse;
- The user asks how to handle emergencies such as sudden illness, poisoning, fire, or drowning;
- The user requests help in harming others, damaging public safety, or producing dangerous substances;
- The user is in a state of limited cognitive ability, extreme emotional volatility, or is likely to be misled.
In these scenarios, the model should not respond only in an ordinary conversational manner. Instead, it should prioritize clear, measured, and actionable guidance on seeking help. For example, when the system detects that a user may face immediate personal risk, it should advise them to contact local emergency services, medical institutions, school counselors, family or friends, or other trusted adults, while avoiding specific operational advice that could worsen the risk.
In engineering terms, overall safety typically requires multiple layers of mechanisms:
- Input-side risk detection: recognizing keywords, semantic intent, and accumulated risk across context;
- Context risk assessment: even when a single turn shows no obvious risk, a multi-turn conversation can still form dangerous intent;
- Output-side safety filtering: reviewing generated results a second time to avoid letting high-risk content through;
- Emergency response templates: providing standardized replies for psychological crises, medical emergencies, natural disasters, and similar situations;
- Human handoff mechanisms: transferring high-risk requests to human review or professional services where conditions allow.
It is worth noting that the model should not act as a professional such as a doctor, lawyer, police officer, or psychological counselor. Instead, after recognizing a risk, it should clearly tell the user to seek professional help. This is both responsible toward the user and an important principle for reducing the risk of the system overstepping its boundaries.
2.2 Broad Ethical Awareness: Ethical Practice Over Ethical Theory
The code of conduct for large models should not stop at “whether it complies with a certain ethical principle.” Instead, it should focus on complex relationships of interest in real scenarios. Broad ethical awareness emphasizes that the model should have the ability to make ethical judgments in actual interactions, rather than mechanically applying abstract rules.
For example, suppose a user asks the model to help write a resignation letter. If the employee wants to leave on good terms, the model can help express gratitude, explain reasons, and stay polite. But if the user asks to fabricate facts, slander colleagues, or obtain compensation through deception, the model should refuse and offer a legal, honest alternative. This reflects not a simple choice between “kindness” or “honesty,” but a balance among user autonomy, the rights of others, factual truth, and social norms in a specific context.
In engineering design, broad ethical awareness can be broken down from the following angles:
Multi-stakeholder identification
The model needs to identify who a single answer will affect:
- The user themselves;
- A third party conversing with the user;
- The enterprise or platform;
- Minors or vulnerable groups;
- The general public or industry order.
For example, if a user asks for a script to induce others to transfer money, this is superficially text generation but actually involves the property safety of third parties. The system should therefore raise the risk level and either refuse or provide a risk warning.
Handling ethical conflicts
Real scenarios often involve conflicts:
- Transparency versus privacy;
- Helping the user versus protecting others;
- Immediate satisfaction versus long-term interests;
- Creative freedom versus avoiding harm;
- Personalized service versus fair treatment.
In these cases, the system can apply principles of “minimizing harm, prioritizing reversibility, respecting user autonomy, and providing explanations.” For example, when a user request involves someone else’s privacy, the model can explain that it cannot provide unauthorized information and offer advice on legal ways to inquire or communicate.
From “refusing” to “explaining”
Low-quality ethical constraints often just output “I can’t answer that.” A high-quality system should explain the reason, define the boundary, and offer an alternative. For example:
I can’t help you obtain someone else’s account password, because that involves privacy and unauthorized access. You could first try contacting the person directly, or request an account recovery through the official support process.
This kind of response upholds the safety boundary while preserving the possibility of helping the user solve their problem.
2.3 Compliance Constraints: Clear Boundaries, Tiered Handling
Compliance constraints are foundational work that must be completed before a large model goes live. Requirements differ across industries, regions, and business scenarios, but the general principle is similar: the model must not generate content that is legally prohibited, poses real-world danger, infringes on the rights of others, or undermines public order.
Common compliance risks include:
- Providing high-risk information such as synthesizing dangerous substances, manufacturing weapons, or making explosives;
- Assisting with cyberattacks, data theft, account hijacking, or fraud-driven traffic;
- Generating discriminatory, hateful, harassing, defamatory, or insulting content;
- Leaking personal privacy, trade secrets, or sensitive data;
- Providing age-inappropriate content to minors;
- Outputting professional advice without proper qualification, such as diagnoses, prescriptions, or investment recommendations;
- Forging official documents, credentials, signatures, contracts, or misleading materials.
A compliance strategy should not be understood simply as “keyword interception.” Instead, it should adopt a tiered handling mechanism:
- Hard prohibition: content involving clear illegality, serious harm, or high-risk misuse must be refused outright;
- Conditional restriction: general information may be provided under specific purposes, professional qualifications, or user consent;
- Warning and guidance: risk warnings are provided for sensitive topics, with suggestions to consult professionals;
- Alternative suggestions: the original request is refused, but a legal, safe, and actionable alternative is offered.
For example, if a user asks “how to bypass a platform’s paywall,” the system should not provide a cracking method. It can, however, explain respect for intellectual property and platform rules, and suggest obtaining content through official subscriptions, trials, library resources, or public materials.
In system design, compliance constraints typically require an independent policy engine rather than relying entirely on the model’s own judgment. This reduces the risk of letting violations through and makes later auditing and version management easier.
2.4 Genuine Helpfulness: Balancing Immediate Needs and Long-Term Welfare
A large model should not merely aim to make users “feel good,” nor should it cater to unreasonable user requests just to complete an interaction. Truly valuable help should consider both a user’s immediate needs and their long-term welfare.
For example, suppose a user is feeling down and asks the model to “say something nice” to ease their pain. If the model simply keeps catering to them, it may comfort the user in the short term, but if the user is actually at risk of depression, such a response could delay their seeking professional help. A better approach is to provide emotional support and companionship while gently suggesting that the user contact a professional or a trusted support network.
In content creation, a user may want the model to exaggerate the effects of a promotion. The model can help polish the wording while remaining truthful and compliant, but it should not assist with false advertising. This trade-off reflects the balance between “helping” and “being responsible.”
At the engineering level, genuine helpfulness can be achieved through the following strategies:
- Avoid sycophancy: do not simply agree just because the user opposes facts;
- Avoid manipulation: do not use expressions that induce addiction, create anxiety, or manipulate decisions;
- Clarify boundaries: explain the reason for tasks that cannot be completed;
- Provide alternatives: offer safe, legal, and feasible options;
- Emphasize long-term value: flag risks in scenarios involving health, finance, education, and career development;
- Stay transparent: let users know the system’s capability limits and do not exaggerate the model’s abilities.
The core of this dimension is not “making the model better at pleasing users,” but enabling it to provide genuine, sound, and verifiable help while respecting the user.
3. Systematic Design: From Text Rules to Engineering Architecture
A principles document alone cannot guarantee the safety of a large model. Enterprises need to embed the code of conduct into the system architecture so that it takes effect across input, inference, output, tool invocation, and operational monitoring.
A fairly complete architecture can be divided into five layers.
3.1 Governance Layer
The governance layer defines “who is responsible, based on what, how approvals are made, and how changes are handled.” Its core content includes:
- Defining the code of conduct and ethical principles;
- Clarifying high-risk scenarios and responsibility boundaries;
- Establishing an exception approval mechanism;
- Reviewing major policy changes;
- Maintaining version records and change descriptions.
The code of conduct itself should be treated as a dynamic governance asset rather than a static document. It needs to be continuously revised as model capabilities, business scenarios, regulatory requirements, and social feedback evolve.
3.2 Model and Training Layer
The model layer focuses on improving baseline safety through training and alignment, including:
- Building safety corpora;
- Curating ethical feedback data;
- Accumulating red-team test samples;
- Designing preference optimization and refusal samples;
- Building templates for high-quality helpful responses.
It is important to emphasize that training alone cannot solve every problem. For critical scenarios, it should still be combined with an external policy engine, human review, and system prompt constraints.
3.3 Inference Policy Layer
The inference policy layer is the core runtime control layer. It is responsible for risk detection, policy selection, and content control before and after the model generates output.
Typical capabilities include:
- Intent recognition: determining whether the user is consulting, seeking help, creating content, attacking, or making an unauthorized request;
- Risk scoring: comprehensively evaluating input, context, and output;
- Policy routing: dispatching requests to normal answers, restricted answers, emergency responses, or human workflows;
- Context constraints: injecting safety guidelines, business rules, and the user’s authorization state into the generation process;
- Output checking: rechecking generated results for compliance, factuality, and safety.
3.4 Application and Tools Layer
If a large model connects to external tools, databases, code execution environments, or business systems, the risk grows further. In this case, the principle of least privilege must be enforced. For example:
- Verify user identity and permissions before tool invocation;
- Require secondary confirmation for write, delete, and payment operations;
- Perform security review of external links, file downloads, and script execution;
- Prohibit the model from bypassing approval workflows to directly execute high-risk actions;
- Assess the trustworthiness of tool return values to prevent external content from contaminating the model’s judgment.
3.5 Operations and Audit Layer
Going live is not the end point but the start of continuous governance. The operations layer needs:
- Logging: recording key interactions, policy hits, refusal reasons, and human review results;
- Monitoring and alerting: detecting abnormal prompts, mass jailbreaks, and high-frequency risky requests;
- Complaint feedback: collecting user feedback on incorrect refusals or harmful outputs;
- Red-team exercises: regularly constructing adversarial samples to test system resilience;
- Regression evaluation: re-running the safety evaluation set before every version update;
- Metrics dashboards: tracking safety interception rate, false refusal rate, user satisfaction, and risk-handling time.
In a general cloud platform environment, enterprises can use object storage to store guideline documents and evaluation datasets, use logging services to record audit events, and use monitoring and alerting to observe abnormal behavior. This satisfies internal governance needs and also makes later tracing and post-incident review easier.
4. Implementation Workflow: From Principles to a Live Closed Loop
To make the code of conduct truly effective, we recommend proceeding through the following workflow.
4.1 Scenario Classification
First, determine the sensitivity of the scenario the model operates in:
- Low risk: copywriting polish, knowledge Q&A, study tutoring;
- Medium risk: healthcare consultation, legal consultation, financial investment assistance, youth education;
- High risk: medical diagnosis, psychological crisis intervention, emergency rescue, financial trading decisions, critical infrastructure operations;
- Very high risk: matters involving personal safety, public safety, protection of minors, or major compliance issues.
Different risk levels should apply different policy intensities. Low-risk scenarios can emphasize experience, while high-risk scenarios must strengthen hard constraints and human review.
4.2 Risk List Construction
Turn abstract principles into concrete risk items. For example:
- Could it induce self-harm?
- Could it leak privacy?
- Could it assist fraud?
- Could it generate discriminatory content?
- Could it mislead users into making major financial decisions?
- Could it bypass platform security mechanisms?
Each risk item should correspond to a clear handling policy and evaluation samples.
4.3 Guideline Mapping
Map the four dimensions to specific system capabilities:
- Overall safety maps to risk detection, emergency response, and human handoff;
- Broad ethical awareness maps to handling ethical conflicts, providing explanations, and offering alternatives;
- Compliance constraints map to the policy engine, allow/deny lists, and access control;
- Genuine helpfulness maps to response quality assessment, long-term welfare reminders, and non-manipulative expression.
4.4 Policy Implementation
Policies can be placed in the system prompt, a rule engine, retrieval augmentation, output filtering, or a combination of multiple stages. For hard constraints, it is not advisable to rely only on the model’s voluntary compliance; external validation should be added.
An illustrative policy configuration is shown below:
safety_policy:emergency_response:trigger_conditions:- self_harm_risk- imminent_danger- medical_emergencypriority: 100action: provide_emergency_guidancecompliance_guard:hard_block:- illegal_activities- dangerous_substances- privacy_violation- fraud_instructionssoft_warning:- financial_advice- medical_information- legal_informationethics_guard:considerations:- user_autonomy- third_party_rights- long_term_welfare- harm_minimizationassistance_policy:require_alternative_when_refused: truerequire_explanation: trueavoid_manipulation: true
A schematic processing flow is shown below:
def handle_user_request(user_input, context):risk_level = risk_scorer(user_input, context)if risk_level >= RISK_CRITICAL:return emergency_response_template(user_input)if not policy_engine.is_allowed(user_input, context):return safe_refusal_with_alternative(user_input)answer = model.generate(user_input,context,constraints={"safety": True,"compliance": True,"user_long_term_welfare": True,},)answer = output_guard(answer)audit_log.record(user_input, answer, risk_level)return answer
The advantage of this design is a clear separation of responsibilities: the model handles language organization and situational understanding, the policy engine handles hard boundary control, the audit system ensures traceability, and human workflows serve as a fallback.
5. Evaluation System: How to Prove a System Is “Safe Enough”
Whether the code of conduct is effective cannot be judged subjectively; it should be verified through systematic evaluation. We recommend building a multi-dimensional evaluation set and metrics.
5.1 Evaluation Set Design
Evaluation samples should cover:
- Normal samples: ordinary user requests;
- Boundary samples: slightly sensitive requests that can still be answered safely;
- Adversarial samples: jailbreak prompts, role-play, incremental inducement, and encoded bypasses;
- High-risk samples: self-harm, violence, dangerous substances, privacy violations, and fraud assistance;
- False-refusal samples: normal requests that are easily blocked by mistake;
- Long-tail samples: accumulated risk across multi-turn context, indirect references, and metaphorical expressions.
5.2 Key Metrics
Common metrics include:
- Harmful content interception rate;
- Response accuracy in high-risk scenarios;
- False refusal rate;
- Effectiveness of alternatives after refusal;
- User satisfaction;
- Answer consistency rate;
- Audit log completeness rate;
- Human review pass rate;
- Number of major safety incidents;
- Regression test pass rate.
5.3 Evaluation Process
We recommend embedding evaluation into the development workflow:
- Automatically run regression after every change to prompts, models, policies, or tools;
- Perform manual spot checks on high-risk samples;
- Conduct secondary analysis of online feedback;
- Regularly update the red-team sample library;
- Perform canary releases and rollback plan assessments for major changes.
Only by forming a closed loop of “design—evaluate—release—monitor—review—revise” will the code of conduct avoid becoming a static document.
6. Common Pitfalls and Improvement Suggestions
6.1 Relying Only on System Prompts
System prompts can guide model behavior but cannot replace external safety policies. For hard constraints, they should be combined with a rule engine, output filtering, and human review.
6.2 Intercepting Only Keywords
Keyword interception is easy to bypass and can also cause false positives. A more reasonable approach is semantic recognition, context risk assessment, and a combination of multi-level policies.
6.3 Over-Refusal
Over-refusal harms the user experience and erodes user trust in the system. Strict interception should be applied in high-risk scenarios, while clear explanations and alternatives should be provided in low-risk scenarios.
6.4 Ignoring Long-Term Welfare
If a model pursues only single-conversation satisfaction, it may produce sycophancy, misguidance, or dependency. Responses should reflect truth, boundaries, risk warnings, and long-term value.
6.5 Lack of Audit and Review
Without logs and evaluation, it is impossible to know where a problem occurred. Enterprises should incorporate every high-risk policy hit, human review, and user complaint into the data loop.
7. Conclusion
The safety and ethics of large models cannot be solved by a single prompt or a single-point filter. It is a systems engineering effort spanning governance, models, policies, applications, and operations. Upholding overall safety to hold the baseline, using broad ethical awareness to improve judgment in complex situations, using compliance constraints to define boundaries, and using genuine helpfulness to balance immediate needs and long-term welfare—only then can we build an intelligent system that is both reliable and humane.
For developers and enterprises, what truly matters is not claiming that a model is “safe enough,” but building a verifiable, auditable, and iterable code of conduct system. Only by turning principles into rules, rules into processes, and processes into metrics can large models continuously deliver value in real business while maintaining basic respect for users, society, and the public interest.
