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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from llama_index.core import SimpleDirectoryReader
|
| 2 |
+
from llama_index.core.node_parser import SentenceSplitter
|
| 3 |
+
from llama_index.core import Settings
|
| 4 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 5 |
+
from llama_index.core import VectorStoreIndex
|
| 6 |
+
from langchain_groq import ChatGroq
|
| 7 |
+
from langchain.tools import BaseTool, StructuredTool, tool
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 10 |
+
from typing import TypedDict ,Annotated
|
| 11 |
+
from langchain_core.runnables import RunnablePassthrough
|
| 12 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 13 |
+
import os
|
| 14 |
+
import uuid
|
| 15 |
+
from typing import TypedDict ,Annotated
|
| 16 |
+
from langchain_core.messages import AnyMessage,SystemMessage,HumanMessage,ToolMessage,AIMessage
|
| 17 |
+
import operator
|
| 18 |
+
from langgraph.checkpoint.memory import InMemorySaver
|
| 19 |
+
from langgraph.graph import StateGraph, END
|
| 20 |
+
from fastapi import FastAPI
|
| 21 |
+
import json
|
| 22 |
+
import shutil
|
| 23 |
+
import os
|
| 24 |
+
from fastapi import FastAPI, File, UploadFile
|
| 25 |
+
|
| 26 |
+
app = FastAPI()
|
| 27 |
+
|
| 28 |
+
@app.get("/")
|
| 29 |
+
def read_root():
|
| 30 |
+
app.state.vector_index = None
|
| 31 |
+
keep_alive()
|
| 32 |
+
return {"message": "Connected"}
|
| 33 |
+
|
| 34 |
+
def keep_alive(space_url="https://1mr-apigmail.hf.space/ping", interval_hours=5):
|
| 35 |
+
while True:
|
| 36 |
+
try:
|
| 37 |
+
print(f"🔄 Pinging {space_url} at {datetime.now()}")
|
| 38 |
+
response = requests.get(space_url)
|
| 39 |
+
|
| 40 |
+
if response.status_code == 200:
|
| 41 |
+
print("")
|
| 42 |
+
else:
|
| 43 |
+
print("")
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print("")
|
| 46 |
+
|
| 47 |
+
time.sleep(interval_hours * 3600)
|
| 48 |
+
|
| 49 |
+
keep_alive()
|
| 50 |
+
|
| 51 |
+
@tool
|
| 52 |
+
def retrieve(query_text):
|
| 53 |
+
"""
|
| 54 |
+
Retrieves relevant information from a vector index based on a query.
|
| 55 |
+
Parameters:
|
| 56 |
+
- query_text (str): Query to search for relevant information.
|
| 57 |
+
Returns:
|
| 58 |
+
- str: Retrieved text from the document.
|
| 59 |
+
"""
|
| 60 |
+
if not hasattr(app.state, "vector_index") or app.state.vector_index is None:
|
| 61 |
+
return "Vector index not found. Please upload a file first."
|
| 62 |
+
else:
|
| 63 |
+
retriever = app.state.vector_index.as_retriever(similarity_top_k=3)
|
| 64 |
+
result = retriever.retrieve(query_text)
|
| 65 |
+
if result:
|
| 66 |
+
return "\n\n".join([node.node.text for node in result])
|
| 67 |
+
return "No relevant information found."
|
| 68 |
+
|
| 69 |
+
tavily_search = TavilySearchResults(max_results=4)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@app.post("/uploadpdfs")
|
| 73 |
+
async def upload_file(file: UploadFile = File(...)):
|
| 74 |
+
# global vector_index
|
| 75 |
+
|
| 76 |
+
# Save uploaded file to a temp directory
|
| 77 |
+
temp_dir = "temp_uploads"
|
| 78 |
+
os.makedirs(temp_dir, exist_ok=True)
|
| 79 |
+
file_id = str(uuid.uuid4())
|
| 80 |
+
file_path = os.path.join(temp_dir, f"{file_id}_{file.filename}")
|
| 81 |
+
|
| 82 |
+
with open(file_path, "wb") as f:
|
| 83 |
+
shutil.copyfileobj(file.file, f)
|
| 84 |
+
|
| 85 |
+
# Load and parse document
|
| 86 |
+
documents = SimpleDirectoryReader(input_files=[file_path]).load_data()
|
| 87 |
+
parser = SentenceSplitter(chunk_size=300, chunk_overlap=50)
|
| 88 |
+
nodes = parser.get_nodes_from_documents(documents)
|
| 89 |
+
|
| 90 |
+
# Create or update vector index
|
| 91 |
+
embed_model = HuggingFaceEmbedding(model_name="WhereIsAI/UAE-Large-V1")
|
| 92 |
+
# if vector_index is None:
|
| 93 |
+
if not hasattr(app.state, "vector_index") or app.state.vector_index is None:
|
| 94 |
+
app.state.vector_index = VectorStoreIndex(nodes, embed_model=embed_model)
|
| 95 |
+
message = "New vector index created and file stored."
|
| 96 |
+
else:
|
| 97 |
+
app.state.vector_index.insert_nodes(nodes)
|
| 98 |
+
message = "File stored and vector index updated."
|
| 99 |
+
|
| 100 |
+
return {"message": message, "filename": file.filename}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class QueryRequest(BaseModel):
|
| 104 |
+
message: str
|
| 105 |
+
|
| 106 |
+
class AgentState(TypedDict):
|
| 107 |
+
messages: Annotated[list[AnyMessage], operator.add]
|
| 108 |
+
|
| 109 |
+
memory = InMemorySaver()
|
| 110 |
+
|
| 111 |
+
class Agent:
|
| 112 |
+
def __init__(self, model, tools, checkpointer=None, system=""):
|
| 113 |
+
self.system = system
|
| 114 |
+
graph = StateGraph(AgentState)
|
| 115 |
+
graph.add_node('llm',self.call_llm)
|
| 116 |
+
graph.add_node('action',self.take_action)
|
| 117 |
+
graph.add_conditional_edges("llm",self.exists_action,{True :"action",False:END})
|
| 118 |
+
graph.add_edge("action","llm")
|
| 119 |
+
graph.set_entry_point("llm")
|
| 120 |
+
self.graph = graph.compile(checkpointer=checkpointer)
|
| 121 |
+
self.tools = {t.name:t for t in tools}
|
| 122 |
+
self.model = model.bind_tools(tools)
|
| 123 |
+
|
| 124 |
+
def call_llm(self, state:AgentState):
|
| 125 |
+
messages = state['messages']
|
| 126 |
+
if self.system :
|
| 127 |
+
messages = [SystemMessage(content=self.system)] + messages
|
| 128 |
+
message = self.model.invoke(messages)
|
| 129 |
+
return {"messages":[message]}
|
| 130 |
+
|
| 131 |
+
def exists_action(self, state:AgentState):
|
| 132 |
+
result = state['messages'][-1]
|
| 133 |
+
return len(result.tool_calls) > 0
|
| 134 |
+
|
| 135 |
+
def take_action(self, state:AgentState):
|
| 136 |
+
tool_calls = state['messages'][-1].tool_calls
|
| 137 |
+
results = []
|
| 138 |
+
for t in tool_calls:
|
| 139 |
+
result= self.tools[t['name']].invoke(t['args'])
|
| 140 |
+
results.append(ToolMessage(tool_call_id=t['id'],name=t['name'],content=str(result)))
|
| 141 |
+
return {"messages":results}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
system_Prompt="""
|
| 145 |
+
You are an AI assistant designed to assist users with health benefits, diet, nutrition information, and recipes.
|
| 146 |
+
You analyze patient reports to offer guidance on self-care with AI support.
|
| 147 |
+
Provide answers directly related to the question, without additional explanation or unrelated information.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
tools=[retrieve,tavily_search]
|
| 151 |
+
|
| 152 |
+
model = ChatGroq(model="qwen-qwq-32b")
|
| 153 |
+
|
| 154 |
+
agent = Agent(model, tools, memory, system=system_Prompt)
|
| 155 |
+
|
| 156 |
+
thread = {"configurable": {'thread_id': '1'}}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@app.post("/askbot")
|
| 160 |
+
async def ask_question(query: QueryRequest):
|
| 161 |
+
messages = [HumanMessage(content=query.message)]
|
| 162 |
+
final_res = ""
|
| 163 |
+
|
| 164 |
+
for event in agent.graph.stream({'messages': messages}, thread):
|
| 165 |
+
for v in event.values():
|
| 166 |
+
if isinstance(v, dict) and 'messages' in v:
|
| 167 |
+
for msg in v['messages']:
|
| 168 |
+
if hasattr(msg, 'content') and isinstance(msg, AIMessage):
|
| 169 |
+
final_res += msg.content
|
| 170 |
+
|
| 171 |
+
return {"answer": final_res}
|