Skip to main content

🛠️ Help Agent Implementation Guide

🎯 Goal: Live Help Agent in 60 Minutes

This guide shows exactly how to implement the global help agent using your existing infrastructure.

📋 Prerequisites Checklist

Existing Infrastructure ✅

  • FabFileService (file ingestion)
  • SmartChunker (document processing)
  • EmbeddingFactory (vectorization)
  • FabFileChunk (vector storage)
  • AgentDetectionFeature (agent routing)
  • Agent CRUD operations
  • MongoDB vector search

Required Access

  • Admin access to create new agent
  • Database access to verify ingestion
  • Code repository access to modify AgentDetectionFeature

🚀 Implementation Steps

Step 1: Upload Documentation (10 minutes)

# 1. Create docs archive
cd /docs-site/docs
zip -r bike4mind-docs.zip .

# 2. Upload via existing UI
# - Go to Knowledge → Upload Files
# - Upload bike4mind-docs.zip
# - Add tags: "help-system", "documentation", "official-docs"
# - Let the system chunk and vectorize automatically

Method B: Programmatic Upload (Alternative)

// Use existing FabFileService API
const uploadDocs = async () => {
const files = await glob('/docs-site/docs/**/*.md');

for (const file of files) {
await fabFileService.upload({
userId: 'system',
file: await fs.readFile(file),
filename: path.basename(file),
tags: ['help-system', 'documentation'],
metadata: {
category: getDocCategory(file), // features, guides, technical, etc.
source: 'docs-site'
}
});
}
};

Step 2: Create Help Agent (10 minutes)

// POST /api/agents
const helpAgent = {
"name": "Bike4Mind Assistant",
"description": "I'm your personal Bike4Mind expert! I have comprehensive knowledge of all features, guides, troubleshooting steps, and technical documentation. Ask me anything about Mementos, Questmaster, voice agents, file management, security, or any other Bike4Mind feature. I can help you get the most out of the platform!",

"triggerWords": ["@help", "@docs", "@assistant", "@support"],

"personality": {
"majorMotivation": "Empowering users to master Bike4Mind and achieve their goals",
"minorMotivation": "Sharing the excitement of discovering powerful feature combinations",
"quirk": "I love showing users workflows they didn't know were possible",
"flaw": "Sometimes I get so excited about features that I share more details than needed",
"description": "Enthusiastic, knowledgeable, and always ready to help users succeed"
},

"capabilities": [JSON.stringify({
"responseStyle": "Helpful and comprehensive with clear action steps",
"specialBehaviors": [
"documentation-expert",
"feature-guide",
"troubleshooter",
"workflow-advisor"
],
"knowledgeDomains": [
"features", "guides", "technical-docs",
"troubleshooting", "api-reference", "security"
]
})],

"identity": {
"gender": "non-binary",
"pronouns": {
"subject": "they",
"object": "them"
}
},

"visual": {
"avatar": "🤖",
"color": "#2563eb", // Blue theme
"style": "helpful-assistant"
},

"tags": ["system-agent", "help-system", "documentation"]
};

Step 3: Enhance Agent Context (25 minutes)

Modify AgentDetectionFeature.ts

// Add to: /b4m-core/packages/core/services/llm/features/AgentDetectionFeature.ts

import { fabFileChunkRepository } from '@b4m-core/database';

// Add this method to AgentDetectionFeature class
async getContextMessages(
quest: IChatHistoryItemDocument,
embeddingFactory: EmbeddingFactory,
message: string,
maxTokens: number,
modelInfo: ModelInfo
): Promise<IMessage[]> {
// Get existing agent context
const baseContext = await super.getContextMessages(...arguments);

// Check if help agent is active
const agentsToProcess: IAgent[] = (quest as any)._agentsToProcess || [];
const isHelpAgent = agentsToProcess.some(agent =>
agent.triggerWords?.some(trigger =>
['@help', '@docs', '@assistant', '@support'].includes(trigger)
)
);

if (isHelpAgent) {
try {
// Search documentation using existing vector infrastructure
const documentationContext = await this.searchDocumentation(
message,
embeddingFactory,
maxTokens * 0.3 // Use 30% of tokens for documentation context
);

this.service.logger.log(`🔍 Help agent found ${documentationContext.length} relevant docs`);

return [
...baseContext,
...documentationContext
];
} catch (error) {
this.service.logger.error('Error searching documentation:', error);
return baseContext;
}
}

return baseContext;
}

// Add new method for documentation search
private async searchDocumentation(
query: string,
embeddingFactory: EmbeddingFactory,
maxTokens: number
): Promise<IMessage[]> {
try {
// Create embedding for the query
const queryEmbedding = await embeddingFactory.createEmbedding(query);

// Search for relevant documentation chunks
const relevantChunks = await fabFileChunkRepository.findByVectorSimilarity({
vector: queryEmbedding,
limit: 5,
threshold: 0.7,
filters: {
// Only search documentation files
'fabFile.tags': { $in: ['help-system', 'documentation'] }
}
});

if (relevantChunks.length === 0) {
return [{
role: 'system',
content: 'No specific documentation found for this query. Provide general helpful guidance based on your knowledge of Bike4Mind features.'
}];
}

// Build context from found chunks
const contextParts = ['You have access to the following relevant documentation:'];
let totalTokens = 0;

for (const chunk of relevantChunks) {
const chunkContent = `
Source: ${chunk.fabFile?.filename || 'Documentation'}
Content: ${chunk.text}
---`;

const chunkTokens = this.estimateTokens(chunkContent);
if (totalTokens + chunkTokens > maxTokens) break;

contextParts.push(chunkContent);
totalTokens += chunkTokens;
}

contextParts.push(`
Please use this documentation to provide accurate, helpful answers.
Always cite your sources when referencing specific documentation.
If the documentation doesn't fully answer the question, supplement with your general knowledge but clearly distinguish between documented facts and general guidance.`);

return [{
role: 'system',
content: contextParts.join('\n')
}];

} catch (error) {
this.service.logger.error('Documentation search failed:', error);
return [{
role: 'system',
content: 'Documentation search temporarily unavailable. Provide helpful guidance based on your general knowledge of Bike4Mind.'
}];
}
}

// Helper method to estimate tokens (rough approximation)
private estimateTokens(text: string): number {
return Math.ceil(text.length / 4); // Rough estimate: 4 chars per token
}

Step 4: Test Implementation (10 minutes)

Basic Functionality Tests

# Test 1: Basic help query
"@help what are Mementos"

# Expected: Agent should respond with Memento explanation from docs
# Should cite documentation sources
# Should maintain helpful personality

# Test 2: Feature guidance
"@docs how do I use Questmaster"

# Expected: Step-by-step Questmaster usage guide
# Should include practical examples
# Should reference relevant documentation

# Test 3: Troubleshooting
"@support troubleshoot voice agents not working"

# Expected: Troubleshooting steps from voice agent docs
# Should provide systematic debugging approach
# Should cite technical documentation

# Test 4: Multiple queries in session
"@help file upload"
# Then follow up with: "how about sharing files?"

# Expected: Should maintain context between queries
# Should build on previous answers
# Should suggest related topics

Verification Checklist

  • Agent responds to @help, @docs, @assistant, @support
  • Responses include relevant documentation content
  • Sources are cited when available
  • Agent maintains personality and helpfulness
  • No errors in server logs during queries
  • Vector search is working (check MongoDB queries)

Step 5: Monitor & Optimize (5 minutes)

Check System Health

# 1. Verify documentation ingestion
# Check MongoDB for FabFileChunk documents with help-system tag

# 2. Monitor vector search performance
# Check logs for search timing and relevance scores

# 3. Track agent usage
# Monitor @help query frequency and response quality

Performance Tuning

// Adjust search parameters based on results
const searchConfig = {
similarity_threshold: 0.7, // Increase for more precise matches
max_chunks: 5, // Adjust based on response quality
token_budget: maxTokens * 0.3 // Balance context vs response space
};

🔧 Configuration & Customization

Agent Personality Variants

Concise Helper

const concisePersonality = {
"responseStyle": "Brief and actionable with essential details only",
"specialBehaviors": ["quick-answers", "essential-steps-only"]
};

Detailed Guide

const detailedPersonality = {
"responseStyle": "Comprehensive explanations with examples and context",
"specialBehaviors": ["in-depth-explanations", "workflow-examples"]
};

Troubleshooting Expert

const troubleshootingPersonality = {
"responseStyle": "Systematic problem-solving with step-by-step diagnostics",
"specialBehaviors": ["diagnostic-questions", "solution-verification"]
};

Documentation Categories

// Tag documentation by category for targeted responses
const docCategories = {
"features": ["mementos.md", "quest-master.md", "knowledge-management.md"],
"guides": ["quick-start.md", "getting-started/*"],
"technical": ["technical_docs/**/*"],
"troubleshooting": ["**/troubleshoot*.md", "**/debug*.md"],
"security": ["security/**/*"],
"api": ["api-reference.md", "**/api*.md"]
};

Advanced Query Routing

// Route different query types to different doc sections
const queryTypeRouting = {
"what is": "features",
"how do I": "guides",
"troubleshoot": "technical + troubleshooting",
"API": "api + technical",
"secure": "security"
};

🚨 Troubleshooting

Common Issues

"No documentation found"

# Check if files were properly ingested
db.fabfilechunks.find({"fabFile.tags": "help-system"}).count()

# Verify embeddings were created
db.fabfilechunks.find({"vector": {$exists: true}}).count()

"Agent not responding to @help"

# Verify agent trigger words
db.agents.find({"triggerWords": "@help"})

# Check AgentDetectionFeature logs
# Look for "AgentDetectionFeature.detectMentions" log entries

"Poor response quality"

# Adjust similarity threshold
similarity_threshold: 0.6 // Lower for more results
similarity_threshold: 0.8 // Higher for more precise matches

# Increase chunk limit
max_chunks: 8 // More context, longer responses
max_chunks: 3 // Less context, faster responses

🎉 Success Indicators

Immediate (Day 1)

  • Agent responds to @help queries
  • Documentation content appears in responses
  • No system errors during operation

Short-term (Week 1)

  • Users discover and use @help commands
  • Response quality meets user expectations
  • System performance remains stable

Medium-term (Month 1)

  • Reduced support ticket volume
  • Increased feature adoption from help guidance
  • Positive user feedback on help quality

🚀 Next Enhancements

Quick Wins (Week 2)

  • Smart follow-up suggestions
  • Query intent detection (what/how/troubleshoot)
  • Related topic recommendations

Advanced Features (Month 2)

  • Multi-modal responses (text + images)
  • Code example extraction
  • Proactive help suggestions
  • Voice integration

Enterprise Features (Month 3+)

  • Usage analytics dashboard
  • Content gap analysis
  • Auto-updating from documentation changes
  • Multi-language support

Ready to go live? This implementation leverages 100% of your existing infrastructure for maximum speed and reliability! 🚀