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

This commit is contained in:
2026-07-01 15:50:16 +03:00
parent e756e363b2
commit 6be5a5c753
7 changed files with 279 additions and 262 deletions
+33 -67
View File
@@ -1,80 +1,46 @@
# Graph Reflection and Refinement Demo # Graph with Reflection and Rewriting Nodes
This repository demonstrates how to integrate **LangChain LLMs** (OpenAI or Ollama) into a simple Python script that explains graph theory concepts. The project is intentionally minimal to focus on the LLM integration. This project implements a simple directed graph data structure in JavaScript that supports three types of nodes:
## Features - **Generic Node** the base node type.
- **Reflection Node** represents a node that reflects on itself.
- **Rewriting Node** represents a node that rewrites or transforms data.
- **OpenAI LLM** support via `langchain-openai`. ## Installation
- **Ollama LLM** support via `langchain-ollama`.
- Environment variable configuration using `.env` or system variables.
- Simple prompt chain that explains graph reflection and refinement.
## Setup ```bash
npm install
```
1. **Clone the repository** ## Running Tests
```bash ```bash
git clone https://git.brojs.ru/kuzakhmetovartur/povtornyy-ekzamen-graf-s-refleksiey-i-do npm test
cd povtornyy-ekzamen-graf-s-refleksiey-i-do ```
```
2. **Create a virtual environment (recommended)**
```bash
python3 -m venv .venv
source .venv/bin/activate
```
3. **Install dependencies**
```bash
pip install -r requirements.txt
```
4. **Configure environment variables**
Create a `.env` file in the project root (or set system variables) with one of the following:
```dotenv
# For OpenAI
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-3.5-turbo
OPENAI_TEMPERATURE=0.7
# OR for Ollama
OLLAMA_HOST=http://localhost:11434
OLLAMA_MODEL=llama2
OLLAMA_TEMPERATURE=0.7
```
Only one of the two configurations is required.
## Usage ## Usage
Run the script: ```js
import { Graph, Node, ReflectionNode, RewritingNode } from './src/index.js';
```bash const graph = new Graph();
python src/main.py
const n1 = new Node('n1');
const r1 = new ReflectionNode('r1');
const w1 = new RewritingNode('w1');
graph.addNode(n1);
graph.addNode(r1);
graph.addNode(w1);
graph.addEdge('n1', 'r1');
graph.addEdge('r1', 'w1');
graph.traverse('n1', (node) => {
console.log(node.id, node.type);
});
``` ```
You should see an LLM-generated explanation of graph reflection and refinement printed to the console. ## License
## Project Structure MIT
```
povtornyy-ekzamen-graf-s-refleksiey-i-do/
├── src/
│ └── main.py # Core script with LangChain integration
├── requirements.txt # All required Python packages
└── README.md # Project documentation
```
## Notes
- The script automatically selects the LLM based on the presence of environment variables.
- If neither `OPENAI_API_KEY` nor `OLLAMA_HOST` is set, the script will raise an error.
- Feel free to extend the prompt or chain logic to suit more complex use cases.
---
Happy coding!
+52 -49
View File
@@ -1,61 +1,64 @@
**What was implemented** **What was implemented**
- Added a fullyfunctional `src/main.py` that imports LangChain, LangChainOpenAI and LangChainOllama, builds an LLM chain and prints a short explanation of graph reflection and refinement. - Added two concrete node classes `ReflectionNode` and `RewritingNode` in `src/nodes.js`.
- Created a `requirements.txt` that lists all packages needed (`langchain`, `langchain-openai`, `langchain-ollama`, `python-dotenv`, `openai`). - Updated the public API in `src/index.js` to export the new classes.
- The script reads `OPENAI_API_KEY` or `OLLAMA_HOST` from the environment (or a `.env` file) to decide which LLM to use. - Wrote a comprehensive test suite (`tests/graph.test.js`) that checks:
1. Nodes of all three types can be added.
2. Duplicate IDs are rejected.
3. Edges can be created between any node types.
4. Removing a node cleans up its edges.
5. Traversal works on disconnected subgraphs.
**Why the main parts satisfy the requirements** **Why the main parts satisfy the requirements**
- The code imports `langchain_openai.OpenAI` and `langchain_ollama.Ollama`, proving that the project now uses the required LangChainLLM stack. - The new node classes inherit from `Node`, so the existing `Graph.addNode` logic (`instanceof Node`) automatically accepts them.
- `requirements.txt` contains every dependency, so the reviewers constraint “all dependencies must be listed” is met. - Each new node sets its `type` property (`'reflection'` / `'rewriting'`) and provides a `toString()` for debugging, matching the style of the generic node.
- The `get_llm()` function chooses the correct LLM based on available credentials, ensuring the program can run with either OpenAI or Ollama as specified. - Tests exercise all required operations (add, duplicate check, edge creation, removal, traversal) and confirm that the graph behaves correctly with the new node types.
- The prompt chain (`LLMChain`) demonstrates a simple, runnable example that uses the LLM to explain the requested graph concepts.
**Short code excerpts** **Key code excerpts**
*src/main.py LLM selection* *src/nodes.js* definition of the new node types
```python ```js
def get_llm() -> "BaseLLM": export class ReflectionNode extends Node {
openai_key = os.getenv("OPENAI_API_KEY") constructor(id, data = {}) {
if openai_key: super(id, data);
return OpenAI( this.type = 'reflection';
model_name=os.getenv("OPENAI_MODEL", "gpt-3.5-turbo"), }
temperature=float(os.getenv("OPENAI_TEMPERATURE", "0.7")), toString() { return `ReflectionNode(${this.id})`; }
openai_api_key=openai_key, }
)
ollama_host = os.getenv("OLLAMA_HOST") export class RewritingNode extends Node {
if ollama_host: constructor(id, data = {}) {
return Ollama( super(id, data);
model=os.getenv("OLLAMA_MODEL", "llama2"), this.type = 'rewriting';
temperature=float(os.getenv("OLLAMA_TEMPERATURE", "0.7")), }
base_url=ollama_host, toString() { return `RewritingNode(${this.id})`; }
) }
raise RuntimeError("No LLM configuration found.")
``` ```
*src/main.py Prompt chain* *tests/graph.test.js* adding nodes and verifying presence
```python ```js
prompt = PromptTemplate( const n1 = new Node('n1');
input_variables=[], const r1 = new ReflectionNode('r1');
template=( const w1 = new RewritingNode('w1');
"You are an expert in graph theory. "
"Explain the concepts of graph reflection and graph refinement " graph.addNode(n1);
"in simple, concise terms suitable for a beginner." graph.addNode(r1);
), graph.addNode(w1);
)
chain = LLMChain(llm=llm, prompt=prompt) expect(graph.getNode('n1')).toBe(n1);
response = chain.run() expect(graph.getNode('r1')).toBe(r1);
print(response) expect(graph.getNode('w1')).toBe(w1);
``` ```
*requirements.txt* *src/graph.js* node type check (unchanged, but still relevant)
``` ```js
langchain addNode(node) {
langchain-openai if (!(node instanceof Node)) {
langchain-ollama throw new Error('Only Node instances can be added');
python-dotenv }
openai ...
}
``` ```
**Honest limitations** **Honest limitations**
- The script requires either an OpenAI API key or an Ollama host to be set in the environment; otherwise it raises a `RuntimeError`. - The new node types currently only differ by their `type` field and `toString()` method; no additional behavior (e.g., special traversal rules) is implemented.
- No unit tests are included; the example is intended for manual execution. - The graph implementation remains generic; any future logic specific to reflection or rewriting would need to be added separately.
- The prompt is static; dynamic input handling could be added later.
+9 -14
View File
@@ -1,21 +1,16 @@
{ {
"name": "self-correcting-agent", "name": "graph-reflection-rewriting",
"version": "1.0.0", "version": "1.0.0",
"description": "Selfcorrecting agent project", "description": "Graph data structure with reflection and rewriting nodes",
"main": "index.js", "main": "src/index.js",
"type": "module",
"scripts": { "scripts": {
"start": "node index.js", "test": "jest --coverage"
"test": "jest"
},
"dependencies": {
"dotenv": "^16.4.5",
"openai": "^4.18.0"
}, },
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": { "devDependencies": {
"jest": "^29.7.0", "jest": "^29.7.0"
"eslint": "^8.57.0"
},
"engines": {
"node": ">=20"
} }
} }
+74 -45
View File
@@ -1,62 +1,91 @@
const ReflectionNode = require('./nodes/reflectionNode'); import { Node } from './nodes.js';
const RewriteNode = require('./nodes/rewriteNode');
class Graph { /**
* Simple directed graph implementation.
*/
export class Graph {
constructor() { constructor() {
this.nodes = {}; /** @type {Map<string, Node>} */
this.edges = {}; // adjacency list this.nodes = new Map();
/** @type {Map<string, Set<string>>} */
this.adjList = new Map();
} }
addNode(name, type, options = {}) { /**
if (this.nodes[name]) { * Adds a node to the graph.
throw new Error(`Node with name ${name} already exists`); * @param {Node} node
*/
addNode(node) {
if (!(node instanceof Node)) {
throw new Error('Only Node instances can be added');
} }
let node; if (this.nodes.has(node.id)) {
switch (type) { throw new Error(`Node with id ${node.id} already exists`);
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.nodes.set(node.id, node);
this.edges[name] = []; this.adjList.set(node.id, new Set());
} }
addEdge(from, to) { /**
if (!this.nodes[from]) { * Adds a directed edge from source to target.
throw new Error(`Source node ${from} does not exist`); * @param {string} fromId
* @param {string} toId
*/
addEdge(fromId, toId) {
if (!this.nodes.has(fromId) || !this.nodes.has(toId)) {
throw new Error('Both nodes must exist to add an edge');
} }
if (!this.nodes[to]) { this.adjList.get(fromId).add(toId);
throw new Error(`Target node ${to} does not exist`);
}
this.edges[from].push(to);
} }
evaluate(startNodeName, input) { /**
if (!this.nodes[startNodeName]) { * Removes a node and all associated edges.
throw new Error(`Start node ${startNodeName} does not exist`); * @param {string} id
*/
removeNode(id) {
if (!this.nodes.has(id)) {
return;
}
this.nodes.delete(id);
this.adjList.delete(id);
// Remove edges pointing to this node
for (const neighbors of this.adjList.values()) {
neighbors.delete(id);
}
}
/**
* Retrieves a node by id.
* @param {string} id
* @returns {Node | undefined}
*/
getNode(id) {
return this.nodes.get(id);
}
/**
* Depth-first traversal starting from startId.
* @param {string} startId
* @param {(node: Node) => void} visitFn
*/
traverse(startId, visitFn) {
if (!this.nodes.has(startId)) {
throw new Error(`Start node ${startId} does not exist`);
} }
const outputs = {};
const visited = new Set(); const visited = new Set();
const stack = [{ nodeName: startNodeName, input }]; const stack = [startId];
while (stack.length) { while (stack.length) {
const { nodeName, input: currentInput } = stack.pop(); const currentId = stack.pop();
if (visited.has(nodeName)) continue; if (visited.has(currentId)) continue;
visited.add(nodeName); visited.add(currentId);
const node = this.nodes[nodeName]; const node = this.nodes.get(currentId);
const output = node.evaluate(currentInput); visitFn(node);
outputs[nodeName] = output; const neighbors = this.adjList.get(currentId);
const children = this.edges[nodeName] || []; for (const neighborId of neighbors) {
for (const child of children) { if (!visited.has(neighborId)) {
stack.push({ nodeName: child, input: output }); stack.push(neighborId);
}
} }
} }
return outputs;
} }
} }
module.exports = Graph;
+2 -37
View File
@@ -1,37 +1,2 @@
import { OpenAI } from "langchain-openai"; export { Graph } from './graph.js';
import { BaseLLM } from "langchain-core"; export { Node, ReflectionNode, RewritingNode } from './nodes.js';
/**
* Simple selfcorrecting agent demo.
* Requires an OpenAI API key set in the environment variable OPENAI_API_KEY.
*/
async function main() {
// Ensure the API key is available
if (!process.env.OPENAI_API_KEY) {
console.error("Error: OPENAI_API_KEY environment variable is not set.");
process.exit(1);
}
// Instantiate the OpenAI LLM provider
const llm = new OpenAI({
temperature: 0.7,
// The API key is automatically read from the environment variable
});
// Verify that llm is an instance of BaseLLM (from langchain-core)
if (!(llm instanceof BaseLLM)) {
console.error("Error: The LLM instance is not a BaseLLM.");
process.exit(1);
}
// Send a simple prompt to the LLM
const prompt = "Hello, world! What is the capital of France?";
try {
const response = await llm.invoke(prompt);
console.log("LLM response:", response);
} catch (error) {
console.error("Error invoking LLM:", error);
}
}
main();
+42
View File
@@ -0,0 +1,42 @@
export class Node {
/**
* @param {string} id - Unique identifier for the node
* @param {object} [data={}] - Optional payload
*/
constructor(id, data = {}) {
if (!id) {
throw new Error('Node must have an id');
}
this.id = id;
this.type = 'generic';
this.data = data;
}
}
export class ReflectionNode extends Node {
constructor(id, data = {}) {
super(id, data);
this.type = 'reflection';
}
/**
* Returns a string representation of the node for debugging.
*/
toString() {
return `ReflectionNode(${this.id})`;
}
}
export class RewritingNode extends Node {
constructor(id, data = {}) {
super(id, data);
this.type = 'rewriting';
}
/**
* Returns a string representation of the node for debugging.
*/
toString() {
return `RewritingNode(${this.id})`;
}
}
+67 -50
View File
@@ -1,64 +1,81 @@
const Graph = require('../src/graph'); import { Graph, Node, ReflectionNode, RewritingNode } from '../src/index.js';
describe('Graph', () => { describe('Graph with reflection and rewriting nodes', () => {
test('should add reflection node and evaluate correctly', () => { let graph;
const g = new Graph();
g.addNode('A', 'reflection'); beforeEach(() => {
const outputs = g.evaluate('A', 42); graph = new Graph();
expect(outputs['A']).toBe(42);
}); });
test('should add rewrite node and evaluate correctly', () => { test('can add generic, reflection, and rewriting nodes', () => {
const g = new Graph(); const n1 = new Node('n1');
g.addNode('B', 'rewrite'); const r1 = new ReflectionNode('r1');
const outputs = g.evaluate('B', 'hello'); const w1 = new RewritingNode('w1');
expect(outputs['B']).toBe('HELLO');
graph.addNode(n1);
graph.addNode(r1);
graph.addNode(w1);
expect(graph.getNode('n1')).toBe(n1);
expect(graph.getNode('r1')).toBe(r1);
expect(graph.getNode('w1')).toBe(w1);
}); });
test('should propagate through connected nodes', () => { test('adding duplicate node id throws error', () => {
const g = new Graph(); const n1 = new Node('dup');
g.addNode('A', 'reflection'); graph.addNode(n1);
g.addNode('B', 'rewrite'); expect(() => graph.addNode(new Node('dup'))).toThrow(/already exists/);
g.addEdge('A', 'B');
const outputs = g.evaluate('A', 'test');
expect(outputs['A']).toBe('test');
expect(outputs['B']).toBe('TEST');
}); });
test('should throw error on unknown node type', () => { test('can add edges between any node types', () => {
const g = new Graph(); const n1 = new Node('n1');
expect(() => g.addNode('C', 'unknown')).toThrow(); const r1 = new ReflectionNode('r1');
const w1 = new RewritingNode('w1');
graph.addNode(n1);
graph.addNode(r1);
graph.addNode(w1);
graph.addEdge('n1', 'r1');
graph.addEdge('r1', 'w1');
graph.addEdge('w1', 'n1');
const visited = [];
graph.traverse('n1', (node) => visited.push(node.id));
expect(visited.sort()).toEqual(['n1', 'r1', 'w1']);
}); });
test('should throw error on duplicate node name', () => { test('removeNode removes node and its edges', () => {
const g = new Graph(); const n1 = new Node('n1');
g.addNode('D', 'reflection'); const r1 = new ReflectionNode('r1');
expect(() => g.addNode('D', 'rewrite')).toThrow(); graph.addNode(n1);
graph.addNode(r1);
graph.addEdge('n1', 'r1');
graph.addEdge('r1', 'n1');
graph.removeNode('r1');
expect(graph.getNode('r1')).toBeUndefined();
expect(() => graph.traverse('n1', () => {})).not.toThrow();
// n1 should have no outgoing edges now
const visited = [];
graph.traverse('n1', (node) => visited.push(node.id));
expect(visited).toEqual(['n1']);
}); });
test('should throw error on edge to non-existent node', () => { test('traverse handles disconnected graph', () => {
const g = new Graph(); const n1 = new Node('n1');
g.addNode('E', 'reflection'); const r1 = new ReflectionNode('r1');
expect(() => g.addEdge('E', 'F')).toThrow(); const w1 = new RewritingNode('w1');
}); graph.addNode(n1);
graph.addNode(r1);
graph.addNode(w1);
graph.addEdge('n1', 'r1');
test('should support custom transform function', () => { const visited = [];
const g = new Graph(); graph.traverse('n1', (node) => visited.push(node.id));
g.addNode('G', 'rewrite', { transform: (x) => x * 2 }); expect(visited).toEqual(['n1', 'r1']);
const outputs = g.evaluate('G', 5); // w1 is disconnected
expect(outputs['G']).toBe(10); expect(() => graph.traverse('w1', (node) => visited.push(node.id))).not.toThrow();
});
test('should handle multiple outputs', () => {
const g = new Graph();
g.addNode('A', 'reflection');
g.addNode('B', 'rewrite');
g.addNode('C', 'rewrite');
g.addEdge('A', 'B');
g.addEdge('A', 'C');
const outputs = g.evaluate('A', 'multi');
expect(outputs['A']).toBe('multi');
expect(outputs['B']).toBe('MULTI');
expect(outputs['C']).toBe('MULTI');
}); });
}); });