在本课中,您将练习两个提示原则及其相关策略,以便为大型语言模型编写有效的提示。
加载 API 密钥和相关的 Python 库。
在本课程中,我们提供了一些代码来为您加载 OpenAI API 密钥。
importopenai
importos
fromdotenvimportload_dotenv,find_dotenv
_=load_dotenv(find_dotenv())
openai.api_key=os.getenv('OPENAI_API_KEY')
在本课程中,我们将使用 OpenAI 的 gpt-3.5-turbo 模型和聊天完成端点。
此 helper 函数将使使用提示和查看生成的输出变得更加容易。
注意:2023 年 6 月,OpenAI 更新了 gpt-3.5-turbo。
您在笔记本中看到的结果可能与视频中的结果略有不同。一些提示也进行了轻微修改,以产生所需的结果。
defget_completion(prompt,model="gpt-3.5-turbo"):
messages=[{"role":"user","content":prompt}]
response=openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0,#thisisthedegreeofrandomnessofthemodel'soutput
)
returnresponse.choices[0].message["content"]
注意:本课程的此笔记本和所有其他实验笔记本都使用 OpenAI 库版本 0.27.0。
为了使用 OpenAI 库版本 1.0.0,以下是您将用于 get_completion 函数的代码:
client=openai.OpenAI()
defget_completion(prompt,model="gpt-3.5-turbo"):
messages=[{"role":"user","content":prompt}]
response=client.chat.completions.create(
model=model,
messages=messages,
temperature=0
)
returnresponse.choices[0].message.content
原则 1:写下清晰具体的指示
原则 2:给模型时间“思考”
分隔符可以是这样的: ''', “”“, < >,, :
text=f"""
Youshouldexpresswhatyouwantamodeltodoby\
providinginstructionsthatareasclearand\
specificasyoucanpossiblymakethem.\
Thiswillguidethemodeltowardsthedesiredoutput,\
andreducethechancesofreceivingirrelevant\
orincorrectresponses.Don'tconfusewritinga\
clearpromptwithwritingashortprompt.\
Inmanycases,longerpromptsprovidemoreclarity\
andcontextforthemodel,whichcanleadto\
moredetailedandrelevantoutputs.
"""
prompt=f"""
Summarizethetextdelimitedbytriplebackticks\
intoasinglesentence.
```{text}```
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Generatealistofthreemade-upbooktitlesalong\
withtheirauthorsandgenres.
ProvidetheminJSONformatwiththefollowingkeys:
book_id,title,author,genre.
"""
response=get_completion(prompt)
print(response)
text_1=f"""
Makingacupofteaiseasy!First,youneedtogetsome\
waterboiling.Whilethat'shappening,\
grabacupandputateabaginit.Oncethewateris\
hotenough,justpouritovertheteabag.\
Letitsitforabitsotheteacansteep.Aftera\
fewminutes,takeouttheteabag.Ifyou\
like,youcanaddsomesugarormilktotaste.\
Andthat'sit!You'vegotyourselfadelicious\
cupofteatoenjoy.
"""
prompt=f"""
Youwillbeprovidedwithtextdelimitedbytriplequotes.
Ifitcontainsasequenceofinstructions,\
re-writethoseinstructionsinthefollowingformat:
Step1-...
Step2-…
…
StepN-…
Ifthetextdoesnotcontainasequenceofinstructions,\
thensimplywrite\"Nostepsprovided.\"
\"\"\"{text_1}\"\"\"
"""
response=get_completion(prompt)
print("CompletionforText1:")
print(response)
text_2=f"""
Thesunisshiningbrightlytoday,andthebirdsare\
singing.It'sabeautifuldaytogofora\
walkinthepark.Theflowersareblooming,andthe\
treesareswayinggentlyinthebreeze.People\
areoutandabout,enjoyingthelovelyweather.\
Somearehavingpicnics,whileothersareplaying\
gamesorsimplyrelaxingonthegrass.It'sa\
perfectdaytospendtimeoutdoorsandappreciatethe\
beautyofnature.
"""
prompt=f"""
Youwillbeprovidedwithtextdelimitedbytriplequotes.
Ifitcontainsasequenceofinstructions,\
re-writethoseinstructionsinthefollowingformat:
Step1-...
Step2-…
…
StepN-…
Ifthetextdoesnotcontainasequenceofinstructions,\
thensimplywrite\"Nostepsprovided.\"
\"\"\"{text_2}\"\"\"
"""
response=get_completion(prompt)
print("CompletionforText2:")
print(response)
prompt=f"""
Yourtaskistoanswerinaconsistentstyle.
<child>:Teachmeaboutpatience.
<grandparent>:Theriverthatcarvesthedeepest\
valleyflowsfromamodestspring;the\
grandestsymphonyoriginatesfromasinglenote;\
themostintricatetapestrybeginswithasolitarythread.
<child>:Teachmeaboutresilience.
"""
response=get_completion(prompt)
print(response)
text=f"""
Inacharmingvillage,siblingsJackandJillsetouton\
aquesttofetchwaterfromahilltop\
well.Astheyclimbed,singingjoyfully,misfortune\
struck—Jacktrippedonastoneandtumbled\
downthehill,withJillfollowingsuit.\
Thoughslightlybattered,thepairreturnedhometo\
comfortingembraces.Despitethemishap,\
theiradventurousspiritsremainedundimmed,andthey\
continuedexploringwithdelight.
"""
#example1
prompt_1=f"""
Performthefollowingactions:
1-Summarizethefollowingtextdelimitedbytriple\
backtickswith1sentence.
2-TranslatethesummaryintoFrench.
3-ListeachnameintheFrenchsummary.
4-Outputajsonobjectthatcontainsthefollowing\
keys:french_summary,num_names.
Separateyouranswerswithlinebreaks.
Text:
```{text}```
"""
response=get_completion(prompt_1)
print("Completionforprompt1:")
print(response)
prompt_2=f"""
Yourtaskistoperformthefollowingactions:
1-Summarizethefollowingtextdelimitedby
<>with1sentence.
2-TranslatethesummaryintoFrench.
3-ListeachnameintheFrenchsummary.
4-Outputajsonobjectthatcontainsthe
followingkeys:french_summary,num_names.
Usethefollowingformat:
Text:<texttosummarize>
Summary:<summary>
Translation:<summarytranslation>
Names:<listofnamesinsummary>
OutputJSON:<jsonwithsummaryandnum_names>
Text:<{text}>
"""
response=get_completion(prompt_2)
print("\nCompletionforprompt2:")
print(response)
prompt=f"""
Determineifthestudent'ssolutioniscorrectornot.
Question:
I'mbuildingasolarpowerinstallationandIneed\
helpworkingoutthefinancials.
-Landcosts$100/squarefoot
-Icanbuysolarpanelsfor$250/squarefoot
-Inegotiatedacontractformaintenancethatwillcost\
meaflat$100kperyear,andanadditional$10/square\
foot
Whatisthetotalcostforthefirstyearofoperations
asafunctionofthenumberofsquarefeet.
Student'sSolution:
Letxbethesizeoftheinstallationinsquarefeet.
Costs:
1.Landcost:100x
2.Solarpanelcost:250x
3.Maintenancecost:100,000+100x
Totalcost:100x+250x+100,000+100x=450x+100,000
"""
response=get_completion(prompt)
print(response)
请注意,学生的解决方案实际上并不正确。 我们可以通过指示模型首先找出自己的解决方案来解决这个问题。
prompt=f"""
Yourtaskistodetermineifthestudent'ssolution\
iscorrectornot.
Tosolvetheproblemdothefollowing:
-First,workoutyourownsolutiontotheproblemincludingthefinaltotal.
-Thencompareyoursolutiontothestudent'ssolution\
andevaluateifthestudent'ssolutioniscorrectornot.
Don'tdecideifthestudent'ssolutioniscorrectuntil
youhavedonetheproblemyourself.
Usethefollowingformat:
Question:
question here
Student'ssolution:
student's solution here
Actualsolution:
steps to work out the solution and your solution here
Isthestudent'ssolutionthesameasactualsolution\
justcalculated:
yes or no
Studentgrade:
correct or incorrect
Question:
I'm building a solar power installation and I need help
working out the financials.
Student'ssolution:
Let x be the size of the installation in square feet. Costs:
Actualsolution:
"""
response=get_completion(prompt)
print(response)
Boie 是一家真实的公司,产品名称不是真实的。
在本课程中,您将迭代地分析和优化您的提示,以从产品情况说明书生成营销副本。
fact_sheet_chair="""
OVERVIEW
-Partofabeautifulfamilyofmid-centuryinspiredofficefurniture,
includingfilingcabinets,desks,bookcases,meetingtables,andmore.
-Severaloptionsofshellcolorandbasefinishes.
-Availablewithplasticbackandfrontupholstery(SWC-100)
orfullupholstery(SWC-110)in10fabricand6leatheroptions.
-Basefinishoptionsare:stainlesssteel,matteblack,
glosswhite,orchrome.
-Chairisavailablewithorwithoutarmrests.
-Suitableforhomeorbusinesssettings.
-Qualifiedforcontractuse.
CONSTRUCTION
-5-wheelplasticcoatedaluminumbase.
-Pneumaticchairadjustforeasyraise/loweraction.
DIMENSIONS
-WIDTH53CM|20.87”
-DEPTH51CM|20.08”
-HEIGHT80CM|31.50”
-SEATHEIGHT44CM|17.32”
-SEATDEPTH41CM|16.14”
OPTIONS
-Softorhard-floorcasteroptions.
-Twochoicesofseatfoamdensities:
medium(1.8lb/ft3)orhigh(2.8lb/ft3)
-Armlessor8positionPUarmrests
MATERIALS
SHELLBASEGLIDER
-CastAluminumwithmodifiednylonPA6/PA66coating.
-Shellthickness:10mm.
SEAT
-HD36foam
COUNTRYOFORIGIN
-Italy
"""
prompt=f"""
Yourtaskistohelpamarketingteamcreatea
descriptionforaretailwebsiteofaproductbased
onatechnicalfactsheet.
Writeaproductdescriptionbasedontheinformation
providedinthetechnicalspecificationsdelimitedby
triplebackticks.
Technicalspecifications:```{fact_sheet_chair}```
"""
response=get_completion(prompt)
print(response)
限制单词/句子/字符的数量。
prompt=f"""
Yourtaskistohelpamarketingteamcreatea
descriptionforaretailwebsiteofaproductbased
onatechnicalfactsheet.
Writeaproductdescriptionbasedontheinformation
providedinthetechnicalspecificationsdelimitedby
triplebackticks.
Useatmost50words.
Technicalspecifications:```{fact_sheet_chair}```
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Yourtaskistohelpamarketingteamcreatea
descriptionforaretailwebsiteofaproductbased
onatechnicalfactsheet.
Writeaproductdescriptionbasedontheinformation
providedinthetechnicalspecificationsdelimitedby
triplebackticks.
Thedescriptionisintendedforfurnitureretailers,
soshouldbetechnicalinnatureandfocusonthe
materialstheproductisconstructedfrom.
Useatmost50words.
Technicalspecifications:```{fact_sheet_chair}```
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Yourtaskistohelpamarketingteamcreatea
descriptionforaretailwebsiteofaproductbased
onatechnicalfactsheet.
Writeaproductdescriptionbasedontheinformation
providedinthetechnicalspecificationsdelimitedby
triplebackticks.
Thedescriptionisintendedforfurnitureretailers,
soshouldbetechnicalinnatureandfocusonthe
materialstheproductisconstructedfrom.
Attheendofthedescription,includeevery7-character
ProductIDinthetechnicalspecification.
Useatmost50words.
Technicalspecifications:```{fact_sheet_chair}```
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Yourtaskistohelpamarketingteamcreatea
descriptionforaretailwebsiteofaproductbased
onatechnicalfactsheet.
Writeaproductdescriptionbasedontheinformation
providedinthetechnicalspecificationsdelimitedby
triplebackticks.
Thedescriptionisintendedforfurnitureretailers,
soshouldbetechnicalinnatureandfocusonthe
materialstheproductisconstructedfrom.
Attheendofthedescription,includeevery7-character
ProductIDinthetechnicalspecification.
Afterthedescription,includeatablethatgivesthe
product'sdimensions.Thetableshouldhavetwocolumns.
Inthefirstcolumnincludethenameofthedimension.
Inthesecondcolumnincludethemeasurementsininchesonly.
Givethetablethetitle'
roductDimensions'.
FormateverythingasHTMLthatcanbeusedinawebsite.
Placethedescriptionina<div>element.
Technicalspecifications:```{fact_sheet_chair}```
"""
response=get_completion(prompt)
print(response)
在本课中,您将对文本进行总结,重点关注特定主题。
prod_review="""
Gotthispandaplushtoyformydaughter'sbirthday,\
wholovesitandtakesiteverywhere.It'ssoftand\
supercute,anditsfacehasafriendlylook.It's\
abitsmallforwhatIpaidthough.Ithinkthere\
mightbeotheroptionsthatarebiggerforthe\
sameprice.Itarrivedadayearlierthanexpected,\
soIgottoplaywithitmyselfbeforeIgaveit\
toher.
"""
prompt=f"""
Yourtaskistogenerateashortsummaryofaproduct\
reviewfromanecommercesite.
Summarizethereviewbelow,delimitedbytriple
backticks,inatmost30words.
Review:```{prod_review}```
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Yourtaskistogenerateashortsummaryofaproduct\
reviewfromanecommercesitetogivefeedbacktothe\
Shippingdeparmtment.
Summarizethereviewbelow,delimitedbytriple
backticks,inatmost30words,andfocusingonanyaspects\
thatmentionshippinganddeliveryoftheproduct.
Review:```{prod_review}```
"""
response=get_completion(prompt)
print(response)
摘要包括与焦点主题无关的主题。
prompt=f"""
Yourtaskistoextractrelevantinformationfrom\
aproductreviewfromanecommercesitetogive\
feedbacktotheShippingdepartment.
Fromthereviewbelow,delimitedbytriplequotes\
extracttheinformationrelevanttoshippingand\
delivery.Limitto30words.
Review:```{prod_review}```
"""
response=get_completion(prompt)
print(response)
review_1=prod_review
#reviewforastandinglamp
review_2="""
Neededanicelampformybedroom,andthisone\
hadadditionalstorageandnottoohighofaprice\
point.Gotitfast-arrivedin2days.Thestring\
tothelampbrokeduringthetransitandthecompany\
happilysentoveranewone.Camewithinafewdays\
aswell.Itwaseasytoputtogether.ThenIhada\
missingpart,soIcontactedtheirsupportandthey\
veryquicklygotmethemissingpiece!Seemstome\
tobeagreatcompanythatcaresabouttheircustomers\
andproducts.
"""
#reviewforanelectrictoothbrush
review_3="""
Mydentalhygienistrecommendedanelectrictoothbrush,\
whichiswhyIgotthis.Thebatterylifeseemstobe\
prettyimpressivesofar.Afterinitialchargingand\
leavingthechargerpluggedinforthefirstweekto\
conditionthebattery,I'veunpluggedthechargerand\
beenusingitfortwicedailybrushingforthelast\
3weeksallonthesamecharge.Butthetoothbrushhead\
istoosmall.I’veseenbabytoothbrushesbiggerthan\
thisone.Iwishtheheadwasbiggerwithdifferent\
lengthbristlestogetbetweenteethbetterbecause\
thisonedoesn’t.Overallifyoucangetthisone\
aroundthe$50mark,it'sagooddeal.Themanufactuer's\
replacementsheadsareprettyexpensive,butyoucan\
getgenericonesthat'remorereasonablypriced.This\
toothbrushmakesmefeellikeI'vebeentothedentist\
everyday.Myteethfeelsparklyclean!
"""
#reviewforablender
review_4="""
So,theystillhadthe17piecesystemonseasonal\
saleforaround$49inthemonthofNovember,about\
halfoff,butforsomereason(callitpricegouging)\
aroundthesecondweekofDecemberthepricesallwent\
uptoaboutanywherefrombetween$70-$89forthesame\
system.Andthe11piecesystemwentuparound$10or\
soinpricealsofromtheearliersalepriceof$29.\
Soitlooksokay,butifyoulookatthebase,thepart\
wherethebladelocksintoplacedoesn’tlookasgood\
asinpreviouseditionsfromafewyearsago,butI\
plantobeverygentlewithit(example,Icrush\
veryharditemslikebeans,ice,rice,etc.inthe\
blenderfirstthenpulverizethemintheservingsize\
Iwantintheblenderthenswitchtothewhipping\
bladeforafinerflour,andusethecrosscuttingblade\
firstwhenmakingsmoothies,thenusetheflatblade\
ifIneedthemfiner/lesspulpy).Specialtipwhenmaking\
smoothies,finelycutandfreezethefruitsand\
vegetables(ifusingspinach-lightlystewsoftenthe\
spinachthenfreezeuntilreadyforuse-andifmaking\
sorbet,useasmalltomediumsizedfoodprocessor)\
thatyouplantousethatwayyoucanavoidaddingso\
muchiceifatall-whenmakingyoursmoothie.\
Afteraboutayear,themotorwasmakingafunnynoise.\
Icalledcustomerservicebutthewarrantyexpired\
already,soIhadtobuyanotherone.FYI:Theoverall\
qualityhasgonedoneinthesetypesofproducts,so\
theyarekindofcountingonbrandrecognitionand\
consumerloyaltytomaintainsales.Gotitinabout\
twodays.
"""
reviews=[review_1,review_2,review_3,review_4]
foriinrange(len(reviews)):
prompt=f"""
Yourtaskistogenerateashortsummaryofaproduct\
reviewfromanecommercesite.
Summarizethereviewbelow,delimitedbytriple\
backticksinatmost20words.
Review:```{reviews[i]}```
"""
response=get_completion(prompt)
print(i,response,"\n")
在本课中,您将从产品评论和新闻文章中推断情绪和主题。
产品评论文本
lamp_review="""
Neededanicelampformybedroom,andthisonehad\
additionalstorageandnottoohighofapricepoint.\
Gotitfast.Thestringtoourlampbrokeduringthe\
transitandthecompanyhappilysentoveranewone.\
Camewithinafewdaysaswell.Itwaseasytoput\
together.Ihadamissingpart,soIcontactedtheir\
supportandtheyveryquicklygotmethemissingpiece!\
Luminaseemstometobeagreatcompanythatcares\
abouttheircustomersandproducts!!
"""
情绪 (积极 / 消极)
prompt=f"""
Whatisthesentimentofthefollowingproductreview,
whichisdelimitedwithtriplebackticks?
Reviewtext:'''{lamp_review}'''
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Whatisthesentimentofthefollowingproductreview,
whichisdelimitedwithtriplebackticks?
Giveyouranswerasasingleword,either"positive"\
or"negative".
Reviewtext:'''{lamp_review}'''
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Identifyalistofemotionsthatthewriterofthe\
followingreviewisexpressing.Includenomorethan\
fiveitemsinthelist.Formatyouranswerasalistof\
lower-casewordsseparatedbycommas.
Reviewtext:'''{lamp_review}'''
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Isthewriterofthefollowingreviewexpressinganger?\
Thereviewisdelimitedwithtriplebackticks.\
Giveyouransweraseitheryesorno.
Reviewtext:'''{lamp_review}'''
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Identifythefollowingitemsfromthereviewtext:
-Itempurchasedbyreviewer
-Companythatmadetheitem
Thereviewisdelimitedwithtriplebackticks.\
FormatyourresponseasaJSONobjectwith\
"Item"and"Brand"asthekeys.
Iftheinformationisn'tpresent,use"unknown"\
asthevalue.
Makeyourresponseasshortaspossible.
Reviewtext:'''{lamp_review}'''
"""
response=get_completion(prompt)
print(response)
prompt=f"""
Identifythefollowingitemsfromthereviewtext:
-Sentiment(positiveornegative)
-Isthereviewerexpressinganger?(trueorfalse)
-Itempurchasedbyreviewer
-Companythatmadetheitem
Thereviewisdelimitedwithtriplebackticks.\
FormatyourresponseasaJSONobjectwith\
"Sentiment","Anger","Item"and"Brand"asthekeys.
Iftheinformationisn'tpresent,use"unknown"\
asthevalue.
Makeyourresponseasshortaspossible.
FormattheAngervalueasaboolean.
Reviewtext:'''{lamp_review}'''
"""
response=get_completion(prompt)
print(response)
story="""
Inarecentsurveyconductedbythegovernment,
publicsectoremployeeswereaskedtoratetheirlevel
ofsatisfactionwiththedepartmenttheyworkat.
TheresultsrevealedthatNASAwasthemostpopular
departmentwithasatisfactionratingof95%.
OneNASAemployee,JohnSmith,commentedonthefindings,
stating,"I'mnotsurprisedthatNASAcameoutontop.
It'sagreatplacetoworkwithamazingpeopleand
incredibleopportunities.I'mproudtobeapartof
suchaninnovativeorganization."
TheresultswerealsowelcomedbyNASA'smanagementteam,
withDirectorTomJohnsonstating,"Wearethrilledto
hearthatouremployeesaresatisfiedwiththeirworkatNASA.
Wehaveatalentedanddedicatedteamwhoworktirelessly
toachieveourgoals,andit'sfantastictoseethattheir
hardworkispayingoff."
Thesurveyalsorevealedthatthe
SocialSecurityAdministrationhadthelowestsatisfaction
rating,withonly45%ofemployeesindicatingtheywere
satisfiedwiththeirjob.Thegovernmenthaspledgedto
addresstheconcernsraisedbyemployeesinthesurveyand
worktowardsimprovingjobsatisfactionacrossalldepartments.
"""
prompt=f"""
Determinefivetopicsthatarebeingdiscussedinthe\
followingtext,whichisdelimitedbytriplebackticks.
Makeeachitemoneortwowordslong.
Formatyourresponseasalistofitemsseparatedbycommas.
Textsample:'''{story}'''
"""
response=get_completion(prompt)
print(response)
response.split(sep=',')
topic_list=[
"nasa","localgovernment","engineering",
"employeesatisfaction","federalgovernment"
]
prompt=f"""
Determinewhethereachiteminthefollowinglistof\
topicsisatopicinthetextbelow,which
isdelimitedwithtriplebackticks.
Giveyouranswerasfollows:
itemfromthelist:0or1
Listoftopics:{",".join(topic_list)}
Textsample:'''{story}'''
"""
response=get_completion(prompt)
print(response)
topic_dict={i.split(':')[0]:int(i.split(':')[1])foriinresponse.split(sep='\n')}
iftopic_dict['nasa']==1:
print("ALERT:NewNASAstory!")
未完待续。。。
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |