# AI Tools for Research Papers

## Status: ✅ PHASE 1 COMPLETE (March 12, 2026)

Inline AI action buttons on research pages, integrated with the existing button row (Download, Cite, Share).

---

## TODO (March 13, 2026)

- [ ] **Go to feed link on Share Research**: The "Go to feed" link after sharing currently only appears for AI response shares. Ensure it also appears when users share via the regular "Share Research" button.
- [ ] **Format AI output in /feed**: AI responses use markdown-style asterisks for bold (`**text**`). When displaying shared AI responses in the feed, convert these to actual bold formatting (`<strong>` tags).

---

## Design Decision (March 12, 2026)

**Previous approach**: Floating button (bottom-right corner) — had visibility issues, felt disconnected from the page.

**New approach**: Inline AI tools section directly below the existing action buttons, more prominent and integrated.

---

## Implementation Progress

### ✅ Phase 1: Ask Academia AI — COMPLETE

**Commits:**
- `05248596` — Initial implementation in `show.html.twig`
- `14fb51e7` — Added to `show_elastic.html.twig` (ES-only research pages)
- `41aa18d3` — Fixed `UserMan.isSubscribed()` method for credit check

**Files Modified:**
| File | Changes |
|------|---------|
| `src/Controller/ResearchAiController.php` | NEW — API endpoint `POST /api/research/{slug}/ask` |
| `src/Service/UserMan.php` | Added `isSubscribed()` and `getSubscription()` methods |
| `src/Service/Playground/UsageMonitorService.php` | Added `ask_ai_paper` operation (5 credits) |
| `show.html.twig` | AI tools section (CSS + HTML + JS) |
| `show_elastic.html.twig` | AI tools section (CSS + HTML + JS) |
| `translations/Research.ar.yml` | Added `ai_tools.*` keys |
| `translations/Research.en.yml` | Added `ai_tools.*` keys |

**Issues Encountered & Fixed:**
1. **Button not visible**: Initially added only to `show.html.twig` — user was viewing ES-only research (`show_elastic.html.twig`)
2. **Subscription check failed**: `userman.isSubscribed()` didn't exist — was calling undefined method. Fixed by adding methods to `UserMan.php`
3. **Property mismatch**: Template used `.creditsRemaining` but entity has `getAvailableCredits()` — fixed

**Legacy Chatbot:**
- Only 2 users, 16 conversations, last used Sep 2024
- Decided to replace with new inline approach
- Old code: `src/Controller/ChatBotController.php`, `BotManController.php`

### 🔲 Phase 2: AI Critique — NOT STARTED
### 🔲 Phase 3: Methodologies — NOT STARTED  
### 🔲 Phase 4: What's New — NOT STARTED

---

## UI Layout

```
┌──────────────────────────────────────────────────────┐
│  [Preview] [Download] [Cite] [Favorites] [Share]     │  ← Existing buttons
├──────────────────────────────────────────────────────┤
│  🤖 أدوات الذكاء الاصطناعي | AI Tools                │  ← New section header
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐     │
│  │ 💬 Ask AI   │ │ 📝 Critique │ │ 🔬 Methods  │     │
│  │   5 credits │ │  10 credits │ │  10 credits │     │
│  └─────────────┘ └─────────────┘ └─────────────┘     │
│  ┌─────────────┐                                     │
│  │ ✨ What's   │                                     │
│  │    New?     │                                     │
│  │  10 credits │                                     │
│  └─────────────┘                                     │
└──────────────────────────────────────────────────────┘
```

---

## AI Tools

| # | Button | Arabic | Function | Credits |
|---|--------|--------|----------|---------|
| 1 | **Ask Academia AI** | اسأل الذكاء الاصطناعي | Interactive Q&A about this paper | 5/question |
| 2 | **AI Critique** | نقد الذكاء الاصطناعي | Strengths, weaknesses, limitations analysis | 10 |
| 3 | **Methodologies** | المنهجية | Extract and explain research methods | 10 |
| 4 | **What's New?** | ما الجديد؟ | Novel contributions vs prior work | 10 |

---

## Auth Flow

**All buttons visible to everyone** (transparency encourages conversion).

| User State | Click Behavior |
|-----------|----------------|
| Not logged in | Modal → "Login to use AI Tools" → Login/Register |
| Logged in, no subscription | Modal → "Get 100 Free Credits" → Trial activation |
| Logged in, has credits | Execute AI tool |
| Logged in, zero credits | Modal → "Out of Credits" → Upgrade options |

---

## Response Display

Options for showing AI responses:

| Option | Pros | Cons |
|--------|------|------|
| **Modal** | Clean, focused | Covers content, feels disconnected |
| **Sidebar panel** | Can reference paper while reading | Complex layout, mobile issues |
| **Inline expansion** | Natural flow, stays in context | Pushes content down |
| **Dedicated page** | Full space, shareable URL | Navigation friction |

**Chosen**: **Inline expansion** — response appears below the AI tools section, can be collapsed.

---

## Implementation Steps

### Phase 1: Ask Academia AI Button ✅ COMPLETE
1. ✅ Add AI tools section HTML below existing buttons
2. ✅ Style the button row (gradient, modern look)
3. ✅ Implement auth state checking JS
4. ✅ Create new `ResearchAiController` with `/api/research/{slug}/ask` endpoint
5. ✅ Fix `UserMan` service with `isSubscribed()` / `getSubscription()` methods
6. ✅ Add translations (ar/en)
7. ✅ Add to both templates (`show.html.twig` + `show_elastic.html.twig`)

### Phase 2: AI Critique
1. Create new API endpoint `/api/research/{slug}/critique`
2. Build prompt template for critique generation
3. Store/cache results (avoid re-generating)
4. Display inline with expand/collapse

### Phase 3: Methodologies
1. Create `/api/research/{slug}/methodologies`
2. Prompt template focused on methods extraction
3. Structured output (study design, sample, analysis, etc.)

### Phase 4: What's New
1. Create `/api/research/{slug}/novelty`
2. Requires comparison with related papers (MLT/ES query)
3. Most complex — may need RAG over related papers

---

## Files to Modify

| File | Changes | Status |
|------|---------|--------|
| `show.html.twig` | Add AI tools section, JS handlers | ✅ Done |
| `show_elastic.html.twig` | Add AI tools section, JS handlers | ✅ Done |
| `Research.ar.yml` | Arabic translations | ✅ Done |
| `Research.en.yml` | English translations | ✅ Done |
| `ResearchAiController.php` | NEW controller for AI endpoints | ✅ Done |
| `UserMan.php` | Add `isSubscribed()` / `getSubscription()` | ✅ Done |
| `UsageMonitorService.php` | Credit deduction for new tools | ✅ Done |

---

## API Endpoints

### Implemented ✅

```
POST /api/research/{slug}/ask
  Body: { question: "..." }
  Response: { answer: "...", creditsUsed: 5, creditsRemaining: N }
  Auth: Required (PlaygroundSubscription with credits)
  Uses: AzureOpenAIService::chatSLM()
```

### Planned 🔲

```
GET /api/research/{slug}/critique
  Response: { critique: {...}, credits_used: 10, cached: true/false }

GET /api/research/{slug}/methodologies  
  Response: { methodologies: {...}, credits_used: 10 }

GET /api/research/{slug}/novelty
  Response: { novelty: {...}, credits_used: 10 }
```

---

## Caching Strategy

- **Critique, Methodologies, What's New**: Cache forever per research (content doesn't change)
- **Ask AI**: No cache (each question is unique)
- Credit deduction: Only on generation, not on cached retrieval
- Storage: `research_ai_analysis` table or JSON in existing entity

---

## Architecture Notes

**New Controller**: `src/Controller/ResearchAiController.php`
- Route: `POST /api/research/{slug}/ask`
- Fetches research content from ES (with 1-hour cache)
- Uses `AzureOpenAIService::chatSLM()` for cost-effective responses
- Deducts 5 credits via `UsageMonitorService`

**UserMan Integration**:
- Added `isSubscribed()` — checks if user has PlaygroundSubscription
- Added `getSubscription()` — returns PlaygroundSubscription entity
- Exposed in Twig as `userman.isSubscribed()` and `userman.getSubscription()`

**Template Integration**:
- Both `show.html.twig` and `show_elastic.html.twig` have AI tools
- ~260 lines of CSS (gradient buttons, chat panel, animations)
- ~230 lines of JS (auth checks, API calls, markdown rendering)
- Uses marked.js for rendering AI responses

---

## Next Action

**Phase 1 Complete!** Continue with **Phase 2: AI Critique** when ready.

```bash
# Phase 2 Files to create/edit:
# 1. ResearchAiController.php — add critique endpoint
# 2. Create prompt template for paper critique
# 3. Add caching layer for critique responses
# 4. Update templates with Critique button handler
```
