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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
|
--[[
Copyright (c) 2024, Vsevolod Stakhov <vsevolod@rspamd.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]] --
local N = "gpt"
local E = {}
if confighelp then
rspamd_config:add_example(nil, 'gpt',
"Performs postfiltering using GPT model",
[[
gpt {
# Supported types: openai, ollama
type = "openai";
# Your key to access the API
api_key = "xxx";
# Model name
model = "gpt-4o-mini";
# Maximum tokens to generate
max_tokens = 1000;
# Temperature for sampling
temperature = 0.0;
# Timeout for requests
timeout = 10s;
# Prompt for the model (use default if not set)
prompt = "xxx";
# Custom condition (lua function)
condition = "xxx";
# Autolearn if gpt classified
autolearn = true;
# Reply conversion (lua code)
reply_conversion = "xxx";
# URL for the API
url = "https://api.openai.com/v1/chat/completions";
# Check messages with passthrough result
allow_passthrough = false;
# Check messages that are apparent ham (no action and negative score)
allow_ham = false;
# default send response_format field { type = "json_object" }
include_response_format = true,
}
]])
return
end
local lua_util = require "lua_util"
local rspamd_http = require "rspamd_http"
local rspamd_logger = require "rspamd_logger"
local lua_mime = require "lua_mime"
local ucl = require "ucl"
local fun = require "fun"
-- Exclude checks if one of those is found
local default_symbols_to_except = {
BAYES_SPAM = 0.9, -- We already know that it is a spam, so we can safely skip it, but no same logic for HAM!
WHITELIST_SPF = -1,
WHITELIST_DKIM = -1,
WHITELIST_DMARC = -1,
FUZZY_DENIED = -1,
REPLY = -1,
BOUNCE = -1,
}
local settings = {
type = 'openai',
api_key = nil,
model = 'gpt-4o-mini',
max_tokens = 1000,
temperature = 0.0,
timeout = 10,
prompt = nil,
condition = nil,
autolearn = false,
url = 'https://api.openai.com/v1/chat/completions',
symbols_to_except = default_symbols_to_except,
allow_passthrough = false,
allow_ham = false,
}
local function default_condition(task)
-- Check result
-- 1) Skip passthrough
-- 2) Skip already decided as spam
-- 3) Skip already decided as ham
local result = task:get_metric_result()
if result then
if result.passthrough and not settings.allow_passthrough then
return false, 'passthrough'
end
local score = result.score
local action = result.action
if action == 'reject' and result.npositive > 1 then
return false, 'already decided as spam'
end
if (action == 'no action' and score < 0) and not settings.allow_ham then
return false, 'negative score, already decided as ham'
end
end
-- We also exclude some symbols
for s, required_weight in pairs(settings.symbols_to_except) do
if task:has_symbol(s) then
if required_weight > 0 then
-- Also check score
local sym = task:get_symbol(s) or E
-- Must exist as we checked it before with `has_symbol`
if sym.weight then
if math.abs(sym.weight) >= required_weight then
return false, 'skip as "' .. s .. '" is found (weight: ' .. sym.weight .. ')'
end
end
lua_util.debugm(N, task, 'symbol %s has weight %s, but required %s', s,
sym.weight, required_weight)
else
return false, 'skip as "' .. s .. '" is found'
end
end
end
-- Check if we have text at all
local sel_part = lua_mime.get_displayed_text_part(task)
if not sel_part then
return false, 'no text part found'
end
-- Check limits and size sanity
local nwords = sel_part:get_words_count()
if nwords < 5 then
return false, 'less than 5 words'
end
if nwords > settings.max_tokens then
-- We need to truncate words (sometimes get_words_count returns a different number comparing to `get_words`)
local words = sel_part:get_words('norm')
nwords = #words
if nwords > settings.max_tokens then
return true, table.concat(words, ' ', 1, settings.max_tokens)
end
end
return true, sel_part:get_content_oneline()
end
local function maybe_extract_json(str)
-- Find the first opening brace
local startPos, endPos = str:find('json%s*{')
if not startPos then
startPos, endPos = str:find('{')
end
if not startPos then
return nil
end
startPos = endPos - 1
local openBraces = 0
endPos = startPos
local len = #str
-- Iterate through the string to find matching braces
for i = startPos, len do
local char = str:sub(i, i)
if char == "{" then
openBraces = openBraces + 1
elseif char == "}" then
openBraces = openBraces - 1
-- When we find the matching closing brace
if openBraces == 0 then
endPos = i
break
end
end
end
-- If we found a complete JSON-like structure
if openBraces == 0 then
return str:sub(startPos, endPos)
end
return nil
end
local function default_conversion(task, input)
local parser = ucl.parser()
local res, err = parser:parse_string(input)
if not res then
rspamd_logger.errx(task, 'cannot parse reply: %s', err)
return
end
local reply = parser:get_object()
if not reply then
rspamd_logger.errx(task, 'cannot get object from reply')
return
end
if type(reply.choices) ~= 'table' or type(reply.choices[1]) ~= 'table' then
rspamd_logger.errx(task, 'no choices in reply')
return
end
local first_message = reply.choices[1].message.content
if not first_message then
rspamd_logger.errx(task, 'no content in the first message')
return
end
-- Apply heuristic to extract JSON
first_message = maybe_extract_json(first_message) or first_message
parser = ucl.parser()
res, err = parser:parse_string(first_message)
if not res then
rspamd_logger.errx(task, 'cannot parse JSON gpt reply: %s', err)
return
end
reply = parser:get_object()
if type(reply) == 'table' and reply.probability then
lua_util.debugm(N, task, 'extracted probability: %s', reply.probability)
local spam_score = tonumber(reply.probability)
if not spam_score then
-- Maybe we need GPT to convert GPT reply here?
if reply.probability == "high" then
spam_score = 0.9
elseif reply.probability == "low" then
spam_score = 0.1
else
rspamd_logger.infox("cannot convert to spam probability: %s", reply.probability)
end
end
if type(reply.usage) == 'table' then
rspamd_logger.infox(task, 'usage: %s tokens', reply.usage.total_tokens)
end
return spam_score
end
rspamd_logger.errx(task, 'cannot convert spam score: %s', first_message)
return
end
local function ollama_conversion(task, input)
local parser = ucl.parser()
local res, err = parser:parse_string(input)
if not res then
rspamd_logger.errx(task, 'cannot parse reply: %s', err)
return
end
local reply = parser:get_object()
if not reply then
rspamd_logger.errx(task, 'cannot get object from reply')
return
end
if type(reply.message) ~= 'table' then
rspamd_logger.errx(task, 'bad message in reply')
return
end
local first_message = reply.message.content
if not first_message then
rspamd_logger.errx(task, 'no content in the first message')
return
end
-- Apply heuristic to extract JSON
first_message = maybe_extract_json(first_message) or first_message
parser = ucl.parser()
res, err = parser:parse_string(first_message)
if not res then
rspamd_logger.errx(task, 'cannot parse JSON gpt reply: %s', err)
return
end
reply = parser:get_object()
if type(reply) == 'table' and reply.probability then
lua_util.debugm(N, task, 'extracted probability: %s', reply.probability)
local spam_score = tonumber(reply.probability)
if not spam_score then
-- Maybe we need GPT to convert GPT reply here?
if reply.probability == "high" then
spam_score = 0.9
elseif reply.probability == "low" then
spam_score = 0.1
else
rspamd_logger.infox("cannot convert to spam probability: %s", reply.probability)
end
end
if type(reply.usage) == 'table' then
rspamd_logger.infox(task, 'usage: %s tokens', reply.usage.total_tokens)
end
return spam_score
end
rspamd_logger.errx(task, 'cannot convert spam score: %s', first_message)
return
end
local function get_meta_llm_content(task)
local url_content = "Url domains: no urls found"
if task:has_urls() then
local urls = lua_util.extract_specific_urls { task = task, limit = 5, esld_limit = 1 }
url_content = "Url domains: " .. table.concat(fun.totable(fun.map(function(u)
return u:get_tld() or ''
end, urls or {})), ', ')
end
local from_or_empty = ((task:get_from('mime') or E)[1] or E)
local from_content = string.format('From: %s <%s>', from_or_empty.name, from_or_empty.addr)
lua_util.debugm(N, task, "gpt urls: %s", url_content)
lua_util.debugm(N, task, "gpt from: %s", from_content)
return url_content, from_content
end
local function default_llm_check(task)
local ret, content = settings.condition(task)
if not ret then
rspamd_logger.info(task, "skip checking gpt as the condition is not met: %s", content)
return
end
if not content then
lua_util.debugm(N, task, "no content to send to gpt classification")
return
end
lua_util.debugm(N, task, "sending content to gpt: %s", content)
local upstream
local function on_reply(err, code, body)
if err then
rspamd_logger.errx(task, 'request failed: %s', err)
upstream:fail()
return
end
upstream:ok()
lua_util.debugm(N, task, "got reply: %s", body)
if code ~= 200 then
rspamd_logger.errx(task, 'bad reply: %s', body)
return
end
local reply = settings.reply_conversion(task, body)
if not reply then
return
end
if reply > 0.75 then
task:insert_result('GPT_SPAM', (reply - 0.75) * 4, tostring(reply))
if settings.autolearn then
task:set_flag("learn_spam")
end
elseif reply < 0.25 then
task:insert_result('GPT_HAM', (0.25 - reply) * 4, tostring(reply))
if settings.autolearn then
task:set_flag("learn_ham")
end
else
lua_util.debugm(N, task, "uncertain result: %s", reply)
end
end
local from_content, url_content = get_meta_llm_content(task)
local body = {
model = settings.model,
max_tokens = settings.max_tokens,
temperature = settings.temperature,
messages = {
{
role = 'system',
content = settings.prompt
},
{
role = 'user',
content = 'Subject: ' .. task:get_subject() or '',
},
{
role = 'user',
content = from_content,
},
{
role = 'user',
content = url_content,
},
{
role = 'user',
content = content
}
}
}
-- Conditionally add response_format
if settings.include_response_format then
body.response_format = { type = "json_object" }
end
upstream = settings.upstreams:get_upstream_round_robin()
local http_params = {
url = settings.url,
mime_type = 'application/json',
timeout = settings.timeout,
log_obj = task,
callback = on_reply,
headers = {
['Authorization'] = 'Bearer ' .. settings.api_key,
},
keepalive = true,
body = ucl.to_format(body, 'json-compact', true),
task = task,
upstream = upstream,
use_gzip = true,
}
rspamd_http.request(http_params)
end
local function ollama_check(task)
local ret, content = settings.condition(task)
if not ret then
rspamd_logger.info(task, "skip checking gpt as the condition is not met: %s", content)
return
end
if not content then
lua_util.debugm(N, task, "no content to send to gpt classification")
return
end
lua_util.debugm(N, task, "sending content to gpt: %s", content)
local upstream
local function on_reply(err, code, body)
if err then
rspamd_logger.errx(task, 'request failed: %s', err)
upstream:fail()
return
end
upstream:ok()
lua_util.debugm(N, task, "got reply: %s", body)
if code ~= 200 then
rspamd_logger.errx(task, 'bad reply: %s', body)
return
end
local reply = settings.reply_conversion(task, body)
if not reply then
return
end
if reply > 0.75 then
task:insert_result('GPT_SPAM', (reply - 0.75) * 4, tostring(reply))
if settings.autolearn then
task:set_flag("learn_spam")
end
elseif reply < 0.25 then
task:insert_result('GPT_HAM', (0.25 - reply) * 4, tostring(reply))
if settings.autolearn then
task:set_flag("learn_ham")
end
else
lua_util.debugm(N, task, "uncertain result: %s", reply)
end
end
local from_content, url_content = get_meta_llm_content(task)
local body = {
stream = false,
model = settings.model,
max_tokens = settings.max_tokens,
temperature = settings.temperature,
messages = {
{
role = 'system',
content = settings.prompt
},
{
role = 'user',
content = 'Subject: ' .. task:get_subject() or '',
},
{
role = 'user',
content = from_content,
},
{
role = 'user',
content = url_content,
},
{
role = 'user',
content = content
}
}
}
-- Conditionally add response_format
if settings.include_response_format then
body.response_format = { type = "json_object" }
end
upstream = settings.upstreams:get_upstream_round_robin()
local http_params = {
url = settings.url,
mime_type = 'application/json',
timeout = settings.timeout,
log_obj = task,
callback = on_reply,
keepalive = true,
body = ucl.to_format(body, 'json-compact', true),
task = task,
upstream = upstream,
use_gzip = true,
}
rspamd_http.request(http_params)
end
local function gpt_check(task)
return settings.specific_check(task)
end
local types_map = {
openai = {
check = default_llm_check,
condition = default_condition,
conversion = default_conversion,
require_passkey = true,
},
ollama = {
check = ollama_check,
condition = default_condition,
conversion = ollama_conversion,
require_passkey = false,
},
}
local opts = rspamd_config:get_all_opt('gpt')
if opts then
settings = lua_util.override_defaults(settings, opts)
if not settings.prompt then
settings.prompt = "You will be provided with the email message, subject, from and url domains, " ..
"and your task is to evaluate the probability to be spam as number from 0 to 1, " ..
"output result as JSON with 'probability' field."
end
local llm_type = types_map[settings.type]
if not llm_type then
rspamd_logger.warnx(rspamd_config, 'unsupported gpt type: %s', settings.type)
lua_util.disable_module(N, "config")
return
end
settings.specific_check = llm_type.check
if settings.condition then
settings.condition = load(settings.condition)()
else
settings.condition = llm_type.condition
end
if settings.reply_conversion then
settings.reply_conversion = load(settings.reply_conversion)()
else
settings.reply_conversion = llm_type.conversion
end
if not settings.api_key and llm_type.require_passkey then
rspamd_logger.warnx(rspamd_config, 'no api_key is specified for LLM type %s, disabling module', settings.type)
lua_util.disable_module(N, "config")
return
end
settings.upstreams = lua_util.http_upstreams_by_url(rspamd_config:get_mempool(), settings.url)
local id = rspamd_config:register_symbol({
name = 'GPT_CHECK',
type = 'postfilter',
callback = gpt_check,
priority = lua_util.symbols_priorities.medium,
augmentations = { string.format("timeout=%f", settings.timeout or 0.0) },
})
rspamd_config:register_symbol({
name = 'GPT_SPAM',
type = 'virtual',
parent = id,
score = 5.0,
})
rspamd_config:register_symbol({
name = 'GPT_HAM',
type = 'virtual',
parent = id,
score = -2.0,
})
end
|