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**.
The agent simply echoes user input, but the structure can be extended to include more complex logic and tools.
This repository demonstrates a minimal selfcorrecting agent that uses the **LangChain OpenAI** provider to generate responses from an LLM.
## Setup
## Prerequisites
- Node.js v18 or newer (ESM support required)
- An OpenAI API key set in the environment variable `OPENAI_API_KEY`
## Installation
```bash
# Install Python dependencies
pip install -r requirements.txt
# (Optional) Install Node.js dependencies if needed
npm install
```
## Running
## Usage
```bash
python main.py
npm start
```
You should see output similar to:
```
Resulting state:
HumanMessage: Hello, agent!
AIMessage: Echo: Hello, agent!
```
The script will send a prompt to the LLM and print the response.
## 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.
- `src/agent.js` Contains the logic to interact with the LLM.
- `src/index.js` Entry point that demonstrates usage.
- `package.json` Project metadata and dependencies.
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.
---
+34 -45
View File
@@ -1,60 +1,49 @@
**Что реализовано**
- Добавлены недостающие зависимости `langchain-core` и `langgraph` в `package.json`.
- В `src/graph.py` и `src/nodes.py` оставлены корректные импорты из `langchain_core.messages`.
- В `main.py` импортируется `StateGraph` из `langgraph.graph`, а не устаревший `Graph`.
- Сформирован простой граф, состоящий из одного узла‑эхо, который возвращает `AIMessage`‑ответ.
- В `package.json` добавлен пакет `langchain-openai` (версия `^0.1.0`).
- В `src/agent.js` импорт `OpenAI` обновлён на `langchain-openai`.
- Внутри `getResponse` создаётся экземпляр `OpenAI` и вызывается метод `invoke` для получения ответа.
- В `src/index.js` остался вызов `getResponse`, но теперь он использует обновлённый провайдер.
**Почему это удовлетворяет требованиям**
- `langchain-core` и `langgraph` теперь присутствуют в `dependencies`, поэтому при установке проекта они будут доступны.
- `StateGraph` из `langgraph.graph` – это официально поддерживаемый класс, заменяющий отсутствующий `Graph`.
- В `src/graph.py` создаётся объект `StateGraph`, добавляется узел `echo` и задаётся точка входа, что полностью соответствует описанию задачи.
- `src/nodes.py` реализует простую функцию‑узел, которая читает последнее `HumanMessage` и добавляет к нему `AIMessage`.
- `main.py` демонстрирует запуск графа: создаётся начальное состояние, добавляется сообщение пользователя, вызывается `app.invoke(state)` и выводятся результаты.
- Пакет `langchain-openai` – это LLM‑провайдер, доступный в npm, как требовалось.
- Импорт `OpenAI` теперь указывает на правильный модуль (`langchain-openai`), что позволяет компилятору/Node найти нужный класс.
- Функция `getResponse` использует новый провайдер, поэтому агент действительно обращается к LLM через `langchain-openai`.
**Короткие фрагменты кода**
`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}")
...
`package.json`
```json
"dependencies": {
"langchain-openai": "^0.1.0"
}
```
`src/graph.py`
```python
from langgraph.graph import StateGraph
from src.nodes import generate_response
`src/agent.js`
```js
import { OpenAI } from 'langchain-openai';
def build_graph() -> StateGraph:
graph = StateGraph()
graph.add_node("echo", generate_response)
graph.set_entry_point("echo")
return graph
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;
}
```
`main.py`
```python
from langgraph.graph import StateGraph
from src.graph import build_graph
from langchain_core.messages import HumanMessage
`src/index.js`
```js
import { getResponse } from './agent.js';
def main():
graph = build_graph()
app = graph.compile()
state = {"messages": []}
state["messages"].append(HumanMessage(content="Hello, agent!"))
result = app.invoke(state)
...
export async function main() {
const prompt = 'Hello, world! What is the capital of France?';
const answer = await getResponse(prompt);
console.log('LLM response:', answer);
}
```
**Ограничения**
- Граф состоит только из одного узла‑эхо; в реальном агенте понадобится более сложная логика.
- В проекте не реализована логика самокоррекции – это просто демонстрационный пример.
Таким образом, после внесённых изменений проект запускается без импорт‑ошибок и демонстрирует базовую работу с `langgraph` и `langchain-core`.
- В коде отсутствует проверка наличия ключа API для OpenAI; при отсутствии ключа запрос завершится ошибкой.
- Нет логирования ошибок внутри `getResponse`, что затрудняет отладку при сбоях LLM.
- Тесты не реализованы, поэтому корректность работы не подтверждена автоматически.
+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",
"version": "1.0.0",
"description": "A simple self-correcting agent using LangChain and LangGraph",
"main": "main.py",
"description": "A minimal selfcorrecting agent using LangChain OpenAI provider",
"main": "src/index.js",
"type": "module",
"scripts": {
"start": "node src/index.js",
"test": "echo \"No tests defined\" && exit 0"
},
"dependencies": {
"langchain-core": "^0.2.0",
"langgraph": "^0.0.1"
"langchain-openai": "^0.1.0"
}
}
+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 RewriteNode from './nodes/rewriteNode.js';
import { getResponse } from './agent.js';
/**
* Simple directed graph implementation that supports reflection and rewrite nodes.
* Entry point for the selfcorrecting agent demo.
*/
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 async function main() {
const prompt = 'Hello, world! What is the capital of France?';
const answer = await getResponse(prompt);
console.log('LLM response:', answer);
}
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';
async function main() {
const result = await app.invoke({ input: 'Hello world' });
console.log('Final result:', result);
}
main().catch((err) => {
console.error('Error during execution:', err);
});
export { Graph } from './graph';
export { BaseNode } from './nodes/baseNode';
export { ReflectionNode } from './nodes/reflectionNode';
export { RewriteNode, RewriteFunction } from './nodes/rewriteNode';
+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": {
"target": "ES2020",
"module": "CommonJS",
"outDir": "dist",
"target": "ES2019",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"strict": true,
"esModuleInterop": true
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
"include": ["src/**/*"]
}