Compare commits

..

2 Commits

12 changed files with 250 additions and 151 deletions
+29 -23
View File
@@ -1,38 +1,44 @@
# Self-Correcting Agent # SelfCorrecting Agent
This project demonstrates a minimal selfcorrecting agent built with **LangChain** and **LangGraph**. This repository demonstrates a minimal selfcorrecting agent that uses the **LangChain OpenAI** provider to generate responses from an LLM.
The agent simply echoes user input, but the structure can be extended to include more complex logic and tools.
## Setup ## Prerequisites
- Node.js v18 or newer (ESM support required)
- An OpenAI API key set in the environment variable `OPENAI_API_KEY`
## Installation
```bash ```bash
# Install Python dependencies
pip install -r requirements.txt
# (Optional) Install Node.js dependencies if needed
npm install npm install
``` ```
## Running ## Usage
```bash ```bash
python main.py npm start
``` ```
You should see output similar to: The script will send a prompt to the LLM and print the response.
```
Resulting state:
HumanMessage: Hello, agent!
AIMessage: Echo: Hello, agent!
```
## Project Structure ## Project Structure
- `src/` Core logic (nodes and graph construction). - `src/agent.js` Contains the logic to interact with the LLM.
- `main.py` Entry point that builds and runs the graph. - `src/index.js` Entry point that demonstrates usage.
- `requirements.txt` Python dependencies. - `package.json` Project metadata and 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. ## Adding a Different LLM Provider
If you prefer to use another provider (e.g., Ollama), replace the dependency and imports:
```bash
npm install langchain-ollama
```
```js
import { Ollama } from 'langchain-ollama';
```
Adjust the model initialization accordingly.
---
+37 -48
View File
@@ -1,60 +1,49 @@
**Что реализовано** **Что реализовано**
- В `package.json` добавлен пакет `langchain-openai` (версия `^0.1.0`).
- В `src/agent.js` импорт `OpenAI` обновлён на `langchain-openai`.
- Внутри `getResponse` создаётся экземпляр `OpenAI` и вызывается метод `invoke` для получения ответа.
- В `src/index.js` остался вызов `getResponse`, но теперь он использует обновлённый провайдер.
- Добавлены недостающие зависимости `langchain-core` и `langgraph` в `package.json`. **Почему это удовлетворяет требованиям**
- В `src/graph.py` и `src/nodes.py` оставлены корректные импорты из `langchain_core.messages`. - Пакет `langchain-openai` – это LLM‑провайдер, доступный в npm, как требовалось.
- В `main.py` импортируется `StateGraph` из `langgraph.graph`, а не устаревший `Graph`. - Импорт `OpenAI` теперь указывает на правильный модуль (`langchain-openai`), что позволяет компилятору/Node найти нужный класс.
- Сформирован простой граф, состоящий из одного узла‑эхо, который возвращает `AIMessage`‑ответ. - Функция `getResponse` использует новый провайдер, поэтому агент действительно обращается к LLM через `langchain-openai`.
**Почему это удовлетворяет требованиям**
- `langchain-core` и `langgraph` теперь присутствуют в `dependencies`, поэтому при установке проекта они будут доступны.
- `StateGraph` из `langgraph.graph` – это официально поддерживаемый класс, заменяющий отсутствующий `Graph`.
- В `src/graph.py` создаётся объект `StateGraph`, добавляется узел `echo` и задаётся точка входа, что полностью соответствует описанию задачи.
- `src/nodes.py` реализует простую функцию‑узел, которая читает последнее `HumanMessage` и добавляет к нему `AIMessage`.
- `main.py` демонстрирует запуск графа: создаётся начальное состояние, добавляется сообщение пользователя, вызывается `app.invoke(state)` и выводятся результаты.
**Короткие фрагменты кода** **Короткие фрагменты кода**
`src/nodes.py` `package.json`
```python ```json
from langchain_core.messages import HumanMessage, AIMessage "dependencies": {
"langchain-openai": "^0.1.0"
def generate_response(state: Dict[str, Any]) -> Dict[str, Any]: }
...
ai_msg = AIMessage(content=f"Echo: {last_msg.content}")
...
``` ```
`src/graph.py` `src/agent.js`
```python ```js
from langgraph.graph import StateGraph import { OpenAI } from 'langchain-openai';
from src.nodes import generate_response
def build_graph() -> StateGraph: export async function getResponse(prompt) {
graph = StateGraph() const model = new OpenAI({
graph.add_node("echo", generate_response) temperature: 0.7,
graph.set_entry_point("echo") modelName: 'gpt-3.5-turbo'
return graph });
const response = await model.invoke(prompt);
return response;
}
``` ```
`main.py` `src/index.js`
```python ```js
from langgraph.graph import StateGraph import { getResponse } from './agent.js';
from src.graph import build_graph
from langchain_core.messages import HumanMessage
def main(): export async function main() {
graph = build_graph() const prompt = 'Hello, world! What is the capital of France?';
app = graph.compile() const answer = await getResponse(prompt);
state = {"messages": []} console.log('LLM response:', answer);
state["messages"].append(HumanMessage(content="Hello, agent!")) }
result = app.invoke(state)
...
``` ```
**Ограничения** **Ограничения**
- В коде отсутствует проверка наличия ключа API для OpenAI; при отсутствии ключа запрос завершится ошибкой.
- Граф состоит только из одного узла‑эхо; в реальном агенте понадобится более сложная логика. - Нет логирования ошибок внутри `getResponse`, что затрудняет отладку при сбоях LLM.
- В проекте не реализована логика самокоррекции – это просто демонстрационный пример. - Тесты не реализованы, поэтому корректность работы не подтверждена автоматически.
Таким образом, после внесённых изменений проект запускается без импорт‑ошибок и демонстрирует базовую работу с `langgraph` и `langchain-core`.
+5
View File
@@ -0,0 +1,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts']
};
+8 -4
View File
@@ -1,10 +1,14 @@
{ {
"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 selfcorrecting agent using LangChain OpenAI provider",
"main": "main.py", "main": "src/index.js",
"type": "module",
"scripts": {
"start": "node src/index.js",
"test": "echo \"No tests defined\" && exit 0"
},
"dependencies": { "dependencies": {
"langchain-core": "^0.2.0", "langchain-openai": "^0.1.0"
"langgraph": "^0.0.1"
} }
} }
+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);
}
}
+12 -61
View File
@@ -1,66 +1,17 @@
import ReflectionNode from './nodes/reflectionNode.js'; import { getResponse } from './agent.js';
import RewriteNode from './nodes/rewriteNode.js';
/** /**
* Simple directed graph implementation that supports reflection and rewrite nodes. * Entry point for the selfcorrecting agent demo.
*/ */
class Graph { export async function main() {
constructor() { const prompt = 'Hello, world! What is the capital of France?';
/** @type {Object.<string, Object>} */ const answer = await getResponse(prompt);
this.nodes = {}; console.log('LLM response:', answer);
/** @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 }; if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((err) => {
console.error('Error:', err);
process.exit(1);
});
}
+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/**/*"]
} }