How to Use the ChatController API for AI Interactions in Project Nomad
The ChatController API exposes RESTful endpoints to create, manage, and converse with AI chat sessions that persist conversation history and delegate language model inference to a local Ollama instance.
The ChatController API serves as the primary HTTP interface in the Crosstalk-Solutions/project-nomad repository for managing stateful AI conversations. Built on the AdonisJS framework, this controller layer validates incoming requests, orchestrates business logic through dedicated services, and maintains conversation state via Lucid ORM models while interfacing with locally-hosted large language models.
Core Architecture
The API follows a layered architecture that separates routing, control, business logic, and data persistence:
- Routes: Defined in
admin/start/routes.ts, mapping HTTP verbs and URLs to controller actions (e.g.,router.get('/api/chat/suggestions', [ChatsController, 'suggestions'])). - Controller (
ChatsController): Located inadmin/app/controllers/chats_controller.ts, validates payloads using Vine schemas and delegates operations toChatService. - Service (
ChatService): Implemented inadmin/app/services/chat_service.ts, encapsulates business logic for persistingChatSessionandChatMessagemodels and coordinating with Ollama. - Models:
ChatSessionandChatMessage(defined inadmin/app/models/) map tochat_sessionsandchat_messagesdatabase tables. - Validation: Request bodies are validated against schemas defined in
admin/app/validators/chat.ts(createSessionSchema,updateSessionSchema,addMessageSchema). - Ollama Integration:
ChatServiceutilizesOllamaService(admin/app/services/ollama_service.ts) to forward generation requests to the local LLM.
Request Processing Flow
When a client initiates a request:
- The Router matches the URL pattern to the specific
ChatsControllermethod. - The Controller validates the incoming payload using Vine validation schemas.
- Upon validation, the Controller invokes the appropriate
ChatServicemethod (e.g.,createSession,addMessage,getChatSuggestions). - The Service layer reads from or writes to the
ChatSessionandChatMessagemodels, optionally calling OllamaService for AI-generated content. - The Controller serializes the result as JSON or returns the appropriate HTTP status code.
API Endpoints Reference
The ChatController exposes eight primary endpoints for session lifecycle management:
GET /api/chat/sessions–indexaction lists all sessions (most recent first).POST /api/chat/sessions–storeaction creates a new chat session.GET /api/chat/sessions/:id–showaction retrieves a single session with its messages.PUT /api/chat/sessions/:id–updateaction modifies session title or model.DELETE /api/chat/sessions/:id–destroyaction deletes a session and cascades to its messages.POST /api/chat/sessions/:id/messages–addMessageaction appends a message to a session.GET /api/chat/suggestions–suggestionsaction returns AI-generated conversation starters.DELETE /api/chat/sessions/all–destroyAllaction removes all sessions (admin utility).
All endpoints return JSON responses. Error conditions return appropriate HTTP status codes (404 for missing sessions, 500 for internal failures) as handled by try-catch blocks in admin/app/controllers/chats_controller.ts.
Managing Chat Sessions
Creating a New Session
To initialize a conversation, send a POST request to /api/chat/sessions with a JSON payload containing the session title and target model:
curl -X POST https://your-host/api/chat/sessions \
-H "Content-Type: application/json" \
-d '{"title":"My first AI chat","model":"llama3"}'
The controller validates this against createSessionSchema in admin/app/validators/chat.ts and returns the created session object:
{
"id": "1",
"title": "My first AI chat",
"model": "llama3",
"timestamp": "2024-10-12T14:23:07.000Z"
}
Retrieving Session History
Fetch a specific session and its associated messages using the show action:
curl https://your-host/api/chat/sessions/1
The response includes the full message array:
{
"id": "1",
"title": "My first AI chat",
"model": "llama3",
"timestamp": "2024-10-12T14:23:07.000Z",
"messages": [
{
"id": "7",
"role": "user",
"content": "What is the capital of France?",
"timestamp": "2024-10-12T14:23:15.000Z"
}
]
}
Sending and Storing Messages
Adding User Messages
To persist a user message without immediately generating an AI response, use the addMessage endpoint. This validates against addMessageSchema and supports roles of system, user, or assistant:
curl -X POST https://your-host/api/chat/sessions/1/messages \
-H "Content-Type: application/json" \
-d '{"role":"user","content":"Tell me a joke"}'
Response:
{
"id": "8",
"role": "user",
"content": "Tell me a joke",
"timestamp": "2024-10-12T14:25:30.000Z"
}
Generating AI Responses
The ChatController handles message persistence, but AI generation occurs through the OllamaController at /api/ollama/chat. This separation allows for flexible client-side implementations:
curl -X POST https://your-host/api/ollama/chat \
-H "Content-Type: application/json" \
-d '{
"sessionId": 1,
"messages": [{"role":"user","content":"Tell me a joke"}],
"model":"llama3"
}'
The OllamaController.chat() method forwards the request to OllamaService.chat(), which generates the assistant's reply and stores it via ChatService.addMessage().
AI-Powered Suggestions
The suggestions endpoint generates conversation starters by prompting Ollama with a system-defined template:
curl https://your-host/api/chat/suggestions
Under the hood, ChatService.getChatSuggestions() calls OllamaService.chat() with the SYSTEM_PROMPTS.chat_suggestions constant (defined in admin/constants/ollama.ts). The service parses the LLM output, title-cases the results, and returns:
{
"suggestions": [
"Explain quantum computing in simple terms",
"Help me plan a weekend trip to the mountains",
"Give me a quick recipe for a healthy smoothie"
]
}
Summary
- The ChatController API in
admin/app/controllers/chats_controller.tsprovides RESTful endpoints for CRUD operations on chat sessions and messages. - Request validation uses Vine schemas in
admin/app/validators/chat.tsto ensure data integrity for session creation, updates, and message insertion. - Business logic is encapsulated in
ChatService(admin/app/services/chat_service.ts), which manages persistence and coordinates withOllamaServicefor AI content generation. - Session management supports listing, creating, updating, and deleting individual sessions or all sessions at once via
DELETE /api/chat/sessions/all. - Message flow separates storage (via
POST /api/chat/sessions/:id/messages) from generation (viaOllamaController), enabling flexible client implementations.
Frequently Asked Questions
How does the ChatController validate incoming request data?
The controller uses Vine validation schemas defined in admin/app/validators/chat.ts. Incoming payloads for session creation are checked against createSessionSchema, updates against updateSessionSchema, and messages against addMessageSchema. If validation fails, the client receives an error response before any business logic executes.
What is the difference between the ChatController and OllamaController?
ChatController handles persistent storage of conversation state—creating sessions, storing messages, and retrieving history. OllamaController (in admin/app/controllers/ollama_controller.ts) handles the actual AI inference by accepting message arrays, forwarding them to the local Ollama instance, and storing the generated responses. The ChatController persists user messages, while the OllamaController generates and persists assistant replies.
Can I modify the AI behavior for chat suggestions?
Yes. The suggestion generation logic in ChatService.getChatSuggestions() uses the SYSTEM_PROMPTS.chat_suggestions constant defined in admin/constants/ollama.ts. Modifying this system prompt changes how Ollama generates the three starter suggestions, allowing customization of tone, topic focus, or format.
What happens when I delete a chat session?
Calling DELETE /api/chat/sessions/:id triggers the destroy action in ChatsController, which invokes ChatService to remove the session record. Due to the database relationship defined in the Lucid models, this operation cascades to delete all associated ChatMessage records for that session, ensuring clean data removal.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →