0% found this document useful (0 votes)
28 views11 pages

Lang Chain

The document outlines various AI-driven applications, including a simple calculator tool using LangChain, a graph traversal algorithm, and a customer service AI agent. It also describes a career assistant AI that extracts skills from resumes and suggests job roles, along with a feedback generation system for job applications. Additionally, it demonstrates how to create and query documents using LlamaIndex and integrates AI agents for career coaching and planning tasks.

Uploaded by

sneha.pawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views11 pages

Lang Chain

The document outlines various AI-driven applications, including a simple calculator tool using LangChain, a graph traversal algorithm, and a customer service AI agent. It also describes a career assistant AI that extracts skills from resumes and suggests job roles, along with a feedback generation system for job applications. Additionally, it demonstrates how to create and query documents using LlamaIndex and integrates AI agents for career coaching and planning tasks.

Uploaded by

sneha.pawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# Step 1: Install LangChain

!pip install langchain --quiet


# Step 2: Import LangChain Tool
from langchain.tools import Tool
# Step 3: Your Custom Calculator Function
def my_calculator(query: str) -> str:
try:
result = eval(query)
return f"The result is {result}"
except:
return "Sorry, I couldn't calculate that."
# Step 4: Wrap in LangChain Tool
calculator_tool = Tool(
name="Simple Calculator",
func=my_calculator,
description="Use this to calculate math expressions like '10 + 20 * 3'"
)
# Step 5: Our "Mini Agent" Logic (Very Basic)
def simple_agent(user_input):
# If the input looks like a math question, use the calculator
if any(op in user_input for op in ['+', '-', '*', '/', '(', ')']):
print("Agent: I think I should use the calculator tool for this.")
return calculator_tool.run(user_input)
else:
return "Sorry, I don't know how to answer that yet."
# Step 6: Ask the agent a question
question = "(15 + 5) * 2"
response = simple_agent(question)
print("Agent Response:", response)
-----------------------------------------------------------------------------------
------------------

# ✅ Step 1: Create a Graph using a Dictionary (Adjacency List)


graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D"],
"D": ["B", "C"]
}

# ✅ Step 2: Print the Graph


print("Graph (Adjacency List):")
for node in graph:
print(f"{node} is connected to {graph[node]}")

# ✅ Step 3: Visit All Nodes (Simple Traversal using BFS)


def bfs(start_node):
visited = []
queue = [start_node]

print("\nBFS Traversal:")
while queue:
current = queue.pop(0)
if current not in visited:
print(f"Visited: {current}")
visited.append(current)
queue.extend(graph[current])

# ✅ Step 4: Run the Traversal


bfs("A")
-----------------------------------------------------------------------------------
-----------------------------

You are a helpful customer service AI agent. Your goal is to assist customers
quickly and politely. Follow these steps:

1. Greet the user warmly using their name if available.


2. Ask what type of support they need:

* 📦 Order tracking
* 🔄 Return/refund
* 🛒 Product inquiry
* 💬 General question
3. Based on the choice, provide a helpful answer or guide them to the next step.
4. If they ask for tracking, ask for their order ID and show a mock status.
5. If they want a refund, confirm the order ID and explain the process.
6. If the question is unknown or outside scope, politely say:
*“Let me connect you with a human agent to assist further.”*
7. Always end with: *“Is there anything else I can help you with?”*

Use `@name`, `@order_id`, or other dynamic fields as needed.

-----------------------------------------------------------------------------------
-----------------------------

You are a career assistant AI.

Your job is to:


1. Accept resume text input from the user.
2. Extract any known skills from the resume. Focus on skills like Python, Java,
SQL, Excel, Power BI, and Communication.
3. Based on the skills, suggest a suitable job role:
- If the resume includes Python and SQL, suggest "Data Analyst".
- If it includes Java, suggest "Backend Developer".
- Else suggest "IT Support".

Important: Always ask for human approval before finalizing the suggestion.**
Say: "Do you approve this suggested role? (Yes or No)"

If the user says:


- "Yes": say "Great! Finalizing the job role as: <role>"
- "No": ask "Would you like me to suggest another role or do you want to provide
feedback?"

You must stop and wait for the human reply before proceeding.

-----------------------------------------------------------------------------------
-----------------------------

# Agent 1: Resume Screener - Extract skills


def extract_skills(resume_text):
known_skills = ["python", "java", "sql", "excel", "power bi", "communication",
"machine learning"]
extracted = [skill for skill in known_skills if skill in resume_text.lower()]
return extracted

# Agent 2: Skill Matcher - Match to job description


def match_skills(candidate_skills, job_required_skills):
match = [skill for skill in candidate_skills if skill in job_required_skills]
missing = [skill for skill in job_required_skills if skill not in
candidate_skills]
return match, missing

# Agent 3: Feedback Generator


def generate_feedback(match, missing):
feedback = f"You matched {len(match)} out of {len(match)+len(missing)} skills.\
n"
feedback += f"Matched Skills: {match}\n"
if missing:
feedback += f"Missing Skills: {missing}\n"
feedback += "Consider learning these skills to increase your chances."
else:
feedback += "Great! You are a perfect match for this job."
return feedback

# Sample resume (as plain text input)


resume = """
Experienced software engineer with expertise in Python, SQL, and Excel.
Worked on several data-driven projects with strong team collaboration.
"""

# Job description requirements


job_skills = ["python", "sql", "excel", "power bi", "communication"]

# Step 1: Extract skills


candidate_skills = extract_skills(resume)

# Step 2: Match skills


matched, missing = match_skills(candidate_skills, job_skills)

# Step 3: Generate feedback


feedback = generate_feedback(matched, missing)

print("Candidate Skills:", candidate_skills)


print("\n--- Feedback ---")
print(feedback)
-----------------------------------------------------------------------------------
----------------------------

You are a career assistant AI.

Your job is to:


1. Accept resume text input from the user.
2. Extract any known skills from the resume. Focus on skills like Python, Java,
SQL, Excel, Power BI, and Communication.
3. Based on the skills, suggest a suitable job role:
- If the resume includes Python and SQL, suggest "Data Analyst".
- If it includes Java, suggest "Backend Developer".
- Else suggest "IT Support".

Important: Always ask for human approval before finalizing the suggestion.
Say: "Do you approve this suggested role? (Yes or No)"

If the user says:


- "Yes": say "Great! Finalizing the job role as: <role>"
- "No": ask "Would you like me to suggest another role or do you want to provide
feedback?"

You must stop and wait for the human reply before proceeding.
-----------------------------------------------------------------------------------
--------------------------------

# Agent 1: Extract skills from resume


def extract_skills(text):
skills = ["python", "java", "sql", "excel", "communication", "power bi"]
return [skill for skill in skills if skill in text.lower()]

# Agent 2: Suggest job role


def suggest_role(skills):
if "python" in skills and "sql" in skills:
return "Data Analyst"
elif "java" in skills:
return "Backend Developer"
else:
return "General IT Support"

# Human-in-the-Loop approval
def human_approval_flow(resume):
print("📄 Extracting skills...")
extracted = extract_skills(resume)
print("Skills Found:", extracted)

role = suggest_role(extracted)
print(f"\n AI Suggests: Based on your skills, the suitable job is: **{role}**")

# HITL Step
decision = input("\n Do you approve this suggestion? (yes/no): ").lower()

if decision == "yes":
print(f"\n Final Decision: Proceeding with role: {role}")
else:
print("\n Let's review manually or suggest another job with human help.")

# Simulate resume input


resume_text = """
I have experience in Python and SQL. I worked on data projects and dashboards using
Excel.
"""

# Run the system


human_approval_flow(resume_text)
-----------------------------------------------------------------------------------
---------------------------------------------------------------
!pip install llama-index openai PyMuPDF

import os
os.environ["OPENAI_API_KEY"] = ""
from google.colab import files
uploaded = files.upload() # Upload a PDF file here
from llama_index.core import VectorStoreIndex
from llama_index.readers.file import PDFReader

# Load PDF (auto-picks the uploaded file)


file_name = next(iter(uploaded))
reader = PDFReader()
documents = reader.load_data(file=file_name)

# Create index and query engine


index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

# Ask a question
response = query_engine.query("What is this document about?")
print("AI Answer:", response)

-----------------------------------------------------------------------------------
----------------------------------------------------------------

!pip install llama-index openai

import os
os.environ["OPENAI_API_KEY"] = ""

# Create a sample handbook.txt file


with open("handbook.txt", "w") as f:
f.write("""
Welcome to the company! Employees are entitled to 12 paid leaves per year.
Unused leaves can be carried forward to the next year.
The official working hours are from 9:00 AM to 5:00 PM, Monday to Friday.
Please refer to your manager for special leave requests.
""")

print("Company handbook created.")

from llama_index.core import SimpleDirectoryReader, VectorStoreIndex

# Load the document using LlamaIndex


documents = SimpleDirectoryReader(input_dir=".").load_data()

# Create an index from the document


index = VectorStoreIndex.from_documents(documents)
print("Document indexed.")
# Create a query engine
query_engine = index.as_query_engine()

# Ask a question from the handbook


question = "How many paid leaves do employees get?"
response = query_engine.query(question)

# Show the result


print(f"Question: {question}")
print(f" Answer: {response}")

-----------------------------------------------------------------------------------
---------------------------------

!pip install langchain-openai --quiet


import os
os.environ["OPENAI_API_KEY"] = ""

from crewai import Agent, Task, Crew


from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)


agent = Agent(
role="AI Researcher",
goal="Track and summarize the latest in Artificial Intelligence.",
backstory="You're an expert who stays updated on all major AI innovations.",
llm=llm,
verbose=True
)

task = Task(
description="Find and summarize the top 3 AI news updates from this week.",
expected_output="Three concise bullet points summarizing major news.",
agent=agent
)

crew = Crew(agents=[agent], tasks=[task])


result = crew.kickoff()
print(result)
-----------------------------------------------------------------------------------
-------------------------------------------------------

# Step 1: Install required packages


!pip install crewai langchain-openai --quiet
# Step 2: Import packages and set OpenAI key
import os
from crewai import Agent, Task, Crew
from langchain_openai import ChatOpenAI

# Replace this with your real API key


os.environ["OPENAI_API_KEY"] = ""
# Step 3: Create the LLM instance
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.6)
# Step 4: Create the agent
education_agent = Agent(
role="Learning Coach",
goal="Answer technical questions for graduates in simple terms",
backstory="You're a friendly AI mentor who loves breaking down tough concepts
into easy examples.",
llm=llm,
verbose=True
)
# Step 5: Take input from the user
user_question = input(" Ask me a technical question you'd like to learn about: ")
# Step 6: Create the task using the user's question
task = Task(
description=f"Explain: '{user_question}' in simple terms for a graduate, using
examples and analogies.",
expected_output="A short explanation with two examples and one analogy.",
agent=education_agent
)
# Step 7: Run the crew and show the result
crew = Crew(agents=[education_agent], tasks=[task])
result = crew.kickoff()
print("\n Educational Output:\n", result)

-----------------------------------------------------------------------------------
------------------------------------------------------------------

!pip install crewai langchain-openai --quiet


import os
from crewai import Agent, Task, Crew
from langchain_openai import ChatOpenAI

os.environ["OPENAI_API_KEY"] = ""
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.5)
career_researcher = Agent(
role="Career Researcher",
goal="Find the most in-demand tech jobs and their required skills",
backstory="You are an expert in analyzing job market trends.",
llm=llm,
verbose=True
)

skills_analyst = Agent(
role="Skills Gap Analyst",
goal="Identify gaps between current skills and job requirements",
backstory="You help people bridge the gap between what they know and what they
need to succeed.",
llm=llm,
verbose=True
)

resume_advisor = Agent(
role="Resume Advisor",
goal="Provide tips to enhance a graduate's resume or portfolio",
backstory="You are a career counselor with years of experience reviewing
resumes and giving actionable advice.",
llm=llm,
verbose=True
)
user_skills = input("💬 Enter your current skills (comma-separated): ")
target_job = input("🎯 What job role are you targeting? (e.g., Data Analyst): ")
task1 = Task(
description=f"Find top in-demand skills for the job: {target_job}.",
expected_output="A bullet list of 5-7 skills required for this job role.",
agent=career_researcher
)

task2 = Task(
description=f"Compare the user's current skills ({user_skills}) with the
required skills for a {target_job}. Identify missing skills.",
expected_output="A comparison list and a 2-line summary of skill gaps.",
agent=skills_analyst,
context=[task1]
)

task3 = Task(
description="Give specific advice to improve the user's resume and online
profile based on the skill gap.",
expected_output="Tips to improve the resume and portfolio with 3 actionable
suggestions.",
agent=resume_advisor,
context=[task2]
)
crew = Crew(
agents=[career_researcher, skills_analyst, resume_advisor],
tasks=[task1, task2, task3]
)
result = crew.kickoff()
print("\n📝 Final Career Report:\n", result)

-----------------------------------------------------------------------------------
---------------------------------------------------------------------

!pip install crewai langchain-openai --quiet


import os
from crewai import Agent, Task, Crew
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory

# Set your OpenAI API key


os.environ["OPENAI_API_KEY"] = ""

# Load GPT-3.5 model


llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=1)
# Add memory to remember previous conversations
memory = ConversationBufferMemory(memory_key="chat_history")

# Create an agent with memory and verbose logging


career_agent = Agent(
role="Career Coach",
goal="Help students choose careers and guide them",
backstory="You are a mentor who remembers everything discussed earlier.",
llm=llm,
memory=memory,
verbose=True
)
# First task: Suggest best careers
task1 = Task(
description="Suggest 3 trending career options for a computer science
graduate.",
expected_output="3 job roles with 1-line descriptions each.",
agent=career_agent
)

# Run the first task


crew1 = Crew(agents=[career_agent], tasks=[task1])
result1 = crew1.kickoff()

print("\n AI Recommendation:\n", result1)


# Ask user to approve or reject the result
approve = input("Do you approve this career list? (yes/no): ")

if approve.lower() == "yes":
print(" Great! Moving to resume tips...\n")

# Task 2: Give resume advice based on chosen role


chosen_role = input("Which career are you most interested in from the list? ")

task2 = Task(
description=f"Give 3 resume improvement tips to apply for a {chosen_role}
role.",
expected_output="3 actionable suggestions to improve the resume.",
agent=career_agent
)
crew2 = Crew(agents=[career_agent], tasks=[task2])
result2 = crew2.kickoff()
print("\n Resume Suggestions:\n", result2)

else:
print(" Let's restart and explore other options.")
-----------------------------------------------------------------------------------
----------------------------------------------
Terminal:
pip install streamlit crewai langchain-openai python-dotenv

main.py
import streamlit as st
from crewai import Agent, Task, Crew
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv
import os

# Load API key


load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")

# Setup LLM
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.5)

# Define Agents
planner = Agent(
role="Daily Planner",
goal="Organize a user's tasks into a balanced daily schedule",
backstory="You help people plan productive and balanced workdays.",
llm=llm,
verbose=True
)

break_advisor = Agent(
role="Break Advisor",
goal="Analyze the schedule and suggest break times for better focus",
backstory="You care about well-being and prevent burnout through timely
breaks.",
llm=llm,
verbose=True
)

summarizer = Agent(
role="Day-End Reporter",
goal="Summarize the user's daily plan in a friendly tone",
backstory="You write simple and short summaries of daily plans to motivate
users.",
llm=llm,
verbose=True
)

# Streamlit UI
st.set_page_config(page_title="AI Productivity Assistant", layout="centered")
st.title(" Personal Productivity Assistant (Multi-Agent AI)")
st.markdown("Get your day planned by an AI team of Planner, Break Advisor, and
Motivator!")

user_tasks = st.text_area(" Enter your top 5 tasks for today (comma-separated)",


placeholder="E.g., write report, attend team meeting, design slides")

if st.button(" Generate My Plan"):


if user_tasks.strip() == "":
st.warning("Please enter your tasks before proceeding.")
else:
with st.spinner("Thinking hard and working as a team..."):
# Define Tasks
task1 = Task(
description=f"Organize these tasks into a day plan: {user_tasks}",
expected_output="A detailed hourly schedule with start and end
times.",
agent=planner
)

task2 = Task(
description="Review the day plan and suggest 2-3 break slots with
reasons.",
expected_output="List of break times and explanation for each.",
agent=break_advisor,
context=[task1]
)

task3 = Task(
description="Create a cheerful summary of the planned day and break
schedule.",
expected_output="A paragraph that motivates the user for their
day.",
agent=summarizer,
context=[task1, task2]
)

crew = Crew(
agents=[planner, break_advisor, summarizer],
tasks=[task1, task2, task3]
)

final_output = crew.kickoff()

st.success(" Here's your productivity plan for the day:")


st.markdown("---")
st.markdown(final_output)

Run: streamlit run app.py

-----------------------------------------------------------------------------------
---------------------------------------------------------------------

# Install updated OpenAI SDK


!pip install --upgrade openai

# Step 2: Import libraries and set API key


import openai
import os

# Replace with your actual OpenAI API key


openai.api_key = ""
# Step 3: Take user input (Context)
user_city = input("Enter the city in Kerala you're visiting: ")
user_preferences = input("What are your preferences? (e.g., food, nature, culture,
etc.): ")
# Step 4: Create messages (Protocol)
messages = [
{
"role": "system",
"content": "You are an expert AI travel guide for Kerala. Your job is to
plan a 1-day itinerary based on the user's preferences."
},
{
"role": "user",
"content": f"My preferences are: {user_preferences}. I am visiting
{user_city} tomorrow. Please give me a 1-day plan including 3 locations to visit, 1
local food dish to try, and 1 cultural activity."
}
]
# Step 5: Call the GPT-4 model (Model)
response = openai.chat.completions.create(
model="gpt-4",
messages=messages,
temperature=0.7
)
# Step 6: Display the output
itinerary = response.choices[0].message.content
print("\n Your 1-Day Kerala Itinerary:\n")
print(itinerary)

You might also like