Content
# AI Smart Tourism Planning Assistant (Backend)
> **Access Address**: [https://www.aitrip.chat/](https://www.aitrip.chat/)
>
> **Welcome to experience the intelligent tourism planning service!**
>
>
> Note: The current project has been discontinued. For the latest version of the AI Smart Tourism Planning Assistant, please visit the following addresses:
>
> **Frontend**: https://github.com/1937983507/ai-tourism-frontend
>
> **Backend**: https://github.com/1937983507/ai-tourism-backend
>
> **Agent Service**: https://github.com/1937983507/ai-tourism-agent
>
## 📖 Project Introduction
**AI-Tourism** is an intelligent tourism planning system. The backend is built based on **Spring Boot, LangChain4j, MySQL, MyBatis, Sa-Token** and other technology stacks.
The system integrates multiple AI capabilities (such as AI Service, MCP tools, etc.) to provide users with functions such as **personalized travel route recommendations, multi-turn conversations, and permission control**.
### 🎯 Core Features
- **Multi-turn conversation and context memory** - Intelligently understand user needs and maintain conversation coherence
- **Map route visualization** - Real-time display of travel routes, intuitive and easy to understand
- **MCP flexible hot-swappable** - Tools can be dynamically enabled/disabled, supporting hot-swapping
- **Unified Tool Registration** - All tools are managed uniformly, easy to expand
- **Security authentication and permission management** - Complete user permission system
---
### 🖼️ AI Smart Tourism Planning Frontend Effect Screenshot
<img src="assets/界面图.png">
### 📹 Video Effect
<img src="./assets/demo.gif">
**AI Smart Tourism Planning System**, combined with `SpringBoot` and `LangChain4j`, after the user inputs natural language, the **AI Agent** calls the **MCP Tool** and **Function Call** to obtain information such as weather and attractions, and the frontend simultaneously renders the text version of the route plan and the structured map route.
---
## 💡 Core Features and Architecture Characteristics
<img src="assets/核心特性与架构特点.png">
### 1. Deep integration of Agent service and map route rendering
- **Combination of graphics and text**: Provide travel guides combining graphics and text, and intuitively display daily routes in the front-end map
- **Streaming transmission**: Use `SSE` to stream the text version of the guide, and output structured data based on `JSON Schema` to support real-time rendering on the front end
### 2. Agent service based on Langchain4j
- **Task planning**: Based on `Prompt` engineering, design role positioning + task goals + constraint restrictions
- **Tool call**: `MCP` tools can be flexibly enabled/disabled through configuration, supporting hot-swapping; all `Tool` tools implement a unified interface and are registered to `ToolManager`, supporting runtime dynamic expansion and management
- **Multi-turn memory**: Implement `ChatMemoryStore`, short-term memory is preferentially stored in `Redis`, and automatically falls back to the database if not hit. `AI Service` instances are cached on a per-session basis, supporting multi-user concurrency and context isolation
- **Structured output route**: Output structured route data based on `JSON Schema` for front-end map rendering and display
- **Security protection**: `LangChain4j` input rail mechanism, pre-validates request content, prevents sensitive words and `Prompt` injection attacks, and ensures system stability
### 3. Unified tool registration and high-performance call anti-shake
- **MCP Tool**: Can be flexibly enabled/disabled through configuration, supporting hot-swapping
- **Function Call Tool**: Unified registration and scheduling through `ToolManager`, supporting runtime expansion
- **Performance optimization**: Introduce `Caffeine` cache to avoid repeated calls to external services. **The average response time has been reduced from 5.20s to 399μs**
### 4. Multi-turn conversation memory and instance isolation
- **Memory management**: Combine `Redis` and database to implement short-term memory, and use database to implement session history
- **Instance caching**: Cache `AI Service` instances based on `Caffeine`, support session isolation, improve service response performance and reduce duplicate instance creation
- **Performance improvement**: The average instance creation time is reduced from **13.1ms to 9.74ms, a performance improvement of 28.4%**
### 5. AI input rail and structured output
- **Security verification**: Pre-request verification, automatically filter sensitive words, malicious injection and other risky content to ensure system security
### 6. Sa-Token permission authentication
- **Token mechanism**: Combination of `JWT` short-term token + `Refresh Token` long-term token
- **Permission control**: Annotation-based permission control, fine-grained role management
### 7. SpringBoot engineering and RESTful design
- **Layered architecture**: Standard layered architecture (`Controller` - `Service` - `Mapper`)
- **Interface specification**: Unified interface, in line with `RESTful` specifications, easy for front-end and back-end collaboration
---
## 🏗️ Overall System Architecture
- **Frontend (ai-tourism-frontend)**: `Vue` application, responsible for interaction, map rendering and conversation display; call `POST /ai_assistant/chat-stream` through `SSE` to consume model output in real time
- **Access Layer (Controller + Authentication)**: Based on `Spring Boot REST`, use `Sa-Token` for login and permission verification (such as `@SaCheckLogin`, `@SaCheckPermission`)
- **Service Layer (MemoryChatServiceImpl)**: Unified processing of request verification, obtaining session history, obtaining session list, message storage, `SSE` streaming return
- **AI Service (MemoryAssistantServiceFactory)**: Build isolated `AssistantService` instances by session, integrate `OpenAI` streaming model, `MessageWindowChatMemory` (based on `ChatMemoryStore`), input rail, tool call; also use `Caffeine` to cache instances by `sessionId` to avoid repeated creation
- **Memory and History (Redis + MySQL)**:
- **Short-term conversation memory**: `CustomRedisChatMemoryStore` is managed based on `Redis`, and also supports `MySQL` message filling
- **Long-term history and structured data**: Write to `MySQL` through `MyBatis` (session table, message table, route JSON)
- **Tool Call (Function Call + MCP)**:
- **Function Call**: `ToolManager` unifies registration of all `BaseTool`
- **MCP**: Based on `LangChain4j MCP`, `McpClientService` creates `ToolProvider` through `SSE`
- **Cache and Anti-shake**:
- **Caffeine**: Cache `AssistantService` instances
- **Redis**: Carry conversation memory and reduce database read and write pressure
- **Observability and Monitoring**: `Micrometer` exposes `Prometheus` metrics (management endpoints have been opened `prometheus`); `AiModelMonitorListener`/`AiModelMetricsCollector` records request volume, duration, Token usage, error rate, cache hits, etc.; see `doc/Prometheus-Grafana.json` for Grafana dashboard
---
## 🚀 Quick Start
### 📂 Directory Structure
```
ai-tourism/
├── src/
│ ├── main/
│ │ ├── java/com/example/aitourism/
│ │ │ ├── ai/ # AI Agent, tools, memory, rails and other core AI capabilities
│ │ │ ├── config/ # Configuration classes (such as Sa-Token, CORS, Redis, etc.)
│ │ │ ├── controller/ # REST API controller
│ │ │ ├── dto/ # Data transfer object
│ │ │ ├── entity/ # Entity class
│ │ │ ├── exception/ # Global exception handling
│ │ │ ├── mapper/ # MyBatis mapping
│ │ │ ├── monitor/ # Monitoring and instrumentation
│ │ │ ├── service/ # Business logic and AI integration
│ │ │ └── util/ # Tool class
│ │ └── resources/
│ │ ├── application.yml # Main configuration file
│ │ └── prompt/ # AI Prompt template
├── sql/
│ └── create_table.sql # Database table structure
├── doc/
│ ├── API.md # API documentation
│ └── Prometheus-Grafana.json # Monitoring dashboard configuration
├── pom.xml # Maven dependencies
└── README.md
```
### 🛠️ Technology Stack and Dependencies
| Technical Category | Technology Stack | Version/Description |
|---------|--------|----------|
| **Core Framework** | Java | `21` |
| | Spring Boot | `3.5.6` |
| **AI Capability** | LangChain4j | AI capability integration |
| **Database** | MySQL | `9.4` |
| **ORM** | MyBatis & MyBatis-Spring-Boot | Data persistence |
| **Security Authentication** | Sa-Token | JWT authentication and permissions |
| | BCrypt | Password encryption |
| **Tool Library** | Lombok | Code simplification |
| | OkHttp3 | HTTP client |
| | Hutool | Tool library |
| **Cache** | Caffeine | Local high-performance cache |
| | Redis | Distributed cache and conversation memory |
| **Monitoring** | Prometheus + Grafana | Monitoring and visualization |
| | Micrometer | Spring Boot monitoring instrumentation |
> See [pom.xml](pom.xml) dependency configuration for details
### 🗄️ Database Structure
#### Main Table Design
| Table Name | Description | Main Fields |
|------|------|----------|
| `t_user` | User table | Mobile phone number, encrypted password, nickname, avatar, status, etc. |
| `t_role` | Role table | USER, ROOT and other roles |
| `t_permission` | Permission table | Permission identifier, permission name, etc. |
| `t_user_role` | User-role association table | User ID, role ID |
| `t_role_permission` | Role-permission association table | Role ID, permission ID |
| `t_refresh_token` | Refresh token table | User ID, token value, expiration time, etc. |
| `t_ai_assistant_sessions` | Session list | Session ID, user ID, session title, etc. |
| `t_ai_assistant_chat_messages` | AI assistant message table | Message ID, session ID, message content, role, etc. |
| `t_poi` | Attraction POI data | Attraction name, city, attraction description |
> See [sql/create_table.sql](sql/create_table.sql) for detailed fields and constraints
### ⚙️ Configuration Instructions
The main configuration items are in `src/main/resources/application.yml`:
- **Basic Configuration**: Port, database connection, logs, MyBatis, etc.
- **Security Authentication**: Sa-Token JWT key, token expiration time, permission annotations, etc.
- **AI Service**: OpenAI/MCP and other AI service parameters
### 🔗 Interface Instructions
#### User and Authentication Related
| Interface | Method | Description |
|------|------|------|
| `/auth/login` | `POST` | User login, return token, user information, etc. |
| `/auth/register` | `POST` | User registration, automatically assign USER role |
| `/auth/me` | `GET` | Get current user information and role |
| `/auth/refresh` | `POST` | Refresh token, improve security and experience |
| `/auth/logout` | `POST` | Logout, clear session |
| `/auth/disable` | `POST` | Disable user (requires permission) |
| `/auth/set_root` | `POST` | ROOT authorization (requires permission) |
#### AI Assistant Related
| Interface | Method | Description |
|------|------|------|
| `/ai_assistant/chat` | `POST` | Initiate AI streaming conversation, return travel route suggestions |
| `/ai_assistant/get_history` | `POST` | Get session history, support multi-turn tracing |
| `/ai_assistant/session_list` | `POST` | Get historical session list, display in pages |
> See [doc/API.md](doc/API.md) for detailed parameters and return format
---
## 📊 Monitoring and Observability (Prometheus + Grafana)
The system has integrated **Prometheus + Grafana** to achieve full-link monitoring, covering core indicators such as AI service calls, tool cache hits, Token consumption, response time, and error rate.
### 1. Data Collection
- **Metric Collection**: Use the `Micrometer` metric collection facade library, which is integrated in `Spring Boot Actuator`. `Micrometer` provides a unified API to define and record metrics, and can convert these metrics into the formats required by various monitoring systems, including `Prometheus`
- **Metric Definition**: Create an `AiModelMetricsCollector` class, in which use the `Micrometer API` to define core business metrics, mainly including:
- **Counter**: Used to count cumulative values, such as total number of AI requests, total Token consumption, total number of errors
- **Timer**: Used to record duration distribution, such as AI response time
- **Listening Mechanism**: Implement the `ChatModelListener` interface, rewrite the `onRequest`, `onResponse`, `onError` and other methods to listen to the corresponding key events, and then call `AiModelMetricsCollector` in them to record the defined metrics in real time
- **Endpoint Exposure**: `Spring Boot Actuator` will automatically create a `/actuator/prometheus` endpoint to expose all the metrics collected by `Micrometer` in the text format required by `Prometheus`
### 2. Data Storage
- **Prometheus Configuration**: Need to deploy an independent `Prometheus` service, add a capture task in its configuration file to allow it to periodically capture the data from the `/actuator/prometheus` endpoint exposed by the backend application
- **Configuration Example**:
```yaml
- job_name: "ai-tourism"
metrics_path: '/actuator/prometheus'
scrape_interval: 10s
static_configs:
- targets: ["localhost:8290"]
labels:
group: "prod"
endpoint: "actuator"
```
- **Data Storage**: `Prometheus` will efficiently store these time-series data in its built-in `TSDB` time-series database
### 3. Data Display
- **Grafana Connection**: Connect to the `Prometheus` service data in `Grafana`
- **Dashboard Creation**: Create a custom monitoring dashboard, and aggregate the original metric data stored in `Prometheus` into meaningful visualization charts by writing `PromQL` query statements
### 4. Monitoring Content
- **AI Model Metrics**: Total number of requests, success rate, average response time, Token consumption trend
- **Performance Comparison**: AI Service instance creation time comparison (cached/non-cached)
- **Cache Effect**: Tool cache hit rate, call response time comparison (cached/non-cached)
- **User Activity**: User/session activity ranking, error type distribution, etc.
### 5. Grafana Dashboard Screenshot
<img src="./assets/仪表盘.png">
> **For specific Grafana configuration**, please refer to the configuration file [doc/Prometheus-Grafana.json](doc/Prometheus-Grafana.json)
---
## 🛫 Deployment and Operation
### 📋 Environment Requirements
1. **JDK 21** - Java runtime environment
2. **Maven** - Project build tool
3. **MySQL 9.4** - Database
4. **Redis 3.0** - Cache service
### 🚀 Deployment Steps
#### 1️. Environment Preparation
```bash
# Install JDK 21
# Install MySQL 9.4
# Install Redis 3.0
```
#### 2️. Database Initialization
```bash
# Execute the database initialization script
mysql -u root -p < sql/create_table.sql
```
#### 3️. Configuration File
Edit `src/main/resources/application.yml`:
- Configure database connection information
- Configure AI API Key
- Configure other necessary parameters
#### 4️. Build and Run
```bash
# Build the project
mvn clean package
# Run the project
java -jar target/ai-tourism-0.0.1-SNAPSHOT.jar
```
#### 5️. Frontend Deployment
For the frontend, please refer to the [ai-tourism-frontend repository](https://github.com/1937983507/ai-tourism-frontend)
---
## 📬 Contact and Contribution
Any suggestions, feedback and contributions are welcome! If you need to communicate or have cooperation intentions, please contact us in the following ways:
- **WeChat**: `13859211947`
- **GitHub**: Submit Issue or PR to this repository
- **Frontend Project**: [ai-tourism-frontend repository](https://github.com/1937983507/ai-tourism-frontend)
If you have any bugs, requirements or ideas, please feel free to raise them, and we will respond actively.
Students who are also interested in Java + AI application development are welcome to exchange and discuss.
---
## 📝 License
This project is for learning purposes only and **commercial use without authorization is prohibited**.
---
## 📋 TODO list
### 1. AI Service Module
- [ ] Sometimes the route planned by AI may take a detour, so it needs to be optimized, such as adding a geocoding MCP Server.
- [ ] More MCP services can be provided, such as image retrieval.
- [ ] Display the called tools on the front-end rendering.
- [ ] **Conversational guided planning** can be adopted. First, confirm the user's preferences, number of people, budget, and pace through multiple rounds of questions and answers. The back-end introduces Prompt templating and reuse mechanisms (multiple travel style templates), and AI automatically switches according to the intention.
- [ ] Introduce **RAG**. The scenic spot content of a certain city can be stored in the vector database. If it can be retrieved, it will be directly handed over to the large model for output; if it cannot be retrieved, the MCP service will be called for retrieval. (At this time, a sufficient amount of scenic spot introductions + user travel notes need to be crawled from platforms such as Mafengwo, Xiaohongshu, and Ctrip)
- [ ] Introduce **LangGraph4j** to solve the problems of uncontrollable process, high task coupling, and poor scalability when directly calling AI Service.
- **Uncontrollable process**: All processes are encapsulated in a single AI service, and it is difficult to intervene in the intermediate process. (For example, if I want it to perform a weather query first, then a scenic spot query, and then search for photos of the scenic spot, such a process is difficult to control and intervene).
- **Task coupling**: Logically independent steps are coupled in a huge system prompt, which not only makes the prompt difficult to maintain and abnormally complex, but also increases the difficulty for AI to understand and execute tasks.
- **Poor scalability**: If you want to add new steps to the process, you can only solve it by modifying the system prompt in the current mode.
- [ ] Implement distributed rate limiting through **Redisson** to prevent malicious requests and resource abuse.
- [ ] Expansion and supplement of the **Redis** part, repair data consistency based on the bypass cache strategy.
- [ ] For user retention, build personalized user profiles (such as travel preferences) through memory.
- [ ] Implement collaboration between multiple Agents based on the A2A protocol, for example, it can be divided into:
- Intention Understanding Agent: Analyze user preferences, budget, and number of days
- Scenic Spot Recall Agent: Retrieve candidate scenic spots from RAG or MCP.
- Route Planning Agent: Obtain the coordinates of scenic spots based on geocoding results, and optimize the order of connecting scenic spots.
- Weather Traffic Agent: Detect accessibility and weather risks.
- Integration Agent: Comprehensive output itinerary.
### 2. Dialogue Module (Not Memory Module)
- [ ] The historical conversation list on the left supports pinning and unpinning.
- [ ] During the conversation, you can directly terminate the conversation.
- [ ] You can edit the previously initiated conversation content and then re-dialogue.
- [ ] The dialog box integrates example prompts, and users can directly select, modify and fill in before initiating a request.
### 3. User Module
- [ ] Improve the administrator's permissions, such as disabling a user, user authorization, etc.
- [ ] Verify the mobile phone number and password level during registration.
### 4. Other Modules
- [ ] Export the route planning results as an h5 page, and then you can scan the code with your mobile phone to display and call up mobile phone navigation.
- [ ] Support jumping to various scenic spot order services.
- [ ] After clicking on a location on the map, display its detailed information (including pictures and text descriptions).
- [ ] Currently, when the OSM map is locating a place, the positioning of some places will have a large error, and there is no good solution yet (because the server is still in Hong Kong, so use the OSM map first).
- [ ] Add an option to automatically render the map.
- [ ] Add a help page.
---
## 📚 Core Basic Code
Contains basic core code for calling **AI Service, MCP, Function Call**
> See [doc/coreBasicCode.md](doc/coreBasicCode.md) file
Connection Info
You Might Also Like
awesome-mcp-servers
A collection of MCP servers.
git
A Model Context Protocol server for Git automation and interaction.
Appwrite
Build like a team of hundreds
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.
oh-my-opencode
Background agents · Curated agents like oracle, librarians, frontend...
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.