import os
import openai
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
True
import os
import openai
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
True
Note: LLM’s do not always produce the same results. When executing the code in your notebook, you may get slightly different answers that those in the video.
# account for deprecation of LLM model
import datetime
# Get the current date
= datetime.datetime.now().date()
current_date
# Define the date after which the model should be set to "gpt-3.5-turbo"
= datetime.date(2024, 6, 12)
target_date
# Set the model variable based on the current date
if current_date > target_date:
= "gpt-3.5-turbo"
llm_model else:
= "gpt-3.5-turbo-0301" llm_model
Let’s start with a direct API calls to OpenAI.
= OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
client
def get_completion(prompt, system = "You are a helpful assistant.", model=llm_model):
= client.chat.completions.create(
completion =model,
model=0,
temperature=[
messages"role": "system", "content": system},
{"role": "user", "content": prompt}
{
]
)return completion.choices[0].message.content
"What is 1+1?") get_completion(
'1 + 1 equals 2.'
= """
customer_email Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse,\
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""
= """American English \
style in a calm and respectful tone
"""
= f"""Translate the text \
prompt that is delimited by triple backticks
into a style that is {style}.
text: ```{customer_email}```
"""
print(prompt)
Translate the text that is delimited by triple backticks
into a style that is American English in a calm and respectful tone
.
text: ```
Arrr, I be fuming that me blender lid flew off and splattered me kitchen walls with smoothie! And to make matters worse,the warranty don't cover the cost of cleaning up me kitchen. I need yer help right now, matey!
```
= get_completion(prompt)
response response
"I understand that you're upset about your blender lid flying off and making a mess in your kitchen. It's frustrating that the warranty doesn't cover the cost of cleaning up. How can I assist you with this situation?"
Let’s try how we can do the same using LangChain.
#!pip install --upgrade langchain
from langchain.chat_models import ChatOpenAI
# To control the randomness and creativity of the generated
# text by an LLM, use temperature = 0.0
= ChatOpenAI(temperature=0.0, model=llm_model)
chat chat
/var/folders/70/7wmmf6t55cb84bfx9g1c1k1m0000gn/T/ipykernel_93925/303651957.py:3: LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 0.3.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`.
chat = ChatOpenAI(temperature=0.0, model=llm_model)
ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x10c8bcfa0>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x10c8be8c0>, temperature=0.0, openai_api_key='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', openai_proxy='')
= """Translate the text \
template_string that is delimited by triple backticks \
into a style that is {style}. \
text: ```{text}```
"""
from langchain.prompts import ChatPromptTemplate
= ChatPromptTemplate.from_template(template_string)
prompt_template prompt_template
ChatPromptTemplate(input_variables=['style', 'text'], messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['style', 'text'], template='Translate the text that is delimited by triple backticks into a style that is {style}. text: ```{text}```\n'))])
0].prompt.input_variables prompt_template.messages[
['style', 'text']
= """American English \
customer_style in a calm and respectful tone
"""
= """
customer_email Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse, \
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""
= prompt_template.format_messages(
customer_messages =customer_style,
style=customer_email)
text
print(customer_messages)
print(customer_messages[0])
[HumanMessage(content="Translate the text that is delimited by triple backticks into a style that is American English in a calm and respectful tone\n. text: ```\nArrr, I be fuming that me blender lid flew off and splattered me kitchen walls with smoothie! And to make matters worse, the warranty don't cover the cost of cleaning up me kitchen. I need yer help right now, matey!\n```\n")]
content="Translate the text that is delimited by triple backticks into a style that is American English in a calm and respectful tone\n. text: ```\nArrr, I be fuming that me blender lid flew off and splattered me kitchen walls with smoothie! And to make matters worse, the warranty don't cover the cost of cleaning up me kitchen. I need yer help right now, matey!\n```\n"
print(type(customer_messages))
print(type(customer_messages[0]))
<class 'list'>
<class 'langchain_core.messages.human.HumanMessage'>
# Call the LLM to translate to the style of the customer message
= chat(customer_messages)
customer_response print(customer_response.content)
Oh man, I'm really frustrated that my blender lid flew off and made a mess of my kitchen walls with smoothie! And on top of that, the warranty doesn't cover the cost of cleaning up my kitchen. I could really use your help right now, friend.
= """Hey there customer, \
service_reply the warranty does not cover \
cleaning expenses for your kitchen \
because it's your fault that \
you misused your blender \
by forgetting to put the lid on before \
starting the blender. \
Tough luck! See ya!
"""
= """\
service_style_pirate a polite tone \
that speaks in English Pirate\
"""
= prompt_template.format_messages(
service_messages =service_style_pirate,
style=service_reply)
text
print(service_messages[0].content)
Translate the text that is delimited by triple backticks into a style that is a polite tone that speaks in English Pirate. text: ```Hey there customer, the warranty does not cover cleaning expenses for your kitchen because it's your fault that you misused your blender by forgetting to put the lid on before starting the blender. Tough luck! See ya!
```
= chat(service_messages)
service_response print(service_response.content)
Ahoy there, me hearty customer! The warranty be not coverin' the cleanin' expenses for yer galley because 'tis yer own fault for misusin' yer blender by forgettin' to put the lid on afore startin' the blender. Tough luck, matey! Farewell and may fair winds be at yer back! Arrr!
Let’s start with defining how we would like the LLM output to look like:
{"gift": False,
"delivery_days": 5,
"price_value": "pretty affordable!"
}
= """\
customer_review This leaf blower is pretty amazing. It has four settings:\
candle blower, gentle breeze, windy city, and tornado. \
It arrived in two days, just in time for my wife's \
anniversary present. \
I think my wife liked it so much she was speechless. \
So far I've been the only one using it, and I've been \
using it every other morning to clear the leaves on our lawn. \
It's slightly more expensive than the other leaf blowers \
out there, but I think it's worth it for the extra features.
"""
= """\
review_template For the following text, extract the following information:
gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.
delivery_days: How many days did it take for the product \
to arrive? If this information is not found, output -1.
price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.
Format the output as JSON with the following keys:
gift
delivery_days
price_value
text: {text}
"""
from langchain.prompts import ChatPromptTemplate
= ChatPromptTemplate.from_template(review_template)
prompt_template print(prompt_template)
input_variables=['text'] messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['text'], template='For the following text, extract the following information:\n\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\n\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\n\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\n\nFormat the output as JSON with the following keys:\ngift\ndelivery_days\nprice_value\n\ntext: {text}\n'))]
= prompt_template.format_messages(text=customer_review)
messages
= ChatOpenAI(temperature=0.0, model=llm_model)
chat = chat(messages)
response print(response.content)
{
"gift": true,
"delivery_days": 2,
"price_value": "It's slightly more expensive than the other leaf blowers out there"
}
type(response.content)
str
# You will get an error by running this line of code
# because'gift' is not a dictionary
# 'gift' is a string
'gift') response.content.get(
from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParser
= ResponseSchema(name="gift",
gift_schema ="Was the item purchased\
description as a gift for someone else? \
Answer True if yes,\
False if not or unknown.")
= ResponseSchema(name="delivery_days",
delivery_days_schema ="How many days\
description did it take for the product\
to arrive? If this \
information is not found,\
output -1.")
= ResponseSchema(name="price_value",
price_value_schema ="Extract any\
description sentences about the value or \
price, and output them as a \
comma separated Python list.")
= [gift_schema,
response_schemas
delivery_days_schema, price_value_schema]
= StructuredOutputParser.from_response_schemas(response_schemas)
output_parser output_parser
StructuredOutputParser(response_schemas=[ResponseSchema(name='gift', description='Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.', type='string'), ResponseSchema(name='delivery_days', description='How many days did it take for the product to arrive? If this information is not found, output -1.', type='string'), ResponseSchema(name='price_value', description='Extract any sentences about the value or price, and output them as a comma separated Python list.', type='string')])
= output_parser.get_format_instructions()
format_instructions format_instructions
'The output should be a markdown code snippet formatted in the following schema, including the leading and trailing "```json" and "```":\n\n```json\n{\n\t"gift": string // Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\n\t"delivery_days": string // How many days did it take for the product to arrive? If this information is not found, output -1.\n\t"price_value": string // Extract any sentences about the value or price, and output them as a comma separated Python list.\n}\n```'
= """\
review_template_2 For the following text, extract the following information:
gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.
delivery_days: How many days did it take for the product\
to arrive? If this information is not found, output -1.
price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.
text: {text}
{format_instructions}
"""
= ChatPromptTemplate.from_template(template=review_template_2)
prompt
= prompt.format_messages(text=customer_review,
messages =format_instructions) format_instructions
print(messages[0].content)
For the following text, extract the following information:
gift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.
delivery_days: How many days did it take for the productto arrive? If this information is not found, output -1.
price_value: Extract any sentences about the value or price,and output them as a comma separated Python list.
text: This leaf blower is pretty amazing. It has four settings:candle blower, gentle breeze, windy city, and tornado. It arrived in two days, just in time for my wife's anniversary present. I think my wife liked it so much she was speechless. So far I've been the only one using it, and I've been using it every other morning to clear the leaves on our lawn. It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.
The output should be a markdown code snippet formatted in the following schema, including the leading and trailing "```json" and "```":
```json
{
"gift": string // Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.
"delivery_days": string // How many days did it take for the product to arrive? If this information is not found, output -1.
"price_value": string // Extract any sentences about the value or price, and output them as a comma separated Python list.
}
```
= chat(messages) response
print(response.content)
```json
{
"gift": true,
"delivery_days": 2,
"price_value": ["It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features."]
}
```
= output_parser.parse(response.content)
output_dict print(type(output_dict))
output_dict
<class 'dict'>
{'gift': True,
'delivery_days': 2,
'price_value': ["It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features."]}
'delivery_days') output_dict.get(
2