fix(needs_fixes): 1 исправлений, 0 отстояно — main.py

This commit is contained in:
2026-06-04 17:20:46 +00:00
parent 80471ece0c
commit 723313e30a
+87 -69
View File
@@ -1,124 +1,142 @@
import os import os
import asyncio import asyncio
import json
from pathlib import Path from pathlib import Path
from langchain_openai import ChatOpenAI, OpenAIEmbeddings from typing import List
from langchain_chroma import Chroma
from langchain_core.documents import Document from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langchain.tools import tool from langchain.tools import tool
from deepagents import create_deep_agent from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
# ----------------- Configuration ----------------- # --- Embeddings and vector store (Qdrant + Ollama) ---
# Load API key from .env or environment variable from langchain_ollama import OllamaEmbeddings
os.environ.setdefault("OPENAI_API_KEY", os.getenv("OPENAI_API_KEY", "")) from langchain_qdrant import Qdrant
from langchain_core.documents import Document
# LLM via OpenRouter # Load OpenRouter key for LLM (required by Ollama embeddings as well)
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# LLM configuration (OpenRouter)
llm = ChatOpenAI( llm = ChatOpenAI(
model="openai/gpt-oss-20b:free", model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1", base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENAI_API_KEY"), api_key=OPENAI_API_KEY,
temperature=0.0, temperature=0.0,
) )
# Embeddings for Chroma # Embeddings via Ollama (nomic-embed-text)
embeddings = OpenAIEmbeddings( embeddings = OllamaEmbeddings(model="nomic-embed-text")
model="text-embedding-3-small",
base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENAI_API_KEY"),
)
# ----------------- Chroma DB ----------------- # Qdrant client (inmemory for demo; replace with host/port for prod)
CHROMA_PATH = Path("./chroma_faq") qdrant_client = Qdrant(
CHROMA_COLLECTION = "faq_collection" collection_name="faq_collection",
vector_store = Chroma( url="http://localhost:6333", # default Qdrant local URL
collection_name=CHROMA_COLLECTION,
embedding_function=embeddings, embedding_function=embeddings,
persist_directory=str(CHROMA_PATH),
) )
# Load markdown files into Chroma (idempotent) # --- Data loading and indexing ---
DATA_DIR = Path("./data") DATA_DIR = Path("data")
if not CHROMA_PATH.exists() or not list(CHROMA_PATH.iterdir()): CHROMA_PERSIST = Path("./qdrant_faq") # not used directly but kept for compatibility
docs = []
def load_faq_to_qdrant() -> None:
"""Read all .md files from DATA_DIR, chunk them, embed and store in Qdrant."""
if not DATA_DIR.exists():
print("Data directory not found. Create 'data/' with .md files.")
return
docs: List[Document] = []
for md_file in DATA_DIR.glob("*.md"): for md_file in DATA_DIR.glob("*.md"):
text = md_file.read_text(encoding="utf-8") text = md_file.read_text(encoding="utf-8")
docs.append(Document(page_content=text, metadata={"source": md_file.name})) # Simple split by double newlines as a naive chunker
vector_store.add_documents(docs) for i, chunk in enumerate(text.split("\n\n")):
vector_store.persist() docs.append(Document(page_content=chunk, metadata={"source": md_file.name, "chunk": i}))
# Add to Qdrant
qdrant_client.add_documents(docs)
print(f"Indexed {len(docs)} chunks into Qdrant.")
# ----------------- Tools ----------------- # --- Tools ---
@tool @tool
def search_course_docs(query: str) -> str: def search_course_docs(query: str, k: int = 3) -> str:
"""Search the local FAQ collection for relevant passages.""" """Search the local FAQ collection for relevant passages."""
results = vector_store.similarity_search(query, k=3) results = qdrant_client.similarity_search(query, k=k)
if not results: if not results:
return "No relevant information found in the course materials." return "No relevant information found in the course materials."
return "\n---\n".join(f"{doc.metadata.get('source', 'unknown')}\n{doc.page_content}" for doc in results) return "\n\n---\n\n".join(r.page_content for r in results)
# Mock MCP tool static JSON data # MCP-style tool: fetch metadata from a static JSON file
COURSE_META = { META_FILE = Path("meta.json")
"schedule": "Monday 10:00-12:00, Wednesday 14:00-16:00",
"instructor": "Dr. Ivanov",
"location": "Room 101",
}
@tool @tool
def fetch_course_meta(query: str) -> str: def fetch_course_meta(query: str) -> str:
"""Return course metadata matching the query keyword. """Return course metadata that matches the query.
For example, query="schedule" returns the schedule string. For demo purposes, we load a static JSON file and perform a simple keyword search.
""" """
key = query.lower().strip() if not META_FILE.exists():
return COURSE_META.get(key, f"No metadata found for '{query}'.") return "Metadata file not found."
data = json.loads(META_FILE.read_text(encoding="utf-8"))
# Very naive matching: return entries where query is a substring of any value
matches = []
for key, value in data.items():
if isinstance(value, str) and query.lower() in value.lower():
matches.append(f"{key}: {value}")
if not matches:
return "No metadata matches your query."
return "\n".join(matches)
# ----------------- Backend ----------------- # --- Agent setup ---
backend = CompositeBackend([ backend = CompositeBackend([
LocalShellBackend(workspace_dir="./workspace"), LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(), FilesystemBackend(),
]) ])
# ----------------- Agent -----------------
agent = create_deep_agent( agent = create_deep_agent(
model=llm, model=llm,
tools=[search_course_docs, fetch_course_meta], tools=[search_course_docs, fetch_course_meta],
backend=backend, backend=backend,
system_prompt=( system_prompt=(
"You are a helpful FAQ assistant for the course.\n" "You are a helpful FAQ bot for a course.\n"
"When answering a question, first decide whether the answer comes from the course materials (use search_course_docs)\n" "When a user asks about course materials, use the search_course_docs tool.\n"
"or from course metadata (use fetch_course_meta).\n" "When a user asks about schedule, metadata, or other nonmaterial info, use fetch_course_meta.\n"
"Do not call both tools unless absolutely necessary.\n" "Do not call both tools unless absolutely necessary.\n"
"In your final answer, prepend 'source: chroma' or 'source: mcp_meta' to indicate the origin." "In your final answer, prepend 'source: chroma' if you used search_course_docs,\n"
"or 'source: mcp_meta' if you used fetch_course_meta."
), ),
) )
# ----------------- CLI ----------------- # --- CLI ---
PRESET_QUESTIONS = [ PRESET_QUESTIONS = [
"What topics are covered in the first lecture?", # should hit chroma "What topics are covered in the first lecture?",
"Who is the instructor for this course?", # should hit mcp_meta "How can I access the lecture slides?",
"When is the next class?", # should hit chroma (or meta if schedule) "What is the schedule for the next week?",
] ]
async def run_question(question: str): async def run_agent(question: str, thread_id: str = "session-1"):
result = await agent.ainvoke( result = await agent.ainvoke(
{"messages": ["HumanMessage(content=\"{}\")".format(question)]}, {"messages": [HumanMessage(content=question)]},
{"configurable": {"thread_id": "session-1"}}, {"configurable": {"thread_id": thread_id}},
) )
# The agent returns a dict with 'messages'; extract last content return result["messages"][-1].content
content = result["messages"][-1].content
print(f"\nQ: {question}\nA: {content}\n")
async def interactive():
print("Enter a question (or 'exit' to quit):")
while True:
q = input("> ")
if q.lower() in {"exit", "quit"}:
break
await run_question(q)
async def main(): async def main():
print("Running preset questions...") # Ensure the vector store is populated
for q in PRESET_QUESTIONS: load_faq_to_qdrant()
await run_question(q)
await interactive() print("\n--- FAQ Bot Demo ---\n")
for i, q in enumerate(PRESET_QUESTIONS, 1):
print(f"Q{i}: {q}")
answer = await run_agent(q, thread_id=f"demo-{i}")
print(f"A{i}: {answer}\n")
# Interactive mode
print("Enter your own questions (type 'exit' to quit):")
while True:
user_q = input("> ")
if user_q.lower() in {"exit", "quit"}:
break
answer = await run_agent(user_q, thread_id="interactive")
print(answer)
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())