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

This commit is contained in:
+125 -101
View File
@@ -1,78 +1,22 @@
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
from langchain_core.documents import Document from langchain_core.documents import Document
from langchain.tools import tool from langchain.tools import tool
from langchain.agents import AgentExecutor, create_openai_tools_agent from deepagents import create_deep_agent
from langchain.agents import Tool from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
from langchain_community.utilities import RetrievalQA from langchain_core.messages import HumanMessage
from langchain_community.vectorstores import Chroma as ChromaStore
# ---------- Configuration ---------- # ---------------------------
# Configuration
# ---------------------------
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY: if not OPENAI_API_KEY:
raise RuntimeError("OPENAI_API_KEY not set in environment") raise RuntimeError("OPENAI_API_KEY not set in environment")
# ---------- Embeddings & Vector Store ---------- # LLM via OpenRouter
embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
base_url="https://openrouter.ai/api/v1",
api_key=OPENAI_API_KEY,
)
vector_store = ChromaStore(
collection_name="faq_collection",
embedding_function=embeddings,
persist_directory="./chroma_faq",
)
# ---------- Load FAQ into Chroma ----------
def load_faq_to_chroma(data_dir: str = "data"):
"""Load all .md files from data_dir into the Chroma vector store.
The function clears the existing collection before loading.
"""
vector_store.delete_collection()
docs = []
for md_file in Path(data_dir).glob("*.md"):
text = md_file.read_text(encoding="utf-8")
docs.append(Document(page_content=text, metadata={"source": md_file.name}))
vector_store.add_documents(docs)
vector_store.persist()
# ---------- Tools ----------
@tool
def search_course_docs(query: str, k: int = 3) -> str:
"""Search the local FAQ collection for relevant passages."""
docs = vector_store.similarity_search(query, k=k)
if not docs:
return "No relevant information found in the course materials."
return "\n\n---\n\n".join([f"{doc.metadata.get('source', 'unknown')}\n{doc.page_content}" for doc in docs])
@tool
def fetch_course_meta(query: str) -> str:
"""MCPstyle tool that queries a local mock server for course metadata.
The mock server should serve a JSON file at http://localhost:8000/meta.json.
"""
url = "http://localhost:8000/meta.json"
try:
response = httpx.get(url, timeout=5.0)
response.raise_for_status()
data = response.json()
except Exception as e:
return f"Error fetching metadata: {e}"
# 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 ----------
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",
@@ -80,49 +24,129 @@ llm = ChatOpenAI(
temperature=0.0, temperature=0.0,
) )
# Define the system prompt with routing rule # Embeddings via OpenRouter
system_prompt = ( embeddings = OpenAIEmbeddings(
"You are a helpful assistant that answers questions about the course. " model="text-embedding-3-small",
"If the question is about course content, use the search_course_docs tool. " base_url="https://openrouter.ai/api/v1",
"If the question is about schedule, metadata, or other noncontent info, " api_key=OPENAI_API_KEY,
"use the fetch_course_meta tool. Do not call both tools unless the question "
"explicitly requires both. In your final answer, prepend 'source: chroma' "
"or 'source: mcp_meta' to indicate which tool provided the information."
) )
# Create Tool objects # Chroma vector store (persisted)
search_tool = Tool(name="search_course_docs", func=search_course_docs, description="Search local course documents.") CHROMA_PATH = Path("./chroma_faq")
meta_tool = Tool(name="fetch_course_meta", func=fetch_course_meta, description="Fetch course metadata from MCP mock server.") vector_store = Chroma(
collection_name="faq_collection",
embedding_function=embeddings,
persist_directory=str(CHROMA_PATH),
)
# Build the agent executor # ---------------------------
agent = create_openai_tools_agent(llm=llm, tools=[search_tool, meta_tool], system_message=system_prompt) # Data loading
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=[search_tool, meta_tool], verbose=True) # ---------------------------
# ---------- CLI ---------- def load_faq_to_chroma(md_folder: str = "data"):
async def run_cli(): """Load all .md files from md_folder into ChromaDB.
# Preload data if not already present Each file is split into chunks and added to the vector store.
if not Path("./chroma_faq").exists(): """
load_faq_to_chroma() md_path = Path(md_folder)
if not md_path.exists():
# Predefined questions raise FileNotFoundError(f"Markdown folder {md_folder} not found")
predefined = [ docs = []
"What is the main topic of the first lecture?", for md_file in md_path.glob("*.md"):
"Explain the concept of polymorphism in the course.", text = md_file.read_text(encoding="utf-8")
"What is the schedule for the next week?", # Simple chunking: split by double newlines
] chunks = [c.strip() for c in text.split("\n\n") if c.strip()]
print("--- Predefined questions ---") for i, chunk in enumerate(chunks):
for i, q in enumerate(predefined, 1): docs.append(Document(page_content=chunk, metadata={"source": md_file.name, "chunk": i}))
print(f"{i}. {q}") if docs:
print("\nEnter a number to ask a predefined question or type your own query.") vector_store.add_documents(docs)
user_input = input("> ") vector_store.persist()
if user_input.isdigit() and 1 <= int(user_input) <= len(predefined):
query = predefined[int(user_input)-1]
else: else:
query = user_input print("No markdown files found to load.")
result = await agent_executor.ainvoke({"input": query}) # ---------------------------
print("\n--- Answer ---") # Tools
print(result["output"]) # ---------------------------
@tool
def search_course_docs(query: str, k: int = 3) -> str:
"""Search the FAQ knowledge base for relevant information."""
docs = vector_store.similarity_search(query, k=k)
if not docs:
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)
@tool
def fetch_course_meta(query: str) -> str:
"""Mock MCP-style tool that returns course metadata.
In production this would perform an HTTP GET to an MCP server.
Here we return a static JSON-like string for simplicity.
"""
# Static mock data
meta = {
"schedule": {
"Monday": "Lecture 1: Introduction",
"Wednesday": "Lecture 2: Advanced Topics",
"Friday": "Lab Session"
},
"instructor": "Dr. Jane Doe",
"credits": 3
}
return f"Course metadata: {meta}"
# ---------------------------
# Backend setup
# ---------------------------
backend = CompositeBackend([
LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(),
])
# ---------------------------
# Agent creation
# ---------------------------
agent = create_deep_agent(
model=llm,
tools=[search_course_docs, fetch_course_meta],
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 or metadata. In your answer, clearly indicate the source: either 'chroma' or 'mcp_meta'. Do not use both tools unless necessary.",
)
# ---------------------------
# CLI
# ---------------------------
PRESET_QUESTIONS = [
"What topics are covered in Lecture 1?", # should hit chroma
"Explain the concept of tokenization in NLP.", # chroma
"When is the next lab session?", # should hit mcp_meta
]
async def run_agent(question: str, thread_id: str = "session-1"):
result = await agent.ainvoke(
{"messages": [HumanMessage(content=question)]},
{"configurable": {"thread_id": thread_id}},
)
# The last message is the agent's reply
reply = result["messages"][-1].content
print(f"\nQ: {question}\nA: {reply}\n")
async def main():
# Load data if not already loaded
if not CHROMA_PATH.exists() or not any(CHROMA_PATH.iterdir()):
print("Loading FAQ data into Chroma...")
load_faq_to_chroma()
else:
print("Chroma database already loaded.")
# Run preset questions
for i, q in enumerate(PRESET_QUESTIONS, 1):
await run_agent(q, thread_id=f"preset-{i}")
# Interactive mode
print("Enter your own questions (type 'exit' to quit):")
while True:
user_input = input("> ")
if user_input.lower() in {"exit", "quit"}:
break
await run_agent(user_input, thread_id="interactive")
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(run_cli()) asyncio.run(main())