Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,19 +9,6 @@ from dotenv import load_dotenv
|
|
| 9 |
import autogen
|
| 10 |
from autogen import AssistantAgent, UserProxyAgent
|
| 11 |
|
| 12 |
-
# Import DeepSeek API or appropriate SDK here
|
| 13 |
-
from deepseek_api import DeepSeekEmbeddings # Hypothetical import
|
| 14 |
-
from langchain_community.vecimport os
|
| 15 |
-
import json
|
| 16 |
-
import random
|
| 17 |
-
import logging
|
| 18 |
-
from typing import List, Dict, Any
|
| 19 |
-
|
| 20 |
-
import streamlit as st
|
| 21 |
-
from dotenv import load_dotenv
|
| 22 |
-
import autogen
|
| 23 |
-
from autogen import AssistantAgent, UserProxyAgent
|
| 24 |
-
|
| 25 |
from langchain_community.embeddings import OpenAIEmbeddings
|
| 26 |
from langchain_community.vectorstores import Chroma
|
| 27 |
from langchain.docstore.document import Document
|
|
@@ -308,224 +295,3 @@ with st.form(key="query_form", clear_on_submit=True):
|
|
| 308 |
st.markdown("### Response")
|
| 309 |
st.write(response)
|
| 310 |
|
| 311 |
-
torstores import Chroma
|
| 312 |
-
from langchain.docstore.document import Document
|
| 313 |
-
|
| 314 |
-
# Load environment variables
|
| 315 |
-
load_dotenv()
|
| 316 |
-
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") # Use DeepSeek API Key
|
| 317 |
-
|
| 318 |
-
logging.basicConfig(level=logging.INFO)
|
| 319 |
-
logger = logging.getLogger(__name__)
|
| 320 |
-
st.set_page_config(page_title="IT Support System (RAG)", layout="centered")
|
| 321 |
-
|
| 322 |
-
# Initialize session memory
|
| 323 |
-
if "chat_history" not in st.session_state:
|
| 324 |
-
st.session_state.chat_history = []
|
| 325 |
-
|
| 326 |
-
# Knowledge Base Setup
|
| 327 |
-
kb_path = os.path.join(os.path.dirname(__file__), 'kb.json')
|
| 328 |
-
with open(kb_path, encoding='utf-8') as f:
|
| 329 |
-
kb_entries = json.load(f)
|
| 330 |
-
|
| 331 |
-
docs: List[Document] = []
|
| 332 |
-
for entry in kb_entries:
|
| 333 |
-
docs.append(Document(
|
| 334 |
-
page_content=entry['answer'],
|
| 335 |
-
metadata={
|
| 336 |
-
'id': entry.get('id'),
|
| 337 |
-
'question': entry.get('question')
|
| 338 |
-
}
|
| 339 |
-
))
|
| 340 |
-
|
| 341 |
-
# Initialize DeepSeek embeddings (Assuming DeepSeek API provides embeddings service)
|
| 342 |
-
embeddings = DeepSeekEmbeddings(api_key=DEEPSEEK_API_KEY)
|
| 343 |
-
|
| 344 |
-
# Vector database setup
|
| 345 |
-
vectordb = Chroma.from_documents(
|
| 346 |
-
documents=docs,
|
| 347 |
-
embedding=embeddings,
|
| 348 |
-
persist_directory='db/chroma'
|
| 349 |
-
)
|
| 350 |
-
retriever = vectordb.as_retriever(search_kwargs={"k": 3})
|
| 351 |
-
|
| 352 |
-
def retrieve_docs(query: str) -> str:
|
| 353 |
-
"""Retrieve relevant documentation from the knowledge base"""
|
| 354 |
-
hits = retriever.get_relevant_documents(query)
|
| 355 |
-
if not hits:
|
| 356 |
-
return "No relevant documentation found."
|
| 357 |
-
|
| 358 |
-
results = []
|
| 359 |
-
for doc in hits:
|
| 360 |
-
question = doc.metadata.get('question', 'FAQ')
|
| 361 |
-
results.append(f"**Q: {question}**\nA: {doc.page_content}")
|
| 362 |
-
return "\n\n".join(results)
|
| 363 |
-
|
| 364 |
-
def escalate_ticket(query: str, analysis: str = "") -> str:
|
| 365 |
-
"""Create a ticket for issues that need human intervention"""
|
| 366 |
-
ticket_id = f"TICKET-{random.randint(1000, 9999)}"
|
| 367 |
-
description = f"User Query: {query}\nAnalysis: {analysis}"
|
| 368 |
-
# In a real system, you would send this to a ticketing system like JIRA, ServiceNow, etc.
|
| 369 |
-
logger.info(f"Escalating issue with ticket {ticket_id}: {description}")
|
| 370 |
-
return f"Escalated issue. Created ticket {ticket_id}. A support technician will contact you shortly."
|
| 371 |
-
|
| 372 |
-
# LLM Configuration for DeepSeek
|
| 373 |
-
llm_config = {
|
| 374 |
-
"model": "deepseek-model", # Replace with actual DeepSeek model name
|
| 375 |
-
"api_key": DEEPSEEK_API_KEY,
|
| 376 |
-
"temperature": 0.5, # Example parameter
|
| 377 |
-
}
|
| 378 |
-
|
| 379 |
-
# Agent Definitions (Same structure but using DeepSeek API)
|
| 380 |
-
master_agent = AssistantAgent(
|
| 381 |
-
name="Master",
|
| 382 |
-
llm_config=llm_config,
|
| 383 |
-
system_message="""You are the Master Agent that orchestrates the IT support workflow..."""
|
| 384 |
-
)
|
| 385 |
-
|
| 386 |
-
planning_agent = AssistantAgent(
|
| 387 |
-
name="Planning",
|
| 388 |
-
llm_config=llm_config,
|
| 389 |
-
system_message="""You are the Planning Agent responsible for..."""
|
| 390 |
-
)
|
| 391 |
-
|
| 392 |
-
analysis_agent = AssistantAgent(
|
| 393 |
-
name="Analysis",
|
| 394 |
-
llm_config=llm_config,
|
| 395 |
-
system_message="""You are the Analysis Agent responsible for..."""
|
| 396 |
-
)
|
| 397 |
-
|
| 398 |
-
resolution_agent = AssistantAgent(
|
| 399 |
-
name="Resolution",
|
| 400 |
-
llm_config=llm_config,
|
| 401 |
-
system_message="""You are the Resolution Agent responsible for...""",
|
| 402 |
-
function_map={"retrieve_docs": retrieve_docs}
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
escalation_agent = AssistantAgent(
|
| 406 |
-
name="Escalation",
|
| 407 |
-
llm_config=llm_config,
|
| 408 |
-
system_message="""You are the Escalation Agent responsible for...""",
|
| 409 |
-
function_map={"escalate_ticket": escalate_ticket}
|
| 410 |
-
)
|
| 411 |
-
|
| 412 |
-
def handle_it_query(query: str) -> str:
|
| 413 |
-
"""Process IT queries through the multi-agent workflow"""
|
| 414 |
-
query = query.strip()
|
| 415 |
-
if not query:
|
| 416 |
-
return "Please enter an IT question or issue."
|
| 417 |
-
|
| 418 |
-
workflow_logs = {"query": query}
|
| 419 |
-
|
| 420 |
-
try:
|
| 421 |
-
# First determine if it's an IT issue through the Master Agent
|
| 422 |
-
master_proxy = UserProxyAgent(
|
| 423 |
-
name="MasterProxy", human_input_mode="NEVER", code_execution_config=False
|
| 424 |
-
)
|
| 425 |
-
master_prompt = f"User query: '{query}'. First, determine if this is an IT-related issue."
|
| 426 |
-
master_proxy.initiate_chat(master_agent, message=master_prompt, max_turns=1)
|
| 427 |
-
initial_assessment = master_proxy.chat_messages[master_agent][-1]["content"]
|
| 428 |
-
workflow_logs["initial_assessment"] = initial_assessment
|
| 429 |
-
|
| 430 |
-
# If not IT-related, return the response directly
|
| 431 |
-
if "NOT IT-RELATED" in initial_assessment.upper():
|
| 432 |
-
return initial_assessment
|
| 433 |
-
|
| 434 |
-
# Planning
|
| 435 |
-
plan_proxy = UserProxyAgent(
|
| 436 |
-
name="PlanningProxy", human_input_mode="NEVER", code_execution_config=False
|
| 437 |
-
)
|
| 438 |
-
plan_proxy.initiate_chat(planning_agent, message=query, max_turns=1)
|
| 439 |
-
planning_output = plan_proxy.chat_messages[planning_agent][-1]["content"]
|
| 440 |
-
workflow_logs["planning"] = planning_output
|
| 441 |
-
logger.info(f"Planning completed: {len(planning_output)} chars")
|
| 442 |
-
|
| 443 |
-
# 2: Analysis
|
| 444 |
-
analysis_proxy = UserProxyAgent(
|
| 445 |
-
name="AnalysisProxy", human_input_mode="NEVER", code_execution_config=False
|
| 446 |
-
)
|
| 447 |
-
analysis_proxy.initiate_chat(analysis_agent, message=planning_output, max_turns=1)
|
| 448 |
-
analysis_output = analysis_proxy.chat_messages[analysis_agent][-1]["content"]
|
| 449 |
-
workflow_logs["analysis"] = analysis_output
|
| 450 |
-
logger.info(f"Analysis completed: {len(analysis_output)} chars")
|
| 451 |
-
|
| 452 |
-
# 3: Resolution
|
| 453 |
-
res_proxy = UserProxyAgent(
|
| 454 |
-
name="ResolutionProxy", human_input_mode="NEVER", code_execution_config=False
|
| 455 |
-
)
|
| 456 |
-
resolution_input = f"User Query: {query}\n\nPlanning: {planning_output}\n\nAnalysis: {analysis_output}"
|
| 457 |
-
res_proxy.initiate_chat(resolution_agent, message=resolution_input, max_turns=1)
|
| 458 |
-
resolution_output = res_proxy.chat_messages[resolution_agent][-1]["content"]
|
| 459 |
-
workflow_logs["resolution"] = resolution_output
|
| 460 |
-
logger.info(f"Resolution completed: {len(resolution_output)} chars")
|
| 461 |
-
|
| 462 |
-
# Escalation if needed
|
| 463 |
-
escalation_output = None
|
| 464 |
-
if "ESCALATION NEEDED" in resolution_output.upper():
|
| 465 |
-
esc_proxy = UserProxyAgent(
|
| 466 |
-
name="EscalationProxy", human_input_mode="NEVER", code_execution_config=False
|
| 467 |
-
)
|
| 468 |
-
escalation_input = f"Original Query: {query}\n\nAnalysis: {analysis_output}\n\nResolution Attempt: {resolution_output}"
|
| 469 |
-
esc_proxy.initiate_chat(escalation_agent, message=escalation_input, max_turns=1)
|
| 470 |
-
escalation_output = esc_proxy.chat_messages[escalation_agent][-1]["content"]
|
| 471 |
-
workflow_logs["escalation"] = escalation_output
|
| 472 |
-
logger.info(f"Escalation completed: {len(escalation_output)} chars")
|
| 473 |
-
|
| 474 |
-
# Master summarizes
|
| 475 |
-
final_master_proxy = UserProxyAgent(
|
| 476 |
-
name="FinalMasterProxy", human_input_mode="NEVER", code_execution_config=False
|
| 477 |
-
)
|
| 478 |
-
|
| 479 |
-
if escalation_output:
|
| 480 |
-
final_prompt = (
|
| 481 |
-
f"Complete workflow results for query: '{query}':\n\n"
|
| 482 |
-
f"Planning: {planning_output}\n\n"
|
| 483 |
-
f"Analysis: {analysis_output}\n\n"
|
| 484 |
-
f"Resolution: {resolution_output}\n\n"
|
| 485 |
-
f"Escalation: {escalation_output}\n\n"
|
| 486 |
-
f"Synthesize these results into a clear, helpful response for the user."
|
| 487 |
-
)
|
| 488 |
-
else:
|
| 489 |
-
final_prompt = (
|
| 490 |
-
f"Complete workflow results for query: '{query}':\n\n"
|
| 491 |
-
f"Planning: {planning_output}\n\n"
|
| 492 |
-
f"Analysis: {analysis_output}\n\n"
|
| 493 |
-
f"Resolution: {resolution_output}\n\n"
|
| 494 |
-
f"Synthesize these results into a clear, helpful response for the user."
|
| 495 |
-
)
|
| 496 |
-
|
| 497 |
-
final_master_proxy.initiate_chat(master_agent, message=final_prompt, max_turns=1)
|
| 498 |
-
final_response = final_master_proxy.chat_messages[master_agent][-1]["content"]
|
| 499 |
-
workflow_logs["final_response"] = final_response
|
| 500 |
-
|
| 501 |
-
# Save to memory
|
| 502 |
-
st.session_state.chat_history.append({
|
| 503 |
-
"user": query,
|
| 504 |
-
"assistant": final_response,
|
| 505 |
-
"workflow_logs": workflow_logs
|
| 506 |
-
})
|
| 507 |
-
|
| 508 |
-
return final_response
|
| 509 |
-
|
| 510 |
-
except Exception as e:
|
| 511 |
-
logger.error(f"Error in workflow: {e}", exc_info=True)
|
| 512 |
-
return f"An error occurred during processing: {str(e)}\n\nPlease try rephrasing your question."
|
| 513 |
-
|
| 514 |
-
# Streamlit UI Setup
|
| 515 |
-
st.title("AI Help Desk")
|
| 516 |
-
st.write("Ask any IT support question and our multi-agent system will assist you.")
|
| 517 |
-
|
| 518 |
-
with st.form(key="query_form", clear_on_submit=True):
|
| 519 |
-
user_input = st.text_area("Describe your IT issue:", height=100)
|
| 520 |
-
show_logs = st.checkbox("Show workflow details", value=False)
|
| 521 |
-
submitted = st.form_submit_button("Submit")
|
| 522 |
-
|
| 523 |
-
if submitted:
|
| 524 |
-
if not user_input:
|
| 525 |
-
st.error("Please type a message before submitting.")
|
| 526 |
-
else:
|
| 527 |
-
with st.spinner("Processing your request through our agent workflow..."):
|
| 528 |
-
response = handle_it_query(user_input)
|
| 529 |
-
|
| 530 |
-
st.markdown("### Response")
|
| 531 |
-
st.write(response)
|
|
|
|
| 9 |
import autogen
|
| 10 |
from autogen import AssistantAgent, UserProxyAgent
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
from langchain_community.embeddings import OpenAIEmbeddings
|
| 13 |
from langchain_community.vectorstores import Chroma
|
| 14 |
from langchain.docstore.document import Document
|
|
|
|
| 295 |
st.markdown("### Response")
|
| 296 |
st.write(response)
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|