Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,222 +1,279 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
from dotenv import load_dotenv
|
| 3 |
from langgraph.graph import START, StateGraph, MessagesState
|
| 4 |
from langgraph.prebuilt import tools_condition
|
| 5 |
from langgraph.prebuilt import ToolNode
|
| 6 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 7 |
-
from langchain_groq import ChatGroq
|
| 8 |
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
|
| 9 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 10 |
-
from langchain_community.document_loaders import WikipediaLoader
|
| 11 |
-
from langchain_community.
|
| 12 |
-
from langchain_community.vectorstores import SupabaseVectorStore
|
| 13 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 14 |
from langchain_core.tools import tool
|
| 15 |
from langchain.tools.retriever import create_retriever_tool
|
| 16 |
-
from
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
load_dotenv()
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
@tool
|
| 21 |
-
def
|
| 22 |
-
"""Multiply two
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
return
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
return
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
return
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
return
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
return
|
| 84 |
-
|
| 85 |
-
@tool
|
| 86 |
-
def
|
| 87 |
-
"""
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
)
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
tools = [
|
| 142 |
-
multiply,
|
| 143 |
-
add,
|
| 144 |
-
subtract,
|
| 145 |
-
divide,
|
| 146 |
-
modulus,
|
| 147 |
-
wiki_search,
|
| 148 |
-
web_search,
|
| 149 |
-
arvix_search,
|
| 150 |
-
]
|
| 151 |
-
|
| 152 |
-
# Build graph function
|
| 153 |
-
def build_graph(provider: str = "google"):
|
| 154 |
-
"""Build the graph"""
|
| 155 |
-
# Load environment variables from .env file
|
| 156 |
-
if provider == "google":
|
| 157 |
-
# Google Gemini
|
| 158 |
-
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
|
| 159 |
-
elif provider == "groq":
|
| 160 |
-
# Groq https://console.groq.com/docs/models
|
| 161 |
-
llm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it
|
| 162 |
-
elif provider == "huggingface":
|
| 163 |
-
# TODO: Add huggingface endpoint
|
| 164 |
-
llm = ChatHuggingFace(
|
| 165 |
-
llm=HuggingFaceEndpoint(
|
| 166 |
-
url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
|
| 167 |
-
temperature=0,
|
| 168 |
-
),
|
| 169 |
-
)
|
| 170 |
-
else:
|
| 171 |
-
raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
|
| 172 |
-
# Bind tools to LLM
|
| 173 |
-
llm_with_tools = llm.bind_tools(tools)
|
| 174 |
-
|
| 175 |
-
# Node
|
| 176 |
-
def assistant(state: MessagesState):
|
| 177 |
-
"""Assistant node"""
|
| 178 |
-
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
| 179 |
-
|
| 180 |
-
# def retriever(state: MessagesState):
|
| 181 |
-
# """Retriever node"""
|
| 182 |
-
# similar_question = vector_store.similarity_search(state["messages"][0].content)
|
| 183 |
-
#example_msg = HumanMessage(
|
| 184 |
-
# content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
|
| 185 |
-
# )
|
| 186 |
-
# return {"messages": [sys_msg] + state["messages"] + [example_msg]}
|
| 187 |
-
|
| 188 |
-
from langchain_core.messages import AIMessage
|
| 189 |
-
|
| 190 |
-
def retriever(state: MessagesState):
|
| 191 |
-
query = state["messages"][-1].content
|
| 192 |
-
similar_doc = vector_store.similarity_search(query, k=1)[0]
|
| 193 |
-
|
| 194 |
-
content = similar_doc.page_content
|
| 195 |
-
if "Final answer :" in content:
|
| 196 |
-
answer = content.split("Final answer :")[-1].strip()
|
| 197 |
-
else:
|
| 198 |
-
answer = content.strip()
|
| 199 |
-
|
| 200 |
-
return {"messages": [AIMessage(content=answer)]}
|
| 201 |
-
|
| 202 |
-
# builder = StateGraph(MessagesState)
|
| 203 |
-
#builder.add_node("retriever", retriever)
|
| 204 |
-
#builder.add_node("assistant", assistant)
|
| 205 |
-
#builder.add_node("tools", ToolNode(tools))
|
| 206 |
-
#builder.add_edge(START, "retriever")
|
| 207 |
-
#builder.add_edge("retriever", "assistant")
|
| 208 |
-
#builder.add_conditional_edges(
|
| 209 |
-
# "assistant",
|
| 210 |
-
# tools_condition,
|
| 211 |
-
#)
|
| 212 |
-
#builder.add_edge("tools", "assistant")
|
| 213 |
-
|
| 214 |
-
builder = StateGraph(MessagesState)
|
| 215 |
-
builder.add_node("retriever", retriever)
|
| 216 |
-
|
| 217 |
-
# Retriever ist Start und Endpunkt
|
| 218 |
-
builder.set_entry_point("retriever")
|
| 219 |
-
builder.set_finish_point("retriever")
|
| 220 |
-
|
| 221 |
-
# Compile graph
|
| 222 |
-
return builder.compile()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import certifi
|
| 3 |
+
os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
from langgraph.graph import START, StateGraph, MessagesState
|
| 6 |
from langgraph.prebuilt import tools_condition
|
| 7 |
from langgraph.prebuilt import ToolNode
|
|
|
|
|
|
|
| 8 |
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
|
| 9 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 10 |
+
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
| 11 |
+
from langchain_community.vectorstores import Chroma
|
|
|
|
| 12 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 13 |
from langchain_core.tools import tool
|
| 14 |
from langchain.tools.retriever import create_retriever_tool
|
| 15 |
+
from langchain_core.documents import Document
|
| 16 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 17 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 18 |
+
from langchain_groq import ChatGroq
|
| 19 |
|
| 20 |
load_dotenv()
|
| 21 |
|
| 22 |
+
|
| 23 |
+
# ---------------- CONFIGURATION ----------------
|
| 24 |
+
# Change this to any valid Hugging Face model endpoint (e.g., meta-llama/Llama-3-8b-chat-hf)
|
| 25 |
+
HF_MODEL_NAME = os.getenv("LLAMA_MODEL_NAME", "meta-llama/Meta-Llama-3-8B-Instruct")
|
| 26 |
+
HF_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 27 |
+
HF_MODEL_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL_NAME}"
|
| 28 |
+
# Use the OpenAI-compatible inference endpoint
|
| 29 |
+
HF_OPENAI_URL = "https://api-inference.huggingface.co/openai"
|
| 30 |
+
# ---------------- UTILITY TOOLS ----------------
|
| 31 |
@tool
|
| 32 |
+
def multiply_numbers(x: int, y: int) -> int:
|
| 33 |
+
"""Multiply two integers and return the result."""
|
| 34 |
+
return x * y
|
| 35 |
+
|
| 36 |
+
@tool
|
| 37 |
+
def add_numbers(x: int, y: int) -> int:
|
| 38 |
+
"""Add two integers and return the sum."""
|
| 39 |
+
return x + y
|
| 40 |
+
|
| 41 |
+
@tool
|
| 42 |
+
def subtract_numbers(x: int, y: int) -> int:
|
| 43 |
+
"""Subtract the second integer from the first and return the result."""
|
| 44 |
+
return x - y
|
| 45 |
+
|
| 46 |
+
@tool
|
| 47 |
+
def divide_numbers(x: int, y: int) -> float:
|
| 48 |
+
"""Divide the first number by the second and return the result. Raises an error on division by zero."""
|
| 49 |
+
if y == 0:
|
| 50 |
+
raise ValueError("Division by zero is not allowed.")
|
| 51 |
+
return x / y
|
| 52 |
+
|
| 53 |
+
@tool
|
| 54 |
+
def modulus_numbers(x: int, y: int) -> int:
|
| 55 |
+
"""Return the remainder when the first number is divided by the second."""
|
| 56 |
+
return x % y
|
| 57 |
+
|
| 58 |
+
@tool
|
| 59 |
+
def power_numbers(base: float, exponent: float) -> float:
|
| 60 |
+
"""Raise the base to the power of exponent and return the result."""
|
| 61 |
+
return base ** exponent
|
| 62 |
+
|
| 63 |
+
@tool
|
| 64 |
+
def root_number(value: float, n: float) -> float:
|
| 65 |
+
"""Compute the nth root of a value and return the result."""
|
| 66 |
+
return value ** (1 / n)
|
| 67 |
+
|
| 68 |
+
@tool
|
| 69 |
+
def wiki_lookup(query: str) -> str:
|
| 70 |
+
"""Search Wikipedia for the query and return up to 2 summarized documents."""
|
| 71 |
+
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
| 72 |
+
return "\n\n---\n\n".join(
|
| 73 |
+
f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
@tool
|
| 77 |
+
def web_lookup(query: str) -> str:
|
| 78 |
+
"""Search the web using Tavily and return up to 3 summarized results."""
|
| 79 |
+
docs = TavilySearchResults(max_results=3).invoke(query=query)
|
| 80 |
+
return "\n\n---\n\n".join(
|
| 81 |
+
f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
@tool
|
| 85 |
+
def arxiv_lookup(query: str) -> str:
|
| 86 |
+
"""Search arXiv for the query and return summaries of up to 3 papers."""
|
| 87 |
+
docs = ArxivLoader(query=query, load_max_docs=3).load()
|
| 88 |
+
return "\n\n---\n\n".join(
|
| 89 |
+
f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content[:800]}</Document>' for d in docs
|
| 90 |
+
)
|
| 91 |
+
@tool
|
| 92 |
+
def add_numbers(x: int, y: int) -> int:
|
| 93 |
+
"""Add two integers and return the sum."""
|
| 94 |
+
return x + y
|
| 95 |
+
|
| 96 |
+
@tool
|
| 97 |
+
def subtract_numbers(x: int, y: int) -> int:
|
| 98 |
+
"""Subtract the second integer from the first and return the result."""
|
| 99 |
+
return x - y
|
| 100 |
+
|
| 101 |
+
@tool
|
| 102 |
+
def divide_numbers(x: int, y: int) -> float:
|
| 103 |
+
"""Divide the first number by the second and return the result. Raises an error on division by zero."""
|
| 104 |
+
if y == 0:
|
| 105 |
+
raise ValueError("Division by zero is not allowed.")
|
| 106 |
+
return x / y
|
| 107 |
+
|
| 108 |
+
@tool
|
| 109 |
+
def modulus_numbers(x: int, y: int) -> int:
|
| 110 |
+
"""Return the remainder when the first number is divided by the second."""
|
| 111 |
+
return x % y
|
| 112 |
+
|
| 113 |
+
@tool
|
| 114 |
+
def power_numbers(base: float, exponent: float) -> float:
|
| 115 |
+
"""Raise the base to the power of exponent and return the result."""
|
| 116 |
+
return base ** exponent
|
| 117 |
+
|
| 118 |
+
@tool
|
| 119 |
+
def root_number(value: float, n: float) -> float:
|
| 120 |
+
"""Compute the nth root of a value and return the result."""
|
| 121 |
+
return value ** (1 / n)
|
| 122 |
+
|
| 123 |
+
@tool
|
| 124 |
+
def wiki_lookup(query: str) -> str:
|
| 125 |
+
"""Search Wikipedia for the query and return up to 2 summarized documents."""
|
| 126 |
+
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
| 127 |
+
return "\n\n---\n\n".join(
|
| 128 |
+
f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
@tool
|
| 132 |
+
def web_lookup(query: str) -> str:
|
| 133 |
+
"""Search the web using Tavily and return up to 3 summarized results."""
|
| 134 |
+
docs = TavilySearchResults(max_results=3).invoke(query=query)
|
| 135 |
+
return "\n\n---\n\n".join(
|
| 136 |
+
f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
@tool
|
| 140 |
+
def arxiv_lookup(query: str) -> str:
|
| 141 |
+
"""Search arXiv for the query and return summaries of up to 3 papers."""
|
| 142 |
+
docs = ArxivLoader(query=query, load_max_docs=3).load()
|
| 143 |
+
return "\n\n---\n\n".join(
|
| 144 |
+
f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content[:800]}</Document>' for d in docs
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# # ---------------- SETUP LOCAL VECTORSTORE ----------------
|
| 148 |
+
# embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
| 149 |
+
# text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
|
| 150 |
+
# sample_docs = [Document(page_content="St. Thomas Aquinas was a medieval Catholic priest and philosopher.", metadata={"source": "wiki", "page": "St. Thomas Aquinas"})]
|
| 151 |
+
# split_docs = text_splitter.split_documents(sample_docs)
|
| 152 |
+
# vector_db = Chroma.from_documents(documents=split_docs, embedding=embedding_model)
|
| 153 |
+
# retriever_tool = create_retriever_tool(
|
| 154 |
+
# retriever=vector_db.as_retriever(),
|
| 155 |
+
# name="SimilarQuestionFinder",
|
| 156 |
+
# description="Retrieve similar questions and examples from vector DB."
|
| 157 |
+
# )
|
| 158 |
+
|
| 159 |
+
# # ---------------- SYSTEM PROMPT ----------------
|
| 160 |
+
# with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
| 161 |
+
# system_content = f.read()
|
| 162 |
+
# system_message = SystemMessage(content=system_content)
|
| 163 |
+
|
| 164 |
+
# # ---------------- BUILD STATE GRAPH ----------------
|
| 165 |
+
# def construct_agent_graph():
|
| 166 |
+
# llama_llm = ChatHuggingFace(
|
| 167 |
+
# llm=HuggingFaceEndpoint(
|
| 168 |
+
# endpoint_url=HF_OPENAI_URL,
|
| 169 |
+
# temperature=0
|
| 170 |
+
# )
|
| 171 |
+
# ).bind_tools([
|
| 172 |
+
# multiply_numbers,
|
| 173 |
+
# add_numbers,
|
| 174 |
+
# subtract_numbers,
|
| 175 |
+
# divide_numbers,
|
| 176 |
+
# modulus_numbers,
|
| 177 |
+
# power_numbers,
|
| 178 |
+
# root_number,
|
| 179 |
+
# wiki_lookup,
|
| 180 |
+
# web_lookup,
|
| 181 |
+
# arxiv_lookup,
|
| 182 |
+
# retriever_tool,
|
| 183 |
+
# ])
|
| 184 |
+
|
| 185 |
+
# def retrieve_node(state: MessagesState):
|
| 186 |
+
# similar = vector_db.similarity_search(state["messages"][0].content)
|
| 187 |
+
# hint = HumanMessage(content=f"Reference example:\n{similar[0].page_content}" if similar else "")
|
| 188 |
+
# return {"messages": [system_message] + state["messages"] + [hint]}
|
| 189 |
+
|
| 190 |
+
# def respond_node(state: MessagesState):
|
| 191 |
+
# return {"messages": [llama_llm.invoke(state["messages"]) ]}
|
| 192 |
+
|
| 193 |
+
# graph_builder = StateGraph(MessagesState)
|
| 194 |
+
# graph_builder.add_node("find_similar", retrieve_node)
|
| 195 |
+
# graph_builder.add_node("generate_answer", respond_node)
|
| 196 |
+
# graph_builder.add_node("tool_executor", ToolNode([]))
|
| 197 |
+
|
| 198 |
+
# graph_builder.add_edge(START, "find_similar")
|
| 199 |
+
# graph_builder.add_edge("find_similar", "generate_answer")
|
| 200 |
+
# graph_builder.add_conditional_edges(
|
| 201 |
+
# "generate_answer",
|
| 202 |
+
# tools_condition,
|
| 203 |
+
# {"tools": "tool_executor", "default": "generate_answer"}
|
| 204 |
+
# )
|
| 205 |
+
# graph_builder.add_edge("tool_executor", "generate_answer")
|
| 206 |
+
|
| 207 |
+
# return graph_builder.compile()
|
| 208 |
+
|
| 209 |
+
# # ---------------- RUN EXAMPLE ----------------
|
| 210 |
+
# if __name__ == "__main__":
|
| 211 |
+
# sample_q = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
|
| 212 |
+
# agent = construct_agent_graph()
|
| 213 |
+
# msgs = [HumanMessage(content=sample_q)]
|
| 214 |
+
# out = agent.invoke({"messages": msgs})
|
| 215 |
+
# for m in out["messages"]:
|
| 216 |
+
# m.pretty_print()
|
| 217 |
+
|
| 218 |
+
# ---------------- EMBEDDINGS & VECTOR DB ----------------
|
| 219 |
+
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
| 220 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
|
| 221 |
+
sample_docs = [Document(page_content="Sample doc.", metadata={"source":"wiki"})]
|
| 222 |
+
split_docs = text_splitter.split_documents(sample_docs)
|
| 223 |
+
vector_db = Chroma.from_documents(documents=split_docs, embedding=embedding_model)
|
| 224 |
+
retriever_tool = create_retriever_tool(
|
| 225 |
+
retriever=vector_db.as_retriever(),
|
| 226 |
+
name="SimilarQuestionFinder",
|
| 227 |
+
description="Retrieve similar questions and examples from vector DB."
|
| 228 |
)
|
| 229 |
|
| 230 |
+
all_tools = [multiply_numbers, add_numbers, subtract_numbers, divide_numbers,
|
| 231 |
+
modulus_numbers, power_numbers, root_number,
|
| 232 |
+
wiki_lookup, web_lookup, arxiv_lookup, retriever_tool]
|
| 233 |
+
|
| 234 |
+
# ---------------- SYSTEM PROMPT ----------------
|
| 235 |
+
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
| 236 |
+
system_content = f.read()
|
| 237 |
+
system_message = SystemMessage(content=system_content)
|
| 238 |
+
# ---------------- BUILD GRAPH ----------------
|
| 239 |
+
def construct_agent_graph():
|
| 240 |
+
llama_llm = ChatGroq(
|
| 241 |
+
model="qwen-qwq-32b",
|
| 242 |
+
api_key=os.environ["GROQ_API_KEY"],
|
| 243 |
+
temperature=0,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
def retrieve_node(state: MessagesState):
|
| 247 |
+
msgs = [system_message] + state["messages"]
|
| 248 |
+
similar = vector_db.similarity_search(state["messages"][0].content)
|
| 249 |
+
if similar:
|
| 250 |
+
msgs.append(HumanMessage(content=f"Reference example:\n{similar[0].page_content}"))
|
| 251 |
+
return {"messages": msgs}
|
| 252 |
+
|
| 253 |
+
def respond_node(state: MessagesState):
|
| 254 |
+
return {"messages": [llama_llm.invoke(state["messages"])]}
|
| 255 |
+
|
| 256 |
+
graph = StateGraph(MessagesState)
|
| 257 |
+
graph.add_node("find_similar", retrieve_node)
|
| 258 |
+
graph.add_node("generate_answer", respond_node)
|
| 259 |
+
graph.add_node("tool_executor", ToolNode(tools=all_tools))
|
| 260 |
+
|
| 261 |
+
graph.add_edge(START, "find_similar")
|
| 262 |
+
graph.add_edge("find_similar", "generate_answer")
|
| 263 |
+
graph.add_conditional_edges(
|
| 264 |
+
"generate_answer",
|
| 265 |
+
tools_condition,
|
| 266 |
+
{"tools": "tool_executor", "__end__": "__end__"}
|
| 267 |
+
)
|
| 268 |
+
graph.add_edge("tool_executor", "generate_answer")
|
| 269 |
+
|
| 270 |
+
return graph.compile()
|
| 271 |
|
| 272 |
+
# ---------------- RUN EXAMPLE ----------------
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
agent = construct_agent_graph()
|
| 275 |
+
sample_q = "When was St. Thomas Aquinas added to that page?"
|
| 276 |
+
out = agent.invoke({"messages": [HumanMessage(content=sample_q)]})
|
| 277 |
+
for m in out["messages"]:
|
| 278 |
+
m.pretty_print()
|
| 279 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|