# How to Use the ChatController API for AI Interactions in Project Nomad

> Learn to use Project Nomad's ChatController API for AI interactions. Manage chat sessions, persist history, and use local Ollama for inference with this guide.

- Repository: [Crosstalk Solutions/project-nomad](https://github.com/Crosstalk-Solutions/project-nomad)
- Tags: how-to-guide
- Published: 2026-03-16

---

**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`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/start/routes.ts), mapping HTTP verbs and URLs to controller actions (e.g., `router.get('/api/chat/suggestions', [ChatsController, 'suggestions'])`).
- **Controller (`ChatsController`)**: Located in [`admin/app/controllers/chats_controller.ts`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/controllers/chats_controller.ts), validates payloads using Vine schemas and delegates operations to `ChatService`.
- **Service (`ChatService`)**: Implemented in [`admin/app/services/chat_service.ts`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/services/chat_service.ts), encapsulates business logic for persisting `ChatSession` and `ChatMessage` models and coordinating with Ollama.
- **Models**: `ChatSession` and `ChatMessage` (defined in `admin/app/models/`) map to `chat_sessions` and `chat_messages` database tables.
- **Validation**: Request bodies are validated against schemas defined in [`admin/app/validators/chat.ts`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/validators/chat.ts) (`createSessionSchema`, `updateSessionSchema`, `addMessageSchema`).
- **Ollama Integration**: `ChatService` utilizes `OllamaService` ([`admin/app/services/ollama_service.ts`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/services/ollama_service.ts)) to forward generation requests to the local LLM.

### Request Processing Flow

When a client initiates a request:

1. The **Router** matches the URL pattern to the specific `ChatsController` method.
2. The **Controller** validates the incoming payload using Vine validation schemas.
3. Upon validation, the **Controller** invokes the appropriate `ChatService` method (e.g., `createSession`, `addMessage`, `getChatSuggestions`).
4. The **Service** layer reads from or writes to the `ChatSession` and `ChatMessage` models, optionally calling **OllamaService** for AI-generated content.
5. 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`** – `index` action lists all sessions (most recent first).
- **`POST /api/chat/sessions`** – `store` action creates a new chat session.
- **`GET /api/chat/sessions/:id`** – `show` action retrieves a single session with its messages.
- **`PUT /api/chat/sessions/:id`** – `update` action modifies session title or model.
- **`DELETE /api/chat/sessions/:id`** – `destroy` action deletes a session and cascades to its messages.
- **`POST /api/chat/sessions/:id/messages`** – `addMessage` action appends a message to a session.
- **`GET /api/chat/suggestions`** – `suggestions` action returns AI-generated conversation starters.
- **`DELETE /api/chat/sessions/all`** – `destroyAll` action 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`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/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:

```bash
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`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/validators/chat.ts) and returns the created session object:

```json
{
  "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:

```bash
curl https://your-host/api/chat/sessions/1

```

The response includes the full message array:

```json
{
  "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`:

```bash
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:

```json
{
  "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:

```bash
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:

```bash
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`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/constants/ollama.ts)). The service parses the LLM output, title-cases the results, and returns:

```json
{
  "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.ts`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/controllers/chats_controller.ts) provides RESTful endpoints for CRUD operations on chat sessions and messages.
- **Request validation** uses Vine schemas in [`admin/app/validators/chat.ts`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/validators/chat.ts) to ensure data integrity for session creation, updates, and message insertion.
- **Business logic** is encapsulated in `ChatService` ([`admin/app/services/chat_service.ts`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/admin/app/services/chat_service.ts)), which manages persistence and coordinates with `OllamaService` for 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 (via `OllamaController`), 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`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/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`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/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`](https://github.com/Crosstalk-Solutions/project-nomad/blob/main/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.