Обновить tools.py

This commit is contained in:
2026-05-28 13:06:11 +00:00
parent ec966f431f
commit 90769e4943
+23 -39
View File
@@ -1,57 +1,41 @@
""" from langchain.tools import tool
tools.py — RAG-инструменты для агента. from vector_store import search_documents, add_documents
Два инструмента через декоратор @tool:
• search_knowledge_base — семантический поиск в базе знаний
• add_to_knowledge_base — добавление документа в базу
"""
from langchain_core.tools import tool
from vector_store import add_documents, search
@tool @tool
def search_knowledge_base(query: str, max_results: int = 5) -> str: def search_knowledge_base(query: str, max_results: int = 5) -> str:
""" """Semantic search in the knowledge base. Use this tool to find relevant information.
Выполняет семантический поиск в базе знаний.
Args: Args:
query: поисковый запрос на естественном языке. query: The search query string.
max_results: максимальное количество возвращаемых результатов (по умолчанию 5). max_results: Maximum number of results to return (default 5).
Returns: Returns:
Строка с найденными фрагментами и их оценками релевантности. Formatted string with search results and relevance scores.
""" """
results = search(query, max_results=max_results) results = search_documents(query, max_results=max_results)
if not results: if not results:
return "В базе знаний ничего не найдено по данному запросу." return "No results found in the knowledge base."
output_lines = [f"Found {len(results)} result(s):\n"]
lines = [] for i, r in enumerate(results, 1):
for i, (doc, score) in enumerate(results, start=1): title = r["metadata"].get("title", "Unknown")
title = doc.metadata.get("title", "") score = r["score"]
chunk = doc.metadata.get("chunk_index", 0) content = r["content"]
lines.append( output_lines.append(f"[{i}] Title: {title} | Score: {score}")
f"[{i}] (score={score:.3f}) «{title}» chunk#{chunk}\n{doc.page_content}" output_lines.append(f" {content}\n")
) return "\n".join(output_lines)
return "\n\n".join(lines)
@tool @tool
def add_to_knowledge_base(content: str, title: str = "") -> str: def add_to_knowledge_base(content: str, title: str) -> str:
""" """Add a document to the knowledge base. Use this tool to store new information.
Добавляет новый документ в базу знаний.
Args: Args:
content: текстовое содержимое документа. content: The full text content of the document to add.
title: название / источник документа (необязательно). title: A descriptive title for the document.
Returns: Returns:
Сообщение об успехе с количеством созданных чанков. Confirmation message with the number of chunks stored.
""" """
n_chunks = add_documents(content, title=title) num_chunks = add_documents(content=content, title=title)
return ( return f"Successfully added document '{title}' to the knowledge base ({num_chunks} chunk(s) stored)."
f"Документ «{title or 'без названия'}» успешно добавлен в базу знаний. "
f"Создано чанков: {n_chunks}."
)