Upload 2 files
Browse files- agent 1.py +210 -0
- metadata (1) 1.jsonl +0 -0
agent 1.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from dotenv import load_dotenv
|
3 |
+
from langgraph.graph import START, StateGraph, MessagesState
|
4 |
+
from langgraph.prebuilt import tools_condition, ToolNode
|
5 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
6 |
+
from langchain_groq import ChatGroq
|
7 |
+
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
|
8 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
9 |
+
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
10 |
+
from langchain_community.vectorstores import Chroma
|
11 |
+
from langchain_core.documents import Document
|
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 |
+
import json
|
16 |
+
from langchain.vectorstores import Chroma
|
17 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
18 |
+
from langchain.schema import Document
|
19 |
+
|
20 |
+
load_dotenv()
|
21 |
+
|
22 |
+
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
|
23 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
24 |
+
|
25 |
+
# Tools
|
26 |
+
@tool
|
27 |
+
def multiply(a: int, b: int) -> int:
|
28 |
+
"""Multiply two numbers.
|
29 |
+
Args:
|
30 |
+
a: first int
|
31 |
+
b: second int
|
32 |
+
"""
|
33 |
+
return a * b
|
34 |
+
|
35 |
+
@tool
|
36 |
+
def add(a: int, b: int) -> int:
|
37 |
+
"""Add two numbers.
|
38 |
+
|
39 |
+
Args:
|
40 |
+
a: first int
|
41 |
+
b: second int
|
42 |
+
"""
|
43 |
+
return a + b
|
44 |
+
|
45 |
+
@tool
|
46 |
+
def subtract(a: int, b: int) -> int:
|
47 |
+
"""Subtract two numbers.
|
48 |
+
|
49 |
+
Args:
|
50 |
+
a: first int
|
51 |
+
b: second int
|
52 |
+
"""
|
53 |
+
return a - b
|
54 |
+
|
55 |
+
@tool
|
56 |
+
def divide(a: int, b: int) -> int:
|
57 |
+
"""Divide two numbers.
|
58 |
+
|
59 |
+
Args:
|
60 |
+
a: first int
|
61 |
+
b: second int
|
62 |
+
"""
|
63 |
+
if b == 0:
|
64 |
+
raise ValueError("Cannot divide by zero.")
|
65 |
+
return a / b
|
66 |
+
|
67 |
+
@tool
|
68 |
+
def modulus(a: int, b: int) -> int:
|
69 |
+
"""Get the modulus of two numbers.
|
70 |
+
|
71 |
+
Args:
|
72 |
+
a: first int
|
73 |
+
b: second int
|
74 |
+
"""
|
75 |
+
return a % b
|
76 |
+
|
77 |
+
@tool
|
78 |
+
def wiki_search(query: str) -> str:
|
79 |
+
"""Search Wikipedia for a query and return maximum 2 results.
|
80 |
+
|
81 |
+
Args:
|
82 |
+
query: The search query."""
|
83 |
+
search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
84 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
85 |
+
[
|
86 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
87 |
+
for doc in search_docs
|
88 |
+
])
|
89 |
+
return {"wiki_results": formatted_search_docs}
|
90 |
+
|
91 |
+
@tool
|
92 |
+
def web_search(query: str) -> str:
|
93 |
+
"""Search Tavily for a query and return maximum 3 results.
|
94 |
+
|
95 |
+
Args:
|
96 |
+
query: The search query."""
|
97 |
+
search_docs = TavilySearchResults(max_results=3).invoke(query=query)
|
98 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
99 |
+
[
|
100 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
101 |
+
for doc in search_docs
|
102 |
+
])
|
103 |
+
return {"web_results": formatted_search_docs}
|
104 |
+
|
105 |
+
@tool
|
106 |
+
def arvix_search(query: str) -> str:
|
107 |
+
"""Search Arxiv for a query and return maximum 3 result.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
query: The search query."""
|
111 |
+
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
|
112 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
113 |
+
[
|
114 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
115 |
+
for doc in search_docs
|
116 |
+
])
|
117 |
+
return {"arvix_results": formatted_search_docs}
|
118 |
+
|
119 |
+
@tool
|
120 |
+
def similar_question_search(question: str) -> str:
|
121 |
+
"""Search the vector database for similar questions and return the first results.
|
122 |
+
|
123 |
+
Args:
|
124 |
+
question: the question human provided."""
|
125 |
+
matched_docs = vector_store.similarity_search(query, 3)
|
126 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
127 |
+
[
|
128 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
129 |
+
for doc in matched_docs
|
130 |
+
])
|
131 |
+
return {"similar_questions": formatted_search_docs}
|
132 |
+
|
133 |
+
# Load system prompt
|
134 |
+
system_prompt = """
|
135 |
+
You are a helpful assistant tasked with answering questions using a set of tools.
|
136 |
+
Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
|
137 |
+
FINAL ANSWER: [YOUR FINAL ANSWER].
|
138 |
+
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
139 |
+
Your answer should only start with "FINAL ANSWER: ", then follows with the answer.
|
140 |
+
"""
|
141 |
+
|
142 |
+
# System message
|
143 |
+
sys_msg = SystemMessage(content=system_prompt)
|
144 |
+
|
145 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
146 |
+
|
147 |
+
with open('metadata.jsonl', 'r') as jsonl_file:
|
148 |
+
json_list = list(jsonl_file)
|
149 |
+
|
150 |
+
json_QA = []
|
151 |
+
for json_str in json_list:
|
152 |
+
json_data = json.loads(json_str)
|
153 |
+
json_QA.append(json_data)
|
154 |
+
|
155 |
+
documents = []
|
156 |
+
for sample in json_QA:
|
157 |
+
content = f"Question : {sample['Question']}\n\nFinal answer : {sample['Final answer']}"
|
158 |
+
metadata = {"source": sample["task_id"]}
|
159 |
+
documents.append(Document(page_content=content, metadata=metadata))
|
160 |
+
|
161 |
+
# Initialize vector store and add documents
|
162 |
+
vector_store = Chroma.from_documents(
|
163 |
+
documents=documents,
|
164 |
+
embedding=embeddings,
|
165 |
+
persist_directory="./chroma_db",
|
166 |
+
collection_name="my_collection"
|
167 |
+
)
|
168 |
+
vector_store.persist()
|
169 |
+
print("Documents inserted:", vector_store._collection.count())
|
170 |
+
|
171 |
+
|
172 |
+
# Retriever tool (optional if you want to expose to agent)
|
173 |
+
retriever_tool = create_retriever_tool(
|
174 |
+
retriever=vector_store.as_retriever(),
|
175 |
+
name="Question Search",
|
176 |
+
description="A tool to retrieve similar questions from a vector store.",
|
177 |
+
)
|
178 |
+
|
179 |
+
# Tool list
|
180 |
+
tools = [
|
181 |
+
multiply, add, subtract, divide, modulus,
|
182 |
+
wiki_search, web_search, arvix_search,
|
183 |
+
]
|
184 |
+
|
185 |
+
# Build graph
|
186 |
+
def build_graph(provider: str = "groq"):
|
187 |
+
|
188 |
+
llm = ChatGroq(model="qwen-qwq-32b", temperature=0,api_key=groq_api_key)
|
189 |
+
llm_with_tools = llm.bind_tools(tools)
|
190 |
+
|
191 |
+
def assistant(state: MessagesState):
|
192 |
+
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
193 |
+
|
194 |
+
def retriever(state: MessagesState):
|
195 |
+
similar = vector_store.similarity_search(state["messages"][0].content)
|
196 |
+
if similar:
|
197 |
+
example_msg = HumanMessage(content=f"Here is a similar question:\n\n{similar[0].page_content}")
|
198 |
+
return {"messages": [sys_msg] + state["messages"] + [example_msg]}
|
199 |
+
return {"messages": [sys_msg] + state["messages"]}
|
200 |
+
|
201 |
+
builder = StateGraph(MessagesState)
|
202 |
+
builder.add_node("retriever", retriever)
|
203 |
+
builder.add_node("assistant", assistant)
|
204 |
+
builder.add_node("tools", ToolNode(tools))
|
205 |
+
builder.add_edge(START, "retriever")
|
206 |
+
builder.add_edge("retriever", "assistant")
|
207 |
+
builder.add_conditional_edges("assistant", tools_condition)
|
208 |
+
builder.add_edge("tools", "assistant")
|
209 |
+
|
210 |
+
return builder.compile()
|
metadata (1) 1.jsonl
ADDED
The diff for this file is too large to render.
See raw diff
|
|