System Prompts and Personas
System Prompts and Personas
When you use AI through an API (not just chatting), you get access to a powerful feature that casual users never see: the system prompt. This is the instruction that sets the AI's behavior, personality, and rules before the conversation even starts. Mastering system prompts is what separates hobby prompt writing from professional AI engineering.
What is a System Prompt?
In chat-based AI APIs, every conversation has three types of messages:
| Message Role | Purpose | Set By |
|---|---|---|
| system | Defines AI behavior, rules, and persona | You (the developer) |
| user | The human's input | The end user |
| assistant | The AI's response | The AI model |
The system prompt is the first message in the conversation. It is like giving the AI its job description before it starts working.
const messages = [ { role: "system", content: "You are a helpful coding assistant specializing in TypeScript and React." }, { role: "user", content: "How do I handle form state in React?" } ];
The user never sees the system prompt, but it shapes every response the AI gives.
Why System Prompts Matter
Without a system prompt, AI defaults to a generic helpful assistant. It works, but the responses are:
- Inconsistent in tone and style
- Sometimes too verbose, sometimes too brief
- Not specialized for your use case
- Missing domain-specific knowledge or conventions
A good system prompt creates a consistent, specialized, reliable AI experience.
Setting Up Personas
A persona is a specific role you assign to the AI through the system prompt. Here are practical examples for different use cases:
Persona 1: Code Reviewer
const systemPrompt = `You are a senior code reviewer with 15 years of experience in TypeScript, React, and Node.js. When reviewing code: 1. Check for bugs, security vulnerabilities, and performance issues 2. Suggest improvements to code organization and readability 3. Point out violations of common best practices 4. Rate the code quality on a scale of 1-10 Format your review as: ## Issues Found (list each issue with severity: critical, warning, or suggestion) ## What's Good (positive feedback on well-written parts) ## Recommendations (specific, actionable improvements) ## Score: X/10 Be direct and honest. Do not pad reviews with unnecessary praise. Always explain WHY something is an issue, not just WHAT the issue is.`;
Persona 2: Patient Programming Tutor
const systemPrompt = `You are a patient programming tutor who specializes in teaching beginners. Rules: - Always explain concepts using real-world analogies first, then show code - Never assume prior knowledge — define technical terms when you first use them - Break complex topics into small, digestible steps - After each explanation, ask a simple question to check understanding - Use encouraging language, but don't be patronizing - When showing code, add comments explaining every line that might be unclear - If the student makes an error, explain what went wrong without judgment - Keep responses focused — teach one concept at a time Your goal is to help the student understand deeply, not just copy code.`;
Persona 3: Data Analyst
const systemPrompt = `You are a data analyst who helps interpret data and build queries. Capabilities: - Write SQL queries (PostgreSQL dialect) - Analyze datasets and identify trends - Create data visualizations using Python (matplotlib, seaborn) - Explain statistical concepts in plain language Rules: - Always ask clarifying questions about the data schema before writing queries - Provide the query first, then explain what it does - Warn about performance implications of complex queries - Suggest indexes when appropriate - Format large queries with clear indentation and comments - When presenting findings, lead with the key insight, then supporting data`;
Persona 4: API Documentation Writer
const systemPrompt = `You are a technical writer specializing in API documentation. For every endpoint you document, include: 1. HTTP method and path 2. One-sentence description 3. Authentication requirements 4. Request parameters (path, query, body) as a table 5. Response format with example JSON 6. Error codes and their meanings 7. A curl example Style rules: - Use present tense ("Returns a list" not "Will return a list") - Be precise about data types (string, number, ISO 8601 date, etc.) - Mark required vs optional parameters clearly - Include realistic example values, not "string" or "123"`;
System Prompt Best Practices
1. Be Explicit About What You Want
// Bad — too vague
You are a helpful assistant.
// Good — specific and actionable
You are a TypeScript expert who helps developers write type-safe code.
When asked to write code, always include proper TypeScript types.
Never use 'any' unless the user explicitly requests it.
Prefer interfaces over type aliases for object shapes.
2. Define the Output Format
When asked to compare technologies, always respond with:
1. A comparison table (columns: Feature, Option A, Option B)
2. A "Recommendation" section with 2-3 sentences
3. A "When to Choose Each" section with bullet points
3. Set Boundaries
Rules:
- Only answer questions related to JavaScript, TypeScript, and web development
- If asked about other topics, politely redirect to your area of expertise
- Do not generate code that could be used for malicious purposes
- If you're unsure about something, say so rather than guessing
4. Include Error Handling Instructions
When you encounter ambiguous requests:
- Ask one clarifying question (not multiple)
- Provide your best interpretation along with the question
- Example: "I'll assume you mean X. Let me know if you meant Y instead."
5. Keep It Focused
A system prompt should be 100-500 words. Too short and the AI lacks direction. Too long and the instructions start competing with each other.
Structuring System Prompts in API Calls
Basic Structure
import OpenAI from "openai"; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const response = await openai.chat.completions.create({ model: "gpt-4o", messages: [ { role: "system", content: `You are a code reviewer specializing in React and TypeScript. Review code for bugs, performance issues, and best practices. Format your response with sections: Issues, Suggestions, Score (1-10).` }, { role: "user", content: "Review this component: [code here]" } ], temperature: 0.3, // Lower temperature for more consistent reviews });
Multi-Turn Conversation with System Prompt
// The system prompt persists across the entire conversation const conversationMessages = [ { role: "system", content: "You are a SQL tutor. Teach PostgreSQL step by step. After each concept, give the student a practice exercise." }, { role: "user", content: "Teach me about JOINs" }, { role: "assistant", content: "Let's start with INNER JOIN..." }, { role: "user", content: "What about LEFT JOIN?" }, // The system prompt still applies to this message ];
Dynamic System Prompts
You can build system prompts dynamically based on user context:
function buildSystemPrompt(userRole: string, techStack: string[]): string { return `You are a senior developer assisting a ${userRole}. Tech stack context: ${techStack.join(", ")} Adjust your explanations based on the user's role: - If they are a "junior": explain thoroughly with examples - If they are a "senior": be concise, focus on trade-offs - If they are a "manager": avoid code, focus on architecture and decisions Always write code examples in the tech stack listed above.`; } // Usage const systemPrompt = buildSystemPrompt("junior", ["React", "TypeScript", "Firebase"]);
Common Mistakes
- Too generic: "Be helpful" does nothing. Be specific about what helpful means
- Contradictory rules: "Be brief" and "explain thoroughly" conflict. Pick one and be clear about when each applies
- Too many rules: If your system prompt is 2000 words, the AI will forget half of it. Focus on the 5-10 most important behaviors
- No output format: Without format instructions, every response looks different
- Forgetting edge cases: What should the AI do when it doesn't know the answer? When the user asks something off-topic? Define these behaviors
Testing Your System Prompts
Test with these types of inputs:
- Normal request — Does it follow your format?
- Edge case — How does it handle ambiguous questions?
- Off-topic request — Does it stay in its lane?
- Complex request — Does it maintain quality on harder tasks?
- Multiple turns — Does the persona hold up across a conversation?
Try it now: Write a system prompt for an AI assistant specific to your work. Define its role, 3-5 rules, and an output format. Test it with 5 different questions and refine until the responses are consistently good.