Spaces:
Sleeping
Sleeping
Create agent.py
Browse files
agent.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from langchain.chains import RetrievalQA
|
| 3 |
+
from langchain_chroma import Chroma
|
| 4 |
+
from langchain_core.messages import SystemMessage, HumanMessage
|
| 5 |
+
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
| 6 |
+
from langgraph.graph import StateGraph, START
|
| 7 |
+
from langgraph.graph.message import MessagesState
|
| 8 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 9 |
+
|
| 10 |
+
from agent_tools import *
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
sys_msg = SystemMessage(
|
| 15 |
+
content=
|
| 16 |
+
"""
|
| 17 |
+
You are a helpful assistant tasked with answering questions using a set of tools. When given a question, follow these steps:
|
| 18 |
+
1. Create a clear, step-by-step plan to solve the question.
|
| 19 |
+
2. If a tool is necessary, select the most appropriate tool based on its functionality. If one tool isn't working, use another with similar functionality.
|
| 20 |
+
3. If a question depends on external numeric or factual data not provided, automatically use your search tools to find it online before answering.
|
| 21 |
+
4. Base your answer on tool outputs and any provided files.
|
| 22 |
+
5. Execute your plan and provide the response in the following format:
|
| 23 |
+
FINAL ANSWER: [YOUR FINAL ANSWER]
|
| 24 |
+
Your final answer should be:
|
| 25 |
+
- A number (without commas or units unless explicitly requested),
|
| 26 |
+
- A short string (avoid articles, abbreviations, and use plain text for digits unless otherwise specified),
|
| 27 |
+
- A comma-separated list (apply the formatting rules above for each element, with exactly one space after each comma).
|
| 28 |
+
Ensure that your answer is concise and follows the task instructions strictly. If the answer is more complex, break it down in a way that follows the format.
|
| 29 |
+
Begin your response with "FINAL ANSWER: " followed by the answer, and nothing else.
|
| 30 |
+
"""
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
class CUSTOM_AGENT:
|
| 34 |
+
"""
|
| 35 |
+
A simple deterministic agent that leverages our tools directly and avoids
|
| 36 |
+
LLM refusal fallbacks.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(self):
|
| 40 |
+
self.llm = ChatOpenAI(model="gpt-5", api_key=os.getenv("OPENAI_API_KEY"), temperature=0)
|
| 41 |
+
self.tools = TOOLS
|
| 42 |
+
self.llm_with_tools = self.llm.bind_tools(self.tools)
|
| 43 |
+
self.sys_msg = sys_msg
|
| 44 |
+
embeddings = OpenAIEmbeddings(api_key=os.getenv("OPENAI_API_KEY"))
|
| 45 |
+
persist_directory = "chroma_db"
|
| 46 |
+
self.vectorstore = Chroma(persist_directory=persist_directory, embedding_function=embeddings)
|
| 47 |
+
self.retriever = self.vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 48 |
+
self.qa_chain = RetrievalQA.from_chain_type(
|
| 49 |
+
llm=self.llm,
|
| 50 |
+
retriever=self.retriever,
|
| 51 |
+
return_source_documents=True
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def _graph_compile(self):
|
| 55 |
+
builder = StateGraph(MessagesState)
|
| 56 |
+
builder.add_node("retriever", self._retriever_node)
|
| 57 |
+
builder.add_node("assistant", self._assistant)
|
| 58 |
+
builder.add_node("tools", ToolNode(self.tools))
|
| 59 |
+
|
| 60 |
+
builder.add_edge(START, "retriever")
|
| 61 |
+
builder.add_edge("retriever", "assistant")
|
| 62 |
+
|
| 63 |
+
builder.add_conditional_edges(
|
| 64 |
+
"assistant",
|
| 65 |
+
tools_condition,
|
| 66 |
+
)
|
| 67 |
+
builder.add_edge("tools", "assistant")
|
| 68 |
+
return builder.compile()
|
| 69 |
+
|
| 70 |
+
def _retriever_node(self, state: MessagesState):
|
| 71 |
+
"""Retriever node"""
|
| 72 |
+
question = state["messages"][ -1 ].content
|
| 73 |
+
docs = self.retriever.invoke(question)
|
| 74 |
+
|
| 75 |
+
if docs:
|
| 76 |
+
context = "\n\n".join([d.page_content for d in docs])
|
| 77 |
+
else:
|
| 78 |
+
context = "No relevant documents found"
|
| 79 |
+
|
| 80 |
+
combined = f"Context:\n{context}\n\nQuestion:\n{question}"
|
| 81 |
+
return {"messages": [HumanMessage(content=combined)]}
|
| 82 |
+
|
| 83 |
+
def _assistant(self, state: MessagesState):
|
| 84 |
+
"""Assistant node"""
|
| 85 |
+
if not any(isinstance(m, SystemMessage) for m in state["messages"]):
|
| 86 |
+
messages = [self.sys_msg] + state["messages"]
|
| 87 |
+
else:
|
| 88 |
+
messages = state["messages"]
|
| 89 |
+
|
| 90 |
+
llm_response = self.llm_with_tools.invoke(messages)
|
| 91 |
+
|
| 92 |
+
return {"messages": [llm_response]}
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def extract_after_final_answer(text):
|
| 96 |
+
keyword = "FINAL ANSWER: "
|
| 97 |
+
index = text.find(keyword)
|
| 98 |
+
if index != -1:
|
| 99 |
+
return text[index + len(keyword):].strip()
|
| 100 |
+
else:
|
| 101 |
+
return text.strip()
|
| 102 |
+
|
| 103 |
+
def run(self, task: dict):
|
| 104 |
+
task_id, question, file_name = task["task_id"], task["question"], task["file_name"]
|
| 105 |
+
print(f"Agent received question (first 100 chars): {question[:100]}...")
|
| 106 |
+
|
| 107 |
+
if file_name == "" or file_name is None:
|
| 108 |
+
question_text = question
|
| 109 |
+
else:
|
| 110 |
+
question_text = f'{question} with TASK-ID: {task_id}'
|
| 111 |
+
|
| 112 |
+
graph = self._graph_compile()
|
| 113 |
+
|
| 114 |
+
max_retries = 3
|
| 115 |
+
base_sleep = 1
|
| 116 |
+
for attempt in range(max_retries):
|
| 117 |
+
try:
|
| 118 |
+
messages: list[HumanMessage] = [HumanMessage(content=question_text)]
|
| 119 |
+
result = graph.invoke({"messages": messages})
|
| 120 |
+
|
| 121 |
+
final_text = result["messages"][-1].content
|
| 122 |
+
return self.extract_after_final_answer(final_text)
|
| 123 |
+
except Exception as e:
|
| 124 |
+
sleep_time = base_sleep * (attempt + 1)
|
| 125 |
+
if attempt < max_retries - 1:
|
| 126 |
+
print(str(e))
|
| 127 |
+
print(f"Attempt {attempt + 1} failed. Retrying in {sleep_time} seconds...")
|
| 128 |
+
time.sleep(sleep_time)
|
| 129 |
+
continue
|
| 130 |
+
return f"Error processing query after {max_retries} attempts: {str(e)}"
|
| 131 |
+
return "This is a default answer."
|