File size: 13,004 Bytes
46df5f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""
LLM-based citation relevance evaluator.
Supports OpenAI, Anthropic, DeepSeek, Gemini, vLLM, and Ollama backends.
"""
import json
import re
from dataclasses import dataclass
from typing import Optional, Dict, Any
from enum import Enum
import os

import requests


class LLMBackend(Enum):
    OPENAI = "openai"
    ANTHROPIC = "anthropic"
    GEMINI = "gemini"
    VLLM = "vllm"
    OLLAMA = "ollama"
    DEEPSEEK = "deepseek"


@dataclass
class EvaluationResult:
    """Result of LLM citation evaluation."""
    entry_key: str
    relevance_score: int  # 1-5
    is_relevant: bool
    explanation: str
    context_used: str
    abstract_used: str
    line_number: Optional[int] = None
    file_path: Optional[str] = None
    error: Optional[str] = None
    
    @property
    def score_label(self) -> str:
        labels = {
            1: "Not Relevant",
            2: "Marginally Relevant", 
            3: "Somewhat Relevant",
            4: "Relevant",
            5: "Highly Relevant"
        }
        return labels.get(self.relevance_score, "Unknown")


class LLMEvaluator:
    """Evaluates citation relevance using LLM."""
    
    PROMPT_TEMPLATE = """You are an expert academic reviewer. Given a citation context from a LaTeX document and the cited paper's abstract, evaluate whether this citation is appropriate and relevant.

## Citation Context (from the manuscript):
{context}

## Cited Paper's Abstract:
{abstract}

## Task:
Evaluate the relevance and appropriateness of this citation. Consider:
1. Does the citation support the claim being made in the context?
2. Is the cited paper's topic related to the discussion?
3. Is this citation necessary, or could it be replaced with a more relevant one?

## Response Format:
Provide your response in the following JSON format:
{{
    "relevance_score": <1-5 integer>,
    "is_relevant": <true/false>,
    "explanation": "<brief explanation in 1-2 sentences>"
}}

Score guide:
- 1: Not relevant at all
- 2: Marginally relevant
- 3: Somewhat relevant
- 4: Relevant and appropriate
- 5: Highly relevant and essential

STRICTLY FOLLOW THE JSON FORMAT. Respond ONLY with the JSON object, no other text."""

    def __init__(
        self,
        backend: LLMBackend = LLMBackend.GEMINI,
        endpoint: Optional[str] = None,
        model: Optional[str] = None,
        api_key: Optional[str] = None
    ):
        self.backend = backend
        self.api_key = api_key or os.environ.get(f"{backend.name}_API_KEY")
        
        # Set defaults based on backend
        if backend == LLMBackend.OPENAI:
            self.endpoint = endpoint or "https://api.openai.com/v1/chat/completions"
            self.model = model or "gpt-5-mini"
        elif backend == LLMBackend.ANTHROPIC:
            self.endpoint = endpoint or "https://api.anthropic.com/v1/messages"
            self.model = model or "claude-4.5-haiku"
        elif backend == LLMBackend.DEEPSEEK:
            self.endpoint = endpoint or "https://api.deepseek.com/chat/completions"
            self.model = model or "deepseek-chat"
        elif backend == LLMBackend.OLLAMA:
            self.endpoint = endpoint or "http://localhost:11434/api/generate"
            self.model = model or "Qwen/qwen3-4B-Instruct-2507"
        elif backend == LLMBackend.VLLM:
            self.endpoint = endpoint or "http://localhost:8000/v1/chat/completions"
            self.model = model or "Qwen/qwen3-4B-Instruct-2507"
        elif backend == LLMBackend.GEMINI:
            self.endpoint = endpoint or "https://generativelanguage.googleapis.com/v1beta/models"
            self.model = model or "gemini-2.5-flash-lite"
    
    def evaluate(self, entry_key: str, context: str, abstract: str) -> EvaluationResult:
        """Evaluate citation relevance."""
        if not context or not abstract:
            return EvaluationResult(
                entry_key=entry_key,
                relevance_score=0,
                is_relevant=False,
                explanation="Missing context or abstract",
                context_used=context,
                abstract_used=abstract,
                error="Missing context or abstract for evaluation"
            )
        
        # Don't truncate - preserve full context and abstract
        prompt = self.PROMPT_TEMPLATE.format(context=context, abstract=abstract)
        
        try:
            if self.backend in (LLMBackend.OPENAI, LLMBackend.DEEPSEEK, LLMBackend.VLLM):
                response = self._call_openai_compatible(prompt)
            elif self.backend == LLMBackend.ANTHROPIC:
                response = self._call_anthropic(prompt)
            elif self.backend == LLMBackend.OLLAMA:
                response = self._call_ollama(prompt)
            elif self.backend == LLMBackend.GEMINI:
                response = self._call_gemini(prompt)
            else:
                raise ValueError(f"Unknown backend: {self.backend}")
            
            return self._parse_response(entry_key, response, context, abstract)
            
        except Exception as e:
            return EvaluationResult(
                entry_key=entry_key,
                relevance_score=0,
                is_relevant=False,
                explanation="",
                context_used=context,
                abstract_used=abstract,
                error=str(e)
            )
    
    def _call_openai_compatible(self, prompt: str) -> str:
        """Call OpenAI-compatible API (OpenAI, DeepSeek, vLLM)."""
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        
        payload = {
            "model": self.model,
            "messages": [
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.1,
            "max_tokens": 2000,
            "response_format": {"type": "json_object"} if self.backend == LLMBackend.OPENAI else None
        }
        
        response = requests.post(
            self.endpoint,
            json=payload,
            headers=headers,
            timeout=60
        )
        response.raise_for_status()
        
        data = response.json()
        choices = data.get("choices", [])
        if choices:
            return choices[0].get("message", {}).get("content", "")
        return ""

    def _call_anthropic(self, prompt: str) -> str:
        """Call Anthropic API."""
        headers = {
            "x-api-key": self.api_key,
            "anthropic-version": "2023-06-01",
            "content-type": "application/json"
        }
        
        payload = {
            "model": self.model,
            "max_tokens": 2000,
            "temperature": 0.1,
            "messages": [
                {"role": "user", "content": prompt}
            ]
        }
        
        response = requests.post(
            self.endpoint,
            json=payload,
            headers=headers,
            timeout=60
        )
        response.raise_for_status()
        
        data = response.json()
        content = data.get("content", [])
        if content and content[0].get("type") == "text":
            return content[0].get("text", "")
        return ""

    def _call_ollama(self, prompt: str) -> str:
        """Call Ollama API."""
        payload = {
            "model": self.model,
            "prompt": prompt,
            "stream": False,
            "options": {
                "temperature": 0.1,
                "num_predict": 2000
            },
            "format": "json"
        }
        
        response = requests.post(
            self.endpoint,
            json=payload,
            timeout=60
        )
        response.raise_for_status()
        
        return response.json().get("response", "")
    
    def _call_gemini(self, prompt: str) -> str:
        """Call Gemini API."""
        # Build URL with model
        url = f"{self.endpoint}/{self.model}:generateContent"
        if self.api_key:
            url += f"?key={self.api_key}"
        
        payload = {
            "contents": [
                {
                    "parts": [
                        {"text": prompt}
                    ]
                }
            ],
            "generationConfig": {
                "temperature": 0.1,
                "maxOutputTokens": 2000,
                "responseMimeType": "application/json"
            }
        }
        
        response = requests.post(
            url,
            json=payload,
            timeout=60
        )
        response.raise_for_status()
        
        candidates = response.json().get("candidates", [])
        if candidates:
            content = candidates[0].get("content", {})
            parts = content.get("parts", [])
            if parts:
                return parts[0].get("text", "")
        return ""
    
    def _parse_response(self, entry_key: str, response: str, context: str, abstract: str) -> EvaluationResult:
        """Parse LLM response."""
        # Try to extract JSON from response
        json_match = re.search(r'\{[^{}]*\}', response, re.DOTALL)
        
        data = {}
        if not json_match:
            # Try to parse the whole response as JSON
            try:
                data = json.loads(response.strip())
            except json.JSONDecodeError:
                pass
        else:
            try:
                data = json.loads(json_match.group())
            except json.JSONDecodeError:
                pass
        
        if not data:
             return EvaluationResult(
                entry_key=entry_key,
                relevance_score=0,
                is_relevant=False,
                explanation=response,
                context_used=context,
                abstract_used=abstract,
                error="Failed to parse LLM response as JSON"
            )
        
        # Extract fields
        relevance_score = data.get("relevance_score", 0)
        if isinstance(relevance_score, str):
            try:
                relevance_score = int(relevance_score)
            except ValueError:
                relevance_score = 0
        
        is_relevant = data.get("is_relevant", False)
        if isinstance(is_relevant, str):
            is_relevant = is_relevant.lower() in ("true", "yes", "1")
        
        explanation = data.get("explanation", "")
        
        return EvaluationResult(
            entry_key=entry_key,
            relevance_score=relevance_score,
            is_relevant=is_relevant,
            explanation=explanation,
            context_used=context,
            abstract_used=abstract
        )
    
    def test_connection(self) -> bool:
        """Test if LLM backend is accessible."""
        try:
            if self.backend == LLMBackend.OLLAMA:
                response = requests.get(
                    self.endpoint.replace("/api/generate", "/api/tags"),
                    timeout=5
                )
                return response.status_code == 200
            elif self.backend in (LLMBackend.OPENAI, LLMBackend.DEEPSEEK, LLMBackend.VLLM):
                # Test with a simple model list or empty completion
                headers = {"Authorization": f"Bearer {self.api_key}"}
                # Try listing models if possible, otherwise simple completion
                if "chat/completions" in self.endpoint:
                    # Try a minimal completion
                    payload = {
                        "model": self.model,
                        "messages": [{"role": "user", "content": "hi"}],
                        "max_tokens": 1
                    }
                    response = requests.post(self.endpoint, json=payload, headers=headers, timeout=10)
                    return response.status_code == 200
                else:
                    return False
            elif self.backend == LLMBackend.ANTHROPIC:
                headers = {
                    "x-api-key": self.api_key,
                    "anthropic-version": "2023-06-01",
                    "content-type": "application/json"
                }
                payload = {
                    "model": self.model,
                    "max_tokens": 1,
                    "messages": [{"role": "user", "content": "hi"}]
                }
                response = requests.post(self.endpoint, json=payload, headers=headers, timeout=10)
                return response.status_code == 200
            elif self.backend == LLMBackend.GEMINI:
                if not self.api_key:
                    return False
                url = f"{self.endpoint}/{self.model}:generateContent?key={self.api_key}"
                payload = {
                    "contents": [{"parts": [{"text": "test"}]}],
                    "generationConfig": {"maxOutputTokens": 10}
                }
                response = requests.post(url, json=payload, timeout=10)
                return response.status_code == 200
        except Exception:
            return False
        return False