# Research Chat Answer Prompt

## Overview

This prompt is used by the **Research Chat** feature on the Shamra Academia homepage. It generates grounded, citation-backed answers to user questions by synthesizing information from relevant papers found in the Shamra Elasticsearch index.

## Feature Context

**Research Chat** (Ask AI) is a BizChat Copilot-style feature that allows users to ask research questions in natural language. The system:

1. **Extracts keywords** from the question (via `research_chat_keywords_prompt.md`)
2. **Searches Elasticsearch** for relevant papers in `arabic_research` index
3. **Filters papers** for relevance using LLM (via `research_chat_filter_prompt.md`)
4. **Generates answer** using this prompt with the filtered papers as context
5. **Appends references** with clickable links to papers

## Access Control

| User Type | Access |
|-----------|--------|
| Anonymous | ❌ Must log in |
| Logged-in (no subscription) | ❌ Must subscribe |
| Trial subscription | ✅ Uses trial credits |
| Paid subscription (starter+) | ✅ Full access |

**Cost**: 5 credits per question

## System Prompt

```
You are "Shamra Academia AI" - a specialized research assistant for answering academic questions.

CRITICAL LANGUAGE RULE:
- Detect the language of the user's question
- Respond in the SAME language as the question
- If the question is in Arabic, respond in formal Arabic
- If the question is in English, respond in English

STRICT RULES:
1. Answer ONLY based on the provided papers - do not invent information
2. Cite papers using their numbers [1], [2], [3]
3. Use formal academic language
4. Be concise and direct
5. If you cannot find a sufficient answer in the papers, clearly state that
6. Do NOT include a references section (it will be added automatically)

User's academic context:
{{USER_CONTEXT}}

{{CONVERSATION_CONTEXT}}
```

## User Prompt

```
Question: {{QUESTION}}

Available papers:
{{PAPERS_CONTEXT}}

Write a comprehensive answer based on these papers with citations.
```

## Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `{{USER_CONTEXT}}` | User's academic context from their profile | `Field: Computer Science / علوم الحاسوب`<br>`Interests: machine learning, NLP` |
| `{{CONVERSATION_CONTEXT}}` | Previous messages for follow-up questions | `Previous context:\n- User: What is AI?\n- Assistant: AI is...` |
| `{{QUESTION}}` | The user's research question | `ما هي أحدث تقنيات الذكاء الاصطناعي في الطب؟` |
| `{{PAPERS_CONTEXT}}` | Formatted list of relevant papers | See format below |

## Paper Context Format

Papers are formatted in English labels for consistent LLM processing:

```
[1] Title: تطبيقات الذكاء الاصطناعي في التشخيص الطبي
Abstract: يهدف هذا البحث إلى دراسة استخدام تقنيات التعلم العميق في تحليل الصور الطبية...
Field: الذكاء الاصطناعي

[2] Title: نظم دعم القرار الطبي المبنية على التعلم الآلي
Abstract: تقدم هذه الدراسة نموذجاً لنظام دعم قرار طبي يعتمد على خوارزميات التعلم الآلي...
Field: علوم الحاسوب
```

## Expected Output

The answer should:
1. **Directly address** the question asked
2. **Synthesize information** from multiple papers (not just list them)
3. **Use citation numbers** `[1]`, `[2]`, `[3]` to reference sources
4. **Acknowledge limitations** when data is sparse or insufficient
5. **Match the question language** (Arabic → Arabic, English → English)
6. **NOT include references** (appended automatically by the service)

## Example Output (Arabic Question)

```
بناءً على الأبحاث المتاحة في شمرا أكاديميا، يمكن تلخيص أحدث تقنيات الذكاء الاصطناعي في المجال الطبي كالتالي:

**1. التشخيص بالصور الطبية**
أوضحت الدراسة [1] أن تقنيات التعلم العميق، وتحديداً الشبكات العصبية الالتفافية (CNN)، حققت دقة تصل إلى 95% في تشخيص الأورام من صور الأشعة.

**2. نظم دعم القرار**
وفقاً لـ [2]، تساعد نظم دعم القرار الطبي المبنية على التعلم الآلي الأطباء في اتخاذ قرارات علاجية أفضل من خلال تحليل بيانات المرضى التاريخية.

**ملاحظة**: لم تتوفر في الأبحاث المتاحة معلومات كافية حول التطبيقات في الجراحة الروبوتية.
```

## Example Output (English Question)

```
Based on the available research in Shamra Academia, here are the key AI applications in healthcare:

**1. Medical Image Diagnosis**
Study [1] demonstrates that deep learning techniques, particularly CNNs, achieved 95% accuracy in tumor detection from radiological images.

**2. Clinical Decision Support**
According to [2], ML-based clinical decision support systems help physicians make better treatment decisions by analyzing historical patient data.

**Note**: The available papers did not contain sufficient information about robotic surgery applications.
```

## Technical Implementation

**File**: `src/Service/ResearchChatService.php` → `generateAnswer()` method

**Flow**:
1. Load this prompt via `loadPrompt('research_chat_answer')`
2. Replace variables with actual values
3. Call `AzureOpenAIService::chat()` with temperature 0.7
4. Append references section with paper links
5. Return complete answer

**Code snippet**:
```php
$prompt = $this->loadPrompt('research_chat_answer');

$systemPrompt = str_replace(
    ['{{USER_CONTEXT}}', '{{CONVERSATION_CONTEXT}}'],
    [$userContext, $conversationContext],
    $prompt['system']
);

$userPrompt = str_replace(
    ['{{QUESTION}}', '{{PAPERS_CONTEXT}}'],
    [$question, $paperContext],
    $prompt['user']
);
```

## LLM Parameters

| Parameter | Value | Rationale |
|-----------|-------|-----------|
| Temperature | 0.7 | Balanced creativity for synthesizing information |
| Max tokens | 2000 | Allow comprehensive answers with multiple sections |
| Model | GPT-5.2 (Azure) | Production model for quality responses |

## Post-Processing

After the LLM response, the service:
1. Detects question language (Arabic vs English)
2. Appends appropriate references header (`**المراجع:**` or `**References:**`)
3. Adds clickable markdown links for each paper: `[1] [Paper Title](URL)`

## Related Files

| File | Purpose |
|------|---------|
| `research_chat_keywords_prompt.md` | Extract search keywords from question |
| `research_chat_filter_prompt.md` | Score paper relevance |
| `src/Service/ResearchChatService.php` | Main service class |
| `src/Controller/ResearchChatController.php` | API endpoints |
| `src/Entity/ResearchChat.php` | Chat session entity |
| `src/Entity/ResearchChatMessage.php` | Message entity |

## Branding

- **English**: Shamra Academia AI
- **Arabic**: شمرا أكاديميا للذكاء الاصطناعي
