LAB 1b : Excercises using LLMs, LangChain and Prompts
Text summarization, classification, sentiment analysis, generating multiple responses,
code explanation, chatbot application, error handling, prompts with single and multiple
input variables.
ALL THESE EXERCISES TO BE RUN USING OPENAI API AND SPYDER IDE
Ex 1: Text Summarisation
Problem Statement: Summarise the minutes of the meeting given below in 4 bullet points:
Car Manufacturing Company
Board of Directors Meeting Minutes
Agenda:
1. Call to Order
2. Approval of Previous Meeting Minutes
3. CEO's Report
4. Financial Report
Meeting Minutes:
1. Call to Order:
- The meeting was called to order by Bharath Thippireddy.
2. Approval of Previous Meeting Minutes:
- The minutes of the previous board meeting, held on [Date], were reviewed and approved.
3. CEO's Report:
- Bharath Thippireddy presented an overview of the company's performance, highlighting key
achievements and challenges. Key points discussed include:
- Sales figures for the last quarter.
- Progress on cost reduction initiatives.
- Highlights from recent industry events.
- The CEO answered questions from board members.
4. Financial Report:
- The Chief Financial Officer ([CFO's Name]) presented the financial report. Key financial metrics
discussed include:
- Revenue and profit margins.
- Budget vs. actual expenditure.
- Cash flow analysis.
- The board discussed financial performance and the impact on shareholder value.
Page 1 of 8
Program :
from openai import OpenAI
client = OpenAI()
instruction = """ Summarise the minutes of the meeting given below in 4 bullet points:
Car Manufacturing Company
Board of Directors Meeting Minutes
Agenda:
1. Call to Order
2. Approval of Previous Meeting Minutes
3. CEO's Report
4. Financial Report
Meeting Minutes:
1. Call to Order:
- The meeting was called to order by Bharath Thippireddy.
2. Approval of Previous Meeting Minutes:
- The minutes of the previous board meeting, held on [Date], were reviewed and approved.
3. CEO's Report:
- Bharath Thippireddy presented an overview of the company's performance, highlighting key
achievements and challenges. Key points discussed include:
- Sales figures for the last quarter.
- Progress on cost reduction initiatives.
- Highlights from recent industry events.
- The CEO answered questions from board members.
4. Financial Report:
- The Chief Financial Officer ([CFO's Name]) presented the financial report. Key financial metrics
discussed include:
- Revenue and profit margins.
- Budget vs. actual expenditure.
- Cash flow analysis.
- The board discussed financial performance and the impact on shareholder value.
"""
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": [
{
Page 2 of 8
"type": "text",
"text": instruction
}
]
},
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
#print(response)
print(response.choices[0].message.content)
--------------------------------------------------------------------------------------------------------------------------------------
EX2: TEXT CLASSIFICATION
Problem : Classify the companies given below :
Microsoft Corporation, Roche Holding AG, Apple Inc, "Amazon.com, Inc,Pfizer Inc, JPMorgan
Chase & Co.,Johnson & Johnson, Bank of America Corporation, Industrial and Commercial Bank of
China
PROGRAM:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Categorise the companies given : "
"Microsoft Corporation, Roche Holding AG, Apple Inc"
"Amazon.com, Inc,Pfizer Inc, JPMorgan Chase & Co."
"Johnson & Johnson, Bank of America Corporation, Industrial and Commercial Bank of China ."
}
]
},
],
max_tokens=300,
)
print(response.choices[0].message.content)
--------------------------------------------------------------------------------------------------------------------------------------
EX3: SENTIMENT ANALYSIS
PROBLEM: Given a set of Social Media Posts below, analyse the sentiment of each and classify it as
either positive, negative, or neutral. Provide a brief explanation for your classification
Page 3 of 8
1. Just got my hands on the new XPhone - absolutely loving the camera and battery life! 📸🔋
#TechLove
2. Disappointed with the XPhone. Its pricey and not much different from the last model. Expected
more. 😕 #TechTalk
3. XPhones latest update is a game-changer for mobile gaming. The graphics are just incredible! 🎮💯
4. Cant believe I waited this long for the XPhone... its underwhelming and overpriced. Back to my old
phone, I guess. 😒
5. The XPhone has exceeded my expectations. Fast, sleek, and the new AI features are a standout! 🚀
#Innovation
PROGRAM:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": """Below are several social media posts. For each post, please analyze the sentiment
expressed and classify it as either positive, negative, or neutral. Provide a brief explanation for your
classification"
"1. Just got my hands on the new XPhone - absolutely loving the camera and battery life!
📸🔋 #TechLove
2. Disappointed with the XPhone. Its pricey and not much different from the last model. Expected
more. 😕 #TechTalk
3. XPhones latest update is a game-changer for mobile gaming. The graphics are just incredible! 🎮💯
4. Cant believe I waited this long for the XPhone... its underwhelming and overpriced. Back to my old
phone, I guess. 😒
5. The XPhone has exceeded my expectations. Fast, sleek, and the new AI features are a standout! 🚀
#Innovation"""
}
]
},
],
)
print(response.choices[0].message.content)
EX4: GENERATING MULTIPLE RESPONSES
PROBLEM : GENERATE 3 RECIPES FOR BAKING A CAKE
PROGRAM:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": [
Page 4 of 8
{
"type": "text",
"text": "You are a cake baker"
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Get me a recipe to bake a cake"
}
]
},
],
n=3,
max_tokens=300,
)
#print(response)
for i in range(3):
print("Recipe : ", i+1)
print("**************")
print(response.choices[i].message.content)
_------------------------------------------------------------------------------------------------------------------------------------
EX5: CODE EXPLANATION
PROBLEM : EXPLAIN THE PYTHON CODE GIVEN BELOW
PROGRAM:
from openai import OpenAI
client = OpenAI()
instruction = """Explain what this Python code does in one sentence:
number = int(input("Enter a number:"))
primeFlag = True
for i in range(2, number):
if number % i == 0:
primeFlag = False
break
if primeFlag == True:
print(number, " is prime.")
else:
print(number, " is not prime.")
"""
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": [
{
Page 5 of 8
"type": "text",
"text": instruction
}
]
},
],
max_tokens=300,
)
print(response.choices[0].message.content)
EX6: ERROR HANDLING
PROBLEM: THROW AN EXCEPTION IF THE API KEY FAILS TO GET AUTHENTICATED
PROGRAM:
from openai import OpenAI
client = OpenAI(api_key="test")
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What is OpenAI"
}
]
},
]
)
except OpenAI().AuthenticationError as e:
print(f"AuthenticationError : {e}")
EX7: CHATBOT APPLICATION
PROBLEM: CREATE A MATHS TUTOR AS A CHATBOT TO ANSWER SOME QUESTIONS IN MATHS
PROGRAM
from openai import OpenAI
client = OpenAI()
messages = [ {'role':'system', 'content':"You are a Math Tutor"}]
user_messages = ['Explain what is PI', 'Summarize this in two bullet points']
for each_message in user_messages:
user_dict = {'role': 'user', 'content':[{'type': 'text', 'text': each_message}]}
messages.append(user_dict)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages
assist_dict ={'role':'assistant', 'content': [{'type': 'text', 'text':
response.choices[0].message.content}]}
messages.append(assist_dict)
Page 6 of 8
print(response.choices[0].message.content)
EX8: PROMPTS AND LLMs USING LANGCHAIN
PROBLEM: USING PROMPTS WITH LLM
PROGRAM:
#from langchain.llms import OpenAI
from langchain_openai import OpenAI
#temperature indicates the randomness in the response. Between 0 to 1. Its 0 when the
#response is determininstic and 1 when the response is more creative
#default openAI model is text-danvinci-003
llm = OpenAI(temperature = 0.9)
prompt = "Suggest a good name for a company that produces socks"
print(llm(prompt))
#get a deterministic response with temp = 0
#generate 5 creative responses using the prompt repeatedly
responses = llm.generate([prompt]*5)
for name in responses.generations:
print(name[0].text)
EX9: PROMPTING AND PROMPT TEMPLATES
PROBLEM: CREATE A PROMPT WITH ONE INPUT VARIABLE. GENERATE A SUITABLE NAME FOR A
COMPANY THAT MAKES A PARTICULAR PRODUCT (USE ANY PRODUCT NAME). INPUT IS THE
NAME OF THE PRODUCT.
PROGRAM:
from langchain_openai import OpenAI
# import prompt template
from langchain import PromptTemplate
# create the prompt
prompt_template: str = """/
You are a vehicle mechanic, give responses to the following/
question: {question}. Do not use technical words, give easy/
to understand responses.
"""
prompt = PromptTemplate.from_template(template=prompt_template)
# format the prompt to add variable values
prompt_formatted_str: str = prompt.format(
question="Why won't a vehicle start on ignition?")
# instantiate the OpenAI intance
llm = OpenAI(temperature = 0.9)
# make a prediction
prediction = llm.predict(prompt_formatted_str)
# print the prediction
print(prediction)
Page 7 of 8
EX10: CREATING PROMPTS WITH MULTIPLE INPUT VARIABLES
PROBLEM: GENERATE A SUITABLE NAME FOR A COMPANY THAT MAKES A PARTICULAR PRODUCT
(USE ANY PRODUCT NAME) IN A SPECIFIC LANGUAGE. INPUTS ARE THE PRODUCT AND THE
LANGUAGE.
PROGRAM:
from langchain_openai import OpenAI
from langchain import PromptTemplate
prompt = PromptTemplate(
template = """/You are a naming consultant, give responses to the following/
question: {question}. Do not use technical words, give easy/
to understand responses. Give your response in {language}""",
input_variables = ["question", "language"]
)
#format the prompt to add variable’s values
prompt_formatted_str : str = prompt.format(
question = "Suggest a good name for a company that makes socks?",
language = "English"
)
# instantiate the OpenAI instance
llm = OpenAI(temperature = 0.9)
# make a prediction
prediction = llm.predict(prompt_formatted_str)
# print the prediction
print(prediction)
!pip install pydantic==1.10.7
!pip install --upgrade pydantic
!pip install --upgrade langchain
!pip install langchain_openai
Page 8 of 8