Skip to content

Commit

Permalink
fix(chat): fix message template replacement (Issue #2271) (#3160)
Browse files Browse the repository at this point in the history
  • Loading branch information
IlyaBondar authored Feb 13, 2025
1 parent fd51a8a commit 39eaca6
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 13 deletions.
7 changes: 3 additions & 4 deletions apps/chat/src/components/Chat/ChatInput/ReplayVariables.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useTranslation } from '@/src/hooks/useTranslation';
import {
getEntitiesFromTemplateMapping,
replaceDefaultValuesFromContent,
replaceTemplates,
} from '@/src/utils/app/prompts';

import { Prompt } from '@/src/types/prompt';
Expand Down Expand Up @@ -94,10 +95,8 @@ const ReplayVariablesDialog = () => {
)
return null;

const template = getEntitiesFromTemplateMapping(
activeMessage.templateMapping,
).reduce(
(acc, [key, value]) => acc.replaceAll(key, value),
const template = replaceTemplates(
getEntitiesFromTemplateMapping(activeMessage.templateMapping),
activeMessage.content,
);
const prompt: Prompt = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useTranslation } from '@/src/hooks/useTranslation';

import {
getEntitiesFromTemplateMapping,
replaceTemplates,
templateMatchContent,
} from '@/src/utils/app/prompts';

Expand Down Expand Up @@ -108,12 +109,8 @@ export const ChatMessageTemplatesModal = ({
]);

const templateResult = useMemo(() => {
return templates
.slice(0, templates.length - 1)
.reduce(
(acc, [key, value]) => acc.replaceAll(key.trim(), value.trim()),
message.content,
);
const items = templates.slice(0, templates.length - 1);
return replaceTemplates(items, message.content);
}, [message.content, templates]);

const isInvalid = useMemo(
Expand Down
12 changes: 12 additions & 0 deletions apps/chat/src/utils/app/prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,15 @@ export const getEntitiesFromTemplateMapping = (
? templateMapping
: Object.entries(templateMapping);
};

export const replaceTemplates = (
templates: TemplateMapping[],
text: string,
): string => {
if (!templates.length) return text;
const [[key, value], ...rest] = templates;
return text
.split(key.trim())
.map((part) => replaceTemplates(rest, part))
.join(value.trim());
};
7 changes: 4 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 39eaca6

Please sign in to comment.