mirror of
https://github.com/langgenius/dify.git
synced 2026-06-23 20:41:17 +08:00
Co-authored-by: Jingyi-Dify <jingyi.qi@dify.ai> Co-authored-by: yyh <yuanyouhuilyz@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: hjlarry <hjlarry@163.com> Co-authored-by: Bond Zhu <783504079@qq.com> Co-authored-by: Yansong Zhang <916125788@qq.com> Co-authored-by: yyh <92089059+lyzno1@users.noreply.github.com>
76 lines
2.2 KiB
TypeScript
76 lines
2.2 KiB
TypeScript
import type { AgentKnowledgeRetrievalItem, AgentTool } from './form-state'
|
|
|
|
const getKnowledgeRetrievalName = (item: AgentKnowledgeRetrievalItem) => item.name ?? item.nameKey ?? item.id
|
|
|
|
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
|
|
const createReferenceToken = (kind: string, id: string, label: string) => (
|
|
`[§${kind}:${id}${label ? `:${label}` : ''}§]`
|
|
)
|
|
|
|
const syncReferenceLabels = ({
|
|
prompt,
|
|
kind,
|
|
currentItems,
|
|
nextItems,
|
|
}: {
|
|
prompt: string
|
|
kind: string
|
|
currentItems: Array<{ id: string, name: string }>
|
|
nextItems: Array<{ id: string, name: string }>
|
|
}) => {
|
|
const currentItemById = new Map(currentItems.map(item => [item.id, item]))
|
|
|
|
return nextItems.reduce((nextPrompt, nextItem) => {
|
|
const currentItem = currentItemById.get(nextItem.id)
|
|
if (!currentItem)
|
|
return nextPrompt
|
|
|
|
if (currentItem.name === nextItem.name)
|
|
return nextPrompt
|
|
|
|
return nextPrompt.replace(
|
|
new RegExp(`\\[§${escapeRegExp(kind)}:${escapeRegExp(nextItem.id)}(?::[^§\\]]*)?§\\]`, 'g'),
|
|
createReferenceToken(kind, nextItem.id, nextItem.name),
|
|
)
|
|
}, prompt)
|
|
}
|
|
|
|
const toReferenceLabelItems = <Item extends { id: string }>(
|
|
items: Item[],
|
|
getName: (item: Item) => string,
|
|
) => items.map(item => ({
|
|
id: item.id,
|
|
name: getName(item),
|
|
}))
|
|
|
|
export const syncKnowledgeReferenceLabels = ({
|
|
prompt,
|
|
currentRetrievals,
|
|
nextRetrievals,
|
|
}: {
|
|
prompt: string
|
|
currentRetrievals: AgentKnowledgeRetrievalItem[]
|
|
nextRetrievals: AgentKnowledgeRetrievalItem[]
|
|
}) => syncReferenceLabels({
|
|
prompt,
|
|
kind: 'knowledge',
|
|
currentItems: toReferenceLabelItems(currentRetrievals, getKnowledgeRetrievalName),
|
|
nextItems: toReferenceLabelItems(nextRetrievals, getKnowledgeRetrievalName),
|
|
})
|
|
|
|
export const syncCliToolReferenceLabels = ({
|
|
prompt,
|
|
currentTools,
|
|
nextTools,
|
|
}: {
|
|
prompt: string
|
|
currentTools: AgentTool[]
|
|
nextTools: AgentTool[]
|
|
}) => syncReferenceLabels({
|
|
prompt,
|
|
kind: 'cli_tool',
|
|
currentItems: toReferenceLabelItems(currentTools.filter(tool => tool.kind === 'cli'), tool => tool.name),
|
|
nextItems: toReferenceLabelItems(nextTools.filter(tool => tool.kind === 'cli'), tool => tool.name),
|
|
})
|