-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path3-output-parser.py
More file actions
85 lines (64 loc) · 2.03 KB
/
3-output-parser.py
File metadata and controls
85 lines (64 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from dotenv import load_dotenv, find_dotenv
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
"""
Load OpenAI API key
"""
_ = load_dotenv(find_dotenv())
"""
Product review analysis
"""
user_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.
"""
# Create response schema
sentiment_schema = ResponseSchema(
name="sentiment",
description="""
Is the review positive or negative? \
Answer "positive" or "negative".
"""
)
gift_schema = ResponseSchema(
name="gift",
description="""
Was the product purchased as a gift for someone else?
Answer True if yes, False if no or unknown.
"""
)
# Create structured output parser
output_parser = StructuredOutputParser.from_response_schemas(
[sentiment_schema, gift_schema]
)
format_instructions = output_parser.get_format_instructions()
# print(format_instructions)
template = """
From the following text, extract the following information:
sentiment: Is the review positive or negative? \
Answer "positive" or "negative".
gift: Was the product purchased as a gift for someone else?
Answer True if yes, False if no or unknown.
text: {review}
{format_instructions}
"""
# Create model
chat_llm = ChatOpenAI(temperature=0.0)
# Design prompt
prompt = ChatPromptTemplate.from_template(template)
final_prompt = prompt.format(
review=user_review,
format_instructions=format_instructions
)
# Inference
response = chat_llm.predict(final_prompt)
print(f"Final prompt: {final_prompt}")
print(f"Response: {response}")