Lesson 95 — Intermediate

Agent & Tool Security

Jab tak model sirf baat karta tha, galti shabd tak simit thi. Agent mein galti action ban jaati hai — ticket update, email, query, code execution. Is lesson mein tum seekhoge useful autonomy deni kaise hai bina unrestricted control diye: tool tiers, LLM-se-bahar validation, human gates, run limits aur sandboxing.

⏱ 20 min• Intermediate• Jailbreaks, Guardrails & Moderation

Agent security kya hai

WHAT

Agent ki woh design jo ensure karti hai ki model galat, manipulated ya confused hone par bhi nuksaan nahi kar paaye — tools minimum, args validated, irreversible actions gated, runs capped.

WHEN

Har us app par jahan model koi action leta hai — support agent, code agent, data pipeline agent. Jahan tool call hai, wahan agent security hai.

WHERE

Tool registry, dispatch layer, approval workflow, agent loop ke limits, aur sandbox infrastructure mein — sab code mein, model ke iraade par nahi.

Core principle: model tumhara colleague nahi, untrusted planner hai. Woh plan banata hai; plan ko execute karne se pehle tumhara code decide karega ki plan allowed hai ya nahi.

Blast radius mindset: Attack hoga hi — injection, hallucination, ya bas galti. Sawaal yeh nahi "hoga ya nahi", sawaal hai "hoga toh kitna nuksaan". Woh tumhare tool design se tay hota hai.

Least privilege: read vs consequential

TOOL_TIERS = {
    "search_kb":     "read",
    "get_ticket":    "read",
    "update_ticket": "write",
    "send_email":    "consequential",
    "run_shell":     "consequential",
}

def run_tool(name, args, approved=lambda n: False):
    tier = TOOL_TIERS.get(name)
    if tier is None:
        raise PermissionError(f"unknown tool: {name}")   # default deny
    if tier == "consequential" and not approved(name):
        return {"status": "needs_approval", "tool": name}  # ruko, insaan dekhe
    return dispatch(name, args)
Task-scoped permissions: Agent ko woh tools do jo us task ke liye hain — support agent ko refund ka tool, code agent ko shell. Har task par registry filter hoti rahe, permanent full-set nahi.

Validation jo LLM se bahar hai

ALLOWED_COLUMNS = {"status", "priority", "assignee"}

def validate_sql(sql: str) -> str:
    head = sql.strip().split()[0].upper()
    if head != "SELECT":
        raise ValueError("read-only endpoint: sirf SELECT")
    if ";" in sql.rstrip(";") or " union " in sql.lower():
        raise ValueError("suspicious SQL shape")
    return sql

# Har tool argument tumhare validator se guzaro:
# parse karo → allowlist check → schema match → phir hi execute.
# LLM ke "trust me" par kabhi nahi. Simple string checks fragile hain —
# real systems mein proper parser, parameterized queries aur DB-level
# permission layer use karo; yeh sirf shape dikhane ke liye hai.

Model arguments ko hostile input maano — hallucinated column, galat ID, injected SQL, ya manipulated JSON. Tumhara dispatch layer untrusted ko typed, validated, scoped call mein badalta hai.

Step, time aur cost limits

LIMITS = {"max_steps": 12, "max_seconds": 300, "max_cost_usd": 1.0}

def agent_loop(task, limits=LIMITS):
    spent, t0, steps = 0.0, time.time(), 0
    while True:
        steps += 1
        if steps > limits["max_steps"]:
            raise RuntimeError("step limit — run band, log alert")
        if time.time() - t0 > limits["max_seconds"]:
            raise RuntimeError("time limit")
        spent += estimate_cost(last_call())
        if spent > limits["max_cost_usd"]:
            raise RuntimeError("cost cap hit")
        step = model_next_step(task)
        result = run_tool(step.tool, step.args)
        if result.get("status") == "needs_approval":
            log_audit(step)
            result = ask_human(step)      # gate: approve / reject, record ke saath
        plan.observe(result)
Limits security control hain: Yeh productivity meter nahi — ek injection ya hallucination ko chhote incident se bachane wali net hai. Default 0 matlab unlimited; hamesha explicit cap rakho.

Sandboxing — generated code ke liye

Honest limit: Sandbox strong hai, perfect nahi — kernel exploits bhi hote hain. Isliye sandbox + least privilege + no secrets, teeno saath. Ek layer par pura bharosa wahi galti hai jo is poore level ki kahani hai.

Exercise

Question: Agent ko sirf woh tools dena jo task ke liye zaroori hain — principle ka naam, do shabd?

Question: Delete, purchase, email jaise irreversible action se pehle kiski approval zaroori? (ek shabd)

Question: Agent run par step, time aur cost ki caps ko ek shabd mein kya bolte hain? (English)

Question: Model-generated code chalane ka safe, isolated environment — ek shabd, English?

Common mistakes

Desi example: Naye intern ko chabiyan

Naye intern (agent) ko pehle reception aur store room ki chabi milti hai (read tools). Tijori aur HR file (consequential) kabhi nahi — manager (human) approval ke saath, har baar likhte hue:

text
intern_ki_chabiyan = [reception, store_room]
# tijori = manager_approval + register entry (audit log)
# Agent bhi wahi: pehle minimum, phir prove karo, tabhi bada access
Interview angle — yahan se sawaal aate hain
  • Q: Tool use ko tiers mein kaise baantoge? (read / write / consequential — har tier ka apna check, consequential par human gate)
  • Q: Tool arguments ko LLM ke bharose execute kyun nahi karna chahiye? (hallucination, injection, galat IDs — validator, schema, ownership check chahiye)
  • Q: Agent loop mein kya kya caps honge? (max steps, wall-clock time, cost budget, bounded retries — har ek ka alert/log)
  • Q: Generated code safely kaise chalaoge? (sandbox container, no secrets, egress allowlist, resource limits — aur code ko bhi untrusted maano)
Lesson complete?

Agent ab controlled hai. Agla lesson — RAG & Knowledge Security — knowledge layer par kitna bharosa karna chahiye.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course