feat: solution for 'Экзамен: Самокорректирующийся агент'
This commit is contained in:
@@ -1,19 +1,61 @@
|
||||
# Project
|
||||
# Self‑Correcting Agent Demo
|
||||
|
||||
This project requires the `langgraph` package. Install dependencies with:
|
||||
This repository demonstrates a minimal Node.js project that uses the **langchain-openai** and **langchain-core** packages to create a simple LLM provider. The goal is to satisfy the requirement of adding these packages and configuring the LLM provider accordingly.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js v18 or newer
|
||||
- An OpenAI API key
|
||||
|
||||
## Setup
|
||||
|
||||
1. **Clone the repository** (or download the files):
|
||||
|
||||
```bash
|
||||
git clone https://git.brojs.ru/kuzakhmetovartur/ekzamen-samokorrektiruyuschiysya-agent.git
|
||||
cd ekzamen-samokorrektiruyuschiysya-agent
|
||||
```
|
||||
|
||||
2. **Install dependencies**:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. **Set the OpenAI API key**:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
On Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:OPENAI_API_KEY="your_api_key_here"
|
||||
```
|
||||
|
||||
## Running the Demo
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
npm start
|
||||
```
|
||||
|
||||
To test the import, you can run a simple Python script:
|
||||
You should see output similar to:
|
||||
|
||||
```python
|
||||
from langgraph.graph import Graph
|
||||
|
||||
# Example usage
|
||||
g = Graph()
|
||||
print("LangGraph imported successfully:", g)
|
||||
```
|
||||
LLM response: The capital of France is Paris.
|
||||
```
|
||||
|
||||
Make sure you have a compatible Python environment (Python 3.8+).
|
||||
## Project Structure
|
||||
|
||||
- `package.json` – Project metadata and dependencies (`langchain-openai` & `langchain-core`).
|
||||
- `src/index.js` – Main entry point that imports the LLM provider, verifies its type, and sends a prompt.
|
||||
- `README.md` – Documentation.
|
||||
|
||||
## Notes
|
||||
|
||||
- No additional external packages are used beyond the required `langchain-openai` and `langchain-core`.
|
||||
- The code uses ES modules (`"type": "module"` in `package.json`).
|
||||
- The LLM instance is verified to be an instance of `BaseLLM` from `langchain-core` to satisfy the configuration requirement.
|
||||
|
||||
---
|
||||
+41
-19
@@ -1,28 +1,50 @@
|
||||
**What was implemented**
|
||||
Added the `langgraph` package to the project’s `requirements.txt` so that imports from `langgraph.graph` resolve correctly.
|
||||
**Что реализовано**
|
||||
- В `package.json` добавлены зависимости `langchain-openai` и `langchain-core`.
|
||||
- В `src/index.js` импортированы `OpenAI` из `langchain-openai` и `BaseLLM` из `langchain-core`.
|
||||
- Создан экземпляр LLM‑провайдера, который автоматически читает ключ из переменной окружения `OPENAI_API_KEY`.
|
||||
- Добавлена проверка, что созданный объект действительно наследует `BaseLLM`.
|
||||
- Отправлен простой запрос к LLM и выведен ответ в консоль.
|
||||
|
||||
**Why it satisfies the requirement**
|
||||
The assignment explicitly asks for the `langgraph` dependency to be listed in the requirements file. By including the line
|
||||
**Почему это удовлетворяет требованиям**
|
||||
- Наличие пакетов в `dependencies` гарантирует, что они будут установлены при `npm install`.
|
||||
- Использование `OpenAI` из `langchain-openai` и проверка через `BaseLLM` из `langchain-core` демонстрирует корректную конфигурацию LLM‑провайдера.
|
||||
- В проекте не добавлено никаких сторонних пакетов помимо указанных, что соответствует ограничению «No other external packages should be added beyond those required».
|
||||
|
||||
```txt
|
||||
langgraph
|
||||
**Короткие фрагменты кода**
|
||||
|
||||
`package.json`
|
||||
```json
|
||||
{
|
||||
"dependencies": {
|
||||
"langchain-core": "^0.1.0",
|
||||
"langchain-openai": "^0.1.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
in `requirements.txt`, the package will be installed during the environment setup, enabling any module that does
|
||||
|
||||
```python
|
||||
from langgraph.graph import ...
|
||||
`src/index.js` – импорты
|
||||
```js
|
||||
import { OpenAI } from "langchain-openai";
|
||||
import { BaseLLM } from "langchain-core";
|
||||
```
|
||||
|
||||
to import without errors.
|
||||
`src/index.js` – создание LLM
|
||||
```js
|
||||
const llm = new OpenAI({
|
||||
temperature: 0.7,
|
||||
});
|
||||
```
|
||||
|
||||
**Code excerpts**
|
||||
`src/index.js` – проверка типа
|
||||
```js
|
||||
if (!(llm instanceof BaseLLM)) {
|
||||
console.error("Error: The LLM instance is not a BaseLLM.");
|
||||
process.exit(1);
|
||||
}
|
||||
```
|
||||
|
||||
- `requirements.txt`
|
||||
**Ограничения**
|
||||
- В примере реализован только базовый запрос; полноценный самокорректирующийся агент ещё не реализован.
|
||||
- Работает только при наличии корректного `OPENAI_API_KEY` в окружении.
|
||||
|
||||
```txt
|
||||
langgraph
|
||||
```
|
||||
|
||||
**Limitations**
|
||||
None – the change is minimal and directly addresses the reviewer’s feedback.
|
||||
Таким образом, проект теперь содержит необходимые пакеты и корректно конфигурирует LLM‑провайдера, как требовалось в задании.
|
||||
+9
-4
@@ -1,14 +1,19 @@
|
||||
{
|
||||
"name": "self-correcting-agent",
|
||||
"version": "1.0.0",
|
||||
"description": "A minimal self‑correcting agent using LangChain OpenAI provider",
|
||||
"description": "A minimal Node.js project demonstrating a self‑correcting 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"
|
||||
}
|
||||
+22
-12
@@ -1,24 +1,34 @@
|
||||
const { OpenAI } = require("langchain-openai");
|
||||
import { OpenAI } from "langchain-openai";
|
||||
import { BaseLLM } from "langchain-core";
|
||||
|
||||
// Ensure the OpenAI API key is set in the environment
|
||||
if (!process.env.OPENAI_API_KEY) {
|
||||
/**
|
||||
* Simple self‑correcting 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 with desired parameters
|
||||
const llm = new OpenAI({
|
||||
// Instantiate the OpenAI LLM provider
|
||||
const llm = new OpenAI({
|
||||
temperature: 0.7,
|
||||
modelName: "gpt-3.5-turbo",
|
||||
});
|
||||
// The API key is automatically read from the environment variable
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const prompt = "Hello, world!";
|
||||
// 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 {
|
||||
// Invoke the LLM with the prompt
|
||||
const response = await llm.invoke(prompt);
|
||||
console.log("Response:", response);
|
||||
console.log("LLM response:", response);
|
||||
} catch (error) {
|
||||
console.error("Error invoking LLM:", error);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user