Skip to content

Commit 11d832a

Browse files
authored
fix(client-twitter): add mention deduplication utility
Currently, the Grok LLM is generating duplicate mentions at the beginning of responses. This adds a simple safeguard to deduplicate mentions before sending the tweet.
1 parent ea9d1c0 commit 11d832a

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

packages/client-twitter/src/utils.ts

+32-2
Original file line numberDiff line numberDiff line change
@@ -212,10 +212,13 @@ export async function sendTweet(
212212
})
213213
);
214214
}
215+
216+
const cleanChunk = deduplicateMentions(chunk.trim())
217+
215218
const result = await client.requestQueue.add(async () =>
216219
isLongTweet
217-
? client.twitterClient.sendLongTweet(chunk.trim(), previousTweetId, mediaData)
218-
: client.twitterClient.sendTweet(chunk.trim(), previousTweetId, mediaData)
220+
? client.twitterClient.sendLongTweet(cleanChunk, previousTweetId, mediaData)
221+
: client.twitterClient.sendTweet(cleanChunk, previousTweetId, mediaData)
219222
);
220223

221224
const body = await result.json();
@@ -361,3 +364,30 @@ function splitParagraph(paragraph: string, maxLength: number): string[] {
361364

362365
return chunks;
363366
}
367+
368+
function deduplicateMentions(paragraph: string) {
369+
// Regex to match mentions at the beginning of the string
370+
const mentionRegex = /^@(\w+)(?:\s+@(\w+))*(\s+|$)/;
371+
372+
// Find all matches
373+
const matches = paragraph.match(mentionRegex);
374+
375+
if (!matches) {
376+
return paragraph; // If no matches, return the original string
377+
}
378+
379+
// Extract mentions from the match groups
380+
let mentions = matches.slice(1).filter(Boolean) as string[];
381+
382+
// Deduplicate mentions
383+
mentions = [...new Set(mentions)];
384+
385+
// Reconstruct the string with deduplicated mentions
386+
const uniqueMentionsString = `@${mentions.join(' ')}`;
387+
388+
// Find where the mentions end in the original string
389+
const endOfMentions = paragraph.indexOf(matches[0]) + matches[0].length;
390+
391+
// Construct the result by combining unique mentions with the rest of the string
392+
return uniqueMentionsString + paragraph.slice(endOfMentions);
393+
}

0 commit comments

Comments
 (0)