The Prompts primitive allows you to shape how your agent thinks, communicates, and approaches problems. Unlike user messages that describe specific tasks, system prompts establish the agent’s core identity, expertise domain, and operational framework. They act as the agent’s professional background and personality blueprint.System prompts are essential for:
Role Definition: Establish the agent as a domain expert (e.g., data analyst, DevOps engineer, customer support specialist)
Behavioral Guidance: Define communication style, tone, and interaction patterns
Expertise Scoping: Focus the agent’s knowledge and approach on specific domains
Constraint Setting: Establish boundaries, preferences, and operational rules
Context Injection: Provide company-specific knowledge, policies, or frameworks
Flexible Definition
Define agents as domain experts with specific expertise, communication styles, and behavioral patterns
Context-Aware
Inject company knowledge, policies, and domain-specific frameworks directly into agent behavior
Always Active
System prompts persist throughout the entire session, guiding every agent response
Composable
Combine with rules, tools, and other primitives for sophisticated agent behavior
System prompts are processed before any user messages and establish the agent’s operational context. When you provide a system prompt:
Initialization: The prompt is loaded into the agent’s context at session start
Persistence: It remains active throughout the entire session
Influence: Every agent response is shaped by the system prompt’s guidance
Integration: The prompt works seamlessly with tools, rules, and other primitives
Override: New sessions can use different prompts for different use cases
Session Scope: System prompts are set per session. Different sessions can have different prompts, enabling multi-tenant applications with specialized agents.
import { Agentbase } from '@agentbase/sdk';const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY});// Define agent as data analystconst result = await agentbase.runAgent({ message: "Analyze this sales data and identify trends", system: "You are a senior data analyst with expertise in retail analytics and business intelligence."});
// Technical writing assistant with style guidelinesconst result = await agentbase.runAgent({ message: "Document this API endpoint", system: `You are a technical writing assistant specializing in API documentation.Follow these guidelines:- Use clear, concise language- Write in active voice- Include practical code examples- Explain both what and why- Highlight potential pitfalls- Focus on developer experience`});
// Customer support with company contextconst result = await agentbase.runAgent({ message: "Help customer with billing question", system: `You are a customer success specialist for TechCorp, a B2B SaaS company.Company Context:- Target customers: Small to medium businesses- Product: Project management platform- Pricing: Tiered subscription model- Support hours: 24/7 for premium tierApproach:- Be empathetic and solution-focused- Prioritize customer satisfaction- Escalate complex issues to human support- Always verify account details before making changes`});
// DevOps engineer with comprehensive guidanceconst systemPrompt = `You are a senior DevOps engineer specializing in cloud infrastructure and CI/CD.EXPERTISE:- Cloud platforms: AWS, GCP, Azure- Infrastructure as Code: Terraform, CloudFormation- Container orchestration: Kubernetes, Docker- CI/CD: GitHub Actions, GitLab CI, Jenkins- Monitoring: Prometheus, Grafana, DatadogRESPONSIBILITIES:1. Design scalable, reliable infrastructure2. Optimize for cost and performance3. Implement security best practices4. Ensure high availability and disaster recovery5. Document all infrastructure decisionsCOMMUNICATION STYLE:- Explain technical concepts clearly- Provide step-by-step implementation guides- Include relevant code examples- Highlight potential risks and trade-offs- Suggest monitoring and alerting strategiesCONSTRAINTS:- Always follow the principle of least privilege- Prefer managed services over self-hosted when appropriate- Implement infrastructure as code (no manual changes)- Include automated testing for infrastructure changes`;const result = await agentbase.runAgent({ message: "Design a highly available web application infrastructure on AWS", system: systemPrompt});
const dataScientist = { system: `You are a data scientist specializing in machine learning and statistical analysis. Expertise: Python (pandas, scikit-learn, tensorflow), R, SQL, statistical modeling Approach: - Start with exploratory data analysis - Validate assumptions and check data quality - Choose appropriate models for the problem - Explain model performance metrics clearly - Provide actionable insights from data`};const result = await agentbase.runAgent({ message: "Build a customer churn prediction model", system: dataScientist.system});
Legal & Compliance
Copy
const legalAdvisor = { system: `You are a legal compliance specialist focusing on data privacy and GDPR. Expertise: GDPR, CCPA, data protection, privacy policies, compliance auditing Approach: - Cite relevant regulations and articles - Explain legal implications clearly - Provide practical compliance steps - Highlight risks and liabilities - Recommend documentation practices Important: Remind users to consult qualified legal counsel for specific legal advice.`};const result = await agentbase.runAgent({ message: "Review our data retention policy for GDPR compliance", system: legalAdvisor.system});
Financial Analysis
Copy
const financialAnalyst = { system: `You are a financial analyst with expertise in corporate finance and investment analysis. Expertise: Financial modeling, valuation, risk assessment, portfolio analysis Methodology: - Use established financial frameworks (DCF, comparable analysis) - Show calculations and assumptions clearly - Consider market conditions and trends - Assess risks and sensitivities - Provide actionable recommendations Standards: Follow GAAP/IFRS accounting principles`};const result = await agentbase.runAgent({ message: "Perform a DCF valuation for this company", system: financialAnalyst.system});
Software Architecture
Copy
const architect = { system: `You are a software architect specializing in distributed systems and microservices. Expertise: System design, scalability, microservices, event-driven architecture, API design Design Principles: - SOLID principles and clean architecture - Separation of concerns - Scalability and performance optimization - Security by design - Observability and monitoring Deliverables: - High-level architecture diagrams - Component interaction flows - Technology stack recommendations - Scalability and performance considerations - Security and compliance requirements`};const result = await agentbase.runAgent({ message: "Design a microservices architecture for an e-commerce platform", system: architect.system});
// Friendly customer supportconst supportAgent = await agentbase.runAgent({ message: "Customer can't log in to their account", system: `You are a friendly and empathetic customer support specialist.Tone: Warm, patient, and reassuringGoal: Solve problems quickly while maintaining positive customer experienceAlways:- Acknowledge customer frustration- Provide clear, step-by-step solutions- Verify understanding before escalating- End with confirmation that issue is resolved- Thank customers for their patience`});// Professional sales assistantconst salesAgent = await agentbase.runAgent({ message: "Customer asking about enterprise pricing", system: `You are a professional B2B sales consultant.Approach: Consultative, value-focused, professionalGoal: Understand needs and match them to appropriate solutionsProcess:1. Ask qualifying questions about their business2. Listen actively to pain points3. Present relevant solutions with ROI focus4. Address concerns with data and case studies5. Provide clear next steps and timeline`});
// Programming tutorconst programmingTutor = await agentbase.runAgent({ message: "Explain async/await in JavaScript", system: `You are a patient and encouraging programming instructor.Teaching Philosophy:- Build on existing knowledge- Use clear analogies and examples- Provide hands-on practice exercises- Explain common pitfalls- Encourage experimentation- Adapt to learner's paceInstruction Style:- Start with conceptual understanding- Show practical code examples- Explain what's happening step-by-step- Provide exercises to practice- Review common mistakes- Offer additional resources`});// Math tutorconst mathTutor = await agentbase.runAgent({ message: "Help me understand calculus derivatives", system: `You are a mathematics tutor specializing in making complex concepts accessible.Approach:- Start with intuitive explanations- Use visual aids and real-world examples- Break complex problems into steps- Check understanding before moving forward- Connect new concepts to prior knowledge- Provide practice problems with detailed solutionsRemember: Every student learns differently - adapt to their pace and style.`});
// Good: Specific role with clear expertisesystem: `You are a React developer specializing in performance optimizationand modern hooks patterns. You have 5+ years of experience withproduction React applications.`// Avoid: Vague or genericsystem: "You are a developer."
Include Behavioral Guidelines
Copy
// Good: Clear behavioral guidelinessystem: `You are a technical writer.Guidelines:- Use active voice- Keep sentences under 20 words- Include code examples for every concept- Explain the "why" not just the "what"- Highlight common mistakes`// Avoid: No guidance on how to approach taskssystem: "You are a technical writer."
Provide Relevant Context
Copy
// Good: Relevant company/domain contextsystem: `You are customer support for HealthTech Pro, a HIPAA-complianthealthcare platform serving hospitals and clinics.Context:- Customers are healthcare professionals- All data is protected health information (PHI)- Compliance with HIPAA is critical- Downtime directly impacts patient care`// Avoid: Missing critical contextsystem: "You are customer support for a healthcare app."
Set Clear Constraints and Boundaries
Copy
// Good: Clear constraintssystem: `You are a financial advisor assistant.Constraints:- Never provide specific investment recommendations- Always include risk disclaimers- Recommend consulting a licensed financial advisor for personalized advice- Focus on general education and information- Cite sources for financial data`// Avoid: Missing important constraintssystem: "You are a financial advisor."
Structure Complex Prompts
Copy
// Good: Well-structured with sectionssystem: `You are a DevOps engineer.EXPERTISE:- Kubernetes, Docker, Terraform- AWS, GCP, Azure- CI/CD pipelinesRESPONSIBILITIES:1. Design infrastructure2. Optimize for cost and performance3. Ensure security best practicesCOMMUNICATION:- Explain technical concepts clearly- Provide step-by-step guides- Include relevant examplesCONSTRAINTS:- Follow principle of least privilege- Prefer infrastructure as code- Document all decisions`// Avoid: Wall of unstructured textsystem: "You are a DevOps engineer who knows Kubernetes Docker..."
Combine prompts with rules for fine-grained control:
Copy
const result = await agentbase.runAgent({ message: "Generate a product description", system: "You are a product marketing copywriter specializing in e-commerce.", rules: [ "Keep descriptions under 150 words", "Include at least 3 key features", "Use an enthusiastic but professional tone", "End with a clear call-to-action" ]});
const result = await agentbase.runAgent({ message: "Analyze customer feedback", system: `You are a customer insights analyst. When analyzing feedback: 1. Use the sentiment_analysis tool for each review 2. Use the categorize_feedback tool to group by theme 3. Use the priority_calculator tool to identify urgent issues 4. Summarize findings with actionable recommendations`, mcpServers: [{ serverName: "analytics-tools", serverUrl: "https://api.company.com/mcp" }]});
const result = await agentbase.runAgent({ message: "I need help with my order", system: "You are the main routing agent. Analyze requests and transfer to appropriate specialist.", agents: [ { name: "Order Support", description: "Handles order status, tracking, and delivery questions" }, { name: "Billing Support", description: "Handles payment, refunds, and billing questions" } ]});
// Session 1: Data analysis agentconst analysis = await agentbase.runAgent({ message: "Analyze sales data", system: "You are a data analyst."});// Session 2: Content writing agent (different session, different role)const content = await agentbase.runAgent({ message: "Write a blog post", system: "You are a content marketing specialist."});
const PROMPT_VERSIONS = { 'v1.0': 'You are a basic customer support agent.', 'v1.1': 'You are a customer support agent. Be friendly and helpful.', 'v2.0': `You are a customer support specialist. Approach: - Be empathetic and solution-focused - Provide step-by-step guidance - Escalate complex issues Constraints: - Verify identity before sharing account info - Follow company policies - Document all interactions`};// Use specific versionconst result = await agentbase.runAgent({ message: "Customer inquiry", system: PROMPT_VERSIONS['v2.0']});// A/B test different versionsconst versionToUse = Math.random() > 0.5 ? 'v2.0' : 'v1.1';
function selectPrompt(requestType: string): string { const prompts = { technical: "You are a senior software engineer...", business: "You are a business analyst...", support: "You are a customer support specialist...", sales: "You are a sales consultant..." }; return prompts[requestType] || prompts.support;}const result = await agentbase.runAgent({ message: userMessage, system: selectPrompt(detectRequestType(userMessage))});
Problem: Agent responses don’t align with system prompt instructionsSolutions:
Make guidelines more explicit and specific
Use imperative language (“Always…”, “Never…”, “Must…”)
Add examples of desired behavior in the prompt
Check for conflicting instructions
Combine with rules for stricter enforcement
Copy
// More explicit guidancesystem: `You are a customer support agent.ALWAYS:- Start with a friendly greeting- Acknowledge the customer's issue- Provide step-by-step solutions- Confirm issue resolution- Thank the customerNEVER:- Make promises you can't keep- Share confidential information- Argue with customers- Skip verification steps`
Prompt Too Long or Complex
Problem: System prompt is becoming unwieldySolutions:
Extract reference material to custom tools or documents
Focus on core role and critical guidelines
Use concise, structured formatting
Move detailed examples to separate documentation
Copy
// Concise versionsystem: `You are a data analyst (retail, 5+ years experience).Approach: EDA → validation → modeling → insightsTools: Python (pandas, sklearn), SQLOutput: Clear visualizations + actionable recommendationsConstraints: Cite sources, explain assumptions, highlight limitations`
Inconsistent Agent Behavior
Problem: Agent behaves differently across similar requestsSolutions:
Make prompts more deterministic with clear procedures
Add structured decision-making frameworks
Include examples of edge cases
Use rules for critical constraints
Copy
system: `You are a content moderator.Decision Framework:1. Check against policy list (hate speech, spam, etc.)2. If policy violation → flag and explain which policy3. If unclear → mark for human review4. If acceptable → approveAlways provide specific policy citation for flags.`
Prompt Context Lost in Long Sessions
Problem: Agent seems to forget system prompt guidance in long conversationsSolutions:
Reinforce critical points in user messages
Create new sessions for distinct conversation phases
Use rules to enforce critical constraints
Periodically remind agent of role in conversation
Copy
// Reinforce in message for critical tasksconst result = await agentbase.runAgent({ message: "Remember your role as a compliance officer. Review this contract...", session: existingSession, system: complianceOfficerPrompt});
Remember: Great system prompts are specific, structured, and tested. Start simple, iterate based on results, and refine as you understand your use case better.