feat: solution for 6a02e23da6fe2e4ac16acf65
This commit is contained in:
@@ -8,7 +8,6 @@ from langchain_ollama import OllamaEmbeddings
|
|||||||
from langchain_core.documents import Document
|
from langchain_core.documents import Document
|
||||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||||
from langchain.agents import create_agent
|
from langchain.agents import create_agent
|
||||||
import os
|
|
||||||
|
|
||||||
# ---------- LLM ----------
|
# ---------- LLM ----------
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
@@ -18,53 +17,49 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.7,
|
temperature=0.7,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Vector Store ----------
|
# ---------- Embeddings ----------
|
||||||
|
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
||||||
|
|
||||||
|
# ---------- Qdrant client ----------
|
||||||
client = QdrantClient(":memory:")
|
client = QdrantClient(":memory:")
|
||||||
client.create_collection(
|
client.create_collection(
|
||||||
collection_name="knowledge_base",
|
collection_name="knowledge_base",
|
||||||
vectors_config=VectorParams(size=1024, distance=Distance.COSINE),
|
vectors_config=VectorParams(size=embeddings.embedding_size, distance=Distance.COSINE),
|
||||||
)
|
)
|
||||||
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
|
||||||
vector_store = QdrantVectorStore(
|
vector_store = QdrantVectorStore(
|
||||||
client=client,
|
client=client,
|
||||||
collection_name="knowledge_base",
|
collection_name="knowledge_base",
|
||||||
embedding=embeddings,
|
embedding=embeddings,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Text Splitter ----------
|
# ---------- Text splitter ----------
|
||||||
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
||||||
|
|
||||||
# ---------- Tools ----------
|
# ---------- Tools ----------
|
||||||
@tool
|
@tool
|
||||||
def add_to_knowledge_base(content: str, title: str) -> str:
|
def search_knowledge_base(query: str, max_results: int = 5) -> str:
|
||||||
"""Add a document to the knowledge base."""
|
"""Search the knowledge base for relevant documents."""
|
||||||
docs = splitter.split_text(content)
|
docs_with_score = vector_store.similarity_search_with_score(query, k=max_results)
|
||||||
documents = [Document(page_content=c, metadata={"title": title}) for c in docs]
|
if not docs_with_score:
|
||||||
vector_store.add_documents(documents)
|
return "No results found."
|
||||||
return f"Added {len(docs)} chunks under title '{title}'."
|
result_lines = [
|
||||||
|
f"{i+1}. {doc.page_content[:200]}..." for i, (doc, _) in enumerate(docs_with_score)
|
||||||
|
]
|
||||||
|
return "\n".join(result_lines)
|
||||||
|
|
||||||
@tool
|
@tool
|
||||||
def search_knowledge_base(query: str, max_results: int = 5) -> str:
|
def add_to_knowledge_base(content: str, title: str) -> str:
|
||||||
"""Search the knowledge base for relevant information."""
|
"""Add a new document to the knowledge base."""
|
||||||
results = vector_store.similarity_search_with_score(query, k=max_results)
|
chunks = splitter.split_text(content)
|
||||||
if not results:
|
documents = [Document(page_content=chunk, metadata={"title": title}) for chunk in chunks]
|
||||||
return "No relevant documents found."
|
vector_store.add_documents(documents)
|
||||||
out_lines = []
|
return f"Added {len(documents)} chunks from '{title}'."
|
||||||
for doc, score in results:
|
|
||||||
title = doc.metadata.get("title", "Untitled")
|
|
||||||
out_lines.append(f"[{score:.2f}] {title}: {doc.page_content[:200]}...")
|
|
||||||
return "\n".join(out_lines)
|
|
||||||
|
|
||||||
# ---------- Agent ----------
|
# ---------- Agent ----------
|
||||||
system_prompt = """
|
|
||||||
You are an assistant with access to a knowledge base.
|
|
||||||
Use the tools `add_to_knowledge_base` and `search_knowledge_base` as needed.
|
|
||||||
Respond concisely. If you need more info, ask the user.
|
|
||||||
"""
|
|
||||||
agent = create_agent(
|
agent = create_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[add_to_knowledge_base, search_knowledge_base],
|
tools=[search_knowledge_base, add_to_knowledge_base],
|
||||||
system_prompt=system_prompt,
|
system_prompt="You are an assistant that can search and add documents to the knowledge base.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- CLI ----------
|
# ---------- CLI ----------
|
||||||
@@ -77,29 +72,37 @@ def main():
|
|||||||
break
|
break
|
||||||
if not inp:
|
if not inp:
|
||||||
continue
|
continue
|
||||||
if inp.lower() in ("exit", "quit", "/quit"):
|
if inp.lower() in ("quit", "exit"):
|
||||||
print("Bye!")
|
print("Bye!")
|
||||||
break
|
break
|
||||||
|
|
||||||
|
# Add document
|
||||||
if inp.startswith("/add "):
|
if inp.startswith("/add "):
|
||||||
parts = inp[5:].split(None, 1)
|
parts = inp[5:].split(None, 1)
|
||||||
if len(parts) != 2:
|
if len(parts) != 2:
|
||||||
print("Usage: /add <title> <content>")
|
print("Usage: /add <title> <content>")
|
||||||
continue
|
continue
|
||||||
title, content = parts
|
title, content = parts
|
||||||
res = add_to_knowledge_base(content=content, title=title)
|
res = agent.invoke({"messages": [{"role": "human", "content": f"Add document '{title}'"}]})
|
||||||
print(res)
|
for msg in res["messages"]:
|
||||||
elif inp.startswith("/search "):
|
if hasattr(msg, "tool_calls"):
|
||||||
query = inp[8:].strip()
|
print(msg.content)
|
||||||
if not query:
|
|
||||||
print("Usage: /search <query>")
|
|
||||||
continue
|
continue
|
||||||
res = search_knowledge_base(query=query, max_results=5)
|
|
||||||
print(res)
|
# Search query
|
||||||
else:
|
if inp.startswith("/search "):
|
||||||
# Regular chat with agent
|
query = inp[8:].strip()
|
||||||
result = agent.invoke({"messages": [{"role": "human", "content": inp}]})
|
res = agent.invoke({"messages": [{"role": "human", "content": f"Search: {query}"}]})
|
||||||
ai_msg = result["messages"][-1]
|
for msg in res["messages"]:
|
||||||
print(ai_msg.content)
|
if hasattr(msg, "tool_calls"):
|
||||||
|
print(msg.content)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# General chat
|
||||||
|
res = agent.invoke({"messages": [{"role": "human", "content": inp}]})
|
||||||
|
for msg in res["messages"]:
|
||||||
|
if hasattr(msg, "content"):
|
||||||
|
print(msg.content)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user