feat: solution for 'Агент с RAG-памятью'
CI / build (push) Has been cancelled

This commit is contained in:
2026-06-25 12:41:22 +03:00
parent 14ab96d098
commit a8a8111eca
4 changed files with 117 additions and 112 deletions
+71 -18
View File
@@ -1,27 +1,80 @@
import express from 'express';
import dotenv from 'dotenv';
import bodyParser from 'body-parser';
import { VirtualFileSystem } from './vfs';
import { LLM } from './llm';
import { Agent } from './agent';
import { createRoutes } from './routes';
import { errorHandler } from './middleware';
import { OpenAI } from "langchain/llms/openai";
import { OpenAIEmbeddings } from "langchain/embeddings/openai";
import { FAISS } from "langchain/vectorstores/faiss";
import { RetrievalQA } from "langchain/chains/retrieval-qa";
import { Tool } from "langchain/tools/base";
import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import * as dotenv from "dotenv";
dotenv.config();
const app = express();
const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
async function main() {
// Ensure API key is set
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
console.error("Error: OPENAI_API_KEY environment variable is not set.");
process.exit(1);
}
app.use(bodyParser.json());
// Sample document
const sampleText = `
The quick brown fox jumps over the lazy dog. This sentence is often used to test typing and fonts.
The capital of France is Paris. Paris is known for its art, gastronomy, and culture.
The Earth revolves around the Sun every 365.25 days. The Moon orbits the Earth approximately every 27.3 days.
`;
const vfs = new VirtualFileSystem();
const llm = new LLM();
const agent = new Agent(vfs, llm);
// Text splitter configuration (chunk size 1000, overlap 200)
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 200,
});
app.use('/', createRoutes(agent));
// Split the document into chunks
const docs = await splitter.splitText(sampleText);
app.use(errorHandler);
// Initialize embeddings and vector store
const embeddings = new OpenAIEmbeddings({ openAIApiKey: apiKey });
const vectorStore = await FAISS.fromTexts(docs, [], embeddings);
app.listen(port, () => {
console.log(`RAG Memory Agent listening on port ${port}`);
// Initialize LLM
const llm = new OpenAI({
openAIApiKey: apiKey,
temperature: 0,
});
// Create RetrievalQA chain
const qaChain = RetrievalQA.fromLLM(llm, vectorStore);
// Define a tool that uses the QA chain
const ragTool = new Tool({
name: "RAG",
description: "Answer questions based on the provided documents using Retrieval-Augmented Generation.",
func: async (input: string) => {
const result = await qaChain.invoke({ query: input });
return result.output as string;
},
});
// Initialize the agent with the updated method
const agent = await initializeAgentExecutorWithOptions(
[ragTool],
llm,
{
agentType: "zero-shot-react-description",
verbose: true,
}
);
// Run a sample query
const query = "What is the capital of France?";
const response = await agent.invoke({ input: query });
console.log("\n=== Agent Response ===");
console.log(response.output);
}
main().catch((err) => {
console.error("Error in main execution:", err);
process.exit(1);
});