llm-worker-rs/docs/prompt-composer.md

107 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# PromptComposer
テンプレートベースのプロンプト構築システム。Handlebarsテンプレートエンジンによる動的プロンプト生成。
## 基本使用方法
```rust
use std::sync::Arc;
use worker::prompt::{PromptComposer, PromptContext, PromptError, ResourceLoader};
struct FsLoader;
impl ResourceLoader for FsLoader {
fn load(&self, identifier: &str) -> Result<String, PromptError> {
std::fs::read_to_string(identifier)
.map_err(|e| PromptError::FileNotFound(format!("{}: {}", identifier, e)))
}
}
// 初期化
let loader = Arc::new(FsLoader);
let mut composer = PromptComposer::from_config_file("role.yaml", context, loader.clone())?;
composer.initialize_session(&messages)?;
// プロンプト構築
let messages = composer.compose(&user_messages)?;
```
## リソースローダー
`PromptComposer` はテンプレート内で参照されるパーシャルや `{{include_file}}` の解決をクレート利用者に委ねています。
`ResourceLoader` トレイトを実装して、任意のストレージや命名規則に基づいて文字列を返してください。
```rust
struct MyLoader;
impl ResourceLoader for MyLoader {
fn load(&self, identifier: &str) -> Result<String, PromptError> {
match identifier.strip_prefix("#workspace/") {
Some(rest) => {
let path = std::env::current_dir()?.join(".nia").join(rest);
std::fs::read_to_string(path).map_err(|e| PromptError::FileNotFound(e.to_string()))
}
None => std::fs::read_to_string(identifier)
.map_err(|e| PromptError::FileNotFound(e.to_string())),
}
}
}
```
## テンプレート構文
### 変数展開
```handlebars
{{workspace.project_name}} # プロジェクト名
{{workspace.project_type}} # プロジェクト種別
{{model.provider}}/{{model.model_name}} # モデル情報
{{tools_schema}} # ツールスキーマ
```
### 条件分岐
```handlebars
{{#if workspace.has_nia_md}}
Project info: {{workspace_content}}
{{/if}}
{{#eq workspace.project_type "Rust"}}
Focus on memory safety and performance.
{{/eq}}
```
### 繰り返し処理
```handlebars
{{#each tools}}
- **{{name}}**: {{description}}
{{/each}}
```
### パーシャルテンプレート
```handlebars
{{> header}}
{{> coding_guidelines}}
{{> footer}}
```
## カスタムヘルパー
### include_file
外部ファイルを読み込み:
```handlebars
{{include_file "~/.config/nia/templates/guidelines.md"}}
```
### workspace_content
ワークスペースのnia.md内容を取得
```handlebars
{{workspace_content}}
```
## 利用可能なコンテキスト変数
- `workspace`: プロジェクト情報root_path、project_type、git_info等
- `model`: LLMモデル情報provider、model_name、capabilities
- `session`: セッション情報conversation_id、message_count
- `user_input`: ユーザー入力内容
- `tools_schema`: ツール定義JSON