Tuesday, April 28, 2026

AGENTIC AI 002 : Agent to Parse Text and provide answers

!pip install langchain langchain-core langchain-community langchain-google-genai faiss-cpu langchain-text-splitters


from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate

from langchain_core.output_parsers import StrOutputParser


import os
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings

from google.colab import userdata
# --- Setup ---
os.environ["GOOGLE_API_KEY"] = userdata.get('geminiapikey')


documents = [
    "Our company offers 21 days of paid annual leave. Employees may work from home up to three days a week with manager approval. Health insurance covers the employee, spouse, and two children.",
    "Standard working hours are 9:00–18:00 with a 1-hour break; flexible start between 8:00–10:00 if 8 hours are met.",
    "The company observes 12 public holidays per calendar year, announced each December.",
    "Employees receive 12 paid sick days per year; a doctor’s note is required after 2+ consecutive days.",
    "Parental leave: 16 weeks paid maternity and 4 weeks paid paternity; additional unpaid leave per local law.",
    "Up to 7 unused annual leave days may carry over; cash encashment is not offered.",
    "Overtime must be pre-approved and is compensated at 1.5× or as time off in lieu within 60 days.",
    "Hybrid work: up to 3 WFH days/week with manager approval; availability required during core hours 10:00–16:00.",
    "Company provides a laptop; eligible roles receive a ₹2,000/month home-office stipend.",
    "Expenses must be submitted within 30 days via the expense portal; economy airfare and mid-tier hotels; receipts required for amounts over ₹1,000.",
    "Medical insurance covers employee, spouse, and up to two children; optional parental cover at employee cost.",
    "Payroll runs on the last business day of the month; reimbursements paid with the next payroll.",
    "Notice period is 30 days for voluntary resignation; the company may provide pay in lieu of notice.",
    "The company enforces a zero-tolerance policy for harassment or discrimination; violations may lead to termination.",
    "Employees must follow the IT acceptable-use policy; confidential data cannot be shared outside approved tools."
]

# --- Convert to docs ---
docs = [Document(page_content=d) for d in documents]

# --- Split ---
splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=30)
chunks = splitter.split_documents(docs)

# --- Embeddings ---
#embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
embeddings = GoogleGenerativeAIEmbeddings(model="gemini-embedding-2-preview")

# --- Vector store ---
vectorstore = FAISS.from_documents(chunks, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 6})

# --- LLM ---
#llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0)

llm = ChatGoogleGenerativeAI(model="gemini-3-flash-preview", temperature=0)

# --- Prompt ---
prompt = ChatPromptTemplate.from_template("""
You are an HR assistant. Answer ONLY from the context.

Rules:
- Do not use outside knowledge
- If answer is not found, say "Not mentioned"
- Answer in a respectful way
- Answer in complete sentences

Context:
{context}

Question:
{question}
""")

# --- Helper ---
def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

# --- RAG Chain (LCEL) ---
rag_chain = (
    {
 

      "context": retriever | format_docs,
        "question": lambda x: x
    }
    | prompt
    | llm
    | StrOutputParser()
)

# --- Query ---
response = rag_chain.invoke("What is the sick leave policy?")

print(response)


Similarity search, MMR and similarity Score threshold : the popular semantic search algos used for retrieval by RAG pipelines

 In search and information retrieval, a search type of "MMR" stands for Maximal Marginal Relevance. 

It is an algorithm used to balance relevance (how well a result matches your query) with diversity (how different the results are from one another). 

Why it is used

Standard search methods (like Similarity Search) often return results that are very similar to each other. For example, if you search for "black jackets," a standard search might give you five nearly identical bomber jackets. 
MMR prevents this "echo chamber" by: 
  • Reducing Redundancy: It penalises documents that are too similar to results already selected for the list.
  • Increasing Coverage: It ensures the results cover different aspects or perspectives of a topic.
  • Optimising Context: In AI systems like RAG (Retrieval-Augmented Generation), MMR is used to feed the AI a diverse set of facts rather than the same information repeated multiple times, leading to more comprehensive answers. 

How it works

MMR uses a mathematical formula to rank items one by one. It chooses the next item by calculating a score based on a trade-off parameter called Lambda ($\lambda$): 
  • Relevance Component: How much the item matches the query.
  • Diversity Component: How much the item differs from items already picked. 
Lambda ($\lambda$) Value Effect
1.0Pure Relevance: Results are identical to a standard similarity search.
0.5Balanced: A mix of highly relevant and diverse results (often the default).
0.0Pure Diversity: Prioritises different results even if they are less relevant.
This search type is widely supported in modern vector databases and frameworks such as LangChain, OpenSearch, and Qdrant. 


retriever = vectorstore.as_retriever(
    search_type="mmr",
    search_kwargs={"k": 6, "lambda_mult": 0.5}
)


LangChain's standard VectorStoreRetriever supports three main search algorithms (or "search types") natively. Beyond these, LangChain provides a massive ecosystem of over 40 specialized retrievers that implement more complex algorithms like keyword matching, hybrid search, and multi-step reasoning. 

1. Built-in search_type Options 

When you create a retriever from a vector store using .as_retriever(), you can specify these three primary types: [4]
  • similarity (Default): A standard Top-K search. It uses cosine similarity or Euclidean distance to find the $K$ most similar documents to your query vector.
  • mmr (Maximal Marginal Relevance): As discussed, this balances relevance and diversity to avoid redundant results.
  • similarity_score_threshold: This retrieves documents like a standard similarity search but filters out any that fall below a specific relevance score (set via score_threshold). 

2. Advanced Retrieval Algorithms

For more complex needs, LangChain offers specialized retrievers that go beyond simple vector matching: [8]
  • BM25 Retriever: A "sparse" retriever based on keyword frequency (TF-IDF style), which is often better for finding exact terms rather than abstract meanings.
  • Ensemble Retriever: Combines multiple algorithms (e.g., BM25 + Semantic Search) and reranks the results using a method like Reciprocal Rank Fusion.
  • Self-Query Retriever: Uses an LLM to transform a natural language query into a structured query (e.g., adding metadata filters like "documents from 2023 only") before searching.
  • Multi-Query Retriever: Uses an LLM to generate multiple versions of your question from different perspectives, retrieves results for all of them, and then merges the best findings.
  • Parent Document Retriever: Searches small text chunks (which are easier for algorithms to match) but returns the larger "parent" document to give the LLM more context.
  • Time-Weighted Retriever: Combines semantic similarity with a "time decay" factor, prioritizing more recent documents—perfect for news or logs. 

Summary of Differences

Algorithm Type GoalUse Case
Top-K (Similarity)Pure RelevanceStandard Q&A where you want the closest matches.
MMRRelevance + DiversityAvoiding repetitive information in the context.
Hybrid (Ensemble)Meaning + KeywordsFinding specific technical terms while keeping semantic context.
Self-QueryStructured SearchWhen you have a lot of metadata (dates, authors, tags).
Do you want to know how to combine a keyword search and a vector search into a single Ensemble Retriever?




multi agent project ideas

 A high-quality agent crew example—often built using frameworks like CrewAI —involves specialized agents (e.g., a researcher, writer, and editor) collaborating autonomously on a shared goal. A top example is a Content Creation Crew, where agents with distinct roles, backstories, and tools work together to research, write, and polish technical content efficiently.


Top Examples of Agent Crews
  • Content Creation Crew: A researcher gathers data, a writer creates a draft, and an editor refines it.
  • Stock Analysis Crew: A financial analyst researches stock trends, while a reporter summarizes findings.
  • Recruitment/HR Crew: Agents screen resumes, match profiles to positions, and draft personalized outreach emails.
  • Travel Planning Crew: Agents research flights, hotels, and attractions, then produce a personalized itinerary. 
Structure of an Effective Crew
  1. Agents (Specialists): Defined by role, goal, and backstory.
  2. Tasks (Actions): Specific, actionable assignments for each agent.
  3. Tools (Capabilities): External tools, such as web search (e.g., ExaSearch) or data analysis tools, assigned to agents. 

https://docs.crewai.com/en/examples/example

https://github.com/crewAIInc/crewAI-examples/tree/main/crews

https://github.com/cybersamurai2410/stock-analysis_multi-agents-AI


A travel planning agent crew uses specialized AI agents to collaborate on researching, booking, and creating detailed itineraries, often implemented through frameworks like
Microsoft AutoGen

or CrewAI. These agents work together, handling tasks such as flight research, hotel booking, and activity recommendations based on user preferences.

Key Examples of Travel Planning Crews:
  • Personalized Surprise Trip Planner: An agent crew specialized in crafting custom, surprise itineraries based on specific user profiles, preferences, and constraints.
  • Collaborative Itinerary Builder (AutoGen): Multiple agents (e.g., a flight researcher, hotel specialist, and activity planner) use a round-robin approach to build a comprehensive, multi-day itinerary.
  • Group Trip Organizer: Agents analyze various inputs, such as budget, desired activities, and accommodation preferences, to create a shared travel plan suitable for multiple people. 
Common Agent Roles in a Travel Crew:
  • Researcher: Identifies destinations, local regulations, and safety tips.
  • Logistics Specialist: Focuses on flight, hotel, and transportation booking.
  • Itinerary Planner: Outlines daily activities, attractions, and dining options. 
For manual planning, structured templates are also useful, such as Trello Travel Planning Template or a
Notion-based trip planner






A high-quality Recruitment/HR Agent Crew is a multi-agent system where specialized AI agents collaborate to automate the end-to-end hiring process, ranging from sourcing to onboarding. A leading example is the "Talent Acquisition Squad" designed using frameworks like CrewAI, which can reduce a 40-hour recruitment process to just a few hours. 

The Recruitment/HR Agent Crew Example

This crew consists of specialized agents collaborating on a shared goal (e.g., "Hire a Senior Python Developer").
  • Agent 1: Job Description Architect (Creator)
    • Goal: Write a compelling, accurate job description.
    • Role: Analyzes company culture and role requirements to create engaging postings.
    • Tools:
      SerperDevTool

      for research.
  • Agent 2: Talent Sourcing Specialist (Researcher)
    • Goal: Find top candidates across platforms (LinkedIn, GitHub).
    • Role: Searches for candidates matching skill requirements, including passive talent.
    • Tools: Web search, Scraping tools.
  • Agent 3: Resume Screening & Scoring Agent (Evaluator)
    • Goal: Rank candidates objectively.
    • Role: Parses resumes and scores them against job criteria (e.g., skills, experience) in seconds.
    • Tools:
      FileReadTool

      ,
      MDXSearchTool

      .
  • Agent 4: Interview Coordinator Agent (Scheduler)
    • Goal: Schedule interviews without back-and-forth emails.
    • Role: Checks interviewer calendars and candidate availability, sends meeting links.
  • Agent 5: Outreach & Communication Agent (Writer)
    • Goal: Maintain candidate engagement.
    • Role: Sends personalized follow-ups, updates, and rejection emails to prevent ghosting. 
Key Benefits of this Crew
  • 5x Faster Hiring Cycles: Reduces time-to-fill roles significantly.
  • Improved Screening Consistency: Removes unconscious bias in initial screening stages.
  • 24/7 Candidate Engagement: Chatbots capture and engage candidates instantly.
  • Reduced Admin Work: Automates tedious tasks like resume parsing and scheduling. 
Implementation Tools
  • CrewAI: For structuring the agents, tasks, and workflow.
  • Lyzr: Provides pre-built AI agents for onboarding and performance management.
  • MindStudio: A no-code platform to build custom AI agents that work together. 
This crew structure ensures that high-quality candidates are surfaced immediately, allowing human HR professionals to focus on relationship-building, cultural fit assessments, and final negotiations. 



Creating a Content Creation Crew involves defining specialized AI agents (e.g., researcher, writer, editor) within a framework like CrewAI, equipping them with tools like search engines, and setting a sequential workflow to automate research, drafting, and polishing. Key steps include defining agent roles, creating tasks, and running them to generate content. 

Steps to Create a Content Creation Crew
  1. Define Agent Roles (agents.yaml):
    • Researcher: Expert in finding high-quality information using tools.
    • Writer: Creates content based on research, adhering to a specific tone.
    • Editor/Publisher: Refines, formats, and ensures quality before publication.
  2. Assign Tasks (tasks.yaml):
    • Research Task: "Find the latest trends regarding X and summarize them."
    • Writing Task: "Write a 500-word blog post based on the research provided."
    • Editing Task: "Edit the blog post for flow and conciseness".
  3. Equip Agents with Tools:
    • Give the researcher tool access to search engines (e.g., SERP API).
  4. Define Workflow (Sequential):
    • Configure the crew so the writer waits for the research to be completed, and the editor waits for the writing to finish, as detailed in the CrewAI Documentation.
  5. Execute and Refine:
    • Run the crew script and analyze output to improve agent prompts and task instructions. 
This structure allows you to build a system that can automate the majority of content creation while ensuring high-quality, specialized results.



.


.



Agentic AI 001 : AI Agent to extract info from a static web page

 # STEP 1.1 INSTALL THE REQUIRED PACKAGES

!pip install langchain_community langchain_google_genai
!pip install -U duckduckgo-search

#you may see an error regarding version of request package ,
google colab requires a lower version.
You can right now ignore this message because we are not using google colab
libs in this notebook.






# STEP 1.2 IMPORT THE NECESSARY MODULES

# For loading the OpenAI API key safely into the colab environment
import os
from google.colab import userdata

# For Extracting the text from the URL
import requests
from bs4 import BeautifulSoup

# For creating the agent
#from langchain.agents import initialize_agent, Tool, AgentType
#from langchain.chat_models import ChatOpenAI

#### # STEP 1.3 LOAD THE OPEN AI API KEY
#### os.environ["OPENAI_API_KEY"] = userdata.get('openai')  
#### The original tutorial ised OPEN AI, but the OPENAI API KEY IS NOT FREE, HENCE WE WILL USE GEMINI.

# Retrieve the secret and set it as an environment variable
os.environ["GOOGLE_API_KEY"] = userdata.get('geminiapikey')

# Now LangChain will automatically find it
from langchain_google_genai import ChatGoogleGenerativeAI
#llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash-lite", temperature=0)
#llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", temperature=0)
llm = ChatGoogleGenerativeAI(model="gemini-3-flash-preview", temperature=0)


# For creating the agent
#from langchain.agents import initialize_agent, Tool, AgentType
#from langchain.chat_models import ChatOpenAI


try:
    # A simple call to verify connectivity
    response = llm.invoke("Are you online? Answer with 'Yes' and your model version.")
    print(f"Response: {response.content}")
except Exception as e:
    print(f"Error: {e}")







# NEW 2026 IMPORTS
from langchain.agents import create_agent
from langchain_core.tools import tool

# 2. DEFINE THE WEB TOOL
@tool
def website_qa_tool(url_and_question: str) -> str:
    """
    Input format: 'url | question'.
    Scrapes a website and returns the content for answering questions.
    """
    try:
        url, question = url_and_question.split("|", 1)
        headers = {'User-Agent': 'Mozilla/5.0'}
        response = requests.get(url.strip(), headers=headers, timeout=10)
        soup = BeautifulSoup(response.text, 'html.parser')

        for script in soup(["script", "style"]):
            script.extract()

        text = " ".join(soup.get_text().split())
        return text
        #return text[:25000] # Gemini 2.5 context handles this easily
    except Exception as e:
        return f"Scraping Error: {str(e)}"

# 3. INITIALIZE GEMINI


# 4. CREATE THE AGENT (Modern 2026 Method)
# This replaces create_react_agent AND AgentExecutor
agent = create_agent(
    model=llm,
    tools=[website_qa_tool],
    system_prompt="You are a research assistant. Use the website_qa_tool to find information from URLs."
)






# 5. RUN
print("\n--- Running Agent ---\n")
#query = "https://www.wikipedia.org | What is the main mission of Wikipedia?"
#query = "https://www.w3schools.com | Do they have any Angular course (NOT AngularJS) ?"
#query = "https://www.tutorialspoint.com | does it have any tutorial on DSA Learning  ? If yes please give link"
#query = "https://en.wikipedia.org/wiki/Arizona | How many private colleges and universities are there in Arizona State ?"
query = "https://en.wikipedia.org/wiki/Arizona | How many films were shot in Arizona State ?"

try:
    # In 2026, agents are run via .invoke() with a 'messages' list
    response = agent.invoke({"messages": [("user", query)]})

    print(response)
    # Get the last message from the agent's response
    final_answer = response["messages"][-1].content
    print("\n--- FINAL ANSWER ---")
    print(final_answer)
except Exception as e:
    print(f"\n❌ Agent Error: {e}")

Temperature, Thinking Budget and Thinking Level

    

Temperature, thinking budget, and thinking level are key parameters for configuring LLM behavior. Temperature controls output randomness (0-2.0, default 1.0)). Thinking Budget determines the number of tokens dedicated to reasoning, while Thinking Level (e.g., MINIMAL, MEDIUM, HIGH) adjusts the depth of reasoning for complex tasks. 

Using thinking budget and thinking level simultaneously will return error 400. 

1. Temperature (Randomness Control)
  • Definition: A sampling parameter that controls the randomness of the model's output. It affects the probability distribution over possible next words.
  • Usage Examples:
    • Low Temperature (\(<0.5\)): Ideal for coding, data extraction, or factual tasks where accuracy is key (e.g., set to \(0\) for near-deterministic results).
    • High Temperature (\(>0.7\)): Suitable for creative writing, brainstorming, or marketing copy to generate varied responses.
  • Synonyms/Related Terms: Randomness, Sampling Temperature, Creativity Setting.
  • Important Note: For Gemini 3, a default of \(1.0\) is recommended for best performance, and lower settings may cause instability. 
2. Thinking Budget (Reasoning Amount)
  • Definition: Specific to older or specific API implementations (e.g., Gemini 2.5), this directly sets a numerical budget of tokens the model can use for intermediate reasoning before generating the final answer.
  • Usage Examples:
    • High Budget: Used for complex logic, multi-step math problems, or deep research.
    • Zero/Low Budget: Used to disable thinking to save costs and reduce latency.
  • Synonyms/Related Terms: Reasoning Tokens, Thought Limit. 
3. Thinking Level (Reasoning Depth) 
  • Definition: A higher-level configuration (introduced in Gemini 3) that controls the depth of reasoning.
  • Types/Usage Examples:
    • MINIMAL (e.g., Flash-Lite): Best for simple tasks requiring low latency.
    • MEDIUM (e.g., Flash/Pro): Balanced approach for moderate complexity.
    • HIGH (e.g., Pro): Used for complex, multi-step reasoning.
  • Synonyms/Related Terms: Reasoning Depth, Logic Level. 
Summary of Differences
Feature FocusUse Case
TemperatureCreativity & RandomnessCreative writing vs. factual answers
Thinking BudgetResource Control (Tokens)Managing cost and speed in reasoning
Thinking LevelReasoning Depth (Logic)Simple vs. complex problem-solving                            
    

credits for the below adaptation function : 
https://help.apiyi.com/en/gemini-api-thinking-budget-level-error-fix-en.html

Smart Parameter Adaptation Function

def get_thinking_config(model_name: str, complexity: str = "medium") -> dict:
    """
    Automatically selects the correct thinking mode parameter based on model version.

    Args:
        model_name: Gemini model name
        complexity: Thinking complexity ("minimal", "low", "medium", "high", "dynamic")

    Returns:
        Parameter dictionary suitable for extra_body
    """
    # Gemini 3.0 model list
    gemini_3_models = [
        "gemini-3.0-flash-preview",
        "gemini-3.0-pro-preview",
        "gemini-3-flash",
        "gemini-3-pro"
    ]

    # Gemini 2.5 model list
    gemini_2_5_models = [
        "gemini-2.5-flash-preview-04-17",
        "gemini-2.5-flash-lite",
        "gemini-2-flash",
        "gemini-2-flash-lite"
    ]

    # Determine model version
    if any(m in model_name for m in gemini_3_models):
        # Gemini 3.0 uses thinking_level
        level_map = {
            "minimal": "minimal",
            "low": "low",
            "medium": "medium",
            "high": "high",
            "dynamic": "high"  # Default to high
        }
        return {"thinking_level": level_map.get(complexity, "medium")}

    elif any(m in model_name for m in gemini_2_5_models):
        # Gemini 2.5 uses thinking_budget
        budget_map = {
            "minimal": 0,
            "low": 512,
            "medium": 2048,
            "high": 8192,
            "dynamic": -1
        }
        return {"thinking_budget": budget_map.get(complexity, -1)}

    else:
        # Unknown model, default to Gemini 3.0 parameters
        return {"thinking_level": "medium"}

# Usage example
import openai

client = openai.OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.apiyi.com/v1"
)

model = "gemini-3.0-flash-preview"  # Can be switched dynamically
thinking_config = get_thinking_config(model, complexity="high")

response = client.chat.completions.create(
    model=model,
    messages=[{"role": "user", "content": "Your question here"}],
    extra_body=thinking_config
)



Comparing features of LangGraph vs CrewAI

LangGraph Orchestration vs CrewAI Orchestration The following table compares LangGraph and CrewAI orchestration across their menta...