Gemini API経由でObsidianのノートにタグを与えるTemplater
code:script.js
<%*
// APIキーを https://aistudio.google.com/app/apikey で取得してください。
const api_key = ""
// 1. ObsidianのAPIを使って既存の全タグを取得
const allTagsWithCount = app.metadataCache.getTags();
// "#tag" の形式から "#" を除いた純粋なタグ名の配列を作成
const existingTags = Object.keys(allTagsWithCount).map(tag => tag.replace(/^#/, ''));
const prompt = あなたは有能な司書です。<title>と<content>を分析し、内容を端的に表すハッシュタグを3〜5個生成してください。## 既存のタグリスト(これらの中から適切なものがあれば優先的に使い、なければ新しく生成してください): ${existingTags.join(', ')} ## 制約事項 - 出力は\`タグ名\` の形式のみとしてください。- 固有名詞、技術用語、または概念的なキーワードを優先してください。- 既存の一般的な分類(例:仕事, アイデア, 読書)に固執せず、内容に特化した具体的なタグを生成してください。
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent'
if(!prompt) return
const title = tp.file.title
const content = tp.file.content
text = <title>${title}</title><content>${content}</content>\n:${prompt}
new Notice("thinking...")
const data = {
contents: [{
parts: text: text }
}]
}
response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-goog-api-key': api_key
},
body: JSON.stringify(data)
})
if(response.ok) {
const result = await response.json()
new Notice("プロパティに設定")
s = result.candidates0.content.parts0.text.split("\n")
const file = tp.file.find_tfile(tp.file.path(true)); // フロントマターを処理・更新
await app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter"tags" = s;
});
}else{
new Notice(response.statusText)
}
%>
https://gyazo.com/1385d96de02c1798350956a1127e7061
目次をノートに含めておけば、一般的な分類はまず大丈夫だろう。
2026/2/27
既存のタグリストも参照させることにした。
#Obsidianの使い方