File size: 69,497 Bytes
434174b | 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 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 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 585 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 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 699 700 701 702 703 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 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 | # PlacementIQ β Agentic AI Full Implementation Plan
## Gemini CLI Execution Guide + Multi-Provider Support
> **How to use this file with Gemini CLI:**
> Run `gemini` in your project root and paste sections or say:
> "Read PLACEMENTIQ_AGENTIC_IMPLEMENTATION.md and create all the files described in it."
---
## Overview
This plan converts PlacementIQ from hardcoded ML + rule tables into a **multi-agent system**
where Claude/Llama/Gemini agents orchestrate your existing XGBoost/LightGBM models as tools.
**Provider support:** Anthropic, OpenRouter, Groq, OpenAI β switchable via a single `.env` variable.
---
## File Tree to Create
```
backend/
βββ config.py β NEW: provider + env config
βββ agents/
β βββ __init__.py β NEW
β βββ provider.py β NEW: multi-provider LLM client
β βββ tools.py β NEW: tool definitions + executors
β βββ base_agent.py β NEW: universal agentic loop
β βββ nba_agent.py β NEW: replaces rule table
β βββ explainability_agent.py β NEW: replaces NLG templates
β βββ market_agent.py β NEW: replaces threshold rules
β βββ career_path_agent.py β NEW: replaces adjacency table
β βββ orchestrator.py β NEW: master coordinator
βββ main.py β MODIFY: wire orchestrator in
βββ .env.example β NEW
βββ requirements.txt β MODIFY: add new deps
```
---
## STEP 0 β Install Dependencies
Add to `backend/requirements.txt` (append these lines, keep existing ones):
```
anthropic>=0.40.0
openai>=1.50.0
python-dotenv>=1.0.0
litellm>=1.50.0
httpx>=0.27.0
```
Run:
```bash
cd backend
pip install anthropic openai python-dotenv litellm httpx
```
---
## STEP 1 β Create `backend/.env.example`
```
# ββ LLM Provider ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Set PROVIDER to one of: anthropic | openrouter | groq | openai
PROVIDER=anthropic
# ββ API Keys (only set the one for your chosen provider) βββββββββββββββββββββ
ANTHROPIC_API_KEY=sk-ant-...
OPENROUTER_API_KEY=sk-or-...
GROQ_API_KEY=gsk_...
OPENAI_API_KEY=sk-...
# ββ Model Overrides (optional β defaults are set per provider in config.py) βββ
# OVERRIDE_MODEL=claude-sonnet-4-20250514
# ββ PlacementIQ Settings ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
RECOVERY_COST_INR=180000
SHOCK_THRESHOLD_WOW=0.15
PORT=8001
```
Copy to `.env` and fill in your key:
```bash
cp .env.example .env
```
---
## STEP 2 β Create `backend/config.py`
```python
# backend/config.py
"""
Central configuration for PlacementIQ.
Reads provider choice and API keys from .env.
All agents import from here β never hardcode keys anywhere else.
"""
import os
from dotenv import load_dotenv
load_dotenv()
# ββ Provider Registry βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Each entry defines: base_url, default model, tool format, and API key env var.
# tool_format: "anthropic" uses Anthropic SDK; "openai" uses OpenAI-compatible SDK.
PROVIDER_REGISTRY = {
"anthropic": {
"base_url": None, # Uses Anthropic SDK directly
"default_model": "claude-sonnet-4-20250514",
"tool_format": "anthropic",
"api_key_env": "ANTHROPIC_API_KEY",
},
"openrouter": {
"base_url": "https://openrouter.ai/api/v1",
"default_model": "anthropic/claude-3.5-sonnet", # Or "meta-llama/llama-3.3-70b-instruct"
"tool_format": "openai",
"api_key_env": "OPENROUTER_API_KEY",
"extra_headers": {
"HTTP-Referer": "https://placementiq.io",
"X-Title": "PlacementIQ"
}
},
"groq": {
"base_url": "https://api.groq.com/openai/v1",
"default_model": "llama-3.3-70b-versatile", # Best Groq model for tool use
"tool_format": "openai",
"api_key_env": "GROQ_API_KEY",
},
"openai": {
"base_url": "https://api.openai.com/v1",
"default_model": "gpt-4o",
"tool_format": "openai",
"api_key_env": "OPENAI_API_KEY",
},
}
# ββ Active Provider βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ACTIVE_PROVIDER = os.getenv("PROVIDER", "anthropic").lower()
if ACTIVE_PROVIDER not in PROVIDER_REGISTRY:
raise ValueError(
f"Unknown PROVIDER='{ACTIVE_PROVIDER}'. "
f"Choose from: {list(PROVIDER_REGISTRY.keys())}"
)
PROVIDER_CONFIG = PROVIDER_REGISTRY[ACTIVE_PROVIDER]
# Allow model override from env
MODEL = os.getenv("OVERRIDE_MODEL") or PROVIDER_CONFIG["default_model"]
# Resolve API key
API_KEY = os.getenv(PROVIDER_CONFIG["api_key_env"])
if not API_KEY:
raise EnvironmentError(
f"Provider '{ACTIVE_PROVIDER}' requires env var "
f"'{PROVIDER_CONFIG['api_key_env']}' to be set."
)
# ββ Business Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
RECOVERY_COST_INR = int(os.getenv("RECOVERY_COST_INR", 180000))
SHOCK_THRESHOLD_WOW = float(os.getenv("SHOCK_THRESHOLD_WOW", 0.15))
print(f"[PlacementIQ] Provider: {ACTIVE_PROVIDER} | Model: {MODEL}")
```
---
## STEP 3 β Create `backend/agents/__init__.py`
```python
# backend/agents/__init__.py
"""PlacementIQ Agent Package"""
```
---
## STEP 4 β Create `backend/agents/provider.py`
This is the most important file. It abstracts the LLM call so all agents
work identically regardless of which provider is active.
```python
# backend/agents/provider.py
"""
Universal LLM client for PlacementIQ.
Supports Anthropic SDK (direct) and OpenAI-compatible APIs (Groq, OpenRouter, OpenAI).
Handles tool call format conversion and response parsing for both formats.
"""
import json
import anthropic
from openai import OpenAI
from config import ACTIVE_PROVIDER, PROVIDER_CONFIG, MODEL, API_KEY
# ββ Tool Format Converters ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _to_openai_tools(anthropic_tools: list) -> list:
"""Convert Anthropic-format tools to OpenAI function-calling format."""
return [
{
"type": "function",
"function": {
"name": t["name"],
"description": t["description"],
"parameters": t["input_schema"],
},
}
for t in anthropic_tools
]
def _to_anthropic_messages(openai_messages: list) -> list:
"""
Convert OpenAI-style message list to Anthropic format.
OpenAI uses role=tool with tool_call_id; Anthropic uses role=user with tool_result blocks.
This function is used internally when building Anthropic message history.
"""
# For our use case, messages are always built internally per-provider, so this
# function handles the conversion when we have tool_result messages.
converted = []
for msg in openai_messages:
if msg["role"] == "tool":
# Wrap as Anthropic tool_result inside a user turn
converted.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": msg.get("tool_call_id", "unknown"),
"content": msg["content"]
}]
})
else:
converted.append(msg)
return converted
# ββ Unified LLM Call ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class LLMResponse:
"""Normalized response object β same shape regardless of provider."""
def __init__(self, text: str = None, tool_calls: list = None, stop_reason: str = "end_turn"):
self.text = text # Final text answer
self.tool_calls = tool_calls or [] # List of {"id", "name", "input"} dicts
self.stop_reason = stop_reason # "end_turn" or "tool_use"
def call_llm(
system: str,
messages: list,
tools: list = None,
max_tokens: int = 2000
) -> LLMResponse:
"""
Make a single LLM call. Returns a normalized LLMResponse.
`messages` should be in a neutral internal format:
[{"role": "user"|"assistant"|"tool", "content": str, "tool_call_id": ...}]
"""
tool_format = PROVIDER_CONFIG["tool_format"]
if tool_format == "anthropic":
return _call_anthropic(system, messages, tools, max_tokens)
else:
return _call_openai_compatible(system, messages, tools, max_tokens)
# ββ Anthropic Implementation ββββββββββββββββββββββββββββββββββββββββββββββββββ
def _call_anthropic(system, messages, tools, max_tokens) -> LLMResponse:
client = anthropic.Anthropic(api_key=API_KEY)
# Build Anthropic message list
anthropic_messages = []
for msg in messages:
role = msg["role"]
content = msg["content"]
if role == "tool":
# Tool result β must be wrapped in user role as tool_result block
anthropic_messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": msg.get("tool_call_id"),
"content": content
}]
})
elif role == "assistant" and isinstance(content, list):
# Assistant message with tool_use blocks (already in Anthropic format)
anthropic_messages.append({"role": "assistant", "content": content})
else:
anthropic_messages.append({"role": role, "content": content})
kwargs = {
"model": MODEL,
"max_tokens": max_tokens,
"system": system,
"messages": anthropic_messages,
}
if tools:
kwargs["tools"] = tools # Already in Anthropic format
response = client.messages.create(**kwargs)
# Parse response
if response.stop_reason == "tool_use":
tool_calls = []
text_parts = []
for block in response.content:
if block.type == "tool_use":
tool_calls.append({
"id": block.id,
"name": block.name,
"input": block.input,
"_raw_block": block # Keep for message reconstruction
})
elif hasattr(block, "text"):
text_parts.append(block.text)
return LLMResponse(
text=" ".join(text_parts) if text_parts else None,
tool_calls=tool_calls,
stop_reason="tool_use"
)
else:
text = " ".join(b.text for b in response.content if hasattr(b, "text"))
return LLMResponse(text=text, stop_reason="end_turn")
# ββ OpenAI-Compatible Implementation (Groq, OpenRouter, OpenAI) βββββββββββββββ
def _call_openai_compatible(system, messages, tools, max_tokens) -> LLMResponse:
extra_headers = PROVIDER_CONFIG.get("extra_headers", {})
client = OpenAI(
api_key=API_KEY,
base_url=PROVIDER_CONFIG["base_url"],
default_headers=extra_headers
)
# Build OpenAI message list
openai_messages = [{"role": "system", "content": system}]
for msg in messages:
role = msg["role"]
if role == "tool":
openai_messages.append({
"role": "tool",
"tool_call_id": msg.get("tool_call_id"),
"content": msg["content"]
})
elif role == "assistant" and "tool_calls" in msg:
openai_messages.append({
"role": "assistant",
"content": msg.get("content"),
"tool_calls": msg["tool_calls"]
})
else:
openai_messages.append({"role": role, "content": msg["content"]})
kwargs = {
"model": MODEL,
"max_tokens": max_tokens,
"messages": openai_messages,
}
if tools:
kwargs["tools"] = _to_openai_tools(tools)
kwargs["tool_choice"] = "auto"
response = client.chat.completions.create(**kwargs)
choice = response.choices[0]
message = choice.message
if choice.finish_reason == "tool_calls" and message.tool_calls:
tool_calls = []
for tc in message.tool_calls:
tool_calls.append({
"id": tc.id,
"name": tc.function.name,
"input": json.loads(tc.function.arguments),
"_raw_openai": tc # Keep for message reconstruction
})
return LLMResponse(
text=message.content,
tool_calls=tool_calls,
stop_reason="tool_use"
)
else:
return LLMResponse(text=message.content, stop_reason="end_turn")
```
---
## STEP 5 β Create `backend/agents/tools.py`
All tool definitions + their executor functions. Agents call `execute_tool(name, input)`.
```python
# backend/agents/tools.py
"""
PlacementIQ Tool Registry.
TOOL_DEFINITIONS: list of tool specs in Anthropic format (auto-converted for other providers).
execute_tool(): dispatches tool name β actual Python function.
"""
import json
import os
import pandas as pd
import numpy as np
# Lazy-load scoring engine to avoid circular imports
_engine = None
_df = None
def _get_engine():
global _engine
if _engine is None:
from scoring_engine import ScoringEngine
_engine = ScoringEngine()
return _engine
def _get_df():
global _df
if _df is None:
csv_path = os.path.join(os.path.dirname(__file__), "..", "data", "synthetic_students.csv")
_df = pd.read_csv(csv_path)
return _df
# ββ Tool Definitions (Anthropic format β auto-converted for other providers) ββ
TOOL_DEFINITIONS = [
{
"name": "predict_placement_probability",
"description": (
"Run the XGBoost placement model to get placement probabilities at 3m/6m/12m "
"horizons for a student given their feature vector. Also returns raw risk_band "
"and confidence score from the model."
),
"input_schema": {
"type": "object",
"properties": {
"student_features": {
"type": "object",
"description": (
"Feature dict with keys: cgpa (float 0-10), iqi (float 0-1), "
"field_demand_score (float 0-100), macro_climate_index (float 0-1), "
"institute_tier_score (float 1-10), behavioral_activity_score (float 0-100), "
"peer_velocity (float 0-1), course_type (str), institute_tier (str A/B/C/D), "
"region (str)."
)
}
},
"required": ["student_features"]
}
},
{
"name": "estimate_salary_range",
"description": (
"Run LightGBM quantile regression to estimate expected starting salary "
"range (low/median/high) in INR/month for a student. Use this to compute "
"the EMI Comfort Ratio."
),
"input_schema": {
"type": "object",
"properties": {
"student_features": {"type": "object"},
"course_type": {
"type": "string",
"enum": ["Engineering", "MBA", "Nursing", "Architecture", "Law", "Pharmacy"]
},
"region": {
"type": "string",
"description": "City/region in India, e.g. Pune, Bengaluru, Mumbai, Delhi, Hyderabad"
}
},
"required": ["student_features", "course_type", "region"]
}
},
{
"name": "get_shap_drivers",
"description": (
"Fetch top-5 SHAP feature attributions for a student. Returns feature name, "
"SHAP value (positive = reduces risk, negative = increases risk), and the "
"student's actual value for that feature. Use this to identify root causes."
),
"input_schema": {
"type": "object",
"properties": {
"student_id": {"type": "string"}
},
"required": ["student_id"]
}
},
{
"name": "get_peer_cohort_stats",
"description": (
"Get aggregated cohort statistics for students with the same course type, "
"institute tier, and graduation year. Returns median/quartile placement "
"probabilities, median IQI, median behavioral score. Use to benchmark student."
),
"input_schema": {
"type": "object",
"properties": {
"course_type": {"type": "string"},
"institute_tier": {"type": "string", "enum": ["A", "B", "C", "D"]},
"graduation_year": {"type": "integer"}
},
"required": ["course_type", "institute_tier", "graduation_year"]
}
},
{
"name": "get_intervention_cost_table",
"description": (
"Returns the full intervention catalog with: intervention type, cost in INR, "
"average placement probability lift in percentage points (pp), and typical "
"completion duration in days. Filter by course_type and relevant risk drivers."
),
"input_schema": {
"type": "object",
"properties": {
"course_type": {"type": "string"},
"risk_drivers": {
"type": "array",
"items": {"type": "string"},
"description": "Top negative SHAP driver names to filter relevant interventions"
}
},
"required": ["course_type"]
}
},
{
"name": "get_emi_data",
"description": (
"Get a student's monthly EMI obligation and their predicted median salary "
"to allow EMI Comfort Ratio calculation. Also returns emi_start_date."
),
"input_schema": {
"type": "object",
"properties": {
"student_id": {"type": "string"}
},
"required": ["student_id"]
}
},
{
"name": "get_labor_market_data",
"description": (
"Fetch current labor market data for a field+region combination. Returns: "
"demand_index (0-100), yoy_change (fraction, negative = decline), "
"top_hiring_companies, recent_layoff_events list, job_openings_per_graduate, "
"and a 4-week trend array. Use for Shock Detector and Career Path scoring."
),
"input_schema": {
"type": "object",
"properties": {
"field": {
"type": "string",
"description": "e.g. 'Software Engineering', 'MBA-Finance', 'Mechanical Engineering', 'Nursing'"
},
"region": {
"type": "string",
"description": "e.g. 'Pune', 'Bengaluru', 'Mumbai', 'Delhi', 'Hyderabad', 'Chennai'"
}
},
"required": ["field", "region"]
}
},
{
"name": "get_adjacent_fields",
"description": (
"Given a primary academic field, return a list of adjacent/pivot career fields "
"that the student could transition to based on their academic background. "
"Returns field names, skill overlap percentage, and typical transition effort."
),
"input_schema": {
"type": "object",
"properties": {
"primary_field": {"type": "string"},
"course_type": {"type": "string"}
},
"required": ["primary_field", "course_type"]
}
},
{
"name": "get_company_health_signals",
"description": (
"Fetch financial health signals for a hiring company. Returns: "
"funding_status, headcount_trend_6m (fraction), glassdoor_rating_trend "
"(from/to), layoff_announced (bool), active_job_postings (bool). "
"Use for Offer Survival Score calculation."
),
"input_schema": {
"type": "object",
"properties": {
"company_name": {"type": "string"},
"student_id": {
"type": "string",
"description": "Optional β used to fetch the specific company from the student's offer record"
}
},
"required": ["company_name"]
}
},
{
"name": "get_institute_momentum",
"description": (
"Get the Institute Momentum Index for a given institute. Returns: "
"momentum_ratio (30d/90d recruiter visits), offer_momentum (30d/90d offers), "
"momentum_flag (bool), and adjustment_pct applied to institute tier score."
),
"input_schema": {
"type": "object",
"properties": {
"institute_id": {"type": "string"}
},
"required": ["institute_id"]
}
},
]
# ββ Tool Executors ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def execute_tool(tool_name: str, tool_input: dict) -> str:
"""Dispatch a tool call to its implementation. Always returns a JSON string."""
try:
result = _dispatch(tool_name, tool_input)
return json.dumps(result)
except Exception as e:
return json.dumps({"error": str(e), "tool": tool_name})
def _dispatch(name: str, inp: dict) -> dict:
if name == "predict_placement_probability":
engine = _get_engine()
features = inp["student_features"]
result = engine.predict(features)
return {
"placement_probability": result.get("placement_probability", {
"within_3_months": 0.45,
"within_6_months": 0.70,
"within_12_months": 0.88
}),
"risk_band": result.get("risk_band", "MEDIUM"),
"risk_score": result.get("risk_score", 50),
}
elif name == "estimate_salary_range":
engine = _get_engine()
result = engine.estimate_salary(
inp["student_features"],
inp.get("course_type", "Engineering"),
inp.get("region", "Pune")
)
return result or {"low": 35000, "median": 55000, "high": 80000, "currency": "INR"}
elif name == "get_shap_drivers":
engine = _get_engine()
student_id = inp["student_id"]
try:
shap = engine.get_shap_values(student_id)
except Exception:
# Fallback synthetic SHAP for demo
shap = [
{"feature": "institute_tier_score", "shap_value": -0.12, "student_value": 4.2,
"readable_name": "Institute Tier", "direction": "negative"},
{"feature": "iqi", "shap_value": -0.09, "student_value": 0.25,
"readable_name": "Internship Quality Index", "direction": "negative"},
{"feature": "field_demand_score", "shap_value": -0.08, "student_value": 28.0,
"readable_name": "Field Demand Score", "direction": "negative"},
{"feature": "behavioral_activity_score", "shap_value": 0.06, "student_value": 72.0,
"readable_name": "Behavioral Activity Score", "direction": "positive"},
{"feature": "cgpa", "shap_value": 0.04, "student_value": 7.8,
"readable_name": "CGPA", "direction": "positive"},
]
return {"student_id": student_id, "top_drivers": shap}
elif name == "get_peer_cohort_stats":
df = _get_df()
cohort = df[
(df["course_type"] == inp["course_type"]) &
(df["institute_tier"] == inp["institute_tier"])
]
if len(cohort) == 0:
return {"error": "No matching cohort found", "cohort_size": 0}
return {
"cohort_size": len(cohort),
"median_placement_6m": float(cohort.get("placement_6m_prob", pd.Series([0.65])).median()),
"top_quartile_placement_6m": float(cohort.get("placement_6m_prob", pd.Series([0.82])).quantile(0.75)),
"median_iqi": float(cohort.get("iqi", pd.Series([0.55])).median()),
"median_behavioral_score": float(cohort.get("behavioral_activity_score", pd.Series([60])).median()),
"median_cgpa": float(cohort.get("cgpa", pd.Series([7.2])).median()),
}
elif name == "get_intervention_cost_table":
course = inp.get("course_type", "Engineering")
drivers = inp.get("risk_drivers", [])
# Full intervention catalog
catalog = {
"SKILL_UP_PYTHON_ANALYTICS": {
"cost_inr": 2000, "avg_pp_lift": 9, "duration_days": 30,
"best_for": ["iqi", "behavioral_activity_score", "field_demand_score"],
"courses": ["Engineering", "MBA"]
},
"SKILL_UP_DATA_ANALYTICS": {
"cost_inr": 3500, "avg_pp_lift": 11, "duration_days": 45,
"best_for": ["iqi", "field_demand_score"],
"courses": ["Engineering", "MBA"]
},
"MOCK_INTERVIEW_X2": {
"cost_inr": 0, "avg_pp_lift": 6, "duration_days": 14,
"best_for": ["behavioral_activity_score"],
"courses": ["Engineering", "MBA", "Nursing", "Law"]
},
"RESUME_REVIEW": {
"cost_inr": 500, "avg_pp_lift": 4, "duration_days": 7,
"best_for": ["behavioral_activity_score"],
"courses": ["Engineering", "MBA", "Nursing"]
},
"INTERNSHIP_REFERRAL": {
"cost_inr": 0, "avg_pp_lift": 13, "duration_days": 60,
"best_for": ["iqi"],
"courses": ["Engineering", "MBA"]
},
"CAREER_COUNSELLING_SESSION": {
"cost_inr": 1000, "avg_pp_lift": 5, "duration_days": 3,
"best_for": ["field_demand_score", "behavioral_activity_score"],
"courses": ["Engineering", "MBA", "Nursing", "Architecture"]
},
"CLINICAL_PLACEMENT_CONNECT": {
"cost_inr": 0, "avg_pp_lift": 10, "duration_days": 30,
"best_for": ["iqi", "field_demand_score"],
"courses": ["Nursing", "Pharmacy"]
},
"CASE_MANAGER_ASSIGNMENT": {
"cost_inr": 0, "avg_pp_lift": 3, "duration_days": 1,
"best_for": ["institute_tier_score", "macro_climate_index"],
"courses": ["Engineering", "MBA", "Nursing", "Architecture", "Law", "Pharmacy"]
},
"EMI_GRACE_REVIEW": {
"cost_inr": 0, "avg_pp_lift": 0, "duration_days": 1,
"best_for": ["emi_comfort"],
"courses": ["Engineering", "MBA", "Nursing", "Architecture", "Law", "Pharmacy"]
},
"SALARY_NEGOTIATION_COACHING": {
"cost_inr": 800, "avg_pp_lift": 2, "duration_days": 7,
"best_for": ["emi_comfort"],
"courses": ["Engineering", "MBA"]
},
}
# Filter by course
filtered = {k: v for k, v in catalog.items() if course in v.get("courses", [])}
return {"interventions": filtered, "course_type": course}
elif name == "get_emi_data":
student_id = inp["student_id"]
df = _get_df()
student_rows = df[df["student_id"] == student_id]
if len(student_rows) > 0:
row = student_rows.iloc[0]
emi = float(row.get("monthly_emi", 18000))
salary = float(row.get("predicted_salary_median", 55000))
else:
emi, salary = 18000, 55000
return {
"student_id": student_id,
"monthly_emi_inr": emi,
"predicted_median_salary_inr": salary,
"emi_comfort_ratio": round(salary / emi, 2) if emi > 0 else None,
"emi_start_date": "2026-09-01"
}
elif name == "get_labor_market_data":
field = inp["field"]
region = inp["region"]
# Synthetic labor market data β replace with NAUKRI/LinkedIn API in production
import random
rng = random.Random(hash(f"{field}{region}") % 10000)
base_demand = rng.randint(25, 85)
yoy = round(rng.uniform(-0.20, 0.15), 3)
return {
"field": field,
"region": region,
"demand_index": base_demand,
"yoy_change": yoy,
"wow_change": round(rng.uniform(-0.12, 0.08), 3),
"job_openings_per_graduate": round(rng.uniform(0.8, 4.5), 1),
"top_hiring_companies": ["TCS", "Infosys", "Wipro", "HCL"][:rng.randint(1, 4)],
"recent_layoff_events": (
[{"company": "TechCorp", "count": 1200, "date": "2026-04-15"}]
if yoy < -0.10 else []
),
"4week_trend": [base_demand + rng.randint(-5, 5) for _ in range(4)],
}
elif name == "get_adjacent_fields":
primary = inp["primary_field"].lower()
adjacency_map = {
"mechanical engineering": [
{"field": "Supply Chain Management", "overlap_pct": 72, "transition_effort": "Low"},
{"field": "Quality Assurance Engineering", "overlap_pct": 68, "transition_effort": "Low"},
{"field": "Operations Management", "overlap_pct": 61, "transition_effort": "Medium"},
{"field": "Manufacturing Consulting", "overlap_pct": 55, "transition_effort": "Medium"},
{"field": "Product Management", "overlap_pct": 48, "transition_effort": "High"},
],
"civil engineering": [
{"field": "Urban Planning", "overlap_pct": 70, "transition_effort": "Low"},
{"field": "Real Estate Consulting", "overlap_pct": 65, "transition_effort": "Low"},
{"field": "Infrastructure Project Management", "overlap_pct": 80, "transition_effort": "Low"},
{"field": "Environmental Consulting", "overlap_pct": 55, "transition_effort": "Medium"},
],
"electrical engineering": [
{"field": "Embedded Systems", "overlap_pct": 82, "transition_effort": "Low"},
{"field": "Power Systems Consulting", "overlap_pct": 75, "transition_effort": "Low"},
{"field": "IoT Solutions", "overlap_pct": 65, "transition_effort": "Medium"},
{"field": "Data Centre Operations", "overlap_pct": 55, "transition_effort": "Medium"},
],
"mba-finance": [
{"field": "Financial Technology (FinTech)", "overlap_pct": 78, "transition_effort": "Low"},
{"field": "Risk Management", "overlap_pct": 85, "transition_effort": "Low"},
{"field": "Investment Banking", "overlap_pct": 90, "transition_effort": "Low"},
{"field": "Corporate Strategy", "overlap_pct": 72, "transition_effort": "Medium"},
],
"nursing": [
{"field": "Healthcare Administration", "overlap_pct": 70, "transition_effort": "Medium"},
{"field": "Medical Coding & Billing", "overlap_pct": 60, "transition_effort": "Low"},
{"field": "Clinical Research Coordinator", "overlap_pct": 75, "transition_effort": "Low"},
{"field": "Health Informatics", "overlap_pct": 55, "transition_effort": "High"},
],
}
for key in adjacency_map:
if key in primary or primary in key:
return {"primary_field": inp["primary_field"], "adjacent_fields": adjacency_map[key]}
return {
"primary_field": inp["primary_field"],
"adjacent_fields": [
{"field": "Business Analytics", "overlap_pct": 55, "transition_effort": "Medium"},
{"field": "Project Management", "overlap_pct": 60, "transition_effort": "Low"},
{"field": "Operations Research", "overlap_pct": 50, "transition_effort": "Medium"},
]
}
elif name == "get_company_health_signals":
company = inp["company_name"]
# Synthetic β replace with Tracxn/Crunchbase/LinkedIn API in production
import random
rng = random.Random(hash(company) % 10000)
health_score = rng.randint(30, 95)
return {
"company_name": company,
"funding_status": rng.choice([
"Series B - active", "Series C - recent", "Profitable - no funding needed",
"Series A - early stage", "Series B - 8 months overdue"
]),
"headcount_trend_6m": round(rng.uniform(-0.25, 0.20), 3),
"glassdoor_rating_trend": {
"from": round(rng.uniform(3.0, 4.5), 1),
"to": round(rng.uniform(2.8, 4.5), 1)
},
"layoff_announced": rng.random() < 0.15,
"active_job_postings": rng.random() > 0.2,
"overall_health_score": health_score,
}
elif name == "get_institute_momentum":
institute_id = inp["institute_id"]
import random
rng = random.Random(hash(institute_id) % 10000)
ratio = round(rng.uniform(0.45, 1.55), 2)
return {
"institute_id": institute_id,
"recruiter_momentum_ratio": ratio,
"offer_momentum_ratio": round(rng.uniform(0.50, 1.50), 2),
"momentum_flag": ratio < 0.6,
"adjustment_pct": -15 if ratio < 0.6 else (10 if ratio > 1.4 else 0),
"last_updated": "2026-05-01"
}
raise ValueError(f"Unknown tool: {name}")
```
---
## STEP 6 β Create `backend/agents/base_agent.py`
The universal agentic loop. Works with any provider.
```python
# backend/agents/base_agent.py
"""
Provider-agnostic agentic loop.
Calls LLM, handles tool use, feeds results back, loops until done.
"""
import json
from provider import call_llm, LLMResponse
from tools import execute_tool, TOOL_DEFINITIONS
import config
def run_agent(
system_prompt: str,
user_message: str,
tools: list = None,
max_iterations: int = 6,
) -> str:
"""
Agentic loop: runs the LLM until it produces a final text response.
The agent may call tools multiple times before answering.
Args:
system_prompt: Role + rules for this agent
user_message: Task description with student context
tools: List of tool definitions (defaults to TOOL_DEFINITIONS)
max_iterations: Safety cap on tool-call rounds
Returns:
Final text response from the agent
"""
if tools is None:
tools = TOOL_DEFINITIONS
messages = [{"role": "user", "content": user_message}]
for iteration in range(max_iterations):
response: LLMResponse = call_llm(
system=system_prompt,
messages=messages,
tools=tools,
max_tokens=2000
)
# Agent is done β return final answer
if response.stop_reason == "end_turn":
return response.text or ""
# Agent wants to call tools
if response.stop_reason == "tool_use" and response.tool_calls:
# Add assistant turn to history (format depends on provider)
_append_assistant_turn(messages, response, config.PROVIDER_CONFIG["tool_format"])
# Execute each requested tool and collect results
tool_results = []
for tc in response.tool_calls:
result_str = execute_tool(tc["name"], tc["input"])
print(f" [Tool] {tc['name']}({list(tc['input'].keys())}) β {result_str[:120]}...")
tool_results.append({
"tool_call_id": tc["id"],
"result": result_str,
"tool_name": tc["name"]
})
# Add tool results to message history
_append_tool_results(messages, tool_results, config.PROVIDER_CONFIG["tool_format"])
continue
# Unexpected stop
break
return response.text or "Agent did not produce a final answer within iteration limit."
def _append_assistant_turn(messages: list, response: LLMResponse, tool_format: str):
"""Append the assistant's tool-calling turn in the correct format for the provider."""
if tool_format == "anthropic":
# Anthropic: assistant content is a list of blocks
content_blocks = []
if response.text:
content_blocks.append({"type": "text", "text": response.text})
for tc in response.tool_calls:
content_blocks.append({
"type": "tool_use",
"id": tc["id"],
"name": tc["name"],
"input": tc["input"]
})
messages.append({"role": "assistant", "content": content_blocks})
else:
# OpenAI format: tool_calls array
openai_tool_calls = []
for tc in response.tool_calls:
openai_tool_calls.append({
"id": tc["id"],
"type": "function",
"function": {
"name": tc["name"],
"arguments": json.dumps(tc["input"])
}
})
messages.append({
"role": "assistant",
"content": response.text,
"tool_calls": openai_tool_calls
})
def _append_tool_results(messages: list, tool_results: list, tool_format: str):
"""Append tool results to message history in the correct format for the provider."""
if tool_format == "anthropic":
# Anthropic: all results go in a single user message as tool_result blocks
result_blocks = []
for tr in tool_results:
result_blocks.append({
"type": "tool_result",
"tool_use_id": tr["tool_call_id"],
"content": tr["result"]
})
messages.append({"role": "user", "content": result_blocks})
else:
# OpenAI: each result is a separate "tool" role message
for tr in tool_results:
messages.append({
"role": "tool",
"tool_call_id": tr["tool_call_id"],
"content": tr["result"]
})
```
---
## STEP 7 β Create `backend/agents/nba_agent.py`
Replaces the hardcoded rule table in PRD Section 13.
```python
# backend/agents/nba_agent.py
"""
NBA (Next-Best-Action) Agent.
Replaces the PRD Section 13 rule table with dynamic, context-aware reasoning.
"""
import json
from base_agent import run_agent
from tools import TOOL_DEFINITIONS
import config
NBA_SYSTEM_PROMPT = f"""
You are the NBA (Next-Best-Action) Agent for PlacementIQ β an education loan risk platform.
Your job: recommend the highest-ROI, cost-aware interventions for an at-risk student.
REASONING PROCESS (follow in order):
1. Call get_shap_drivers to identify root cause risk factors
2. Call get_emi_data to understand financial urgency (EMI Comfort Ratio)
3. Call get_intervention_cost_table with the student's course_type and the top negative driver names
4. Reason about the combination of risk factors β address root causes, not symptoms
5. Rank interventions by: (pp_lift Γ default_risk_reduction_pct) / cost_inr
For zero-cost interventions, rank by pp_lift alone
6. Select at most 3 interventions β never recommend more (decision fatigue kills completion)
HARD RULES (always apply, no exceptions):
- If EMI Comfort Ratio < 1.0 β EMI_GRACE_REVIEW is ALWAYS the first action
- If behavioral_activity_score < 40 β job search coaching before skill-up courses
- If field_demand_score < 30 β include career counselling or alternate path recommendation
- If iqi < 0.3 β internship referral outranks skill-up courses
- Never recommend a 45-day course if graduation is within 30 days
- Recovery cost avoided = default_risk_reduction_pct Γ {config.RECOVERY_COST_INR}
- ROI = recovery_cost_avoided / course_cost_inr (infinity for free interventions β label as "β")
OUTPUT: Return ONLY valid JSON in this exact structure (no markdown, no preamble):
{{
"reasoning": "2-3 sentence plain-English assessment of why this student is at risk and what the priority is",
"actions": [
{{
"rank": 1,
"action_type": "SKILL_UP | MOCK_INTERVIEW | EMI_GRACE_REVIEW | INTERNSHIP_REFERRAL | CAREER_COUNSELLING | CASE_MANAGER | SALARY_NEGOTIATION",
"detail": "Specific recommendation text β name the course, the mock interview source, etc.",
"estimated_pp_lift": 9,
"cost_inr": 2000,
"default_risk_reduction_pct": 12,
"roi_label": "10.8x",
"rationale": "One sentence: why THIS action for THIS specific student's situation"
}}
]
}}
"""
def get_nba_recommendations(student_id: str, student_context: dict) -> dict:
"""
Generate Next-Best-Action recommendations for a student.
Returns parsed dict with reasoning + ranked actions list.
"""
user_message = f"""
Generate Next-Best-Action recommendations for student: {student_id}
Student profile:
- Course type: {student_context.get('course_type', 'Unknown')}
- Institute tier: {student_context.get('institute_tier', 'Unknown')}
- Region: {student_context.get('region', 'Unknown')}
- Current risk band: {student_context.get('risk_band', 'MEDIUM')}
- CGPA: {student_context.get('cgpa', 'N/A')}
- IQI (Internship Quality Index): {student_context.get('iqi', 'N/A')}
- Behavioral activity score: {student_context.get('behavioral_activity_score', 'N/A')}
- Field demand score: {student_context.get('field_demand_score', 'N/A')}
- Months to graduation: {student_context.get('months_to_graduation', 'N/A')}
- Peer velocity (cohort placement rate): {student_context.get('peer_velocity', 'N/A')}
- 6-month placement probability: {student_context.get('placement_6m', 'N/A')}
Steps:
1. Call get_shap_drivers for student {student_id}
2. Call get_emi_data for student {student_id}
3. Call get_intervention_cost_table for course_type="{student_context.get('course_type', 'Engineering')}"
4. Produce ranked NBA JSON output
"""
raw = run_agent(NBA_SYSTEM_PROMPT, user_message, TOOL_DEFINITIONS)
try:
start = raw.find("{")
end = raw.rfind("}") + 1
return json.loads(raw[start:end])
except (json.JSONDecodeError, ValueError):
return {
"reasoning": raw[:300] if raw else "Agent could not generate recommendations.",
"actions": []
}
```
---
## STEP 8 β Create `backend/agents/explainability_agent.py`
Replaces NLG template strings with contextual, cohort-aware narratives.
```python
# backend/agents/explainability_agent.py
"""
Explainability Agent.
Converts SHAP values + cohort stats into human-readable risk narratives.
Replaces hardcoded NLG template strings.
"""
import json
from base_agent import run_agent
from tools import TOOL_DEFINITIONS
EXPLAIN_SYSTEM_PROMPT = """
You are the Explainability Agent for PlacementIQ β an AI risk system for education loans.
Your job: translate raw SHAP values and model scores into clear, specific, actionable
narratives for non-technical Relationship Managers and compliance auditors.
WRITING RULES (strictly follow):
- Never mention "the model", "the algorithm", or "SHAP values" β speak about the student's actual situation
- Be specific with numbers: say "IQI of 0.25 vs cohort median of 0.55" not "low internship quality"
- Always contextualize against the cohort, not in isolation
- Acknowledge positive factors genuinely β don't bury good news in a list of risks
- Summary must be under 80 words β relationship managers read dozens of these
- If risk is HIGH, end with ONE urgent action sentence
- If data gaps limit confidence, mention it once at the end
TOOL USAGE:
1. Call get_shap_drivers to get the actual feature attributions
2. Call get_peer_cohort_stats to get the cohort benchmark for comparison
3. Write the narrative using both
OUTPUT: Return ONLY valid JSON (no markdown, no preamble):
{
"summary": "Plain-English risk narrative under 80 words",
"positive_factors": ["Specific positive factor with student's actual value"],
"negative_factors": ["Specific negative factor with student's value vs cohort median"],
"urgency_note": "One urgent action sentence for HIGH risk, or null for LOW/MEDIUM"
}
"""
def generate_explainability_narrative(student_id: str, student_context: dict) -> dict:
user_message = f"""
Generate an explainability narrative for student {student_id}.
Current prediction outputs:
- Risk band: {student_context.get('risk_band')}
- Placement probability (6m): {student_context.get('placement_6m')}
- Peer percentile: {student_context.get('peer_percentile')}th percentile in their cohort
- EMI Comfort Ratio: {student_context.get('emi_comfort_ratio')}
- Confidence level: {student_context.get('confidence_level', 'MEDIUM')}
Student data:
- Course type: {student_context.get('course_type')}
- Institute tier: {student_context.get('institute_tier')}
- Graduation year: {student_context.get('graduation_year', 2026)}
- CGPA: {student_context.get('cgpa')}
- IQI: {student_context.get('iqi')}
- Behavioral activity: {student_context.get('behavioral_activity_score')}
- Field demand: {student_context.get('field_demand_score')}
Steps:
1. Call get_shap_drivers for student {student_id}
2. Call get_peer_cohort_stats: course_type="{student_context.get('course_type', 'Engineering')}",
institute_tier="{student_context.get('institute_tier', 'B')}",
graduation_year={student_context.get('graduation_year', 2026)}
3. Write the narrative JSON
"""
raw = run_agent(EXPLAIN_SYSTEM_PROMPT, user_message, TOOL_DEFINITIONS)
try:
start = raw.find("{")
end = raw.rfind("}") + 1
return json.loads(raw[start:end])
except (json.JSONDecodeError, ValueError):
return {
"summary": raw[:300] if raw else "Explainability narrative unavailable.",
"positive_factors": [],
"negative_factors": [],
"urgency_note": None
}
```
---
## STEP 9 β Create `backend/agents/market_agent.py`
Replaces the 15% WoW threshold rule with reasoning-based severity assessment.
```python
# backend/agents/market_agent.py
"""
Market Intelligence Agent.
Replaces hardcoded threshold triggers in the Placement Shock Detector.
Reasons about severity, distinguishes seasonal dips from genuine shocks.
"""
import json
from base_agent import run_agent
from tools import TOOL_DEFINITIONS
import config
MARKET_SYSTEM_PROMPT = f"""
You are the Market Intelligence Agent for PlacementIQ.
Monitor labor market signals and assess placement shock severity for student portfolios.
SEVERITY SCALE:
- NORMAL: Demand stable or minor fluctuation (<5% WoW). No action needed.
- WATCH: Demand declining 5β10% WoW OR 1β2 minor layoff events. Flag for awareness.
- ALERT: Demand down 10β15% WoW OR 1 major layoff event (500+ employees). Escalate to RM.
- SHOCK: Demand down 15%+ WoW OR 1,000+ layoffs at a major employer. Emergency escalation.
REASONING GUIDELINES:
- Distinguish seasonal dips from structural decline (use YoY not just WoW alone)
- A single company's troubles β sector shock unless they are a top-5 employer in that field
- Consider whether the field has high student concentration in the portfolio
- When WoW and YoY disagree, weight YoY more heavily (seasonal filter)
- Only trigger SHOCK if you are confident β false positives cause alert fatigue
TOOL USAGE:
1. Call get_labor_market_data for the field+region combination
2. Reason about severity using both WoW and YoY signals
3. Output your assessment
OUTPUT: Valid JSON only (no markdown):
{{
"field": "...",
"region": "...",
"severity": "NORMAL | WATCH | ALERT | SHOCK",
"demand_index": 65,
"wow_change": -0.12,
"yoy_change": -0.08,
"trigger_reason": "Specific reason or null",
"confidence": "HIGH | MEDIUM | LOW",
"recommended_action": "What the lender risk team should do now",
"affected_segment_description": "Which students are most exposed"
}}
"""
def assess_market_shock(field: str, region: str) -> dict:
user_message = f"""
Assess current placement shock severity for:
- Field: {field}
- Region: {region}
Call get_labor_market_data, then provide your severity assessment.
"""
raw = run_agent(MARKET_SYSTEM_PROMPT, user_message, TOOL_DEFINITIONS)
try:
start = raw.find("{")
end = raw.rfind("}") + 1
return json.loads(raw[start:end])
except (json.JSONDecodeError, ValueError):
return {"field": field, "region": region, "severity": "NORMAL",
"trigger_reason": "Assessment unavailable", "confidence": "LOW"}
def scan_portfolio_for_shocks(field_region_pairs: list) -> list:
"""
Scan multiple field+region combinations and return only non-NORMAL ones.
field_region_pairs: list of {"field": str, "region": str}
"""
results = []
for pair in field_region_pairs:
assessment = assess_market_shock(pair["field"], pair["region"])
if assessment.get("severity", "NORMAL") != "NORMAL":
results.append(assessment)
return results
```
---
## STEP 10 β Create `backend/agents/career_path_agent.py`
Replaces static adjacency table with demand-aware, geography-filtered reasoning.
```python
# backend/agents/career_path_agent.py
"""
Career Path Agent.
Replaces the static role-adjacency mapping table in PRD Section 10.4.
Fetches adjacent fields AND their current demand in the student's region.
"""
import json
from base_agent import run_agent
from tools import TOOL_DEFINITIONS
CAREER_SYSTEM_PROMPT = """
You are the Career Path Agent for PlacementIQ.
When a student's primary field has weak demand, recommend adjacent career pivots
that are (a) compatible with their academic background and (b) have strong current demand
in their specific region.
TOOL USAGE:
1. Call get_adjacent_fields to get academically compatible pivot options
2. For each adjacent field (up to 4), call get_labor_market_data with the student's region
3. Rank pivots by: demand_index Γ (overlap_pct / 100) β the "reachability-weighted demand" score
4. Only recommend pivots where demand_index > 40 AND overlap_pct > 50
5. Include the skill gap each pivot requires (inferred from overlap_pct)
WRITING RULES:
- Be concrete about why each pivot fits this student's background
- Include demand_index and salary_match as numbers
- Mention what specific skills/certifications bridge the gap
- If no pivots score well (all demand < 40), recommend geographic mobility as an option
OUTPUT: Valid JSON only:
{
"primary_field": "...",
"primary_demand_index": 28,
"primary_demand_assessment": "One sentence on why the primary field is weak",
"recommended_pivots": [
{
"rank": 1,
"field": "Supply Chain Management",
"demand_index": 71,
"overlap_pct": 72,
"reachability_score": 51.1,
"transition_effort": "Low | Medium | High",
"bridge_skills": ["Excel Advanced", "SAP Basics"],
"rationale": "Why this pivot specifically for this student"
}
]
}
"""
def get_career_path_recommendations(student_id: str, student_context: dict) -> dict:
user_message = f"""
Generate alternative career path recommendations for student {student_id}.
Student profile:
- Primary field: {student_context.get('field', student_context.get('course_type'))}
- Course type: {student_context.get('course_type')}
- Region: {student_context.get('region')}
- Field demand score (primary): {student_context.get('field_demand_score')} / 100
- CGPA: {student_context.get('cgpa')}
- Certifications: {student_context.get('certifications', 'None listed')}
Steps:
1. Call get_adjacent_fields: primary_field="{student_context.get('field', '')}",
course_type="{student_context.get('course_type', '')}"
2. For top 4 adjacent fields, call get_labor_market_data with region="{student_context.get('region', 'Pune')}"
3. Rank and filter pivots, output JSON
"""
raw = run_agent(CAREER_SYSTEM_PROMPT, user_message, TOOL_DEFINITIONS)
try:
start = raw.find("{")
end = raw.rfind("}") + 1
return json.loads(raw[start:end])
except (json.JSONDecodeError, ValueError):
return {"primary_field": student_context.get("field", ""), "recommended_pivots": []}
```
---
## STEP 11 β Create `backend/agents/offer_survival_agent.py`
Phase 3 feature β agent-driven Offer Survival Score.
```python
# backend/agents/offer_survival_agent.py
"""
Offer Survival Agent.
Scores P(offer not revoked in 60 days) by reasoning about company health signals.
Replaces the gradient boosted classifier approach with LLM reasoning over signals.
"""
import json
from base_agent import run_agent
from tools import TOOL_DEFINITIONS
OFFER_SURVIVAL_SYSTEM_PROMPT = """
You are the Offer Survival Agent for PlacementIQ.
A student has received a job offer. Your job: assess whether that offer is at risk
of revocation within the next 60 days based on the hiring company's financial health.
SIGNAL WEIGHTS (use for scoring, not as rigid rules):
- Headcount declined > 15% in 6 months: Very High Risk (-25 points from 100)
- Funding round overdue by > 6 months: High Risk (-20 points)
- Glassdoor rating dropped > 0.5 points in 90 days: Moderate Risk (-15 points)
- Layoff announced: Very High Risk (-30 points)
- Active job postings ongoing: Weak positive (+10 points)
- Recent successful funding: Strong positive (+20 points)
- Large public company: Strong positive (+15 points)
Start from a baseline of 75 (most offers survive). Apply signal adjustments.
Cap at 0 (floor) and 100 (ceiling).
Score interpretation:
- 70β100: LOW RISK β standard monitoring
- 40β69: MEDIUM RISK β advise parallel job search
- 0β39: HIGH RISK β urgently advise parallel search; flag for RM
TOOL USAGE:
1. Call get_company_health_signals with the company name
2. Apply signal weights to compute a score
3. Produce your assessment
OUTPUT: Valid JSON only:
{
"company_name": "...",
"offer_survival_score": 72,
"risk_level": "LOW | MEDIUM | HIGH",
"positive_signals": ["signal description"],
"risk_signals": ["signal description with severity"],
"score_reasoning": "2-3 sentences explaining the score",
"recommended_action": "What to tell the student and RM"
}
"""
def get_offer_survival_score(student_id: str, company_name: str) -> dict:
user_message = f"""
Assess offer survival risk for student {student_id}.
Hiring company: {company_name}
Call get_company_health_signals for "{company_name}", then compute
the offer survival score and produce your assessment JSON.
"""
raw = run_agent(OFFER_SURVIVAL_SYSTEM_PROMPT, user_message, TOOL_DEFINITIONS)
try:
start = raw.find("{")
end = raw.rfind("}") + 1
return json.loads(raw[start:end])
except (json.JSONDecodeError, ValueError):
return {
"company_name": company_name,
"offer_survival_score": 75,
"risk_level": "LOW",
"score_reasoning": "Insufficient signals to assess.",
"recommended_action": "Standard monitoring."
}
```
---
## STEP 12 β Create `backend/agents/orchestrator.py`
The master coordinator. This is what your FastAPI endpoints call.
```python
# backend/agents/orchestrator.py
"""
Master Orchestrator for PlacementIQ.
Coordinates all sub-agents. FastAPI endpoints call functions from here.
ML scoring engine runs first (fast + reliable), then agents add reasoning layers.
"""
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
from nba_agent import get_nba_recommendations
from explainability_agent import generate_explainability_narrative
from market_agent import assess_market_shock, scan_portfolio_for_shocks
from career_path_agent import get_career_path_recommendations
from offer_survival_agent import get_offer_survival_score
def score_student_full(student_data: dict) -> dict:
"""
Full agentic pipeline for a single student scoring request.
Flow:
1. ML models run first (XGBoost + LightGBM) β fast, deterministic
2. NBA + Explainability agents run in parallel β agent-driven, contextual
3. Results merged into final response
This keeps API latency predictable: ML is fast (~50ms),
agents add ~1β2s for contextual reasoning.
"""
student_id = student_data.get("student_id", "UNKNOWN")
# ββ Step 1: Run ML scoring engine (fast path) βββββββββββββββββββββββββββββ
try:
from scoring_engine import ScoringEngine
engine = ScoringEngine()
ml_scores = engine.predict(student_data)
except Exception as e:
# Graceful fallback if scoring engine unavailable
ml_scores = _fallback_ml_scores(student_data)
print(f"[Orchestrator] Scoring engine error: {e} β using fallback")
# ββ Step 2: Enrich context with ML outputs ββββββββββββββββββββββββββββββββ
student_context = {
**student_data,
"risk_band": ml_scores.get("risk_band", "MEDIUM"),
"placement_6m": ml_scores.get("placement_probability", {}).get("within_6_months", 0.65),
"peer_percentile": ml_scores.get("peer_benchmark", {}).get("student_percentile", 50),
"emi_comfort_ratio": ml_scores.get("emi_comfort", {}).get("ratio", 2.5),
"confidence_level": ml_scores.get("confidence", {}).get("level", "MEDIUM"),
}
# ββ Step 3: Run NBA + Explainability in parallel ββββββββββββββββββββββββββ
nba_result = {}
explain_result = {}
with ThreadPoolExecutor(max_workers=2) as executor:
futures = {
executor.submit(get_nba_recommendations, student_id, student_context): "nba",
executor.submit(generate_explainability_narrative, student_id, student_context): "explain",
}
for future in as_completed(futures):
key = futures[future]
try:
result = future.result(timeout=30)
if key == "nba":
nba_result = result
else:
explain_result = result
except Exception as e:
print(f"[Orchestrator] Agent '{key}' error: {e}")
# ββ Step 4: Assemble final response βββββββββββββββββββββββββββββββββββββββ
return {
**ml_scores,
"agentic_nba": {
"reasoning": nba_result.get("reasoning"),
"actions": nba_result.get("actions", []),
},
"agentic_explainability": {
"summary": explain_result.get("summary"),
"positive_factors": explain_result.get("positive_factors", []),
"negative_factors": explain_result.get("negative_factors", []),
"urgency_note": explain_result.get("urgency_note"),
}
}
def score_student_fast(student_data: dict) -> dict:
"""
ML-only scoring (no agents). Use for bulk scoring or latency-sensitive requests.
NBA and explainability will use hardcoded fallbacks.
"""
try:
from scoring_engine import ScoringEngine
engine = ScoringEngine()
return engine.predict(student_data)
except Exception as e:
return _fallback_ml_scores(student_data)
def get_career_paths(student_id: str, student_context: dict) -> dict:
"""Get alternate career path recommendations for a student."""
return get_career_path_recommendations(student_id, student_context)
def get_shock_report(field_region_pairs: list) -> list:
"""Run the Market Intelligence Agent across a list of field+region pairs."""
return scan_portfolio_for_shocks(field_region_pairs)
def get_offer_survival(student_id: str, company_name: str) -> dict:
"""Get Offer Survival Score for a student with an active offer."""
return get_offer_survival_score(student_id, company_name)
def _fallback_ml_scores(student_data: dict) -> dict:
"""Emergency fallback scores when the scoring engine is unavailable."""
return {
"student_id": student_data.get("student_id"),
"risk_band": "MEDIUM",
"risk_score": 50,
"placement_probability": {
"within_3_months": 0.45,
"within_6_months": 0.68,
"within_12_months": 0.87
},
"salary_estimate": {"low": 35000, "median": 55000, "high": 80000, "currency": "INR"},
"emi_comfort": {"ratio": 2.5, "tier": "ADEQUATE"},
"confidence": {"level": "LOW", "percentage": 40, "data_gaps": ["Scoring engine unavailable"]},
"peer_benchmark": {"student_percentile": 50, "cohort_median_probability_6m": 0.65},
"risk_drivers": []
}
```
---
## STEP 13 β Modify `backend/main.py`
Add these imports and new/updated endpoints. **Do not delete existing endpoints** β add alongside them.
Find your existing imports block and add:
```python
# Add at top of main.py, after existing imports
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "agents"))
from agents.orchestrator import (
score_student_full,
score_student_fast,
get_career_paths,
get_shock_report,
get_offer_survival,
)
```
Replace (or add alongside) your existing `/api/v1/score/student` endpoint:
```python
# In main.py β update or add these endpoints
@app.post("/api/v1/score/student")
async def score_student_endpoint(request: StudentScoreRequest):
"""
Full agentic scoring: ML model + NBA agent + Explainability agent.
Use this for individual student risk cards in the dashboard.
"""
result = score_student_full(request.dict())
return result
@app.post("/api/v1/score/student/fast")
async def score_student_fast_endpoint(request: StudentScoreRequest):
"""
ML-only scoring without agents. Use for bulk operations or latency-sensitive contexts.
"""
result = score_student_fast(request.dict())
return result
@app.get("/api/v1/student/{student_id}/career-paths")
async def career_paths_endpoint(student_id: str):
"""Alternate Career Path Engine β agent-driven."""
# Fetch student data from your DB/CSV
student_context = _fetch_student_context(student_id)
result = get_career_paths(student_id, student_context)
return result
@app.get("/api/v1/student/{student_id}/offer-survival")
async def offer_survival_endpoint(student_id: str, company: str):
"""Offer Survival Score β agent-driven company health assessment."""
result = get_offer_survival(student_id, company)
return result
@app.get("/api/v1/shocks/active")
async def active_shocks_endpoint():
"""
Placement Shock Detector β agent-driven severity assessment.
Scans all field+region combinations from the active student portfolio.
"""
# Build list of unique field+region pairs from your student data
field_region_pairs = _get_portfolio_segments()
shocks = get_shock_report(field_region_pairs)
return {"active_shocks": shocks, "total_segments_scanned": len(field_region_pairs)}
# ββ Helper functions (add to main.py) ββββββββββββββββββββββββββββββββββββββββ
def _fetch_student_context(student_id: str) -> dict:
"""Fetch student data from CSV. Replace with DB query in production."""
import pandas as pd
try:
df = pd.read_csv("data/synthetic_students.csv")
row = df[df["student_id"] == student_id].iloc[0]
return row.to_dict()
except Exception:
return {"student_id": student_id, "course_type": "Engineering",
"region": "Pune", "field": "Software Engineering"}
def _get_portfolio_segments() -> list:
"""Get unique field+region pairs from active student portfolio."""
import pandas as pd
try:
df = pd.read_csv("data/synthetic_students.csv")
pairs = df[["course_type", "region"]].drop_duplicates()
return [
{"field": row["course_type"], "region": row["region"]}
for _, row in pairs.iterrows()
]
except Exception:
return [
{"field": "Software Engineering", "region": "Pune"},
{"field": "MBA-Finance", "region": "Mumbai"},
]
```
---
## STEP 14 β Provider Switching Instructions
### Switch to OpenRouter (access Claude, Gemini, Llama via one key):
```bash
# .env
PROVIDER=openrouter
OPENROUTER_API_KEY=sk-or-...
# Optional: choose a specific model
OVERRIDE_MODEL=meta-llama/llama-3.3-70b-instruct # cheapest
# or
OVERRIDE_MODEL=anthropic/claude-3.5-sonnet # best quality
# or
OVERRIDE_MODEL=google/gemini-2.0-flash-001 # fast + cheap
```
### Switch to Groq (fastest inference, free tier):
```bash
# .env
PROVIDER=groq
GROQ_API_KEY=gsk_...
# Default model: llama-3.3-70b-versatile (best tool use on Groq)
# Groq free tier: 14,400 requests/day β enough for demo
```
### Switch to Anthropic (most reliable tool use):
```bash
# .env
PROVIDER=anthropic
ANTHROPIC_API_KEY=sk-ant-...
```
### Switch to OpenAI:
```bash
# .env
PROVIDER=openai
OPENAI_API_KEY=sk-...
OVERRIDE_MODEL=gpt-4o-mini # cheaper, still supports tool use
```
---
## STEP 15 β Test the Full Pipeline
```bash
# From backend/ directory
cd backend
# Test a single agent directly
python -c "
import sys; sys.path.insert(0, 'agents')
from agents.nba_agent import get_nba_recommendations
result = get_nba_recommendations('STU-001', {
'course_type': 'MBA',
'institute_tier': 'C',
'region': 'Pune',
'risk_band': 'HIGH',
'cgpa': 6.2,
'iqi': 0.2,
'behavioral_activity_score': 32,
'field_demand_score': 25,
'months_to_graduation': 3,
'placement_6m': 0.38
})
import json; print(json.dumps(result, indent=2))
"
# Test orchestrator
python -c "
import sys; sys.path.insert(0, 'agents')
from agents.orchestrator import score_student_full
result = score_student_full({
'student_id': 'STU-001',
'course_type': 'MBA',
'institute_tier': 'C',
'region': 'Pune',
'cgpa': 6.2,
'iqi': 0.2,
'behavioral_activity_score': 32,
'field_demand_score': 25,
'monthly_emi': 18000
})
import json; print(json.dumps(result, indent=2))
"
# Start the API
python main.py
```
---
## Provider Capability Matrix
| Provider | Tool Use Quality | Speed | Cost | Best For |
|---|---|---|---|---|
| Anthropic Claude Sonnet | βββββ | Medium | Medium | Production, hackathon demo |
| OpenRouter + Claude | βββββ | Medium | Medium | If you need OpenRouter billing |
| OpenRouter + Llama 3.3 | ββββ | Fast | Very Low | Cost-optimized production |
| Groq + Llama 3.3 | ββββ | β‘ Fastest | Free tier | Live demos, prototyping |
| OpenAI GPT-4o | ββββ | Fast | Medium | Alternative to Anthropic |
| OpenAI GPT-4o-mini | βββ | Fast | Low | Budget option |
**Recommendation for TenzorX demo:** Use `PROVIDER=groq` (free, fast) during development.
Switch to `PROVIDER=anthropic` or `PROVIDER=openrouter` with Claude for the final demo
(best tool use reliability).
---
## Gemini CLI Prompt to Execute Everything
Paste this into Gemini CLI:
```
Read the file PLACEMENTIQ_AGENTIC_IMPLEMENTATION.md.
For each file described in the "File Tree to Create" section, create the exact file
at the exact path shown, with the exact code in the corresponding code block.
Order of creation:
1. backend/.env.example
2. backend/config.py
3. backend/agents/__init__.py
4. backend/agents/provider.py
5. backend/agents/tools.py
6. backend/agents/base_agent.py
7. backend/agents/nba_agent.py
8. backend/agents/explainability_agent.py
9. backend/agents/market_agent.py
10. backend/agents/career_path_agent.py
11. backend/agents/offer_survival_agent.py
12. backend/agents/orchestrator.py
13. Modify backend/main.py as described in Step 13
Then run: cd backend && pip install anthropic openai python-dotenv httpx
Do not modify any existing files except main.py and requirements.txt.
Do not delete any existing endpoints in main.py β only add new ones.
```
|