🤖 AI Agents, LangChain & Multi-Agent Systems
1️⃣ What are AI Agents? (LLM vs Agent)
Definition: Ek standalone LLM sirf text prediction engine hota hai jo prompt lene ke baad response dekar ruk jata hai. Ek AI Agent LLM ko ek "Brain" ki tarah use karta hai jo environment observe karta hai, decisions plan karta hai, external digital tools (APIs, Web search, SQL, Python interpreter) execute karta hai aur iterative goal achieve karta hai.
| Criteria | Standard LLM (Chatbot) | Autonomous AI Agent |
|---|---|---|
| Interaction Mode | Single-turn / Multi-turn conversation. | Autonomous execution loop: Goal receive karne par tab tak execute hota hai jab tak objective complete na ho. |
| Tool Access | None (Knowledge cutoff se bound). | Dynamic tools: Google Search, Database queries, Bash terminal, Slack alerts. |
| Memory | Chat context window buffer. | Short-Term + Long-Term: Vector memory, session checkpoints, episodic recall. |
| Self-Correction | User prompt ke through hi re-attempt karta hai. | Automated reflection: Error aane par tool parameters adjust karke auto retry karta hai. |
2️⃣ The ReAct Pattern (Reason + Act)
Princeton & Google research dwara propose kiya gaya framework jo Agent reasoning ko tool actions ke sath synchronize karta hai:
# The ReAct Execution Cycle:
Question: "FresherJobsAlert portal par active Spring Boot jobs kitni hain aur average package kya hai?"
-------------------------------------------------------------------------------------------------
Thought 1: Mujhe database query tool run karke Spring Boot related active listings fetch karni hongi.
Action 1 : run_sql_query("SELECT COUNT(*), AVG(salary) FROM jobs WHERE tech_stack LIKE '%SpringBoot%'")
Observation 1: {"count": 48, "avg_salary_lpa": 8.5}
Thought 2: Data receive ho chuka hai. Ab final answer format karke output deliver kar sakta hoon.
Final Answer: FresherJobsAlert par total 48 Spring Boot jobs active hain jinka average salary package 8.5 LPA hai.
3️⃣ Native Tool & Function Calling (JSON Schemas)
Modern LLMs plain text ke sath-sath structured JSON arguments output karte hain jo developer functions se directly bind hote hain:
from langchain_core.tools import tool
# Defining a custom Python tool using decorator
@tool
def check_job_status(job_id: str) -> str:
"""Useful to check the interview application status of a candidate on FresherJobsAlert."""
# Internal DB / API call
return f"Status for {job_id}: Shortlisted for Technical Round 2."
# Binding tools to LLM
llm_with_tools = chat_model.bind_tools([check_job_status])
4️⃣ LangChain Expression Language (LCEL)
Chains ko modular, streaming-ready aur production-grade compose karne ke liye Unix pipe operator (|) syntax:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_template("Explain the role of {topic} in modern DevOps in 3 bullet points.")
model = ChatOpenAI(model="gpt-4o-mini", temperature=0.2)
output_parser = StrOutputParser()
# Declarative LCEL Pipeline
chain = prompt | model | output_parser
# Invocation
response = chain.invoke({"topic": "Kubernetes"})
print(response)
5️⃣ Stateful Cyclic Graphs with LangGraph
Traditional DAG (Directed Acyclic Graph) chains me loops aur self-correction support nahi hote. LangGraph state machines aur cyclic graphs support karta hai:
• State: Central typed dictionary jo execution history aur agent variables hold karti hai.
• Nodes: Functions jo current state receive karke updated state return karte hain (e.g.
call_model, call_tool).• Conditional Edges: Routing decisions (e.g. "Agar LLM ne tool call request ki → route to ToolNode, warna route to END").
from langgraph.graph import StateGraph, END
# Define workflow graph
workflow = StateGraph(AgentState)
workflow.add_node("agent", call_model_step)
workflow.add_node("action", execute_tools_step)
workflow.set_entry_point("agent")
workflow.add_conditional_edges("agent", should_continue, {"continue": "action", "end": END})
workflow.add_edge("action", "agent") # Loop back to agent with observation!
app = workflow.compile()
6️⃣ Role-Based Multi-Agent Teams with CrewAI
Complex business problems ko solve karne ke liye specialized role-playing agents collaborate karte hain:
from crewai import Agent, Task, Crew, Process
# 1. Specialized Researcher Agent
researcher = Agent(
role="Tech Talent Researcher",
goal="Discover high-demand emerging programming skills in 2026",
backstory="You are an expert HR analyst scanning tech hiring trends.",
tools=[search_tool]
)
# 2. Specialized Content Writer Agent
writer = Agent(
role="Curriculum Architect",
goal="Write engaging course syllabus based on research data",
backstory="You craft pedagogical masterclasses for student developers."
)
# Orchestrating in Crew
crew = Crew(
agents=[researcher, writer],
tasks=[task1, task2],
process=Process.sequential # or Process.hierarchical with a Manager Agent
)
result = crew.kickoff()
7️⃣ Human-in-the-Loop & Production Guardrails
| Guardrail Layer | Implementation Strategy |
|---|---|
| Human-in-the-Loop (HITL) | Financial transactions ya critical email sends se pehle graph interrupt karke human admin approval lena (interrupt_before=["send_email"]). |
| Input / Output Validation | Pydantic schemas aur NeMo Guardrails use karke PII leakage aur prompt injection attacks prevent karna. |
| Tracing & Monitoring | LangSmith ya Phoenix use karke multi-turn agent execution steps, token latency aur tool errors monitor karna. |