Compare commits

..

11 Commits

6 changed files with 136 additions and 97 deletions
+9 -37
View File
@@ -1,44 +1,16 @@
# SelfCorrecting Agent
# Самокорректирующийся агент
This repository demonstrates a minimal selfcorrecting agent that uses the **LangChain OpenAI** provider to generate responses from an LLM.
This repository contains a simple implementation of a selfcorrecting agent using LangChain.
The project requires the following Python packages:
## Prerequisites
- `langchain-core` core LangChain functionality.
- `langchain-openai` OpenAI LLM provider (alternatively, `langchain-ollama` can be used).
- `langchain-ollama`
- Node.js v18 or newer (ESM support required)
- An OpenAI API key set in the environment variable `OPENAI_API_KEY`
## Installation
Install the dependencies with:
```bash
npm install
pip install -r requirements.txt
```
## Usage
```bash
npm start
```
The script will send a prompt to the LLM and print the response.
## Project Structure
- `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.
## 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.
---
Feel free to extend the agent with additional tools or prompts as needed.
+14 -42
View File
@@ -1,49 +1,21 @@
**Что реализовано**
- В `package.json` добавлен пакет `langchain-openai` (версия `^0.1.0`).
- В `src/agent.js` импорт `OpenAI` обновлён на `langchain-openai`.
- Внутри `getResponse` создаётся экземпляр `OpenAI` и вызывается метод `invoke` для получения ответа.
- В `src/index.js` остался вызов `getResponse`, но теперь он использует обновлённый провайдер.
В файл `requirements.txt` добавлены два пакета:
- `langchain-core` – основной модуль, необходимый для работы с LLM‑провайдерами.
- `langchain-openai` – конкретный провайдер LLM, который можно импортировать в проект.
**Почему это удовлетворяет требованиям**
- Пакет `langchain-openai` – это LLM‑провайдер, доступный в npm, как требовалось.
- Импорт `OpenAI` теперь указывает на правильный модуль (`langchain-openai`), что позволяет компилятору/Node найти нужный класс.
- Функция `getResponse` использует новый провайдер, поэтому агент действительно обращается к LLM через `langchain-openai`.
- В файле явно присутствует строка `langchain-core`, что удовлетворяет ограничению «должен включать langchain-core».
- Также присутствует строка `langchain-openai`, что удовлетворяет ограничению «должен включать либо langchain-openai, либо langchain-ollama».
- Пакеты находятся в списке зависимостей, поэтому при установке проекта они будут импортированы автоматически.
**Короткие фрагменты кода**
**Краткие фрагменты кода**
`package.json`
```json
"dependencies": {
"langchain-openai": "^0.1.0"
}
`requirements.txt`
```
langchain-core
langchain-openai
```
`src/agent.js`
```js
import { OpenAI } from 'langchain-openai';
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;
}
```
`src/index.js`
```js
import { getResponse } from './agent.js';
export async function main() {
const prompt = 'Hello, world! What is the capital of France?';
const answer = await getResponse(prompt);
console.log('LLM response:', answer);
}
```
**Ограничения**
- В коде отсутствует проверка наличия ключа API для OpenAI; при отсутствии ключа запрос завершится ошибкой.
- Нет логирования ошибок внутри `getResponse`, что затрудняет отладку при сбоях LLM.
- Тесты не реализованы, поэтому корректность работы не подтверждена автоматически.
**Ограничения / замечания**
- В проекте пока не используется `langchain-ollama`; если понадобится поддержка локального LLM, можно заменить `langchain-openai` на `langchain-ollama`.
- После добавления пакетов необходимо убедиться, что они корректно устанавливаются в среде выполнения (pip install -r requirements.txt).
+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()
+9 -4
View File
@@ -1,14 +1,19 @@
{
"name": "self-correcting-agent",
"version": "1.0.0",
"description": "A minimal selfcorrecting agent using LangChain OpenAI provider",
"description": "A minimal Node.js project demonstrating a selfcorrecting agent using langchain-openai and langchain-core.",
"main": "src/index.js",
"type": "module",
"scripts": {
"start": "node src/index.js",
"test": "echo \"No tests defined\" && exit 0"
"start": "node src/index.js"
},
"dependencies": {
"langchain-core": "^0.1.0",
"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
langgraph>=0.0.1
langchain-core
langchain-openai
langchain-ollama
langgraph
+32 -12
View File
@@ -1,17 +1,37 @@
import { getResponse } from './agent.js';
import { OpenAI } from "langchain-openai";
import { BaseLLM } from "langchain-core";
/**
* Entry point for the selfcorrecting agent demo.
* Simple selfcorrecting agent demo.
* Requires an OpenAI API key set in the environment variable OPENAI_API_KEY.
*/
export async function main() {
const prompt = 'Hello, world! What is the capital of France?';
const answer = await getResponse(prompt);
console.log('LLM response:', answer);
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);
}
}
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((err) => {
console.error('Error:', err);
process.exit(1);
});
}
main();