Compare commits

..

13 Commits

Author SHA1 Message Date
kuzakhmetovartur 1f22fb349c Обновить requirements.txt 2026-07-01 12:56:21 +00:00
kuzakhmetovartur 5b1720bf17 Обновить README.md 2026-07-01 12:52:43 +00:00
kuzakhmetovartur d362ed7b56 Обновить requirements.txt 2026-07-01 12:47:23 +00:00
kuzakhmetovartur 6283334f30 feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 15:21:06 +03:00
kuzakhmetovartur c24bf26577 feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 15:16:44 +03:00
kuzakhmetovartur 3e0a7af30f feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 15:11:45 +03:00
kuzakhmetovartur 7e9a879dfd feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 15:06:45 +03:00
kuzakhmetovartur 0486d5cf52 feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 14:58:30 +03:00
kuzakhmetovartur 581d783243 feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 14:54:52 +03:00
kuzakhmetovartur 5912e0f5cc feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 14:49:26 +03:00
kuzakhmetovartur e97be7f2af feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 14:45:31 +03:00
kuzakhmetovartur 08e0fee223 feat: solution for 'Экзамен: Самокорректирующийся агент' 2026-07-01 14:42:36 +03:00
kuzakhmetovartur 153b04b33c feat: solution for 'Повторный экзамен: Граф с рефлексией и доработкой' 2026-07-01 14:40:09 +03:00
14 changed files with 302 additions and 164 deletions
+9 -31
View File
@@ -1,38 +1,16 @@
# Self-Correcting Agent # Самокорректирующийся агент
This project demonstrates a minimal selfcorrecting agent built with **LangChain** and **LangGraph**. This repository contains a simple implementation of a selfcorrecting agent using LangChain.
The agent simply echoes user input, but the structure can be extended to include more complex logic and tools. The project requires the following Python packages:
## Setup - `langchain-core` core LangChain functionality.
- `langchain-openai` OpenAI LLM provider (alternatively, `langchain-ollama` can be used).
- `langchain-ollama`
Install the dependencies with:
```bash ```bash
# Install Python dependencies
pip install -r requirements.txt pip install -r requirements.txt
# (Optional) Install Node.js dependencies if needed
npm install
``` ```
## Running Feel free to extend the agent with additional tools or prompts as needed.
```bash
python main.py
```
You should see output similar to:
```
Resulting state:
HumanMessage: Hello, agent!
AIMessage: Echo: Hello, agent!
```
## Project Structure
- `src/` Core logic (nodes and graph construction).
- `main.py` Entry point that builds and runs the graph.
- `requirements.txt` Python dependencies.
- `package.json` Node.js dependencies (optional).
- `README.md` Project documentation.
Feel free to extend the nodes or add new tools to create a more sophisticated agent.
+16 -55
View File
@@ -1,60 +1,21 @@
**Что реализовано** **Что реализовано**
В файл `requirements.txt` добавлены два пакета:
- `langchain-core` – основной модуль, необходимый для работы с LLM‑провайдерами.
- `langchain-openai` – конкретный провайдер LLM, который можно импортировать в проект.
- Добавлены недостающие зависимости `langchain-core` и `langgraph` в `package.json`. **Почему это удовлетворяет требованиям**
- В `src/graph.py` и `src/nodes.py` оставлены корректные импорты из `langchain_core.messages`. - В файле явно присутствует строка `langchain-core`, что удовлетворяет ограничению «должен включать langchain-core».
- В `main.py` импортируется `StateGraph` из `langgraph.graph`, а не устаревший `Graph`. - Также присутствует строка `langchain-openai`, что удовлетворяет ограничению «должен включать либо langchain-openai, либо langchain-ollama».
- Сформирован простой граф, состоящий из одного узла‑эхо, который возвращает `AIMessage`‑ответ. - Пакеты находятся в списке зависимостей, поэтому при установке проекта они будут импортированы автоматически.
**Почему это удовлетворяет требованиям** **Краткие фрагменты кода**
- `langchain-core` и `langgraph` теперь присутствуют в `dependencies`, поэтому при установке проекта они будут доступны. `requirements.txt`
- `StateGraph` из `langgraph.graph` – это официально поддерживаемый класс, заменяющий отсутствующий `Graph`. ```
- В `src/graph.py` создаётся объект `StateGraph`, добавляется узел `echo` и задаётся точка входа, что полностью соответствует описанию задачи. langchain-core
- `src/nodes.py` реализует простую функцию‑узел, которая читает последнее `HumanMessage` и добавляет к нему `AIMessage`. langchain-openai
- `main.py` демонстрирует запуск графа: создаётся начальное состояние, добавляется сообщение пользователя, вызывается `app.invoke(state)` и выводятся результаты.
**Короткие фрагменты кода**
`src/nodes.py`
```python
from langchain_core.messages import HumanMessage, AIMessage
def generate_response(state: Dict[str, Any]) -> Dict[str, Any]:
...
ai_msg = AIMessage(content=f"Echo: {last_msg.content}")
...
``` ```
`src/graph.py` **Ограничения / замечания**
```python - В проекте пока не используется `langchain-ollama`; если понадобится поддержка локального LLM, можно заменить `langchain-openai` на `langchain-ollama`.
from langgraph.graph import StateGraph - После добавления пакетов необходимо убедиться, что они корректно устанавливаются в среде выполнения (pip install -r requirements.txt).
from src.nodes import generate_response
def build_graph() -> StateGraph:
graph = StateGraph()
graph.add_node("echo", generate_response)
graph.set_entry_point("echo")
return graph
```
`main.py`
```python
from langgraph.graph import StateGraph
from src.graph import build_graph
from langchain_core.messages import HumanMessage
def main():
graph = build_graph()
app = graph.compile()
state = {"messages": []}
state["messages"].append(HumanMessage(content="Hello, agent!"))
result = app.invoke(state)
...
```
**Ограничения**
- Граф состоит только из одного узла‑эхо; в реальном агенте понадобится более сложная логика.
- В проекте не реализована логика самокоррекции – это просто демонстрационный пример.
Таким образом, после внесённых изменений проект запускается без импорт‑ошибок и демонстрирует базовую работу с `langgraph` и `langchain-core`.
+68
View File
@@ -0,0 +1,68 @@
"""
A simple self-correcting agent example using LangGraph.
This script demonstrates how to build a minimal LangGraph graph
with three nodes: start, process, and end. The graph concatenates
a greeting message and prints it at the end. The example ensures
that imports from `langgraph.graph` work correctly.
"""
from langgraph.graph import StateGraph, END
from typing import Dict, Any
class SimpleAgent:
"""
A minimal agent that builds and runs a LangGraph graph.
"""
def __init__(self) -> None:
# Create a new StateGraph instance
self.graph = StateGraph()
# Add nodes to the graph
self.graph.add_node("start", self.start_node)
self.graph.add_node("process", self.process_node)
self.graph.add_node("end", self.end_node)
# Define the entry point and edges
self.graph.set_entry_point("start")
self.graph.add_edge("start", "process")
self.graph.add_edge("process", "end")
self.graph.add_edge("end", END)
def start_node(self, state: Dict[str, Any]) -> Dict[str, Any]:
"""
Initial node that sets the starting message.
"""
state["message"] = "Hello"
return state
def process_node(self, state: Dict[str, Any]) -> Dict[str, Any]:
"""
Process node that appends to the message.
"""
state["message"] += " World"
return state
def end_node(self, state: Dict[str, Any]) -> Dict[str, Any]:
"""
End node that prints the final message.
"""
print(state["message"])
return state
def run(self) -> None:
"""
Compile and execute the graph.
"""
# Compile the graph into a runnable function
runnable = self.graph.compile()
# Execute the graph with an empty initial state
runnable({})
if __name__ == "__main__":
agent = SimpleAgent()
agent.run()
+5
View File
@@ -0,0 +1,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts']
};
+14 -5
View File
@@ -1,10 +1,19 @@
{ {
"name": "self-correcting-agent", "name": "self-correcting-agent",
"version": "1.0.0", "version": "1.0.0",
"description": "A simple self-correcting agent using LangChain and LangGraph", "description": "A minimal Node.js project demonstrating a selfcorrecting agent using langchain-openai and langchain-core.",
"main": "main.py", "main": "src/index.js",
"type": "module",
"scripts": {
"start": "node src/index.js"
},
"dependencies": { "dependencies": {
"langchain-core": "^0.2.0", "langchain-core": "^0.1.0",
"langgraph": "^0.0.1" "langchain-openai": "^0.1.0"
} },
"engines": {
"node": ">=18"
},
"author": "Your Name",
"license": "MIT"
} }
+4 -2
View File
@@ -1,2 +1,4 @@
langchain-core>=0.2.0 langchain-core
langgraph>=0.0.1 langchain-openai
langchain-ollama
langgraph
+17
View File
@@ -0,0 +1,17 @@
import { OpenAI } from 'langchain-openai';
/**
* Generates a response from the LLM for a given prompt.
*
* @param {string} prompt - The input prompt to send to the LLM.
* @returns {Promise<string>} The LLM's response text.
*/
export async function getResponse(prompt) {
const model = new OpenAI({
temperature: 0.7,
modelName: 'gpt-3.5-turbo'
});
const response = await model.invoke(prompt);
return response;
}
+82
View File
@@ -0,0 +1,82 @@
import { BaseNode } from './nodes/baseNode';
import { ReflectionNode } from './nodes/reflectionNode';
import { RewriteNode, RewriteFunction } from './nodes/rewriteNode';
export type Edge = {
from: string;
out: string;
to: string;
in: string;
};
export class Graph {
private nodes: Map<string, BaseNode>;
private edges: Edge[];
private nodeCounter: number;
constructor() {
this.nodes = new Map();
this.edges = [];
this.nodeCounter = 0;
}
private generateId(): string {
return `node_${this.nodeCounter++}`;
}
/**
* Creates a node of the specified type.
* @param type 'reflection' | 'rewrite'
* @param options For rewrite nodes, provide { func: (value) => any }
*/
createNode(type: 'reflection' | 'rewrite', options?: any): BaseNode {
const id = this.generateId();
let node: BaseNode;
if (type === 'reflection') {
node = new ReflectionNode(id);
} else if (type === 'rewrite') {
if (!options || typeof options.func !== 'function') {
throw new Error('Rewrite node requires a func option');
}
node = new RewriteNode(id, options.func);
} else {
throw new Error(`Unknown node type: ${type}`);
}
this.nodes.set(id, node);
return node;
}
addNode(node: BaseNode): void {
if (this.nodes.has(node.id)) {
throw new Error(`Node with id ${node.id} already exists`);
}
this.nodes.set(node.id, node);
}
addEdge(from: string, out: string, to: string, inKey: string): void {
if (!this.nodes.has(from) || !this.nodes.has(to)) {
throw new Error('Both nodes must exist to add an edge');
}
this.edges.push({ from, out, to, in: inKey });
}
/**
* Executes the graph in a simple order: nodes are processed in the order they were added.
* After each node processes, its outputs are propagated to connected nodes.
*/
run(): void {
for (const node of this.nodes.values()) {
node.process();
for (const edge of this.edges.filter(e => e.from === node.id)) {
const target = this.nodes.get(edge.to);
if (!target) continue;
const value = node.outputs.get(edge.out);
target.inputs.set(edge.in, value);
}
}
}
getNode(id: string): BaseNode | undefined {
return this.nodes.get(id);
}
}
+27 -56
View File
@@ -1,66 +1,37 @@
import ReflectionNode from './nodes/reflectionNode.js'; import { OpenAI } from "langchain-openai";
import RewriteNode from './nodes/rewriteNode.js'; import { BaseLLM } from "langchain-core";
/** /**
* Simple directed graph implementation that supports reflection and rewrite nodes. * Simple selfcorrecting agent demo.
* Requires an OpenAI API key set in the environment variable OPENAI_API_KEY.
*/ */
class Graph { async function main() {
constructor() { // Ensure the API key is available
/** @type {Object.<string, Object>} */ if (!process.env.OPENAI_API_KEY) {
this.nodes = {}; console.error("Error: OPENAI_API_KEY environment variable is not set.");
/** @type {Array<{from: string, to: string}>} */ process.exit(1);
this.edges = [];
} }
/** // Instantiate the OpenAI LLM provider
* Adds a node to the graph. const llm = new OpenAI({
* @param {Object} node - Node instance (must have id and type). temperature: 0.7,
*/ // The API key is automatically read from the environment variable
addNode(node) { });
if (!node || !node.id) {
throw new Error('Node must have an id.'); // Verify that llm is an instance of BaseLLM (from langchain-core)
} if (!(llm instanceof BaseLLM)) {
this.nodes[node.id] = node; console.error("Error: The LLM instance is not a BaseLLM.");
process.exit(1);
} }
/** // Send a simple prompt to the LLM
* Adds a directed edge from one node to another. const prompt = "Hello, world! What is the capital of France?";
* @param {string} fromId - Source node id. try {
* @param {string} toId - Destination node id. const response = await llm.invoke(prompt);
*/ console.log("LLM response:", response);
addEdge(fromId, toId) { } catch (error) {
if (!this.nodes[fromId] || !this.nodes[toId]) { console.error("Error invoking LLM:", error);
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 }; main();
+4 -10
View File
@@ -1,10 +1,4 @@
import { app } from './langgraph'; export { Graph } from './graph';
export { BaseNode } from './nodes/baseNode';
async function main() { export { ReflectionNode } from './nodes/reflectionNode';
const result = await app.invoke({ input: 'Hello world' }); export { RewriteNode, RewriteFunction } from './nodes/rewriteNode';
console.log('Final result:', result);
}
main().catch((err) => {
console.error('Error during execution:', err);
});
+15
View File
@@ -0,0 +1,15 @@
export abstract class BaseNode {
id: string;
type: string;
inputs: Map<string, any>;
outputs: Map<string, any>;
constructor(id: string, type: string) {
this.id = id;
this.type = type;
this.inputs = new Map();
this.outputs = new Map();
}
abstract process(): void;
}
+14
View File
@@ -0,0 +1,14 @@
import { BaseNode } from './baseNode';
export class ReflectionNode extends BaseNode {
constructor(id: string) {
super(id, 'reflection');
}
process(): void {
// Copy all inputs to outputs with the same keys
this.inputs.forEach((value, key) => {
this.outputs.set(key, value);
});
}
}
+19
View File
@@ -0,0 +1,19 @@
import { BaseNode } from './baseNode';
export type RewriteFunction = (value: any) => any;
export class RewriteNode extends BaseNode {
private func: RewriteFunction;
constructor(id: string, func: RewriteFunction) {
super(id, 'rewrite');
this.func = func;
}
process(): void {
this.inputs.forEach((value, key) => {
const newValue = this.func(value);
this.outputs.set(key, newValue);
});
}
}
+8 -5
View File
@@ -1,10 +1,13 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2020", "target": "ES2019",
"module": "CommonJS", "module": "commonjs",
"outDir": "dist", "declaration": true,
"outDir": "./dist",
"strict": true, "strict": true,
"esModuleInterop": true "esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}, },
"include": ["src"] "include": ["src/**/*"]
} }