-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_ollama_backend.php
More file actions
174 lines (142 loc) · 4.81 KB
/
test_ollama_backend.php
File metadata and controls
174 lines (142 loc) · 4.81 KB
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
<?php
/**
* Ollama Direct Test - PHP Backend
*/
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit;
}
// Only POST allowed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'Only POST allowed']);
exit;
}
// Get input
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
echo json_encode(['status' => 'error', 'message' => 'No input data']);
exit;
}
$question = $input['question'] ?? '';
$reference_answer = $input['reference_answer'] ?? '';
$student_answer = $input['student_answer'] ?? '';
$rubric = $input['rubric'] ?? [];
if (empty($question) || empty($reference_answer) || empty($student_answer)) {
echo json_encode(['status' => 'error', 'message' => 'Missing fields']);
exit;
}
// Config
$ollama_url = 'http://localhost:11434';
$model = 'mistral';
// Build prompt
$rubric_text = "Evaluation Rubric:\n";
$total_marks = 0;
foreach ($rubric as $r) {
$rubric_text .= "- {$r['criteria']}: {$r['marks']} marks\n";
$total_marks += (int)$r['marks'];
}
$prompt = "You are an expert examiner evaluating a student's answer.
QUESTION: $question
REFERENCE ANSWER: $reference_answer
$rubric_text
STUDENT'S ANSWER: $student_answer
---
Evaluate strictly based on the rubric. Return ONLY valid JSON in this exact format:
{
\"total_score\": 8,
\"criterion_marks\": [
{\"criteria\": \"Understanding\", \"awarded_marks\": 4, \"reason\": \"Good grasp of concepts\"},
{\"criteria\": \"Accuracy\", \"awarded_marks\": 3, \"reason\": \"Mostly correct\"},
{\"criteria\": \"Completeness\", \"awarded_marks\": 1, \"reason\": \"Missing details\"}
],
\"feedback\": \"Overall good answer but needs more detail.\",
\"strengths\": [\"Clear explanation\", \"Good structure\"],
\"improvements\": [\"Add more examples\", \"Explain edge cases\"]
}
Return ONLY the JSON, no other text.";
// Call Ollama
$start = microtime(true);
$ch = curl_init("{$ollama_url}/api/generate");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'model' => $model,
'prompt' => $prompt,
'stream' => false,
'temperature' => 0.3,
'format' => 'json'
])
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
$elapsed = round(microtime(true) - $start, 2);
if ($curl_error) {
echo json_encode(['status' => 'error', 'message' => "Curl error: $curl_error", 'elapsed' => $elapsed]);
exit;
}
if ($http_code !== 200) {
echo json_encode(['status' => 'error', 'message' => "HTTP $http_code", 'elapsed' => $elapsed]);
exit;
}
// Parse Ollama response
$data = json_decode($response, true);
if (!$data || !isset($data['response'])) {
echo json_encode(['status' => 'error', 'message' => 'Invalid Ollama response', 'elapsed' => $elapsed]);
exit;
}
$generated = $data['response'];
// Extract JSON from response
$generated = trim($generated);
// Remove markdown code blocks if present
$generated = preg_replace('/^```json\s*/i', '', $generated);
$generated = preg_replace('/\s*```$/', '', $generated);
$generated = trim($generated);
// Parse evaluation JSON
$evaluation = json_decode($generated, true);
if (json_last_error() !== JSON_ERROR_NONE) {
// Try to find JSON in text
if (preg_match('/\{.*\}/s', $generated, $matches)) {
$evaluation = json_decode($matches[0], true);
}
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode([
'status' => 'error',
'message' => 'JSON parse error: ' . json_last_error_msg(),
'generated_text' => substr($generated, 0, 500),
'elapsed' => $elapsed
]);
exit;
}
}
// Validate and fill defaults
if (!isset($evaluation['total_score'])) {
$score = 0;
if (isset($evaluation['criterion_marks'])) {
foreach ($evaluation['criterion_marks'] as $c) {
$score += (int)($c['awarded_marks'] ?? 0);
}
}
$evaluation['total_score'] = $score;
}
$evaluation['feedback'] = $evaluation['feedback'] ?? 'No feedback provided';
$evaluation['criterion_marks'] = $evaluation['criterion_marks'] ?? [];
$evaluation['strengths'] = $evaluation['strengths'] ?? [];
$evaluation['improvements'] = $evaluation['improvements'] ?? [];
// Success
echo json_encode([
'status' => 'success',
'message' => 'Evaluation completed',
'elapsed' => $elapsed,
'model_used' => $model,
'evaluation' => $evaluation
]);