想去日本玩, 趁機了解一下神社 (Jinja). 不同於普通的神社, 這個神社是 Python 的一個程式庫, 現在已經有 Jinja 2.
Jinja 主要用在建立 template, 例如產生動態網頁. 可替換的字串會在 template 中用 {{}} 包起來. 引用時指定這個字串等於某筆資料就行了.
import pandas as pd
from jinja2 import Environment, FileSystemLoader
# Create a simple DataFrame
data = {
'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 34, 29, 32],
'City': ['New York', 'Paris', 'Berlin', 'London']
}
df = pd.DataFrame(data)
# Define a Jinja template
template = """
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
{% for _, row in df.iterrows() %}
<tr>
<td>{{ row['Name'] }}</td>
<td>{{ row['Age'] }}</td>
<td>{{ row['City'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
"""
# Create a Jinja environment
env = Environment(loader=FileSystemLoader('.'))
template = env.from_string(template)
# Render the template with the DataFrame
html_table = template.render(df=df)
print(html_table)
上面的 code 執行後得到一段 HTML. 用 browser 開啟就會顯示下面的表格.
| Name | Age | City |
|---|---|---|
| John | 28 | New York |
| Anna | 34 | Paris |
| Peter | 29 | Berlin |
| Linda | 32 | London |
當然, 如果這些資料要 hard code 在 Python 裡面就很 low 了. 我們應該是從一個隨時變動的資料庫中讀出他們, 然後靠著 Jinja 做出動態更新的 HTML 網頁.
另外我們可以在 in-context learning 時教導 LLM 要做的事. 像是給它一個範例. 下面的 code 使用了 DEFAULT_KEYWORD_EXTRACT_TEMPLATE_TMPL 這個 template. 中間 text (紅字) 和max_ keywords (藍字) 是每次可置換的.固定的部分在於 告訴 LLM 說只能輸出用 comma (,) 分開的關鍵字. 不包括 stop word (如標點符號, 介係詞之類的).
from jinja2 import Template
# Define the template
DEFAULT_KEYWORD_EXTRACT_TEMPLATE_TMPL = Template(
"Some text is provided below. Given the text, extract up to {{ max_keywords }}"
" keywords from the text. Avoid stopwords.\n"
"---------------------\n"
"{{ text }}\n"
"---------------------\n"
"Provide keywords in the following comma-separated format: 'KEYWORDS: <keywords>'\n"
)
# Generate the prompt
def generate_prompt(text, max_keywords=5):
return DEFAULT_KEYWORD_EXTRACT_TEMPLATE_TMPL.render(text=text, max_keywords=max_keywords)
# Example usage
prompt = generate_prompt("Jinja2 is a popular templating engine in the Python ecosystem.", 3)
print(prompt)
這個 example 輸出的長相如下:
Some text is provided below. Given the text, extract up to 3 keywords from the text. Avoid stopwords.
---------------------
Jinja2 is a popular templating engine in the Python ecosystem.
---------------------
Provide keywords in the following comma-separated format: 'KEYWORDS: <keywords>'