LLM及LangChain開發筆記(10)_文本語言模型LLMs的PromptTemplate


在過去幾篇章中探討到關於prompt技巧,至於所謂PromptTemplate主要聚焦在如何去重複運用提示詞,並將其抽離成可以重複使用的模板。類似所謂「字串插值」(String interpolation)。

傳統透過python f string去做format字串傳參數的寫法較不靈活。

示範程式1

 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
import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())  # read local .env file

openai.api_key = os.getenv('OPENAI_API_KEY')

from langchain.llms import OpenAI
llm = OpenAI(model_name="gpt-3.5-turbo-instruct",max_tokens=1024)
from langchain import PromptTemplate

template =  """
請將由三個反引號分隔的文本內容用一句話進行概括
```{text}```
"""

prompt_template = PromptTemplate(
    input_variables = ["text"],
    template = template
)

print(
    prompt_template.format(
        text = "這是一個神奇的大模型,可以像人一樣對話"
    )
)



示範程式2

 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
template2 = """ 
請將以下以三個反引號分隔的文字翻譯成英文,並轉換為「{style}」的風格。\
文字如下:```{text}```
"""

prompt_template2 = PromptTemplate(
    input_variables = ["text", "style"],
    template = template2
)

text2 ="""
啊,我的攪拌機蓋子飛了出去,把我廚房的牆壁都弄得滿是果汁! \
更糟的是,保固不包括清理廚房的費用。夥計,我現在需要你的幫助!
"""
style2="""
平靜和尊重的美式英語語氣
"""

print(prompt_template2)
print("=====================================\n")
print(prompt_template2.format(
    text=text2,
    style=style2
))
print("=====================================\n")
print(llm.invoke(prompt_template.format(text=text2, style=style2)))






留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header