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

This commit is contained in:
+86 -100
View File
@@ -1,142 +1,128 @@
import os import os
import asyncio import asyncio
import json
import httpx
from pathlib import Path from pathlib import Path
from langchain_community.embeddings import OllamaEmbeddings from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_chroma import Chroma from langchain_chroma import Chroma
from langchain_core.documents import Document from langchain_core.documents import Document
from langchain_openai import ChatOpenAI
from langchain.tools import tool from langchain.tools import tool
from deepagents import create_deep_agent from langchain.agents import AgentExecutor, create_openai_tools_agent
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend from langchain.agents import Tool
from langchain_core.messages import HumanMessage from langchain_community.utilities import RetrievalQA
from langchain_community.vectorstores import Chroma as ChromaStore
# --------------------------- # ---------- Configuration ----------
# 1. Embeddings & Chroma setup OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# --------------------------- if not OPENAI_API_KEY:
# Using OllamaEmbeddings with nomic-embed-text as required by the "Исправить" section. raise RuntimeError("OPENAI_API_KEY not set in environment")
# The embeddings are used for both loading the FAQ and for the search tool.
embeddings = OllamaEmbeddings(model="nomic-embed-text")
# Persistent Chroma collection for the FAQ knowledge base. # ---------- Embeddings & Vector Store ----------
vector_store = Chroma( embeddings = OpenAIEmbeddings(
collection_name="faq_collection", model="text-embedding-3-small",
embedding_function=embeddings, base_url="https://openrouter.ai/api/v1",
persist_directory="./chroma_faq" api_key=OPENAI_API_KEY,
) )
# --------------------------- vector_store = ChromaStore(
# 2. Load FAQ markdown files into Chroma collection_name="faq_collection",
# --------------------------- embedding_function=embeddings,
persist_directory="./chroma_faq",
)
# ---------- Load FAQ into Chroma ----------
def load_faq_to_chroma(data_dir: str = "data"): def load_faq_to_chroma(data_dir: str = "data"):
"""Load all .md files from *data_dir* into the persistent Chroma collection. """Load all .md files from data_dir into the Chroma vector store.
Each file is split into documents with a simple linebased splitter. The function clears the existing collection before loading.
""" """
data_path = Path(data_dir) vector_store.delete_collection()
if not data_path.exists():
raise FileNotFoundError(f"Data directory {data_dir} not found")
docs = [] docs = []
for md_file in data_path.glob("*.md"): for md_file in Path(data_dir).glob("*.md"):
text = md_file.read_text(encoding="utf-8") text = md_file.read_text(encoding="utf-8")
# Simple split by double newlines to create chunks docs.append(Document(page_content=text, metadata={"source": md_file.name}))
for i, chunk in enumerate(text.split("\n\n")):
docs.append(Document(page_content=chunk, metadata={"source": md_file.name, "chunk": i}))
vector_store.add_documents(docs) vector_store.add_documents(docs)
vector_store.persist() vector_store.persist()
# --------------------------- # ---------- Tools ----------
# 3. Tools
# ---------------------------
@tool @tool
def search_course_docs(query: str, k: int = 3) -> str: def search_course_docs(query: str, k: int = 3) -> str:
"""Search the FAQ knowledge base for relevant information.""" """Search the local FAQ collection for relevant passages."""
docs = vector_store.similarity_search(query, k=k) docs = vector_store.similarity_search(query, k=k)
if not docs: if not docs:
return "No relevant information found in the FAQ." return "No relevant information found in the course materials."
return "\n\n---\n\n".join(f"**{doc.metadata.get('source')}** (chunk {doc.metadata.get('chunk')}):\n{doc.page_content}" for doc in docs) return "\n\n---\n\n".join([f"{doc.metadata.get('source', 'unknown')}\n{doc.page_content}" for doc in docs])
@tool @tool
def fetch_course_meta(query: str) -> str: def fetch_course_meta(query: str) -> str:
"""Mock MCPstyle tool that returns course metadata. """MCPstyle tool that queries a local mock server for course metadata.
In production this would perform an HTTP GET to an MCP server. The mock server should serve a JSON file at http://localhost:8000/meta.json.
Here we simply return a static JSON string based on the query.
""" """
# Simple static mapping for demo purposes url = "http://localhost:8000/meta.json"
meta = { try:
"schedule": "Monday 10:00-12:00, Wednesday 14:00-16:00", response = httpx.get(url, timeout=5.0)
"instructor": "Dr. Ivanov", response.raise_for_status()
"credits": "3" data = response.json()
} except Exception as e:
key = query.lower().strip() return f"Error fetching metadata: {e}"
return meta.get(key, f"No metadata found for '{query}'.") # Simple lookup: return value if query matches a key (caseinsensitive)
key = query.strip().lower()
value = data.get(key)
if value is None:
return f"No metadata entry found for '{query}'."
return f"{key}: {value}"
# --------------------------- # ---------- Agent Setup ----------
# 4. Agent setup with deepagents
# ---------------------------
# LLM via OpenRouter as per course requirement
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,
) )
backend = CompositeBackend([ # Define the system prompt with routing rule
LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(),
])
# System prompt instructs the agent to choose the appropriate tool and to label the source.
system_prompt = ( system_prompt = (
"You are a helpful FAQ assistant.\n" "You are a helpful assistant that answers questions about the course. "
"When a user asks a question about course materials, use the tool `search_course_docs`.\n" "If the question is about course content, use the search_course_docs tool. "
"When a user asks about schedule, instructor, or credits, use the tool `fetch_course_meta`.\n" "If the question is about schedule, metadata, or other noncontent info, "
"Do not call both tools unless necessary.\n" "use the fetch_course_meta tool. Do not call both tools unless the question "
"In your final answer, prepend the source label: `source: chroma` or `source: mcp_meta`." "explicitly requires both. In your final answer, prepend 'source: chroma' "
"or 'source: mcp_meta' to indicate which tool provided the information."
) )
agent = create_deep_agent( # Create Tool objects
model=llm, search_tool = Tool(name="search_course_docs", func=search_course_docs, description="Search local course documents.")
tools=[search_course_docs, fetch_course_meta], meta_tool = Tool(name="fetch_course_meta", func=fetch_course_meta, description="Fetch course metadata from MCP mock server.")
backend=backend,
system_prompt=system_prompt,
)
# --------------------------- # Build the agent executor
# 5. CLI agent = create_openai_tools_agent(llm=llm, tools=[search_tool, meta_tool], system_message=system_prompt)
# --------------------------- agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=[search_tool, meta_tool], verbose=True)
PRESET_QUESTIONS = [
"What topics are covered in the first lecture?",
"Who is the instructor for this course?",
"When is the next class?"
]
async def run_agent(question: str, thread_id: str = "session-1"): # ---------- CLI ----------
result = await agent.ainvoke( async def run_cli():
{"messages": [HumanMessage(content=question)]}, # Preload data if not already present
{"configurable": {"thread_id": thread_id}}, if not Path("./chroma_faq").exists():
) load_faq_to_chroma()
# The last message is the agent's response
return result["messages"][-1].content
async def main(): # Predefined questions
# Ensure FAQ is loaded predefined = [
load_faq_to_chroma() "What is the main topic of the first lecture?",
"Explain the concept of polymorphism in the course.",
"What is the schedule for the next week?",
]
print("--- Predefined questions ---")
for i, q in enumerate(predefined, 1):
print(f"{i}. {q}")
print("\nEnter a number to ask a predefined question or type your own query.")
user_input = input("> ")
if user_input.isdigit() and 1 <= int(user_input) <= len(predefined):
query = predefined[int(user_input)-1]
else:
query = user_input
print("--- FAQ Bot Demo ---\n") result = await agent_executor.ainvoke({"input": query})
for i, q in enumerate(PRESET_QUESTIONS, 1): print("\n--- Answer ---")
print(f"Q{i}: {q}") print(result["output"])
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_input = input("> ")
if user_input.lower() in {"exit", "quit"}:
break
answer = await run_agent(user_input, thread_id="interactive")
print(answer)
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(run_cli())