🚀 VS Code で で入手しましょう!

言語モデルのプロンプトを作成する

文字列連結を使用して言語モデルのプロンプトを構築できますが、機能を構成し、プロンプトが言語モデルのコンテキストウィンドウ内に収まるようにするのは困難です。これらの制限を克服するために、@vscode/prompt-tsx ライブラリを使用できます。

@vscode/prompt-tsx ライブラリは、次の機能を提供します。

  • TSX ベースのプロンプトレンダリング: TSX コンポーネントを使用してプロンプトを構成し、読みやすく保守しやすくします
  • 優先度ベースのプルーニング: モデルのコンテキストウィンドウに収まるように、プロンプトの重要度の低い部分を自動的にプルーニングします
  • 柔軟なトークン管理: flexGrowflexReserveflexBasis などのプロパティを使用して、トークンバジェットを協調的に使用します
  • ツール統合: VS Code の言語モデルツール API と統合します

すべての機能の詳細な概要と使用方法については、完全な README を参照してください。

この記事では、ライブラリを使用したプロンプト設計の実用的な例について説明します。これらの例の完全なコードは、prompt-tsx リポジトリにあります。

会話履歴の優先度を管理する

プロンプトに会話履歴を含めることは、ユーザーが以前のメッセージにフォローアップの質問をできるようにするために重要です。ただし、履歴は時間の経過とともに大きくなる可能性があるため、その優先度が適切に扱われるようにする必要があります。通常、最も理にかなっているパターンは、次の順序で優先順位を付けることです。

  1. 基本プロンプトの指示
  2. 現在のユーザーのクエリ
  3. チャット履歴の直近数ターン
  4. サポートデータ
  5. 可能な限り多くの残りの履歴

このため、プロンプトで履歴を 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 コンポーネントを使用してファイルの内容を含めることができるようになりました。flexGrow1 を割り当てて、基本指示、ユーザーのクエリ、履歴の後にレンダリングされるようにします。

<FileContext priority={70} flexGrow={1} files={this.props.files} />

flexGrow 値を使用すると、要素は、render() および prepare() 呼び出しに渡される PromptSizing オブジェクトで使用されていないトークンバジェットを取得します。フレックス要素の動作の詳細については、prompt-tsx ドキュメントを参照してください。

ステップ 3: 履歴を含める

次に、以前に作成した History コンポーネントを使用して履歴メッセージを含めます。これは少しトリッキーです。履歴の一部を表示したいだけでなく、ファイルの内容にプロンプトの大部分を占めてほしいからです。

したがって、History コンポーネントに flexGrow2 を割り当てて、<FileContext /> を含む他のすべての要素の後にレンダリングされるようにします。ただし、履歴用に予算全体の 1/5 を予約するために、flexReserve"/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 リポジトリを参照してください。