Spaces:
Sleeping
Sleeping
File size: 15,240 Bytes
564f142 5d42805 1f6995c 5d42805 c6774a0 5d42805 1f6995c 849b2e7 8c314b2 849b2e7 8c314b2 849b2e7 8c314b2 5d42805 1f6995c 5d42805 1f6995c 23a8b3a 1f6995c e08d293 afd5786 4c019ab afd5786 c6774a0 afd5786 e08d293 afd5786 e08d293 c6774a0 afd5786 c6774a0 afd5786 c6774a0 564f142 c6774a0 e08d293 1f6995c 5d42805 1f6995c 5d42805 1f6995c 849b2e7 1f6995c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
#DOCS
# https://langchain-ai.github.io/langgraph/reference/prebuilt/#langgraph.prebuilt.chat_agent_executor.create_react_agent
import uuid
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from langchain_core.messages import (
BaseMessage,
HumanMessage,
SystemMessage,
trim_messages,
)
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
from pydantic import BaseModel
import json
from typing import Optional, Annotated
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt import InjectedState
from document_rag_router import router as document_rag_router
from document_rag_router import QueryInput, query_collection, SearchResult,db
from fastapi import HTTPException
import requests
from sse_starlette.sse import EventSourceResponse
from fastapi.middleware.cors import CORSMiddleware
import re
import os
from langchain_core.prompts import ChatPromptTemplate
import logging.config
# Configure logging at application startup
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
"formatter": "default",
"level": "DEBUG",
}
},
"root": {
"level": "DEBUG",
"handlers": ["console"]
},
"loggers": {
"uvicorn": {"handlers": ["console"], "level": "DEBUG"},
"fastapi": {"handlers": ["console"], "level": "DEBUG"}
}
})
# Create logger instance
logger = logging.getLogger(__name__)
app = FastAPI()
app.include_router(document_rag_router)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def get_current_files():
"""Get list of files in current directory"""
try:
files = os.listdir('.')
return ", ".join(files)
except Exception as e:
return f"Error getting files: {str(e)}"
@tool
def get_user_age(name: str) -> str:
"""Use this tool to find the user's age."""
if "bob" in name.lower():
return "42 years old"
return "41 years old"
@tool
async def query_documents(
query: str,
config: RunnableConfig,
) -> str:
"""Use this tool to retrieve relevant data from the collection.
Args:
query: The search query to find relevant document passages
"""
# Get collection_id and user_id from config
thread_config = config.get("configurable", {})
collection_id = thread_config.get("collection_id")
user_id = thread_config.get("user_id")
if not collection_id or not user_id:
return "Error: collection_id and user_id are required in the config"
try:
# Create query input
input_data = QueryInput(
collection_id=collection_id,
query=query,
user_id=user_id,
top_k=6
)
response = await query_collection(input_data)
results = []
# Access response directly since it's a Pydantic model
for r in response.results:
result_dict = {
"text": r.text,
"distance": r.distance,
"metadata": {
"document_id": r.metadata.get("document_id"),
"chunk_index": r.metadata.get("location", {}).get("chunk_index")
}
}
results.append(result_dict)
return str(results)
except Exception as e:
print(e)
return f"Error querying documents: {e} PAUSE AND ASK USER FOR HELP"
async def query_documents_raw(
query: str,
config: RunnableConfig,
) -> SearchResult:
"""Use this tool to retrieve relevant data from the collection.
Args:
query: The search query to find relevant document passages
"""
# Get collection_id and user_id from config
thread_config = config.get("configurable", {})
collection_id = thread_config.get("collection_id")
user_id = thread_config.get("user_id")
if not collection_id or not user_id:
return "Error: collection_id and user_id are required in the config"
try:
# Create query input
input_data = QueryInput(
collection_id=collection_id,
query=query,
user_id=user_id,
top_k=6
)
response = await query_collection(input_data)
return response.results
except Exception as e:
print(e)
return f"Error querying documents: {e} PAUSE AND ASK USER FOR HELP"
memory = MemorySaver()
model = ChatOpenAI(model="gpt-4o-mini", streaming=True)
# Create a prompt template for formatting
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful AI assistant. The current collection contains the following files: {collection_files}, use query_documents tool to answer user queries from the document. use query planning to create document section queries if a summary is required"),
("placeholder", "{messages}"),
])
import requests
from requests.exceptions import RequestException, Timeout
import logging
from typing import Optional
# def get_collection_files(collection_id: str, user_id: str) -> str:
# """
# Synchronously get list of files in the specified collection using the external API
# with proper timeout and error handling.
# """
# try:
# url = "https://pvanand-documind-api-v2.hf.space/rag/get_collection_files"
# params = {
# "collection_id": collection_id,
# "user_id": user_id
# }
# headers = {
# 'accept': 'application/json'
# }
# logger.debug(f"Requesting collection files for user {user_id}, collection {collection_id}")
# # Set timeout to 5 seconds
# response = requests.post(url, params=params, headers=headers, data='', timeout=5)
# if response.status_code == 200:
# logger.info(f"Successfully retrieved collection files: {response.text[:100]}...")
# return response.text
# else:
# logger.error(f"API error (status {response.status_code}): {response.text}")
# return f"Error fetching files (status {response.status_code})"
# except Timeout:
# logger.error("Timeout while fetching collection files")
# return "Error: Request timed out"
# except RequestException as e:
# logger.error(f"Network error fetching collection files: {str(e)}")
# return f"Error: Network issue - {str(e)}"
# except Exception as e:
# logger.error(f"Error fetching collection files: {str(e)}", exc_info=True)
# return f"Error fetching files: {str(e)}"
def get_collection_files(collection_id: str, user_id: str) -> str:
"""Get list of files in the specified collection"""
try:
# Get the full collection name
collection_name = f"{user_id}_{collection_id}"
# Open the table and convert to pandas
table = db.open_table(collection_name)
df = table.to_pandas()
print(df.head())
# Get unique file names
unique_files = df['file_name'].unique()
# Join the file names into a string
return ", ".join(unique_files)
except Exception as e:
logging.error(f"Error getting collection files: {str(e)}")
return f"Error getting files: {str(e)}"
def format_for_model(state: dict, config: Optional[RunnableConfig] = None) -> list[BaseMessage]:
"""
Format the input state and config for the model.
Args:
state: The current state dictionary containing messages
config: Optional RunnableConfig containing thread configuration
Returns:
Formatted messages for the model
"""
# Get collection_id and user_id from config instead of state
thread_config = config.get("configurable", {}) if config else {}
collection_id = thread_config.get("collection_id")
user_id = thread_config.get("user_id")
try:
# Get files in the collection with timeout protection
if collection_id and user_id:
collection_files = get_collection_files(collection_id, user_id)
else:
collection_files = "No files available"
logger.info(f"Fetching collection for userid {user_id} and collection_id {collection_id} || Results: {collection_files[:100]}...")
# Format using the prompt template
return prompt.invoke({
"collection_files": collection_files,
"messages": state.get("messages", [])
})
except Exception as e:
logger.error(f"Error in format_for_model: {str(e)}", exc_info=True)
# Return a basic format if there's an error
return prompt.invoke({
"collection_files": "Error fetching files",
"messages": state.get("messages", [])
})
async def clean_tool_input(tool_input: str):
# Use regex to parse the first key and value
pattern = r"{\s*'([^']+)':\s*'([^']+)'"
match = re.search(pattern, tool_input)
if match:
key, value = match.groups()
return {key: value}
return [tool_input]
async def clean_tool_response(tool_output: str):
"""Clean and extract relevant information from tool response if it contains query_documents."""
if "query_documents" in tool_output:
try:
# First safely evaluate the string as a Python literal
import ast
print(tool_output)
# Extract the list string from the content
start = tool_output.find("[{")
end = tool_output.rfind("}]") + 2
if start >= 0 and end > 0:
list_str = tool_output[start:end]
# Convert string to Python object using ast.literal_eval
results = ast.literal_eval(list_str)
# Return only relevant fields
return [{"text": r["text"], "document_id": r["metadata"]["document_id"]}
for r in results]
except SyntaxError as e:
print(f"Syntax error in parsing: {e}")
return f"Error parsing document results: {str(e)}"
except Exception as e:
print(f"General error: {e}")
return f"Error processing results: {str(e)}"
return tool_output
agent = create_react_agent(
model,
tools=[query_documents],
checkpointer=memory,
state_modifier=format_for_model,
)
class ChatInput(BaseModel):
message: str
thread_id: Optional[str] = None
collection_id: Optional[str] = None
user_id: Optional[str] = None
@app.post("/chat")
async def chat(input_data: ChatInput):
thread_id = input_data.thread_id or str(uuid.uuid4())
config = {
"configurable": {
"thread_id": thread_id,
"collection_id": input_data.collection_id,
"user_id": input_data.user_id
}
}
input_message = HumanMessage(content=input_data.message)
async def generate():
async for event in agent.astream_events(
{"messages": [input_message]},
config,
version="v2"
):
kind = event["event"]
if kind == "on_chat_model_stream":
content = event["data"]["chunk"].content
if content:
yield f"{json.dumps({'type': 'token', 'content': content})}"
elif kind == "on_tool_start":
tool_input = str(event['data'].get('input', ''))
yield f"{json.dumps({'type': 'tool_start', 'tool': event['name'], 'input': tool_input})}"
elif kind == "on_tool_end":
tool_output = str(event['data'].get('output', ''))
yield f"{json.dumps({'type': 'tool_end', 'tool': event['name'], 'output': tool_output})}"
return EventSourceResponse(
generate(),
media_type="text/event-stream"
)
@app.post("/chat2")
async def chat2(input_data: ChatInput):
thread_id = input_data.thread_id or str(uuid.uuid4())
config = {
"configurable": {
"thread_id": thread_id,
"collection_id": input_data.collection_id,
"user_id": input_data.user_id
}
}
input_message = HumanMessage(content=input_data.message)
async def generate():
async for event in agent.astream_events(
{"messages": [input_message]},
config,
version="v2"
):
kind = event["event"]
if kind == "on_chat_model_stream":
content = event["data"]["chunk"].content
if content:
yield f"{json.dumps({'type': 'token', 'content': content})}"
elif kind == "on_tool_start":
tool_name = event['name']
tool_input = event['data'].get('input', '')
clean_input = await clean_tool_input(str(tool_input))
yield f"{json.dumps({'type': 'tool_start', 'tool': tool_name, 'inputs': clean_input})}"
elif kind == "on_tool_end":
if "query_documents" in event['name']:
print(event)
raw_output = await query_documents_raw(str(event['data'].get('input', '')), config)
try:
serializable_output = [
{
"text": result.text,
"distance": result.distance,
"metadata": result.metadata
}
for result in raw_output
]
yield f"{json.dumps({'type': 'tool_end', 'tool': event['name'], 'output': json.dumps(serializable_output)})}"
except Exception as e:
print(e)
yield f"{json.dumps({'type': 'tool_end', 'tool': event['name'], 'output': str(raw_output)})}"
else:
tool_name = event['name']
raw_output = str(event['data'].get('output', ''))
clean_output = await clean_tool_response(raw_output)
yield f"{json.dumps({'type': 'tool_end', 'tool': tool_name, 'output': clean_output})}"
return EventSourceResponse(
generate(),
media_type="text/event-stream"
)
@app.get("/health")
async def health_check():
return {"status": "healthy"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |