|
| 1 | +import { |
| 2 | + ConversationContext, |
| 3 | + ConversationEdge, |
| 4 | + ConversationGraph, |
| 5 | + EdgeOption, |
| 6 | + TraversalResult |
| 7 | +} from '@conversation-trainer/types'; |
| 8 | + |
| 9 | +const tokenize = (value: string) => |
| 10 | + value |
| 11 | + .toLowerCase() |
| 12 | + .replace(/[^a-z0-9\s]/g, ' ') |
| 13 | + .split(/\s+/) |
| 14 | + .filter(Boolean); |
| 15 | + |
| 16 | +const cosineSimilarity = (a: string[], b: string[]) => { |
| 17 | + const aFreq = new Map<string, number>(); |
| 18 | + const bFreq = new Map<string, number>(); |
| 19 | + a.forEach((token) => aFreq.set(token, (aFreq.get(token) ?? 0) + 1)); |
| 20 | + b.forEach((token) => bFreq.set(token, (bFreq.get(token) ?? 0) + 1)); |
| 21 | + |
| 22 | + const keys = new Set([...aFreq.keys(), ...bFreq.keys()]); |
| 23 | + let dot = 0; |
| 24 | + let aMag = 0; |
| 25 | + let bMag = 0; |
| 26 | + |
| 27 | + keys.forEach((key) => { |
| 28 | + const aValue = aFreq.get(key) ?? 0; |
| 29 | + const bValue = bFreq.get(key) ?? 0; |
| 30 | + dot += aValue * bValue; |
| 31 | + aMag += aValue * aValue; |
| 32 | + bMag += bValue * bValue; |
| 33 | + }); |
| 34 | + |
| 35 | + if (!aMag || !bMag) return 0; |
| 36 | + return dot / (Math.sqrt(aMag) * Math.sqrt(bMag)); |
| 37 | +}; |
| 38 | + |
| 39 | +const levenshteinDistance = (a: string, b: string) => { |
| 40 | + const dp = Array.from({ length: a.length + 1 }, () => Array.from<number>({ length: b.length + 1 }).fill(0)); |
| 41 | + for (let i = 0; i <= a.length; i++) dp[i][0] = i; |
| 42 | + for (let j = 0; j <= b.length; j++) dp[0][j] = j; |
| 43 | + |
| 44 | + for (let i = 1; i <= a.length; i++) { |
| 45 | + for (let j = 1; j <= b.length; j++) { |
| 46 | + const cost = a[i - 1] === b[j - 1] ? 0 : 1; |
| 47 | + dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost); |
| 48 | + } |
| 49 | + } |
| 50 | + return dp[a.length][b.length]; |
| 51 | +}; |
| 52 | + |
| 53 | +export class GraphEngine { |
| 54 | + constructor(private readonly graph: ConversationGraph) {} |
| 55 | + |
| 56 | + getInitialContext(conversationId: string): ConversationContext { |
| 57 | + const defaultVariables = Object.fromEntries( |
| 58 | + (this.graph.variables ?? []).map((v) => [v.name, v.default ?? null]) |
| 59 | + ); |
| 60 | + |
| 61 | + return { |
| 62 | + conversationId, |
| 63 | + currentNodeId: this.graph.entryNode, |
| 64 | + variables: defaultVariables, |
| 65 | + history: [{ nodeId: this.graph.entryNode, timestamp: new Date().toISOString() }] |
| 66 | + }; |
| 67 | + } |
| 68 | + |
| 69 | + processInput(context: ConversationContext, input: string): TraversalResult { |
| 70 | + const edges = this.graph.edges.filter((edge) => edge.from === context.currentNodeId); |
| 71 | + const matched = this.matchEdge(edges, input); |
| 72 | + |
| 73 | + if (!matched) { |
| 74 | + const currentNode = this.graph.nodes[context.currentNodeId]; |
| 75 | + return { |
| 76 | + node: currentNode, |
| 77 | + context, |
| 78 | + message: "I didn't understand that. Try one of the available options.", |
| 79 | + availableOptions: this.getAvailableOptions(context.currentNodeId), |
| 80 | + isComplete: currentNode.type === 'end' |
| 81 | + }; |
| 82 | + } |
| 83 | + |
| 84 | + const nextContext = this.executeActions(context, matched); |
| 85 | + nextContext.currentNodeId = matched.to; |
| 86 | + nextContext.history.push({ nodeId: matched.to, timestamp: new Date().toISOString(), choice: input }); |
| 87 | + |
| 88 | + const node = this.graph.nodes[matched.to]; |
| 89 | + return { |
| 90 | + node, |
| 91 | + context: nextContext, |
| 92 | + matchedEdgeId: matched.id, |
| 93 | + message: matched.response, |
| 94 | + availableOptions: this.getAvailableOptions(matched.to), |
| 95 | + isComplete: node.type === 'end' |
| 96 | + }; |
| 97 | + } |
| 98 | + |
| 99 | + getAvailableOptions(nodeId: string): EdgeOption[] { |
| 100 | + return this.graph.edges |
| 101 | + .filter((edge) => edge.from === nodeId) |
| 102 | + .map((edge) => ({ id: edge.id, label: String(edge.trigger.value), to: edge.to })); |
| 103 | + } |
| 104 | + |
| 105 | + private executeActions(context: ConversationContext, edge: ConversationEdge): ConversationContext { |
| 106 | + const copy: ConversationContext = { |
| 107 | + ...context, |
| 108 | + variables: { ...context.variables }, |
| 109 | + history: [...context.history] |
| 110 | + }; |
| 111 | + |
| 112 | + (edge.actions ?? []).forEach((action) => { |
| 113 | + if (!action.target) return; |
| 114 | + if (action.type === 'setVariable') { |
| 115 | + copy.variables[action.target] = action.value ?? null; |
| 116 | + } |
| 117 | + if (action.type === 'increment') { |
| 118 | + copy.variables[action.target] = Number(copy.variables[action.target] ?? 0) + 1; |
| 119 | + } |
| 120 | + }); |
| 121 | + |
| 122 | + return copy; |
| 123 | + } |
| 124 | + |
| 125 | + private matchEdge(edges: ConversationEdge[], input: string): ConversationEdge | undefined { |
| 126 | + const normalized = input.trim().toLowerCase(); |
| 127 | + const exact = edges.find((edge) => { |
| 128 | + if (edge.trigger.type !== 'exact' && edge.trigger.type !== 'button') return false; |
| 129 | + const values = Array.isArray(edge.trigger.value) ? edge.trigger.value : [edge.trigger.value]; |
| 130 | + return values.some((v) => String(v).toLowerCase() === normalized); |
| 131 | + }); |
| 132 | + if (exact) return exact; |
| 133 | + |
| 134 | + const regex = edges.find((edge) => { |
| 135 | + if (edge.trigger.type !== 'regex') return false; |
| 136 | + return new RegExp(String(edge.trigger.value), 'i').test(input); |
| 137 | + }); |
| 138 | + if (regex) return regex; |
| 139 | + |
| 140 | + const intents = edges |
| 141 | + .filter((edge) => edge.trigger.type === 'intent') |
| 142 | + .map((edge) => { |
| 143 | + const values = Array.isArray(edge.trigger.value) ? edge.trigger.value : [edge.trigger.value]; |
| 144 | + const scores = values.map((value) => this.matchIntent(input, String(value))); |
| 145 | + return { edge, score: Math.max(...scores) }; |
| 146 | + }) |
| 147 | + .sort((a, b) => b.score - a.score); |
| 148 | + |
| 149 | + if (intents[0] && intents[0].score >= 0.5) return intents[0].edge; |
| 150 | + |
| 151 | + const fuzzy = edges.find((edge) => { |
| 152 | + const values = Array.isArray(edge.trigger.value) ? edge.trigger.value : [edge.trigger.value]; |
| 153 | + return values.some((value) => { |
| 154 | + const candidate = String(value).toLowerCase(); |
| 155 | + const distance = levenshteinDistance(candidate, normalized); |
| 156 | + const ratio = 1 - distance / Math.max(candidate.length, normalized.length, 1); |
| 157 | + return ratio >= 0.8; |
| 158 | + }); |
| 159 | + }); |
| 160 | + |
| 161 | + return fuzzy; |
| 162 | + } |
| 163 | + |
| 164 | + private matchIntent(input: string, pattern: string): number { |
| 165 | + return cosineSimilarity(tokenize(input), tokenize(pattern)); |
| 166 | + } |
| 167 | +} |
0 commit comments