From c43bbd68d2ccfa4997f272ae98b28982b96e09ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=9A=D1=83=D1=82?= =?UTF-8?q?=D0=BB=D0=B0=D1=85=D0=BC=D0=B5=D1=82=D0=BE=D0=B2?= Date: Thu, 28 May 2026 07:33:04 +0000 Subject: [PATCH] add tools.py --- tools.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tools.py diff --git a/tools.py b/tools.py new file mode 100644 index 0000000..b66d40d --- /dev/null +++ b/tools.py @@ -0,0 +1,54 @@ +""" +Utility tools for the LangChain agent. + +Two tools are exposed: + +* ``search_knowledge_base`` – semantic search in a Qdrant collection. +* ``add_to_knowledge_base`` – add a document to the same collection. + +Both use the :mod:`qdrant_store` module defined in this repository. +""" + +from __future__ import annotations + +import json +from typing import List, Dict + +from langchain.tools import tool +from langchain_core.documents import Document + +# Import the singleton store instance from qdrant_store.py +from .qdrant_store import store + +# --------------------------------------------------------------------------- +@tool +def search_knowledge_base(query: str, max_results: int = 5) -> str: + """Return a formatted string with the top *max_results* documents. + + The function performs a semantic similarity search using Qdrant and returns + a human‑readable list. If no results are found an explanatory message is + returned. + """ + docs: List[Document] = store.similarity_search(query, k=max_results) + if not docs: + return "No relevant documents found." + lines: List[str] = [] + for i, doc in enumerate(docs, start=1): + title = doc.metadata.get("title", f"doc{i}") + lines.append(f"{i}. {title}:\n{doc.page_content[:200]}{'...' if len(doc.page_content)>200 else ''}") + return "\n\n".join(lines) + +# --------------------------------------------------------------------------- +@tool +def add_to_knowledge_base(content: str, title: str = "document") -> str: + """Add a document to the knowledge base. + + The function creates a :class:`langchain_core.documents.Document` with the + supplied ``content`` and optional ``title`` metadata. It then delegates to + :func:`qdrant_store.store.add_documents`. + """ + doc = Document(page_content=content, metadata={"title": title}) + store.add_documents([doc]) + return f"Added '{title}' to the knowledge base." + +__all__ = ["search_knowledge_base", "add_to_knowledge_base"]