言語モデルのプロンプトを作成する
言語モデルのプロンプトは文字列連結で作成できますが、機能を組み合わせたり、プロンプトが言語モデルのコンテキストウィンドウ内に収まるようにしたりするのは困難です。これらの制限を克服するために、@vscode/prompt-tsx
ライブラリを使用できます。
@vscode/prompt-tsx
ライブラリは以下の機能を提供します。
- TSXベースのプロンプトレンダリング: TSXコンポーネントを使用してプロンプトを構成し、読みやすく、保守しやすくします。
- 優先度ベースの剪定: モデルのコンテキストウィンドウ内に収まるように、プロンプトの重要度の低い部分を自動的に剪定します。
- 柔軟なトークン管理:
flexGrow
、flexReserve
、flexBasis
などのプロパティを使用して、トークン予算を協力的に使用します。 - ツール統合: VS Codeの言語モデルツールAPIと統合します。
すべての機能と詳細な使用方法については、完全なREADMEを参照してください。
この記事では、ライブラリを使用したプロンプト設計の実践的な例を説明します。これらの例の完全なコードは、prompt-tsx リポジトリで確認できます。
会話履歴の優先順位を管理する
プロンプトに会話履歴を含めることは、ユーザーが以前のメッセージに対して追加の質問をできるようにするため重要です。しかし、履歴は時間とともに大きくなる可能性があるため、その優先順位が適切に扱われることを確認する必要があります。最も理にかなっているパターンは、通常、以下の順序で優先順位を付けることだと判明しました。
- ベースとなるプロンプトの指示
- 現在のユーザーのクエリ
- チャット履歴の最後の数ターン
- 補助データ
- 残りの履歴で収まるだけの量
このため、プロンプトでは履歴を2つの部分に分割し、最近のプロンプトターンが一般的なコンテキスト情報よりも優先されるようにします。
このライブラリでは、ツリー内の各TSXノードは概念的にzIndexに似た優先順位を持ち、数値が大きいほど優先順位が高くなります。
ステップ1: HistoryMessages コンポーネントを定義する
履歴メッセージをリスト表示するには、HistoryMessages
コンポーネントを定義します。この例は良い出発点となりますが、より複雑なデータ型を扱う場合は拡張する必要があるかもしれません。
この例では、PrioritizedList
ヘルパーコンポーネントを使用しており、その子要素に自動的に昇順または降順の優先順位を割り当てます。
import {
UserMessage,
AssistantMessage,
PromptElement,
BasePromptElementProps,
PrioritizedList,
} from '@vscode/prompt-tsx';
import { ChatContext, ChatRequestTurn, ChatResponseTurn, ChatResponseMarkdownPart } from 'vscode';
interface IHistoryMessagesProps extends BasePromptElementProps {
history: ChatContext['history'];
}
export class HistoryMessages extends PromptElement<IHistoryMessagesProps> {
render(): PromptPiece {
const history: (UserMessage | AssistantMessage)[] = [];
for (const turn of this.props.history) {
if (turn instanceof ChatRequestTurn) {
history.push(<UserMessage>{turn.prompt}</UserMessage>);
} else if (turn instanceof ChatResponseTurn) {
history.push(
<AssistantMessage name={turn.participant}>
{chatResponseToMarkdown(turn)}
</AssistantMessage>
);
}
}
return (
<PrioritizedList priority={0} descending={false}>
{history}
</PrioritizedList>
);
}
}
ステップ2: Prompt コンポーネントを定義する
次に、ベースの指示、ユーザーのクエリ、および履歴メッセージを適切な優先順位で含む MyPrompt
コンポーネントを定義します。優先順位の値は兄弟間でローカルです。プロンプト内の他の要素に触れる前に履歴の古いメッセージをトリミングしたい場合があるため、2つの <HistoryMessages>
要素に分割する必要があります。
import {
UserMessage,
PromptElement,
BasePromptElementProps,
} from '@vscode/prompt-tsx';
interface IMyPromptProps extends BasePromptElementProps {
history: ChatContext['history'];
userQuery: string;
}
export class MyPrompt extends PromptElement<IMyPromptProps> {
render() {
return (
<>
<UserMessage priority={100}>
Here are your base instructions. They have the highest priority because you want to make
sure they're always included!
</UserMessage>
{/* Older messages in the history have the lowest priority since they're less relevant */}
<HistoryMessages history={this.props.history.slice(0, -2)} priority={0} />
{/* The last 2 history messages are preferred over any workspace context you have below */}
<HistoryMessages history={this.props.history.slice(-2)} priority={80} />
{/* The user query is right behind the based instructions in priority */}
<UserMessage priority={90}>{this.props.userQuery}</UserMessage>
<UserMessage priority={70}>
With a slightly lower priority, you can include some contextual data about the workspace
or files here...
</UserMessage>
</>
);
}
}
これで、他のプロンプト要素を剪定しようとする前に、すべての古い履歴メッセージが剪定されます。
ステップ3: History コンポーネントを定義する
使用を少し簡単にするために、履歴メッセージをラップし、passPriority
属性を使用してパススルーコンテナとして機能する History
コンポーネントを定義します。passPriority
を使用すると、その子要素は優先順位付けの目的で、あたかも包含要素の直接の子であるかのように扱われます。
import { PromptElement, BasePromptElementProps } from '@vscode/prompt-tsx';
interface IHistoryProps extends BasePromptElementProps {
history: ChatContext['history'];
newer: number; // last 2 message priority values
older: number; // previous message priority values
passPriority: true; // require this prop be set!
}
export class History extends PromptElement<IHistoryProps> {
render(): PromptPiece {
return (
<>
<HistoryMessages history={this.props.history.slice(0, -2)} priority={this.props.older} />
<HistoryMessages history={this.props.history.slice(-2)} priority={this.props.newer} />
</>
);
}
}
これで、この単一の要素を使用してチャット履歴を含めることができます。
<History history={this.props.history} passPriority older={0} newer={80}/>
ファイルのコンテンツを合わせて拡大する
この例では、ユーザーが現在見ているすべてのファイルのコンテンツをプロンプトに含めたいと考えています。これらのファイルは大きくなる可能性があり、すべてを含めるとテキストが剪定されてしまうほどです!この例では、flexGrow
プロパティを使用して、ファイルのコンテンツをトークン予算内に収まるように協調的にサイズ調整する方法を示します。
ステップ1: ベースの指示とユーザーのクエリを定義する
まず、ベースの指示を含む UserMessage
コンポーネントを定義します。
<UserMessage priority={100}>Here are your base instructions.</UserMessage>
次に、UserMessage
コンポーネントを使用してユーザーのクエリを含めます。このコンポーネントは、ベースの指示の直後に含まれることを確実にするため、高い優先順位を持ちます。
<UserMessage priority={90}>{this.props.userQuery}</UserMessage>
ステップ2: ファイルのコンテンツを含める
次に、FileContext
コンポーネントを使用してファイルコンテンツを含めることができます。ベースの指示、ユーザーのクエリ、履歴の後にレンダリングされるように、flexGrow
の値を 1
に割り当てます。
<FileContext priority={70} flexGrow={1} files={this.props.files} />
flexGrow
の値が設定されていると、その要素は render()
および prepare()
呼び出しに渡される PromptSizing
オブジェクト内の「未使用の」トークン予算を取得します。flex要素の動作については、prompt-tsx ドキュメントで詳しく読むことができます。
ステップ3: 履歴を含める
次に、以前に作成した History
コンポーネントを使用して履歴メッセージを含めます。これは少し複雑です。なぜなら、一部の履歴を表示したい一方で、プロンプトの大部分をファイルの内容が占めるようにしたいからです。
そのため、History
コンポーネントに flexGrow
の値を 2
に割り当て、<FileContext />
を含む他のすべての要素の後にレンダリングされるようにします。しかし、同時に flexReserve
の値を "/5"
に設定し、履歴のために総予算の1/5を予約します。
<History
history={this.props.history}
passPriority
older={0}
newer={80}
flexGrow={2}
flexReserve="/5"
/>
ステップ3: プロンプトのすべての要素を結合する
これで、すべての要素を MyPrompt
コンポーネントに結合します。
import {
UserMessage,
PromptElement,
BasePromptElementProps,
} from '@vscode/prompt-tsx';
import { History } from './history';
interface IFilesToInclude {
document: TextDocument;
line: number;
}
interface IMyPromptProps extends BasePromptElementProps {
history: ChatContext['history'];
userQuery: string;
files: IFilesToInclude[];
}
export class MyPrompt extends PromptElement<IMyPromptProps> {
render() {
return (
<>
<UserMessage priority={100}>Here are your base instructions.</UserMessage>
<History
history={this.props.history}
passPriority
older={0}
newer={80}
flexGrow={2}
flexReserve="/5"
/>
<UserMessage priority={90}>{this.props.userQuery}</UserMessage>
<FileContext priority={70} flexGrow={1} files={this.props.files} />
</>
);
}
}
ステップ4: FileContext コンポーネントを定義する
最後に、ユーザーが現在見ているファイルのコンテンツを含む FileContext
コンポーネントを定義します。flexGrow
を使用したため、PromptSizing
の情報を使用して、各ファイルの「興味深い」行の周辺からできるだけ多くの行を取得するロジックを実装できます。
簡潔にするため、getExpandedFiles
の実装ロジックは省略されています。prompt-tsx リポジトリで確認できます。
import { PromptElement, BasePromptElementProps, PromptSizing, PromptPiece } from '@vscode/prompt-tsx';
class FileContext extends PromptElement<{ files: IFilesToInclude[] } & BasePromptElementProps> {
async render(_state: void, sizing: PromptSizing): Promise<PromptPiece> {
const files = await this.getExpandedFiles(sizing);
return <>{files.map(f => f.toString())}</>;
}
private async getExpandedFiles(sizing: PromptSizing) {
// Implementation details are summarized here.
// Refer to the repo for the complete implementation.
}
}
まとめ
これらの例では、ベースの指示、ユーザーのクエリ、履歴メッセージ、およびさまざまな優先順位を持つファイルコンテンツを含む MyPrompt
コンポーネントを作成しました。flexGrow
を使用して、ファイルコンテンツをトークン予算内に収まるように協調的にサイズ調整しました。
このパターンに従うことで、プロンプトの最も重要な部分が常に含まれるようにし、重要度の低い部分は必要に応じてモデルのコンテキストウィンドウに収まるように剪定することができます。getExpandedFiles
メソッドと FileContextTracker
クラスの完全な実装詳細については、prompt-tsx リポジトリを参照してください。