File tree 2 files changed +71
-0
lines changed
src/backend/src/modules/puterai/lib
2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change @@ -46,4 +46,30 @@ module.exports = class Messages {
46
46
messages [ i ] = this . normalize_single_message ( messages [ i ] , params ) ;
47
47
}
48
48
}
49
+ static extract_text ( messages ) {
50
+ return messages . map ( m => {
51
+ if ( whatis ( m ) === 'string' ) {
52
+ return m ;
53
+ }
54
+ if ( whatis ( m ) !== 'object' ) {
55
+ return '' ;
56
+ }
57
+ if ( whatis ( m . content ) === 'array' ) {
58
+ return m . content . map ( c => c . text ) . join ( ' ' ) ;
59
+ }
60
+ if ( whatis ( m . content ) === 'string' ) {
61
+ return m . content ;
62
+ } else {
63
+ const is_text_type = m . content . type === 'text' ||
64
+ ! m . content . hasOwnProperty ( 'type' ) ;
65
+ if ( is_text_type ) {
66
+ if ( whatis ( m . content . text ) !== 'string' ) {
67
+ throw new Error ( 'text content must be a string' ) ;
68
+ }
69
+ return m . content . text ;
70
+ }
71
+ return '' ;
72
+ }
73
+ } ) . join ( ' ' ) ;
74
+ }
49
75
}
Original file line number Diff line number Diff line change @@ -25,4 +25,49 @@ describe('Messages', () => {
25
25
} ) ;
26
26
}
27
27
} ) ;
28
+ describe ( 'extract_text' , ( ) => {
29
+ const cases = [
30
+ {
31
+ name : 'string message' ,
32
+ input : [ 'Hello, world!' ] ,
33
+ output : 'Hello, world!' ,
34
+ } ,
35
+ {
36
+ name : 'object message' ,
37
+ input : [ {
38
+ content : [
39
+ {
40
+ type : 'text' ,
41
+ text : 'Hello, world!' ,
42
+ }
43
+ ]
44
+ } ] ,
45
+ output : 'Hello, world!' ,
46
+ } ,
47
+ {
48
+ name : 'irregular messages' ,
49
+ input : [
50
+ 'First Part' ,
51
+ {
52
+ content : [
53
+ {
54
+ type : 'text' ,
55
+ text : 'Second Part' ,
56
+ }
57
+ ]
58
+ } ,
59
+ {
60
+ content : 'Third Part' ,
61
+ }
62
+ ] ,
63
+ output : 'First Part Second Part Third Part' ,
64
+ }
65
+ ] ;
66
+ for ( const tc of cases ) {
67
+ it ( `should extract text from ${ tc . name } ` , ( ) => {
68
+ const output = Messages . extract_text ( tc . input ) ;
69
+ expect ( output ) . to . equal ( tc . output ) ;
70
+ } ) ;
71
+ }
72
+ } ) ;
28
73
} ) ;
You can’t perform that action at this time.
0 commit comments