Skip to main content

Overview

The Mentorship module provides healthcare professionals with instant access to CUIDO, an AI-powered virtual mentor specialized in rural healthcare challenges. Built on Claude’s advanced language model, it offers empathetic, context-aware guidance available 24/7.
CUIDO uses Claude 3.5 Sonnet with specialized prompt engineering to understand the unique challenges faced by rural healthcare workers in Latin America.

Key Features

24/7 Availability

Always-on support for healthcare workers across all shifts and time zones

Context-Aware Responses

Tailored advice based on position, department, and specific situation

Emotional Support

Warm, empathetic responses focused on mental wellness and burnout prevention

Ethical Guidance

Help navigating complex ethical dilemmas in patient care

Claude AI Integration

Architecture

The mentorship system is built on a sophisticated Claude integration:
// From claudeService.js:1-214
class ClaudeService {
  constructor() {
    this.anthropic = null;
    this.model = 'claude-3-5-sonnet-20241022';
    this.defaultMaxTokens = 1000;
    this.defaultTemperature = 0.7;
    this.initialized = false;
  }
  
  // Lazy initialization - only initialize when first needed
  initialize() {
    if (this.initialized) return;
    
    if (!process.env.ANTHROPIC_API_KEY.startsWith('sk-ant-')) {
      throw new Error('ANTHROPIC_API_KEY has invalid format');
    }
    
    this.anthropic = new Anthropic({
      apiKey: process.env.ANTHROPIC_API_KEY
    });
    
    this.initialized = true;
  }
}

Response Generation

1

Initialize Claude Service

The service uses lazy initialization for optimal performance:
// From claudeService.js:48-150
async generateResponse(combinedPrompt, options = {}) {
  this.initialize(); // Only runs once
  
  const {
    maxTokens = this.defaultMaxTokens,
    temperature = this.defaultTemperature,
    systemMessage = null
  } = options;
  
  const requestConfig = {
    model: this.model,
    max_tokens: maxTokens,
    temperature: temperature,
    messages: [{
      role: 'user',
      content: combinedPrompt
    }]
  };
  
  if (systemMessage) {
    requestConfig.system = systemMessage;
  }
  
  const response = await this.anthropic.messages.create(requestConfig);
  
  return {
    response: response.content[0].text.trim(),
    usage: {
      inputTokens: response.usage.input_tokens,
      outputTokens: response.usage.output_tokens,
      totalTokens: response.usage.input_tokens + response.usage.output_tokens
    },
    metadata: {
      model: this.model,
      responseTime,
      stopReason: response.stop_reason
    }
  };
}
2

Build Specialized Prompt

The mentorship service constructs context-rich prompts:
// From mentorshipService.js:40-72
buildMentorshipSystemPrompt() {
  return `Eres CUIDO, un mentor virtual especializado en salud rural. Tu función es:
  
  1. Brindar acompañamiento emocional y profesional a trabajadores de la salud
  2. Dar consejos prácticos para situaciones del día a día
  3. Ayudar con dilemas éticos y comunicación con pacientes
  4. Ofrecer apoyo motivacional
  
  IMPORTANTE:
  - Responde en español con tono cálido y empático
  - Máximo 200 palabras por respuesta
  - Si es algo médico grave, recomienda consultar con supervisor
  - Enfócate en lo práctico y aplicable
  - Termina siempre con una pregunta de seguimiento`;
}

buildMentorshipUserPrompt(question, context) {
  let prompt = `Pregunta del trabajador de salud: "${question}"`;
  
  if (context.position) {
    prompt += `\nCargo: ${context.position}`;
  }
  
  if (context.department) {
    prompt += `\nDepartamento: ${context.department}`;
  }
  
  if (context.area) {
    prompt += `\nÁrea de consulta: ${context.area}`;
  }
  
  return prompt;
}
3

Generate Response

The service combines prompts and calls Claude:
// From mentorshipService.js:10-38
async provideMentorship(employeeId, question, context = {}) {
  const systemPrompt = this.buildMentorshipSystemPrompt();
  const userPrompt = this.buildMentorshipUserPrompt(question, context);
  
  const response = await claudeService.generateResponse(userPrompt, {
    maxTokens: 800,
    temperature: 0.8, // Higher temperature for more empathetic, varied responses
    systemMessage: systemPrompt
  });
  
  logger.info('Mentoría proporcionada', {
    employeeId,
    questionLength: question.length,
    responseLength: response.response.length
  });
  
  return {
    response: response.response,
    timestamp: new Date(),
    context: context.area || 'general'
  };
}

Prompt Engineering

System Prompt Design

The system prompt defines CUIDO’s personality and behavior:
Eres CUIDO, un mentor virtual especializado en salud rural.
CUIDO is positioned as a specialized mentor, not a generic chatbot. This establishes expertise and trust.
1. Brindar acompañamiento emocional y profesional a trabajadores de la salud
2. Dar consejos prácticos para situaciones del día a día
3. Ayudar con dilemas éticos y comunicación con pacientes
4. Ofrecer apoyo motivacional
Clear functional boundaries help Claude stay focused on relevant healthcare worker support.
- Responde en español con tono cálido y empático
- Máximo 200 palabras por respuesta
- Si es algo médico grave, recomienda consultar con supervisor
- Enfócate en lo práctico y aplicable
- Termina siempre con una pregunta de seguimiento
These constraints ensure:
  • Language: Spanish for Latin American users
  • Tone: Warm and empathetic, not clinical
  • Brevity: 200-word limit for mobile-friendly responses
  • Safety: Escalates serious medical issues to human supervisors
  • Practicality: Actionable advice over theory
  • Engagement: Follow-up questions maintain conversation

Context Enrichment

User prompts are enriched with employee context:
Pregunta del trabajador de salud: "¿Cómo manejo a un paciente agresivo?"
Cargo: Enfermera
Departamento: urgencias
Área de consulta: manejo_pacientes
This allows Claude to provide role-specific, department-aware guidance.

Usage Examples

Example 1: Emotional Support

POST /api/mentorship/ask
{
  "question": "Me siento agotada, cada día es más difícil motivarme para venir a trabajar",
  "context": {
    "position": "Enfermera",
    "department": "urgencias",
    "area": "bienestar_emocional"
  }
}

Example 2: Ethical Dilemma

POST /api/mentorship/ask
{
  "question": "Tengo un paciente que rechaza un tratamiento necesario por creencias religiosas. ¿Qué hago?",
  "context": {
    "position": "Médico General",
    "department": "consulta_externa",
    "area": "dilemas_eticos"
  }
}

Example 3: Communication Skills

POST /api/mentorship/ask
{
  "question": "¿Cómo le comunico malas noticias a la familia de un paciente?",
  "context": {
    "position": "Médico Interno",
    "department": "hospitalizacion",
    "area": "comunicacion"
  }
}

Temperature and Token Configuration

Response Parameters

const response = await claudeService.generateResponse(userPrompt, {
  maxTokens: 800,      // Limits response length (~600 words)
  temperature: 0.8,    // Higher temperature = more varied, empathetic responses
  systemMessage: systemPrompt
});
Temperature: 0.8 - Higher than typical (0.7) to encourage:
  • More natural, conversational tone
  • Varied phrasing across similar questions
  • Greater empathy in responses
  • Less rigid, more human-like answers
Max Tokens: 800 - Carefully chosen to:
  • Allow detailed responses (unlike 200-word constraint in prompt)
  • Prevent overly long responses that overwhelm users
  • Optimize API costs while maintaining quality
  • Target ~600 words maximum in Spanish

Safety and Escalation

Built-in Safety Measures

The system includes multiple safety layers:
1

Prompt-Level Safety

The system prompt includes:
Si es algo médico grave, recomienda consultar con supervisor
This instructs Claude to escalate serious medical issues to human supervisors.
2

Response Validation

if (!response.content || response.content.length === 0) {
  throw new AppError('Claude no generó respuesta', 500);
}

if (assistantMessage.type !== 'text') {
  throw new AppError('Tipo de respuesta no esperado de Claude', 500);
}
3

Error Handling

// From claudeService.js:122-149
catch (error) {
  if (error.status === 400) {
    throw new AppError('Solicitud inválida a Claude: ' + error.message, 400);
  }
  if (error.status === 401) {
    throw new AppError('API key de Claude inválida', 500);
  }
  if (error.status === 429) {
    throw new AppError('Límite de rate excedido para Claude API', 429);
  }
  if (error.status >= 500) {
    throw new AppError('Error interno del servicio Claude', 503);
  }
}
4

Usage Tracking

All interactions are logged for analytics and safety review:
logger.info('Mentoría proporcionada', {
  employeeId,
  questionLength: question.length,
  responseLength: response.response.length
});

API Reference

Ask Mentor

// Submit question to virtual mentor
{
  "question": "¿Cómo manejo el estrés del trabajo?",
  "context": {
    "position": "Enfermera",
    "department": "urgencias",
    "area": "bienestar_emocional"
  }
}

Context Parameters

ParameterTypeDescription
questionstringThe employee’s question (required)
context.positionstringEmployee’s job position
context.departmentstringEmployee’s department
context.areastringTopic area (bienestar_emocional, dilemas_eticos, comunicacion, manejo_pacientes)

Token Usage and Analytics

Every request tracks token usage for cost monitoring:
usage: {
  inputTokens: 245,
  outputTokens: 387,
  totalTokens: 632
},
metadata: {
  model: 'claude-3-5-sonnet-20241022',
  responseTime: 2.3,
  temperature: 0.8,
  maxTokens: 800,
  stopReason: 'end_turn'
}
Average Cost per Interaction:
  • Input tokens: ~250 tokens (0.003per1Ktokens)=0.003 per 1K tokens) = 0.00075
  • Output tokens: ~400 tokens (0.015per1Ktokens)=0.015 per 1K tokens) = 0.006
  • Total: ~$0.007 per mentorship interaction

Best Practices

Concise Questions

Encourage employees to ask focused questions for better responses

Provide Context

Always include position and department for relevant advice

Follow-up

Use CUIDO’s follow-up questions to deepen conversations

Human Escalation

Have a clear path to human supervisors for complex issues

Next Steps

Diagnostic Module

Learn about wellness surveys and risk detection

Claude Service

Deep dive into the Claude integration architecture

Microlearning

Explore the course and training system

API Reference

Complete API documentation for the Mentorship module

Build docs developers (and LLMs) love