@@ -6,6 +6,7 @@ const { DB_WRITE } = require("../../services/database/consts");
6
6
const { TypeSpec } = require ( "../../services/drivers/meta/Construct" ) ;
7
7
const { TypedValue } = require ( "../../services/drivers/meta/Runtime" ) ;
8
8
const { Context } = require ( "../../util/context" ) ;
9
+ const { AsModeration } = require ( "./lib/AsModeration" ) ;
9
10
10
11
// Maximum number of fallback attempts when a model fails, including the first attempt
11
12
const MAX_FALLBACKS = 3 + 1 ; // includes first attempt
@@ -489,11 +490,6 @@ class AIChatService extends BaseService {
489
490
* Returns true if OpenAI service is unavailable or all messages pass moderation.
490
491
*/
491
492
async moderate ( { messages } ) {
492
- const svc_openai = this . services . get ( 'openai-completion' ) ;
493
-
494
- // We can't use moderation of openai service isn't available
495
- if ( ! svc_openai ) return true ;
496
-
497
493
for ( const msg of messages ) {
498
494
const texts = [ ] ;
499
495
if ( typeof msg . content === 'string' ) texts . push ( msg . content ) ;
@@ -508,8 +504,39 @@ class AIChatService extends BaseService {
508
504
509
505
const fulltext = texts . join ( '\n' ) ;
510
506
511
- const mod_result = await svc_openai . check_moderation ( fulltext ) ;
512
- if ( mod_result . flagged ) return false ;
507
+ let mod_last_error = null ;
508
+ let mod_result = null ;
509
+ try {
510
+ const svc_openai = this . services . get ( 'openai-completion' ) ;
511
+ mod_result = await svc_openai . check_moderation ( fulltext ) ;
512
+ if ( mod_result . flagged ) return false ;
513
+ } catch ( e ) {
514
+ console . error ( e ) ;
515
+ mod_last_error = e ;
516
+ }
517
+ try {
518
+ const svc_claude = this . services . get ( 'claude' ) ;
519
+ const chat = svc_claude . as ( 'puter-chat-completion' ) ;
520
+ const mod = new AsModeration ( {
521
+ chat,
522
+ model : 'claude-3-haiku-20240307' ,
523
+ } )
524
+ if ( ! await mod . moderate ( fulltext ) ) {
525
+ return false ;
526
+ }
527
+ mod_last_error = null ;
528
+ } catch ( e ) {
529
+ console . error ( e ) ;
530
+ mod_last_error = e ;
531
+ }
532
+
533
+ if ( mod_last_error ) {
534
+ this . log . error ( 'moderation error' , {
535
+ fulltext,
536
+ mod_last_error,
537
+ } ) ;
538
+ throw new Error ( 'no working moderation service' ) ;
539
+ }
513
540
}
514
541
return true ;
515
542
}
0 commit comments