Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,806 +1,804 @@
|
|
| 1 |
-
|
| 2 |
-
import os
|
| 3 |
-
import json
|
| 4 |
-
import re
|
| 5 |
-
import requests
|
| 6 |
-
from typing import Optional, Any, Dict
|
| 7 |
-
from contextlib import asynccontextmanager
|
| 8 |
-
from fastapi import FastAPI, HTTPException
|
| 9 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
-
from pydantic import BaseModel
|
| 11 |
-
from dotenv import load_dotenv
|
| 12 |
-
from datetime import datetime
|
| 13 |
-
|
| 14 |
-
# KB services (Chroma + sentence-transformers + BM25 hybrid)
|
| 15 |
-
from services.kb_creation import (
|
| 16 |
-
collection,
|
| 17 |
-
ingest_documents,
|
| 18 |
-
hybrid_search_knowledge_base, # new
|
| 19 |
-
)
|
| 20 |
-
|
| 21 |
-
# Optional routers/utilities you already have
|
| 22 |
-
from services.login import router as login_router # login API router
|
| 23 |
-
from services.generate_ticket import get_valid_token, create_incident # ServiceNow helpers
|
| 24 |
-
|
| 25 |
-
VERIFY_SSL = os.getenv("SERVICENOW_SSL_VERIFY", "true").lower() in ("1", "true", "yes")
|
| 26 |
-
GEMINI_SSL_VERIFY = os.getenv("GEMINI_SSL_VERIFY", "true").lower() in ("1", "true", "yes")
|
| 27 |
-
|
| 28 |
-
# ---------------------- Env & App bootstrap ----------------------
|
| 29 |
-
load_dotenv()
|
| 30 |
-
os.environ["POSTHOG_DISABLED"] = "true" # Disable telemetry if present
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
@asynccontextmanager
|
| 34 |
-
async def lifespan(app: FastAPI):
|
| 35 |
-
"""
|
| 36 |
-
On startup: populate KB if empty.
|
| 37 |
-
"""
|
| 38 |
-
try:
|
| 39 |
-
folder_path = os.path.join(os.getcwd(), "documents")
|
| 40 |
-
if collection.count() == 0:
|
| 41 |
-
print("🔎 KB empty. Running ingestion...")
|
| 42 |
-
ingest_documents(folder_path) # walks /documents & ingests .docx
|
| 43 |
-
else:
|
| 44 |
-
print(f"✅ KB already populated with {collection.count()} entries. Skipping ingestion.")
|
| 45 |
-
except Exception as e:
|
| 46 |
-
print(f"⚠️ KB ingestion failed: {e}")
|
| 47 |
-
yield
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
app = FastAPI(lifespan=lifespan)
|
| 51 |
-
app.include_router(login_router)
|
| 52 |
-
|
| 53 |
-
# CORS (adjust origins as needed)
|
| 54 |
-
origins = [
|
| 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 |
-
if
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
if
|
| 141 |
-
m["
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
best_distance =
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
best_combined =
|
| 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 |
-
f'
|
| 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 |
-
.get("
|
| 286 |
-
.
|
| 287 |
-
.
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
return
|
| 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 |
-
f"**
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
"
|
| 448 |
-
"
|
| 449 |
-
"
|
| 450 |
-
"
|
| 451 |
-
"
|
| 452 |
-
"
|
| 453 |
-
"
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
"
|
| 466 |
-
"•
|
| 467 |
-
"•
|
| 468 |
-
|
| 469 |
-
"
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
"
|
| 474 |
-
"
|
| 475 |
-
"
|
| 476 |
-
"
|
| 477 |
-
"
|
| 478 |
-
"
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
"
|
| 510 |
-
"
|
| 511 |
-
"
|
| 512 |
-
"
|
| 513 |
-
"
|
| 514 |
-
"
|
| 515 |
-
"
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
"
|
| 524 |
-
"
|
| 525 |
-
"
|
| 526 |
-
"
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
"
|
| 530 |
-
"-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
result =
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
"
|
| 569 |
-
"
|
| 570 |
-
"
|
| 571 |
-
"
|
| 572 |
-
"
|
| 573 |
-
"
|
| 574 |
-
"
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
"
|
| 578 |
-
"
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
except
|
| 585 |
-
raise
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
#
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
"
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
print(f"[SN PATCH progress]
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
"
|
| 637 |
-
"
|
| 638 |
-
"
|
| 639 |
-
"
|
| 640 |
-
"
|
| 641 |
-
"
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
"
|
| 653 |
-
"
|
| 654 |
-
"
|
| 655 |
-
"
|
| 656 |
-
"
|
| 657 |
-
"
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
"
|
| 675 |
-
"
|
| 676 |
-
"
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
sys_id
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
ticket_text =
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
"
|
| 711 |
-
"
|
| 712 |
-
"
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
"
|
| 726 |
-
"
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
}
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
f"**
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
"
|
| 801 |
-
"
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
except Exception as e:
|
| 806 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import requests
|
| 6 |
+
from typing import Optional, Any, Dict
|
| 7 |
+
from contextlib import asynccontextmanager
|
| 8 |
+
from fastapi import FastAPI, HTTPException
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
|
| 14 |
+
# KB services (Chroma + sentence-transformers + BM25 hybrid)
|
| 15 |
+
from services.kb_creation import (
|
| 16 |
+
collection,
|
| 17 |
+
ingest_documents,
|
| 18 |
+
hybrid_search_knowledge_base, # new
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Optional routers/utilities you already have
|
| 22 |
+
from services.login import router as login_router # login API router
|
| 23 |
+
from services.generate_ticket import get_valid_token, create_incident # ServiceNow helpers
|
| 24 |
+
|
| 25 |
+
VERIFY_SSL = os.getenv("SERVICENOW_SSL_VERIFY", "true").lower() in ("1", "true", "yes")
|
| 26 |
+
GEMINI_SSL_VERIFY = os.getenv("GEMINI_SSL_VERIFY", "true").lower() in ("1", "true", "yes")
|
| 27 |
+
|
| 28 |
+
# ---------------------- Env & App bootstrap ----------------------
|
| 29 |
+
load_dotenv()
|
| 30 |
+
os.environ["POSTHOG_DISABLED"] = "true" # Disable telemetry if present
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@asynccontextmanager
|
| 34 |
+
async def lifespan(app: FastAPI):
|
| 35 |
+
"""
|
| 36 |
+
On startup: populate KB if empty.
|
| 37 |
+
"""
|
| 38 |
+
try:
|
| 39 |
+
folder_path = os.path.join(os.getcwd(), "documents")
|
| 40 |
+
if collection.count() == 0:
|
| 41 |
+
print("🔎 KB empty. Running ingestion...")
|
| 42 |
+
ingest_documents(folder_path) # walks /documents & ingests .docx
|
| 43 |
+
else:
|
| 44 |
+
print(f"✅ KB already populated with {collection.count()} entries. Skipping ingestion.")
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"⚠️ KB ingestion failed: {e}")
|
| 47 |
+
yield
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
app = FastAPI(lifespan=lifespan)
|
| 51 |
+
app.include_router(login_router)
|
| 52 |
+
|
| 53 |
+
# CORS (adjust origins as needed)
|
| 54 |
+
origins = [
|
| 55 |
+
"https://chatbotnova-chatbot-frontend.hf.space",
|
| 56 |
+
]
|
| 57 |
+
app.add_middleware(
|
| 58 |
+
CORSMiddleware,
|
| 59 |
+
allow_origins=origins,
|
| 60 |
+
allow_credentials=True,
|
| 61 |
+
allow_methods=["*"],
|
| 62 |
+
allow_headers=["*"],
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# ---------------------- Models ----------------------
|
| 66 |
+
class ChatInput(BaseModel):
|
| 67 |
+
user_message: str
|
| 68 |
+
prev_status: Optional[str] = None # "NO_KB_MATCH" | "PARTIAL" | "OK" | None
|
| 69 |
+
last_issue: Optional[str] = None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class IncidentInput(BaseModel):
|
| 73 |
+
short_description: str
|
| 74 |
+
description: str
|
| 75 |
+
mark_resolved: Optional[bool] = False
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class TicketDescInput(BaseModel):
|
| 79 |
+
issue: str
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class TicketStatusInput(BaseModel):
|
| 83 |
+
sys_id: Optional[str] = None
|
| 84 |
+
number: Optional[str] = None # IncidentID (incident number)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ✅ Human‑readable mapping for ServiceNow incident state codes
|
| 88 |
+
STATE_MAP = {
|
| 89 |
+
"1": "New",
|
| 90 |
+
"2": "In Progress",
|
| 91 |
+
"3": "On Hold",
|
| 92 |
+
"6": "Resolved",
|
| 93 |
+
"7": "Closed",
|
| 94 |
+
"8": "Canceled",
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
# ---------------------- Gemini setup ----------------------
|
| 98 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 99 |
+
GEMINI_URL = (
|
| 100 |
+
f"https://generativelanguage.googleapis.com/v1beta/models/"
|
| 101 |
+
f"gemini-2.5-flash-lite:generateContent?key={GEMINI_API_KEY}"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# ---------------------- Helpers: KB context merge + sanitation ----------------------
|
| 105 |
+
def extract_kb_context(kb_results: Optional[Dict[str, Any]], top_chunks: int = 2) -> Dict[str, Any]:
|
| 106 |
+
"""
|
| 107 |
+
Merge documents + metadatas + distances.
|
| 108 |
+
If documents are missing but ids exist, fetch via collection.get (rare).
|
| 109 |
+
Supports hybrid fields: 'combined_scores' in results.
|
| 110 |
+
"""
|
| 111 |
+
if not kb_results or not isinstance(kb_results, dict):
|
| 112 |
+
return {"context": "", "sources": [], "top_hits": [], "context_found": False, "best_score": None, "best_combined": None}
|
| 113 |
+
|
| 114 |
+
documents = kb_results.get("documents") or []
|
| 115 |
+
metadatas = kb_results.get("metadatas") or []
|
| 116 |
+
distances = kb_results.get("distances") or []
|
| 117 |
+
ids = kb_results.get("ids") or []
|
| 118 |
+
combined = kb_results.get("combined_scores") or []
|
| 119 |
+
|
| 120 |
+
# Fallback fetch by ids if needed
|
| 121 |
+
if (not documents) and ids:
|
| 122 |
+
try:
|
| 123 |
+
fetched = collection.get(ids=ids, include=['documents', 'metadatas'])
|
| 124 |
+
documents = fetched.get('documents', []) or []
|
| 125 |
+
metadatas = fetched.get('metadatas', []) or metadatas
|
| 126 |
+
except Exception:
|
| 127 |
+
pass
|
| 128 |
+
|
| 129 |
+
items = []
|
| 130 |
+
for i, doc in enumerate(documents):
|
| 131 |
+
text = doc.strip() if isinstance(doc, str) else ""
|
| 132 |
+
if not text:
|
| 133 |
+
continue
|
| 134 |
+
meta = metadatas[i] if i < len(metadatas) and isinstance(metadatas[i], dict) else {}
|
| 135 |
+
score = distances[i] if i < len(distances) else None
|
| 136 |
+
comb = combined[i] if i < len(combined) else None
|
| 137 |
+
m = dict(meta)
|
| 138 |
+
if score is not None:
|
| 139 |
+
m["distance"] = score
|
| 140 |
+
if comb is not None:
|
| 141 |
+
m["combined"] = comb
|
| 142 |
+
items.append({"text": text, "meta": m})
|
| 143 |
+
|
| 144 |
+
selected = items[:max(1, top_chunks)]
|
| 145 |
+
context = "\n\n---\n\n".join([s["text"] for s in selected]) if selected else ""
|
| 146 |
+
sources = [s["meta"] for s in selected]
|
| 147 |
+
|
| 148 |
+
# best (lower distance is better, higher combined is better)
|
| 149 |
+
best_distance = None
|
| 150 |
+
if distances:
|
| 151 |
+
try:
|
| 152 |
+
best_distance = min([d for d in distances if d is not None])
|
| 153 |
+
except Exception:
|
| 154 |
+
best_distance = None
|
| 155 |
+
|
| 156 |
+
best_combined = None
|
| 157 |
+
if combined:
|
| 158 |
+
try:
|
| 159 |
+
best_combined = max([c for c in combined if c is not None])
|
| 160 |
+
except Exception:
|
| 161 |
+
best_combined = None
|
| 162 |
+
|
| 163 |
+
return {
|
| 164 |
+
"context": context,
|
| 165 |
+
"sources": sources,
|
| 166 |
+
"top_hits": [], # hidden in UI
|
| 167 |
+
"context_found": bool(selected),
|
| 168 |
+
"best_score": best_distance,
|
| 169 |
+
"best_combined": best_combined,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _strip_any_source_lines(text: str) -> str:
|
| 174 |
+
lines = text.splitlines()
|
| 175 |
+
kept = []
|
| 176 |
+
for ln in lines:
|
| 177 |
+
if re.match(r"^\s*source\s*:", ln, flags=re.IGNORECASE):
|
| 178 |
+
continue
|
| 179 |
+
kept.append(ln)
|
| 180 |
+
return "\n".join(kept).strip()
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _build_clarifying_message() -> str:
|
| 184 |
+
return (
|
| 185 |
+
"I couldn’t find matching content in the KB yet. To help me narrow it down, please share:\n\n"
|
| 186 |
+
"• Module/area (e.g., Picking, Receiving, Trailer Close)\n"
|
| 187 |
+
"• Exact error message text/code (copy-paste)\n"
|
| 188 |
+
"• IDs involved (Order#, Load ID, Shipment#, Item#)\n"
|
| 189 |
+
"• Warehouse/site & environment (prod/test)\n"
|
| 190 |
+
"• When it started and how many users are impacted\n\n"
|
| 191 |
+
"Reply with these details and I’ll search again."
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# ---------------------- Intent helpers ----------------------
|
| 195 |
+
def _build_tracking_descriptions(issue_text: str, resolved_text: str) -> tuple[str, str]:
|
| 196 |
+
"""
|
| 197 |
+
Short: first 100 chars of the ORIGINAL issue text (preferred).
|
| 198 |
+
Long: clear sentence that includes both original issue and resolved ack.
|
| 199 |
+
"""
|
| 200 |
+
issue = (issue_text or "").strip()
|
| 201 |
+
resolved = (resolved_text or "").strip()
|
| 202 |
+
short_desc = issue[:100] if issue else (resolved[:100] or "Issue resolved (user confirmation)")
|
| 203 |
+
long_desc = (
|
| 204 |
+
f'User reported: "{issue}". '
|
| 205 |
+
f'User confirmation: "{resolved}". '
|
| 206 |
+
f'Tracking record created automatically by NOVA.'
|
| 207 |
+
).strip()
|
| 208 |
+
return short_desc, long_desc
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _is_incident_intent(msg_norm: str) -> bool:
|
| 212 |
+
intent_phrases = [
|
| 213 |
+
"create ticket", "create a ticket", "raise ticket", "raise a ticket", "open ticket", "open a ticket",
|
| 214 |
+
"create incident", "create an incident", "raise incident", "raise an incident", "open incident", "open an incident",
|
| 215 |
+
"log ticket", "log an incident", "generate ticket", "create snow ticket", "raise snow ticket",
|
| 216 |
+
"raise service now ticket", "create service now ticket", "raise sr", "open sr",
|
| 217 |
+
]
|
| 218 |
+
return any(p in msg_norm for p in intent_phrases)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _is_feedback_message(msg_norm: str) -> bool:
|
| 222 |
+
feedback_phrases = [
|
| 223 |
+
"issue not resolved", "not resolved", "still not working",
|
| 224 |
+
"same issue", "no change", "didn't work", "doesn't work",
|
| 225 |
+
"not fixed", "still failing", "failed again",
|
| 226 |
+
]
|
| 227 |
+
return any(p in msg_norm for p in feedback_phrases)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _parse_ticket_status_intent(msg_norm: str) -> Dict[str, Optional[str]]:
|
| 231 |
+
status_keywords = [
|
| 232 |
+
"status", "ticket status", "incident status",
|
| 233 |
+
"check status", "check ticket status", "check incident status",
|
| 234 |
+
]
|
| 235 |
+
if not any(k in msg_norm for k in status_keywords):
|
| 236 |
+
return {} # not a status intent
|
| 237 |
+
|
| 238 |
+
patterns = [
|
| 239 |
+
r"(?:incident\s*id|incidentid|ticket\s*number|number)\s*[:=]?\s*(inc\d+)",
|
| 240 |
+
r"(inc\d+)",
|
| 241 |
+
]
|
| 242 |
+
for pat in patterns:
|
| 243 |
+
m = re.search(pat, msg_norm, flags=re.IGNORECASE)
|
| 244 |
+
if m:
|
| 245 |
+
val = m.group(1).strip()
|
| 246 |
+
if val:
|
| 247 |
+
return {"number": val.upper() if val.lower().startswith("inc") else val}
|
| 248 |
+
return {"number": None, "ask_number": True}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _is_resolution_ack_heuristic(msg_norm: str) -> bool:
|
| 252 |
+
phrases = [
|
| 253 |
+
"it is resolved", "resolved", "issue resolved", "problem resolved",
|
| 254 |
+
"it's working", "working now", "works now", "fixed", "sorted",
|
| 255 |
+
"ok now", "fine now", "all good", "all set", "thanks works", "thank you it works", "back to normal",
|
| 256 |
+
]
|
| 257 |
+
return any(p in msg_norm for p in phrases)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _has_negation_resolved(msg_norm: str) -> bool:
|
| 261 |
+
neg_phrases = [
|
| 262 |
+
"not resolved", "issue not resolved", "still not working", "not working",
|
| 263 |
+
"didn't work", "doesn't work", "no change", "not fixed", "still failing", "failed again", "broken", "fail",
|
| 264 |
+
]
|
| 265 |
+
return any(p in msg_norm for p in neg_phrases)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _classify_resolution_llm(user_message: str) -> bool:
|
| 269 |
+
if not GEMINI_API_KEY:
|
| 270 |
+
return False
|
| 271 |
+
prompt = (
|
| 272 |
+
"Classify if the following user message indicates that the issue is resolved or working now.\n"
|
| 273 |
+
"Return only 'true' or 'false'.\n\n"
|
| 274 |
+
f"Message: {user_message}"
|
| 275 |
+
)
|
| 276 |
+
headers = {"Content-Type": "application/json"}
|
| 277 |
+
payload = {"contents": [{"parts": [{"text": prompt}]}]}
|
| 278 |
+
try:
|
| 279 |
+
resp = requests.post(GEMINI_URL, headers=headers, json=payload, timeout=12, verify=GEMINI_SSL_VERIFY)
|
| 280 |
+
data = resp.json()
|
| 281 |
+
text = (
|
| 282 |
+
data.get("candidates", [{}])[0]
|
| 283 |
+
.get("content", {})
|
| 284 |
+
.get("parts", [{}])[0]
|
| 285 |
+
.get("text", "")
|
| 286 |
+
.strip()
|
| 287 |
+
.lower()
|
| 288 |
+
)
|
| 289 |
+
return "true" in text
|
| 290 |
+
except Exception:
|
| 291 |
+
return False
|
| 292 |
+
|
| 293 |
+
# ---------------------- Health ----------------------
|
| 294 |
+
@app.get("/")
|
| 295 |
+
async def health_check():
|
| 296 |
+
return {"status": "ok"}
|
| 297 |
+
|
| 298 |
+
# ---------------------- Chat endpoint ----------------------
|
| 299 |
+
@app.post("/chat")
|
| 300 |
+
async def chat_with_ai(input_data: ChatInput):
|
| 301 |
+
"""
|
| 302 |
+
Policy:
|
| 303 |
+
A) If 'resolved/working' detected → auto-create tracking incident, auto-mark Resolved, and ask if further help needed.
|
| 304 |
+
B) If user intent is 'create ticket' → offer incident form (Yes/No).
|
| 305 |
+
C) Ticket status intent → if number missing, ask for it; else return status from ServiceNow.
|
| 306 |
+
D) Feedback-only → ask details (or offer incident on second try) without KB search.
|
| 307 |
+
E) Otherwise, use HYBRID search; rewrite answer from KB only; ask resolved if 'OK', or refine if 'PARTIAL'.
|
| 308 |
+
"""
|
| 309 |
+
try:
|
| 310 |
+
msg_norm = (input_data.user_message or "").lower().strip()
|
| 311 |
+
|
| 312 |
+
# --- Handle Yes/No replies from the UI ---
|
| 313 |
+
if msg_norm in ("yes", "y", "sure", "ok", "okay"):
|
| 314 |
+
return {
|
| 315 |
+
"bot_response": (
|
| 316 |
+
"Great! Tell me what you’d like to do next — check another ticket, "
|
| 317 |
+
"create an incident, or describe your issue."
|
| 318 |
+
),
|
| 319 |
+
"status": "OK",
|
| 320 |
+
"followup": "You can say: 'create ticket', 'incident status INC0012345', or describe your problem.",
|
| 321 |
+
"options": [],
|
| 322 |
+
"debug": {"intent": "continue_conversation"},
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
if msg_norm in ("no", "no thanks", "nope"):
|
| 326 |
+
return {
|
| 327 |
+
"bot_response": "Glad I could help! 👋 If you need anything else later, just let me know.",
|
| 328 |
+
"status": "OK",
|
| 329 |
+
"end_chat": True,
|
| 330 |
+
"followup": None,
|
| 331 |
+
"options": [],
|
| 332 |
+
"debug": {"intent": "end_conversation"},
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
# --- (A) Resolution acknowledgement
|
| 336 |
+
is_llm_resolved = _classify_resolution_llm(input_data.user_message)
|
| 337 |
+
if _has_negation_resolved(msg_norm):
|
| 338 |
+
is_llm_resolved = False
|
| 339 |
+
|
| 340 |
+
if (not _has_negation_resolved(msg_norm)) and (_is_resolution_ack_heuristic(msg_norm) or is_llm_resolved):
|
| 341 |
+
try:
|
| 342 |
+
short_desc, long_desc = _build_tracking_descriptions(input_data.last_issue, input_data.user_message)
|
| 343 |
+
result = create_incident(short_desc, long_desc) # ServiceNow helper
|
| 344 |
+
if isinstance(result, dict) and not result.get("error"):
|
| 345 |
+
inc_number = result.get("number", "<unknown>")
|
| 346 |
+
sys_id = result.get("sys_id")
|
| 347 |
+
# Auto-mark resolved (state=6) if we have sys_id
|
| 348 |
+
resolved_note = ""
|
| 349 |
+
if sys_id:
|
| 350 |
+
ok = _set_incident_resolved(sys_id)
|
| 351 |
+
resolved_note = " (marked Resolved)" if ok else " (could not mark Resolved; please update manually)"
|
| 352 |
+
return {
|
| 353 |
+
"bot_response": f"✅ Incident created: {inc_number}{resolved_note}",
|
| 354 |
+
"status": "OK",
|
| 355 |
+
"context_found": False,
|
| 356 |
+
"ask_resolved": False,
|
| 357 |
+
"suggest_incident": False,
|
| 358 |
+
"followup": None,
|
| 359 |
+
"top_hits": [],
|
| 360 |
+
"sources": [],
|
| 361 |
+
"auto_incident": True,
|
| 362 |
+
"debug": {"intent": "resolved_ack", "auto_created": True},
|
| 363 |
+
}
|
| 364 |
+
else:
|
| 365 |
+
err = (result or {}).get("error", "Unknown error")
|
| 366 |
+
return {
|
| 367 |
+
"bot_response": f"⚠️ I couldn’t create the tracking incident automatically ({err}). Would you like me to try again?",
|
| 368 |
+
"status": "PARTIAL",
|
| 369 |
+
"context_found": False,
|
| 370 |
+
"ask_resolved": False,
|
| 371 |
+
"suggest_incident": True,
|
| 372 |
+
"followup": "Shall I create a ticket now?",
|
| 373 |
+
"top_hits": [],
|
| 374 |
+
"sources": [],
|
| 375 |
+
"debug": {"intent": "resolved_ack", "auto_created": False, "error": err},
|
| 376 |
+
}
|
| 377 |
+
except Exception as e:
|
| 378 |
+
return {
|
| 379 |
+
"bot_response": f"⚠️ Something went wrong while creating the tracking incident: {str(e)}",
|
| 380 |
+
"status": "PARTIAL",
|
| 381 |
+
"context_found": False,
|
| 382 |
+
"ask_resolved": False,
|
| 383 |
+
"suggest_incident": True,
|
| 384 |
+
"followup": "Shall I create a ticket now?",
|
| 385 |
+
"top_hits": [],
|
| 386 |
+
"sources": [],
|
| 387 |
+
"debug": {"intent": "resolved_ack", "exception": True},
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
# --- (B) Incident intent
|
| 391 |
+
if _is_incident_intent(msg_norm):
|
| 392 |
+
return {
|
| 393 |
+
"bot_response": "Okay. Shall I create a ServiceNow incident now?",
|
| 394 |
+
"status": (input_data.prev_status or "PARTIAL"),
|
| 395 |
+
"context_found": False,
|
| 396 |
+
"ask_resolved": False,
|
| 397 |
+
"suggest_incident": True,
|
| 398 |
+
"followup": "Shall I create a ticket now?",
|
| 399 |
+
"top_hits": [],
|
| 400 |
+
"sources": [],
|
| 401 |
+
"debug": {"intent": "create_ticket"},
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
# --- (C) Ticket status intent
|
| 405 |
+
status_intent = _parse_ticket_status_intent(msg_norm)
|
| 406 |
+
if status_intent:
|
| 407 |
+
if status_intent.get("ask_number"):
|
| 408 |
+
return {
|
| 409 |
+
"bot_response": "Please share the Incident ID (e.g., INC0012345) to check the status.",
|
| 410 |
+
"status": "PARTIAL",
|
| 411 |
+
"context_found": False,
|
| 412 |
+
"ask_resolved": False,
|
| 413 |
+
"suggest_incident": False,
|
| 414 |
+
"followup": "Provide the Incident ID and I’ll fetch the status.",
|
| 415 |
+
"top_hits": [],
|
| 416 |
+
"sources": [],
|
| 417 |
+
"debug": {"intent": "status_request_missing_id"},
|
| 418 |
+
}
|
| 419 |
+
try:
|
| 420 |
+
token = get_valid_token()
|
| 421 |
+
instance_url = os.getenv("SERVICENOW_INSTANCE_URL")
|
| 422 |
+
if not instance_url:
|
| 423 |
+
raise HTTPException(status_code=500, detail="SERVICENOW_INSTANCE_URL missing")
|
| 424 |
+
|
| 425 |
+
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
|
| 426 |
+
number = status_intent.get("number")
|
| 427 |
+
url = f"{instance_url}/api/now/table/incident?number={number}"
|
| 428 |
+
response = requests.get(url, headers=headers, verify=VERIFY_SSL, timeout=25)
|
| 429 |
+
data = response.json()
|
| 430 |
+
lst = data.get("result", [])
|
| 431 |
+
result = (lst or [{}])[0] if response.status_code == 200 else {}
|
| 432 |
+
|
| 433 |
+
state_code = str(result.get("state", "unknown"))
|
| 434 |
+
state_label = STATE_MAP.get(state_code, state_code)
|
| 435 |
+
short = result.get("short_description", "")
|
| 436 |
+
num = result.get("number", number or "unknown")
|
| 437 |
+
|
| 438 |
+
# ✅ Use bold labels + hard line breaks so lines appear separately in Markdown
|
| 439 |
+
return {
|
| 440 |
+
"bot_response": (
|
| 441 |
+
f"**Ticket:** {num} \n"
|
| 442 |
+
f"**Status:** {state_label} \n"
|
| 443 |
+
f"**Issue description:** {short}"
|
| 444 |
+
),
|
| 445 |
+
"status": "OK",
|
| 446 |
+
"show_assist_card": True, # <— triggers Yes/No card
|
| 447 |
+
"context_found": False,
|
| 448 |
+
"ask_resolved": False,
|
| 449 |
+
"suggest_incident": False,
|
| 450 |
+
"followup": "Is there anything else I can assist you with?",
|
| 451 |
+
"top_hits": [],
|
| 452 |
+
"sources": [],
|
| 453 |
+
"debug": {"intent": "status", "http_status": response.status_code},
|
| 454 |
+
}
|
| 455 |
+
except Exception as e:
|
| 456 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 457 |
+
|
| 458 |
+
# --- (D) Feedback-only messages
|
| 459 |
+
if _is_feedback_message(msg_norm):
|
| 460 |
+
second_try = (input_data.prev_status or "").upper() == "NO_KB_MATCH"
|
| 461 |
+
return {
|
| 462 |
+
"bot_response": (
|
| 463 |
+
"Understood. To refine the steps, please share:\n"
|
| 464 |
+
"• Exact error text/code\n"
|
| 465 |
+
"• IDs (Order#, Load ID, Shipment#)\n"
|
| 466 |
+
"• Site & environment (prod/test)\n"
|
| 467 |
+
"• When it started and how many users are impacted"
|
| 468 |
+
if not second_try else
|
| 469 |
+
"It still looks unresolved after clarification.\n\nWould you like me to raise a ServiceNow incident?"
|
| 470 |
+
),
|
| 471 |
+
"status": "NO_KB_MATCH",
|
| 472 |
+
"context_found": False,
|
| 473 |
+
"ask_resolved": False,
|
| 474 |
+
"suggest_incident": bool(second_try),
|
| 475 |
+
"followup": ("Please reply with the above details." if not second_try else "Shall I create a ticket now?"),
|
| 476 |
+
"top_hits": [],
|
| 477 |
+
"sources": [],
|
| 478 |
+
"debug": {"feedback_only": True, "second_try": second_try},
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
# --- (E) HYBRID KB search & rewrite ---
|
| 482 |
+
kb_results = hybrid_search_knowledge_base(input_data.user_message, top_k=10, alpha=0.6, beta=0.4)
|
| 483 |
+
kb_ctx = extract_kb_context(kb_results, top_chunks=2)
|
| 484 |
+
context = kb_ctx.get("context", "") or ""
|
| 485 |
+
context_found = bool(kb_ctx.get("context_found", False))
|
| 486 |
+
best_distance = kb_ctx.get("best_score") # lower = better
|
| 487 |
+
best_combined = kb_ctx.get("best_combined") # higher = better
|
| 488 |
+
|
| 489 |
+
# Dynamic gating based on combined score primarily, distance secondarily
|
| 490 |
+
short_query = len((input_data.user_message or "").split()) <= 4
|
| 491 |
+
gate_combined_no_kb = 0.22 if short_query else 0.28 # below this → NO_KB
|
| 492 |
+
gate_combined_ok = 0.60 if short_query else 0.55 # above this → OK
|
| 493 |
+
gate_distance_no_kb = 2.0 # if semantic distance is very high, treat carefully
|
| 494 |
+
|
| 495 |
+
if (not context_found or not context.strip()) or (
|
| 496 |
+
(best_combined is None or best_combined < gate_combined_no_kb)
|
| 497 |
+
and (best_distance is None or best_distance >= gate_distance_no_kb)
|
| 498 |
+
):
|
| 499 |
+
second_try = (input_data.prev_status or "").upper() == "NO_KB_MATCH"
|
| 500 |
+
clarify_text = (
|
| 501 |
+
_build_clarifying_message()
|
| 502 |
+
if not second_try
|
| 503 |
+
else "I still don’t find a relevant KB match for this scenario even after clarification.\n\n"
|
| 504 |
+
"Would you like me to raise a ServiceNow incident?"
|
| 505 |
+
)
|
| 506 |
+
return {
|
| 507 |
+
"bot_response": clarify_text,
|
| 508 |
+
"status": "NO_KB_MATCH",
|
| 509 |
+
"context_found": False,
|
| 510 |
+
"ask_resolved": False,
|
| 511 |
+
"suggest_incident": bool(second_try),
|
| 512 |
+
"followup": ("Please reply with the above details." if not second_try else "Shall I create a ticket now?"),
|
| 513 |
+
"top_hits": [],
|
| 514 |
+
"sources": [],
|
| 515 |
+
"debug": {"used_chunks": 0, "second_try": second_try, "best_distance": best_distance, "best_combined": best_combined},
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
# We have KB context → LLM rewrite (KB‑only, no Source lines)
|
| 519 |
+
threshold_ok = gate_combined_ok # use combined score as the primary signal
|
| 520 |
+
enhanced_prompt = (
|
| 521 |
+
"Rewrite the following knowledge base context into clear, actionable steps for the user's question. "
|
| 522 |
+
"Use ONLY the provided context; do NOT add information that is not present in it. "
|
| 523 |
+
"If the context is incomplete, say that the answer may be partial. "
|
| 524 |
+
"Do NOT include any 'Source:' or citation lines in your output.\n\n"
|
| 525 |
+
f"### Context\n{context}\n\n"
|
| 526 |
+
f"### Question\n{input_data.user_message}\n\n"
|
| 527 |
+
"### Output\n"
|
| 528 |
+
"- Provide numbered steps or concise bullets.\n"
|
| 529 |
+
"- Mention any prerequisites or validations only if present in the context.\n"
|
| 530 |
+
"- If context is insufficient, add a one-line note: 'This may be partial based on available KB.'\n"
|
| 531 |
+
)
|
| 532 |
+
headers = {"Content-Type": "application/json"}
|
| 533 |
+
payload = {"contents": [{"parts": [{"text": enhanced_prompt}]}]}
|
| 534 |
+
try:
|
| 535 |
+
resp = requests.post(GEMINI_URL, headers=headers, json=payload, timeout=25, verify=VERIFY_SSL)
|
| 536 |
+
try:
|
| 537 |
+
result = resp.json()
|
| 538 |
+
except Exception:
|
| 539 |
+
result = {}
|
| 540 |
+
except Exception:
|
| 541 |
+
resp = type("RespStub", (), {"status_code": 0})()
|
| 542 |
+
result = {}
|
| 543 |
+
|
| 544 |
+
try:
|
| 545 |
+
bot_text = (
|
| 546 |
+
result["candidates"][0]["content"]["parts"][0]["text"]
|
| 547 |
+
if isinstance(result, dict) else ""
|
| 548 |
+
)
|
| 549 |
+
except Exception:
|
| 550 |
+
bot_text = ""
|
| 551 |
+
|
| 552 |
+
if not bot_text.strip():
|
| 553 |
+
bot_text = context
|
| 554 |
+
|
| 555 |
+
bot_text = _strip_any_source_lines(bot_text)
|
| 556 |
+
status = "OK" if (best_combined is not None and best_combined >= threshold_ok) else "PARTIAL"
|
| 557 |
+
lower = bot_text.lower()
|
| 558 |
+
if ("partial" in lower) or ("may be partial" in lower) or ("closest" in lower) or ("may not fully" in lower):
|
| 559 |
+
status = "PARTIAL"
|
| 560 |
+
|
| 561 |
+
ask_resolved = (status == "OK")
|
| 562 |
+
suggest_incident = False
|
| 563 |
+
followup = ("Does this match your scenario? I can refine the steps." if status == "PARTIAL" else None)
|
| 564 |
+
|
| 565 |
+
return {
|
| 566 |
+
"bot_response": bot_text,
|
| 567 |
+
"status": status,
|
| 568 |
+
"context_found": True,
|
| 569 |
+
"ask_resolved": ask_resolved,
|
| 570 |
+
"suggest_incident": suggest_incident,
|
| 571 |
+
"followup": followup,
|
| 572 |
+
"top_hits": [],
|
| 573 |
+
"sources": [],
|
| 574 |
+
"debug": {
|
| 575 |
+
"used_chunks": len(context.split("\n\n---\n\n")) if context else 0,
|
| 576 |
+
"best_distance": best_distance,
|
| 577 |
+
"best_combined": best_combined,
|
| 578 |
+
"http_status": getattr(resp, "status_code", 0),
|
| 579 |
+
},
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
except HTTPException:
|
| 583 |
+
raise
|
| 584 |
+
except Exception as e:
|
| 585 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
# ---------------------- Incident endpoints ----------------------
|
| 589 |
+
def _set_incident_resolved(sys_id: str) -> bool:
|
| 590 |
+
"""
|
| 591 |
+
Robust resolver:
|
| 592 |
+
A) Try default fields (close_code/close_notes/caller_id) with state=6
|
| 593 |
+
B) If fails, try state="Resolved"
|
| 594 |
+
C) If still fails, try custom field names from env (e.g., u_resolution_code/u_resolution_notes)
|
| 595 |
+
Optional: pre-step to In Progress if SERVICENOW_REQUIRE_IN_PROGRESS_FIRST=true
|
| 596 |
+
Logs a short diagnostic line on failure so we can see the exact reason.
|
| 597 |
+
"""
|
| 598 |
+
try:
|
| 599 |
+
# 1) Get an OAuth token the same way you already do for other ServiceNow calls
|
| 600 |
+
token = get_valid_token()
|
| 601 |
+
# 2) Read your instance URL from env
|
| 602 |
+
instance_url = os.getenv("SERVICENOW_INSTANCE_URL")
|
| 603 |
+
if not instance_url:
|
| 604 |
+
print("[SN PATCH resolve] missing SERVICENOW_INSTANCE_URL")
|
| 605 |
+
return False
|
| 606 |
+
|
| 607 |
+
headers = {
|
| 608 |
+
"Authorization": f"Bearer {token}",
|
| 609 |
+
"Accept": "application/json",
|
| 610 |
+
"Content-Type": "application/json",
|
| 611 |
+
}
|
| 612 |
+
url = f"{instance_url}/api/now/table/incident/{sys_id}"
|
| 613 |
+
|
| 614 |
+
close_code_val = os.getenv("SERVICENOW_CLOSE_CODE", "Solution provided")
|
| 615 |
+
close_notes_val = os.getenv("SERVICENOW_RESOLUTION_NOTES", "Issue resolved, user confirmed")
|
| 616 |
+
caller_sysid = os.getenv("SERVICENOW_CALLER_SYSID")
|
| 617 |
+
resolved_by_sysid = os.getenv("SERVICENOW_RESOLVED_BY_SYSID") # optional
|
| 618 |
+
assign_group = os.getenv("SERVICENOW_ASSIGNMENT_GROUP_SYSID") # optional
|
| 619 |
+
require_progress = os.getenv("SERVICENOW_REQUIRE_IN_PROGRESS_FIRST", "false").lower() in ("1", "true", "yes")
|
| 620 |
+
|
| 621 |
+
# Optional pre-step: set state=2 (In Progress) if your org enforces transitions
|
| 622 |
+
if require_progress:
|
| 623 |
+
try:
|
| 624 |
+
resp1 = requests.patch(url, headers=headers, json={"state": "2"}, verify=VERIFY_SSL, timeout=25) # <-- use VERIFY_SSL
|
| 625 |
+
print(f"[SN PATCH progress] status={resp1.status_code} body={resp1.text[:500]}")
|
| 626 |
+
except Exception as e:
|
| 627 |
+
print(f"[SN PATCH progress] exception={str(e)}")
|
| 628 |
+
|
| 629 |
+
# Helper to clean payload
|
| 630 |
+
def clean(d: dict) -> dict:
|
| 631 |
+
return {k: v for k, v in d.items() if v is not None}
|
| 632 |
+
|
| 633 |
+
payload_A = clean({
|
| 634 |
+
"state": "6", # numeric Resolved
|
| 635 |
+
"close_code": close_code_val, # Resolution code (default field name)
|
| 636 |
+
"close_notes": close_notes_val, # Resolution notes (default field name)
|
| 637 |
+
"caller_id": caller_sysid, # mandatory in your org
|
| 638 |
+
"resolved_at": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
|
| 639 |
+
"work_notes": "Auto-resolve set by NOVA.",
|
| 640 |
+
"resolved_by": resolved_by_sysid, # optional if BR requires who resolved
|
| 641 |
+
"assignment_group": assign_group, # optional if BR requires a group
|
| 642 |
+
})
|
| 643 |
+
respA = requests.patch(url, headers=headers, json=payload_A, verify=VERIFY_SSL, timeout=25)
|
| 644 |
+
if respA.status_code in (200, 204):
|
| 645 |
+
return True
|
| 646 |
+
print(f"[SN PATCH resolve A] status={respA.status_code} body={respA.text[:500]}")
|
| 647 |
+
|
| 648 |
+
# ---- B) PATCH with state label (some orgs map differently)
|
| 649 |
+
payload_B = clean({
|
| 650 |
+
"state": "Resolved", # label instead of numeric
|
| 651 |
+
"close_code": close_code_val,
|
| 652 |
+
"close_notes": close_notes_val,
|
| 653 |
+
"caller_id": caller_sysid,
|
| 654 |
+
"resolved_at": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
|
| 655 |
+
"work_notes": "Auto-resolve set by NOVA.",
|
| 656 |
+
"resolved_by": resolved_by_sysid,
|
| 657 |
+
"assignment_group": assign_group,
|
| 658 |
+
})
|
| 659 |
+
respB = requests.patch(url, headers=headers, json=payload_B, verify=VERIFY_SSL, timeout=25)
|
| 660 |
+
if respB.status_code in (200, 204):
|
| 661 |
+
return True
|
| 662 |
+
print(f"[SN PATCH resolve B] status={respB.status_code} body={respB.text[:500]}")
|
| 663 |
+
|
| 664 |
+
# ---- C) PATCH using custom field names from env
|
| 665 |
+
# If your dictionary uses, for example, u_resolution_code/u_resolution_notes
|
| 666 |
+
code_field = os.getenv("SERVICENOW_RESOLUTION_CODE_FIELD", "close_code")
|
| 667 |
+
notes_field = os.getenv("SERVICENOW_RESOLUTION_NOTES_FIELD", "close_notes")
|
| 668 |
+
payload_C = clean({
|
| 669 |
+
"state": "6",
|
| 670 |
+
code_field: close_code_val,
|
| 671 |
+
notes_field: close_notes_val,
|
| 672 |
+
"caller_id": caller_sysid,
|
| 673 |
+
"resolved_at": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
|
| 674 |
+
"work_notes": "Auto-resolve set by NOVA.",
|
| 675 |
+
"resolved_by": resolved_by_sysid,
|
| 676 |
+
"assignment_group": assign_group,
|
| 677 |
+
})
|
| 678 |
+
respC = requests.patch(url, headers=headers, json=payload_C, verify=VERIFY_SSL, timeout=25)
|
| 679 |
+
if respC.status_code in (200, 204):
|
| 680 |
+
return True
|
| 681 |
+
print(f"[SN PATCH resolve C] status={respC.status_code} body={respC.text[:500]}")
|
| 682 |
+
|
| 683 |
+
# If all attempts failed, return False so the chat shows the soft message
|
| 684 |
+
return False
|
| 685 |
+
except Exception as e:
|
| 686 |
+
print(f"[SN PATCH resolve] exception={str(e)}")
|
| 687 |
+
return False
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
@app.post("/incident")
|
| 691 |
+
async def raise_incident(input_data: IncidentInput):
|
| 692 |
+
try:
|
| 693 |
+
result = create_incident(input_data.short_description, input_data.description)
|
| 694 |
+
if isinstance(result, dict) and not result.get("error"):
|
| 695 |
+
inc_number = result.get("number", "<unknown>")
|
| 696 |
+
sys_id = result.get("sys_id")
|
| 697 |
+
resolved_note = ""
|
| 698 |
+
if bool(input_data.mark_resolved) and sys_id not in ("<unknown>", None):
|
| 699 |
+
ok = _set_incident_resolved(sys_id)
|
| 700 |
+
resolved_note = " (marked Resolved)" if ok else " (could not mark Resolved; please update manually)"
|
| 701 |
+
ticket_text = f"Incident created: {inc_number}{resolved_note}"
|
| 702 |
+
else:
|
| 703 |
+
ticket_text = "Incident created."
|
| 704 |
+
|
| 705 |
+
# ✅ Do NOT include follow-up question inside bot_response to avoid duplication in UI.
|
| 706 |
+
# The front-end will show a Yes/No assist card after this.
|
| 707 |
+
return {
|
| 708 |
+
"bot_response": f"✅ {ticket_text}",
|
| 709 |
+
"debug": "Incident created via ServiceNow",
|
| 710 |
+
"persist": True,
|
| 711 |
+
"show_assist_card": True,
|
| 712 |
+
"followup": "Is there anything else I can assist you with?",
|
| 713 |
+
}
|
| 714 |
+
except Exception as e:
|
| 715 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
@app.post("/generate_ticket_desc")
|
| 719 |
+
async def generate_ticket_desc_ep(input_data: TicketDescInput):
|
| 720 |
+
try:
|
| 721 |
+
prompt = (
|
| 722 |
+
f"You are helping generate ServiceNow ticket descriptions based on the issue: {input_data.issue}.\n"
|
| 723 |
+
"Please return the output strictly in JSON format with the following keys:\n"
|
| 724 |
+
"{\n"
|
| 725 |
+
' "ShortDescription": "A concise summary of the issue (max 100 characters)",\n'
|
| 726 |
+
' "DetailedDescription": "A detailed explanation of the issue"\n'
|
| 727 |
+
"}\n"
|
| 728 |
+
"Do not include any extra text, comments, or explanations outside the JSON."
|
| 729 |
+
)
|
| 730 |
+
headers = {"Content-Type": "application/json"}
|
| 731 |
+
payload = {"contents": [{"parts": [{"text": prompt}]}]}
|
| 732 |
+
resp = requests.post(GEMINI_URL, headers=headers, json=payload, timeout=25, verify=GEMINI_SSL_VERIFY)
|
| 733 |
+
try:
|
| 734 |
+
data = resp.json()
|
| 735 |
+
except Exception:
|
| 736 |
+
return {"ShortDescription": "", "DetailedDescription": "", "error": "Gemini returned non-JSON"}
|
| 737 |
+
|
| 738 |
+
try:
|
| 739 |
+
text = data["candidates"][0]["content"]["parts"][0]["text"].strip()
|
| 740 |
+
except Exception:
|
| 741 |
+
return {"ShortDescription": "", "DetailedDescription": "", "error": "Gemini parsing failed"}
|
| 742 |
+
|
| 743 |
+
if text.startswith("```"):
|
| 744 |
+
lines = [ln for ln in text.splitlines() if not ln.strip().startswith("```")]
|
| 745 |
+
text = "\n".join(lines).strip()
|
| 746 |
+
|
| 747 |
+
try:
|
| 748 |
+
ticket_json = json.loads(text)
|
| 749 |
+
return {
|
| 750 |
+
"ShortDescription": ticket_json.get("ShortDescription", "").strip(),
|
| 751 |
+
"DetailedDescription": ticket_json.get("DetailedDescription", "").strip(),
|
| 752 |
+
}
|
| 753 |
+
except Exception:
|
| 754 |
+
return {"ShortDescription": "", "DetailedDescription": "", "error": "Invalid JSON returned"}
|
| 755 |
+
except Exception as e:
|
| 756 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
@app.post("/incident_status")
|
| 760 |
+
async def incident_status(input_data: TicketStatusInput):
|
| 761 |
+
try:
|
| 762 |
+
token = get_valid_token()
|
| 763 |
+
instance_url = os.getenv("SERVICENOW_INSTANCE_URL")
|
| 764 |
+
if not instance_url:
|
| 765 |
+
raise HTTPException(status_code=500, detail="SERVICENOW_INSTANCE_URL missing")
|
| 766 |
+
|
| 767 |
+
headers = {
|
| 768 |
+
"Authorization": f"Bearer {token}",
|
| 769 |
+
"Accept": "application/json",
|
| 770 |
+
}
|
| 771 |
+
|
| 772 |
+
if input_data.sys_id:
|
| 773 |
+
url = f"{instance_url}/api/now/table/incident/{input_data.sys_id}"
|
| 774 |
+
response = requests.get(url, headers=headers, verify=VERIFY_SSL, timeout=25)
|
| 775 |
+
data = response.json()
|
| 776 |
+
result = data.get("result", {}) if response.status_code == 200 else {}
|
| 777 |
+
elif input_data.number:
|
| 778 |
+
url = f"{instance_url}/api/now/table/incident?number={input_data.number}"
|
| 779 |
+
response = requests.get(url, headers=headers, verify=VERIFY_SSL, timeout=25)
|
| 780 |
+
data = response.json()
|
| 781 |
+
lst = data.get("result", [])
|
| 782 |
+
result = (lst or [{}])[0] if response.status_code == 200 else {}
|
| 783 |
+
else:
|
| 784 |
+
raise HTTPException(status_code=400, detail="Provide IncidentID (number) or sys_id")
|
| 785 |
+
|
| 786 |
+
state_code = str(result.get("state", "unknown"))
|
| 787 |
+
state_label = STATE_MAP.get(state_code, state_code)
|
| 788 |
+
short = result.get("short_description", "")
|
| 789 |
+
number = result.get("number", input_data.number or "unknown")
|
| 790 |
+
|
| 791 |
+
# ✅ Bold labels + hard line breaks so ReactMarkdown renders on separate lines
|
| 792 |
+
return {
|
| 793 |
+
"bot_response": (
|
| 794 |
+
f"**Ticket:** {number} \n"
|
| 795 |
+
f"**Status:** {state_label} \n"
|
| 796 |
+
f"**Issue description:** {short}"
|
| 797 |
+
).replace("\n", " \n"), # ensure hard-breaks
|
| 798 |
+
"followup": "Is there anything else I can assist you with?",
|
| 799 |
+
"show_assist_card": True, # <— show Yes/No card from UI after status
|
| 800 |
+
"persist": True,
|
| 801 |
+
"debug": "Incident status fetched",
|
| 802 |
+
}
|
| 803 |
+
except Exception as e:
|
| 804 |
+
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|