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

This commit is contained in:
+78 -55
View File
@@ -1,5 +1,7 @@
import os import os
import asyncio import asyncio
import json
import httpx
from pathlib import Path from pathlib import Path
from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_chroma import Chroma from langchain_chroma import Chroma
@@ -7,16 +9,20 @@ from langchain_core.documents import Document
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
from langchain_core.messages import HumanMessage
# ----------------- Configuration ----------------- # ---------------------------
# Load API key from .env or environment variable # Configuration
os.environ.setdefault("OPENAI_API_KEY", os.getenv("OPENAI_API_KEY", "")) # ---------------------------
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise RuntimeError("OPENAI_API_KEY not set in environment")
# LLM via OpenRouter # LLM via 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,
) )
@@ -24,97 +30,114 @@ llm = ChatOpenAI(
embeddings = OpenAIEmbeddings( embeddings = OpenAIEmbeddings(
model="text-embedding-3-small", model="text-embedding-3-small",
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,
) )
# ----------------- Chroma DB ----------------- # ---------------------------
CHROMA_PATH = Path("./chroma_faq") # Chroma DB utilities
CHROMA_COLLECTION = "faq_collection" # ---------------------------
CHROMA_DIR = Path("./chroma_faq")
CHROMA_DIR.mkdir(parents=True, exist_ok=True)
vector_store = Chroma( vector_store = Chroma(
collection_name=CHROMA_COLLECTION, collection_name="faq_collection",
persist_directory=str(CHROMA_DIR),
embedding_function=embeddings, embedding_function=embeddings,
persist_directory=str(CHROMA_PATH),
) )
# Load markdown files into Chroma (idempotent)
DATA_DIR = Path("./data") def load_faq_to_chroma(md_dir: str = "data"):
if not CHROMA_PATH.exists() or not any(CHROMA_PATH.iterdir()): """Load all .md files from md_dir into ChromaDB.
docs = [] Each file is split into chunks and added to the vector store.
for md_file in DATA_DIR.glob("*.md"): """
md_path = Path(md_dir)
if not md_path.exists():
raise FileNotFoundError(f"Markdown directory {md_dir} not found")
for md_file in md_path.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 chunking: split by double newlines
chunks = [c.strip() for c in text.split("\n\n") if c.strip()]
docs = [Document(page_content=c, metadata={"source": md_file.name}) for c in chunks]
vector_store.add_documents(docs) vector_store.add_documents(docs)
vector_store.persist() vector_store.persist()
# ----------------- 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 ChromaDB for relevant passages."""
results = vector_store.similarity_search(query, k=3) docs = vector_store.similarity_search(query, k=k)
if not results: if not docs:
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(f"{d.metadata.get('source', 'unknown')}\n{d.page_content}" for d in docs)
@tool @tool
def fetch_course_meta(query: str) -> str: def fetch_course_meta(query: str) -> str:
"""Mock MCP-style tool that returns course metadata. """Mock MCP-style tool that fetches course metadata from a local JSON file.
In production this would be an HTTP call to an MCP server. In production this would be an HTTP call to an MCP server.
Here we return a static JSON-like string based on the query.
""" """
meta = { # For simplicity, we use a local JSON file. In a real scenario, replace with httpx.get.
"schedule": "Mon 10-12, Wed 14-16, Fri 9-11", meta_path = Path("course_meta.json")
"instructor": "Dr. Ivanov", if not meta_path.exists():
"credits": 3, return "Course metadata not available."
} data = json.loads(meta_path.read_text(encoding="utf-8"))
# Simple keyword matching # Very naive search: return any entry where query is a substring of title or description
if "schedule" in query.lower(): results = [f"{item['title']}: {item['description']}" for item in data if query.lower() in item.get('title', '').lower() or query.lower() in item.get('description', '').lower()]
return f"Course schedule: {meta['schedule']}" return "\n".join(results) if results else "No matching metadata found."
if "instructor" in query.lower():
return f"Instructor: {meta['instructor']}"
if "credits" in query.lower():
return f"Credits: {meta['credits']}"
return "No metadata matches your query."
# ----------------- 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="You are a helpful FAQ bot for the course. Use the search_course_docs tool for questions about lecture materials and fetch_course_meta for questions about schedule, instructor, or credits. Do not use both tools unless necessary. In your final answer, prefix the source with 'source: chroma' or 'source: mcp_meta'.", system_prompt=(
"You are a helpful FAQ bot for the course.\n"
"When a user asks about course content, use the search_course_docs tool.\n"
"When a user asks about schedule, metadata, or other non-content info, use fetch_course_meta.\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."
),
) )
# ----------------- CLI ----------------- # ---------------------------
# CLI
# ---------------------------
PRESET_QUESTIONS = [ PRESET_QUESTIONS = [
"What topics are covered in lecture 3?", "What is the deadline for the final project?", # likely in metadata
"When is the next class?", "Explain the concept of tokenization in NLP.", # content
"Who is the instructor for this course?", "How many lectures are there in the first module?", # content
] ]
async def run_agent(question: str, thread_id: str = "session-1"): 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": thread_id}}, {"configurable": {"thread_id": thread_id}},
) )
# The agent returns a dict with 'messages'; extract last content # The last message is the agent's reply
content = result["messages"][-1].content reply = result["messages"][-1].content
print(f"\nQ: {question}\nA: {content}\n") print(f"\nQ: {question}\nA: {reply}\n")
async def main(): async def main():
print("--- FAQ Bot Demo ---") # Load data into Chroma if not already persisted
for i, q in enumerate(PRESET_QUESTIONS, 1): if not CHROMA_DIR.exists() or not any(CHROMA_DIR.iterdir()):
await run_agent(q, thread_id=f"demo-{i}") print("Loading FAQ data into ChromaDB...")
print("Enter your own question (or 'exit' to quit):") load_faq_to_chroma()
print("\n--- Predefined questions ---")
for q in PRESET_QUESTIONS:
await run_agent(q)
print("\n--- Interactive mode (type 'exit' to quit) ---")
while True: while True:
q = input("> ") user_input = input("You: ")
if q.lower() in {"exit", "quit"}: if user_input.lower() in {"exit", "quit"}:
break break
await run_agent(q, thread_id="interactive") await run_agent(user_input)
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())