33. AI Agents
🇬🇧 English Definition
An AI Agent is an autonomous software system powered by an LLM that receives a high-level goal, plans sub-tasks, executes external tools, evaluates results, and iterates until the goal is accomplished.
🇮🇳 Hinglish Definition
Chatbot sirf simple reply karta hai. AI Agent ko ek goal milta hai, wo khud multi-step plan banata hai, tools (search, DB, calculator) execute karta hai aur results observe karke final goal hit karta hai.
// Basic ReAct (Reasoning + Acting) Agent Loop Simulation
def agent_react_loop(goal, max_steps=3):
state = f"Goal: {goal}"
for step in range(1, max_steps + 1):
print(f"--- Step {step} ---")
// 1. Reason
thought = f"Thought {step}: I need to check data for {goal}"
// 2. Act
action = f"Action {step}: Call tool search_database('{goal}')"
// 3. Observe
observation = f"Observation {step}: Found valid record matching {goal}"
print(thought)
print(action)
print(observation)
return "Final Answer: Goal achieved successfully."
print(agent_react_loop("Customer refund validation"))
🔍 Line-by-Line Code Breakdown
- agent_react_loop: Implements the classic ReAct framework loop: Thought -> Action -> Observation cycle.
🎯 Interview Focus & Questions
Q: What is the ReAct framework in AI Agents?
A: ReAct (Reasoning + Acting) combines step-by-step verbal reasoning traces with action tool calls, allowing the agent to update its plan based on environment feedback.
34. Agent Architecture & Tool Calling
🇬🇧 English Definition
Agent architectures couple an LLM core with an execution runtime, tool registries, system safety guardrails, state managers, and loop exit criteria to prevent infinite execution loops.
🇮🇳 Hinglish Definition
Agent architecture main loop, tool registry, safety authorization gates aur timeout bounds ko aggregate karta hai taaki agent safely execute ho aur infinite loops mein na phase.
// Tool Execution Engine with Exception Safety
def execute_agent_tool(tool_name, args_dict, allowed_tools):
if tool_name not in allowed_tools:
return f"Error: Tool '{tool_name}' is unauthorized."
try:
result = allowed_tools[tool_name](**args_dict)
return {"status": "success", "data": result}
except Exception as e:
return {"status": "error", "message": str(e)}
tools = {"add": lambda a, b: a + b}
print(execute_agent_tool("add", {"a": 15, "b": 27}, tools))
print(execute_agent_tool("delete_db", {}, tools))
🔍 Line-by-Line Code Breakdown
- execute_agent_tool: Secure tool router checking tool authorization and catching runtime execution exceptions safely.
🎯 Interview Focus & Questions
Q: How do you prevent AI Agents from getting stuck in infinite loops?
A: Set strict maximum step count limits, timeout thresholds, duplicate action detection filters, and human-in-the-loop approval checkpoints.
35. Agent Memory
🇬🇧 English Definition
Agent memory manages state across interactions. Short-term memory maintains immediate execution context; long-term memory persists user preferences, facts, and past tool results in databases or vector stores.
🇮🇳 Hinglish Definition
Agent memory do type ki hoti hai: Short-term memory (current session/convo tokens) aur Long-term memory (DB/Vector store mein persisted facts, past decisions aur user preferences).
// Agent Memory Manager Class Concept
class AgentMemory:
def __init__(self):
self.short_term = []
self.long_term_db = {}
def add_interaction(self, user_msg, agent_resp):
self.short_term.append({"user": user_msg, "agent": agent_resp})
def store_fact(self, key, value):
self.long_term_db[key] = value
mem = AgentMemory()
mem.add_interaction("My name is Gagan", "Hello Gagan!")
mem.store_fact("user_role", "Lead AI Engineer")
print("Long-term Fact:", mem.long_term_db["user_role"])
🔍 Line-by-Line Code Breakdown
- AgentMemory: Class separating ephemeral in-memory conversation list from persistent key-value/vector fact storage.
🎯 Interview Focus & Questions
Q: How does semantic memory retrieval work in long-term agent memory?
A: Past conversation summaries are vectorized and stored in a vector DB; when a user returns, the agent searches relevant past memories using query embeddings.
36. Multi-Agent Systems
🇬🇧 English Definition
Multi-Agent Systems coordinate multiple specialized autonomous agents (e.g. Researcher, Coder, Reviewer) using orchestration patterns like sequential handoffs, hierarchical management, or consensus routing.
🇮🇳 Hinglish Definition
Multi-agent system mein alag-alag specialized agents milkar kaam karte hain (e.g., Researcher Agent info dhoondhta hai, Writer Agent draft karta hai, Reviewer Agent double-check karta hai).
// Sequential Multi-Agent Handoff Pattern
def researcher_agent(topic):
return f"Research facts for '{topic}': GenAI is expanding rapidly."
def writer_agent(research_data):
return f"Blog Post Draft: {research_data} Explore its impact now!"
def reviewer_agent(draft):
return f"Approved Draft: {draft} (Verified format)."
topic = "Multi-Agent AI"
facts = researcher_agent(topic)
draft = writer_agent(facts)
final_output = reviewer_agent(draft)
print(final_output)
🔍 Line-by-Line Code Breakdown
- Sequential Handoff: Output of previous agent becomes input to next specialized agent.
🎯 Interview Focus & Questions
Q: What is the main drawback of over-engineering with Multi-Agent Systems?
A: Increased system latency, multiplied API costs, complex state synchronization bugs, and potential cascading errors across agent communication steps.
37. LangChain and LangGraph Concepts
🇬🇧 English Definition
LangChain provides abstractions for prompt templates, chains, and tool integration. LangGraph extends this to stateful, cyclic, graph-based agent workflows with nodes, edges, and state persistence.
🇮🇳 Hinglish Definition
LangChain components compose karne ke liye library hai. LangGraph graph-based workflows (Nodes = Actions/LLMs, Edges = Decisions) banata hai jisse complex stateful cycles aur human-in-the-loop loops control hote hain.
// Graph Node & State Update Concept (LangGraph pattern)
def node_search(state):
query = state["query"]
return {"retrieved_docs": f"Docs matching {query}", "step": state["step"] + 1}
def node_generate(state):
docs = state["retrieved_docs"]
return {"final_response": f"Generated answer using {docs}"}
state = {"query": "LangGraph state", "step": 0}
state.update(node_search(state))
state.update(node_generate(state))
print("Final Graph State:", state)
🔍 Line-by-Line Code Breakdown
- state dictionary: Central immutable/mutable data structure passed between nodes in a graph-based workflow.
🎯 Interview Focus & Questions
Q: Why is LangGraph preferred over linear chains for production agents?
A: LangGraph supports cyclic loops, explicit branch conditionals, built-in state persistence, time-travel debugging, and human-in-the-loop pause/resume gates.
38. LlamaIndex Concepts
🇬🇧 English Definition
LlamaIndex is a data-centric framework engineered specifically to connect enterprise data sources (SQL, Notion, PDFs) to LLMs via document connectors, indexers, retrievers, and query engines.
🇮🇳 Hinglish Definition
LlamaIndex framework specific data ingestion, custom indexing, knowledge graphs aur enterprise RAG pipelines build karne ke liye optimize kiya gaya hai.
// LlamaIndex High-Level Workflow Conceptual Structure
def llamaindex_conceptual_flow(document_list):
// 1. Connect and parse documents
parsed_nodes = [f"Node_{i}: {doc}" for i, doc in enumerate(document_list)]
// 2. Build VectorStoreIndex
index = f"VectorStoreIndex with {len(parsed_nodes)} nodes"
// 3. Create QueryEngine
query_engine = f"QueryEngine initialized over {index}"
return query_engine
print(llamaindex_conceptual_flow(["PDF 1 content", "PDF 2 content"]))
🔍 Line-by-Line Code Breakdown
- Nodes & VectorStoreIndex: Core LlamaIndex primitives splitting documents into chunk nodes and building queryable search indexes.
🎯 Interview Focus & Questions
Q: What is the core difference between LangChain and LlamaIndex?
A: LangChain focuses broadly on action chains, tools, and agent workflows; LlamaIndex specializes deeply in data ingestion, indexing, and advanced retrieval optimization.