# AI Service Module

This module provides a unified interface for interacting with various AI language model providers, including OpenAI, Anthropic, Google Gemini, Groq, and others.

## Architecture Overview

The AI service module follows a provider pattern with:

- **Base Service**: Common interface and error handling (`base-service.ts`)
- **Provider Implementations**: Service-specific implementations for each AI provider
- **Factory**: Service instantiation and configuration (`factory.ts`)
- **Message Normalizer**: Cross-provider message format standardization (`message-normalizer.ts`)
- **Tool Converters**: Tool call format conversion between providers (`tool-converters.ts`)

## Source Field Implementation

### Background

In LibrAgent, messages can originate from two distinct sources:

- **Assistant-generated messages**: Direct responses from AI models
- **UI-generated messages**: Messages created by user interface actions (e.g., tool calls triggered by UI buttons)

### Problem Statement

Prior to this implementation, there was no way to distinguish between messages generated by the AI assistant versus those created by user interface interactions. This caused issues with:

1. **AI Service Compatibility**: Some AI services expect specific message roles and may misinterpret UI-generated messages
2. **Conversation Flow**: UI-generated tool calls were indistinguishable from AI-initiated tool calls
3. **Debugging**: Difficult to trace the origin of messages in conversation logs

### Solution: Source Field

Added an optional `source` field to the `Message` interface:

```typescript
interface Message {
  // ... existing fields
  source?: 'assistant' | 'ui';
}
```

#### Field Values

- `'assistant'`: Message generated by AI model (default behavior)
- `'ui'`: Message generated by user interface actions

### Implementation Details

#### 1. Message Interface Extension (`src/models/chat.ts`)

```typescript
export interface Message {
  id: string;
  content: MCPContent[];
  role: 'system' | 'user' | 'assistant' | 'tool';
  sessionId: string;
  assistantId?: string;
  tool_calls?: ToolCall[];
  tool_call_id?: string;
  createdAt: Date;
  source?: 'assistant' | 'ui'; // NEW: Source tracking field
}
```

#### 2. Utility Functions (`src/lib/chat-utils.ts`)

All message creation functions now accept an optional `source` parameter:

```typescript
export const createToolMessage = (
  content: MCPContent[],
  toolCallId: string,
  sessionId: string,
  assistantId?: string,
  source?: 'assistant' | 'ui', // NEW: Source parameter
): Message => {
  /* ... */
};

export const createToolMessagePair = (
  toolName: string,
  params: Record<string, unknown>,
  result: MCPContent[],
  toolCallId: string,
  sessionId: string,
  assistantId?: string,
  source?: 'assistant' | 'ui', // NEW: Source parameter
  delayMs?: number,
): [Message, Message] => {
  /* ... */
};
```

#### 3. UI Component Integration (`src/components/MessageRenderer.tsx`)

UI action handlers now explicitly set `source: 'ui'`:

```typescript
const handleUIAction = async (action: UIAction) => {
  const [callMessage, resultMessage] = createToolMessagePair(
    action.toolName,
    action.params,
    action.result,
    action.toolCallId,
    sessionId,
    assistantId,
    'ui', // EXPLICIT: Mark as UI-generated
  );
  // ...
};
```

#### 4. AI Service Conversion (`src/lib/ai-service/openai.ts`)

UI-generated messages are converted to user role for proper AI interpretation:

```typescript
const effectiveRole = m.source === 'ui' ? 'user' : m.role;
// This ensures UI-generated messages are treated as user input
// rather than assistant messages by the AI service
```

### Provider-Specific Handling

#### OpenAI (`openai.ts`)

- UI-sourced messages → converted to `'user'` role
- Assistant-sourced messages → retain original role
- Ensures compatibility with OpenAI's message format expectations

#### Anthropic (`anthropic.ts`)

- Currently inherits base behavior
- May need provider-specific handling if Anthropic has different requirements

#### Other Providers

- Gemini, Groq, Cerebras, etc. currently use default behavior
- Can be extended with provider-specific source handling as needed

### Benefits

1. **Clear Message Origin**: Easy to distinguish UI vs AI-generated messages
2. **AI Service Compatibility**: Proper message role conversion prevents misinterpretation
3. **Better Debugging**: Source tracking aids in troubleshooting conversation flows
4. **Future Extensibility**: Foundation for more sophisticated message handling
5. **Audit Trail**: Clear record of how messages were created

### Usage Examples

#### Creating UI-Generated Messages

```typescript
import { createToolMessagePair } from '@/lib/chat-utils';

// UI-triggered tool call
const [callMsg, resultMsg] = createToolMessagePair(
  'browser_click',
  { selector: '#submit-btn' },
  [{ type: 'text', text: 'Button clicked successfully' }],
  'call_123',
  sessionId,
  assistantId,
  'ui', // Mark as UI-generated
);
```

#### AI Service Message Conversion

```typescript
// In AI service implementation
const messages = conversation.map((m) => ({
  role: m.source === 'ui' ? 'user' : m.role,
  content: m.content,
  // ... other fields
}));
```

### Future Considerations

1. **Additional Source Types**: May need more granular source tracking (e.g., 'system', 'api', 'scheduled')
2. **Provider-Specific Requirements**: Different AI providers may need different source handling
3. **Message Filtering**: UI for filtering messages by source in conversation history
4. **Analytics**: Source-based analytics for understanding user interaction patterns
5. **Security**: Source validation to prevent spoofing of message origins

### Migration Notes

- **Backward Compatibility**: The `source` field is optional, existing code continues to work
- **Default Behavior**: Messages without `source` field default to `'assistant'` behavior
- **Gradual Adoption**: New UI features should explicitly set `source: 'ui'` when appropriate

### Testing

Ensure that:

- UI-generated messages are properly marked with `source: 'ui'`
- AI services correctly convert UI messages to appropriate roles
- Conversation flow remains intact
- No breaking changes to existing functionality

### Related Files

- `src/models/chat.ts` - Message interface definition
- `src/lib/chat-utils.ts` - Message creation utilities
- `src/components/MessageRenderer.tsx` - UI message generation
- `src/lib/ai-service/openai.ts` - OpenAI-specific source handling
