Development Summary
Documents the development journey of an AI agent server, covering AI-assisted vs hand-written code, bugs, architecture, and production plans.
What this file does
Documents the development journey of an AI agent server, covering AI-assisted vs hand-written code, bugs, architecture, and production plans.
When to use it
- Reviewing how a developer split work between AI and manual coding
- Learning from common bugs in TypeScript, Groq SDK, and vector embeddings
- Understanding a request pipeline for an LLM-based agent with plugins
- Planning production readiness for a similar agent server project
Assumes this stack
Development Summary
AI-Generated vs Hand-Written Code
๐ค AI-Generated Components (with GitHub Copilot assistance):
- Plugin interface patterns: Leveraged AI suggestions for the BasePlugin abstract class structure
- Vector similarity algorithms: Used AI assistance for cosine similarity calculations and simple embedding logic
- Express middleware patterns: AI-generated error handling middleware structure
- API route validation: Copilot suggested input validation patterns
โ Hand-Written Components:
- Core agent orchestration logic: The main AgentService class flow was manually designed
- Custom plugin implementations: Weather and Math plugins logic written from scratch
- Session management strategy: Manual implementation of conversation memory and cleanup
- LLM integration: Hand-crafted system prompt engineering and message formatting
- Vector store architecture: Custom document chunking and retrieval strategy
- Plugin manager intelligence: Manual intent detection and plugin routing logic
๐ Bugs Faced and Solutions
1. TypeScript Module Resolution Issues
Problem: Initial setup had issues with ES modules vs CommonJS Solution:
- Configured
tsconfig.jsonwith propermodule: "commonjs" - Set
esModuleInterop: truefor better import compatibility - Used consistent import/export patterns throughout
2. Groq SDK Integration
Problem: Groq SDK types weren't initially available Solution:
- Installed
groq-sdkpackage separately - Added proper type definitions for Groq responses
- Implemented error handling for API failures
3. Vector Embedding Challenges
Problem: Initially planned to use OpenAI embeddings but needed offline solution Solution:
- Created custom simple embedding algorithm using word frequency
- Implemented cosine similarity for document matching
- Added normalization to prevent magnitude issues
4. Plugin Intent Detection
Problem: Agent wasn't reliably detecting when to call plugins Solution:
- Added multiple pattern variations for each plugin
- Implemented fallback logic when patterns don't match
5. Session Memory Management
Problem: Memory could grow indefinitely with long conversations Solution:
- Limited session history to last 20 messages
- Implemented automatic cleanup of old sessions
- Added memory-efficient message summarization
6. Async Error Handling
Problem: Express async errors weren't being caught properly Solution:
- Created
asyncHandlerwrapper function - Proper error middleware chain setup
- Consistent error response format
๐ง Agent Architecture Flow
Request Processing Pipeline:
- Input Validation: Validate message and session_id
- Session Management: Load/create session, add user message
- Context Retrieval: Search vector store for relevant documents
- Plugin Analysis: Detect intent and execute applicable plugins
- LLM Generation: Combine context, plugin results, and history for response
- Response Storage: Save assistant message to session
- Response Formatting: Return structured response with metadata
Memory Integration:
- Short-term: Recent conversation history (last 10 messages)
- Long-term: Vector store knowledge base (markdown documents)
- Plugin memory: Results from previous plugin executions in session
Context Injection Strategy:
System Prompt:
โโโ Base Instructions (role, capabilities)
โโโ Memory Summary (last 2 messages)
โโโ Retrieved Chunks (top 3 relevant documents)
โโโ Plugin Results (if any plugins executed)
โโโ Response Guidelines
๐ Plugin Call Routing
Intent Detection Process:
- Pattern Matching: Regex patterns for each plugin type
- Keyword Analysis: Look for specific trigger words/phrases
- Confidence Scoring: Multiple patterns increase confidence
- Parallel Execution: Multiple plugins can be triggered simultaneously
Weather Plugin Routing:
- Triggers: "weather", "forecast", "temperature", location names
- Extraction: Uses regex to find location in query
- Fallback: Mock data for demonstration purposes
Math Plugin Routing:
- Triggers: "calculate", "math", "solve", arithmetic operators
- Validation: Ensures expression contains only safe characters
- Security: Custom parser prevents code injection
๐๏ธ Vector Store Implementation
Document Processing:
- Loading: Read all .md files from data directory
- Chunking: Split into ~500 word chunks with overlap
- Embedding: Generate simple frequency-based vectors
- Indexing: Store with metadata for retrieval
Similarity Search:
- Query Embedding: Convert user query to vector
- Similarity Calculation: Cosine similarity with all documents
- Ranking: Sort by similarity score
- Selection: Return top K most relevant chunks
๐ฏ Production Considerations
Scalability Improvements Needed:
- Replace in-memory storage with persistent database
- Use proper embedding models (OpenAI, Sentence Transformers)
- Implement caching layer for frequently accessed data
- Add rate limiting and authentication
Security Enhancements:
- API key rotation mechanism
- Input sanitization for all endpoints
- CORS configuration for production
- Request logging and monitoring
Performance Optimizations:
- Batch processing for embeddings
- Lazy loading of vector store
- Connection pooling for external APIs
- Response caching for static queries
๐ Testing Strategy
Components to Test:
- Vector similarity search accuracy
- Plugin intent detection reliability
- Session management lifecycle
- LLM response quality
- API endpoint error handling
- Math expression safety validation
Integration Tests:
- End-to-end conversation flow
- Plugin execution with real queries
- Error recovery and graceful degradation
- Load testing with multiple sessions
๐ Deployment Notes
Current Status: Development Ready
- All core functionality implemented
- Local testing completed
- Documentation written
- Error handling in place
Next Steps for Production:
- Set up CI/CD pipeline
- Configure environment-specific settings
- Add monitoring and alerting
- Deploy to cloud provider (AWS/GCP/Azure)
- Set up domain and SSL certificates
- Configure load balancer if needed
Environment Configuration:
- Development: Local with hot reload
- Staging: Docker container with test data
- Production: Cloud deployment with real APIs
What's inside
8 sections: AI vs hand-written code, 6 bugs, request pipeline, plugin routing, vector store, production considerations, testing strategy, deployment notes
Change this for your project
- Replace
groq-sdkwith your own LLM SDK if not using Groq - Replace
data directorypath with your own markdown files location - Replace
WeatherandMathplugin implementations with your own plugins
Where it goes
Keep it in your repository where the agent or team that needs it will read it.
Worth borrowing
- Separating AI-generated from hand-written code to track ownership and debugging responsibility
- Using a structured request pipeline with session management, context retrieval, and plugin analysis
- Documenting bugs with problem and solution pairs for future reference
Related Documents
Building SupportX AI Assist: A Multi-Agent IT Support System
Describes building a multi-agent IT support system with AutoGen, Azure AI Search, and Gemini embeddings for instant issue resolution and automatic escalation.
Intelligent Document Query Platform โ GitHub-ready Low-Level Design (LLD)
Provides a copy-ready low-level design for a serverless document query platform with vector search and LLM integration.
Graph Matching with Topological Features
Teaches enhanced graph matching by combining spatial distances with node2vec and commute times embeddings, then applying the Hungarian algorithm.
Pulse โ Life Cofounder | Build Log
Documents a full-stack monorepo that ingests LinkedIn and GitHub data, generates embeddings in-browser, and provides a RAG chat with an AI cofounder.