feat: solution for 'Экзамен: Самокорректирующийся агент'
This commit is contained in:
+36
-73
@@ -1,86 +1,49 @@
|
||||
**What was implemented**
|
||||
- Added two concrete node types – `ReflectionNode` and `RewriteNode` – that satisfy the assignment’s definition of reflection and rewriting nodes.
|
||||
- Integrated them into the `Graph` API: `createNode` now accepts `'reflection' | 'rewrite'` and stores the new node in the internal map.
|
||||
- Updated the execution loop in `Graph.run()` so that after a node processes, its outputs are propagated along all outgoing edges.
|
||||
- Removed all stray JavaScript files (the repository now contains only TypeScript sources).
|
||||
**Что реализовано**
|
||||
- В `package.json` добавлен пакет `langchain-openai` (версия `^0.1.0`).
|
||||
- В `src/agent.js` импорт `OpenAI` обновлён на `langchain-openai`.
|
||||
- Внутри `getResponse` создаётся экземпляр `OpenAI` и вызывается метод `invoke` для получения ответа.
|
||||
- В `src/index.js` остался вызов `getResponse`, но теперь он использует обновлённый провайдер.
|
||||
|
||||
**Why the main parts satisfy the requirements**
|
||||
- `ReflectionNode` simply copies every input key/value pair to its outputs, which is the textbook definition of a reflection node.
|
||||
- `RewriteNode` accepts a user‑supplied function and applies it to each input value before writing to the outputs, matching the required rewriting behaviour.
|
||||
- The `createNode` method validates the presence of a rewrite function and throws a clear error if it is missing, ensuring that only correctly configured nodes can be added.
|
||||
- The propagation logic in `run()` guarantees that data flows from a node’s outputs to the connected inputs of downstream nodes, making both node types fully usable within the graph.
|
||||
- Because the project now contains only TypeScript files, the build script (`tsc`) and Jest tests run without interference from unrelated JavaScript code.
|
||||
**Почему это удовлетворяет требованиям**
|
||||
- Пакет `langchain-openai` – это LLM‑провайдер, доступный в npm, как требовалось.
|
||||
- Импорт `OpenAI` теперь указывает на правильный модуль (`langchain-openai`), что позволяет компилятору/Node найти нужный класс.
|
||||
- Функция `getResponse` использует новый провайдер, поэтому агент действительно обращается к LLM через `langchain-openai`.
|
||||
|
||||
**Key code excerpts**
|
||||
**Короткие фрагменты кода**
|
||||
|
||||
*src/nodes/reflectionNode.ts*
|
||||
```ts
|
||||
export class ReflectionNode extends BaseNode {
|
||||
constructor(id: string) {
|
||||
super(id, 'reflection');
|
||||
}
|
||||
|
||||
process(): void {
|
||||
this.inputs.forEach((value, key) => {
|
||||
this.outputs.set(key, value);
|
||||
});
|
||||
}
|
||||
`package.json`
|
||||
```json
|
||||
"dependencies": {
|
||||
"langchain-openai": "^0.1.0"
|
||||
}
|
||||
```
|
||||
|
||||
*src/nodes/rewriteNode.ts*
|
||||
```ts
|
||||
export class RewriteNode extends BaseNode {
|
||||
private func: RewriteFunction;
|
||||
`src/agent.js`
|
||||
```js
|
||||
import { OpenAI } from 'langchain-openai';
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
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/graph.ts – node creation*
|
||||
```ts
|
||||
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);
|
||||
}
|
||||
this.nodes.set(id, node);
|
||||
return node;
|
||||
`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);
|
||||
}
|
||||
```
|
||||
|
||||
*src/graph.ts – execution loop*
|
||||
```ts
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Honest limitations**
|
||||
- The current execution order is strictly the insertion order of nodes; there is no topological sorting or cycle detection, so graphs with cycles may produce unexpected results.
|
||||
- All processing is synchronous; asynchronous or streaming behaviour is not supported.
|
||||
- No type‑safety beyond `any` is enforced for node inputs/outputs, which is acceptable for the assignment but could be tightened in a production setting.
|
||||
**Ограничения**
|
||||
- В коде отсутствует проверка наличия ключа API для OpenAI; при отсутствии ключа запрос завершится ошибкой.
|
||||
- Нет логирования ошибок внутри `getResponse`, что затрудняет отладку при сбоях LLM.
|
||||
- Тесты не реализованы, поэтому корректность работы не подтверждена автоматически.
|
||||
Reference in New Issue
Block a user