A sophisticated Spring Boot application that provides intelligent LLM token optimization, multi-provider routing, and stateful chat capabilities with document processing features.
- Features
- Architecture
- Prerequisites
- Quick Start
- API Documentation
- Configuration
- Docker Deployment
- Development
- Testing
- Contributing
- License
- ๐ข Token Counting: Accurate token counting using OpenAI's tokenization algorithm (jtokkit)
- ๐ Document Optimization: Intelligent summarization to fit within LLM context windows
- ๐ฌ Stateful Chat: Persistent conversation sessions with context management
- ๐ File Processing: Upload and extract text from PDF, DOCX, and other document formats
- ๐ Web Scraping: Extract content from URLs for processing
- ๐ฏ Smart Routing: Intelligent LLM provider selection based on request complexity
- โก Fast Tier: Groq/Azure AI Inference for rapid responses
- ๐ง Gemini: Google's Gemini AI for advanced reasoning
- ๐ Fallback: Automatic provider switching for reliability
- ๐ Token Optimization: Real-time token usage optimization and compression
- ๐พ Chat History: Persistent chat sessions with intelligent compression
- ๐๏ธ Context Management: Dynamic context window management
- ๐ Metrics & Analytics: Detailed usage statistics and cost tracking
- ๐ Production Ready: Comprehensive error handling, logging, and validation
- ๐ณ Docker Support: Containerized deployment with health checks
- ๐ API Documentation: Full Swagger/OpenAPI integration
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Client Layer โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Web UI โ โ cURL/CLI โ โ Third-party Apps โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Spring Boot Gateway โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Controllers โ โ
โ โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ Token API โ โ Advanced Chat API โ โ โ
โ โ โ (v1) โ โ (v2) โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Orchestration Layer โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ AdvancedGatewayOrchestrationService โ โ โ
โ โ โ - Context Management โ โ โ
โ โ โ - Chat History Compression โ โ โ
โ โ โ - Smart Provider Routing โ โ โ
โ โ โ - Token Optimization โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Service Layer โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ โ
โ โ โ Token โ โ File Parser โ โ Web Scraper โ โ โ
โ โ โ Counter โ โ Service โ โ Service โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ โ
โ โ โ LLM โ โ Token โ โ Chat History โ โ โ
โ โ โ Summarizer โ โ Optimizer โ โ Repository โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Provider Registry โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ โ
โ โ โ Fast Tier โ โ Gemini โ โ Provider โ โ โ
โ โ โ (Groq/Azure) โ โ Provider โ โ Registry โ โ โ
โ โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ
โ External APIs โ โ Local Processing โ
โ โโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโ โ
โ โ Groq/Azure โ โ โ โ jtokkit โ โ
โ โ Inference โ โ โ โ (Tokenizer)โ โ
โ โโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโ โ
โ โ Gemini โ โ โ โ File โ โ
โ โ API โ โ โ โ Parsers โ โ
โ โโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ
- Java 21 or higher
- Maven 3.9+
- Docker (optional, for containerized deployment)
- API Keys:
- Groq/Azure AI Inference Key (free at console.groq.com or Azure AI)
- Gemini API Key (optional, from Google AI Studio)
git clone https://github.com/nikbarse1/demo-for-llm.git
cd demo-for-llmOption A: Using application-local.properties (Recommended for Development)
Create a file: src/main/resources/application-local.properties
# Fast Tier Configuration (Required)
llm.fast_tier.base_url=https://models.inference.ai.azure.com/chat/completions
llm.fast_tier.api.key=your-azure-groq-api-key-here
llm.fast_tier.model=gpt-4o-mini
# Gemini Configuration (Optional)
gemini.api.key=your-gemini-api-key-hereOption B: Using Environment Variables
# Fast Tier (Required)
export LLM_API_KEY=your-azure-groq-api-key-here
export LLM_MODEL=gpt-4o-mini
# Gemini (Optional)
export GEMINI_API_KEY=your-gemini-api-key-here# Build the project
mvn clean install
# Run the application
mvn spring-boot:runThe application will start on http://localhost:8080
- Web UI: http://localhost:8080
- Swagger UI: http://localhost:8080/swagger-ui.html
- API Docs: http://localhost:8080/v3/api-docs
The application provides two API versions:
Basic token counting and document optimization endpoints.
Endpoint: POST /api/v1/tokens/count
Request:
{
"text": "Hello, how are you today?"
}Response:
{
"modelUsed": "gpt-4",
"tokenCount": 7,
"characterCount": 26,
"estimatedCostNote": "1 token is roughly 4 characters in English.",
"timestamp": "2026-06-26T12:00:00"
}Endpoint: POST /api/v1/optimize
Request:
{
"document": "Your long document text here...",
"contextWindow": 16000
}Response:
{
"contextWindow": 16000,
"originalTokens": 5000,
"summaryTokens": 500,
"reductionPercentage": 90.0,
"headroomBefore": 11000,
"headroomAfter": 15500,
"summary": "Summarized content...",
"timestamp": "2026-06-26T12:00:00"
}Stateful chat with file upload, URL processing, and intelligent routing.
Endpoint: POST /api/v2/chat
Content-Type: multipart/form-data
Parameters:
instruction(required): The user's instruction or questionfile(optional): Document file (PDF, DOCX, TXT, etc.)url(optional): URL to scrape content fromchatId(optional): Session identifier for conversation continuityprovider(optional): LLM provider (GEMINI,FAST_TIER)contextWindow(optional): Context window size (default: 8192)X-Developer-Mode(header): Enable detailed metrics (default: false)
cURL Example:
# Basic chat
curl -X POST http://localhost:8080/api/v2/chat \
-F "instruction=What is machine learning?"
# Chat with file upload
curl -X POST http://localhost:8080/api/v2/chat \
-F "instruction=Summarize this document" \
-F "file=@document.pdf"
# Chat with URL
curl -X POST http://localhost:8080/api/v2/chat \
-F "instruction=What's the main topic of this page?" \
-F "url=https://example.com/article"
# Continue conversation
curl -X POST http://localhost:8080/api/v2/chat \
-F "instruction=Can you explain more about that?" \
-F "chatId=abc-123-session-id"Response:
{
"userReadableMessage": "Machine learning is a subset of AI...",
"sourceType": "TEXT_ONLY",
"wasOptimized": true,
"optimizationMetrics": {
"routingDecision": {
"requestedProvider": "GEMINI",
"executedProvider": "FAST_TIER",
"actionTaken": "DOWNGRADED_TO_CHEAPER_MODEL"
},
"billingImpact": {
"baselineTokens": 1500,
"billedTokens": 800,
"tokensSaved": 700,
"savingsPercentage": 46.67
},
"compressionInternals": {
"tokensProcessed": 1200,
"tokensOutput": 600,
"compressionReduction": 50.0
}
},
"chatId": "abc-123-session-id"
}| Property | Description | Default |
|---|---|---|
llm.fast_tier.base_url |
Fast tier API base URL | Azure AI Inference |
llm.fast_tier.api.key |
Fast tier API key | Required |
llm.fast_tier.model |
Fast tier model | gpt-4o-mini |
gemini.api.key |
Gemini API key | Optional |
server.port |
Server port | 8080 |
spring.servlet.multipart.max-file-size |
Max file upload size | 50MB |
web.scraper.timeout |
Web scraper timeout | 10000ms |
gpt-4o-mini(Fast, cost-effective)llama-3.1-8b-instant(Very fast)llama-3.3-70b-versatile(More accurate)mixtral-8x7b-32768(Large context window)
gemini-1.5-flash(Fast, versatile)gemini-1.5-pro(Advanced reasoning)gemini-1.0-pro(Legacy support)
The system automatically routes requests based on:
- Request Complexity: Simple queries use FAST_TIER
- Context Size: Large documents may trigger compression
- Provider Availability: Automatic fallback if provider fails
- Cost Optimization: Prefer cheaper models for simple tasks
# Copy and configure environment file
cp .env.example .env
# Edit .env with your API keys
# Start the application
docker-compose up -d
# View logs
docker-compose logs -f
# Stop the application
docker-compose down# Build the image
docker build -t llm-token-optimizer .
# Run the container with environment variables
docker run -d -p 8080:8080 \
-e LLM_API_KEY=your-azure-groq-api-key-here \
-e LLM_MODEL=gpt-4o-mini \
-e GEMINI_API_KEY=your-gemini-api-key-here \
--name llm-optimizer \
llm-token-optimizerdemo-for-llm/
โโโ src/
โ โโโ main/
โ โ โโโ java/com/example/demo/
โ โ โ โโโ advancePlusOne/ # Advanced gateway features
โ โ โ โ โโโ AdvancedGatewayOrchestrationService.java
โ โ โ โ โโโ AiChatController2.java
โ โ โ โ โโโ LlmProvider*.java # Provider implementations
โ โ โ โ โโโ GatewayMessage.java # Chat message model
โ โ โ โโโ config/ # Configuration classes
โ โ โ โ โโโ LLMConfig.java
โ โ โ โ โโโ OpenApiConfig.java
โ โ โ โ โโโ WebClientConfig.java
โ โ โ โโโ dto/ # Data transfer objects
โ โ โ โ โโโ UnifiedAnalysisResponse.java
โ โ โ โโโ exception/ # Custom exceptions & handlers
โ โ โ โ โโโ GlobalExceptionHandler.java
โ โ โ โ โโโ LLMServiceException.java
โ โ โ โโโ llmrouter/ # LLM routing services
โ โ โ โ โโโ PrimaryLlmService.java
โ โ โ โ โโโ GeminiResponse.java
โ โ โ โโโ *Controller.java # REST controllers (v1 API)
โ โ โ โโโ *Service.java # Core business logic
โ โ โ โโโ *.java # Models and utilities
โ โ โโโ resources/
โ โ โโโ static/ # Frontend files
โ โ โโโ application.properties
โ โโโ test/ # Unit tests
โโโ .github/workflows/ # CI/CD pipelines
โโโ Dockerfile
โโโ docker-compose.yml
โโโ pom.xml
โโโ README.md
# Run all tests
mvn test
# Run specific test class
mvn test -Dtest=TokenCounterServiceTest
# Run with coverage
mvn clean test jacoco:report# Check code style
mvn checkstyle:check
# Analyze dependencies
mvn dependency:analyze
# Security scan
mvn dependency-check:checkTest Token Counter:
curl -X POST http://localhost:8080/api/v1/tokens/count \
-H "Content-Type: application/json" \
-d '{
"text": "The quick brown fox jumps over the lazy dog"
}'Test Document Optimizer:
curl -X POST http://localhost:8080/api/v1/optimize \
-H "Content-Type: application/json" \
-d '{
"document": "This is a very long document that needs to be summarized...",
"contextWindow": 8000
}'- Navigate to http://localhost:8080
- Use the Token Counter tab to count tokens
- Use the Document Optimizer tab to summarize documents
- Token Budget Management: Calculate exact token counts before sending requests to manage costs
- Context Window Optimization: Automatically compress documents to fit within model limits
- Cost Estimation: Estimate API costs across different providers with detailed metrics
- Smart Routing: Automatically select the most cost-effective provider for each request
- Document Q&A: Upload documents and ask questions about their content
- Web Content Analysis: Extract and analyze information from URLs
- Multi-turn Conversations: Maintain context across multiple interactions
- Research Assistant: Process multiple documents and provide insights
- RAG Pipeline Integration: Pre-process documents for retrieval systems
- Content Analysis: Analyze large volumes of text efficiently
- Customer Support: Handle document-based customer queries
- Knowledge Management: Extract and summarize information from corporate documents
- Prompt Engineering: Optimize prompts for maximum efficiency
- API Gateway: Single interface for multiple LLM providers
- Load Testing: Test different providers under various conditions
- Performance Monitoring: Track token usage and costs in real-time
Problem: LLM service error or 401 Unauthorized
Solution:
- Verify your Groq API key is correct
- Check environment variable is set:
echo $LLM_API_KEY - Ensure API key has proper permissions
Problem: Port 8080 is already in use
Solution:
# Change port in application.properties
server.port=8081
# Or use environment variable
export SERVER_PORT=8081Problem: Docker build fails with memory error
Solution:
# Increase Docker memory limit
docker build --memory=4g -t llm-token-optimizer .Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow Java code conventions
- Add unit tests for new features
- Update documentation
- Ensure all tests pass
- Keep commits atomic and well-described
This project demonstrates:
- โ Spring Boot REST API development
- โ Integration with external LLM APIs
- โ Token counting for cost optimization
- โ Reactive programming with WebFlux
- โ Error handling and validation
- โ Docker containerization
- โ CI/CD with GitHub Actions
- โ API documentation with Swagger/OpenAPI
- Support for more LLM providers (OpenAI, Anthropic, etc.)
- Batch processing API
- Token cost calculator with pricing
- Multiple summarization strategies
- Streaming responses for large documents
- Rate limiting and caching
- User authentication
- Metrics and monitoring dashboard
This project is licensed under the MIT License - see the LICENSE file for details.
- jtokkit - OpenAI tokenizer for Java
- Groq - Fast LLM inference API
- Spring Boot - Application framework
For questions or support, please open an issue on GitHub.
Made with โค๏ธ for the LLM community