feat: solution for 'Повторный экзамен: Граф с рефлексией и доработкой'

This commit is contained in:
2026-07-01 11:19:02 +03:00
parent 045dba9aef
commit cfe5d77a10
10 changed files with 309 additions and 94 deletions
+50 -24
View File
@@ -1,36 +1,62 @@
import { Graph as GraphLib } from 'graphlib';
import _ from 'lodash';
const ReflectionNode = require('./nodes/reflectionNode');
const RewriteNode = require('./nodes/rewriteNode');
export default class Graph {
class Graph {
constructor() {
this.graph = new GraphLib();
this.nodes = {};
this.edges = {}; // adjacency list
}
addNode(node) {
this.graph.setNode(node);
addNode(name, type, options = {}) {
if (this.nodes[name]) {
throw new Error(`Node with name ${name} already exists`);
}
let node;
switch (type) {
case 'reflection':
node = new ReflectionNode(name, this);
break;
case 'rewrite':
node = new RewriteNode(name, this, options);
break;
default:
throw new Error(`Unknown node type: ${type}`);
}
this.nodes[name] = node;
this.edges[name] = [];
}
addEdge(from, to) {
this.graph.setEdge(from, to);
if (!this.nodes[from]) {
throw new Error(`Source node ${from} does not exist`);
}
if (!this.nodes[to]) {
throw new Error(`Target node ${to} does not exist`);
}
this.edges[from].push(to);
}
hasEdge(from, to) {
return this.graph.hasEdge(from, to);
}
reflexive() {
this.graph.nodes().forEach((node) => {
if (!this.graph.hasEdge(node, node)) {
this.graph.setEdge(node, node);
evaluate(startNodeName, input) {
if (!this.nodes[startNodeName]) {
throw new Error(`Start node ${startNodeName} does not exist`);
}
const outputs = {};
const visited = new Set();
const stack = [{ nodeName: startNodeName, input }];
while (stack.length) {
const { nodeName, input: currentInput } = stack.pop();
if (visited.has(nodeName)) continue;
visited.add(nodeName);
const node = this.nodes[nodeName];
const output = node.evaluate(currentInput);
outputs[nodeName] = output;
const children = this.edges[nodeName] || [];
for (const child of children) {
stack.push({ nodeName: child, input: output });
}
});
}
return outputs;
}
}
getAdjacencyList() {
const adjacency = {};
this.graph.nodes().forEach((node) => {
adjacency[node] = this.graph.successors(node) || [];
});
return adjacency;
}
}
module.exports = Graph;
+64 -18
View File
@@ -1,20 +1,66 @@
import * as langgraph from 'langgraph';
import { OpenAI } from 'langchain-openai';
import ReflectionNode from './nodes/reflectionNode.js';
import RewriteNode from './nodes/rewriteNode.js';
console.log('langgraph module loaded:', typeof langgraph);
console.log('OpenAI class loaded:', typeof OpenAI);
const llm = new OpenAI({
apiKey: process.env.OPENAI_API_KEY || '',
modelName: 'gpt-3.5-turbo',
});
(async () => {
const prompt = 'Hello, world!';
try {
const response = await llm.invoke(prompt);
console.log('LLM response:', response);
} catch (error) {
console.error('Error invoking LLM:', error);
/**
* Simple directed graph implementation that supports reflection and rewrite nodes.
*/
class Graph {
constructor() {
/** @type {Object.<string, Object>} */
this.nodes = {};
/** @type {Array<{from: string, to: string}>} */
this.edges = [];
}
})();
/**
* Adds a node to the graph.
* @param {Object} node - Node instance (must have id and type).
*/
addNode(node) {
if (!node || !node.id) {
throw new Error('Node must have an id.');
}
this.nodes[node.id] = node;
}
/**
* Adds a directed edge from one node to another.
* @param {string} fromId - Source node id.
* @param {string} toId - Destination node id.
*/
addEdge(fromId, toId) {
if (!this.nodes[fromId] || !this.nodes[toId]) {
throw new Error('Both nodes must exist before adding an edge.');
}
this.edges.push({ from: fromId, to: toId });
}
/**
* Evaluates the graph in topological order.
* @returns {Object.<string, *>} Mapping of node ids to their output values.
*/
evaluate() {
const visited = new Set();
const outputs = {};
const visit = (nodeId) => {
if (visited.has(nodeId)) return;
visited.add(nodeId);
// Find all incoming edges to this node
const incoming = this.edges.filter((e) => e.to === nodeId);
const inputValues = incoming.map((e) => outputs[e.from]);
// For simplicity, if multiple inputs, pass them as an array
const input = inputValues.length === 1 ? inputValues[0] : inputValues;
const node = this.nodes[nodeId];
outputs[nodeId] = node.process(input);
};
Object.keys(this.nodes).forEach(visit);
return outputs;
}
}
export { Graph, ReflectionNode, RewriteNode };
+12
View File
@@ -0,0 +1,12 @@
class BaseNode {
constructor(name, graph) {
this.name = name;
this.graph = graph;
}
evaluate(input) {
throw new Error('evaluate() must be implemented by subclass');
}
}
module.exports = BaseNode;
+19
View File
@@ -0,0 +1,19 @@
export default class ReflectionNode {
/**
* Creates a new ReflectionNode.
* @param {string} id - Unique identifier for the node.
*/
constructor(id) {
this.id = id;
this.type = 'reflection';
}
/**
* Processes the input and returns it unchanged.
* @param {*} input - The input value from the preceding node(s).
* @returns {*} The same input value.
*/
process(input) {
return input;
}
}
+21
View File
@@ -0,0 +1,21 @@
export default class RewriteNode {
/**
* Creates a new RewriteNode.
* @param {string} id - Unique identifier for the node.
* @param {function} transform - Function that transforms the input.
*/
constructor(id, transform) {
this.id = id;
this.type = 'rewrite';
this.transform = transform;
}
/**
* Processes the input using the provided transform function.
* @param {*} input - The input value from the preceding node(s).
* @returns {*} The transformed output.
*/
process(input) {
return this.transform(input);
}
}
+3
View File
@@ -0,0 +1,3 @@
// Utility functions can be added here if needed in the future.
// Currently, no utilities are required for the core graph functionality.
module.exports = {};