AI Conversation Management
Relevant source files
The following files were used as context for generating this wiki page:
The AI Conversation Management system is a cornerstone of the VineSight application, designed to provide farmers with a stateful, context-aware, and personalized AI assistant. Its primary purpose is to manage the entire lifecycle of a user's interaction with the AI, from the initial query to storing conversation history for long-term memory. This enables the AI to move beyond simple, stateless Q&A and become a proactive, learning advisor that remembers past interactions, decisions, and farm context.
This system is crucial for delivering Phase 3 features like the Personalized Crop Advisory and an Enhanced AI Chat Assistant with long-term memory. It integrates the frontend chat interface, a persistent storage layer powered by Supabase, and a sophisticated database schema designed for contextual understanding and relevance decay.
Sources: context/PRD.md:148-164, CLAUDE.md:32-36, 218-235
Architecture Overview
The conversation management system is composed of three main layers: the Frontend UI, the Persistence Service, and the Database. The AIAssistant component captures user input, the supabaseConversationStorage service handles all database operations, and the Supabase PostgreSQL database stores the conversation data securely.
This diagram illustrates the high-level data flow for managing conversations.
Frontend Component: AIAssistant
The AIAssistant.tsx component is the user-facing interface for all AI chat interactions. It manages the real-time state of a conversation, handles user inputs (text, voice, attachments), and orchestrates the communication with the backend services.
Sources: src/components/ai/AIAssistant.tsx.
Key Responsibilities
- State Management: Manages local state for messages, conversation history, loading status, and the current conversation ID.
- User Interaction: Captures user text input, handles file attachments, and integrates with the Web Speech API for voice-to-text.
- Conversation Lifecycle: Provides functions to start a new conversation (
startNewConversation), load a past one (loadConversation), and delete history (deleteConversation). - Context Building: Gathers and sends contextual information to the backend with each message, including farm data, language, and recent message history.
- Persistence: Interacts with the
supabaseConversationStorageservice to load and save conversations, ensuring data is not lost. - Quota Management: Tracks the user's daily question quota and disables input when the limit is exceeded.
Sources: src/components/ai/AIAssistant.tsx:43-65, 290-318, 597-622
Message Sending Flow
The handleSendMessage function is the core of the component's logic. It orchestrates query analysis, state updates, API calls, and persistence.
This sequence diagram shows the steps involved when a user sends a message.
Data Models and Types
The system relies on a set of well-defined TypeScript interfaces to ensure type safety and consistency between the frontend, backend, and database.
Sources: context/TYPES_AND_INTERFACES.md:315-336, src/components/ai/AIAssistant.tsx:36-39
Message Interface
The Message interface defines the structure of a single message within a conversation.
| Property | Type | Description |
|---|---|---|
id | string | Unique identifier for the message. |
role | 'user' | 'assistant' | The sender of the message. |
content | string | The text content of the message. |
timestamp | Date | When the message was created. |
language | 'en' | 'hi' | 'mr' | The language of the message content. |
attachments | Array<{...}> | Optional array of attachments (e.g., images). |
context | Record<string, any> | Metadata about the query, such as queryType. |
Sources: src/components/ai/AIAssistant.tsx:37, context/TYPES_AND_INTERFACES.md:326-336
Conversation Interface
The Conversation interface represents a complete chat session.
| Property | Type | Description |
|---|---|---|
id | string | Unique identifier for the conversation. |
title | string | An auto-generated title for the conversation. |
messages | Message[] | An array of all messages in the conversation. |
createdAt | Date | When the conversation was started. |
updatedAt | Date | When the last message was added. |
farmId | number | The farm this conversation is associated with. |
userId | string | The user who owns the conversation. |
lastMessageAt | Date | Timestamp of the very last message. |
messageCount | number | Total number of messages in the conversation. |
Sources: src/components/ai/AIAssistant.tsx:38, context/TYPES_AND_INTERFACES.md:316-325
Database Schema
The conversation data is persisted in a Supabase PostgreSQL database. The schema is designed to support long-term memory and efficient retrieval.
Sources: supabase/migrations/20250903_phase3_ai_schema.sql
ER Diagram
This diagram shows the relationship between conversations, context, users, and farms.
ai_conversation_context Table
This table is the core of the AI's long-term memory system. It stores discrete pieces of context extracted from conversations, which can be retrieved later to inform future responses.
| Column | Type | Description |
|---|---|---|
id | SERIAL PRIMARY KEY | Unique identifier for the context entry. |
conversation_id | INTEGER | Foreign key referencing ai_conversations.id. |
context_type | TEXT | The type of context (e.g., farm_state, decision_history, preference). |
context_data | JSONB | The actual contextual data stored as a JSON object. |
relevance_score | REAL | A score from 0.0 to 1.0 indicating the context's importance. |
decay_factor | REAL | A factor (e.g., 0.95) by which the relevance score decreases over time. |
created_at | TIMESTAMP | When the context was first created. |
last_referenced | TIMESTAMP | When the context was last used to inform a response. |
Sources: supabase/migrations/20250903_phase3_ai_schema.sql:114-123, CLAUDE.md:118-127
Long-Term Memory and Context Decay
The system is designed to make the AI smarter over time.
- Context Extraction: As the user chats, key information (e.g., a decision to use a specific fertilizer, a preference for organic methods) is extracted.
- Context Storage: This information is saved as a new row in the
ai_conversation_contexttable with an initialrelevance_score. - Context Retrieval: When generating new responses, the system queries for relevant historical context.
- Relevance Update: When a piece of context is used, its
last_referencedtimestamp is updated. - Decay: A periodic process (
decay_context_relevancefunction) runs to reduce therelevance_scoreof older, unreferenced context, ensuring that the AI's memory stays relevant. Context with a very low score is eventually deleted.
Sources: CLAUDE.md:218-235, supabase/migrations/20250903_phase3_ai_schema.sql:165-176
Row Level Security (RLS)
All conversation-related tables are protected by PostgreSQL's Row Level Security to ensure data privacy. A user can only access conversations and context that belong to them.
-- AI Conversation Context RLS
CREATE POLICY "Users can access context from their conversations" ON ai_conversation_context
FOR ALL USING (
EXISTS (
SELECT 1 FROM ai_conversations
WHERE ai_conversations.id = ai_conversation_context.conversation_id
AND ai_conversations.user_id = auth.uid()
)
);
Sources: supabase/migrations/20250903_phase3_ai_schema.sql:154-163, CLAUDE.md:255-264
Persistence Layer
The supabaseConversationStorage service, imported in AIAssistant.tsx, acts as an abstraction layer between the frontend component and the Supabase database. It encapsulates all CRUD (Create, Read, Update, Delete) operations for conversations.
Sources: src/components/ai/AIAssistant.tsx:40, 80-100, 616-622
Key Functions
saveConversation(conversation, userId): Atomically saves or updates a conversation. It uses an "upsert" logic, creating a new conversation or updating an existing one based on the conversation ID.loadConversations(userId, farmId): Retrieves all conversations for a given user and optional farm.deleteConversation(conversationId, userId): Deletes a conversation and its associated messages from the database.migrateFromLocalStorage(userId): A utility function to migrate conversation data from the browser's local storage to the Supabase database, ensuring a smooth transition for existing users.
Sources: src/components/ai/AIAssistant.tsx:80-100, 299-318, 616-622
Summary
The AI Conversation Management system is a sophisticated module that transforms the AI Assistant from a simple chatbot into a persistent, learning companion. By combining a reactive frontend, a robust persistence layer, and a purpose-built database schema with long-term memory capabilities, the system provides a foundation for the advanced, personalized AI advisory features that are central to the VineSight project's vision. The use of Row Level Security ensures that this sensitive conversational data remains private and secure for each user.