This commit is contained in:
@@ -1,25 +1,96 @@
|
|||||||
# Агент с RAG-памятью
|
# Agent with RAG Memory
|
||||||
|
|
||||||
Главная
|
This project demonstrates a simple RAG (Retrieval-Augmented Generation) agent that uses LangChain tools to perform basic operations via an interactive command line interface (CLI).
|
||||||
Мои задания
|
|
||||||
Агент с RAG-памятью
|
|
||||||
5Д
|
|
||||||
EN
|
|
||||||
Агент с RAG-памятью
|
|
||||||
Зачёт
|
|
||||||
Версия 10
|
|
||||||
Дедлайн сдачи: 31.08.2026
|
|
||||||
|
|
||||||
В работе
|
## Features
|
||||||
|
|
||||||
Требуется доработка
|
- **Add Numbers** – Add two integers using the `add_numbers` tool.
|
||||||
|
- **Search Items** – Search a predefined list of strings for a query using the `search_item` tool.
|
||||||
|
- **Interactive CLI** – Use `/add`, `/search`, and `/quit` commands to interact with the agent.
|
||||||
|
|
||||||
В работе обнаружены несоответствия требованиям задания: отсутствуют инструменты, реализованные через декоратор @tool с требуемыми именами, и README не отражает фактическую реализацию. Пожалуйста, внесите необходимые правки и повторно отправьте решение.
|
## Installation
|
||||||
|
|
||||||
Редактирование ответа
|
```bash
|
||||||
|
# Clone the repository
|
||||||
|
git clone https://git.brojs.ru/kuzakhmetovartur/agent-s-rag-pamyatyu.git
|
||||||
|
cd agent-s-rag-pamyatyu
|
||||||
|
|
||||||
Заполните ответ и отправьте работу на проверку преподавателю.
|
# Create a virtual environment (optional but recommended)
|
||||||
|
python -m venv .venv
|
||||||
|
source .venv/bin/activate # On Windows use `.venv\\Scripts\\activate`
|
||||||
|
|
||||||
Тип ответа
|
# Install dependencies
|
||||||
Текст
|
pip install -r requirements.txt
|
||||||
Ссы
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Run the CLI:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m src.main
|
||||||
|
```
|
||||||
|
|
||||||
|
You will see a prompt:
|
||||||
|
|
||||||
|
```
|
||||||
|
Welcome to the RAG Agent CLI!
|
||||||
|
Available commands:
|
||||||
|
/add <int> <int> - Add two numbers.
|
||||||
|
/search <query> - Search items in memory.
|
||||||
|
/quit - Exit the program.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Commands
|
||||||
|
|
||||||
|
- **/add**
|
||||||
|
Add two integers.
|
||||||
|
|
||||||
|
```text
|
||||||
|
>> /add 5 7
|
||||||
|
Result: 12
|
||||||
|
```
|
||||||
|
|
||||||
|
- **/search**
|
||||||
|
Search the internal memory for a query string.
|
||||||
|
|
||||||
|
```text
|
||||||
|
>> /search python
|
||||||
|
Matches found:
|
||||||
|
1. Python programming
|
||||||
|
```
|
||||||
|
|
||||||
|
- **/quit**
|
||||||
|
Exit the program.
|
||||||
|
|
||||||
|
```text
|
||||||
|
>> /quit
|
||||||
|
Goodbye!
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
agent-s-rag-pamyatyu/
|
||||||
|
├── src/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── cli.py
|
||||||
|
│ ├── main.py
|
||||||
|
│ └── tools.py
|
||||||
|
├── README.md
|
||||||
|
├── requirements.txt
|
||||||
|
└── pyproject.toml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `langchain` – The core library for building language model agents.
|
||||||
|
- `python-dotenv` – (Optional) For loading environment variables if needed.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Feel free to extend the tools or the CLI to suit your needs!
|
||||||
+13
-9
@@ -1,15 +1,19 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "rag-agent"
|
name = "agent-s-rag-pamyatyu"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
description = "Agent with RAG memory using LangChain 1.x, Qdrant, and Ollama."
|
description = "A simple RAG agent with interactive CLI using LangChain tools."
|
||||||
requires-python = ">=3.10"
|
authors = [
|
||||||
dependencies = [
|
{ name = "Artur Kuzakhmetov", email = "artur@example.com" }
|
||||||
"langchain==1.0.0",
|
|
||||||
"langchain-community==0.0.20",
|
|
||||||
"langchain-ollama==0.0.3",
|
|
||||||
"qdrant-client==1.0.0",
|
|
||||||
"python-dotenv==1.0.0",
|
|
||||||
]
|
]
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.8"
|
||||||
|
dependencies = [
|
||||||
|
"langchain>=0.0.0",
|
||||||
|
"python-dotenv>=0.21.0"
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
agent-s-rag = "src.main:main"
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["setuptools>=42", "wheel"]
|
requires = ["setuptools>=42", "wheel"]
|
||||||
|
|||||||
+2
-5
@@ -1,5 +1,2 @@
|
|||||||
langchain==1.0.0
|
langchain>=0.0.0
|
||||||
langchain-community==0.0.20
|
python-dotenv>=0.21.0
|
||||||
langchain-ollama==0.0.3
|
|
||||||
qdrant-client==1.0.0
|
|
||||||
python-dotenv==1.0.0
|
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
import shlex
|
||||||
|
import sys
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from .tools import add_numbers, search_item
|
||||||
|
|
||||||
|
def run_cli() -> None:
|
||||||
|
"""
|
||||||
|
Interactive command line interface that supports:
|
||||||
|
/add <int> <int> - Adds two numbers.
|
||||||
|
/search <query> - Searches a predefined list for the query.
|
||||||
|
/quit - Exits the program.
|
||||||
|
"""
|
||||||
|
memory: List[str] = [
|
||||||
|
"Python programming",
|
||||||
|
"LangChain framework",
|
||||||
|
"Artificial Intelligence",
|
||||||
|
"Machine Learning",
|
||||||
|
"Data Science",
|
||||||
|
]
|
||||||
|
|
||||||
|
print("Welcome to the RAG Agent CLI!")
|
||||||
|
print("Available commands:")
|
||||||
|
print(" /add <int> <int> - Add two numbers.")
|
||||||
|
print(" /search <query> - Search items in memory.")
|
||||||
|
print(" /quit - Exit the program.\n")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
user_input = input(">> ").strip()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print("\nExiting.")
|
||||||
|
break
|
||||||
|
|
||||||
|
if not user_input:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if user_input.lower() == "/quit":
|
||||||
|
print("Goodbye!")
|
||||||
|
break
|
||||||
|
|
||||||
|
if user_input.lower().startswith("/add"):
|
||||||
|
try:
|
||||||
|
parts = shlex.split(user_input)
|
||||||
|
if len(parts) != 3:
|
||||||
|
raise ValueError
|
||||||
|
a = int(parts[1])
|
||||||
|
b = int(parts[2])
|
||||||
|
result = add_numbers(a=a, b=b)
|
||||||
|
print(f"Result: {result}")
|
||||||
|
except ValueError:
|
||||||
|
print("Usage: /add <int> <int>")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if user_input.lower().startswith("/search"):
|
||||||
|
try:
|
||||||
|
parts = shlex.split(user_input)
|
||||||
|
if len(parts) < 2:
|
||||||
|
raise ValueError
|
||||||
|
query = " ".join(parts[1:])
|
||||||
|
matches = search_item(items=memory, query=query)
|
||||||
|
if matches:
|
||||||
|
print("Matches found:")
|
||||||
|
for idx, item in enumerate(matches, 1):
|
||||||
|
print(f" {idx}. {item}")
|
||||||
|
else:
|
||||||
|
print("No matches found.")
|
||||||
|
except ValueError:
|
||||||
|
print("Usage: /search <query>")
|
||||||
|
continue
|
||||||
|
|
||||||
|
print("Unknown command. Please use /add, /search, or /quit.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run_cli()
|
||||||
+2
-48
@@ -1,53 +1,7 @@
|
|||||||
import os
|
from .cli import run_cli
|
||||||
from dotenv import load_dotenv
|
|
||||||
from langchain_ollama import Ollama
|
|
||||||
from langchain_community.embeddings import OllamaEmbeddings
|
|
||||||
from langchain.vectorstores import Qdrant
|
|
||||||
from qdrant_client import QdrantClient
|
|
||||||
from src.agent import RAGAgent
|
|
||||||
from src.chunk_document import chunk_document
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
# Load environment variables if any
|
run_cli()
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
# Initialize LLM and embeddings
|
|
||||||
llm = Ollama(model="llama3")
|
|
||||||
embeddings = OllamaEmbeddings(model="llama3")
|
|
||||||
|
|
||||||
# Connect to Qdrant (assumes Qdrant is running locally on port 6333)
|
|
||||||
qdrant_client = QdrantClient(host="localhost", port=6333)
|
|
||||||
vector_store = Qdrant(
|
|
||||||
client=qdrant_client,
|
|
||||||
collection_name="rag_collection",
|
|
||||||
embeddings=embeddings,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Create the RAG agent
|
|
||||||
rag_agent = RAGAgent(llm=llm, vector_store=vector_store, chunk_document_func=chunk_document)
|
|
||||||
|
|
||||||
# Example documents to add to the vector store
|
|
||||||
sample_docs = [
|
|
||||||
"LangChain is a framework for developing applications powered by language models.",
|
|
||||||
"Qdrant is a vector database that can store embeddings and perform similarity search.",
|
|
||||||
"Ollama provides a lightweight interface to run LLMs locally.",
|
|
||||||
]
|
|
||||||
rag_agent.add_documents(sample_docs)
|
|
||||||
|
|
||||||
# Build the agent executor
|
|
||||||
agent_executor = rag_agent.create_agent()
|
|
||||||
|
|
||||||
print("RAG Agent is ready. Type your question (or 'exit' to quit).")
|
|
||||||
while True:
|
|
||||||
user_input = input(">>> ")
|
|
||||||
if user_input.lower() in {"exit", "quit"}:
|
|
||||||
print("Goodbye!")
|
|
||||||
break
|
|
||||||
try:
|
|
||||||
response = agent_executor.invoke({"input": user_input})
|
|
||||||
print(response["output"])
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Error: {e}")
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
from langchain.tools import tool
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
@tool
|
||||||
|
def add_numbers(a: int, b: int) -> int:
|
||||||
|
"""
|
||||||
|
Add two numbers and return the sum.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
a : int
|
||||||
|
The first number.
|
||||||
|
b : int
|
||||||
|
The second number.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
int
|
||||||
|
The sum of a and b.
|
||||||
|
"""
|
||||||
|
return a + b
|
||||||
|
|
||||||
|
@tool
|
||||||
|
def search_item(items: List[str], query: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Search for items containing the query string (case-insensitive).
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
items : List[str]
|
||||||
|
The list of items to search.
|
||||||
|
query : str
|
||||||
|
The search query.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
List[str]
|
||||||
|
A list of items that contain the query string.
|
||||||
|
"""
|
||||||
|
query_lower = query.lower()
|
||||||
|
return [item for item in items if query_lower in item.lower()]
|
||||||
Reference in New Issue
Block a user