Skip to content

Commit 0009ede

Browse files
committed
dev: implement generic extract_text for ai messages
1 parent e9279ff commit 0009ede

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

src/backend/src/modules/puterai/lib/Messages.js

+26
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,30 @@ module.exports = class Messages {
4646
messages[i] = this.normalize_single_message(messages[i], params);
4747
}
4848
}
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+
}
4975
}

src/backend/src/modules/puterai/lib/messages.test.js

+45
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,49 @@ describe('Messages', () => {
2525
});
2626
}
2727
});
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+
});
2873
});

0 commit comments

Comments
 (0)