In this blog, I will document the udemy course I watched "LangChain- Develop LLM powered applications with LangChain" by Eden Marco.
This blog aims to help fellow learners set up and build their first LangChain-powered app using both OpenAI and local LLMs like LLaMA3 with Ollama.
Project Setup
- Clone starting branch
- Create pipenv environment
- Install LangChain
- Write boilerplate code
- Setup Pycharm Runners
marygracezabala@Marys-MBP LANGCHAIN_PROJECTS % git clone -b 1-start-here https://github.com/emarco177/ice_breaker.git
git add *
git commit -m "Added icebeaker_project"
git push 1-start-here originInstall pipenv
cd icebreaker
pip3 install pipenv
pipenv install
pipenv shell
This will create virtual environment and pipfile.lock
Install Langchain
pip install langchain
pipenv install langchain-openaiThis langchain-openai integrates with GPT3.5
Create the python file ice_breaker.py
if __name__ = __main__:
print(Hello LangChain!)
Add debug
https://code.visualstudio.com/docs/python/debugging
Include the envfile in the debug
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Attach using Process Id",
"type": "debugpy",
"request": "attach",
"processId": "${command:pickProcess}"
},
{
"name": "Icebreaker Runner",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/icebreaker/.env"
}
]
}
Install formatter black pipenv install black
Sometimes the .env may not be picked up easily and debug is not working properly. Just quit and reoprn the vscode as the shell settings may need to be reinitialized to vscode. Alternatively, to run the environment file, run pipenv run python-dotenv
What is LangChain?
- Framework for developing applications powered by language model
- Connect language model to other sources of data
- Allow language data to interact with the environment
- Create abstraction of task that is repetetive

Your First LangChain application-Chaining a simple prompt
- PromptTemplate - helps to translate user input and parameters into instructions for a language model
- ChatModel - wrappers around LLM. support assignment of distinct roles to conversation messages, helping to distinguish messages from the AI, users, and instructions such as system messages.
The chat model interface is based around messages rather than raw text. The types of messages currently supported in LangChain are AIMessage, HumanMessage, SystemMessage, FunctionMessage and ChatMessage -- ChatMessage takes in an arbitrary role parameter. Most of the time, you'll just be dealing with HumanMessage, AIMessage, and SystemMessage
- Chains - LangCHain provides a standard interface for Chains as well as some common implementations of chains for ease of use. combine things together.
- Working summary example
Prompt Template
- Input to the language model
- takes the input as a dictionary, each key represents a variable
Prompt Template Input --> PromptValue Dictionary --> LLM/Chat Model
- String PromptTemplates - used to format a single string (simpler inputs)
Chat Models
You can create API key in https://platform.openai.com/api-keys

import os
from dotenv import load_dotenv
from langchain.prompts.prompt import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
information = """
Elon Reeve Musk (/ˈiːlɒn/; born June 28, 1971) is a businessman and investor known for his key roles in space company SpaceX and automotive company Tesla, Inc. Other involvements include ownership of X Corp., formerly Twitter, and his role in the founding of The Boring Company, xAI, Neuralink and OpenAI. He is one of the wealthiest people in the world; as of June 2024, Forbes estimates his net worth to be US$214 billion.[4]
"""
if __name__ == "__main__":
load_dotenv
print("Hello LangChain!")
print(os.environ["OPENAI_API_KEY"])
summary_template = """
given the information {information} about a person from I want to create:
1. a short summary
2. two interesting facts about them
"""
summary_prompt_template = PromptTemplate(
input_variables="infomation", template=summary_template
)
llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo")
chain = summary_prompt_template | llm
res = chain.invoke(input={"information": information})
print(res)OpenSource Models
- Mistral
- Ollama - build llm in our local machines - generate by meta - need to download
Using Ollama
marygracezabala@Marys-MBP ~ % ollama run llama3
pulling manifest
pulling manifest
pulling 6a0746a1ec1a... 100% ▕████████████████▏ 4.7 GB
pulling 4fa551d4f938... 100% ▕████████████████▏ 12 KB
pulling 8ab4849b038c... 100% ▕████████████████▏ 254 B
pulling 577073ffcc6c... 100% ▕████████████████▏ 110 B
pulling 3f8eb4da87fa... 100% ▕████████████████▏ 485 B
verifying sha256 digest
writing manifest
removing any unused layers
success
>>>
>>>
>>> hi
Hi! It's nice to meet you. Is there something I can help you with, or
would you like to chat?
You can also install ollama in your pipenv
(ice_breaker) marygracezabala@Marys-MBP ice_breaker % sudo pipenv install langchain-ollama
Password:
Loading .env environment variables...
Installing langchain-ollama...
Resolving langchain-ollama...
✔ Installation Succeeded
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.
Installing dependencies from Pipfile.lock (489837)...
Here is the code. The good thing about llm is that it has stroutput to return you response in readable format. It has also a json formatter
import os
from dotenv import load_dotenv
from langchain.prompts.prompt import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain_ollama import ChatOllama
from langchain_core.output_parsers.string import StrOutputParser
information = """
Elon Reeve Musk (/ˈiːlɒn/; born June 28, 1971) is a businessman and investor known for his key roles in space company SpaceX and automotive company Tesla, Inc. Other involvements include ownership of X Corp., formerly Twitter, and his role in the founding of The Boring Company, xAI, Neuralink and OpenAI. He is one of the wealthiest people in the world; as of June 2024, Forbes estimates his net worth to be US$214 billion.[4]
Musk was born in Pretoria, a member of the South African Musk family, and briefly attended the University of Pretoria before immigrating to Canada at age 18, acquiring citizenship through his Canadian-born mother. Two years later, he matriculated at Queen's University at Kingston in Canada. Musk later transferred to the University of Pennsylvania and received bachelor's degrees in economics and physics. He moved to California in 1995 to attend Stanford University, but dropped out after two days and, with his brother Kimbal, co-founded online city guide software company Zip2. The startup was acquired by Compaq for $307 million in 1999. That same year, Musk co-founded X.com, a direct bank. X.com merged with Confinity in 2000 to form PayPal. In October 2002, eBay acquired PayPal for $1.5 billion. Using $100 million of the money he made from the sale of PayPal, Musk founded SpaceX, a spaceflight services company, in 2002.
In 2004, Musk was an early investor in electric vehicle manufacturer Tesla Motors, Inc. (later Tesla, Inc.). He became the company's chairman and product architect, assuming the position of CEO in 2008. In 2006, Musk helped create SolarCity, a solar-energy company that was acquired by Tesla in 2016 and became Tesla Energy. In 2013, he proposed a hyperloop high-speed vactrain transportation system. In 2015, he co-founded OpenAI, a nonprofit artificial intelligence research company. The following year, Musk co-founded Neuralink—a neurotechnology company developing brain–computer interfaces—and The Boring Company, a tunnel construction company. In 2018, the U.S. Securities and Exchange Commission (SEC) sued Musk, alleging that he had falsely announced that he had secured funding for a private takeover of Tesla. To settle the case, Musk stepped down as the chairman of Tesla and paid a $20 million fine. In 2022, he acquired Twitter for $44 billion. He subsequently merged the company into newly created X Corp. and rebranded the service as X the following year. In March 2023, Musk founded xAI, an artificial intelligence company.
Musk has expressed views that have made him a polarizing figure.[5] He has been criticized for making unscientific and misleading statements, including COVID-19 misinformation and appearing to endorse antisemitic conspiracy theories, which he later apologized for.[5][6][7][8] His ownership of Twitter has been similarly controversial, being marked by layoffs of large numbers of employees, an increase in hate speech, misinformation and disinformation posts on the website, and changes to Twitter Blue verification.
"""
if __name__ == "__main__":
load_dotenv
print("Hello LangChain!")
summary_template = """
given the information {information} about a person from I want to create:
1. a short summary
2. two interesting facts about them
"""
summary_prompt_template = PromptTemplate(
input_variables="infomation", template=summary_template
)
llm = ChatOllama(model="llama3")
# chain = LLMChain(llm=llm, prompt=summary_prompt_template)
chain = summary_prompt_template | llm | StrOutputParser()
res = chain.invoke(input={"information": information})
print(res)
If there is no StrOutputParser, here is the response:
Hello LangChain!
content="Here's what I came up with:\n\n**Summary:** Elon Reeve Musk is a business magnate and investor known for his roles in companies such as SpaceX, Tesla, Inc., and Twitter (now X Corp.). He has been involved in various ventures, including The Boring Company, Neuralink, OpenAI, and more. As of 2024, Forbes estimates his net worth to be over $214 billion.\n\n**Interesting Facts:**\n\n1. **Dropout turned entrepreneur:** Musk dropped out of Stanford University after just two days to co-found Zip2, an online city guide software company that was later acquired for $307 million.\n2. **Controversial figure:** Musk has been criticized for spreading misinformation and making unscientific statements on topics like COVID-19 and antisemitic conspiracy theories. His ownership of Twitter has also led to controversy, with concerns about hate speech, disinformation, and changes to the platform's verification process." response_metadata={'model': 'llama3', 'created_at': '2024-08-17T02:39:46.833927Z', 'message': {'role': 'assistant', 'content': ''}, 'done_reason': 'stop', 'done': True, 'total_duration': 14231223042, 'load_duration': 5829665208, 'prompt_eval_count': 708, 'prompt_eval_duration': 2278164000, 'eval_count': 190, 'eval_duration': 6118557000} id='run-28425e9b-e5cc-4b3e-a7fa-740dd066eeb3-0' usage_metadata={'input_tokens': 708, 'output_tokens': 190, 'total_tokens': 898}
If there is StrOutput, here is the reposnse
Hello LangChain!
Here's what I came up with:
**Summary:** Elon Musk is a businessman and investor known for his key roles in space company SpaceX, automotive company Tesla, Inc., and other ventures. He is one of the wealthiest people in the world.
**Interesting Facts:**
1. **Early Entrepreneurial Spirit**: At just 18 years old, Musk immigrated to Canada and acquired Canadian citizenship through his mother. Two years later, he co-founded online city guide software company Zip2, which was acquired by Compaq for $307 million in 1999.
2. **Polarizing Figure**: Elon Musk has been criticized for making unscientific statements and spreading misinformation, including COVID-19 misinformation and appearing to endorse antisemitic conspiracy theories (which he later apologized for). His ownership of Twitter has also been marked by controversy, with layoffs, increased hate speech, and changes to verification processes.
For fetching linked in profile via proxycurl
First we just want to get the data from proxycurl
import requests
from dotenv import load_dotenv
import os
api_endpoint = "https://nubela.co/proxycurl/api/v2/linkedin"
header_dict = {"Authorization": f'Bearer {os.environ.get("PROXYCURL_API_KEY")}'}
response = requests.get(
api_endpoint,
params={"url":"https://www.linkedin.com/in/mary-grace-zabala/"},
headers=header_dict,
timeout=10
)
print(response.json())
print(response._content.decode('utf-8'))
Copy the response and put in jsonlint to validate the json. Then we can go the gist to paste the json. Here is my json parsed in gist https://gist.githubusercontent.com/grace188031/a25f26effe759e4b5cc834943acbaa21/raw/179fa6f0cab7d7b8dbafb9cffdbb8936b3196c44/grace-zabala.json
Then create a script to either get the data in gist or in proxycurl. I prefer the gist cause there is cost when getting data from proxcurl
import os
import requests
from dotenv import load_dotenv
load_dotenv()
def scrape_linkedin_profile(linkedin_profile_url: str, mock: bool = False):
"""scrape information from LinkedIn profiles,
Manually scrape the information from LinkedIn profile"""
if mock:
linkedin_profile_url = "https://gist.githubusercontent.com/grace188031/a25f26effe759e4b5cc834943acbaa21/raw/179fa6f0cab7d7b8dbafb9cffdbb8936b3196c44/grace-zabala.json"
response = requests.get(
linkedin_profile_url,
timeout=10,
)
else:
api_endpoint = "https://nubela.co/proxycurl/api/v2/linkedin"
header_dict = {"Authorization": f'Bearer {os.environ.get("PROXYCURL_API_KEY")}'}
response = requests.get(
api_endpoint,
params={"url":linkedin_profile_url},
headers=header_dict,
timeout=10
)
data = response.json()
data = {
k: v
for k, v in data.items()
if v not in ([], "", "",None)
and k not in ["people_also_viewed", "certifications"]
}
if data.get("groups"):
for group_dict in data.get("groups"):
group_dict.pop("profile_pic_url")
return data
# Use proxycurl
if __name__ == "__main__":
print(
scrape_linkedin_profile(
linkedin_profile_url="https://www.linkedin.com/in/mary-grace-zabala/",mock=True)
)
Now we are going to used our linkedindata to parse in our langchain
import os
from dotenv import load_dotenv
from langchain.prompts.prompt import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
# from langchain_ollama import ChatOllama
from langchain_core.output_parsers.string import StrOutputParser
from third_parties.linkedin import scrape_linkedin_profile
information = """ """
if __name__ == "__main__":
load_dotenv
print("Hello LangChain!")
print(os.environ["OPENAI_API_KEY"])
summary_template = """
given the LinkedIn {information} about a person from I want to create:
1. a short summary
2. two interesting facts about them
"""
summary_prompt_template = PromptTemplate(
input_variables=["infomation"], template=summary_template
)
llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo")
# chain = LLMChain(llm=llm, prompt=summary_prompt_template)
chain = summary_prompt_template | llm | StrOutputParser() | StrOutputParser()
linkedin_data = scrape_linkedin_profile("https://www.linkedin.com/in/mary-grace-zabala/",mock=True)
res = chain.invoke(input={"information": linkedin_data})
print(res) The output will be:
1. Mary Grace Zabala is a Senior Service Engineer specializing in systems, Linux, networks, cloud, and security. With certifications in CCNP Encore, Redhat, Azure, and Palo Alto, she has a successful track record as an incident responder at Trend Micro and has effectively managed data center network operations at Accenture.
2. Two interesting facts about Mary Grace Zabala:
- She received multiple awards for her outstanding service and contributions, including the "Trustworthiness and Customer Excellence Award" and the "Service Management Award" at Trend Micro.
- Mary Grace has a Bachelor's degree in Electronics Engineering from Don Honorio Ventura Technological State University, showcasing her strong educational background in the field.
No Comments