Solution published: update src/agent.py
This commit is contained in:
+46
-39
@@ -1,57 +1,64 @@
|
|||||||
import argparse
|
import os
|
||||||
from langchain.agents.openai_functions import create_openai_functions_agent
|
from typing import Dict
|
||||||
from langchain.agents import AgentExecutor
|
|
||||||
from langchain_core.prompts import ChatPromptTemplate
|
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
||||||
from langchain_ollama import Ollama
|
from langchain_ollama import Ollama
|
||||||
from src.utils import load_faq_to_chroma, search_course_docs, fetch_course_meta
|
from langchain_core.prompts import ChatPromptTemplate
|
||||||
|
from langchain_core.messages import HumanMessage
|
||||||
|
|
||||||
# Initialize embeddings and LLM
|
from src.utils import search_course_docs
|
||||||
llm = Ollama(model="llama3.1")
|
from src.mcp_tool import fetch_course_meta
|
||||||
|
|
||||||
# Load or create Chroma collection
|
|
||||||
try:
|
|
||||||
chroma = load_faq_to_chroma()
|
|
||||||
except Exception:
|
|
||||||
chroma = None
|
|
||||||
|
|
||||||
# Define tools
|
# Define tools
|
||||||
from langchain.tools import tool
|
|
||||||
|
|
||||||
@tool
|
def chroma_tool(query: str):
|
||||||
def search_course_docs_tool(query: str, k: int = 3) -> str:
|
return search_course_docs(query)
|
||||||
"""Search local FAQ docs in ChromaDB."""
|
|
||||||
docs = search_course_docs(query, k)
|
|
||||||
return "\n".join([doc.page_content for doc in docs])
|
|
||||||
|
|
||||||
@tool
|
# Wrap MCP tool
|
||||||
def fetch_course_meta_tool(query: str) -> str:
|
|
||||||
"""Fetch course metadata via MCP-style tool."""
|
|
||||||
results = fetch_course_meta(query)
|
|
||||||
return str(results)
|
|
||||||
|
|
||||||
tools = [search_course_docs_tool, fetch_course_meta_tool]
|
def mcp_tool(query: str):
|
||||||
|
return fetch_course_meta(query)
|
||||||
|
|
||||||
# Prompt template with source hint
|
# Simple tool registry
|
||||||
prompt = ChatPromptTemplate.from_messages([
|
TOOL_DEFINITIONS = {
|
||||||
("system", "You are a helpful FAQ assistant. Use the tools only when necessary. In your answer, include a line like 'source: chroma' or 'source: mcp_meta' to indicate which tool was used.")
|
"search_course_docs": {
|
||||||
|
"func": chroma_tool,
|
||||||
|
"description": "Search FAQ documents in Chroma. Use when question about course content.",
|
||||||
|
},
|
||||||
|
"fetch_course_meta": {
|
||||||
|
"func": mcp_tool,
|
||||||
|
"description": "Get course metadata such as schedule. Use when question about schedule or instructor.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prompt template
|
||||||
|
SYSTEM_PROMPT = """You are a FAQ bot for the course. Use only the tools provided. Do not call both tools unless necessary. Indicate source in your answer: 'source: chroma' or 'source: mcp_meta'."""
|
||||||
|
|
||||||
|
PROMPT = ChatPromptTemplate.from_messages([
|
||||||
|
("system", SYSTEM_PROMPT),
|
||||||
|
("human", "{input}"),
|
||||||
])
|
])
|
||||||
|
|
||||||
agent = create_openai_functions_agent(llm=llm, tools=tools, prompt=prompt)
|
# Create agent
|
||||||
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
llm = Ollama(model="llama2")
|
||||||
|
agent = create_openai_tools_agent(llm, TOOL_DEFINITIONS, PROMPT)
|
||||||
|
executor = AgentExecutor(agent=agent, tools=list(TOOL_DEFINITIONS.values()), verbose=True)
|
||||||
|
|
||||||
|
# CLI entry point
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
import argparse
|
||||||
parser = argparse.ArgumentParser(description="FAQ bot CLI")
|
parser = argparse.ArgumentParser(description="FAQ bot CLI")
|
||||||
parser.add_argument("--question", type=str, help="Question to ask the bot")
|
parser.add_argument("--question", type=str, help="Question to ask the bot")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
if args.question:
|
if args.question:
|
||||||
response = executor.invoke({"input": args.question})
|
result = executor.invoke({"input": args.question})
|
||||||
print(response["output"])
|
print(result["output"])
|
||||||
else:
|
else:
|
||||||
# Interactive mode
|
print("Enter questions (Ctrl-D to exit):")
|
||||||
print("FAQ Bot. Type 'exit' to quit.")
|
try:
|
||||||
while True:
|
while True:
|
||||||
q = input("> ")
|
q = input("Q: ")
|
||||||
if q.lower() in ("exit", "quit"):
|
res = executor.invoke({"input": q})
|
||||||
break
|
print("A:", res["output"])
|
||||||
resp = executor.invoke({"input": q})
|
except EOFError:
|
||||||
print(resp["output"])
|
pass
|
||||||
|
|||||||
Reference in New Issue
Block a user