Skip to content

Commit abbc57a

Browse files
authored
fix(formatMessages): Conform Name Property to OpenAI Expected Regex (#1076)
* fix(formatMessages): conform name property to OpenAI expected regex * fix(ci): prior test was expecting non-sanitized name input
1 parent fd99bac commit abbc57a

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

api/app/clients/prompts/formatMessages.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,16 @@ const formatMessage = ({ message, userName, assistantName, langChain = false })
4444
formattedMessage.name = assistantName;
4545
}
4646

47+
if (formattedMessage.name) {
48+
// Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$
49+
// https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2
50+
formattedMessage.name = formattedMessage.name.replace(/[^a-zA-Z0-9_-]/g, '_');
51+
52+
if (formattedMessage.name.length > 64) {
53+
formattedMessage.name = formattedMessage.name.substring(0, 64);
54+
}
55+
}
56+
4757
if (!langChain) {
4858
return formattedMessage;
4959
}

api/app/clients/prompts/formatMessages.spec.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,36 @@ describe('formatMessage', () => {
1818
});
1919
});
2020

21+
it('sanitizes the name by replacing invalid characters (per OpenAI)', () => {
22+
const input = {
23+
message: {
24+
sender: 'user',
25+
text: 'Hello',
26+
},
27+
userName: ' John$Doe@Example! ',
28+
};
29+
const result = formatMessage(input);
30+
expect(result).toEqual({
31+
role: 'user',
32+
content: 'Hello',
33+
name: '_John_Doe_Example__',
34+
});
35+
});
36+
37+
it('trims the name to a maximum length of 64 characters', () => {
38+
const longName = 'a'.repeat(100);
39+
const input = {
40+
message: {
41+
sender: 'user',
42+
text: 'Hello',
43+
},
44+
userName: longName,
45+
};
46+
const result = formatMessage(input);
47+
expect(result.name.length).toBe(64);
48+
expect(result.name).toBe('a'.repeat(64));
49+
});
50+
2151
it('formats a realistic user message', () => {
2252
const input = {
2353
message: {

api/app/clients/specs/OpenAIClient.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ describe('OpenAIClient', () => {
221221
isChatCompletion: true,
222222
});
223223
const hasUserWithName = result.prompt.some(
224-
(item) => item.role === 'user' && item.name === 'Test User',
224+
(item) => item.role === 'user' && item.name === 'Test_User',
225225
);
226226
expect(hasUserWithName).toBe(true);
227227
});

0 commit comments

Comments
 (0)